Project

General

Profile

Download (65.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_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 gettext("MASTER");
346
		if(stristr($int, "BACKUP")) 
347
			return gettext("BACKUP");
348
		if(stristr($int, "INIT")) 
349
			return gettext("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(gettext("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(gettext("Error creating socket!"));
463
		log_error(sprintf(gettext("Error code is '%1\$s' - %2\$s"), 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(sprintf(gettext("setsockopt() failed, error: %s"), strerror($opt_ret)));
469
		$e = socket_sendto($s, $msg, strlen($msg), 0, $addr, 2050);
470
		socket_close($s);
471
		log_error(sprintf(gettext('Magic Packet sent (%1$s) to {%2$s} MAC=%3$s'), $e, $addr, $mac));
472
		return true;
473
	}
474

    
475
	return false;
476
}
477

    
478
/*
479
 * reverse_strrchr($haystack, $needle):  Return everything in $haystack up to the *last* instance of $needle.
480
 *					 Useful for finding paths and stripping file extensions.
481
 */
482
function reverse_strrchr($haystack, $needle) {
483
	if (!is_string($haystack))
484
		return;
485
	return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) +1 ) : false;
486
}
487

    
488
/*
489
 *  backup_config_section($section): returns as an xml file string of
490
 *                                   the configuration section
491
 */
492
function backup_config_section($section) {
493
	global $config;
494
	$new_section = &$config[$section];
495
	/* generate configuration XML */
496
	$xmlconfig = dump_xml_config($new_section, $section);
497
	$xmlconfig = str_replace("<?xml version=\"1.0\"?>", "", $xmlconfig);
498
	return $xmlconfig;
499
}
500

    
501
/*
502
 *  restore_config_section($section, new_contents): restore a configuration section,
503
 *                                                  and write the configuration out
504
 *                                                  to disk/cf.
505
 */
506
function restore_config_section($section, $new_contents) {
507
	global $config, $g;
508
	conf_mount_rw();
509
	$fout = fopen("{$g['tmp_path']}/tmpxml","w");
510
	fwrite($fout, $new_contents);
511
	fclose($fout);
512
	$section_xml = parse_xml_config($g['tmp_path'] . "/tmpxml", $section);
513
	if ($section_xml != -1)
514
		$config[$section] = &$section_xml;
515
	@unlink($g['tmp_path'] . "/tmpxml");
516
	if(file_exists("{$g['tmp_path']}/config.cache"))
517
		unlink("{$g['tmp_path']}/config.cache");
518
	write_config(sprintf(gettext("Restored %s of config file (maybe from CARP partner)"), $section));
519
	disable_security_checks();
520
	conf_mount_ro();
521
	return;
522
}
523

    
524
/*
525
 *  merge_config_section($section, new_contents):   restore a configuration section,
526
 *                                                  and write the configuration out
527
 *                                                  to disk/cf.  But preserve the prior
528
 * 													structure if needed
529
 */
530
function merge_config_section($section, $new_contents) {
531
	global $config;
532
	conf_mount_rw();
533
	$fname = get_tmp_filename();
534
	$fout = fopen($fname, "w");
535
	fwrite($fout, $new_contents);
536
	fclose($fout);
537
	$section_xml = parse_xml_config($fname, $section);
538
	$config[$section] = $section_xml;
539
	unlink($fname);
540
	write_config(sprintf(gettext("Restored %s of config file (maybe from CARP partner)"), $section));
541
	disable_security_checks();
542
	conf_mount_ro();
543
	return;
544
}
545

    
546
/*
547
 * http_post($server, $port, $url, $vars): does an http post to a web server
548
 *                                         posting the vars array.
549
 * written by nf@bigpond.net.au
550
 */
551
function http_post($server, $port, $url, $vars) {
552
	$user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)";
553
	$urlencoded = "";
554
	while (list($key,$value) = each($vars))
555
		$urlencoded.= urlencode($key) . "=" . urlencode($value) . "&";
556
	$urlencoded = substr($urlencoded,0,-1);
557
	$content_length = strlen($urlencoded);
558
	$headers = "POST $url HTTP/1.1
559
Accept: */*
560
Accept-Language: en-au
561
Content-Type: application/x-www-form-urlencoded
562
User-Agent: $user_agent
563
Host: $server
564
Connection: Keep-Alive
565
Cache-Control: no-cache
566
Content-Length: $content_length
567

    
568
";
569

    
570
	$errno = "";
571
	$errstr = "";
572
	$fp = fsockopen($server, $port, $errno, $errstr);
573
	if (!$fp) {
574
		return false;
575
	}
576

    
577
	fputs($fp, $headers);
578
	fputs($fp, $urlencoded);
579

    
580
	$ret = "";
581
	while (!feof($fp))
582
		$ret.= fgets($fp, 1024);
583
	fclose($fp);
584

    
585
	return $ret;
586
}
587

    
588
/*
589
 *  php_check_syntax($code_tocheck, $errormessage): checks $code_to_check for errors
590
 */
591
if (!function_exists('php_check_syntax')){
592
	global $g;
593
	function php_check_syntax($code_to_check, &$errormessage){
594
		return false;
595
		$fout = fopen("{$g['tmp_path']}/codetocheck.php","w");
596
		$code = $_POST['content'];
597
		$code = str_replace("<?php", "", $code);
598
		$code = str_replace("?>", "", $code);
599
		fwrite($fout, "<?php\n\n");
600
		fwrite($fout, $code_to_check);
601
		fwrite($fout, "\n\n?>\n");
602
		fclose($fout);
603
		$command = "/usr/local/bin/php -l {$g['tmp_path']}/codetocheck.php";
604
		$output = exec_command($command);
605
		if (stristr($output, "Errors parsing") == false) {
606
			echo "false\n";
607
			$errormessage = '';
608
			return(false);
609
		} else {
610
			$errormessage = $output;
611
			return(true);
612
		}
613
	}
614
}
615

    
616
/*
617
 *  php_check_filename_syntax($filename, $errormessage): checks the file $filename for errors
618
 */
619
if (!function_exists('php_check_syntax')){
620
	function php_check_syntax($code_to_check, &$errormessage){
621
		return false;
622
		$command = "/usr/local/bin/php -l " . $code_to_check;
623
		$output = exec_command($command);
624
		if (stristr($output, "Errors parsing") == false) {
625
			echo "false\n";
626
			$errormessage = '';
627
			return(false);
628
		} else {
629
			$errormessage = $output;
630
			return(true);
631
		}
632
	}
633
}
634

    
635
/*
636
 * rmdir_recursive($path,$follow_links=false)
637
 * Recursively remove a directory tree (rm -rf path)
638
 * This is for directories _only_
639
 */
