Project

General

Profile

Download (74.3 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
               "100.64.0.0/10",
119
               "172.16.0.0/12",
120
               "192.168.0.0/16",
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") && ($g['platform'] != "nanobsd")) {
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
	}
977
	if($g['platform'] != "cdrom") {
978
		/* serial console - write out /boot/loader.conf */
979
		if ($when == "upgrade")
980
			system("echo \"Reading {$loader_conf_file}...\" >> /conf/upgrade_log.txt");
981
		$boot_config = file_get_contents($loader_conf_file);
982
		$boot_config_split = explode("\n", $boot_config);
983
		if(count($boot_config_split) > 0) {
984
			$new_boot_config = array();
985
			// Loop through and only add lines that are not empty, and which
986
			//  do not contain a console directive.
987
			foreach($boot_config_split as $bcs)
988
				if(!empty($bcs)
989
					&& (stripos($bcs, "console") === false)
990
					&& (stripos($bcs, "boot_multicons") === false)
991
					&& (stripos($bcs, "boot_serial") === false))
992
					$new_boot_config[] = $bcs;
993

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

    
1024
	conf_mount_ro();
1025
	return;
1026
}
1027

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

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

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

    
1048
	$Iflist = get_configured_interface_list();
1049

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

    
1059
	return $dhcpdenable;
1060
}
1061

    
1062
/* DHCP enabled on any interfaces? */
1063
function is_dhcpv6_server_enabled() 
1064
{
1065
	global $config;
1066

    
1067
	$dhcpdenable = false;
1068
	
1069
	$Iflist = get_configured_interface_list();
1070

    
1071
	foreach($Iflist as $ifname) {
1072
		if($config['interfaces'][$ifname]['track6-interface'] <> "") {
1073
			return true;
1074
		}
1075
	}
1076

    
1077
	if (!is_array($config['dhcpdv6']))
1078
		return false;
1079

    
1080

    
1081
	if(is_array($config['dhcpdv6'])) {
1082
		foreach ($config['dhcpdv6'] as $dhcpv6if => $dhcpv6ifconf) {
1083
			if (isset($dhcpv6ifconf['enable']) && isset($Iflist[$dhcpv6if])) {
1084
				$dhcpdenable = true;
1085
				break;
1086
			}
1087
		}
1088
	}
1089

    
1090
	return $dhcpdenable;
1091
}
1092

    
1093
/* radvd enabled on any interfaces? */
1094
function is_radvd_enabled() {
1095
	global $config;
1096

    
1097
	if (!is_array($config['dhcpdv6']))
1098
		$config['dhcpdv6'] = array();
1099

    
1100
	$dhcpdv6cfg = $config['dhcpdv6'];
1101
	$Iflist = get_configured_interface_list();
1102

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

    
1108
		if(!isset($dhcpv6ifconf['ramode']))
1109
			$dhcpv6ifconf['ramode'] = $dhcpv6ifconf['mode'];
1110

    
1111
		if($dhcpv6ifconf['ramode'] == "disabled")
1112
			continue;
1113

    
1114
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1115
		if(!is_ipaddrv6($ifcfgipv6))
1116
			continue;
1117

    
1118
		return true;
1119
	}
1120

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

    
1128
		$ifcfgipv6 = get_interface_ipv6($if);
1129
		if(!is_ipaddrv6($ifcfgipv6))
1130
			continue;
1131

    
1132
		$ifcfgsnv6 = get_interface_subnetv6($if);
1133
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1134

    
1135
		if(!is_ipaddrv6($subnetv6))
1136
			continue;
1137

    
1138
		return true;
1139
	}
1140

    
1141
	return false;
1142
}
1143

    
1144
/* Any PPPoE servers enabled? */
1145
function is_pppoe_server_enabled() {
1146
	global $config;
1147

    
1148
	$pppoeenable = false;
1149

    
1150
	if (!is_array($config['pppoes']) || !is_array($config['pppoes']['pppoe']))
1151
		return false;
1152

    
1153
	foreach ($config['pppoes']['pppoe'] as $pppoes)
1154
		if ($pppoes['mode'] == 'server')
1155
			$pppoeenable = true;
1156

    
1157
	return $pppoeenable;
1158
}
1159

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

    
1180
/* Compute the total uptime from the ppp uptime log file in the conf directory */
1181

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

    
1197
//returns interface information
1198
function get_interface_info($ifdescr) {
1199
	global $config, $g;
1200

    
1201
	$ifinfo = array();
1202
	if (empty($config['interfaces'][$ifdescr]))
1203
		return;
1204
	$ifinfo['hwif'] = $config['interfaces'][$ifdescr]['if'];
1205
	$ifinfo['if'] = get_real_interface($ifdescr);
1206

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

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

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

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

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

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

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

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

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

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

    
1412
		}
1413
		/* lookup the gateway */
1414
		if (interface_has_gateway($ifdescr)) {
1415
			$ifinfo['gateway'] = get_interface_gateway($ifdescr);
1416
			$ifinfo['gatewayv6'] = get_interface_gateway_v6($ifdescr);
1417
		}
1418
	}
1419

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

    
1436
	return $ifinfo;
1437
}
1438

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

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

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

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

    
1499
function pfsense_default_tables_size() {
1500
	$current = `pfctl -sm | grep ^tables | awk '{print $4};'`;
1501
	return $current;
1502
}
1503

    
1504
function pfsense_default_table_entries_size() {
1505
	$current = `pfctl -sm | grep table-entries | awk '{print $4};'`;
1506
	return $current;
1507
}
1508

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

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

    
1555
/*
1556
 * load_crypto() - Load crypto modules if enabled in config.
1557
 */
