Project

General

Profile

Download (60.8 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 = `cat /etc/resolv.conf`;
153
	$dns_s = split("\n", $dns);
154
	foreach($dns_s as $dns) {
155
		$matches = "";
156
		if (preg_match("/nameserver (.*)/", $dns, $matches))
157
			$dns_servers[] = $matches[1];
158
	}
159
	$dns_server_master = array();
160
	$lastseen = "";
161
	foreach($dns_servers as $t) {
162
		if($t <> $lastseen)
163
			if($t <> "")
164
				$dns_server_master[] = $t;
165
		$lastseen = $t;
166
	}
167
	return $dns_server_master;
168
}
169

    
170
/****f* pfsense-utils/enable_hardware_offloading
171
 * NAME
172
 *   enable_hardware_offloading - Enable a NIC's supported hardware features.
173
 * INPUTS
174
 *   $interface	- string containing the physical interface to work on.
175
 * RESULT
176
 *   null
177
 * NOTES
178
 *   This function only supports the fxp driver's loadable microcode.
179
 ******/
180
function enable_hardware_offloading($interface) {
181
	global $g, $config;
182

    
183
	if(isset($config['system']['do_not_use_nic_microcode']))
184
		return;
185

    
186
	/* translate wan, lan, opt -> real interface if needed */
187
	$int = get_real_interface($interface);
188
	if(empty($int)) 
189
		return;
190
	$int_family = preg_split("/[0-9]+/", $int);
191
	$supported_ints = array('fxp');
192
	if (in_array($int_family, $supported_ints)) {
193
		if(does_interface_exist($int)) 
194
			pfSense_interface_flags($int, IFF_LINK0);
195
	}
196

    
197
	return;
198
}
199

    
200
/****f* pfsense-utils/interface_supports_polling
201
 * NAME
202
 *   checks to see if an interface supports polling according to man polling
203
 * INPUTS
204
 *
205
 * RESULT
206
 *   true or false
207
 * NOTES
208
 *
209
 ******/
210
function interface_supports_polling($iface) {
211
	$opts = pfSense_get_interface_addresses($iface);
212
	if (is_array($opts) && isset($opts['caps']['polling']))
213
		return true;
214

    
215
	return false;
216
}
217

    
218
/****f* pfsense-utils/is_alias_inuse
219
 * NAME
220
 *   checks to see if an alias is currently in use by a rule
221
 * INPUTS
222
 *
223
 * RESULT
224
 *   true or false
225
 * NOTES
226
 *
227
 ******/
228
function is_alias_inuse($alias) {
229
	global $g, $config;
230

    
231
	if($alias == "") return false;
232
	/* loop through firewall rules looking for alias in use */
233
	if(is_array($config['filter']['rule']))
234
		foreach($config['filter']['rule'] as $rule) {
235
			if($rule['source']['address'])
236
				if($rule['source']['address'] == $alias)
237
					return true;
238
			if($rule['destination']['address'])
239
				if($rule['destination']['address'] == $alias)
240
					return true;
241
		}
242
	/* loop through nat rules looking for alias in use */
243
	if(is_array($config['nat']['rule']))
244
		foreach($config['nat']['rule'] as $rule) {
245
			if($rule['target'] && $rule['target'] == $alias)
246
				return true;
247
			if($rule['source']['address'] && $rule['source']['address'] == $alias)
248
				return true;
249
			if($rule['destination']['address'] && $rule['destination']['address'] == $alias)
250
				return true;
251
		}
252
	return false;
253
}
254

    
255
/****f* pfsense-utils/is_schedule_inuse
256
 * NAME
257
 *   checks to see if a schedule is currently in use by a rule
258
 * INPUTS
259
 *
260
 * RESULT
261
 *   true or false
262
 * NOTES
263
 *
264
 ******/
265
function is_schedule_inuse($schedule) {
266
	global $g, $config;
267

    
268
	if($schedule == "") return false;
269
	/* loop through firewall rules looking for schedule in use */
270
	if(is_array($config['filter']['rule']))
271
		foreach($config['filter']['rule'] as $rule) {
272
			if($rule['sched'] == $schedule)
273
				return true;
274
		}
275
	return false;
276
}
277

    
278
/****f* pfsense-utils/setup_polling
279
 * NAME
280
 *   sets up polling
281
 * INPUTS
282
 *
283
 * RESULT
284
 *   null
285
 * NOTES
286
 *
287
 ******/
288
function setup_polling() {
289
	global $g, $config;
290

    
291
	if (isset($config['system']['polling']))
292
		mwexec("/sbin/sysctl kern.polling.idle_poll=1");
293
	else
294
		mwexec("/sbin/sysctl kern.polling.idle_poll=0");
295

    
296
	if($config['system']['polling_each_burst'])
297
		mwexec("/sbin/sysctl kern.polling.each_burst={$config['system']['polling_each_burst']}");
298
	if($config['system']['polling_burst_max'])
299
		mwexec("/sbin/sysctl kern.polling.burst_max={$config['system']['polling_burst_max']}");
300
	if($config['system']['polling_user_frac'])
301
		mwexec("/sbin/sysctl kern.polling.user_frac={$config['system']['polling_user_frac']}");
302
}
303

    
304
/****f* pfsense-utils/setup_microcode
305
 * NAME
306
 *   enumerates all interfaces and calls enable_hardware_offloading which
307
 *   enables a NIC's supported hardware features.
308
 * INPUTS
309
 *
310
 * RESULT
311
 *   null
312
 * NOTES
313
 *   This function only supports the fxp driver's loadable microcode.
314
 ******/
315
function setup_microcode() {
316

    
317
	/* if list */
318
	$ifs = get_interface_arr();
319

    
320
	foreach($ifs as $if)
321
		enable_hardware_offloading($if);
322
}
323

    
324
/****f* pfsense-utils/get_carp_status
325
 * NAME
326
 *   get_carp_status - Return whether CARP is enabled or disabled.
327
 * RESULT
328
 *   boolean	- true if CARP is enabled, false if otherwise.
329
 ******/
330
function get_carp_status() {
331
    /* grab the current status of carp */
332
    $status = `/sbin/sysctl net.inet.carp.allow | cut -d" " -f2`;
333
    if(intval($status) == "0") return false;
334
    return true;
335
}
336

    
337
/*
338
 * convert_ip_to_network_format($ip, $subnet): converts an ip address to network form
339

    
340
 */
341
function convert_ip_to_network_format($ip, $subnet) {
342
	$ipsplit = split('[.]', $ip);
343
	$string = $ipsplit[0] . "." . $ipsplit[1] . "." . $ipsplit[2] . ".0/" . $subnet;
344
	return $string;
345
}
346

    
347
/*
348
 * get_carp_interface_status($carpinterface): returns the status of a carp ip
349
 */
