Project

General

Profile

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

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

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

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

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

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

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

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

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

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

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

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

    
188
	return;
189
}
190

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

    
206
	return false;
207
}
208

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

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

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

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

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

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

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

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

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

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

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

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

    
330
 */
331
function convert_ip_to_network_format($ip, $subnet) {
332
	$ipsplit = explode('.', $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_name) {
493
	global $config;
494
	$new_section = &$config[$section_name];
495
	/* generate configuration XML */
496
	$xmlconfig = dump_xml_config($new_section, $section_name);
497
	$xmlconfig = str_replace("<?xml version=\"1.0\"?>", "", $xmlconfig);
498
	return $xmlconfig;
499
}
500

    
501
/*
502
 *  restore_config_section($section_name, new_contents): restore a configuration section,
503
 *                                                  and write the configuration out
504
 *                                                  to disk/cf.
505
 */
506
function restore_config_section($section_name, $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

    
513
	$xml = parse_xml_config($g['tmp_path'] . "/tmpxml", null);
514
	if ($xml['pfsense']) {
515
		$xml = $xml['pfsense'];
516
	}
517
	else if ($xml['m0n0wall']) {
518
		$xml = $xml['m0n0wall'];
519
	}
520
	if ($xml[$section_name]) {
521
		$section_xml = $xml[$section_name];
522
	} else {
523
		$section_xml = -1;
524
	}
525

    
526
	@unlink($g['tmp_path'] . "/tmpxml");
527
	if ($section_xml === -1) {
528
		return false;
529
	}
530
	$config[$section_name] = &$section_xml;
531
	if(file_exists("{$g['tmp_path']}/config.cache"))
532
		unlink("{$g['tmp_path']}/config.cache");
533
	write_config(sprintf(gettext("Restored %s of config file (maybe from CARP partner)"), $section_name));
534
	disable_security_checks();
535
	conf_mount_ro();
536
	return true;
537
}
538

    
539
/*
540
 *  merge_config_section($section_name, new_contents):   restore a configuration section,
541
 *                                                  and write the configuration out
542
 *                                                  to disk/cf.  But preserve the prior
543
 * 													structure if needed
544
 */
545
function merge_config_section($section_name, $new_contents) {
546
	global $config;
547
	conf_mount_rw();
548
	$fname = get_tmp_filename();
549
	$fout = fopen($fname, "w");
550
	fwrite($fout, $new_contents);
551
	fclose($fout);
552
	$section_xml = parse_xml_config($fname, $section_name);
553
	$config[$section_name] = $section_xml;
554
	unlink($fname);
555
	write_config(sprintf(gettext("Restored %s of config file (maybe from CARP partner)"), $section_name));
556
	disable_security_checks();
557
	conf_mount_ro();
558
	return;
559
}
560

    
561
/*
562
 * http_post($server, $port, $url, $vars): does an http post to a web server
563
 *                                         posting the vars array.
564
 * written by nf@bigpond.net.au
565
 */
566
function http_post($server, $port, $url, $vars) {
567
	$user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)";
568
	$urlencoded = "";
569
	while (list($key,$value) = each($vars))
570
		$urlencoded.= urlencode($key) . "=" . urlencode($value) . "&";
571
	$urlencoded = substr($urlencoded,0,-1);
572
	$content_length = strlen($urlencoded);
573
	$headers = "POST $url HTTP/1.1
574
Accept: */*
575
Accept-Language: en-au
576
Content-Type: application/x-www-form-urlencoded
577
User-Agent: $user_agent
578
Host: $server
579
Connection: Keep-Alive
580
Cache-Control: no-cache
581
Content-Length: $content_length
582

    
583
";
584

    
585
	$errno = "";
586
	$errstr = "";
587
	$fp = fsockopen($server, $port, $errno, $errstr);
588
	if (!$fp) {
589
		return false;
590
	}
591

    
592
	fputs($fp, $headers);
593
	fputs($fp, $urlencoded);
594

    
595
	$ret = "";
596
	while (!feof($fp))
597
		$ret.= fgets($fp, 1024);
598
	fclose($fp);
599

    
600
	return $ret;
601
}
602

    
603
/*
604
 *  php_check_syntax($code_tocheck, $errormessage): checks $code_to_check for errors
605
 */
606
if (!function_exists('php_check_syntax')){
607
	global $g;
608
	function php_check_syntax($code_to_check, &$errormessage){
609
		return false;
610
		$fout = fopen("{$g['tmp_path']}/codetocheck.php","w");
611
		$code = $_POST['content'];
612
		$code = str_replace("<?php", "", $code);
613
		$code = str_replace("?>", "", $code);
614
		fwrite($fout, "<?php\n\n");
615
		fwrite($fout, $code_to_check);
616
		fwrite($fout, "\n\n?>\n");
617
		fclose($fout);
618
		$command = "/usr/local/bin/php -l {$g['tmp_path']}/codetocheck.php";
619
		$output = exec_command($command);
620
		if (stristr($output, "Errors parsing") == false) {
621
			echo "false\n";
622
			$errormessage = '';
623
			return(false);
624
		} else {
625
			$errormessage = $output;
626
			return(true);
627
		}
628
	}
629
}
630

    
631
/*
632
 *  php_check_filename_syntax($filename, $errormessage): checks the file $filename for errors
633
 */
634
if (!function_exists('php_check_syntax')){
635
	function php_check_syntax($code_to_check, &$errormessage){
636
		return false;
637
		$command = "/usr/local/bin/php -l " . $code_to_check;
638
		$output = exec_command($command);
639
		if (stristr($output, "Errors parsing") == false) {
640
			echo "false\n";
641
			$errormessage = '';
642
			return(false);
643
		} else {
644
			$errormessage = $output;
645
			return(true);
646
		}
647
	}
648
}
649

    
650
/*
651
 * rmdir_recursive($path,$follow_links=false)
652
 * Recursively remove a directory tree (rm -rf path)
653
 * This is for directories _only_
654
 */
655
function rmdir_recursive($path,$follow_links=false) {
656
	$to_do = glob($path);
657
	if(!is_array($to_do)) $to_do = array($to_do);
658
	foreach($to_do as $workingdir) { // Handle wildcards by foreaching.
659
		if(file_exists($workingdir)) {
660
			if(is_dir($workingdir)) {
661
				$dir = opendir($workingdir);
662
				while ($entry = readdir($dir)) {
663
					if (is_file("$workingdir/$entry") || ((!$follow_links) && is_link("$workingdir/$entry")))
664
						unlink("$workingdir/$entry");
665
					elseif (is_dir("$workingdir/$entry") && $entry!='.' && $entry!='..')
666
						rmdir_recursive("$workingdir/$entry");
667
				}
668
				closedir($dir);
669
				rmdir($workingdir);
670
			} elseif (is_file($workingdir)) {
671
				unlink($workingdir);
672
			}
673
               	}
674
	}
675
	return;
676
}
677

    
678
/*
679
 * call_pfsense_method(): Call a method exposed by the pfsense.com XMLRPC server.
680
 */
681
function call_pfsense_method($method, $params, $timeout = 0) {
682
	global $g, $config;
683

    
684
	$ip = gethostbyname($g['product_website']);
685
	if($ip == $g['product_website'])
686
		return false;
687

    
688
	$xmlrpc_base_url = isset($config['system']['altpkgrepo']['enable']) ? $config['system']['altpkgrepo']['xmlrpcbaseurl'] : $g['xmlrpcbaseurl'];
689
	$xmlrpc_path = $g['xmlrpcpath'];
690
	$msg = new XML_RPC_Message($method, array(XML_RPC_Encode($params)));
691
	$port = 0;
692
	$proxyurl = "";
693
	$proxyport = 0;
694
	$proxyuser = "";
695
	$proxypass = "";
696
	if (!empty($config['system']['proxyurl']))
697
		$proxyurl = $config['system']['proxyurl'];
698
	if (!empty($config['system']['proxyport']) && is_numeric($config['system']['proxyport']))
699
		$proxyport = $config['system']['proxyport'];
700
	if (!empty($config['system']['proxyuser']))
701
		$proxyuser = $config['system']['proxyuser'];
702
	if (!empty($config['system']['proxypass']))
703
		$proxypass = $config['system']['proxypass'];
704
	$cli = new XML_RPC_Client($xmlrpc_path, $xmlrpc_base_url, $port, $proxyurl, $proxyport, $proxyuser, $proxypass);
705
	// If the ALT PKG Repo has a username/password set, use it.
706
	if($config['system']['altpkgrepo']['username'] && 
707
	   $config['system']['altpkgrepo']['password']) {
708
		$username = $config['system']['altpkgrepo']['username'];
709
		$password = $config['system']['altpkgrepo']['password'];
710
		$cli->setCredentials($username, $password);
711
	}
712
	$resp = $cli->send($msg, $timeout);
713
	if(!is_object($resp)) {
714
		log_error(sprintf(gettext("XMLRPC communication error: %s"), $cli->errstr));
715
		return false;
716
	} elseif($resp->faultCode()) {
717
		log_error(sprintf(gettext('XMLRPC request failed with error %1$s: %2$s'), $resp->faultCode(), $resp->faultString()));
718
		return false;
719
	} else {
720
		return XML_RPC_Decode($resp->value());
721
	}
722
}
723

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

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

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

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

    
758
	return $versions;
759
}
760

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

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

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

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

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

    
809
	if($g['debug'])
810
		log_error(gettext("reload_interfaces_sync() is starting."));
811

    
812
	/* parse config.xml again */
813
	$config = parse_config(true);
814

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

    
820
	if($g['debug'])
821
		log_error(gettext("Cleaning up Interfaces"));
822

    
823
	/* set up interfaces */
824
	interfaces_configure();
825
}
826

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

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

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

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

    
864
	/* parse config.xml again */
865
	$config = parse_config(true);
866

    
867
	/* set up our timezone */
868
	system_timezone_configure();
869

    
870
	/* set up our hostname */
871
	system_hostname_configure();