640
function rmdir_recursive($path,$follow_links=false) {
641
	$to_do = glob($path);
642
	if(!is_array($to_do)) $to_do = array($to_do);
643
	foreach($to_do as $workingdir) { // Handle wildcards by foreaching.
644
		if(file_exists($workingdir)) {
645
			if(is_dir($workingdir)) {
646
				$dir = opendir($workingdir);
647
				while ($entry = readdir($dir)) {
648
					if (is_file("$workingdir/$entry") || ((!$follow_links) && is_link("$workingdir/$entry")))
649
						unlink("$workingdir/$entry");
650
					elseif (is_dir("$workingdir/$entry") && $entry!='.' && $entry!='..')
651
						rmdir_recursive("$workingdir/$entry");
652
				}
653
				closedir($dir);
654
				rmdir($workingdir);
655
			} elseif (is_file($workingdir)) {
656
				unlink($workingdir);
657
			}
658
               	}
659
	}
660
	return;
661
}
662

    
663
/*
664
 * call_pfsense_method(): Call a method exposed by the pfsense.com XMLRPC server.
665
 */
666
function call_pfsense_method($method, $params, $timeout = 0) {
667
	global $g, $config;
668

    
669
	$ip = gethostbyname($g['product_website']);
670
	if($ip == $g['product_website'])
671
		return false;
672

    
673
	$xmlrpc_base_url = isset($config['system']['altpkgrepo']['enable']) ? $config['system']['altpkgrepo']['xmlrpcbaseurl'] : $g['xmlrpcbaseurl'];
674
	$xmlrpc_path = $g['xmlrpcpath'];
675
	$msg = new XML_RPC_Message($method, array(XML_RPC_Encode($params)));
676
	$port = 0;
677
	$proxyurl = "";
678
	$proxyport = 0;
679
	$proxyuser = "";
680
	$proxypass = "";
681
	if (!empty($config['system']['proxyurl']))
682
		$proxyurl = $config['system']['proxyurl'];
683
	if (!empty($config['system']['proxyport']) && is_numeric($config['system']['proxyport']))
684
		$proxyport = $config['system']['proxyport'];
685
	if (!empty($config['system']['proxyuser']))
686
		$proxyuser = $config['system']['proxyuser'];
687
	if (!empty($config['system']['proxypass']))
688
		$proxypass = $config['system']['proxypass'];
689
	$cli = new XML_RPC_Client($xmlrpc_path, $xmlrpc_base_url, $port, $proxyurl, $proxyport, $proxyuser, $proxypass);
690
	// If the ALT PKG Repo has a username/password set, use it.
691
	if($config['system']['altpkgrepo']['username'] && 
692
	   $config['system']['altpkgrepo']['password']) {
693
		$username = $config['system']['altpkgrepo']['username'];
694
		$password = $config['system']['altpkgrepo']['password'];
695
		$cli->setCredentials($username, $password);
696
	}
697
	$resp = $cli->send($msg, $timeout);
698
	if(!is_object($resp)) {
699
		log_error(sprintf(gettext("XMLRPC communication error: %s"), $cli->errstr));
700
		return false;
701
	} elseif($resp->faultCode()) {
702
		log_error(sprintf(gettext('XMLRPC request failed with error %1$s: %2$s'), $resp->faultCode(), $resp->faultString()));
703
		return false;
704
	} else {
705
		return XML_RPC_Decode($resp->value());
706
	}
707
}
708

    
709
/*
710
 * check_firmware_version(): Check whether the current firmware installed is the most recently released.
711
 */
712
function check_firmware_version($tocheck = "all", $return_php = true) {
713
	global $g, $config;
714

    
715
	$ip = gethostbyname($g['product_website']);
716
	if($ip == $g['product_website'])
717
		return false;
718

    
719
	$rawparams = array("firmware" => array("version" => trim(file_get_contents('/etc/version'))),
720
		"kernel"   => array("version" => trim(file_get_contents('/etc/version_kernel'))),
721
		"base"     => array("version" => trim(file_get_contents('/etc/version_base'))),
722
		"platform" => trim(file_get_contents('/etc/platform')),
723
		"config_version" => $config['version']
724
		);
725
	if($tocheck == "all") {
726
		$params = $rawparams;
727
	} else {
728
		foreach($tocheck as $check) {
729
			$params['check'] = $rawparams['check'];
730
			$params['platform'] = $rawparams['platform'];
731
		}
732
	}
733
	if($config['system']['firmware']['branch'])
734
		$params['branch'] = $config['system']['firmware']['branch'];
735

    
736
	/* XXX: What is this method? */
737
	if(!($versions = call_pfsense_method('pfsense.get_firmware_version', $params))) {
738
		return false;
739
	} else {
740
		$versions["current"] = $params;
741
	}
742

    
743
	return $versions;
744
}
745

    
746
/*
747
 * host_firmware_version(): Return the versions used in this install
748
 */
749
function host_firmware_version($tocheck = "") {
750
        global $g, $config;
751

    
752
        return array(
753
		"firmware" => array("version" => trim(file_get_contents('/etc/version', " \n"))),
754
                "kernel"   => array("version" => trim(file_get_contents('/etc/version_kernel', " \n"))),
755
                "base"     => array("version" => trim(file_get_contents('/etc/version_base', " \n"))),
756
                "platform" => trim(file_get_contents('/etc/platform', " \n")),
757
                "config_version" => $config['version']
758
                );
759
}
760

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

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

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

    
794
	if($g['debug'])
795
		log_error(gettext("reload_interfaces_sync() is starting."));
796

    
797
	/* parse config.xml again */
798
	$config = parse_config(true);
799

    
800
	/* enable routing */
801
	system_routing_enable();
802
	if($g['debug'])
803
		log_error(gettext("Enabling system routing"));
804

    
805
	if($g['debug'])
806
		log_error(gettext("Cleaning up Interfaces"));
807

    
808
	/* set up interfaces */
809
	interfaces_configure();
810
}
811

    
812
/****f* pfsense-utils/reload_all
813
 * NAME
814
 *   reload_all - triggers a reload of all settings
815
 *   * INPUTS
816
 *   none
817
 * RESULT
818
 *   none
819
 ******/
820
function reload_all() {
821
	send_event("service reload all");
822
}
823

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

    
836
/****f* pfsense-utils/reload_all_sync
837
 * NAME
838
 *   reload_all - reload all settings
839
 *   * INPUTS
840
 *   none
841
 * RESULT
842
 *   none
843
 ******/