350
function get_carp_interface_status($carpinterface) {
351
	/* basically cache the contents of ifconfig statement
352
	to speed up this routine */
353
	global $carp_query;
354
	if($carp_query == "")
355
		$carp_query = split("\n", `/sbin/ifconfig $carpinterface | grep carp`);
356
	foreach($carp_query as $int) {
357
		if(stristr($int, "MASTER")) 
358
			return "MASTER";
359
		if(stristr($int, "BACKUP")) 
360
			return "BACKUP";
361
		if(stristr($int, "INIT")) 
362
			return "INIT";
363
	}
364
	return;
365
}
366

    
367
/*
368
 * get_pfsync_interface_status($pfsyncinterface): returns the status of a pfsync
369
 */
370
function get_pfsync_interface_status($pfsyncinterface) {
371
    $result = does_interface_exist($pfsyncinterface);
372
    if($result <> true) return;
373
    $status = exec_command("/sbin/ifconfig {$pfsyncinterface} | /usr/bin/awk '/pfsync:/ {print \$5}'");
374
    return $status;
375
}
376

    
377
/*
378
 * add_rule_to_anchor($anchor, $rule): adds the specified rule to an anchor
379
 */
380
function add_rule_to_anchor($anchor, $rule, $label) {
381
	mwexec("echo " . $rule . " | /sbin/pfctl -a " . $anchor . ":" . $label . " -f -");
382
}
383

    
384
/*
385
 * remove_text_from_file
386
 * remove $text from file $file
387
 */
388
function remove_text_from_file($file, $text) {
389
	global $fd_log;
390
	if($fd_log)
391
		fwrite($fd_log, "Adding needed text items:\n");
392
	$filecontents = file_get_contents($file);
393
	$textTMP = str_replace($text, "", $filecontents);
394
	$text = $textTMP;
395
	if($fd_log)
396
		fwrite($fd_log, $text);
397
	$fd = fopen($file, "w");
398
	fwrite($fd, $text);
399
	fclose($fd);
400
}
401

    
402
/*
403
 * add_text_to_file($file, $text): adds $text to $file.
404
 * replaces the text if it already exists.
405
 */
406
function add_text_to_file($file, $text, $replace = false) {
407
	if(file_exists($file) and is_writable($file)) {
408
		$filecontents = file($file);
409
		$fout = fopen($file, "w");
410

    
411
		$filecontents = array_map('rtrim', $filecontents);
412
		array_push($filecontents, $text);
413
		if ($replace)
414
			$filecontents = array_unique($filecontents);
415

    
416
		$file_text = implode("\n", $filecontents);
417

    
418
		fwrite($fout, $file_text);
419
		fclose($fout);
420
		return true;
421
	} else {
422
		return false;
423
	}
424
}
425

    
426
/*
427
 *   after_sync_bump_adv_skew(): create skew values by 1S
428
 */
429
function after_sync_bump_adv_skew() {
430
	global $config, $g;
431
	$processed_skew = 1;
432
	$a_vip = &$config['virtualip']['vip'];
433
	foreach ($a_vip as $vipent) {
434
		if($vipent['advskew'] <> "") {
435
			$processed_skew = 1;
436
			$vipent['advskew'] = $vipent['advskew']+1;
437
		}
438
	}
439
	if($processed_skew == 1)
440
		write_config("After synch increase advertising skew");
441
}
442

    
443
/*
444
 * get_filename_from_url($url): converts a url to its filename.
445
 */
446
function get_filename_from_url($url) {
447
	return basename($url);
448
}
449

    
450
/*
451
 *   get_dir: return an array of $dir
452
 */
453
function get_dir($dir) {
454
	$dir_array = array();
455
	$d = dir($dir);
456
	while (false !== ($entry = $d->read())) {
457
		array_push($dir_array, $entry);
458
	}
459
	$d->close();
460
	return $dir_array;
461
}
462

    
463
/****f* pfsense-utils/WakeOnLan
464
 * NAME
465
 *   WakeOnLan - Wake a machine up using the wake on lan format/protocol
466
 * RESULT
467
 *   true/false - true if the operation was successful
468
 ******/
469
function WakeOnLan($addr, $mac)
470
{
471
	$addr_byte = explode(':', $mac);
472
	$hw_addr = '';
473

    
474
	for ($a=0; $a < 6; $a++)
475
		$hw_addr .= chr(hexdec($addr_byte[$a]));
476

    
477
	$msg = chr(255).chr(255).chr(255).chr(255).chr(255).chr(255);
478

    
479
	for ($a = 1; $a <= 16; $a++)
480
		$msg .= $hw_addr;
481

    
482
	// send it to the broadcast address using UDP
483
	$s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
484
	if ($s == false) {
485
		log_error("Error creating socket!");
486
		log_error("Error code is '".socket_last_error($s)."' - " . socket_strerror(socket_last_error($s)));
487
	} else {
488
		// setting a broadcast option to socket:
489
		$opt_ret =  socket_set_option($s, 1, 6, TRUE);
490
		if($opt_ret < 0)
491
			log_error("setsockopt() failed, error: " . strerror($opt_ret));
492
		$e = socket_sendto($s, $msg, strlen($msg), 0, $addr, 2050);
493
		socket_close($s);
494
		log_error("Magic Packet sent ({$e}) to {$addr} MAC={$mac}");
495
		return true;
496
	}
497

    
498
	return false;
499
}
500

    
501
/*
502
 * gather_altq_queue_stats():  gather altq queue stats and return an array that
503
 *                             is queuename|qlength|measured_packets
504
 *                             NOTE: this command takes 5 seconds to run
505
 */
506
function gather_altq_queue_stats($dont_return_root_queues) {
507
	exec("/sbin/pfctl -vvsq", $stats_array);
508
	$queue_stats = array();
509
	foreach ($stats_array as $stats_line) {
510
		$match_array = "";
511
		if (preg_match_all("/queue\s+(\w+)\s+/",$stats_line,$match_array))
512
			$queue_name = $match_array[1][0];
513
		if (preg_match_all("/measured:\s+.*packets\/s\,\s(.*)\s+\]/",$stats_line,$match_array))
514
			$speed = $match_array[1][0];
515
		if (preg_match_all("/borrows:\s+(.*)/",$stats_line,$match_array))
516
			$borrows = $match_array[1][0];
517
		if (preg_match_all("/suspends:\s+(.*)/",$stats_line,$match_array))
518
			$suspends = $match_array[1][0];
519
		if (preg_match_all("/dropped pkts:\s+(.*)/",$stats_line,$match_array))
520
			$drops = $match_array[1][0];
521
		if (preg_match_all("/measured:\s+(.*)packets/",$stats_line,$match_array)) {
522
			$measured = $match_array[1][0];
523
			if($dont_return_root_queues == true)
524
				if(stristr($queue_name,"root_") == false)
525
					array_push($queue_stats, "{$queue_name}|{$speed}|{$measured}|{$borrows}|{$suspends}|{$drops}");
526
		}
527
	}
528
	return $queue_stats;
529
}
530

    
531
/*
532
 * reverse_strrchr($haystack, $needle):  Return everything in $haystack up to the *last* instance of $needle.
533
 *					 Useful for finding paths and stripping file extensions.
534
 */