872

    
873
	/* make hosts file */
874
	system_hosts_generate();
875

    
876
	/* generate resolv.conf */
877
	system_resolvconf_generate();
878

    
879
	/* enable routing */
880
	system_routing_enable();
881

    
882
	/* set up interfaces */
883
	interfaces_configure();
884

    
885
	/* start dyndns service */
886
	services_dyndns_configure();
887

    
888
	/* configure cron service */
889
	configure_cron();
890

    
891
	/* start the NTP client */
892
	system_ntp_configure();
893

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

    
900
	/* restart sshd */
901
	send_event("service restart sshd");
902

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

    
907
function auto_login() {
908
	global $config;
909

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

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

    
945
function setup_serial_port($when="save", $path="") {
946
	global $g, $config;
947
	conf_mount_rw();
948
	$prefix = "";
949
	if (($when == "upgrade") && (!empty($path)) && is_dir($path.'/boot/'))
950
		$prefix = "/tmp/{$path}";
951
	$boot_config_file = "{$path}/boot.config";
952
	$loader_conf_file = "{$path}/boot/loader.conf";
953
	/* serial console - write out /boot.config */
954
	if(file_exists($boot_config_file))
955
		$boot_config = file_get_contents($boot_config_file);
956
	else
957
		$boot_config = "";
958

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

    
990
			$serialspeed = (is_numeric($config['system']['serialspeed'])) ? $config['system']['serialspeed'] : "9600";
991
			if(isset($config['system']['enableserial'])) {
992
				$new_boot_config[] = 'boot_multicons="YES"';
993
				$new_boot_config[] = 'boot_serial="YES"';
994
				$new_boot_config[] = 'comconsole_speed="' . $serialspeed . '"';
995
				$new_boot_config[] = 'console="comconsole,vidconsole"';
996
			} elseif ($g['platform'] == "nanobsd") {
997
				$new_boot_config[] = 'comconsole_speed="' . $serialspeed . '"';
998
				$new_boot_config[] = 'console="comconsole"';
999
			}
1000
			file_put_contents($loader_conf_file, implode("\n", $new_boot_config) . "\n");
1001
		}
1002
	}
1003
	$ttys = file_get_contents("/etc/ttys");
1004
	$ttys_split = explode("\n", $ttys);
1005
	$fd = fopen("/etc/ttys", "w");
1006
	foreach($ttys_split as $tty) {
1007
		if(stristr($tty, "ttyd0") or stristr($tty, "ttyu0")) {
1008
			if(isset($config['system']['enableserial'])) {
1009
				fwrite($fd, "ttyu0	\"/usr/libexec/getty bootupcli\"	cons25	on	secure\n");
1010
			} else {
1011
				fwrite($fd, "ttyu0	\"/usr/libexec/getty bootupcli\"	cons25	off	secure\n");
1012
			}
1013
		} else {
1014
			fwrite($fd, $tty . "\n");
1015
		}
1016
	}
1017
	fclose($fd);
1018
	auto_login();
1019

    
1020
	conf_mount_ro();
1021
	return;
1022
}
1023

    
1024
function print_value_list($list, $count = 10, $separator = ",") {
1025
	$list = implode($separator, array_slice($list, 0, $count));
1026
	if(count($list) < $count) {
1027
		$list .= ".";
1028
	} else {
1029
		$list .= "...";
1030
	}
1031
	return $list;
1032
}
1033

    
1034
/* DHCP enabled on any interfaces? */
1035
function is_dhcp_server_enabled() 
1036
{
1037
	global $config;
1038

    
1039
	$dhcpdenable = false;
1040
	
1041
	if (!is_array($config['dhcpd']))
1042
		return false;
1043

    
1044
	$Iflist = get_configured_interface_list();
1045

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

    
1055
	return $dhcpdenable;
1056
}
1057

    
1058
/* DHCP enabled on any interfaces? */
1059
function is_dhcpv6_server_enabled() 
1060
{
1061
	global $config;
1062

    
1063
	$dhcpdenable = false;
1064
	
1065
	$Iflist = get_configured_interface_list();
1066

    
1067
	foreach($Iflist as $ifname) {
1068
		if($config['interfaces'][$ifname]['track6-interface'] <> "") {
1069
			return true;
1070
		}
1071
	}
1072

    
1073
	if (!is_array($config['dhcpdv6']))
1074
		return false;
1075

    
1076

    
1077
	if(is_array($config['dhcpdv6'])) {
1078
		foreach ($config['dhcpdv6'] as $dhcpv6if => $dhcpv6ifconf) {
1079
			if (isset($dhcpv6ifconf['enable']) && isset($Iflist[$dhcpv6if])) {
1080
				$dhcpdenable = true;
1081
				break;
1082
			}
1083
		}
1084
	}
1085

    
1086
	return $dhcpdenable;
1087
}
1088

    
1089
/* radvd enabled on any interfaces? */
1090
function is_radvd_enabled() {
1091
	global $config;
1092

    
1093
	if (!is_array($config['dhcpdv6']))
1094
		$config['dhcpdv6'] = array();
1095

    
1096
	$dhcpdv6cfg = $config['dhcpdv6'];
1097
	$Iflist = get_configured_interface_list();
1098

    
1099
	/* handle manually configured DHCP6 server settings first */
1100
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1101
		if(!isset($config['interfaces'][$dhcpv6if]['enable']))
1102
			continue;
1103

    
1104
		if(!isset($dhcpv6ifconf['ramode']))
1105
			$dhcpv6ifconf['ramode'] = $dhcpv6ifconf['mode'];
1106

    
1107
		if($dhcpv6ifconf['ramode'] == "disabled")
1108
			continue;
1109

    
1110
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1111
		if(!is_ipaddrv6($ifcfgipv6))
1112
			continue;
1113

    
1114
		return true;
1115
	}
1116

    
1117
	/* handle DHCP-PD prefixes and 6RD dynamic interfaces */
1118
	foreach ($Iflist as $if => $ifdescr) {
1119
		if(!isset($config['interfaces'][$if]['track6-interface']))
1120
			continue;
1121
		if(!isset($config['interfaces'][$if]['enable']))
1122
			continue;
1123

    
1124
		$ifcfgipv6 = get_interface_ipv6($if);
1125
		if(!is_ipaddrv6($ifcfgipv6))
1126
			continue;
1127

    
1128
		$ifcfgsnv6 = get_interface_subnetv6($if);
1129
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1130

    
1131
		if(!is_ipaddrv6($subnetv6))
1132
			continue;
1133

    
1134
		return true;
1135
	}
1136

    
1137
	return false;