844
function reload_all_sync() {
845
	global $config, $g;
846

    
847
	$g['booting'] = false;
848

    
849
	/* parse config.xml again */
850
	$config = parse_config(true);
851

    
852
	/* set up our timezone */
853
	system_timezone_configure();
854

    
855
	/* set up our hostname */
856
	system_hostname_configure();
857

    
858
	/* make hosts file */
859
	system_hosts_generate();
860

    
861
	/* generate resolv.conf */
862
	system_resolvconf_generate();
863

    
864
	/* enable routing */
865
	system_routing_enable();
866

    
867
	/* set up interfaces */
868
	interfaces_configure();
869

    
870
	/* start dyndns service */
871
	services_dyndns_configure();
872

    
873
	/* configure cron service */
874
	configure_cron();
875

    
876
	/* start the NTP client */
877
	system_ntp_configure();
878

    
879
	/* sync pw database */
880
	conf_mount_rw();
881
	unlink_if_exists("/etc/spwd.db.tmp");
882
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
883
	conf_mount_ro();
884

    
885
	/* restart sshd */
886
	send_event("service restart sshd");
887

    
888
	/* restart webConfigurator if needed */
889
	send_event("service restart webgui");
890
}
891

    
892
function auto_login() {
893
	global $config;
894

    
895
	if(isset($config['system']['disableconsolemenu']))
896
		$status = false;
897
	else
898
		$status = true;
899

    
900
	$gettytab = file_get_contents("/etc/gettytab");
901
	$getty_split = split("\n", $gettytab);
902
	conf_mount_rw();
903
	$fd = false;
904
	$tries = 0;
905
	while (!$fd && $tries < 100) {
906
		$fd = fopen("/etc/gettytab", "w");
907
		$tries++;
908
		
909
	}
910
	if (!$fd) {
911
		conf_mount_ro();
912
		log_error(gettext("Enabling auto login was not possible."));
913
		return;
914
	}
915
	foreach($getty_split as $gs) {
916
		if(stristr($gs, ":ht:np:sp#115200") ) {
917
			if($status == true) {
918
				fwrite($fd, "	:ht:np:sp#115200:al=root:\n");
919
			} else {
920
				fwrite($fd, "	:ht:np:sp#115200:\n");
921
			}
922
		} else {
923
			fwrite($fd, "{$gs}\n");
924
		}
925
	}
926
	fclose($fd);
927
	conf_mount_ro();
928
}
929

    
930
function setup_serial_port() {
931
	global $g, $config;
932
	conf_mount_rw();
933
	/* serial console - write out /boot.config */
934
	if(file_exists("/boot.config"))
935
		$boot_config = file_get_contents("/boot.config");
936
	else
937
		$boot_config = "";
938

    
939
	if($g['platform'] <> "cdrom") {
940
		$boot_config_split = split("\n", $boot_config);
941
		$fd = fopen("/boot.config","w");
942
		if($fd) {
943
			foreach($boot_config_split as $bcs) {
944
				if(stristr($bcs, "-D")) {
945
					/* DONT WRITE OUT, WE'LL DO IT LATER */
946
				} else {
947
					if($bcs <> "")
948
						fwrite($fd, "{$bcs}\n");
949
				}
950
			}
951
			if(isset($config['system']['enableserial'])) {
952
				fwrite($fd, "-D");
953
			}
954
			fclose($fd);
955
		}
956
		/* serial console - write out /boot/loader.conf */
957
		$boot_config = file_get_contents("/boot/loader.conf");
958
		$boot_config_split = explode("\n", $boot_config);
959
		if(count($boot_config_split) > 0) {
960
			$new_boot_config = array();
961
			// Loop through and only add lines that are not empty, and which
962
			//  do not contain a console directive.
963
			foreach($boot_config_split as $bcs)
964
				if(!empty($bcs) && (stripos($bcs, "console") === false))
965
					$new_boot_config[] = $bcs;
966

    
967
			if(isset($config['system']['enableserial']))
968
				$new_boot_config[] = 'console="comconsole"';
969
			file_put_contents("/boot/loader.conf", implode("\n", $new_boot_config));
970
		}
971
	}
972
	$ttys = file_get_contents("/etc/ttys");
973
	$ttys_split = split("\n", $ttys);
974
	$fd = fopen("/etc/ttys", "w");
975
	foreach($ttys_split as $tty) {
976
		if(stristr($tty, "ttyd0") or stristr($tty, "ttyu0")) {
977
			if(isset($config['system']['enableserial'])) {
978
				fwrite($fd, "ttyu0	\"/usr/libexec/getty bootupcli\"	cons25	on	secure\n");
979
			} else {
980
				fwrite($fd, "ttyu0	\"/usr/libexec/getty bootupcli\"	cons25	off	secure\n");
981
			}
982
		} else {
983
			fwrite($fd, $tty . "\n");
984
		}
985
	}
986
	fclose($fd);
987
	auto_login();
988

    
989
	conf_mount_ro();
990
	return;
991
}
992

    
993
function print_value_list($list, $count = 10, $separator = ",") {
994
	$list = implode($separator, array_slice($list, 0, $count));
995
	if(count($list) < $count) {
996
		$list .= ".";
997
	} else {
998
		$list .= "...";
999
	}
1000
	return $list;
1001
}
1002

    
1003
/* DHCP enabled on any interfaces? */
1004
function is_dhcp_server_enabled() 
1005
{
1006
	global $config;
1007

    
1008
	$dhcpdenable = false;
1009
	
1010
	if ((!is_array($config['dhcpd'])) && (!is_array($config['dhcpdv6'])))
1011
		return false;
1012

    
1013
	$Iflist = get_configured_interface_list();
1014

    
1015
	if(is_array($config['dhcpd'])) {
1016
		foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf) {
1017
			if (isset($dhcpifconf['enable']) && isset($Iflist[$dhcpif])) {
1018
				$dhcpdenable = true;
1019
				break;
1020
			}
1021
		}
1022
	}
1023

    
1024
	if(is_array($config['dhcpdv6'])) {
1025
		foreach ($config['dhcpdv6'] as $dhcpv6if => $dhcpv6ifconf) {
1026
			if (isset($dhcpv6ifconf['enable']) && isset($Iflist[$dhcpv6if])) {
1027
				$dhcpdenable = true;
1028
				break;
1029
			}
1030
		}
1031
	}
1032

    
1033
	return $dhcpdenable;