1558
function load_crypto() {
1559
	global $config, $g;
1560
	$crypto_modules = array('glxsb', 'aesni');
1561

    
1562
	if (!in_array($config['system']['crypto_hardware'], $crypto_modules))
1563
		return false;
1564

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

    
1572
/*
1573
 * load_thermal_hardware() - Load temperature monitor kernel module
1574
 */
1575
function load_thermal_hardware() {
1576
	global $config, $g;
1577
	$thermal_hardware_modules = array('coretemp', 'amdtemp');
1578

    
1579
	if (!in_array($config['system']['thermal_hardware'], $thermal_hardware_modules))
1580
		return false;
1581

    
1582
	$is_loaded = `/sbin/kldstat | /usr/bin/grep -c {$config['system']['thermal_hardware']}`;
1583
	if (!empty($config['system']['thermal_hardware']) && ($is_loaded == 0)) {
1584
		log_error("Loading {$config['system']['thermal_hardware']} thermal monitor module.");
1585
		mwexec("/sbin/kldload {$config['system']['thermal_hardware']}");
1586
	}
1587
}
1588

    
1589
/****f* pfsense-utils/isvm
1590
 * NAME
1591
 *   isvm
1592
 * INPUTS
1593
 *	 none
1594
 * RESULT
1595
 *   returns true if machine is running under a virtual environment
1596
 ******/
1597
function isvm() {
1598
	$virtualenvs = array("vmware", "parallels", "qemu", "bochs", "plex86");
1599
	$bios_vendor = strtolower(`/bin/kenv | /usr/bin/awk -F= '/smbios.bios.vendor/ {print $2}'`);
1600
	if(in_array($bios_vendor, $virtualenvs)) 
1601
		return true;
1602
	else
1603
		return false;
1604
}
1605

    
1606
function get_freebsd_version() {
1607
	$version = php_uname("r");
1608
	return $version[0];
1609
}
1610

    
1611
function download_file_with_progress_bar($url_file, $destination_file, $readbody = 'read_body', $connect_timeout=60, $timeout=0) {
1612
        global $ch, $fout, $file_size, $downloaded, $config;
1613
        $file_size  = 1;
1614
        $downloaded = 1;
1615
        /* open destination file */
1616
        $fout = fopen($destination_file, "wb");
1617

    
1618
        /*
1619
         *      Originally by Author: Keyvan Minoukadeh
1620
         *      Modified by Scott Ullrich to return Content-Length size
1621
         */
1622

    
1623
        $ch = curl_init();
1624
        curl_setopt($ch, CURLOPT_URL, $url_file);
1625
        curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
1626
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1627
        /* Don't verify SSL peers since we don't have the certificates to do so. */
1628
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1629
        curl_setopt($ch, CURLOPT_WRITEFUNCTION, $readbody);
1630
        curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
1631
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connect_timeout);
1632
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1633

    
1634
	if (!empty($config['system']['proxyurl'])) {
1635
		curl_setopt($ch, CURLOPT_PROXY, $config['system']['proxyurl']);
1636
		if (!empty($config['system']['proxyport']))
1637
			curl_setopt($ch, CURLOPT_PROXYPORT, $config['system']['proxyport']);
1638
		if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
1639
			@curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY | CURLAUTH_ANYSAFE);
1640
			curl_setopt($ch, CURLOPT_PROXYUSERPWD, "{$config['system']['proxyuser']}:{$config['system']['proxypass']}");
1641
		}
1642
	}
1643

    
1644
        @curl_exec($ch);
1645
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1646
        if($fout)
1647
                fclose($fout);
1648
        curl_close($ch);
1649
        return ($http_code == 200) ? true : $http_code;
1650
}
1651

    
1652
function read_header($ch, $string) {
1653
        global $file_size, $fout;
1654
        $length = strlen($string);
1655
        $regs = "";
1656
        preg_match("/(Content-Length:) (.*)/", $string, $regs);
1657
        if($regs[2] <> "") {
1658
                $file_size = intval($regs[2]);
1659
        }
1660
        ob_flush();
1661
        return $length;
1662
}
1663

    
1664
function read_body($ch, $string) {
1665
        global $fout, $file_size, $downloaded, $sendto, $static_status, $static_output, $lastseen;
1666
		global $pkg_interface;
1667
        $length = strlen($string);
1668
        $downloaded += intval($length);
1669
        if($file_size > 0) {
1670
                $downloadProgress = round(100 * (1 - $downloaded / $file_size), 0);
1671
                $downloadProgress = 100 - $downloadProgress;
1672
        } else
1673
                $downloadProgress = 0;
1674
        if($lastseen <> $downloadProgress and $downloadProgress < 101) {
1675
                if($sendto == "status") {
1676
					if($pkg_interface == "console") {
1677
						if(substr($downloadProgress,2,1) == "0" || count($downloadProgress) < 2) {
1678
                        	$tostatus = $static_status . $downloadProgress . "%";
1679
                        	update_status($tostatus);
1680
						}
1681
					} else {
1682
                        $tostatus = $static_status . $downloadProgress . "%";
1683
                        update_status($tostatus);						
1684
					}
1685
                } else {
1686
					if($pkg_interface == "console") {
1687
						if(substr($downloadProgress,2,1) == "0" || count($downloadProgress) < 2) {
1688
                        	$tooutput = $static_output . $downloadProgress . "%";
1689
                        	update_output_window($tooutput);
1690
						}
1691
					} else {
1692
                        $tooutput = $static_output . $downloadProgress . "%";
1693
                        update_output_window($tooutput);
1694
					}
1695
                }
1696
                update_progress_bar($downloadProgress);
1697
                $lastseen = $downloadProgress;
1698
        }
1699
        if($fout)
1700
                fwrite($fout, $string);
1701
        ob_flush();
1702
        return $length;
1703
}
1704

    
1705
/*
1706
 *   update_output_window: update bottom textarea dynamically.
1707
 */