535
function reverse_strrchr($haystack, $needle) {
536
	if (!is_string($haystack))
537
		return;
538
	return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) +1 ) : false;
539
}
540

    
541
/*
542
 *  backup_config_section($section): returns as an xml file string of
543
 *                                   the configuration section
544
 */
545
function backup_config_section($section) {
546
	global $config;
547
	$new_section = &$config[$section];
548
	/* generate configuration XML */
549
	$xmlconfig = dump_xml_config($new_section, $section);
550
	$xmlconfig = str_replace("<?xml version=\"1.0\"?>", "", $xmlconfig);
551
	return $xmlconfig;
552
}
553

    
554
/*
555
 *  restore_config_section($section, new_contents): restore a configuration section,
556
 *                                                  and write the configuration out
557
 *                                                  to disk/cf.
558
 */
559
function restore_config_section($section, $new_contents) {
560
	global $config, $g;
561
	conf_mount_rw();
562
	$fout = fopen("{$g['tmp_path']}/tmpxml","w");
563
	fwrite($fout, $new_contents);
564
	fclose($fout);
565
	$section_xml = parse_xml_config($g['tmp_path'] . "/tmpxml", $section);
566
	if ($section_xml != -1)
567
		$config[$section] = &$section_xml;
568
	@unlink($g['tmp_path'] . "/tmpxml");
569
	if(file_exists("{$g['tmp_path']}/config.cache"))
570
		unlink("{$g['tmp_path']}/config.cache");
571
	write_config("Restored {$section} of config file (maybe from CARP partner)");
572
	conf_mount_ro();
573
	return;
574
}
575

    
576
/*
577
 *  merge_config_section($section, new_contents):   restore a configuration section,
578
 *                                                  and write the configuration out
579
 *                                                  to disk/cf.  But preserve the prior
580
 * 													structure if needed
581
 */
582
function merge_config_section($section, $new_contents) {
583
	global $config;
584
	conf_mount_rw();
585
	$fname = get_tmp_filename();
586
	$fout = fopen($fname, "w");
587
	fwrite($fout, $new_contents);
588
	fclose($fout);
589
	$section_xml = parse_xml_config($fname, $section);
590
	$config[$section] = $section_xml;
591
	unlink($fname);
592
	write_config("Restored {$section} of config file (maybe from CARP partner)");
593
	conf_mount_ro();
594
	return;
595
}
596

    
597
/*
598
 * http_post($server, $port, $url, $vars): does an http post to a web server
599
 *                                         posting the vars array.
600
 * written by nf@bigpond.net.au
601
 */
602
function http_post($server, $port, $url, $vars) {
603
	$user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)";
604
	$urlencoded = "";
605
	while (list($key,$value) = each($vars))
606
		$urlencoded.= urlencode($key) . "=" . urlencode($value) . "&";
607
	$urlencoded = substr($urlencoded,0,-1);
608
	$content_length = strlen($urlencoded);
609
	$headers = "POST $url HTTP/1.1
610
Accept: */*
611
Accept-Language: en-au
612
Content-Type: application/x-www-form-urlencoded
613
User-Agent: $user_agent
614
Host: $server
615
Connection: Keep-Alive
616
Cache-Control: no-cache
617
Content-Length: $content_length
618

    
619
";
620

    
621
	$errno = "";
622
	$errstr = "";
623
	$fp = fsockopen($server, $port, $errno, $errstr);
624
	if (!$fp) {
625
		return false;
626
	}
627

    
628
	fputs($fp, $headers);
629
	fputs($fp, $urlencoded);
630

    
631
	$ret = "";
632
	while (!feof($fp))
633
		$ret.= fgets($fp, 1024);
634
	fclose($fp);
635

    
636
	return $ret;
637
}
638

    
639
/*
640
 *  php_check_syntax($code_tocheck, $errormessage): checks $code_to_check for errors
641
 */
642
if (!function_exists('php_check_syntax')){
643
	global $g;
644
	function php_check_syntax($code_to_check, &$errormessage){
645
		return false;
646
		$fout = fopen("{$g['tmp_path']}/codetocheck.php","w");
647
		$code = $_POST['content'];
648
		$code = str_replace("<?php", "", $code);
649
		$code = str_replace("?>", "", $code);
650
		fwrite($fout, "<?php\n\n");
651
		fwrite($fout, $code_to_check);
652
		fwrite($fout, "\n\n?>\n");
653
		fclose($fout);
654
		$command = "/usr/local/bin/php -l {$g['tmp_path']}/codetocheck.php";
655
		$output = exec_command($command);
656
		if (stristr($output, "Errors parsing") == false) {
657
			echo "false\n";
658
			$errormessage = '';
659
			return(false);
660
		} else {
661
			$errormessage = $output;
662
			return(true);
663
		}
664
	}
665
}
666

    
667
/*
668
 *  php_check_filename_syntax($filename, $errormessage): checks the file $filename for errors
669
 */
670
if (!function_exists('php_check_syntax')){
671
	function php_check_syntax($code_to_check, &$errormessage){
672
		return false;
673
		$command = "/usr/local/bin/php -l " . $code_to_check;
674
		$output = exec_command($command);
675
		if (stristr($output, "Errors parsing") == false) {
676
			echo "false\n";
677
			$errormessage = '';
678
			return(false);
679
		} else {
680
			$errormessage = $output;
681
			return(true);
682
		}
683
	}
684
}
685

    
686
/*
687
 * rmdir_recursive($path,$follow_links=false)
688
 * Recursively remove a directory tree (rm -rf path)
689
 * This is for directories _only_
690
 */
691
function rmdir_recursive($path,$follow_links=false) {
692
	$to_do = glob($path);
693
	if(!is_array($to_do)) $to_do = array($to_do);
694
	foreach($to_do as $workingdir) { // Handle wildcards by foreaching.
695
		if(file_exists($workingdir)) {
696
			if(is_dir($workingdir)) {
697
				$dir = opendir($workingdir);
698
				while ($entry = readdir($dir)) {
699
					if (is_file("$workingdir/$entry") || ((!$follow_links) && is_link("$workingdir/$entry")))
700
						unlink("$workingdir/$entry");
701
					elseif (is_dir("$workingdir/$entry") && $entry!='.' && $entry!='..')
702
						rmdir_recursive("$workingdir/$entry");
703
				}
704
				closedir($dir);
705
				rmdir($workingdir);
706
			} elseif (is_file($workingdir)) {
707
				unlink($workingdir);
708
			}
709
               	}
710
	}
711
	return;
712
}
713

    
714
/*
715
 * call_pfsense_method(): Call a method exposed by the pfsense.com XMLRPC server.
716
 */