1034
}
1035

    
1036
/* Any PPPoE servers enabled? */
1037
function is_pppoe_server_enabled() {
1038
	global $config;
1039

    
1040
	$pppoeenable = false;
1041

    
1042
	if (!is_array($config['pppoes']) || !is_array($config['pppoes']['pppoe']))
1043
		return false;
1044

    
1045
	foreach ($config['pppoes']['pppoe'] as $pppoes)
1046
		if ($pppoes['mode'] == 'server')
1047
			$pppoeenable = true;
1048

    
1049
	return $pppoeenable;
1050
}
1051

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

    
1072
/* Compute the total uptime from the ppp uptime log file in the conf directory */
1073

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

    
1089
//returns interface information
1090
function get_interface_info($ifdescr) {
1091
	global $config, $g;
1092

    
1093
	$ifinfo = array();
1094
	if (empty($config['interfaces'][$ifdescr]))
1095
		return;
1096
	$ifinfo['hwif'] = $config['interfaces'][$ifdescr]['if'];
1097
	$ifinfo['if'] = get_real_interface($ifdescr);
1098

    
1099
	$chkif = $ifinfo['if'];
1100
	$ifinfotmp = pfSense_get_interface_addresses($chkif);
1101
	$ifinfo['status'] = $ifinfotmp['status'];
1102
	if (empty($ifinfo['status']))
1103
                $ifinfo['status'] = "down";
1104
	$ifinfo['macaddr'] = $ifinfotmp['macaddr'];
1105
	$ifinfo['ipaddr'] = $ifinfotmp['ipaddr'];
1106
	$ifinfo['subnet'] = $ifinfotmp['subnet'];
1107
	$ifinfo['ipaddrv6'] = get_interface_ipv6($ifdescr);
1108
	$ifinfo['subnetv6'] = get_interface_subnetv6($ifdescr);
1109
	if (isset($ifinfotmp['link0']))
1110
		$link0 = "down";
1111
	$ifinfotmp = pfSense_get_interface_stats($chkif);
1112
        // $ifinfo['inpkts'] = $ifinfotmp['inpkts'];
1113
        // $ifinfo['outpkts'] = $ifinfotmp['outpkts'];
1114
        $ifinfo['inerrs'] = $ifinfotmp['inerrs'];
1115
        $ifinfo['outerrs'] = $ifinfotmp['outerrs'];
1116
        $ifinfo['collisions'] = $ifinfotmp['collisions'];
1117

    
1118
	/* Use pfctl for non wrapping 64 bit counters */
1119
	/* Pass */
1120
	exec("/sbin/pfctl -vvsI -i {$chkif}", $pfctlstats);
1121
	$pf_in4_pass = preg_split("/ +/ ", $pfctlstats[3]);
1122
	$pf_out4_pass = preg_split("/ +/", $pfctlstats[5]);
1123
	$pf_in6_pass = preg_split("/ +/ ", $pfctlstats[7]);
1124
	$pf_out6_pass = preg_split("/ +/", $pfctlstats[9]);
1125
	$in4_pass = $pf_in4_pass[5];
1126
	$out4_pass = $pf_out4_pass[5];
1127
	$in4_pass_packets = $pf_in4_pass[3];
1128
	$out4_pass_packets = $pf_out4_pass[3];
1129
	$in6_pass = $pf_in6_pass[5];
1130
	$out6_pass = $pf_out6_pass[5];
1131
	$in6_pass_packets = $pf_in6_pass[3];
1132
	$out6_pass_packets = $pf_out6_pass[3];
1133
	$ifinfo['inbytespass'] = $in4_pass + $in6_pass;
1134
	$ifinfo['outbytespass'] = $out4_pass + $out6_pass;
1135
	$ifinfo['inpktspass'] = $in4_pass_packets + $in6_pass_packets;
1136
	$ifinfo['outpktspass'] = $out4_pass_packets + $in6_pass_packets;
1137

    
1138
	/* Block */
1139
	$pf_in4_block = preg_split("/ +/", $pfctlstats[4]);
1140
	$pf_out4_block = preg_split("/ +/", $pfctlstats[6]);
1141
	$pf_in6_block = preg_split("/ +/", $pfctlstats[8]);
1142
	$pf_out6_block = preg_split("/ +/", $pfctlstats[10]);
1143
	$in4_block = $pf_in4_block[5];
1144
	$out4_block = $pf_out4_block[5];
1145
	$in4_block_packets = $pf_in4_block[3];
1146
	$out4_block_packets = $pf_out4_block[3];
1147
	$in6_block = $pf_in6_block[5];
1148
	$out6_block = $pf_out6_block[5];
1149
	$in6_block_packets = $pf_in6_block[3];
1150
	$out6_block_packets = $pf_out6_block[3];
1151
	$ifinfo['inbytesblock'] = $in4_block + $in6_block;
1152
	$ifinfo['outbytesblock'] = $out4_block + $out6_block;
1153
	$ifinfo['inpktsblock'] = $in4_block_packets + $in6_block_packets;
1154
	$ifinfo['outpktsblock'] = $out4_block_packets + $out6_block_packets;
1155

    
1156
	$ifinfo['inbytes'] = $in4_pass + $in6_pass;
1157
	$ifinfo['outbytes'] = $out4_pass + $out6_pass;
1158
	$ifinfo['inpkts'] = $in4_pass_packets + $in6_pass_packets;
1159
	$ifinfo['outpkts'] = $in4_pass_packets + $out6_pass_packets;
1160
		
1161
	$ifconfiginfo = "";
1162
	$link_type = $config['interfaces'][$ifdescr]['ipaddr'];
1163
	switch ($link_type) {
1164
	 /* DHCP? -> see if dhclient is up */
1165
	case "dhcp":
1166
	case "carpdev-dhcp":
1167
		/* see if dhclient is up */
1168
		if (find_dhclient_process($ifinfo['if']) <> "")
1169
			$ifinfo['dhcplink'] = "up";
1170
		else
1171
			$ifinfo['dhcplink'] = "down";
1172

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

    
1184
		break;
1185
	/* PPP interface? -> get uptime for this session and cumulative uptime from the persistant log file in conf */
1186
	case "ppp":
1187
		if ($ifinfo['status'] == "up")
1188
			$ifinfo['ppplink'] = "up";
1189
		else
1190
			$ifinfo['ppplink'] = "down" ;
1191

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

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

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

    
1271
		}
1272
		/* lookup the gateway */
1273
		if (interface_has_gateway($ifdescr)) {
1274
			$ifinfo['gateway'] = get_interface_gateway($ifdescr);
1275
			$ifinfo['gatewayv6'] = get_interface_gateway_v6($ifdescr);
1276
		}
1277
	}
1278

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

    
1295
	return $ifinfo;
1296
}
1297

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

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

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

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

    
1358
function pfsense_default_table_entries_size() {
1359
	$current = `pfctl -sm | grep table-entries | awk '{print $4};'`;
1360
	return $current;
1361
}
1362

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

    
1399
	if(trim($oldcontents) != trim($contents)) {
1400
		if($g['debug']) {
1401
			log_error(sprintf(gettext('DNSCACHE: Found old IP %1$s and new IP %2$s'), $oldcontents, $contents));
1402
		}
1403
		return ($oldcontents);
1404
	} else {
1405
		return false;
1406
	}
1407
}
1408

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

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

    
1437
function get_freebsd_version() {
1438
	$version = php_uname("r");
1439
	return $version[0];
1440
}
1441

    
1442
function download_file_with_progress_bar($url_file, $destination_file, $readbody = 'read_body', $connect_timeout=60, $timeout=0) {
1443
        global $ch, $fout, $file_size, $downloaded, $config;
1444
        $file_size  = 1;
1445
        $downloaded = 1;
1446
        /* open destination file */
1447
        $fout = fopen($destination_file, "wb");
1448

    
1449
        /*
1450
         *      Originally by Author: Keyvan Minoukadeh
1451
         *      Modified by Scott Ullrich to return Content-Length size
1452
         */
1453

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

    
1465
	if (!empty($config['system']['proxyurl'])) {
1466
		curl_setopt($ch, CURLOPT_PROXY, $config['system']['proxyurl']);
1467
		if (!empty($config['system']['proxyport']))
1468
			curl_setopt($ch, CURLOPT_PROXYPORT, $config['system']['proxyport']);
1469
		if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
1470
			@curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY | CURLAUTH_ANYSAFE);
1471
			curl_setopt($ch, CURLOPT_PROXYUSERPWD, "{$config['system']['proxyuser']}:{$config['system']['proxypass']}");
1472
		}