1708
function update_output_window($text) {
1709
        global $pkg_interface;
1710
        $log = preg_replace("/\n/", "\\n", $text);
1711
        if($pkg_interface != "console") {
1712
                echo "\n<script language=\"JavaScript\">\nthis.document.forms[0].output.value = \"" . $log . "\";\n";
1713
				echo "this.document.forms[0].output.scrollTop = this.document.forms[0].output.scrollHeight;\n";	
1714
				echo "</script>";
1715
        }
1716
        /* ensure that contents are written out */
1717
        ob_flush();
1718
}
1719

    
1720
/*
1721
 *   update_output_window: update top textarea dynamically.
1722
 */
1723
function update_status($status) {
1724
        global $pkg_interface;
1725
        if($pkg_interface == "console") {
1726
                echo $status . "\n";
1727
        } else {
1728
                echo "\n<script type=\"text/javascript\">this.document.forms[0].status.value=\"" . $status . "\";</script>";
1729
        }
1730
        /* ensure that contents are written out */
1731
        ob_flush();
1732
}
1733

    
1734
/*
1735
 * update_progress_bar($percent): updates the javascript driven progress bar.
1736
 */
1737
function update_progress_bar($percent) {
1738
        global $pkg_interface;
1739
        if($percent > 100) $percent = 1;
1740
        if($pkg_interface <> "console") {
1741
                echo "\n<script type=\"text/javascript\" language=\"javascript\">";
1742
                echo "\ndocument.progressbar.style.width='" . $percent . "%';";
1743
                echo "\n</script>";
1744
        } else {
1745
                echo " {$percent}%";
1746
        }
1747
}
1748

    
1749
/* 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. */
1750
if(!function_exists("split")) {
1751
	function split($seperator, $haystack, $limit = null) {
1752
		log_error("deprecated split() call with seperator '{$seperator}'");
1753
		return preg_split($seperator, $haystack, $limit);
1754
	}
1755
}
1756

    
1757
function update_alias_names_upon_change($section, $field, $new_alias_name, $origname) {
1758
	global $g, $config, $pconfig, $debug;
1759
	if(!$origname) 
1760
		return;
1761

    
1762
	$sectionref = &$config;
1763
	foreach($section as $sectionname) {
1764
		if(is_array($sectionref) && isset($sectionref[$sectionname]))
1765
			$sectionref = &$sectionref[$sectionname];
1766
		else
1767
			return;
1768
	}
1769

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

    
1773
	if(is_array($sectionref)) {
1774
		foreach($sectionref as $itemkey => $item) {
1775
			if($debug) fwrite($fd, "$itemkey\n");
1776

    
1777
			$fieldfound = true;
1778
			$fieldref = &$sectionref[$itemkey];
1779
			foreach($field as $fieldname) {
1780
				if(is_array($fieldref) && isset($fieldref[$fieldname]))
1781
					$fieldref = &$fieldref[$fieldname];
1782
				else {
1783
					$fieldfound = false;
1784
					break;
1785
				}
1786
			}
1787
			if($fieldfound && $fieldref == $origname) {
1788
				if($debug) fwrite($fd, "Setting old alias value $origname to $new_alias_name\n");
1789
				$fieldref = $new_alias_name;
1790
			}
1791
		}
1792
	}
1793

    
1794
	if($debug) fclose($fd);
1795

    
1796
}
1797

    
1798
function update_alias_url_data() {
1799
	global $config, $g;
1800

    
1801
	/* item is a url type */
1802
	$lockkey = lock('config');
1803
	if (is_array($config['aliases']['alias'])) {
1804
		foreach ($config['aliases']['alias'] as $x => $alias) {
1805
			if (empty($alias['aliasurl']))
1806
				continue;
1807

    
1808
			/* fetch down and add in */
1809
			$isfirst = 0;
1810
			$temp_filename = tempnam("{$g['tmp_path']}/", "alias_import");
1811
			unlink($temp_filename);
1812
			$fda = fopen("{$g['tmp_path']}/tmpfetch","w");
1813
			fwrite($fda, "/usr/bin/fetch -T 5 -q -o \"{$temp_filename}/aliases\" \"" . $config['aliases']['alias'][$x]['aliasurl'] . "\"");
1814
			fclose($fda);
1815
			mwexec("/bin/mkdir -p {$temp_filename}");
1816
			mwexec("/usr/bin/fetch -T 5 -q -o \"{$temp_filename}/aliases\" \"" . $config['aliases']['alias'][$x]['aliasurl'] . "\"");
1817
			/* if the item is tar gzipped then extract */
1818
			if(stristr($alias['aliasurl'], ".tgz"))
1819
				process_alias_tgz($temp_filename);
1820
			else if(stristr($alias['aliasurl'], ".zip"))
1821
				process_alias_unzip($temp_filename);
1822
			if(file_exists("{$temp_filename}/aliases")) {
1823
				$file_contents = file_get_contents("{$temp_filename}/aliases");
1824
				$file_contents = str_replace("#", "\n#", $file_contents);
1825
				$file_contents_split = explode("\n", $file_contents);
1826
				foreach($file_contents_split as $fc) {
1827
					$tmp = trim($fc);
1828
					if(stristr($fc, "#")) {
1829
						$tmp_split = explode("#", $tmp);
1830
						$tmp = trim($tmp_split[0]);
1831
					}
1832
					if(trim($tmp) <> "") {
1833
						if($isfirst == 1)
1834
							$address .= " ";
1835
						$address .= $tmp;
1836
						$isfirst = 1;
1837
					}
1838
				}
1839
				if($isfirst > 0) {
1840
					$config['aliases']['alias'][$x]['address'] = $address;
1841
					$updated = true;
1842
				}
1843
				mwexec("/bin/rm -rf {$temp_filename}");
1844
			}
1845
		}
1846
	}
1847
	if($updated)
1848
		write_config();
1849
	unlock($lockkey);
1850
}
1851

    
1852
function process_alias_unzip($temp_filename) {
1853
	if(!file_exists("/usr/local/bin/unzip"))
1854
		return;
1855
	mwexec("/bin/mv {$temp_filename}/aliases {$temp_filename}/aliases.zip");
1856
	mwexec("/usr/local/bin/unzip {$temp_filename}/aliases.tgz -d {$temp_filename}/aliases/");
1857
	unlink("{$temp_filename}/aliases.zip");
1858
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1859
	/* foreach through all extracted files and build up aliases file */
1860
	$fd = fopen("{$temp_filename}/aliases", "w");
1861
	foreach($files_to_process as $f2p) {
1862
		$file_contents = file_get_contents($f2p);
1863
		fwrite($fd, $file_contents);
1864
		unlink($f2p);
1865
	}
1866
	fclose($fd);
1867
}
1868

    
1869
function process_alias_tgz($temp_filename) {
1870
	if(!file_exists("/usr/bin/tar"))
1871
		return;
1872
	mwexec("/bin/mv {$temp_filename}/aliases {$temp_filename}/aliases.tgz");
1873
	mwexec("/usr/bin/tar xzf {$temp_filename}/aliases.tgz -C {$temp_filename}/aliases/");
1874
	unlink("{$temp_filename}/aliases.tgz");
1875
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1876
	/* foreach through all extracted files and build up aliases file */
1877
	$fd = fopen("{$temp_filename}/aliases", "w");
1878
	foreach($files_to_process as $f2p) {
1879
		$file_contents = file_get_contents($f2p);
1880
		fwrite($fd, $file_contents);
1881
		unlink($f2p);
1882
	}
1883
	fclose($fd);
1884
}
1885

    
1886
function version_compare_dates($a, $b) {
1887
	$a_time = strtotime($a);
1888
	$b_time = strtotime($b);
1889

    
1890
	if ((!$a_time) || (!$b_time)) {
1891
		return FALSE;
1892
	} else {
1893
		if ($a_time < $b_time)
1894
			return -1;
1895
		elseif ($$a_time == $b_time)
1896
			return 0;
1897
		else
1898
			return 1;
1899
	}
1900
}
1901
function version_get_string_value($a) {
1902
	$strs = array(
1903
		0 => "ALPHA-ALPHA",
1904
		2 => "ALPHA",
1905
		3 => "BETA",
1906
		4 => "B",
1907
		5 => "C",
1908
		6 => "D",
1909
		7 => "RC",
1910
		8 => "RELEASE"
1911
	);
1912
	$major = 0;
1913
	$minor = 0;
1914
	foreach ($strs as $num => $str) {
1915
		if (substr($a, 0, strlen($str)) == $str) {
1916
			$major = $num;
1917
			$n = substr($a, strlen($str));
1918
			if (is_numeric($n))
1919
				$minor = $n;
1920
			break;
1921
		}
1922
	}
1923
	return "{$major}.{$minor}";
1924
}
1925
function version_compare_string($a, $b) {
1926
	return version_compare_numeric(version_get_string_value($a), version_get_string_value($b));
1927
}
1928
function version_compare_numeric($a, $b) {
1929
	$a_arr = explode('.', rtrim($a, '.0'));
1930
	$b_arr = explode('.', rtrim($b, '.0'));
1931

    
1932
	foreach ($a_arr as $n => $val) {
1933
		if (array_key_exists($n, $b_arr)) {
1934
			// So far so good, both have values at this minor version level. Compare.
1935
			if ($val > $b_arr[$n])
1936
				return 1;
1937
			elseif ($val < $b_arr[$n])
1938
				return -1;
1939
		} else {
1940
			// a is greater, since b doesn't have any minor version here.
1941
			return 1;
1942
		}
1943
	}
1944
	if (count($b_arr) > count($a_arr)) {
1945
		// b is longer than a, so it must be greater.
1946
		return -1;
1947
	} else {
1948
		// Both a and b are of equal length and value.
1949
		return 0;
1950
	}
1951
}
1952
function pfs_version_compare($cur_time, $cur_text, $remote) {
1953
	// First try date compare
1954
	$v = version_compare_dates($cur_time, $remote);
1955
	if ($v === FALSE) {
1956
		// If that fails, try to compare by string
1957
		// Before anything else, simply test if the strings are equal
1958
		if (($cur_text == $remote) || ($cur_time == $remote))
1959
			return 0;
1960
		list($cur_num, $cur_str) = explode('-', $cur_text);
1961
		list($rem_num, $rem_str) = explode('-', $remote);
1962

    
1963
		// First try to compare the numeric parts of the version string.
1964
		$v = version_compare_numeric($cur_num, $rem_num);
1965

    
1966
		// If the numeric parts are the same, compare the string parts.
1967
		if ($v == 0)
1968
			return version_compare_string($cur_str, $rem_str);
1969
	}
1970
	return $v;
1971
}
1972
function process_alias_urltable($name, $url, $freq, $forceupdate=false) {
1973
	$urltable_prefix = "/var/db/aliastables/";
1974
	$urltable_filename = $urltable_prefix . $name . ".txt";
1975

    
1976
	// Make the aliases directory if it doesn't exist
1977
	if (!file_exists($urltable_prefix)) {
1978
		mkdir($urltable_prefix);
1979
	} elseif (!is_dir($urltable_prefix)) {
1980
		unlink($urltable_prefix);
1981
		mkdir($urltable_prefix);
1982
	}
1983

    
1984
	// If the file doesn't exist or is older than update_freq days, fetch a new copy.
1985
	if (!file_exists($urltable_filename)
1986
		|| ((time() - filemtime($urltable_filename)) > ($freq * 86400))
1987
		|| $forceupdate) {
1988

    
1989
		// Try to fetch the URL supplied
1990
		conf_mount_rw();
1991
		unlink_if_exists($urltable_filename . ".tmp");
1992
		// 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.
1993
		mwexec("/usr/bin/fetch -T 5 -q -o " . escapeshellarg($urltable_filename . ".tmp") . " " . escapeshellarg($url));
1994
		// Remove comments. Might need some grep-fu to only allow lines that look like IPs/subnets
1995
		if (file_exists($urltable_filename . ".tmp")) {
1996
			mwexec("/usr/bin/grep -v '^#' " . escapeshellarg($urltable_filename . ".tmp") . " > " . escapeshellarg($urltable_filename));
1997
			unlink_if_exists($urltable_filename . ".tmp");
1998
		} else
1999
			mwexec("/usr/bin/touch {$urltable_filename}");
2000
		conf_mount_ro();
2001
		return true;
2002
	} else {
2003
		// File exists, and it doesn't need updated.
2004
		return -1;
2005
	}
2006
}
2007
function get_real_slice_from_glabel($label) {
2008
	$label = escapeshellarg($label);
2009
	return trim(`/sbin/glabel list | /usr/bin/grep -B2 ufs/{$label} | /usr/bin/head -n 1 | /usr/bin/cut -f3 -d' '`);
2010
}
2011
function nanobsd_get_boot_slice() {
2012
	return trim(`/sbin/mount | /usr/bin/grep pfsense | /usr/bin/cut -d'/' -f4 | /usr/bin/cut -d' ' -f1`);
2013
}
2014
function nanobsd_get_boot_drive() {
2015
	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`);
2016
}
2017
function nanobsd_get_active_slice() {
2018
	$boot_drive = nanobsd_get_boot_drive();
2019
	$active = trim(`gpart show $boot_drive | grep '\[active\]' | awk '{print $3;}'`);
2020

    
2021
	return "{$boot_drive}s{$active}";
2022
}
2023
function nanobsd_get_size() {
2024
	return strtoupper(file_get_contents("/etc/nanosize.txt"));
2025
}
2026
function nanobsd_switch_boot_slice() {
2027
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2028
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2029
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2030
	nanobsd_detect_slice_info();
2031

    
2032
	if ($BOOTFLASH == $ACTIVE_SLICE) {
2033
		$slice = $TOFLASH;
2034
	} else {
2035
		$slice = $BOOTFLASH;
2036
	}
2037

    
2038
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
2039
	ob_implicit_flush(1);
2040
	if(strstr($slice, "s2")) {
2041
		$ASLICE="2";
2042
		$AOLDSLICE="1";
2043
		$AGLABEL_SLICE="pfsense1";
2044
		$AUFS_ID="1";
2045
		$AOLD_UFS_ID="0";
2046
	} else {
2047
		$ASLICE="1";
2048
		$AOLDSLICE="2";
2049
		$AGLABEL_SLICE="pfsense0";
2050
		$AUFS_ID="0";
2051
		$AOLD_UFS_ID="1";
2052
	}
2053
	$ATOFLASH="{$BOOT_DRIVE}s{$ASLICE}";
2054
	$ACOMPLETE_PATH="{$BOOT_DRIVE}s{$ASLICE}a";
2055
	$ABOOTFLASH="{$BOOT_DRIVE}s{$AOLDSLICE}";
2056
	conf_mount_rw();
2057
	exec("sysctl kern.geom.debugflags=16");
2058
	exec("gpart set -a active -i {$ASLICE} {$BOOT_DRIVE}");
2059
	exec("/usr/sbin/boot0cfg -s {$ASLICE} -v /dev/{$BOOT_DRIVE}");
2060
	// We can't update these if they are mounted now.
2061
	if ($BOOTFLASH != $slice) {
2062
		exec("/sbin/tunefs -L ${AGLABEL_SLICE} /dev/$ACOMPLETE_PATH");
2063
		nanobsd_update_fstab($AGLABEL_SLICE, $ACOMPLETE_PATH, $AOLD_UFS_ID, $AUFS_ID);
2064
	}
2065
	exec("/sbin/sysctl kern.geom.debugflags=0");
2066
	conf_mount_ro();
2067
}
2068
function nanobsd_clone_slice() {
2069
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2070
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2071
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2072
	nanobsd_detect_slice_info();
2073

    
2074
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
2075
	ob_implicit_flush(1);
2076
	exec("/sbin/sysctl kern.geom.debugflags=16");
2077
	exec("/bin/dd if=/dev/zero of=/dev/{$TOFLASH} bs=1m count=1");
2078
	exec("/bin/dd if=/dev/{$BOOTFLASH} of=/dev/{$TOFLASH} bs=64k");
2079
	exec("/sbin/tunefs -L {$GLABEL_SLICE} /dev/{$COMPLETE_PATH}");
2080
	$status = nanobsd_update_fstab($GLABEL_SLICE, $COMPLETE_PATH, $OLD_UFS_ID, $UFS_ID);
2081
	exec("/sbin/sysctl kern.geom.debugflags=0");
2082
	if($status) {
2083
		return false;
2084
	} else {
2085
		return true;
2086
	}
2087
}
2088
function nanobsd_update_fstab($gslice, $complete_path, $oldufs, $newufs) {
2089
	$tmppath = "/tmp/{$gslice}";
2090
	$fstabpath = "/tmp/{$gslice}/etc/fstab";
2091

    
2092
	exec("/bin/mkdir {$tmppath}");
2093
	exec("/sbin/fsck_ufs -y /dev/{$complete_path}");
2094
	exec("/sbin/mount /dev/ufs/{$gslice} {$tmppath}");
2095
	exec("/bin/cp /etc/fstab {$fstabpath}");
2096

    
2097
	if (!file_exists($fstabpath)) {
2098
		$fstab = <<<EOF
2099
/dev/ufs/{$gslice} / ufs ro,noatime 1 1
2100
/dev/ufs/cf /cf ufs ro,noatime 1 1
2101
EOF;
2102
		if (file_put_contents($fstabpath, $fstab))
2103
			$status = true;
2104
		else
2105
			$status = false;
2106
	} else {
2107
		$status = exec("sed -i \"\" \"s/pfsense{$oldufs}/pfsense{$newufs}/g\" {$fstabpath}");
2108
	}
2109
	exec("/sbin/umount {$tmppath}");
2110
	exec("/bin/rmdir {$tmppath}");
2111

    
2112
	return $status;
2113
}
2114
function nanobsd_detect_slice_info() {
2115
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2116
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2117
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2118

    
2119
	$BOOT_DEVICE=nanobsd_get_boot_slice();
2120
	$REAL_BOOT_DEVICE=get_real_slice_from_glabel($BOOT_DEVICE);
2121
	$BOOT_DRIVE=nanobsd_get_boot_drive();
2122
	$ACTIVE_SLICE=nanobsd_get_active_slice();
2123

    
2124
	// Detect which slice is active and set information.
2125
	if(strstr($REAL_BOOT_DEVICE, "s1")) {
2126
		$SLICE="2";
2127
		$OLDSLICE="1";
2128
		$GLABEL_SLICE="pfsense1";
2129
		$UFS_ID="1";
2130
		$OLD_UFS_ID="0";
2131

    
2132
	} else {
2133
		$SLICE="1";
2134
		$OLDSLICE="2";
2135
		$GLABEL_SLICE="pfsense0";
2136
		$UFS_ID="0";
2137
		$OLD_UFS_ID="1";
2138
	}
2139
	$TOFLASH="{$BOOT_DRIVE}s{$SLICE}";
2140
	$COMPLETE_PATH="{$BOOT_DRIVE}s{$SLICE}a";
2141
	$COMPLETE_BOOT_PATH="{$BOOT_DRIVE}s{$OLDSLICE}";
2142
	$BOOTFLASH="{$BOOT_DRIVE}s{$OLDSLICE}";
2143
}
2144

    
2145
function nanobsd_friendly_slice_name($slicename) {
2146
	global $g;
2147
	return strtolower(str_ireplace('pfsense', $g['product_name'], $slicename));
2148
}
2149

    
2150
function get_include_contents($filename) {
2151
    if (is_file($filename)) {
2152
        ob_start();
2153
        include $filename;
2154
        $contents = ob_get_contents();
2155
        ob_end_clean();
2156
        return $contents;
2157
    }
2158
    return false;
2159
}
2160

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

    
2296
function get_country_name($country_code) {
2297
	if ($country_code != "ALL" && strlen($country_code) != 2)
2298
		return "";
2299

    
2300
	$country_names_xml = "/usr/local/share/mobile-broadband-provider-info/iso_3166-1_list_en.xml";
2301
	$country_names_contents = file_get_contents($country_names_xml);
2302
	$country_names = xml2array($country_names_contents);
2303

    
2304
	if($country_code == "ALL") {
2305
		$country_list = array();
2306
		foreach($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2307
			$country_list[] = array( "code" => $country['ISO_3166-1_Alpha-2_Code_element'],
2308
						 "name" => ucwords(strtolower($country['ISO_3166-1_Country_name'])) );
2309
		}
2310
		return $country_list;
2311
	}
2312

    
2313
	foreach ($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2314
		if ($country['ISO_3166-1_Alpha-2_Code_element'] == strtoupper($country_code)) {
2315
			return ucwords(strtolower($country['ISO_3166-1_Country_name']));
2316
		}
2317
	}
2318
	return "";
2319
}
2320

    
2321
/* sort by interface only, retain the original order of rules that apply to
2322
   the same interface */
2323
function filter_rules_sort() {
2324
	global $config;
2325

    
2326
	/* mark each rule with the sequence number (to retain the order while sorting) */
2327
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2328
		$config['filter']['rule'][$i]['seq'] = $i;
2329

    
2330
	usort($config['filter']['rule'], "filter_rules_compare");
2331

    
2332
	/* strip the sequence numbers again */
2333
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2334
		unset($config['filter']['rule'][$i]['seq']);
2335
}
2336
function filter_rules_compare($a, $b) {
2337
	if (isset($a['floating']) && isset($b['floating']))
2338
		return $a['seq'] - $b['seq'];
2339
	else if (isset($a['floating']))
2340
		return -1;
2341
	else if (isset($b['floating']))
2342
		return 1;
2343
	else if ($a['interface'] == $b['interface'])
2344
		return $a['seq'] - $b['seq'];
2345
	else
2346
		return compare_interface_friendly_names($a['interface'], $b['interface']);
2347
}
2348

    
2349
function generate_ipv6_from_mac($mac) {
2350
	$elements = explode(":", $mac);
2351
	if(count($elements) <> 6)
2352
		return false;
2353

    
2354
	$i = 0;
2355
	$ipv6 = "fe80::";
2356
	foreach($elements as $byte) {
2357
		if($i == 0) {
2358
			$hexadecimal =  substr($byte, 1, 2);
2359
			$bitmap = base_convert($hexadecimal, 16, 2);
2360
			$bitmap = str_pad($bitmap, 4, "0", STR_PAD_LEFT);
2361
			$bitmap = substr($bitmap, 0, 2) ."1". substr($bitmap, 3,4);
2362
			$byte = substr($byte, 0, 1) . base_convert($bitmap, 2, 16);
2363
		}
2364
		$ipv6 .= $byte;
2365
		if($i == 1) {
2366
			$ipv6 .= ":";
2367
		}
2368
		if($i == 3) {
2369
			$ipv6 .= ":";
2370
		}
2371
		if($i == 2) {
2372
			$ipv6 .= "ff:fe";
2373
		}
2374
		
2375
		$i++;
2376
	}	
2377
	return $ipv6;
2378
}
2379

    
2380
/****f* pfsense-utils/load_mac_manufacturer_table
2381
 * NAME
2382
 *   load_mac_manufacturer_table
2383
 * INPUTS
2384
 *   none
2385
 * RESULT
2386
 *   returns associative array with MAC-Manufacturer pairs
2387
 ******/
2388
function load_mac_manufacturer_table() {
2389
	/* load MAC-Manufacture data from the file */
2390
	$macs = false;
2391
	if (file_exists("/usr/local/share/nmap/nmap-mac-prefixes"))
2392
		$macs=file("/usr/local/share/nmap/nmap-mac-prefixes");
2393
	if ($macs){
2394
		foreach ($macs as $line){
2395
			if (preg_match('/([0-9A-Fa-f]{6}) (.*)$/', $line, $matches)){
2396
				/* store values like this $mac_man['000C29']='VMware' */
2397
				$mac_man["$matches[1]"]=$matches[2];
2398
			}
2399
		}
2400
 		return $mac_man;
2401
	} else
2402
		return -1;
2403

    
2404
}
2405

    
2406
/****f* pfsense-utils/is_ipaddr_configured
2407
 * NAME
2408
 *   is_ipaddr_configured
2409
 * INPUTS
2410
 *   IP Address to check.
2411
 * RESULT
2412
 *   returns true if the IP Address is
2413
 *   configured and present on this device.
2414
*/
2415
function is_ipaddr_configured($ipaddr) {
2416
	$interface_list_ips = get_configured_ip_addresses();
2417
	foreach($interface_list_ips as $ilips) {
2418
		if(strcasecmp($ipaddr, $ilips) == 0) 
2419
				return true;
2420
	}	
2421
}
2422

    
2423
/****f* pfsense-utils/pfSense_handle_custom_code
2424
 * NAME
2425
 *   pfSense_handle_custom_code
2426
 * INPUTS
2427
 *   directory name to process
2428
 * RESULT
2429
 *   globs the directory and includes the files
2430
 */
2431
function pfSense_handle_custom_code($src_dir) {
2432
	// Allow extending of the nat edit page and include custom input validation 
2433
	if(is_dir("$src_dir")) {
2434
		$cf = glob($src_dir . "/*.inc");
2435
		foreach($cf as $nf) {
2436
			if($nf == "." || $nf == "..") 
2437
				continue;
2438
			// Include the extra handler
2439
			include("$nf");
2440
		}
2441
	}
2442
}
2443

    
2444
function set_language($lang = 'en_US', $encoding = "ISO8859-1") {
2445
	putenv("LANG={$lang}.{$encoding}");
2446
	setlocale(LC_ALL, "{$lang}.{$encoding}");
2447
	textdomain("pfSense");
2448
	bindtextdomain("pfSense","/usr/local/share/locale");
2449
	bind_textdomain_codeset("pfSense","{$lang}.{$encoding}");
2450
}
2451

    
2452
function get_locale_list() {
2453
	$locales = array(
2454
		"en_US" => gettext("English"),
2455
		"pt_BR" => gettext("Portuguese (Brazil)"),
2456
	);
2457
	asort($locales);
2458
	return $locales;
2459
}
2460

    
2461
function return_hex_ipv4($ipv4) {
2462
	if(!is_ipaddrv4($ipv4))
2463
		return(false);
2464
	
2465
	/* we need the hex form of the interface IPv4 address */
2466
	$ip4arr = explode(".", $ipv4);
2467
	$hexwanv4 = "";
2468
	foreach($ip4arr as $octet)
2469
		$hexwanv4 .= sprintf("%02x", $octet);
2470

    
2471
	return($hexwanv4);
2472
}
2473

    
2474
function convert_ipv6_to_128bit($ipv6) {
2475
	if(!is_ipaddrv6($ipv6))
2476
		return(false);
2477

    
2478
	$ip6arr = array();
2479
	$ip6prefix = Net_IPv6::uncompress($ipv6);
2480
	$ip6arr = explode(":", $ip6prefix);
2481
	/* binary presentation of the prefix for all 128 bits. */
2482
	$ip6prefixbin = "";
2483
	foreach($ip6arr as $element) {
2484
		$ip6prefixbin .= sprintf("%016b", hexdec($element));
2485
	}
2486
	return($ip6prefixbin);
2487
}
2488

    
2489
function convert_128bit_to_ipv6($ip6bin) {
2490
	if(strlen($ip6bin) <> 128)
2491
		return(false);
2492

    
2493
	$ip6arr = array();
2494
	$ip6binarr = array();
2495
	$ip6binarr = str_split($ip6bin, 16);
2496
	foreach($ip6binarr as $binpart)
2497
		$ip6arr[] = dechex(bindec($binpart));
2498
	$ip6addr = Net_IPv6::compress(implode(":", $ip6arr));
2499

    
2500
	return($ip6addr);
2501
}
2502

    
2503

    
2504
/* Returns the calculated bit length of the prefix delegation from the WAN interface */
2505
/* DHCP-PD is variable, calculate from the prefix-len on the WAN interface */
2506
/* 6rd is variable, calculate from 64 - (v6 prefixlen - (32 - v4 prefixlen)) */
2507
/* 6to4 is 16 bits, e.g. 65535 */
2508
function calculate_ipv6_delegation_length($if) {
2509
	global $config;
2510

    
2511
	if(!is_array($config['interfaces'][$if]))
2512
		return false;
2513

    
2514
	switch($config['interfaces'][$if]['ipaddrv6']) {
2515
		case "6to4":
2516
			$pdlen = 16;
2517
			break;
2518
		case "6rd":
2519
			$rd6cfg = $config['interfaces'][$if];
2520
			$rd6plen = explode("/", $rd6cfg['prefix-6rd']);
2521
			$pdlen = (64 - ($rd6plen[1] + (32 - $rd6cfg['prefix-6rd-v4plen'])));
2522
			break;
2523
		case "dhcp6":
2524
			$dhcp6cfg = $config['interfaces'][$if];
2525
			$pdlen = $dhcp6cfg['dhcp6-ia-pd-len'];
2526
			break;
2527
		default:
2528
			$pdlen = 0;
2529
			break;
2530
	}
2531
	return($pdlen);
2532
}
2533

    
2534
function huawei_rssi_to_string($rssi) {
2535
	$dbm = array();
2536
	$i = 0;
2537
	$dbstart = -51;
2538
	while($i < 31) {
2539
		$dbm[$i] = $dbstart - ($i * 2);
2540
		$i++;
2541
	}
2542
	$percent = round(($rssi / 31) * 100);
2543
	$string = "rssi:8 level:{$dbm[$rssi]}dBm percent:{$percent}%";
2544
	return $string;
2545
}
2546

    
2547
function huawei_mode_to_string($mode, $submode) {
2548
	$modes[0] = "None";
2549
	$modes[1] = "AMPS"; 
2550
	$modes[2] = "CDMA";
2551
	$modes[3] = "GSM/GPRS";
2552
	$modes[4] = "HDR";
2553
	$modes[5] = "WCDMA";
2554
	$modes[6] = "GPS"; 
2555

    
2556
	$submodes[0] = "No Service";
2557
	$submodes[1] = "GSM";
2558
	$submodes[2] = "GPRS";
2559
	$submodes[3] = "EDGE";
2560
	$submodes[4] = "WCDMA";
2561
	$submodes[5] = "HSDPA";
2562
	$submodes[6] = "HSUPA";
2563
	$submodes[7] = "HSDPA+HSUPA";
2564
	$submodes[8] = "TD-SCDMA";
2565
	$submodes[9] = "HSPA+";
2566
	$string = "{$modes[$mode]}, {$submodes[$submode]} Mode";
2567
	return $string;
2568
}
2569

    
2570
function huawei_service_to_string($state) {
2571
	$modes[0] = "No";
2572
	$modes[1] = "Restricted"; 
2573
	$modes[2] = "Valid";
2574
	$modes[3] = "Restricted Regional";
2575
	$modes[4] = "Powersaving";
2576
	$string = "{$modes[$state]} Service";
2577
	return $string;
2578
}
2579

    
2580
function huawei_simstate_to_string($state) {
2581
	$modes[0] = "Invalid SIM/locked";
2582
	$modes[1] = "Valid SIM"; 
2583
	$modes[2] = "Invalid SIM CS";
2584
	$modes[3] = "Invalid SIM PS";
2585
	$modes[4] = "Invalid SIM CS/PS";
2586
	$modes[255] = "Missing SIM";
2587
	$string = "{$modes[$state]} State";
2588
	return $string;
2589
}
2590

    
2591
function zte_rssi_to_string($rssi) {
2592
	return huawei_rssi_to_string($rssi);
2593
}
2594

    
2595
function zte_mode_to_string($mode, $submode) {
2596
	$modes[0] = "No Service";
2597
	$modes[1] = "Limited Service"; 
2598
	$modes[2] = "GPRS";
2599
	$modes[3] = "GSM";
2600
	$modes[4] = "UMTS";
2601
	$modes[5] = "EDGE";
2602
	$modes[6] = "HSDPA"; 
2603

    
2604
	$submodes[0] = "CS_ONLY";
2605
	$submodes[1] = "PS_ONLY";
2606
	$submodes[2] = "CS_PS";
2607
	$submodes[3] = "CAMPED";
2608
	$string = "{$modes[$mode]}, {$submodes[$submode]} Mode";
2609
	return $string;
2610
}
2611

    
2612
function zte_service_to_string($state) {
2613
	$modes[0] = "Initializing";
2614
	$modes[1] = "Network Lock error"; 
2615
	$modes[2] = "Network Locked";
2616
	$modes[3] = "Unlocked or correct MCC/MNC";
2617
	$string = "{$modes[$state]} Service";
2618
	return $string;
2619
}
2620

    
2621
function zte_simstate_to_string($state) {
2622
	$modes[0] = "No action";
2623
	$modes[1] = "Network lock"; 
2624
	$modes[2] = "(U)SIM card lock";
2625
	$modes[3] = "Network Lock and (U)SIM card Lock";
2626
	$string = "{$modes[$state]} State";
2627
	return $string;
2628
}
2629
?>
(38-38/66)