1138
}
1139

    
1140
/* Any PPPoE servers enabled? */
1141
function is_pppoe_server_enabled() {
1142
	global $config;
1143

    
1144
	$pppoeenable = false;
1145

    
1146
	if (!is_array($config['pppoes']) || !is_array($config['pppoes']['pppoe']))
1147
		return false;
1148

    
1149
	foreach ($config['pppoes']['pppoe'] as $pppoes)
1150
		if ($pppoes['mode'] == 'server')
1151
			$pppoeenable = true;
1152

    
1153
	return $pppoeenable;
1154
}
1155

    
1156
function convert_seconds_to_hms($sec){
1157
	$min=$hrs=0;
1158
	if ($sec != 0){
1159
		$min = floor($sec/60);
1160
		$sec %= 60;
1161
	}
1162
	if ($min != 0){
1163
		$hrs = floor($min/60);
1164
		$min %= 60;
1165
	}
1166
	if ($sec < 10)
1167
		$sec = "0".$sec;
1168
	if ($min < 10)
1169
		$min = "0".$min;
1170
	if ($hrs < 10)
1171
		$hrs = "0".$hrs;
1172
	$result = $hrs.":".$min.":".$sec;
1173
	return $result;
1174
}
1175

    
1176
/* Compute the total uptime from the ppp uptime log file in the conf directory */
1177

    
1178
function get_ppp_uptime($port){
1179
	if (file_exists("/conf/{$port}.log")){
1180
    	$saved_time = file_get_contents("/conf/{$port}.log");
1181
    	$uptime_data = explode("\n",$saved_time);
1182
		$sec=0;
1183
		foreach($uptime_data as $upt) {
1184
			$sec += substr($upt, 1 + strpos($upt, " "));
1185
 		}
1186
		return convert_seconds_to_hms($sec);
1187
	} else {
1188
		$total_time = gettext("No history data found!");
1189
		return $total_time;
1190
	}
1191
}
1192

    
1193
//returns interface information
1194
function get_interface_info($ifdescr) {
1195
	global $config, $g;
1196

    
1197
	$ifinfo = array();
1198
	if (empty($config['interfaces'][$ifdescr]))
1199
		return;
1200
	$ifinfo['hwif'] = $config['interfaces'][$ifdescr]['if'];
1201
	$ifinfo['if'] = get_real_interface($ifdescr);
1202

    
1203
	$chkif = $ifinfo['if'];
1204
	$ifinfotmp = pfSense_get_interface_addresses($chkif);
1205
	$ifinfo['status'] = $ifinfotmp['status'];
1206
	if (empty($ifinfo['status']))
1207
                $ifinfo['status'] = "down";
1208
	$ifinfo['macaddr'] = $ifinfotmp['macaddr'];
1209
	$ifinfo['ipaddr'] = $ifinfotmp['ipaddr'];
1210
	$ifinfo['subnet'] = $ifinfotmp['subnet'];
1211
	$ifinfo['linklocal'] = get_interface_linklocal($ifdescr);
1212
	$ifinfo['ipaddrv6'] = get_interface_ipv6($ifdescr);
1213
	$ifinfo['subnetv6'] = get_interface_subnetv6($ifdescr);
1214
	if (isset($ifinfotmp['link0']))
1215
		$link0 = "down";
1216
	$ifinfotmp = pfSense_get_interface_stats($chkif);
1217
        // $ifinfo['inpkts'] = $ifinfotmp['inpkts'];
1218
        // $ifinfo['outpkts'] = $ifinfotmp['outpkts'];
1219
        $ifinfo['inerrs'] = $ifinfotmp['inerrs'];
1220
        $ifinfo['outerrs'] = $ifinfotmp['outerrs'];
1221
        $ifinfo['collisions'] = $ifinfotmp['collisions'];
1222

    
1223
	/* Use pfctl for non wrapping 64 bit counters */
1224
	/* Pass */
1225
	exec("/sbin/pfctl -vvsI -i {$chkif}", $pfctlstats);
1226
	$pf_in4_pass = preg_split("/ +/ ", $pfctlstats[3]);
1227
	$pf_out4_pass = preg_split("/ +/", $pfctlstats[5]);
1228
	$pf_in6_pass = preg_split("/ +/ ", $pfctlstats[7]);
1229
	$pf_out6_pass = preg_split("/ +/", $pfctlstats[9]);
1230
	$in4_pass = $pf_in4_pass[5];
1231
	$out4_pass = $pf_out4_pass[5];
1232
	$in4_pass_packets = $pf_in4_pass[3];
1233
	$out4_pass_packets = $pf_out4_pass[3];
1234
	$in6_pass = $pf_in6_pass[5];
1235
	$out6_pass = $pf_out6_pass[5];
1236
	$in6_pass_packets = $pf_in6_pass[3];
1237
	$out6_pass_packets = $pf_out6_pass[3];
1238
	$ifinfo['inbytespass'] = $in4_pass + $in6_pass;
1239
	$ifinfo['outbytespass'] = $out4_pass + $out6_pass;
1240
	$ifinfo['inpktspass'] = $in4_pass_packets + $in6_pass_packets;
1241
	$ifinfo['outpktspass'] = $out4_pass_packets + $in6_pass_packets;
1242

    
1243
	/* Block */
1244
	$pf_in4_block = preg_split("/ +/", $pfctlstats[4]);
1245
	$pf_out4_block = preg_split("/ +/", $pfctlstats[6]);
1246
	$pf_in6_block = preg_split("/ +/", $pfctlstats[8]);
1247
	$pf_out6_block = preg_split("/ +/", $pfctlstats[10]);
1248
	$in4_block = $pf_in4_block[5];
1249
	$out4_block = $pf_out4_block[5];
1250
	$in4_block_packets = $pf_in4_block[3];
1251
	$out4_block_packets = $pf_out4_block[3];
1252
	$in6_block = $pf_in6_block[5];
1253
	$out6_block = $pf_out6_block[5];
1254
	$in6_block_packets = $pf_in6_block[3];
1255
	$out6_block_packets = $pf_out6_block[3];
1256
	$ifinfo['inbytesblock'] = $in4_block + $in6_block;
1257
	$ifinfo['outbytesblock'] = $out4_block + $out6_block;
1258
	$ifinfo['inpktsblock'] = $in4_block_packets + $in6_block_packets;
1259
	$ifinfo['outpktsblock'] = $out4_block_packets + $out6_block_packets;
1260

    
1261
	$ifinfo['inbytes'] = $in4_pass + $in6_pass;
1262
	$ifinfo['outbytes'] = $out4_pass + $out6_pass;
1263
	$ifinfo['inpkts'] = $in4_pass_packets + $in6_pass_packets;
1264
	$ifinfo['outpkts'] = $in4_pass_packets + $out6_pass_packets;
1265
		
1266
	$ifconfiginfo = "";
1267
	$link_type = $config['interfaces'][$ifdescr]['ipaddr'];
1268
	switch ($link_type) {
1269
	 /* DHCP? -> see if dhclient is up */
1270
	case "dhcp":
1271
		/* see if dhclient is up */
1272
		if (find_dhclient_process($ifinfo['if']) <> "")
1273
			$ifinfo['dhcplink'] = "up";
1274
		else
1275
			$ifinfo['dhcplink'] = "down";
1276

    
1277
		break;
1278
	/* PPPoE/PPTP/L2TP interface? -> get status from virtual interface */
1279
	case "pppoe":
1280
	case "pptp":
1281
	case "l2tp":
1282
		if ($ifinfo['status'] == "up" && !isset($link0))
1283
			/* get PPPoE link status for dial on demand */
1284
			$ifinfo["{$link_type}link"] = "up";
1285
		else
1286
			$ifinfo["{$link_type}link"] = "down";
1287

    
1288
		break;
1289
	/* PPP interface? -> get uptime for this session and cumulative uptime from the persistant log file in conf */
1290
	case "ppp":
1291
		if ($ifinfo['status'] == "up")
1292
			$ifinfo['ppplink'] = "up";
1293
		else
1294
			$ifinfo['ppplink'] = "down" ;
1295

    
1296
		if (empty($ifinfo['status']))
1297
			$ifinfo['status'] = "down";
1298
			
1299
		if (is_array($config['ppps']['ppp']) && count($config['ppps']['ppp'])) {
1300
			foreach ($config['ppps']['ppp'] as $pppid => $ppp) {
1301
				if ($config['interfaces'][$ifdescr]['if'] == $ppp['if'])
1302
					break;
1303
			}
1304
		}
1305
		$dev = $ppp['ports'];
1306
		if ($config['interfaces'][$ifdescr]['if'] != $ppp['if'] || empty($dev))
1307
			break;
1308
		if (!file_exists($dev)) {
1309
			$ifinfo['nodevice'] = 1;
1310
			$ifinfo['pppinfo'] = $dev . " " . gettext("device not present! Is the modem attached to the system?");	
1311
		}
1312

    
1313
		$usbmodemoutput = array();
1314
		exec("usbconfig", $usbmodemoutput);
1315
		$mondev = "{$g['tmp_path']}/3gstats.{$ifdescr}";
1316
		if(file_exists($mondev)) {
1317
			$cellstats = file($mondev);
1318
			/* skip header */
1319
			$a_cellstats = explode(",", $cellstats[1]);
1320
			if(preg_match("/huawei/i", implode("\n", $usbmodemoutput))) {
1321
				$ifinfo['cell_rssi'] = huawei_rssi_to_string($a_cellstats[1]);
1322
				$ifinfo['cell_mode'] = huawei_mode_to_string($a_cellstats[2], $a_cellstats[3]);
1323
				$ifinfo['cell_simstate'] = huawei_simstate_to_string($a_cellstats[10]);
1324
				$ifinfo['cell_service'] = huawei_service_to_string(trim($a_cellstats[11]));
1325
			}
1326
			if(preg_match("/zte/i", implode("\n", $usbmodemoutput))) {
1327
				$ifinfo['cell_rssi'] = zte_rssi_to_string($a_cellstats[1]);
1328
				$ifinfo['cell_mode'] = zte_mode_to_string($a_cellstats[2], $a_cellstats[3]);
1329
				$ifinfo['cell_simstate'] = zte_simstate_to_string($a_cellstats[10]);
1330
				$ifinfo['cell_service'] = zte_service_to_string(trim($a_cellstats[11]));
1331
			}
1332
			$ifinfo['cell_upstream'] = $a_cellstats[4];
1333
			$ifinfo['cell_downstream'] = trim($a_cellstats[5]);
1334
			$ifinfo['cell_sent'] = $a_cellstats[6];
1335
			$ifinfo['cell_received'] = trim($a_cellstats[7]);
1336
			$ifinfo['cell_bwupstream'] = $a_cellstats[8];
1337
			$ifinfo['cell_bwdownstream'] = trim($a_cellstats[9]);
1338
		}
1339
		// Calculate cumulative uptime for PPP link. Useful for connections that have per minute/hour contracts so you don't go over!
1340
		if (isset($ppp['uptime']))
1341
			$ifinfo['ppp_uptime_accumulated'] = "(".get_ppp_uptime($ifinfo['if']).")";
1342
		break;
1343
	default:
1344
		break;
1345
	}
1346
	
1347
	if (file_exists("{$g['varrun_path']}/{$link_type}_{$ifdescr}.pid")) {
1348
		$sec = trim(`/usr/local/sbin/ppp-uptime.sh {$ifinfo['if']}`);
1349
		$ifinfo['ppp_uptime'] = convert_seconds_to_hms($sec);
1350
	}
1351
	
1352
	if ($ifinfo['status'] == "up") {
1353
		/* try to determine media with ifconfig */
1354
		unset($ifconfiginfo);
1355
		exec("/sbin/ifconfig " . $ifinfo['if'], $ifconfiginfo);
1356
		$wifconfiginfo = array();
1357
		if(is_interface_wireless($ifdescr)) {
1358
			exec("/sbin/ifconfig {$ifinfo['if']} list sta", $wifconfiginfo);
1359
			array_shift($wifconfiginfo);
1360
		}
1361
		$matches = "";
1362
		foreach ($ifconfiginfo as $ici) {
1363

    
1364
			/* don't list media/speed for wireless cards, as it always
1365
			   displays 2 Mbps even though clients can connect at 11 Mbps */
1366
			if (preg_match("/media: .*? \((.*?)\)/", $ici, $matches)) {
1367
				$ifinfo['media'] = $matches[1];
1368
			} else if (preg_match("/media: Ethernet (.*)/", $ici, $matches)) {
1369
				$ifinfo['media'] = $matches[1];
1370
			} else if (preg_match("/media: IEEE 802.11 Wireless Ethernet (.*)/", $ici, $matches)) {
1371
				$ifinfo['media'] = $matches[1];
1372
			}
1373

    
1374
			if (preg_match("/status: (.*)$/", $ici, $matches)) {
1375
				if ($matches[1] != "active")
1376
					$ifinfo['status'] = $matches[1];
1377
				if($ifinfo['status'] == gettext("running"))
1378
					$ifinfo['status'] = gettext("up");
1379
			}
1380
			if (preg_match("/channel (\S*)/", $ici, $matches)) {
1381
				$ifinfo['channel'] = $matches[1];
1382
			}
1383
			if (preg_match("/ssid (\".*?\"|\S*)/", $ici, $matches)) {
1384
				if ($matches[1][0] == '"')
1385
					$ifinfo['ssid'] = substr($matches[1], 1, -1);
1386
				else
1387
					$ifinfo['ssid'] = $matches[1];
1388
			}
1389
			if (preg_match("/laggproto (.*)$/", $ici, $matches)) {
1390
				$ifinfo['laggproto'] = $matches[1];
1391
			}
1392
			if (preg_match("/laggport: (.*)$/", $ici, $matches)) {
1393
				$ifinfo['laggport'][] = $matches[1];
1394
			}
1395
		}
1396
		foreach($wifconfiginfo as $ici) {
1397
			$elements = preg_split("/[ ]+/i", $ici);
1398
			if ($elements[0] != "") {
1399
				$ifinfo['bssid'] = $elements[0];
1400
			}
1401
			if ($elements[3] != "") {
1402
				$ifinfo['rate'] = $elements[3];
1403
			}
1404
			if ($elements[4] != "") {
1405
				$ifinfo['rssi'] = $elements[4];
1406
			}
1407

    
1408
		}
1409
		/* lookup the gateway */
1410
		if (interface_has_gateway($ifdescr)) {
1411
			$ifinfo['gateway'] = get_interface_gateway($ifdescr);
1412
			$ifinfo['gatewayv6'] = get_interface_gateway_v6($ifdescr);
1413
		}
1414
	}
1415

    
1416
	$bridge = "";
1417
	$bridge = link_interface_to_bridge($ifdescr);
1418
	if($bridge) {
1419
		$bridge_text = `/sbin/ifconfig {$bridge}`;
1420
		if(stristr($bridge_text, "blocking") <> false) {
1421
			$ifinfo['bridge'] = "<b><font color='red'>" . gettext("blocking") . "</font></b> - " . gettext("check for ethernet loops");
1422
			$ifinfo['bridgeint'] = $bridge;
1423
		} else if(stristr($bridge_text, "learning") <> false) {
1424
			$ifinfo['bridge'] = gettext("learning");
1425
			$ifinfo['bridgeint'] = $bridge;
1426
		} else if(stristr($bridge_text, "forwarding") <> false) {
1427
			$ifinfo['bridge'] = gettext("forwarding");
1428
			$ifinfo['bridgeint'] = $bridge;
1429
		}
1430
	}
1431

    
1432
	return $ifinfo;
1433
}
1434

    
1435
//returns cpu speed of processor. Good for determining capabilities of machine
1436
function get_cpu_speed() {
1437
	 return exec("sysctl hw.clockrate | awk '{ print $2 }'");
1438
}
1439

    
1440
function add_hostname_to_watch($hostname) {
1441
	if(!is_dir("/var/db/dnscache")) {
1442
		mkdir("/var/db/dnscache");
1443
	}
1444
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1445
		$domrecords = array();
1446
		$domips = array();
1447
		exec("host -t A $hostname", $domrecords, $rethost);
1448
		if($rethost == 0) {
1449
			foreach($domrecords as $domr) {
1450
				$doml = explode(" ", $domr);
1451
				$domip = $doml[3];
1452
				/* fill array with domain ip addresses */
1453
				if(is_ipaddr($domip)) {
1454
					$domips[] = $domip;
1455
				}
1456
			}
1457
		}
1458
		sort($domips);
1459
		$contents = "";
1460
		if(! empty($domips)) {
1461
			foreach($domips as $ip) {
1462
				$contents .= "$ip\n";
1463
			}
1464
		}
1465
		file_put_contents("/var/db/dnscache/$hostname", $contents);
1466
	}