1473
	}
1474

    
1475
        @curl_exec($ch);
1476
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1477
        if($fout)
1478
                fclose($fout);
1479
        curl_close($ch);
1480
        return ($http_code == 200) ? true : $http_code;
1481
}
1482

    
1483
function read_header($ch, $string) {
1484
        global $file_size, $fout;
1485
        $length = strlen($string);
1486
        $regs = "";
1487
        ereg("(Content-Length:) (.*)", $string, $regs);
1488
        if($regs[2] <> "") {
1489
                $file_size = intval($regs[2]);
1490
        }
1491
        ob_flush();
1492
        return $length;
1493
}
1494

    
1495
function read_body($ch, $string) {
1496
        global $fout, $file_size, $downloaded, $sendto, $static_status, $static_output, $lastseen;
1497
		global $pkg_interface;
1498
        $length = strlen($string);
1499
        $downloaded += intval($length);
1500
        if($file_size > 0) {
1501
                $downloadProgress = round(100 * (1 - $downloaded / $file_size), 0);
1502
                $downloadProgress = 100 - $downloadProgress;
1503
        } else
1504
                $downloadProgress = 0;
1505
        if($lastseen <> $downloadProgress and $downloadProgress < 101) {
1506
                if($sendto == "status") {
1507
					if($pkg_interface == "console") {
1508
						if(substr($downloadProgress,2,1) == "0" || count($downloadProgress) < 2) {
1509
                        	$tostatus = $static_status . $downloadProgress . "%";
1510
                        	update_status($tostatus);
1511
						}
1512
					} else {
1513
                        $tostatus = $static_status . $downloadProgress . "%";
1514
                        update_status($tostatus);						
1515
					}
1516
                } else {
1517
					if($pkg_interface == "console") {
1518
						if(substr($downloadProgress,2,1) == "0" || count($downloadProgress) < 2) {
1519
                        	$tooutput = $static_output . $downloadProgress . "%";
1520
                        	update_output_window($tooutput);
1521
						}
1522
					} else {
1523
                        $tooutput = $static_output . $downloadProgress . "%";
1524
                        update_output_window($tooutput);
1525
					}
1526
                }
1527
                update_progress_bar($downloadProgress);
1528
                $lastseen = $downloadProgress;
1529
        }
1530
        if($fout)
1531
                fwrite($fout, $string);
1532
        ob_flush();
1533
        return $length;
1534
}
1535

    
1536
/*
1537
 *   update_output_window: update bottom textarea dynamically.
1538
 */
1539
function update_output_window($text) {
1540
        global $pkg_interface;
1541
        $log = ereg_replace("\n", "\\n", $text);
1542
        if($pkg_interface != "console") {
1543
                echo "\n<script language=\"JavaScript\">\nthis.document.forms[0].output.value = \"" . $log . "\";\n";
1544
				echo "this.document.forms[0].output.scrollTop = this.document.forms[0].output.scrollHeight;\n";	
1545
				echo "</script>";
1546
        }
1547
        /* ensure that contents are written out */
1548
        ob_flush();
1549
}
1550

    
1551
/*
1552
 *   update_output_window: update top textarea dynamically.
1553
 */
1554
function update_status($status) {
1555
        global $pkg_interface;
1556
        if($pkg_interface == "console") {
1557
                echo $status . "\n";
1558
        } else {
1559
                echo "\n<script type=\"text/javascript\">this.document.forms[0].status.value=\"" . $status . "\";</script>";
1560
        }
1561
        /* ensure that contents are written out */
1562
        ob_flush();
1563
}
1564

    
1565
/*
1566
 * update_progress_bar($percent): updates the javascript driven progress bar.
1567
 */