717
function call_pfsense_method($method, $params, $timeout = 0) {
718
	global $g, $config;
719

    
720
	$ip = gethostbyname($g['product_website']);
721
	if($ip == $g['product_website'])
722
		return false;
723

    
724
	$xmlrpc_base_url = isset($config['system']['altpkgrepo']['enable']) ? $config['system']['altpkgrepo']['xmlrpcbaseurl'] : $g['xmlrpcbaseurl'];
725
	$xmlrpc_path = $g['xmlrpcpath'];
726
	$msg = new XML_RPC_Message($method, array(XML_RPC_Encode($params)));
727
	$cli = new XML_RPC_Client($xmlrpc_path, $xmlrpc_base_url);
728
	// If the ALT PKG Repo has a username/password set, use it.
729
	if($config['system']['altpkgrepo']['username'] && 
730
	   $config['system']['altpkgrepo']['password']) {
731
		$username = $config['system']['altpkgrepo']['username'];
732
		$password = $config['system']['altpkgrepo']['password'];
733
		$cli->setCredentials($username, $password);
734
	}
735
	$resp = $cli->send($msg, $timeout);
736
	if(!$resp) {
737
		log_error("XMLRPC communication error: " . $cli->errstr);
738
		return false;
739
	} elseif($resp->faultCode()) {
740
		log_error("XMLRPC request failed with error " . $resp->faultCode() . ": " . $resp->faultString());
741
		return false;
742
	} else {
743
		return XML_RPC_Decode($resp->value());
744
	}
745
}
746

    
747
/*
748
 * check_firmware_version(): Check whether the current firmware installed is the most recently released.
749
 */
750
function check_firmware_version($tocheck = "all", $return_php = true) {
751
	global $g, $config;
752
	$ip = gethostbyname($g['product_website']);
753
	if($ip == $g['product_website'])
754
		return false;
755
	$rawparams = array("firmware" => array("version" => trim(file_get_contents('/etc/version'))),
756
		"kernel"   => array("version" => trim(file_get_contents('/etc/version_kernel'))),
757
		"base"     => array("version" => trim(file_get_contents('/etc/version_base'))),
758
		"platform" => trim(file_get_contents('/etc/platform'))
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
	if(!$versions = call_pfsense_method('pfsense.get_firmware_version', $params)) {
772
		return false;
773
	} else {
774
		$versions["current"] = $params;
775
	}
776
	return $versions;
777
}
778

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

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

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

    
813
	/* XXX: Use locks?! */
814
	if (file_exists("{$g['tmp_path']}/reloading_all")) {
815
		log_error("WARNING: Recursive call to interfaces sync!");
816
		return;
817
	}
818
	touch("{$g['tmp_path']}/reloading_all");
819

    
820
	if($g['debug'])
821
		log_error("reload_interfaces_sync() is starting.");
822

    
823
	/* parse config.xml again */
824
	$config = parse_config(true);
825

    
826
	/* enable routing */
827
	system_routing_enable();
828
	if($g['debug'])
829
		log_error("Enabling system routing");
830

    
831
	if($g['debug'])
832
		log_error("Cleaning up Interfaces");
833

    
834
	/* set up interfaces */
835
	interfaces_configure();
836

    
837
	/* remove reloading_all trigger */
838
	if($g['debug'])
839
		log_error("Removing {$g['tmp_path']}/reloading_all");
840

    
841
	/* start devd back up */
842
	mwexec("/bin/rm {$g['tmp_path']}/reload*");
843
}
844

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

    
858
/****f* pfsense-utils/reload_interfaces
859
 * NAME
860
 *   reload_interfaces - triggers a reload of all interfaces
861
 * INPUTS
862
 *   none
863
 * RESULT
864
 *   none
865
 ******/
866
function reload_interfaces() {
867
	global $g;
868
	touch("{$g['tmp_path']}/reload_interfaces");
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
	/* XXX: Use locks?! */
885
        if (file_exists("{$g['tmp_path']}/reloading_all")) {
886
                log_error("WARNING: Recursive call to reload all sync!");
887
                return;
888
        }
889
	touch("{$g['tmp_path']}/reloading_all");
890

    
891
	/* parse config.xml again */
892
	$config = parse_config(true);
893

    
894
	/* set up our timezone */
895
	system_timezone_configure();
896

    
897
	/* set up our hostname */
898
	system_hostname_configure();
899

    
900
	/* make hosts file */
901
	system_hosts_generate();
902

    
903
	/* generate resolv.conf */
904
	system_resolvconf_generate();
905

    
906
	/* enable routing */
907
	system_routing_enable();
908

    
909
	/* set up interfaces */
910
	interfaces_configure();
911

    
912
	/* start dyndns service */
913
	services_dyndns_configure();
914

    
915
	/* configure cron service */
916
	configure_cron();
917

    
918
	/* start the NTP client */
919
	system_ntp_configure();
920

    
921
	/* sync pw database */
922
	conf_mount_rw();
923
	unlink_if_exists("/etc/spwd.db.tmp");
924
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
925
	conf_mount_ro();
926

    
927
	/* restart sshd */
928
	send_event("service restart sshd");
929

    
930
	/* restart webConfigurator if needed */
931
	send_event("service restart webgui");
932

    
933
	mwexec("/bin/rm {$g['tmp_path']}/reload*");
934
}
935

    
936
function auto_login() {
937
	global $config;
938

    
939
	if(isset($config['system']['disableconsolemenu']))
940
		$status = false;
941
	else
942
		$status = true;
943

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

    
974
function setup_serial_port() {
975
	global $g, $config;
976
	conf_mount_rw();
977
	/* serial console - write out /boot.config */
978
	if(file_exists("/boot.config"))
979
		$boot_config = file_get_contents("/boot.config");
980
	else
981
		$boot_config = "";
982

    
983
	if($g['platform'] <> "cdrom") {
984
		$boot_config_split = split("\n", $boot_config);
985
		$fd = fopen("/boot.config","w");
986
		if($fd) {
987
			foreach($boot_config_split as $bcs) {
988
				if(stristr($bcs, "-D")) {
989
					/* DONT WRITE OUT, WE'LL DO IT LATER */
990
				} else {
991
					if($bcs <> "")
992
						fwrite($fd, "{$bcs}\n");
993
				}
994
			}
995
			if(isset($config['system']['enableserial'])) {
996
				fwrite($fd, "-D");
997
			}
998
			fclose($fd);
999
		}
1000
		/* serial console - write out /boot/loader.conf */
1001
		$boot_config = file_get_contents("/boot/loader.conf");
1002
		$boot_config_split = split("\n", $boot_config);
1003
		$fd = fopen("/boot/loader.conf","w");
1004
		if($fd) {
1005
			foreach($boot_config_split as $bcs) {
1006
				if(stristr($bcs, "console")) {
1007
					/* DONT WRITE OUT, WE'LL DO IT LATER */
1008
				} else {
1009
					if($bcs <> "")
1010
						fwrite($fd, "{$bcs}\n");
1011
				}
1012
			}
1013
			if(isset($config['system']['enableserial'])) {
1014
				fwrite($fd, "console=\"comconsole\"\n");
1015
			}
1016
			fclose($fd);
1017
		}
1018
	}
1019
	$ttys = file_get_contents("/etc/ttys");
1020
	$ttys_split = split("\n", $ttys);
1021
	$fd = fopen("/etc/ttys", "w");
1022
	foreach($ttys_split as $tty) {
1023
		if(stristr($tty, "ttyd0") or stristr($tty, "ttyu0")) {
1024
			if(isset($config['system']['enableserial'])) {
1025
				fwrite($fd, "ttyu0	\"/usr/libexec/getty bootupcli\"	cons25	on	secure\n");
1026
			} else {
1027
				fwrite($fd, "ttyu0	\"/usr/libexec/getty bootupcli\"	cons25	off	secure\n");
1028
			}
1029
		} else {
1030
			fwrite($fd, $tty . "\n");
1031
		}
1032
	}
1033
	fclose($fd);
1034
	auto_login();
1035

    
1036
	conf_mount_ro();
1037
	return;
1038
}
1039

    
1040
function print_value_list($list, $count = 10, $separator = ",") {
1041
	$list = implode($separator, array_slice($list, 0, $count));
1042
	if(count($list) < $count) {
1043
		$list .= ".";
1044
	} else {
1045
		$list .= "...";
1046
	}
1047
	return $list;
1048
}
1049

    
1050
/* DHCP enabled on any interfaces? */
1051
function is_dhcp_server_enabled() 
1052
{
1053
	global $config;
1054

    
1055
	$dhcpdenable = false;
1056
	
1057
	if (!is_array($config['dhcpd']))
1058
		return false;
1059

    
1060
	$Iflist = get_configured_interface_list();
1061

    
1062
	foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf) {
1063
		if (isset($dhcpifconf['enable']) && isset($Iflist[$dhcpif])) {
1064
			$dhcpdenable = true;
1065
			break;
1066
		}
1067
	}
1068

    
1069
	return $dhcpdenable;
1070
}
1071

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

    
1092
/* Compute the total uptime from the ppp uptime log file in the conf directory */
1093

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

    
1109
//returns interface information
1110
function get_interface_info($ifdescr) {
1111
	global $config, $g;
1112

    
1113
	$ifinfo = array();
1114
	if (empty($config['interfaces'][$ifdescr]))
1115
		return;
1116
	$ifinfo['hwif'] = $config['interfaces'][$ifdescr]['if'];
1117
	$ifinfo['if'] = get_real_interface($ifdescr);
1118

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

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

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

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

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

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

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

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

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

    
1277
		}