1467
}
1468

    
1469
function is_fqdn($fqdn) {
1470
	$hostname = false;
1471
	if(preg_match("/[-A-Z0-9\.]+\.[-A-Z0-9\.]+/i", $fqdn)) {
1472
		$hostname = true;
1473
	}
1474
	if(preg_match("/\.\./", $fqdn)) {
1475
		$hostname = false;
1476
	}
1477
	if(preg_match("/^\./i", $fqdn)) { 
1478
		$hostname = false;
1479
	}
1480
	if(preg_match("/\//i", $fqdn)) {
1481
		$hostname = false;
1482
	}
1483
	return($hostname);
1484
}
1485

    
1486
function pfsense_default_state_size() {
1487
  /* get system memory amount */
1488
  $memory = get_memory();
1489
  $avail = $memory[0];
1490
  /* Be cautious and only allocate 10% of system memory to the state table */
1491
  $max_states = (int) ($avail/10)*1000;
1492
  return $max_states;
1493
}
1494

    
1495
function pfsense_default_tables_size() {
1496
	$current = `pfctl -sm | grep ^tables | awk '{print $4};'`;
1497
	return $current;
1498
}
1499

    
1500
function pfsense_default_table_entries_size() {
1501
	$current = `pfctl -sm | grep table-entries | awk '{print $4};'`;
1502
	return $current;
1503
}
1504

    
1505
/* Compare the current hostname DNS to the DNS cache we made
1506
 * if it has changed we return the old records
1507
 * if no change we return true */
1508
function compare_hostname_to_dnscache($hostname) {
1509
	if(!is_dir("/var/db/dnscache")) {
1510
		mkdir("/var/db/dnscache");
1511
	}
1512
	$hostname = trim($hostname);
1513
	if(is_readable("/var/db/dnscache/{$hostname}")) {
1514
		$oldcontents = file_get_contents("/var/db/dnscache/{$hostname}");
1515
	} else {
1516
		$oldcontents = "";
1517
	}
1518
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1519
		$domrecords = array();
1520
		$domips = array();
1521
		exec("host -t A $hostname", $domrecords, $rethost);
1522
		if($rethost == 0) {
1523
			foreach($domrecords as $domr) {
1524
				$doml = explode(" ", $domr);
1525
				$domip = $doml[3];
1526
				/* fill array with domain ip addresses */
1527
				if(is_ipaddr($domip)) {
1528
					$domips[] = $domip;
1529
				}
1530
			}
1531
		}
1532
		sort($domips);
1533
		$contents = "";
1534
		if(! empty($domips)) {
1535
			foreach($domips as $ip) {
1536
				$contents .= "$ip\n";
1537
			}
1538
		}
1539
	}
1540

    
1541
	if(trim($oldcontents) != trim($contents)) {
1542
		if($g['debug']) {
1543
			log_error(sprintf(gettext('DNSCACHE: Found old IP %1$s and new IP %2$s'), $oldcontents, $contents));
1544
		}
1545
		return ($oldcontents);
1546
	} else {
1547
		return false;
1548
	}
1549
}
1550

    
1551
/*
1552
 * load_crypto() - Load crypto modules if enabled in config.
1553
 */
1554
function load_crypto() {
1555
	global $config, $g;
1556
	$crypto_modules = array('glxsb', 'aesni');
1557

    
1558
	if (!in_array($config['system']['crypto_hardware'], $crypto_modules))
1559
		return false;
1560

    
1561
	$is_loaded = `/sbin/kldstat | /usr/bin/grep -c {$config['system']['crypto_hardware']}`;
1562
	if (!empty($config['system']['crypto_hardware']) && ($is_loaded == 0)) {
1563
		log_error("Loading {$config['system']['crypto_hardware']} cryptographic accelerator module.");
1564
		mwexec("/sbin/kldload {$config['system']['crypto_hardware']}");
1565
	}
1566
}
1567

    
1568
/****f* pfsense-utils/isvm
1569
 * NAME
1570
 *   isvm
1571
 * INPUTS
1572
 *	 none
1573
 * RESULT
1574
 *   returns true if machine is running under a virtual environment
1575
 ******/
1576
function isvm() {
1577
	$virtualenvs = array("vmware", "parallels", "qemu", "bochs", "plex86");
1578
	$bios_vendor = strtolower(`/bin/kenv | /usr/bin/awk -F= '/smbios.bios.vendor/ {print $2}'`);
1579
	if(in_array($bios_vendor, $virtualenvs)) 
1580
		return true;
1581
	else
1582
		return false;
1583
}
1584

    
1585
function get_freebsd_version() {
1586
	$version = php_uname("r");
1587
	return $version[0];
1588
}
1589

    
1590
function download_file_with_progress_bar($url_file, $destination_file, $readbody = 'read_body', $connect_timeout=60, $timeout=0) {
1591
        global $ch, $fout, $file_size, $downloaded, $config;
1592
        $file_size  = 1;
1593
        $downloaded = 1;
1594
        /* open destination file */
1595
        $fout = fopen($destination_file, "wb");
1596

    
1597
        /*
1598
         *      Originally by Author: Keyvan Minoukadeh
1599
         *      Modified by Scott Ullrich to return Content-Length size
1600
         */
1601

    
1602
        $ch = curl_init();
1603
        curl_setopt($ch, CURLOPT_URL, $url_file);
1604
        curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
1605
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1606
        /* Don't verify SSL peers since we don't have the certificates to do so. */
1607
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1608
        curl_setopt($ch, CURLOPT_WRITEFUNCTION, $readbody);
1609
        curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
1610
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connect_timeout);
1611
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1612

    
1613
	if (!empty($config['system']['proxyurl'])) {
1614
		curl_setopt($ch, CURLOPT_PROXY, $config['system']['proxyurl']);
1615
		if (!empty($config['system']['proxyport']))
1616
			curl_setopt($ch, CURLOPT_PROXYPORT, $config['system']['proxyport']);
1617
		if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
1618
			@curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY | CURLAUTH_ANYSAFE);
1619
			curl_setopt($ch, CURLOPT_PROXYUSERPWD, "{$config['system']['proxyuser']}:{$config['system']['proxypass']}");
1620
		}
1621
	}
1622

    
1623
        @curl_exec($ch);
1624
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1625
        if($fout)
1626
                fclose($fout);
1627
        curl_close($ch);
1628
        return ($http_code == 200) ? true : $http_code;