1568
function update_progress_bar($percent) {
1569
        global $pkg_interface;
1570
        if($percent > 100) $percent = 1;
1571
        if($pkg_interface <> "console") {
1572
                echo "\n<script type=\"text/javascript\" language=\"javascript\">";
1573
                echo "\ndocument.progressbar.style.width='" . $percent . "%';";
1574
                echo "\n</script>";
1575
        } else {
1576
                echo " {$percent}%";
1577
        }
1578
}
1579

    
1580
/* 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. */
1581
if(!function_exists("split")) {
1582
	function split($seperator, $haystack, $limit = null) {
1583
		return preg_split($seperator, $haystack, $limit);
1584
	}
1585
}
1586

    
1587
function update_alias_names_upon_change($section, $field, $new_alias_name, $origname) {
1588
	global $g, $config, $pconfig, $debug;
1589
	if(!$origname) 
1590
		return;
1591

    
1592
	$sectionref = &$config;
1593
	foreach($section as $sectionname) {
1594
		if(is_array($sectionref) && isset($sectionref[$sectionname]))
1595
			$sectionref = &$sectionref[$sectionname];
1596
		else
1597
			return;
1598
	}
1599

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

    
1603
	if(is_array($sectionref)) {
1604
		foreach($sectionref as $itemkey => $item) {
1605
			if($debug) fwrite($fd, "$itemkey\n");
1606

    
1607
			$fieldfound = true;
1608
			$fieldref = &$sectionref[$itemkey];
1609
			foreach($field as $fieldname) {
1610
				if(is_array($fieldref) && isset($fieldref[$fieldname]))
1611
					$fieldref = &$fieldref[$fieldname];
1612
				else {
1613
					$fieldfound = false;
1614
					break;
1615
				}
1616
			}
1617
			if($fieldfound && $fieldref == $origname) {
1618
				if($debug) fwrite($fd, "Setting old alias value $origname to $new_alias_name\n");
1619
				$fieldref = $new_alias_name;
1620
			}
1621
		}
1622
	}
1623

    
1624
	if($debug) fclose($fd);
1625

    
1626
}
1627

    
1628
function update_alias_url_data() {
1629
	global $config, $g;
1630

    
1631
	/* item is a url type */
1632
	$lockkey = lock('config');
1633
	if (is_array($config['aliases']['alias'])) {
1634
		foreach ($config['aliases']['alias'] as $x => $alias) {
1635
			if (empty($alias['aliasurl']))
1636
				continue;
1637

    
1638
			/* fetch down and add in */
1639
			$isfirst = 0;
1640
			$temp_filename = tempnam("{$g['tmp_path']}/", "alias_import");
1641
			unlink($temp_filename);
1642
			$fda = fopen("{$g['tmp_path']}/tmpfetch","w");
1643
			fwrite($fda, "/usr/bin/fetch -q -o \"{$temp_filename}/aliases\" \"" . $config['aliases']['alias'][$x]['aliasurl'] . "\"");
1644
			fclose($fda);
1645
			mwexec("/bin/mkdir -p {$temp_filename}");
1646
			mwexec("/usr/bin/fetch -q -o \"{$temp_filename}/aliases\" \"" . $config['aliases']['alias'][$x]['aliasurl'] . "\"");
1647
			/* if the item is tar gzipped then extract */
1648
			if(stristr($alias['aliasurl'], ".tgz"))
1649
				process_alias_tgz($temp_filename);
1650
			else if(stristr($alias['aliasurl'], ".zip"))
1651
				process_alias_unzip($temp_filename);
1652
			if(file_exists("{$temp_filename}/aliases")) {
1653
				$file_contents = file_get_contents("{$temp_filename}/aliases");
1654
				$file_contents = str_replace("#", "\n#", $file_contents);
1655
				$file_contents_split = split("\n", $file_contents);
1656
				foreach($file_contents_split as $fc) {
1657
					$tmp = trim($fc);
1658
					if(stristr($fc, "#")) {
1659
						$tmp_split = split("#", $tmp);
1660
						$tmp = trim($tmp_split[0]);
1661
					}
1662
					if(trim($tmp) <> "") {
1663
						if($isfirst == 1)
1664
							$address .= " ";
1665
						$address .= $tmp;
1666
						$isfirst = 1;
1667
					}
1668
				}
1669
				if($isfirst > 0) {
1670
					$config['aliases']['alias'][$x]['address'] = $address;
1671
					$updated = true;
1672
				}
1673
				mwexec("/bin/rm -rf {$temp_filename}");
1674
			}
1675
		}
1676
	}
1677
	if($updated)
1678
		write_config();
1679
	unlock($lockkey);
1680
}
1681

    
1682
function process_alias_unzip($temp_filename) {
1683
	if(!file_exists("/usr/local/bin/unzip"))
1684
		return;
1685
	mwexec("/bin/mv {$temp_filename}/aliases {$temp_filename}/aliases.zip");
1686
	mwexec("/usr/local/bin/unzip {$temp_filename}/aliases.tgz -d {$temp_filename}/aliases/");
1687
	unlink("{$temp_filename}/aliases.zip");
1688
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1689
	/* foreach through all extracted files and build up aliases file */
1690
	$fd = fopen("{$temp_filename}/aliases", "w");
1691
	foreach($files_to_process as $f2p) {
1692
		$file_contents = file_get_contents($f2p);
1693
		fwrite($fd, $file_contents);
1694
		unlink($f2p);
1695
	}
1696
	fclose($fd);
1697
}
1698

    
1699
function process_alias_tgz($temp_filename) {
1700
	if(!file_exists("/usr/bin/tar"))
1701
		return;
1702
	mwexec("/bin/mv {$temp_filename}/aliases {$temp_filename}/aliases.tgz");
1703
	mwexec("/usr/bin/tar xzf {$temp_filename}/aliases.tgz -C {$temp_filename}/aliases/");
1704
	unlink("{$temp_filename}/aliases.tgz");
1705
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1706
	/* foreach through all extracted files and build up aliases file */
1707
	$fd = fopen("{$temp_filename}/aliases", "w");
1708
	foreach($files_to_process as $f2p) {
1709
		$file_contents = file_get_contents($f2p);
1710
		fwrite($fd, $file_contents);
1711
		unlink($f2p);
1712
	}
1713
	fclose($fd);
1714
}
1715

    
1716
function version_compare_dates($a, $b) {
1717
	$a_time = strtotime($a);
1718
	$b_time = strtotime($b);
1719

    
1720
	if ((!$a_time) || (!$b_time)) {
1721
		return FALSE;
1722
	} else {
1723
		if ($a_time < $b_time)
1724
			return -1;
1725
		elseif ($$a_time == $b_time)
1726
			return 0;
1727
		else
1728
			return 1;
1729
	}
1730
}
1731
function version_get_string_value($a) {
1732
	$strs = array(
1733
		0 => "ALPHA-ALPHA",
1734
		2 => "ALPHA",
1735
		3 => "BETA",
1736
		4 => "B",
1737
		5 => "C",
1738
		6 => "D",
1739
		7 => "RC",
1740
		8 => "RELEASE"
1741
	);
1742
	$major = 0;
1743
	$minor = 0;
1744
	foreach ($strs as $num => $str) {
1745
		if (substr($a, 0, strlen($str)) == $str) {
1746
			$major = $num;
1747
			$n = substr($a, strlen($str));
1748
			if (is_numeric($n))
1749
				$minor = $n;
1750
			break;
1751
		}
1752
	}
1753
	return "{$major}.{$minor}";
1754
}
1755
function version_compare_string($a, $b) {
1756
	return version_compare_numeric(version_get_string_value($a), version_get_string_value($b));
1757
}
1758
function version_compare_numeric($a, $b) {
1759
	$a_arr = explode('.', rtrim($a, '.0'));
1760
	$b_arr = explode('.', rtrim($b, '.0'));
1761

    
1762
	foreach ($a_arr as $n => $val) {
1763
		if (array_key_exists($n, $b_arr)) {
1764
			// So far so good, both have values at this minor version level. Compare.
1765
			if ($val > $b_arr[$n])
1766
				return 1;
1767
			elseif ($val < $b_arr[$n])
1768
				return -1;
1769
		} else {
1770
			// a is greater, since b doesn't have any minor version here.
1771
			return 1;
1772
		}
1773
	}
1774
	if (count($b_arr) > count($a_arr)) {
1775
		// b is longer than a, so it must be greater.
1776
		return -1;
1777
	} else {
1778
		// Both a and b are of equal length and value.
1779
		return 0;
1780
	}
1781
}
1782
function pfs_version_compare($cur_time, $cur_text, $remote) {
1783
	// First try date compare
1784
	$v = version_compare_dates($cur_time, $remote);
1785
	if ($v === FALSE) {
1786
		// If that fails, try to compare by string
1787
		// Before anything else, simply test if the strings are equal
1788
		if (($cur_text == $remote) || ($cur_time == $remote))
1789
			return 0;
1790
		list($cur_num, $cur_str) = explode('-', $cur_text);
1791
		list($rem_num, $rem_str) = explode('-', $remote);
1792

    
1793
		// First try to compare the numeric parts of the version string.
1794
		$v = version_compare_numeric($cur_num, $rem_num);
1795

    
1796
		// If the numeric parts are the same, compare the string parts.
1797
		if ($v == 0)
1798
			return version_compare_string($cur_str, $rem_str);
1799
	}
1800
	return $v;
1801
}
1802
function process_alias_urltable($name, $url, $freq, $forceupdate=false) {
1803
	$urltable_prefix = "/var/db/aliastables/";
1804
	$urltable_filename = $urltable_prefix . $name . ".txt";
1805

    
1806
	// Make the aliases directory if it doesn't exist
1807
	if (!file_exists($urltable_prefix)) {
1808
		mkdir($urltable_prefix);
1809
	} elseif (!is_dir($urltable_prefix)) {
1810
		unlink($urltable_prefix);
1811
		mkdir($urltable_prefix);
1812
	}
1813

    
1814
	// If the file doesn't exist or is older than update_freq days, fetch a new copy.
1815
	if (!file_exists($urltable_filename)
1816
		|| ((time() - filemtime($urltable_filename)) > ($freq * 86400))
1817
		|| $forceupdate) {
1818

    
1819
		// Try to fetch the URL supplied
1820
		conf_mount_rw();
1821
		unlink_if_exists($urltable_filename . ".tmp");
1822
		// 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.
1823
		mwexec("/usr/bin/fetch -q -o " . escapeshellarg($urltable_filename . ".tmp") . " " . escapeshellarg($url));
1824
		// Remove comments. Might need some grep-fu to only allow lines that look like IPs/subnets
1825
		mwexec("/usr/bin/grep -v '^#' " . escapeshellarg($urltable_filename . ".tmp") . " > " . escapeshellarg($urltable_filename));
1826
		unlink_if_exists($urltable_filename . ".tmp");
1827
		conf_mount_ro();
1828
		if (filesize($urltable_filename)) {
1829
			return true;
1830
		} else {
1831
			// If it's unfetchable or an empty file, bail
1832
			return false;
1833
		}
1834
	} else {
1835
		// File exists, and it doesn't need updated.
1836
		return -1;
1837
	}
1838
}
1839
function get_real_slice_from_glabel($label) {
1840
	$label = escapeshellarg($label);
1841
	return trim(`/sbin/glabel list | /usr/bin/grep -B2 ufs/{$label} | /usr/bin/head -n 1 | /usr/bin/cut -f3 -d' '`);
1842
}
1843
function nanobsd_get_boot_slice() {
1844
	return trim(`/sbin/mount | /usr/bin/grep pfsense | /usr/bin/cut -d'/' -f4 | /usr/bin/cut -d' ' -f1`);
1845
}
1846
function nanobsd_get_boot_drive() {
1847
	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`);
1848
}
1849
function nanobsd_get_active_slice() {
1850
	$boot_drive = nanobsd_get_boot_drive();
1851
	$active = trim(`gpart show $boot_drive | grep '\[active\]' | awk '{print $3;}'`);
1852

    
1853
	return "{$boot_drive}s{$active}";
1854
}
1855
function nanobsd_get_size() {
1856
	return strtoupper(file_get_contents("/etc/nanosize.txt"));
1857
}
1858
function nanobsd_switch_boot_slice() {
1859
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
1860
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
1861
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
1862
	nanobsd_detect_slice_info();
1863

    
1864
	if ($BOOTFLASH == $ACTIVE_SLICE) {
1865
		$slice = $TOFLASH;
1866
	} else {
1867
		$slice = $BOOTFLASH;
1868
	}
1869

    
1870
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
1871
	ob_implicit_flush(1);
1872
	if(strstr($slice, "s2")) {
1873
		$ASLICE="2";
1874
		$AOLDSLICE="1";
1875
		$AGLABEL_SLICE="pfsense1";
1876
		$AUFS_ID="1";
1877
		$AOLD_UFS_ID="0";
1878
	} else {
1879
		$ASLICE="1";
1880
		$AOLDSLICE="2";
1881
		$AGLABEL_SLICE="pfsense0";
1882
		$AUFS_ID="0";
1883
		$AOLD_UFS_ID="1";
1884
	}
1885
	$ATOFLASH="{$BOOT_DRIVE}s{$ASLICE}";
1886
	$ACOMPLETE_PATH="{$BOOT_DRIVE}s{$ASLICE}a";
1887
	$ABOOTFLASH="{$BOOT_DRIVE}s{$AOLDSLICE}";
1888
	conf_mount_rw();
1889
	exec("sysctl kern.geom.debugflags=16");
1890
	exec("gpart set -a active -i {$ASLICE} {$BOOT_DRIVE}");
1891
	exec("/usr/sbin/boot0cfg -s {$ASLICE} -v /dev/{$BOOT_DRIVE}");
1892
	// We can't update these if they are mounted now.
1893
	if ($BOOTFLASH != $slice) {
1894
		exec("/sbin/tunefs -L ${AGLABEL_SLICE} /dev/$ACOMPLETE_PATH");
1895
		nanobsd_update_fstab($AGLABEL_SLICE, $ACOMPLETE_PATH, $AOLD_UFS_ID, $AUFS_ID);
1896
	}
1897
	exec("/sbin/sysctl kern.geom.debugflags=0");
1898
	conf_mount_ro();
1899
}
1900
function nanobsd_clone_slice() {
1901
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
1902
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
1903
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
1904
	nanobsd_detect_slice_info();
1905

    
1906
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
1907
	ob_implicit_flush(1);
1908
	exec("/sbin/sysctl kern.geom.debugflags=16");
1909
	exec("/bin/dd if=/dev/zero of=/dev/{$TOFLASH} bs=1m count=1");
1910
	exec("/bin/dd if=/dev/{$BOOTFLASH} of=/dev/{$TOFLASH} bs=64k");
1911
	exec("/sbin/tunefs -L {$GLABEL_SLICE} /dev/{$COMPLETE_PATH}");
1912
	$status = nanobsd_update_fstab($GLABEL_SLICE, $COMPLETE_PATH, $OLD_UFS_ID, $UFS_ID);
1913
	exec("/sbin/sysctl kern.geom.debugflags=0");
1914
	if($status) {
1915
		return false;
1916
	} else {
1917
		return true;
1918
	}
1919
}
1920
function nanobsd_update_fstab($gslice, $complete_path, $oldufs, $newufs) {
1921
	$tmppath = "/tmp/{$gslice}";
1922
	$fstabpath = "/tmp/{$gslice}/etc/fstab";
1923

    
1924
	exec("/bin/mkdir {$tmppath}");
1925
	exec("/sbin/fsck_ufs -y /dev/{$complete_path}");
1926
	exec("/sbin/mount /dev/ufs/{$gslice} {$tmppath}");
1927
	exec("/bin/cp /etc/fstab {$fstabpath}");
1928

    
1929
	if (!file_exists($fstabpath)) {
1930
		$fstab = <<<EOF
1931
/dev/ufs/{$gslice} / ufs ro,noatime 1 1
1932
/dev/ufs/cf /cf ufs ro,noatime 1 1
1933
EOF;
1934
		if (file_put_contents($fstabpath, $fstab))
1935
			$status = true;
1936
		else
1937
			$status = false;
1938
	} else {
1939
		$status = exec("sed -i \"\" \"s/pfsense{$oldufs}/pfsense{$newufs}/g\" {$fstabpath}");
1940
	}
1941
	exec("/sbin/umount {$tmppath}");
1942
	exec("/bin/rmdir {$tmppath}");
1943

    
1944
	return $status;
1945
}
1946
function nanobsd_detect_slice_info() {
1947
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
1948
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
1949
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
1950

    
1951
	$BOOT_DEVICE=nanobsd_get_boot_slice();
1952
	$REAL_BOOT_DEVICE=get_real_slice_from_glabel($BOOT_DEVICE);
1953
	$BOOT_DRIVE=nanobsd_get_boot_drive();
1954
	$ACTIVE_SLICE=nanobsd_get_active_slice();
1955

    
1956
	// Detect which slice is active and set information.
1957
	if(strstr($REAL_BOOT_DEVICE, "s1")) {
1958
		$SLICE="2";
1959
		$OLDSLICE="1";
1960
		$GLABEL_SLICE="pfsense1";
1961
		$UFS_ID="1";
1962
		$OLD_UFS_ID="0";
1963

    
1964
	} else {
1965
		$SLICE="1";
1966
		$OLDSLICE="2";
1967
		$GLABEL_SLICE="pfsense0";
1968
		$UFS_ID="0";
1969
		$OLD_UFS_ID="1";
1970
	}
1971
	$TOFLASH="{$BOOT_DRIVE}s{$SLICE}";
1972
	$COMPLETE_PATH="{$BOOT_DRIVE}s{$SLICE}a";
1973
	$COMPLETE_BOOT_PATH="{$BOOT_DRIVE}s{$OLDSLICE}";
1974
	$BOOTFLASH="{$BOOT_DRIVE}s{$OLDSLICE}";
1975
}
1976

    
1977
function nanobsd_friendly_slice_name($slicename) {
1978
	global $g;
1979
	return strtolower(str_ireplace('pfsense', $g['product_name'], $slicename));
1980
}
1981

    
1982
function get_include_contents($filename) {
1983
    if (is_file($filename)) {
1984
        ob_start();
1985
        include $filename;
1986
        $contents = ob_get_contents();
1987
        ob_end_clean();
1988
        return $contents;
1989
    }
1990
    return false;
1991
}
1992

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

    
2128
function get_country_name($country_code) {
2129
	if ($country_code != "ALL" && strlen($country_code) != 2)
2130
		return "";
2131

    
2132
	$country_names_xml = "/usr/local/share/mobile-broadband-provider-info/iso_3166-1_list_en.xml";
2133
	$country_names_contents = file_get_contents($country_names_xml);
2134
	$country_names = xml2array($country_names_contents);
2135

    
2136
	if($country_code == "ALL") {
2137
		$country_list = array();
2138
		foreach($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2139
			$country_list[] = array( "code" => $country['ISO_3166-1_Alpha-2_Code_element'],
2140
						 "name" => ucwords(strtolower($country['ISO_3166-1_Country_name'])) );
2141
		}
2142
		return $country_list;
2143
	}
2144

    
2145
	foreach ($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2146
		if ($country['ISO_3166-1_Alpha-2_Code_element'] == strtoupper($country_code)) {
2147
			return ucwords(strtolower($country['ISO_3166-1_Country_name']));
2148
		}
2149
	}
2150
	return "";
2151
}
2152

    
2153
/* sort by interface only, retain the original order of rules that apply to
2154
   the same interface */
2155
function filter_rules_sort() {
2156
	global $config;
2157

    
2158
	/* mark each rule with the sequence number (to retain the order while sorting) */
2159
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2160
		$config['filter']['rule'][$i]['seq'] = $i;
2161

    
2162
	usort($config['filter']['rule'], "filter_rules_compare");
2163

    
2164
	/* strip the sequence numbers again */
2165
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2166
		unset($config['filter']['rule'][$i]['seq']);
2167
}
2168
function filter_rules_compare($a, $b) {
2169
	if (isset($a['floating']) && isset($b['floating']))
2170
		return $a['seq'] - $b['seq'];
2171
	else if (isset($a['floating']))
2172
		return -1;
2173
	else if (isset($b['floating']))
2174
		return 1;
2175
	else if ($a['interface'] == $b['interface'])
2176
		return $a['seq'] - $b['seq'];
2177
	else
2178
		return compare_interface_friendly_names($a['interface'], $b['interface']);
2179
}
2180

    
2181
function generate_ipv6_from_mac($mac) {
2182
	$elements = explode(":", $mac);
2183
	if(count($elements) <> 6)
2184
		return false;
2185

    
2186
	$i = 0;
2187
	$ipv6 = "fe80::";
2188
	foreach($elements as $byte) {
2189
		if($i == 0) {
2190
			$hexadecimal =  substr($byte, 1, 2);
2191
			$bitmap = base_convert($hexadecimal, 16, 2);
2192
			$bitmap = str_pad($bitmap, 4, "0", STR_PAD_LEFT);
2193
			$bitmap = substr($bitmap, 0, 2) ."1". substr($bitmap, 3,4);
2194
			$byte = substr($byte, 0, 1) . base_convert($bitmap, 2, 16);
2195
		}
2196
		$ipv6 .= $byte;
2197
		if($i == 1) {
2198
			$ipv6 .= ":";
2199
		}
2200
		if($i == 3) {
2201
			$ipv6 .= ":";
2202
		}
2203
		if($i == 2) {
2204
			$ipv6 .= "ff:fe";
2205
		}
2206
		
2207
		$i++;
2208
	}	
2209
	return $ipv6;
2210
}
2211

    
2212
/****f* pfsense-utils/load_mac_manufacturer_table
2213
 * NAME
2214
 *   load_mac_manufacturer_table
2215
 * INPUTS
2216
 *   none
2217
 * RESULT
2218
 *   returns associative array with MAC-Manufacturer pairs
2219
 ******/
2220
function load_mac_manufacturer_table() {
2221
	/* load MAC-Manufacture data from the file */
2222
	$macs = false;
2223
	if (file_exists("/usr/local/share/nmap/nmap-mac-prefixes"))
2224
		$macs=file("/usr/local/share/nmap/nmap-mac-prefixes");
2225
	if ($macs){
2226
		foreach ($macs as $line){
2227
			if (preg_match('/([0-9A-Fa-f]{6}) (.*)$/', $line, $matches)){
2228
				/* store values like this $mac_man['000C29']='VMware' */
2229
				$mac_man["$matches[1]"]=$matches[2];
2230
			}
2231
		}
2232
 		return $mac_man;
2233
	} else
2234
		return -1;
2235

    
2236
}
2237

    
2238
/****f* pfsense-utils/is_ipaddr_configured
2239
 * NAME
2240
 *   is_ipaddr_configured
2241
 * INPUTS
2242
 *   IP Address to check.
2243
 * RESULT
2244
 *   returns true if the IP Address is
2245
 *   configured and present on this device.
2246
*/
2247
function is_ipaddr_configured($ipaddr) {
2248
	$interface_list_ips = get_configured_ip_addresses();
2249
	foreach($interface_list_ips as $ilips) {
2250
		if(strcasecmp($ipaddr, $ilips) == 0) 
2251
				return true;
2252
	}	
2253
}
2254

    
2255
/****f* pfsense-utils/pfSense_handle_custom_code
2256
 * NAME
2257
 *   pfSense_handle_custom_code
2258
 * INPUTS
2259
 *   directory name to process
2260
 * RESULT
2261
 *   globs the directory and includes the files
2262
 */
2263
function pfSense_handle_custom_code($src_dir) {
2264
	// Allow extending of the nat edit page and include custom input validation 
2265
	if(is_dir("$src_dir")) {
2266
		$cf = glob($src_dir . "/*.inc");
2267
		foreach($cf as $nf) {
2268
			if($nf == "." || $nf == "..") 
2269
				continue;
2270
			// Include the extra handler
2271
			include("$nf");
2272
		}
2273
	}
2274
}
2275

    
2276
?>
(35-35/62)