1278
		/* lookup the gateway */
1279
		if (interface_has_gateway($ifdescr)) 
1280
			$ifinfo['gateway'] = get_interface_gateway($ifdescr);
1281
	}
1282

    
1283
	$bridge = "";
1284
	$bridge = link_interface_to_bridge($ifdescr);
1285
	if($bridge) {
1286
		$bridge_text = `/sbin/ifconfig {$bridge}`;
1287
		if(stristr($bridge_text, "blocking") <> false) {
1288
			$ifinfo['bridge'] = "<b><font color='red'>blocking</font></b> - check for ethernet loops";
1289
			$ifinfo['bridgeint'] = $bridge;
1290
		} else if(stristr($bridge_text, "learning") <> false) {
1291
			$ifinfo['bridge'] = "learning";
1292
			$ifinfo['bridgeint'] = $bridge;
1293
		} else if(stristr($bridge_text, "forwarding") <> false) {
1294
			$ifinfo['bridge'] = "forwarding";
1295
			$ifinfo['bridgeint'] = $bridge;
1296
		}
1297
	}
1298

    
1299
	return $ifinfo;
1300
}
1301

    
1302
//returns cpu speed of processor. Good for determining capabilities of machine
1303
function get_cpu_speed() {
1304
	 return exec("sysctl hw.clockrate | awk '{ print $2 }'");
1305
}
1306

    
1307
function add_hostname_to_watch($hostname) {
1308
	if(!is_dir("/var/db/dnscache")) {
1309
		mkdir("/var/db/dnscache");
1310
	}
1311
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1312
		$domrecords = array();
1313
		$domips = array();
1314
		exec("host -t A $hostname", $domrecords, $rethost);
1315
		if($rethost == 0) {
1316
			foreach($domrecords as $domr) {
1317
				$doml = explode(" ", $domr);
1318
				$domip = $doml[3];
1319
				/* fill array with domain ip addresses */
1320
				if(is_ipaddr($domip)) {
1321
					$domips[] = $domip;
1322
				}
1323
			}
1324
		}
1325
		sort($domips);
1326
		$contents = "";
1327
		if(! empty($domips)) {
1328
			foreach($domips as $ip) {
1329
				$contents .= "$ip\n";
1330
			}
1331
		}
1332
		file_put_contents("/var/db/dnscache/$hostname", $contents);
1333
	}
1334
}
1335

    
1336
function is_fqdn($fqdn) {
1337
	$hostname = false;
1338
	if(preg_match("/[-A-Z0-9\.]+\.[-A-Z0-9\.]+/i", $fqdn)) {
1339
		$hostname = true;
1340
	}
1341
	if(preg_match("/\.\./", $fqdn)) {
1342
		$hostname = false;
1343
	}
1344
	if(preg_match("/^\./i", $fqdn)) { 
1345
		$hostname = false;
1346
	}
1347
	if(preg_match("/\//i", $fqdn)) {
1348
		$hostname = false;
1349
	}
1350
	return($hostname);
1351
}
1352

    
1353
function pfsense_default_state_size() {
1354
  /* get system memory amount */
1355
  $memory = get_memory();
1356
  $avail = $memory[0];
1357
  /* Be cautious and only allocate 10% of system memory to the state table */
1358
  $max_states = (int) ($avail/10)*1000;
1359
  return $max_states;
1360
}
1361

    
1362
function pfsense_default_table_entries_size() {
1363
	$current = `pfctl -sm | grep table-entries | awk '{print $4};'`;
1364
	return $current;
1365
}
1366

    
1367
/* Compare the current hostname DNS to the DNS cache we made
1368
 * if it has changed we return the old records
1369
 * if no change we return true */