1629
}
1630

    
1631
function read_header($ch, $string) {
1632
        global $file_size, $fout;
1633
        $length = strlen($string);
1634
        $regs = "";
1635
        ereg("(Content-Length:) (.*)", $string, $regs);
1636
        if($regs[2] <> "") {
1637
                $file_size = intval($regs[2]);
1638
        }
1639
        ob_flush();
1640
        return $length;
1641
}
1642

    
1643
function read_body($ch, $string) {
1644
        global $fout, $file_size, $downloaded, $sendto, $static_status, $static_output, $lastseen;
1645
		global $pkg_interface;
1646
        $length = strlen($string);
1647
        $downloaded += intval($length);
1648
        if($file_size > 0) {
1649
                $downloadProgress = round(100 * (1 - $downloaded / $file_size), 0);
1650
                $downloadProgress = 100 - $downloadProgress;
1651
        } else
1652
                $downloadProgress = 0;
1653
        if($lastseen <> $downloadProgress and $downloadProgress < 101) {
1654
                if($sendto == "status") {
1655
					if($pkg_interface == "console") {
1656
						if(substr($downloadProgress,2,1) == "0" || count($downloadProgress) < 2) {
1657
                        	$tostatus = $static_status . $downloadProgress . "%";
1658
                        	update_status($tostatus);
1659
						}
1660
					} else {
1661
                        $tostatus = $static_status . $downloadProgress . "%";
1662
                        update_status($tostatus);						
1663
					}
1664
                } else {
1665
					if($pkg_interface == "console") {
1666
						if(substr($downloadProgress,2,1) == "0" || count($downloadProgress) < 2) {
1667
                        	$tooutput = $static_output . $downloadProgress . "%";
1668
                        	update_output_window($tooutput);
1669
						}
1670
					} else {
1671
                        $tooutput = $static_output . $downloadProgress . "%";
1672
                        update_output_window($tooutput);
1673
					}
1674
                }
1675
                update_progress_bar($downloadProgress);
1676
                $lastseen = $downloadProgress;
1677
        }
1678
        if($fout)
1679
                fwrite($fout, $string);
1680
        ob_flush();
1681
        return $length;
1682
}
1683

    
1684
/*
1685
 *   update_output_window: update bottom textarea dynamically.
1686
 */
1687
function update_output_window($text) {
1688
        global $pkg_interface;
1689
        $log = ereg_replace("\n", "\\n", $text);
1690
        if($pkg_interface != "console") {
1691
                echo "\n<script language=\"JavaScript\">\nthis.document.forms[0].output.value = \"" . $log . "\";\n";
1692
				echo "this.document.forms[0].output.scrollTop = this.document.forms[0].output.scrollHeight;\n";	
1693
				echo "</script>";
1694
        }
1695
        /* ensure that contents are written out */
1696
        ob_flush();
1697
}
1698

    
1699
/*
1700
 *   update_output_window: update top textarea dynamically.
1701
 */
1702
function update_status($status) {
1703
        global $pkg_interface;
1704
        if($pkg_interface == "console") {
1705
                echo $status . "\n";
1706
        } else {
1707
                echo "\n<script type=\"text/javascript\">this.document.forms[0].status.value=\"" . $status . "\";</script>";
1708
        }
1709
        /* ensure that contents are written out */
1710
        ob_flush();
1711
}
1712

    
1713
/*
1714
 * update_progress_bar($percent): updates the javascript driven progress bar.
1715
 */