1370
function compare_hostname_to_dnscache($hostname) {
1371
	if(!is_dir("/var/db/dnscache")) {
1372
		mkdir("/var/db/dnscache");
1373
	}
1374
	$hostname = trim($hostname);
1375
	if(is_readable("/var/db/dnscache/{$hostname}")) {
1376
		$oldcontents = file_get_contents("/var/db/dnscache/{$hostname}");
1377
	} else {
1378
		$oldcontents = "";
1379
	}
1380
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1381
		$domrecords = array();
1382
		$domips = array();
1383
		exec("host -t A $hostname", $domrecords, $rethost);
1384
		if($rethost == 0) {
1385
			foreach($domrecords as $domr) {
1386
				$doml = explode(" ", $domr);
1387
				$domip = $doml[3];
1388
				/* fill array with domain ip addresses */
1389
				if(is_ipaddr($domip)) {
1390
					$domips[] = $domip;
1391
				}
1392
			}
1393
		}
1394
		sort($domips);
1395
		$contents = "";
1396
		if(! empty($domips)) {
1397
			foreach($domips as $ip) {
1398
				$contents .= "$ip\n";
1399
			}
1400
		}
1401
	}
1402

    
1403
	if(trim($oldcontents) != trim($contents)) {
1404
		if($g['debug']) {
1405
			log_error("DNSCACHE: Found old IP {$oldcontents} and new IP {$contents}");
1406
		}
1407
		return ($oldcontents);
1408
	} else {
1409
		return false;
1410
	}
1411
}
1412

    
1413
/*
1414
 * load_glxsb() - Load the glxsb crypto module if enabled in config.
1415
 */
1416
function load_glxsb() {
1417
	global $config, $g;
1418
	$is_loaded = `/sbin/kldstat | /usr/bin/grep -c glxsb`;
1419
	if (isset($config['system']['glxsb_enable']) && ($is_loaded == 0)) {
1420
		mwexec("/sbin/kldload glxsb");
1421
	}
1422
}
1423

    
1424
/****f* pfsense-utils/isvm
1425
 * NAME
1426
 *   isvm
1427
 * INPUTS
1428
 *	 none
1429
 * RESULT
1430
 *   returns true if machine is running under a virtual environment
1431
 ******/
1432
function isvm() {
1433
	$virtualenvs = array("vmware", "parallels", "qemu", "bochs", "plex86");
1434
	$bios_vendor = strtolower(`/bin/kenv | /usr/bin/awk -F= '/smbios.bios.vendor/ {print $2}'`);
1435
	if(in_array($bios_vendor, $virtualenvs)) 
1436
		return true;
1437
	else
1438
		return false;
1439
}
1440

    
1441
function get_freebsd_version() {
1442
	$version = trim(`/usr/bin/uname -r | /usr/bin/cut  -d'.' -f1`);
1443
	return $version;
1444
}
1445

    
1446
function download_file_with_progress_bar($url_file, $destination_file, $readbody = 'read_body') {
1447
        global $ch, $fout, $file_size, $downloaded;
1448
        $file_size  = 1;
1449
        $downloaded = 1;
1450
        /* open destination file */
1451
        $fout = fopen($destination_file, "wb");
1452

    
1453
        /*
1454
         *      Originally by Author: Keyvan Minoukadeh
1455
         *      Modified by Scott Ullrich to return Content-Length size
1456
         */
1457

    
1458
        $ch = curl_init();
1459
        curl_setopt($ch, CURLOPT_URL, $url_file);
1460
        curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
1461
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1462
        /* Don't verify SSL peers since we don't have the certificates to do so. */
1463
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1464
        curl_setopt($ch, CURLOPT_WRITEFUNCTION, $readbody);
1465
        curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
1466
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, '5');
1467
        curl_setopt($ch, CURLOPT_TIMEOUT, 0);
1468

    
1469
        curl_exec($ch);
1470
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1471
        if($fout)
1472
                fclose($fout);
1473
        curl_close($ch);
1474
        return ($http_code == 200) ? true : $http_code;
1475
}
1476

    
1477
function read_header($ch, $string) {
1478
        global $file_size, $fout;
1479
        $length = strlen($string);
1480
        $regs = "";
1481
        ereg("(Content-Length:) (.*)", $string, $regs);
1482
        if($regs[2] <> "") {
1483
                $file_size = intval($regs[2]);
1484
        }
1485
        ob_flush();
1486
        return $length;
1487
}
1488

    
1489
function read_body($ch, $string) {
1490
        global $fout, $file_size, $downloaded, $sendto, $static_status, $static_output, $lastseen;
1491
        $length = strlen($string);
1492
        $downloaded += intval($length);
1493
        $downloadProgress = round(100 * (1 - $downloaded / $file_size), 0);
1494
        $downloadProgress = 100 - $downloadProgress;
1495
        if($lastseen <> $downloadProgress and $downloadProgress < 101) {
1496
                if($sendto == "status") {
1497
                        $tostatus = $static_status . $downloadProgress . "%";
1498
                        update_status($tostatus);
1499
                } else {
1500
                        $tooutput = $static_output . $downloadProgress . "%";
1501
                        update_output_window($tooutput);
1502
                }
1503
                update_progress_bar($downloadProgress);
1504
                $lastseen = $downloadProgress;
1505
        }
1506
        if($fout)
1507
                fwrite($fout, $string);
1508
        ob_flush();
1509
        return $length;
1510
}
1511

    
1512
/*
1513
 *   update_output_window: update bottom textarea dynamically.
1514
 */
1515
function update_output_window($text) {
1516
        global $pkg_interface;
1517
        $log = ereg_replace("\n", "\\n", $text);
1518
        if($pkg_interface == "console") {
1519
                /* too chatty */
1520
        } else {
1521
                echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = \"" . $log . "\";</script>";
1522
        }
1523
        /* ensure that contents are written out */
1524
        ob_flush();
1525
}
1526

    
1527
/*
1528
 *   update_output_window: update top textarea dynamically.
1529
 */
1530
function update_status($status) {
1531
        global $pkg_interface;
1532
        if($pkg_interface == "console") {
1533
                echo $status . "\n";
1534
        } else {
1535
                echo "\n<script type=\"text/javascript\">this.document.forms[0].status.value=\"" . $status . "\";</script>";
1536
        }
1537
        /* ensure that contents are written out */
1538
        ob_flush();
1539
}
1540

    
1541
/*
1542
 * update_progress_bar($percent): updates the javascript driven progress bar.
1543
 */
1544
function update_progress_bar($percent) {
1545
        global $pkg_interface;
1546
        if($percent > 100) $percent = 1;
1547
        if($pkg_interface <> "console") {
1548
                echo "\n<script type=\"text/javascript\" language=\"javascript\">";
1549
                echo "\ndocument.progressbar.style.width='" . $percent . "%';";
1550
                echo "\n</script>";
1551
        } else {
1552
                echo " {$percent}%";
1553
        }
1554
}
1555

    
1556
/* 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. */
1557
if(!function_exists("split")) {
1558
	function split($seperator, $haystack, $limit = null) {
1559
		return preg_split($seperator, $haystack, $limit);
1560
	}
1561
}
1562

    
1563
function update_alias_names_upon_change($section, $subsection, $fielda, $fieldb, $new_alias_name, $origname) {
1564
	global $g, $config, $pconfig, $debug;
1565
	if(!$origname) 
1566
		return;
1567

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

    
1571
	if($fieldb) {
1572
		if($debug) fwrite($fd, "fieldb exists\n");
1573
		for ($i = 0; isset($config["$section"]["$subsection"][$i]["$fielda"]); $i++) {
1574
			if($debug) fwrite($fd, "$i\n");
1575
			if($config["$section"]["$subsection"][$i]["$fielda"]["$fieldb"] == $origname) {
1576
				if($debug) fwrite($fd, "Setting old alias value $origname to $new_alias_name\n");
1577
				$config["$section"]["$subsection"][$i]["$fielda"]["$fieldb"] = $new_alias_name;
1578
			}
1579
		}	
1580
	} else {
1581
		if($debug) fwrite($fd, "fieldb does not exist\n");
1582
		for ($i = 0; isset($config["$section"]["$subsection"][$i]["$fielda"]); $i++) {
1583
			if($config["$section"]["$subsection"][$i]["$fielda"] == $origname) {
1584
				$config["$section"]["$subsection"][$i]["$fielda"] = $new_alias_name;
1585
				if($debug) fwrite($fd, "Setting old alias value $origname to $new_alias_name\n");
1586
			}
1587
		}
1588
	}
1589

    
1590
	if($debug) fclose($fd);
1591

    
1592
}
1593

    
1594
function update_alias_url_data() {
1595
	global $config, $g;
1596

    
1597
	/* item is a url type */
1598
	$lockkey = lock('config');
1599
	if (is_array($config['aliases']['alias'])) {
1600
		foreach ($config['aliases']['alias'] as $x => $alias) {
1601
			if (empty($alias['aliasurl']))
1602
				continue;
1603

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

    
1648
function process_alias_unzip($temp_filename) {
1649
	if(!file_exists("/usr/local/bin/unzip"))
1650
		return;
1651
	mwexec("/bin/mv {$temp_filename}/aliases {$temp_filename}/aliases.zip");
1652
	mwexec("/usr/local/bin/unzip {$temp_filename}/aliases.tgz -d {$temp_filename}/aliases/");
1653
	unlink("{$temp_filename}/aliases.zip");
1654
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1655
	/* foreach through all extracted files and build up aliases file */
1656
	$fd = fopen("{$temp_filename}/aliases", "w");
1657
	foreach($files_to_process as $f2p) {
1658
		$file_contents = file_get_contents($f2p);
1659
		fwrite($fd, $file_contents);
1660
		unlink($f2p);
1661
	}
1662
	fclose($fd);
1663
}
1664

    
1665
function process_alias_tgz($temp_filename) {
1666
	if(!file_exists("/usr/bin/tar"))
1667
		return;
1668
	mwexec("/bin/mv {$temp_filename}/aliases {$temp_filename}/aliases.tgz");
1669
	mwexec("/usr/bin/tar xzf {$temp_filename}/aliases.tgz -C {$temp_filename}/aliases/");
1670
	unlink("{$temp_filename}/aliases.tgz");
1671
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1672
	/* foreach through all extracted files and build up aliases file */
1673
	$fd = fopen("{$temp_filename}/aliases", "w");
1674
	foreach($files_to_process as $f2p) {
1675
		$file_contents = file_get_contents($f2p);
1676
		fwrite($fd, $file_contents);
1677
		unlink($f2p);
1678
	}
1679
	fclose($fd);
1680
}
1681

    
1682
function version_compare_dates($a, $b) {
1683
	$a_time = strtotime($a);
1684
	$b_time = strtotime($b);
1685

    
1686
	if ((!$a_time) || (!$b_time)) {
1687
		return FALSE;
1688
	} else {
1689
		if ($a < $b)
1690
			return -1;
1691
		elseif ($a == $b)
1692
			return 0;
1693
		else
1694
			return 1;
1695
	}
1696
}
1697
function version_get_string_value($a) {
1698
	$strs = array(
1699
		0 => "ALPHA-ALPHA",
1700
		2 => "ALPHA",
1701
		3 => "BETA",
1702
		4 => "B",
1703
		5 => "C",
1704
		6 => "D",
1705
		7 => "RC",
1706
		8 => "RELEASE"
1707
	);
1708
	$major = 0;
1709
	$minor = 0;
1710
	foreach ($strs as $num => $str) {
1711
		if (substr($a, 0, strlen($str)) == $str) {
1712
			$major = $num;
1713
			$n = substr($a, strlen($str));
1714
			if (is_numeric($n))
1715
				$minor = $n;
1716
			break;
1717
		}
1718
	}
1719
	return "{$major}.{$minor}";
1720
}
1721
function version_compare_string($a, $b) {
1722
	return version_compare_numeric(version_get_string_value($a), version_get_string_value($b));
1723
}
1724
function version_compare_numeric($a, $b) {
1725
	$a_arr = explode('.', rtrim($a, '.0'));
1726
	$b_arr = explode('.', rtrim($b, '.0'));
1727

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

    
1759
		// First try to compare the numeric parts of the version string.
1760
		$v = version_compare_numeric($cur_num, $rem_num);
1761

    
1762
		// If the numeric parts are the same, compare the string parts.
1763
		if ($v == 0)
1764
			return version_compare_string($cur_str, $rem_str);
1765
	}
1766
	return $v;
1767
}
1768
function process_alias_urltable($name, $url, $freq, $forceupdate=false) {
1769
	$urltable_prefix = "/var/db/aliastables/";
1770
	$urltable_filename = $urltable_prefix . $name . ".txt";
1771

    
1772
	// Make the aliases directory if it doesn't exist
1773
	if (!file_exists($urltable_prefix)) {
1774
		mkdir($urltable_prefix);
1775
	} elseif (!is_dir($urltable_prefix)) {
1776
		unlink($urltable_prefix);
1777
		mkdir($urltable_prefix);
1778
	}
1779

    
1780
	// If the file doesn't exist or is older than update_freq days, fetch a new copy.
1781
	if (!file_exists($urltable_filename)
1782
		|| ((time() - filemtime($urltable_filename)) > ($freq * 86400))
1783
		|| $forceupdate) {
1784

    
1785
		// Try to fetch the URL supplied
1786
		conf_mount_rw();
1787
		unlink_if_exists($urltable_filename . ".tmp");
1788
		// 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.
1789
		mwexec("/usr/bin/fetch -q -o " . escapeshellarg($urltable_filename . ".tmp") . " " . escapeshellarg($url));
1790
		// Remove comments. Might need some grep-fu to only allow lines that look like IPs/subnets
1791
		mwexec("/usr/bin/grep -v '^#' " . escapeshellarg($urltable_filename . ".tmp") . " > " . escapeshellarg($urltable_filename));
1792
		unlink_if_exists($urltable_filename . ".tmp");
1793
		conf_mount_ro();
1794
		if (filesize($urltable_filename)) {
1795
			return true;
1796
		} else {
1797
			// If it's unfetchable or an empty file, bail
1798
			return false;
1799
		}
1800
	} else {
1801
		// File exists, and it doesn't need updated.
1802
		return -1;
1803
	}
1804
}
1805
function get_real_slice_from_glabel($label) {
1806
	$label = escapeshellarg($label);
1807
	return trim(`/sbin/glabel list | /usr/bin/grep -B2 ufs/{$label} | /usr/bin/head -n 1 | /usr/bin/cut -f3 -d' '`);
1808
}
1809
function nanobsd_get_boot_slice() {
1810
	return trim(`/sbin/mount | /usr/bin/grep pfsense | /usr/bin/cut -d'/' -f4 | /usr/bin/cut -d' ' -f1`);
1811
}
1812
function nanobsd_get_boot_drive() {
1813
	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`);
1814
}
1815
function nanobsd_get_active_slice() {
1816
	$boot_drive = nanobsd_get_boot_drive();
1817
	$active = trim(`gpart show $boot_drive | grep '\[active\]' | awk '{print $3;}'`);
1818

    
1819
	return "{$boot_drive}s{$active}";
1820
}
1821
function nanobsd_get_size() {
1822
	return strtoupper(file_get_contents("/etc/nanosize.txt"));
1823
}
1824
function nanobsd_switch_boot_slice() {
1825
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
1826
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
1827
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
1828
	nanobsd_detect_slice_info();
1829

    
1830
	if ($BOOTFLASH == $ACTIVE_SLICE) {
1831
		$slice = $TOFLASH;
1832
	} else {
1833
		$slice = $BOOTFLASH;
1834
	}
1835

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

    
1872
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
1873
	ob_implicit_flush(1);
1874
	exec("/sbin/sysctl kern.geom.debugflags=16");
1875
	exec("/bin/dd if=/dev/zero of=/dev/{$TOFLASH} bs=1m count=1");
1876
	exec("/bin/dd if=/dev/{$BOOTFLASH} of=/dev/{$TOFLASH} bs=64k");
1877
	exec("/sbin/tunefs -L {$GLABEL_SLICE} /dev/{$COMPLETE_PATH}");
1878
	$status = nanobsd_update_fstab($GLABEL_SLICE, $COMPLETE_PATH, $OLD_UFS_ID, $UFS_ID);
1879
	exec("/sbin/sysctl kern.geom.debugflags=0");
1880
	if($status) {
1881
		return false;
1882
	} else {
1883
		return true;
1884
	}
1885
}
1886
function nanobsd_update_fstab($gslice, $complete_path, $oldufs, $newufs) {
1887
	$tmppath = "/tmp/{$gslice}";
1888
	$fstabpath = "/tmp/{$gslice}/etc/fstab";
1889

    
1890
	exec("/bin/mkdir {$tmppath}");
1891
	exec("/sbin/fsck_ufs -y /dev/{$complete_path}");
1892
	exec("/sbin/mount /dev/ufs/{$gslice} {$tmppath}");
1893
	exec("/bin/cp /etc/fstab {$fstabpath}");
1894

    
1895
	if (!file_exists($fstabpath)) {
1896
		$fstab = <<<EOF
1897
/dev/ufs/{$gslice} / ufs ro,noatime 1 1
1898
/dev/ufs/cf /cf ufs ro,noatime 1 1
1899
EOF;
1900
		if (file_put_contents($fstabpath, $fstab))
1901
			$status = true;
1902
		else
1903
			$status = false;
1904
	} else {
1905
		$status = exec("sed -i \"\" \"s/pfsense{$oldufs}/pfsense{$newufs}/g\" {$fstabpath}");
1906
	}
1907
	exec("/sbin/umount {$tmppath}");
1908
	exec("/bin/rmdir {$tmppath}");
1909

    
1910
	return $status;
1911
}
1912
function nanobsd_detect_slice_info() {
1913
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
1914
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
1915
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
1916

    
1917
	$BOOT_DEVICE=nanobsd_get_boot_slice();
1918
	$REAL_BOOT_DEVICE=get_real_slice_from_glabel($BOOT_DEVICE);
1919
	$BOOT_DRIVE=nanobsd_get_boot_drive();
1920
	$ACTIVE_SLICE=nanobsd_get_active_slice();
1921

    
1922
	// Detect which slice is active and set information.
1923
	if(strstr($REAL_BOOT_DEVICE, "s1")) {
1924
		$SLICE="2";
1925
		$OLDSLICE="1";
1926
		$GLABEL_SLICE="pfsense1";
1927
		$UFS_ID="1";
1928
		$OLD_UFS_ID="0";
1929

    
1930
	} else {
1931
		$SLICE="1";
1932
		$OLDSLICE="2";
1933
		$GLABEL_SLICE="pfsense0";
1934
		$UFS_ID="0";
1935
		$OLD_UFS_ID="1";
1936
	}
1937
	$TOFLASH="{$BOOT_DRIVE}s{$SLICE}";
1938
	$COMPLETE_PATH="{$BOOT_DRIVE}s{$SLICE}a";
1939
	$COMPLETE_BOOT_PATH="{$BOOT_DRIVE}s{$OLDSLICE}";
1940
	$BOOTFLASH="{$BOOT_DRIVE}s{$OLDSLICE}";
1941
}
1942

    
1943
function nanobsd_friendly_slice_name($slicename) {
1944
	global $g;
1945
	return strtolower(str_ireplace('pfsense', $g['product_name'], $slicename));
1946
}
1947

    
1948
function get_include_contents($filename) {
1949
    if (is_file($filename)) {
1950
        ob_start();
1951
        include $filename;
1952
        $contents = ob_get_contents();
1953
        ob_end_clean();
1954
        return $contents;
1955
    }
1956
    return false;
1957
}
1958

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

    
2094
function get_country_name($country_code) {
2095
	if ($country_code != "ALL" && strlen($country_code) != 2)
2096
		return "";
2097

    
2098
	$country_names_xml = "/usr/local/share/mobile-broadband-provider-info/iso_3166-1_list_en.xml";
2099
	$country_names_contents = file_get_contents($country_names_xml);
2100
	$country_names = xml2array($country_names_contents);
2101

    
2102
	if($country_code == "ALL") {
2103
		$country_list = array();
2104
		foreach($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2105
			$country_list[] = array( "code" => $country['ISO_3166-1_Alpha-2_Code_element'],
2106
						 "name" => ucwords(strtolower($country['ISO_3166-1_Country_name'])) );
2107
		}
2108
		return $country_list;
2109
	}
2110

    
2111
	foreach ($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2112
		if ($country['ISO_3166-1_Alpha-2_Code_element'] == strtoupper($country_code)) {
2113
			return ucwords(strtolower($country['ISO_3166-1_Country_name']));
2114
		}
2115
	}
2116
	return "";
2117
}
2118

    
2119
?>
(30-30/54)