1716
function update_progress_bar($percent) {
1717
        global $pkg_interface;
1718
        if($percent > 100) $percent = 1;
1719
        if($pkg_interface <> "console") {
1720
                echo "\n<script type=\"text/javascript\" language=\"javascript\">";
1721
                echo "\ndocument.progressbar.style.width='" . $percent . "%';";
1722
                echo "\n</script>";
1723
        } else {
1724
                echo " {$percent}%";
1725
        }
1726
}
1727

    
1728
/* 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. */
1729
if(!function_exists("split")) {
1730
	function split($seperator, $haystack, $limit = null) {
1731
		log_error("deprecated split() call with seperator '{$seperator}'");
1732
		return preg_split($seperator, $haystack, $limit);
1733
	}
1734
}
1735

    
1736
function update_alias_names_upon_change($section, $field, $new_alias_name, $origname) {
1737
	global $g, $config, $pconfig, $debug;
1738
	if(!$origname) 
1739
		return;
1740

    
1741
	$sectionref = &$config;
1742
	foreach($section as $sectionname) {
1743
		if(is_array($sectionref) && isset($sectionref[$sectionname]))
1744
			$sectionref = &$sectionref[$sectionname];
1745
		else
1746
			return;
1747
	}
1748

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

    
1752
	if(is_array($sectionref)) {
1753
		foreach($sectionref as $itemkey => $item) {
1754
			if($debug) fwrite($fd, "$itemkey\n");
1755

    
1756
			$fieldfound = true;
1757
			$fieldref = &$sectionref[$itemkey];
1758
			foreach($field as $fieldname) {
1759
				if(is_array($fieldref) && isset($fieldref[$fieldname]))
1760
					$fieldref = &$fieldref[$fieldname];
1761
				else {
1762
					$fieldfound = false;
1763
					break;
1764
				}
1765
			}
1766
			if($fieldfound && $fieldref == $origname) {
1767
				if($debug) fwrite($fd, "Setting old alias value $origname to $new_alias_name\n");
1768
				$fieldref = $new_alias_name;
1769
			}
1770
		}
1771
	}
1772

    
1773
	if($debug) fclose($fd);
1774

    
1775
}
1776

    
1777
function update_alias_url_data() {
1778
	global $config, $g;
1779

    
1780
	/* item is a url type */
1781
	$lockkey = lock('config');
1782
	if (is_array($config['aliases']['alias'])) {
1783
		foreach ($config['aliases']['alias'] as $x => $alias) {
1784
			if (empty($alias['aliasurl']))
1785
				continue;
1786

    
1787
			/* fetch down and add in */
1788
			$isfirst = 0;
1789
			$temp_filename = tempnam("{$g['tmp_path']}/", "alias_import");
1790
			unlink($temp_filename);
1791
			$fda = fopen("{$g['tmp_path']}/tmpfetch","w");
1792
			fwrite($fda, "/usr/bin/fetch -T 5 -q -o \"{$temp_filename}/aliases\" \"" . $config['aliases']['alias'][$x]['aliasurl'] . "\"");
1793
			fclose($fda);
1794
			mwexec("/bin/mkdir -p {$temp_filename}");
1795
			mwexec("/usr/bin/fetch -T 5 -q -o \"{$temp_filename}/aliases\" \"" . $config['aliases']['alias'][$x]['aliasurl'] . "\"");
1796
			/* if the item is tar gzipped then extract */
1797
			if(stristr($alias['aliasurl'], ".tgz"))
1798
				process_alias_tgz($temp_filename);
1799
			else if(stristr($alias['aliasurl'], ".zip"))
1800
				process_alias_unzip($temp_filename);
1801
			if(file_exists("{$temp_filename}/aliases")) {
1802
				$file_contents = file_get_contents("{$temp_filename}/aliases");
1803
				$file_contents = str_replace("#", "\n#", $file_contents);
1804
				$file_contents_split = explode("\n", $file_contents);
1805
				foreach($file_contents_split as $fc) {
1806
					$tmp = trim($fc);
1807
					if(stristr($fc, "#")) {
1808
						$tmp_split = explode("#", $tmp);
1809
						$tmp = trim($tmp_split[0]);
1810
					}
1811
					if(trim($tmp) <> "") {
1812
						if($isfirst == 1)
1813
							$address .= " ";
1814
						$address .= $tmp;
1815
						$isfirst = 1;
1816
					}
1817
				}
1818
				if($isfirst > 0) {
1819
					$config['aliases']['alias'][$x]['address'] = $address;
1820
					$updated = true;
1821
				}
1822
				mwexec("/bin/rm -rf {$temp_filename}");
1823
			}
1824
		}
1825
	}
1826
	if($updated)
1827
		write_config();
1828
	unlock($lockkey);
1829
}
1830

    
1831
function process_alias_unzip($temp_filename) {
1832
	if(!file_exists("/usr/local/bin/unzip"))
1833
		return;
1834
	mwexec("/bin/mv {$temp_filename}/aliases {$temp_filename}/aliases.zip");
1835
	mwexec("/usr/local/bin/unzip {$temp_filename}/aliases.tgz -d {$temp_filename}/aliases/");
1836
	unlink("{$temp_filename}/aliases.zip");
1837
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1838
	/* foreach through all extracted files and build up aliases file */
1839
	$fd = fopen("{$temp_filename}/aliases", "w");
1840
	foreach($files_to_process as $f2p) {
1841
		$file_contents = file_get_contents($f2p);
1842
		fwrite($fd, $file_contents);
1843
		unlink($f2p);
1844
	}
1845
	fclose($fd);
1846
}
1847

    
1848
function process_alias_tgz($temp_filename) {
1849
	if(!file_exists("/usr/bin/tar"))
1850
		return;
1851
	mwexec("/bin/mv {$temp_filename}/aliases {$temp_filename}/aliases.tgz");
1852
	mwexec("/usr/bin/tar xzf {$temp_filename}/aliases.tgz -C {$temp_filename}/aliases/");
1853
	unlink("{$temp_filename}/aliases.tgz");
1854
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1855
	/* foreach through all extracted files and build up aliases file */
1856
	$fd = fopen("{$temp_filename}/aliases", "w");
1857
	foreach($files_to_process as $f2p) {
1858
		$file_contents = file_get_contents($f2p);
1859
		fwrite($fd, $file_contents);
1860
		unlink($f2p);
1861
	}
1862
	fclose($fd);
1863
}
1864

    
1865
function version_compare_dates($a, $b) {
1866
	$a_time = strtotime($a);
1867
	$b_time = strtotime($b);
1868

    
1869
	if ((!$a_time) || (!$b_time)) {
1870
		return FALSE;
1871
	} else {
1872
		if ($a_time < $b_time)
1873
			return -1;
1874
		elseif ($$a_time == $b_time)
1875
			return 0;
1876
		else
1877
			return 1;
1878
	}
1879
}
1880
function version_get_string_value($a) {
1881
	$strs = array(
1882
		0 => "ALPHA-ALPHA",
1883
		2 => "ALPHA",
1884
		3 => "BETA",
1885
		4 => "B",
1886
		5 => "C",
1887
		6 => "D",
1888
		7 => "RC",
1889
		8 => "RELEASE"
1890
	);
1891
	$major = 0;
1892
	$minor = 0;
1893
	foreach ($strs as $num => $str) {
1894
		if (substr($a, 0, strlen($str)) == $str) {
1895
			$major = $num;
1896
			$n = substr($a, strlen($str));
1897
			if (is_numeric($n))
1898
				$minor = $n;
1899
			break;
1900
		}
1901
	}
1902
	return "{$major}.{$minor}";
1903
}
1904
function version_compare_string($a, $b) {
1905
	return version_compare_numeric(version_get_string_value($a), version_get_string_value($b));
1906
}
1907
function version_compare_numeric($a, $b) {
1908
	$a_arr = explode('.', rtrim($a, '.0'));
1909
	$b_arr = explode('.', rtrim($b, '.0'));
1910

    
1911
	foreach ($a_arr as $n => $val) {
1912
		if (array_key_exists($n, $b_arr)) {
1913
			// So far so good, both have values at this minor version level. Compare.
1914
			if ($val > $b_arr[$n])
1915
				return 1;
1916
			elseif ($val < $b_arr[$n])
1917
				return -1;
1918
		} else {
1919
			// a is greater, since b doesn't have any minor version here.
1920
			return 1;
1921
		}
1922
	}
1923
	if (count($b_arr) > count($a_arr)) {
1924
		// b is longer than a, so it must be greater.
1925
		return -1;
1926
	} else {
1927
		// Both a and b are of equal length and value.
1928
		return 0;
1929
	}
1930
}
1931
function pfs_version_compare($cur_time, $cur_text, $remote) {
1932
	// First try date compare
1933
	$v = version_compare_dates($cur_time, $remote);
1934
	if ($v === FALSE) {
1935
		// If that fails, try to compare by string
1936
		// Before anything else, simply test if the strings are equal
1937
		if (($cur_text == $remote) || ($cur_time == $remote))
1938
			return 0;
1939
		list($cur_num, $cur_str) = explode('-', $cur_text);
1940
		list($rem_num, $rem_str) = explode('-', $remote);
1941

    
1942
		// First try to compare the numeric parts of the version string.
1943
		$v = version_compare_numeric($cur_num, $rem_num);
1944

    
1945
		// If the numeric parts are the same, compare the string parts.
1946
		if ($v == 0)
1947
			return version_compare_string($cur_str, $rem_str);
1948
	}
1949
	return $v;
1950
}
1951
function process_alias_urltable($name, $url, $freq, $forceupdate=false) {
1952
	$urltable_prefix = "/var/db/aliastables/";
1953
	$urltable_filename = $urltable_prefix . $name . ".txt";
1954

    
1955
	// Make the aliases directory if it doesn't exist
1956
	if (!file_exists($urltable_prefix)) {
1957
		mkdir($urltable_prefix);
1958
	} elseif (!is_dir($urltable_prefix)) {
1959
		unlink($urltable_prefix);
1960
		mkdir($urltable_prefix);
1961
	}
1962

    
1963
	// If the file doesn't exist or is older than update_freq days, fetch a new copy.
1964
	if (!file_exists($urltable_filename)
1965
		|| ((time() - filemtime($urltable_filename)) > ($freq * 86400))
1966
		|| $forceupdate) {
1967

    
1968
		// Try to fetch the URL supplied
1969
		conf_mount_rw();
1970
		unlink_if_exists($urltable_filename . ".tmp");
1971
		// 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.
1972
		mwexec("/usr/bin/fetch -T 5 -q -o " . escapeshellarg($urltable_filename . ".tmp") . " " . escapeshellarg($url));
1973
		// Remove comments. Might need some grep-fu to only allow lines that look like IPs/subnets
1974
		if (file_exists($urltable_filename . ".tmp")) {
1975
			mwexec("/usr/bin/grep -v '^#' " . escapeshellarg($urltable_filename . ".tmp") . " > " . escapeshellarg($urltable_filename));
1976
			unlink_if_exists($urltable_filename . ".tmp");
1977
		} else
1978
			mwexec("/usr/bin/touch {$urltable_filename}");
1979
		conf_mount_ro();
1980
		return true;
1981
	} else {
1982
		// File exists, and it doesn't need updated.
1983
		return -1;
1984
	}
1985
}
1986
function get_real_slice_from_glabel($label) {
1987
	$label = escapeshellarg($label);
1988
	return trim(`/sbin/glabel list | /usr/bin/grep -B2 ufs/{$label} | /usr/bin/head -n 1 | /usr/bin/cut -f3 -d' '`);
1989
}
1990
function nanobsd_get_boot_slice() {
1991
	return trim(`/sbin/mount | /usr/bin/grep pfsense | /usr/bin/cut -d'/' -f4 | /usr/bin/cut -d' ' -f1`);
1992
}
1993
function nanobsd_get_boot_drive() {
1994
	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`);
1995
}
1996
function nanobsd_get_active_slice() {
1997
	$boot_drive = nanobsd_get_boot_drive();
1998
	$active = trim(`gpart show $boot_drive | grep '\[active\]' | awk '{print $3;}'`);
1999

    
2000
	return "{$boot_drive}s{$active}";
2001
}
2002
function nanobsd_get_size() {
2003
	return strtoupper(file_get_contents("/etc/nanosize.txt"));
2004
}
2005
function nanobsd_switch_boot_slice() {
2006
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2007
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2008
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2009
	nanobsd_detect_slice_info();
2010

    
2011
	if ($BOOTFLASH == $ACTIVE_SLICE) {
2012
		$slice = $TOFLASH;
2013
	} else {
2014
		$slice = $BOOTFLASH;
2015
	}
2016

    
2017
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
2018
	ob_implicit_flush(1);
2019
	if(strstr($slice, "s2")) {
2020
		$ASLICE="2";
2021
		$AOLDSLICE="1";
2022
		$AGLABEL_SLICE="pfsense1";
2023
		$AUFS_ID="1";
2024
		$AOLD_UFS_ID="0";
2025
	} else {
2026
		$ASLICE="1";
2027
		$AOLDSLICE="2";
2028
		$AGLABEL_SLICE="pfsense0";
2029
		$AUFS_ID="0";
2030
		$AOLD_UFS_ID="1";
2031
	}
2032
	$ATOFLASH="{$BOOT_DRIVE}s{$ASLICE}";
2033
	$ACOMPLETE_PATH="{$BOOT_DRIVE}s{$ASLICE}a";
2034
	$ABOOTFLASH="{$BOOT_DRIVE}s{$AOLDSLICE}";
2035
	conf_mount_rw();
2036
	exec("sysctl kern.geom.debugflags=16");
2037
	exec("gpart set -a active -i {$ASLICE} {$BOOT_DRIVE}");
2038
	exec("/usr/sbin/boot0cfg -s {$ASLICE} -v /dev/{$BOOT_DRIVE}");
2039
	// We can't update these if they are mounted now.
2040
	if ($BOOTFLASH != $slice) {
2041
		exec("/sbin/tunefs -L ${AGLABEL_SLICE} /dev/$ACOMPLETE_PATH");
2042
		nanobsd_update_fstab($AGLABEL_SLICE, $ACOMPLETE_PATH, $AOLD_UFS_ID, $AUFS_ID);
2043
	}
2044
	exec("/sbin/sysctl kern.geom.debugflags=0");
2045
	conf_mount_ro();
2046
}
2047
function nanobsd_clone_slice() {
2048
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2049
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2050
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2051
	nanobsd_detect_slice_info();
2052

    
2053
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
2054
	ob_implicit_flush(1);
2055
	exec("/sbin/sysctl kern.geom.debugflags=16");
2056
	exec("/bin/dd if=/dev/zero of=/dev/{$TOFLASH} bs=1m count=1");
2057
	exec("/bin/dd if=/dev/{$BOOTFLASH} of=/dev/{$TOFLASH} bs=64k");
2058
	exec("/sbin/tunefs -L {$GLABEL_SLICE} /dev/{$COMPLETE_PATH}");
2059
	$status = nanobsd_update_fstab($GLABEL_SLICE, $COMPLETE_PATH, $OLD_UFS_ID, $UFS_ID);
2060
	exec("/sbin/sysctl kern.geom.debugflags=0");
2061
	if($status) {
2062
		return false;
2063
	} else {
2064
		return true;
2065
	}
2066
}
2067
function nanobsd_update_fstab($gslice, $complete_path, $oldufs, $newufs) {
2068
	$tmppath = "/tmp/{$gslice}";
2069
	$fstabpath = "/tmp/{$gslice}/etc/fstab";
2070

    
2071
	exec("/bin/mkdir {$tmppath}");
2072
	exec("/sbin/fsck_ufs -y /dev/{$complete_path}");
2073
	exec("/sbin/mount /dev/ufs/{$gslice} {$tmppath}");
2074
	exec("/bin/cp /etc/fstab {$fstabpath}");
2075

    
2076
	if (!file_exists($fstabpath)) {
2077
		$fstab = <<<EOF
2078
/dev/ufs/{$gslice} / ufs ro,noatime 1 1
2079
/dev/ufs/cf /cf ufs ro,noatime 1 1
2080
EOF;
2081
		if (file_put_contents($fstabpath, $fstab))
2082
			$status = true;
2083
		else
2084
			$status = false;
2085
	} else {
2086
		$status = exec("sed -i \"\" \"s/pfsense{$oldufs}/pfsense{$newufs}/g\" {$fstabpath}");
2087
	}
2088
	exec("/sbin/umount {$tmppath}");
2089
	exec("/bin/rmdir {$tmppath}");
2090

    
2091
	return $status;
2092
}
2093
function nanobsd_detect_slice_info() {
2094
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2095
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2096
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2097

    
2098
	$BOOT_DEVICE=nanobsd_get_boot_slice();
2099
	$REAL_BOOT_DEVICE=get_real_slice_from_glabel($BOOT_DEVICE);
2100
	$BOOT_DRIVE=nanobsd_get_boot_drive();
2101
	$ACTIVE_SLICE=nanobsd_get_active_slice();
2102

    
2103
	// Detect which slice is active and set information.
2104
	if(strstr($REAL_BOOT_DEVICE, "s1")) {
2105
		$SLICE="2";
2106
		$OLDSLICE="1";
2107
		$GLABEL_SLICE="pfsense1";
2108
		$UFS_ID="1";
2109
		$OLD_UFS_ID="0";
2110

    
2111
	} else {
2112
		$SLICE="1";
2113
		$OLDSLICE="2";
2114
		$GLABEL_SLICE="pfsense0";
2115
		$UFS_ID="0";
2116
		$OLD_UFS_ID="1";
2117
	}
2118
	$TOFLASH="{$BOOT_DRIVE}s{$SLICE}";
2119
	$COMPLETE_PATH="{$BOOT_DRIVE}s{$SLICE}a";
2120
	$COMPLETE_BOOT_PATH="{$BOOT_DRIVE}s{$OLDSLICE}";
2121
	$BOOTFLASH="{$BOOT_DRIVE}s{$OLDSLICE}";
2122
}
2123

    
2124
function nanobsd_friendly_slice_name($slicename) {
2125
	global $g;
2126
	return strtolower(str_ireplace('pfsense', $g['product_name'], $slicename));
2127
}
2128

    
2129
function get_include_contents($filename) {
2130
    if (is_file($filename)) {
2131
        ob_start();
2132
        include $filename;
2133
        $contents = ob_get_contents();
2134
        ob_end_clean();
2135
        return $contents;
2136
    }
2137
    return false;
2138
}
2139

    
2140
/* This xml 2 array function is courtesy of the php.net comment section on xml_parse.
2141
 * it is roughly 4 times faster then our existing pfSense parser but due to the large
2142
 * size of the RRD xml dumps this is required.
2143
 * The reason we do not use it for pfSense is that it does not know about array fields
2144
 * which causes it to fail on array fields with single items. Possible Todo?
2145
 */
2146
function xml2array($contents, $get_attributes = 1, $priority = 'tag')
2147
{
2148
	if (!function_exists('xml_parser_create'))
2149
	{
2150
		return array ();
2151
	}
2152
	$parser = xml_parser_create('');
2153
	xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
2154
	xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
2155
	xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
2156
	xml_parse_into_struct($parser, trim($contents), $xml_values);
2157
	xml_parser_free($parser);
2158
	if (!$xml_values)
2159
		return; //Hmm...
2160
	$xml_array = array ();
2161
	$parents = array ();
2162
	$opened_tags = array ();
2163
	$arr = array ();
2164
	$current = & $xml_array;
2165
	$repeated_tag_index = array ();
2166
	foreach ($xml_values as $data)
2167
	{
2168
		unset ($attributes, $value);
2169
		extract($data);
2170
		$result = array ();
2171
		$attributes_data = array ();
2172
		if (isset ($value))
2173
		{
2174
			if ($priority == 'tag')
2175
				$result = $value;
2176
			else
2177
				$result['value'] = $value;
2178
		}
2179
		if (isset ($attributes) and $get_attributes)
2180
		{
2181
			foreach ($attributes as $attr => $val)
2182
			{
2183
				if ($priority == 'tag')
2184
					$attributes_data[$attr] = $val;
2185
				else
2186
					$result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
2187
			}
2188
		}
2189
		if ($type == "open")
2190
		{
2191
			$parent[$level -1] = & $current;
2192
			if (!is_array($current) or (!in_array($tag, array_keys($current))))
2193
			{
2194
				$current[$tag] = $result;
2195
				if ($attributes_data)
2196
					$current[$tag . '_attr'] = $attributes_data;
2197
				$repeated_tag_index[$tag . '_' . $level] = 1;
2198
				$current = & $current[$tag];
2199
			}
2200
			else
2201
			{
2202
				if (isset ($current[$tag][0]))
2203
				{
2204
					$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
2205
					$repeated_tag_index[$tag . '_' . $level]++;
2206
				}
2207
				else
2208
				{
2209
					$current[$tag] = array (
2210
						$current[$tag],
2211
						$result
2212
						);
2213
					$repeated_tag_index[$tag . '_' . $level] = 2;
2214
					if (isset ($current[$tag . '_attr']))
2215
					{
2216
						$current[$tag]['0_attr'] = $current[$tag . '_attr'];
2217
						unset ($current[$tag . '_attr']);
2218
					}
2219
				}
2220
				$last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
2221
				$current = & $current[$tag][$last_item_index];
2222
			}
2223
		}
2224
		elseif ($type == "complete")
2225
		{
2226
			if (!isset ($current[$tag]))
2227
			{
2228
				$current[$tag] = $result;
2229
				$repeated_tag_index[$tag . '_' . $level] = 1;
2230
				if ($priority == 'tag' and $attributes_data)
2231
					$current[$tag . '_attr'] = $attributes_data;
2232
			}
2233
			else
2234
			{
2235
				if (isset ($current[$tag][0]) and is_array($current[$tag]))
2236
				{
2237
					$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
2238
					if ($priority == 'tag' and $get_attributes and $attributes_data)
2239
					{
2240
						$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
2241
					}
2242
					$repeated_tag_index[$tag . '_' . $level]++;
2243
				}
2244
				else
2245
				{
2246
					$current[$tag] = array (
2247
						$current[$tag],
2248
						$result
2249
						);
2250
					$repeated_tag_index[$tag . '_' . $level] = 1;
2251
					if ($priority == 'tag' and $get_attributes)
2252
					{
2253
						if (isset ($current[$tag . '_attr']))
2254
						{
2255
							$current[$tag]['0_attr'] = $current[$tag . '_attr'];
2256
							unset ($current[$tag . '_attr']);
2257
						}
2258
						if ($attributes_data)
2259
						{
2260
							$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
2261
						}
2262
					}
2263
					$repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
2264
				}
2265
			}
2266
		}
2267
		elseif ($type == 'close')
2268
		{
2269
			$current = & $parent[$level -1];
2270
		}
2271
	}
2272
	return ($xml_array);
2273
}
2274

    
2275
function get_country_name($country_code) {
2276
	if ($country_code != "ALL" && strlen($country_code) != 2)
2277
		return "";
2278

    
2279
	$country_names_xml = "/usr/local/share/mobile-broadband-provider-info/iso_3166-1_list_en.xml";
2280
	$country_names_contents = file_get_contents($country_names_xml);
2281
	$country_names = xml2array($country_names_contents);
2282

    
2283
	if($country_code == "ALL") {
2284
		$country_list = array();
2285
		foreach($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2286
			$country_list[] = array( "code" => $country['ISO_3166-1_Alpha-2_Code_element'],
2287
						 "name" => ucwords(strtolower($country['ISO_3166-1_Country_name'])) );
2288
		}
2289
		return $country_list;
2290
	}
2291

    
2292
	foreach ($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2293
		if ($country['ISO_3166-1_Alpha-2_Code_element'] == strtoupper($country_code)) {
2294
			return ucwords(strtolower($country['ISO_3166-1_Country_name']));
2295
		}
2296
	}
2297
	return "";
2298
}
2299

    
2300
/* sort by interface only, retain the original order of rules that apply to
2301
   the same interface */
2302
function filter_rules_sort() {
2303
	global $config;
2304

    
2305
	/* mark each rule with the sequence number (to retain the order while sorting) */
2306
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2307
		$config['filter']['rule'][$i]['seq'] = $i;
2308

    
2309
	usort($config['filter']['rule'], "filter_rules_compare");
2310

    
2311
	/* strip the sequence numbers again */
2312
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2313
		unset($config['filter']['rule'][$i]['seq']);
2314
}
2315
function filter_rules_compare($a, $b) {
2316
	if (isset($a['floating']) && isset($b['floating']))
2317
		return $a['seq'] - $b['seq'];
2318
	else if (isset($a['floating']))
2319
		return -1;
2320
	else if (isset($b['floating']))
2321
		return 1;
2322
	else if ($a['interface'] == $b['interface'])
2323
		return $a['seq'] - $b['seq'];
2324
	else
2325
		return compare_interface_friendly_names($a['interface'], $b['interface']);
2326
}
2327

    
2328
function generate_ipv6_from_mac($mac) {
2329
	$elements = explode(":", $mac);
2330
	if(count($elements) <> 6)
2331
		return false;
2332

    
2333
	$i = 0;
2334
	$ipv6 = "fe80::";
2335
	foreach($elements as $byte) {
2336
		if($i == 0) {
2337
			$hexadecimal =  substr($byte, 1, 2);
2338
			$bitmap = base_convert($hexadecimal, 16, 2);
2339
			$bitmap = str_pad($bitmap, 4, "0", STR_PAD_LEFT);
2340
			$bitmap = substr($bitmap, 0, 2) ."1". substr($bitmap, 3,4);
2341
			$byte = substr($byte, 0, 1) . base_convert($bitmap, 2, 16);
2342
		}
2343
		$ipv6 .= $byte;
2344
		if($i == 1) {
2345
			$ipv6 .= ":";
2346
		}
2347
		if($i == 3) {
2348
			$ipv6 .= ":";
2349
		}
2350
		if($i == 2) {
2351
			$ipv6 .= "ff:fe";
2352
		}
2353
		
2354
		$i++;
2355
	}	
2356
	return $ipv6;
2357
}
2358

    
2359
/****f* pfsense-utils/load_mac_manufacturer_table
2360
 * NAME
2361
 *   load_mac_manufacturer_table
2362
 * INPUTS
2363
 *   none
2364
 * RESULT
2365
 *   returns associative array with MAC-Manufacturer pairs
2366
 ******/
2367
function load_mac_manufacturer_table() {
2368
	/* load MAC-Manufacture data from the file */
2369
	$macs = false;
2370
	if (file_exists("/usr/local/share/nmap/nmap-mac-prefixes"))
2371
		$macs=file("/usr/local/share/nmap/nmap-mac-prefixes");
2372
	if ($macs){
2373
		foreach ($macs as $line){
2374
			if (preg_match('/([0-9A-Fa-f]{6}) (.*)$/', $line, $matches)){
2375
				/* store values like this $mac_man['000C29']='VMware' */
2376
				$mac_man["$matches[1]"]=$matches[2];
2377
			}
2378
		}
2379
 		return $mac_man;
2380
	} else
2381
		return -1;
2382

    
2383
}
2384

    
2385
/****f* pfsense-utils/is_ipaddr_configured
2386
 * NAME
2387
 *   is_ipaddr_configured
2388
 * INPUTS
2389
 *   IP Address to check.
2390
 * RESULT
2391
 *   returns true if the IP Address is
2392
 *   configured and present on this device.
2393
*/
2394
function is_ipaddr_configured($ipaddr) {
2395
	$interface_list_ips = get_configured_ip_addresses();
2396
	foreach($interface_list_ips as $ilips) {
2397
		if(strcasecmp($ipaddr, $ilips) == 0) 
2398
				return true;
2399
	}	
2400
}
2401

    
2402
/****f* pfsense-utils/pfSense_handle_custom_code
2403
 * NAME
2404
 *   pfSense_handle_custom_code
2405
 * INPUTS
2406
 *   directory name to process
2407
 * RESULT
2408
 *   globs the directory and includes the files
2409
 */
2410
function pfSense_handle_custom_code($src_dir) {
2411
	// Allow extending of the nat edit page and include custom input validation 
2412
	if(is_dir("$src_dir")) {
2413
		$cf = glob($src_dir . "/*.inc");
2414
		foreach($cf as $nf) {
2415
			if($nf == "." || $nf == "..") 
2416
				continue;
2417
			// Include the extra handler
2418
			include("$nf");
2419
		}
2420
	}
2421
}
2422

    
2423
function set_language($lang = 'en_US', $encoding = "ISO8859-1") {
2424
	putenv("LANG={$lang}.{$encoding}");
2425
	setlocale(LC_ALL, "{$lang}.{$encoding}");
2426
	textdomain("pfSense");
2427
	bindtextdomain("pfSense","/usr/share/locale");
2428
	bind_textdomain_codeset("pfSense","{$lang}.{$encoding}");
2429
}
2430

    
2431
function get_locale_list() {
2432
	$locales = array(
2433
		"en_US" => gettext("English"),
2434
		"pt_BR" => gettext("Portuguese (Brazil)"),
2435
	);
2436
	asort($locales);
2437
	return $locales;
2438
}
2439

    
2440
function return_hex_ipv4($ipv4) {
2441
	if(!is_ipaddrv4($ipv4))
2442
		return(false);
2443
	
2444
	/* we need the hex form of the interface IPv4 address */
2445
	$ip4arr = explode(".", $ipv4);
2446
	$hexwanv4 = "";
2447
	foreach($ip4arr as $octet)
2448
		$hexwanv4 .= sprintf("%02x", $octet);
2449

    
2450
	return($hexwanv4);
2451
}
2452

    
2453
function convert_ipv6_to_128bit($ipv6) {
2454
	if(!is_ipaddrv6($ipv6))
2455
		return(false);
2456

    
2457
	$ip6arr = array();
2458
	$ip6prefix = Net_IPv6::uncompress($ipv6);
2459
	$ip6arr = explode(":", $ip6prefix);
2460
	/* binary presentation of the prefix for all 128 bits. */
2461
	$ip6prefixbin = "";
2462
	foreach($ip6arr as $element) {
2463
		$ip6prefixbin .= sprintf("%016b", hexdec($element));
2464
	}
2465
	return($ip6prefixbin);
2466
}
2467

    
2468
function convert_128bit_to_ipv6($ip6bin) {
2469
	if(strlen($ip6bin) <> 128)
2470
		return(false);
2471

    
2472
	$ip6arr = array();
2473
	$ip6binarr = array();
2474
	$ip6binarr = str_split($ip6bin, 16);
2475
	foreach($ip6binarr as $binpart)
2476
		$ip6arr[] = dechex(bindec($binpart));
2477
	$ip6addr = Net_IPv6::compress(implode(":", $ip6arr));
2478

    
2479
	return($ip6addr);
2480
}
2481

    
2482

    
2483
/* Returns the calculated bit length of the prefix delegation from the WAN interface */
2484
/* DHCP-PD is variable, calculate from the prefix-len on the WAN interface */
2485
/* 6rd is variable, calculate from 64 - (v6 prefixlen - (32 - v4 prefixlen)) */
2486
/* 6to4 is 16 bits, e.g. 65535 */
2487
function calculate_ipv6_delegation_length($if) {
2488
	global $config;
2489

    
2490
	if(!is_array($config['interfaces'][$if]))
2491
		return false;
2492

    
2493
	switch($config['interfaces'][$if]['ipaddrv6']) {
2494
		case "6to4":
2495
			$pdlen = 16;
2496
			break;
2497
		case "6rd":
2498
			$rd6cfg = $config['interfaces'][$if];
2499
			$rd6plen = explode("/", $rd6cfg['prefix-6rd']);
2500
			$pdlen = (64 - ($rd6plen[1] + (32 - $rd6cfg['prefix-6rd-v4plen'])));
2501
			break;
2502
		case "dhcp6":
2503
			$dhcp6cfg = $config['interfaces'][$if];
2504
			$pdlen = $dhcp6cfg['dhcp6-ia-pd-len'];
2505
			break;
2506
		default:
2507
			$pdlen = 0;
2508
			break;
2509
	}
2510
	return($pdlen);
2511
}
2512

    
2513
function huawei_rssi_to_string($rssi) {
2514
	$dbm = array();
2515
	$i = 0;
2516
	$dbstart = -51;
2517
	while($i < 31) {
2518
		$dbm[$i] = $dbstart - ($i * 2);
2519
		$i++;
2520
	}
2521
	$percent = round(($rssi / 31) * 100);
2522
	$string = "rssi:8 level:{$dbm[$rssi]}dBm percent:{$percent}%";
2523
	return $string;
2524
}
2525

    
2526
function huawei_mode_to_string($mode, $submode) {
2527
	$modes[0] = "None";
2528
	$modes[1] = "AMPS"; 
2529
	$modes[2] = "CDMA";
2530
	$modes[3] = "GSM/GPRS";
2531
	$modes[4] = "HDR";
2532
	$modes[5] = "WCDMA";
2533
	$modes[6] = "GPS"; 
2534

    
2535
	$submodes[0] = "No Service";
2536
	$submodes[1] = "GSM";
2537
	$submodes[2] = "GPRS";
2538
	$submodes[3] = "EDGE";
2539
	$submodes[4] = "WCDMA";
2540
	$submodes[5] = "HSDPA";
2541
	$submodes[6] = "HSUPA";
2542
	$submodes[7] = "HSDPA+HSUPA";
2543
	$submodes[8] = "TD-SCDMA";
2544
	$submodes[9] = "HSPA+";
2545
	$string = "{$modes[$mode]}, {$submodes[$submode]} Mode";
2546
	return $string;
2547
}
2548

    
2549
function huawei_service_to_string($state) {
2550
	$modes[0] = "No";
2551
	$modes[1] = "Restricted"; 
2552
	$modes[2] = "Valid";
2553
	$modes[3] = "Restricted Regional";
2554
	$modes[4] = "Powersaving";
2555
	$string = "{$modes[$state]} Service";
2556
	return $string;
2557
}
2558

    
2559
function huawei_simstate_to_string($state) {
2560
	$modes[0] = "Invalid SIM/locked";
2561
	$modes[1] = "Valid SIM"; 
2562
	$modes[2] = "Invalid SIM CS";
2563
	$modes[3] = "Invalid SIM PS";
2564
	$modes[4] = "Invalid SIM CS/PS";
2565
	$modes[255] = "Missing SIM";
2566
	$string = "{$modes[$state]} State";
2567
	return $string;
2568
}
2569

    
2570
function zte_rssi_to_string($rssi) {
2571
	return huawei_rssi_to_string($rssi);
2572
}
2573

    
2574
function zte_mode_to_string($mode, $submode) {
2575
	$modes[0] = "No Service";
2576
	$modes[1] = "Limited Service"; 
2577
	$modes[2] = "GPRS";
2578
	$modes[3] = "GSM";
2579
	$modes[4] = "UMTS";
2580
	$modes[5] = "EDGE";
2581
	$modes[6] = "HSDPA"; 
2582

    
2583
	$submodes[0] = "CS_ONLY";
2584
	$submodes[1] = "PS_ONLY";
2585
	$submodes[2] = "CS_PS";
2586
	$submodes[3] = "CAMPED";
2587
	$string = "{$modes[$mode]}, {$submodes[$submode]} Mode";
2588
	return $string;
2589
}
2590

    
2591
function zte_service_to_string($state) {
2592
	$modes[0] = "Initializing";
2593
	$modes[1] = "Network Lock error"; 
2594
	$modes[2] = "Network Locked";
2595
	$modes[3] = "Unlocked or correct MCC/MNC";
2596
	$string = "{$modes[$state]} Service";
2597
	return $string;
2598
}
2599

    
2600
function zte_simstate_to_string($state) {
2601
	$modes[0] = "No action";
2602
	$modes[1] = "Network lock"; 
2603
	$modes[2] = "(U)SIM card lock";
2604
	$modes[3] = "Network Lock and (U)SIM card Lock";
2605
	$string = "{$modes[$state]} State";
2606
	return $string;
2607
}
2608
?>
(38-38/66)