Project

General

Profile

Download (74.9 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
				if (file_exists("/etc/nano_use_vga.txt")) {
1002
					$new_boot_config[] = 'boot_multicons="YES"';
1003
					$new_boot_config[] = 'comconsole_speed="' . $serialspeed . '"';
1004
					$new_boot_config[] = 'console="vidconsole,comconsole"';
1005
				} else {
1006
					$new_boot_config[] = 'comconsole_speed="' . $serialspeed . '"';
1007
					$new_boot_config[] = 'console="comconsole"';
1008
				}
1009
			}
1010
			file_put_contents($loader_conf_file, implode("\n", $new_boot_config) . "\n");
1011
		}
1012
	}
1013
	$ttys = file_get_contents("/etc/ttys");
1014
	$ttys_split = explode("\n", $ttys);
1015
	$fd = fopen("/etc/ttys", "w");
1016
	foreach($ttys_split as $tty) {
1017
		if(stristr($tty, "ttyd0") or stristr($tty, "ttyu0")) {
1018
			if(isset($config['system']['enableserial'])) {
1019
				fwrite($fd, "ttyu0	\"/usr/libexec/getty bootupcli\"	cons25	on	secure\n");
1020
			} else {
1021
				fwrite($fd, "ttyu0	\"/usr/libexec/getty bootupcli\"	cons25	off	secure\n");
1022
			}
1023
		} else {
1024
			fwrite($fd, $tty . "\n");
1025
		}
1026
	}
1027
	fclose($fd);
1028
	auto_login();
1029

    
1030
	conf_mount_ro();
1031
	return;
1032
}
1033

    
1034
function print_value_list($list, $count = 10, $separator = ",") {
1035
	$list = implode($separator, array_slice($list, 0, $count));
1036
	if(count($list) < $count) {
1037
		$list .= ".";
1038
	} else {
1039
		$list .= "...";
1040
	}
1041
	return $list;
1042
}
1043

    
1044
/* DHCP enabled on any interfaces? */
1045
function is_dhcp_server_enabled() 
1046
{
1047
	global $config;
1048

    
1049
	$dhcpdenable = false;
1050
	
1051
	if (!is_array($config['dhcpd']))
1052
		return false;
1053

    
1054
	$Iflist = get_configured_interface_list();
1055

    
1056
	if(is_array($config['dhcpd'])) {
1057
		foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf) {
1058
			if (isset($dhcpifconf['enable']) && isset($Iflist[$dhcpif])) {
1059
				$dhcpdenable = true;
1060
				break;
1061
			}
1062
		}
1063
	}
1064

    
1065
	return $dhcpdenable;
1066
}
1067

    
1068
/* DHCP enabled on any interfaces? */
1069
function is_dhcpv6_server_enabled() 
1070
{
1071
	global $config;
1072

    
1073
	$dhcpdenable = false;
1074
	
1075
	$Iflist = get_configured_interface_list();
1076

    
1077
	foreach($Iflist as $ifname) {
1078
		if($config['interfaces'][$ifname]['track6-interface'] <> "") {
1079
			return true;
1080
		}
1081
	}
1082

    
1083
	if (!is_array($config['dhcpdv6']))
1084
		return false;
1085

    
1086

    
1087
	if(is_array($config['dhcpdv6'])) {
1088
		foreach ($config['dhcpdv6'] as $dhcpv6if => $dhcpv6ifconf) {
1089
			if (isset($dhcpv6ifconf['enable']) && isset($Iflist[$dhcpv6if])) {
1090
				$dhcpdenable = true;
1091
				break;
1092
			}
1093
		}
1094
	}
1095

    
1096
	return $dhcpdenable;
1097
}
1098

    
1099
/* radvd enabled on any interfaces? */
1100
function is_radvd_enabled() {
1101
	global $config;
1102

    
1103
	if (!is_array($config['dhcpdv6']))
1104
		$config['dhcpdv6'] = array();
1105

    
1106
	$dhcpdv6cfg = $config['dhcpdv6'];
1107
	$Iflist = get_configured_interface_list();
1108

    
1109
	/* handle manually configured DHCP6 server settings first */
1110
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1111
		if(!isset($config['interfaces'][$dhcpv6if]['enable']))
1112
			continue;
1113

    
1114
		if(!isset($dhcpv6ifconf['ramode']))
1115
			$dhcpv6ifconf['ramode'] = $dhcpv6ifconf['mode'];
1116

    
1117
		if($dhcpv6ifconf['ramode'] == "disabled")
1118
			continue;
1119

    
1120
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1121
		if(!is_ipaddrv6($ifcfgipv6))
1122
			continue;
1123

    
1124
		return true;
1125
	}
1126

    
1127
	/* handle DHCP-PD prefixes and 6RD dynamic interfaces */
1128
	foreach ($Iflist as $if => $ifdescr) {
1129
		if(!isset($config['interfaces'][$if]['track6-interface']))
1130
			continue;
1131
		if(!isset($config['interfaces'][$if]['enable']))
1132
			continue;
1133

    
1134
		$ifcfgipv6 = get_interface_ipv6($if);
1135
		if(!is_ipaddrv6($ifcfgipv6))
1136
			continue;
1137

    
1138
		$ifcfgsnv6 = get_interface_subnetv6($if);
1139
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1140

    
1141
		if(!is_ipaddrv6($subnetv6))
1142
			continue;
1143

    
1144
		return true;
1145
	}
1146

    
1147
	return false;
1148
}
1149

    
1150
/* Any PPPoE servers enabled? */
1151
function is_pppoe_server_enabled() {
1152
	global $config;
1153

    
1154
	$pppoeenable = false;
1155

    
1156
	if (!is_array($config['pppoes']) || !is_array($config['pppoes']['pppoe']))
1157
		return false;
1158

    
1159
	foreach ($config['pppoes']['pppoe'] as $pppoes)
1160
		if ($pppoes['mode'] == 'server')
1161
			$pppoeenable = true;
1162

    
1163
	return $pppoeenable;
1164
}
1165

    
1166
function convert_seconds_to_hms($sec){
1167
	$min=$hrs=0;
1168
	if ($sec != 0){
1169
		$min = floor($sec/60);
1170
		$sec %= 60;
1171
	}
1172
	if ($min != 0){
1173
		$hrs = floor($min/60);
1174
		$min %= 60;
1175
	}
1176
	if ($sec < 10)
1177
		$sec = "0".$sec;
1178
	if ($min < 10)
1179
		$min = "0".$min;
1180
	if ($hrs < 10)
1181
		$hrs = "0".$hrs;
1182
	$result = $hrs.":".$min.":".$sec;
1183
	return $result;
1184
}
1185

    
1186
/* Compute the total uptime from the ppp uptime log file in the conf directory */
1187

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

    
1203
//returns interface information
1204
function get_interface_info($ifdescr) {
1205
	global $config, $g;
1206

    
1207
	$ifinfo = array();
1208
	if (empty($config['interfaces'][$ifdescr]))
1209
		return;
1210
	$ifinfo['hwif'] = $config['interfaces'][$ifdescr]['if'];
1211
	$ifinfo['if'] = get_real_interface($ifdescr);
1212

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

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

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

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

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

    
1298
		break;
1299
	/* PPP interface? -> get uptime for this session and cumulative uptime from the persistant log file in conf */
1300
	case "ppp":
1301
		if ($ifinfo['status'] == "up")
1302
			$ifinfo['ppplink'] = "up";
1303
		else
1304
			$ifinfo['ppplink'] = "down" ;
1305

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

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

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

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

    
1418
		}
1419
		/* lookup the gateway */
1420
		if (interface_has_gateway($ifdescr)) {
1421
			$ifinfo['gateway'] = get_interface_gateway($ifdescr);
1422
			$ifinfo['gatewayv6'] = get_interface_gateway_v6($ifdescr);
1423
		}
1424
	}
1425

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

    
1442
	return $ifinfo;
1443
}
1444

    
1445
//returns cpu speed of processor. Good for determining capabilities of machine
1446
function get_cpu_speed() {
1447
	 return exec("sysctl hw.clockrate | awk '{ print $2 }'");
1448
}
1449

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

    
1479
function is_fqdn($fqdn) {
1480
	$hostname = false;
1481
	if(preg_match("/[-A-Z0-9\.]+\.[-A-Z0-9\.]+/i", $fqdn)) {
1482
		$hostname = true;
1483
	}
1484
	if(preg_match("/\.\./", $fqdn)) {
1485
		$hostname = false;
1486
	}
1487
	if(preg_match("/^\./i", $fqdn)) { 
1488
		$hostname = false;
1489
	}
1490
	if(preg_match("/\//i", $fqdn)) {
1491
		$hostname = false;
1492
	}
1493
	return($hostname);
1494
}
1495

    
1496
function pfsense_default_state_size() {
1497
  /* get system memory amount */
1498
  $memory = get_memory();
1499
  $avail = $memory[0];
1500
  /* Be cautious and only allocate 10% of system memory to the state table */
1501
  $max_states = (int) ($avail/10)*1000;
1502
  return $max_states;
1503
}
1504

    
1505
function pfsense_default_tables_size() {
1506
	$current = `pfctl -sm | grep ^tables | awk '{print $4};'`;
1507
	return $current;
1508
}
1509

    
1510
function pfsense_default_table_entries_size() {
1511
	$current = `pfctl -sm | grep table-entries | awk '{print $4};'`;
1512
	return $current;
1513
}
1514

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

    
1551
	if(trim($oldcontents) != trim($contents)) {
1552
		if($g['debug']) {
1553
			log_error(sprintf(gettext('DNSCACHE: Found old IP %1$s and new IP %2$s'), $oldcontents, $contents));
1554
		}
1555
		return ($oldcontents);
1556
	} else {
1557
		return false;
1558
	}
1559
}
1560

    
1561
/*
1562
 * load_crypto() - Load crypto modules if enabled in config.
1563
 */
1564
function load_crypto() {
1565
	global $config, $g;
1566
	$crypto_modules = array('glxsb', 'aesni');
1567

    
1568
	if (!in_array($config['system']['crypto_hardware'], $crypto_modules))
1569
		return false;
1570

    
1571
	$is_loaded = `/sbin/kldstat | /usr/bin/grep -c {$config['system']['crypto_hardware']}`;
1572
	if (!empty($config['system']['crypto_hardware']) && ($is_loaded == 0)) {
1573
		log_error("Loading {$config['system']['crypto_hardware']} cryptographic accelerator module.");
1574
		mwexec("/sbin/kldload {$config['system']['crypto_hardware']}");
1575
	}
1576
}
1577

    
1578
/*
1579
 * load_thermal_hardware() - Load temperature monitor kernel module
1580
 */
1581
function load_thermal_hardware() {
1582
	global $config, $g;
1583
	$thermal_hardware_modules = array('coretemp', 'amdtemp');
1584

    
1585
	if (!in_array($config['system']['thermal_hardware'], $thermal_hardware_modules))
1586
		return false;
1587

    
1588
	$is_loaded = `/sbin/kldstat | /usr/bin/grep -c {$config['system']['thermal_hardware']}`;
1589
	if (!empty($config['system']['thermal_hardware']) && ($is_loaded == 0)) {
1590
		log_error("Loading {$config['system']['thermal_hardware']} thermal monitor module.");
1591
		mwexec("/sbin/kldload {$config['system']['thermal_hardware']}");
1592
	}
1593
}
1594

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

    
1612
function get_freebsd_version() {
1613
	$version = php_uname("r");
1614
	return $version[0];
1615
}
1616

    
1617
function download_file_with_progress_bar($url_file, $destination_file, $readbody = 'read_body', $connect_timeout=60, $timeout=0) {
1618
        global $ch, $fout, $file_size, $downloaded, $config, $first_progress_update;
1619
        $file_size  = 1;
1620
        $downloaded = 1;
1621
	$first_progress_update = TRUE;
1622
        /* open destination file */
1623
        $fout = fopen($destination_file, "wb");
1624

    
1625
        /*
1626
         *      Originally by Author: Keyvan Minoukadeh
1627
         *      Modified by Scott Ullrich to return Content-Length size
1628
         */
1629

    
1630
        $ch = curl_init();
1631
        curl_setopt($ch, CURLOPT_URL, $url_file);
1632
        curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
1633
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1634
        /* Don't verify SSL peers since we don't have the certificates to do so. */
1635
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1636
        curl_setopt($ch, CURLOPT_WRITEFUNCTION, $readbody);
1637
        curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
1638
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connect_timeout);
1639
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1640

    
1641
	if (!empty($config['system']['proxyurl'])) {
1642
		curl_setopt($ch, CURLOPT_PROXY, $config['system']['proxyurl']);
1643
		if (!empty($config['system']['proxyport']))
1644
			curl_setopt($ch, CURLOPT_PROXYPORT, $config['system']['proxyport']);
1645
		if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
1646
			@curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY | CURLAUTH_ANYSAFE);
1647
			curl_setopt($ch, CURLOPT_PROXYUSERPWD, "{$config['system']['proxyuser']}:{$config['system']['proxypass']}");
1648
		}
1649
	}
1650

    
1651
        @curl_exec($ch);
1652
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1653
        if($fout)
1654
                fclose($fout);
1655
        curl_close($ch);
1656
        return ($http_code == 200) ? true : $http_code;
1657
}
1658

    
1659
function read_header($ch, $string) {
1660
        global $file_size, $fout;
1661
        $length = strlen($string);
1662
        $regs = "";
1663
        preg_match("/(Content-Length:) (.*)/", $string, $regs);
1664
        if($regs[2] <> "") {
1665
                $file_size = intval($regs[2]);
1666
        }
1667
        ob_flush();
1668
        return $length;
1669
}
1670

    
1671
function read_body($ch, $string) {
1672
        global $fout, $file_size, $downloaded, $sendto, $static_status, $static_output, $lastseen, $first_progress_update;
1673
		global $pkg_interface;
1674
        $length = strlen($string);
1675
        $downloaded += intval($length);
1676
        if($file_size > 0) {
1677
                $downloadProgress = round(100 * (1 - $downloaded / $file_size), 0);
1678
                $downloadProgress = 100 - $downloadProgress;
1679
        } else
1680
                $downloadProgress = 0;
1681
        if($lastseen <> $downloadProgress and $downloadProgress < 101) {
1682
                if($sendto == "status") {
1683
			if($pkg_interface == "console") {
1684
				if(($downloadProgress % 10) == 0 || $downloadProgress < 10) {
1685
					$tostatus = $static_status . $downloadProgress . "%";
1686
					if ($downloadProgress == 100) {
1687
						$tostatus = $tostatus . "\n";
1688
					}
1689
					update_status($tostatus);
1690
				}
1691
			} else {
1692
				$tostatus = $static_status . $downloadProgress . "%";
1693
				update_status($tostatus);						
1694
			}
1695
                } else {
1696
			if($pkg_interface == "console") {
1697
				if(($downloadProgress % 10) == 0 || $downloadProgress < 10) {
1698
					$tooutput = $static_output . $downloadProgress . "%";
1699
					if ($downloadProgress == 100) {
1700
						$tooutput = $tooutput . "\n";
1701
					}
1702
					update_output_window($tooutput);
1703
				}
1704
			} else {
1705
				$tooutput = $static_output . $downloadProgress . "%";
1706
				update_output_window($tooutput);
1707
			}
1708
                }
1709
				if(($pkg_interface != "console") || (($downloadProgress % 10) == 0) || ($downloadProgress < 10)) {
1710
					update_progress_bar($downloadProgress, $first_progress_update);
1711
					$first_progress_update = FALSE;
1712
				}
1713
                $lastseen = $downloadProgress;
1714
        }
1715
        if($fout)
1716
                fwrite($fout, $string);
1717
        ob_flush();
1718
        return $length;
1719
}
1720

    
1721
/*
1722
 *   update_output_window: update bottom textarea dynamically.
1723
 */
1724
function update_output_window($text) {
1725
        global $pkg_interface;
1726
        $log = preg_replace("/\n/", "\\n", $text);
1727
        if($pkg_interface != "console") {
1728
                echo "\n<script language=\"JavaScript\">\nthis.document.forms[0].output.value = \"" . $log . "\";\n";
1729
				echo "this.document.forms[0].output.scrollTop = this.document.forms[0].output.scrollHeight;\n";	
1730
				echo "</script>";
1731
        }
1732
        /* ensure that contents are written out */
1733
        ob_flush();
1734
}
1735

    
1736
/*
1737
 *   update_status: update top textarea dynamically.
1738
 */
1739
function update_status($status) {
1740
        global $pkg_interface;
1741
        if($pkg_interface == "console") {
1742
                echo "\r{$status}";
1743
        } else {
1744
                echo "\n<script type=\"text/javascript\">this.document.forms[0].status.value=\"" . $status . "\";</script>";
1745
        }
1746
        /* ensure that contents are written out */
1747
        ob_flush();
1748
}
1749

    
1750
/*
1751
 * update_progress_bar($percent, $first_time): updates the javascript driven progress bar.
1752
 */
1753
function update_progress_bar($percent, $first_time) {
1754
        global $pkg_interface;
1755
        if($percent > 100) $percent = 1;
1756
        if($pkg_interface <> "console") {
1757
                echo "\n<script type=\"text/javascript\" language=\"javascript\">";
1758
                echo "\ndocument.progressbar.style.width='" . $percent . "%';";
1759
                echo "\n</script>";
1760
        } else {
1761
		if(!($first_time))
1762
			echo "\x08\x08\x08\x08\x08";
1763
		echo sprintf("%4d%%", $percent);
1764
        }
1765
}
1766

    
1767
/* 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. */
1768
if(!function_exists("split")) {
1769
	function split($seperator, $haystack, $limit = null) {
1770
		log_error("deprecated split() call with seperator '{$seperator}'");
1771
		return preg_split($seperator, $haystack, $limit);
1772
	}
1773
}
1774

    
1775
function update_alias_names_upon_change($section, $field, $new_alias_name, $origname) {
1776
	global $g, $config, $pconfig, $debug;
1777
	if(!$origname) 
1778
		return;
1779

    
1780
	$sectionref = &$config;
1781
	foreach($section as $sectionname) {
1782
		if(is_array($sectionref) && isset($sectionref[$sectionname]))
1783
			$sectionref = &$sectionref[$sectionname];
1784
		else
1785
			return;
1786
	}
1787

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

    
1791
	if(is_array($sectionref)) {
1792
		foreach($sectionref as $itemkey => $item) {
1793
			if($debug) fwrite($fd, "$itemkey\n");
1794

    
1795
			$fieldfound = true;
1796
			$fieldref = &$sectionref[$itemkey];
1797
			foreach($field as $fieldname) {
1798
				if(is_array($fieldref) && isset($fieldref[$fieldname]))
1799
					$fieldref = &$fieldref[$fieldname];
1800
				else {
1801
					$fieldfound = false;
1802
					break;
1803
				}
1804
			}
1805
			if($fieldfound && $fieldref == $origname) {
1806
				if($debug) fwrite($fd, "Setting old alias value $origname to $new_alias_name\n");
1807
				$fieldref = $new_alias_name;
1808
			}
1809
		}
1810
	}
1811

    
1812
	if($debug) fclose($fd);
1813

    
1814
}
1815

    
1816
function update_alias_url_data() {
1817
	global $config, $g;
1818

    
1819
	/* item is a url type */
1820
	$lockkey = lock('config');
1821
	if (is_array($config['aliases']['alias'])) {
1822
		foreach ($config['aliases']['alias'] as $x => $alias) {
1823
			if (empty($alias['aliasurl']))
1824
				continue;
1825

    
1826
			$address = "";
1827
			$isfirst = 0;
1828
			foreach ($alias['aliasurl'] as $alias_url) {
1829
				/* fetch down and add in */
1830
				$temp_filename = tempnam("{$g['tmp_path']}/", "alias_import");
1831
				unlink($temp_filename);
1832
				$fda = fopen("{$g['tmp_path']}/tmpfetch","w");
1833
				fwrite($fda, "/usr/bin/fetch -T 5 -q -o \"{$temp_filename}/aliases\" \"" . $alias_url . "\"");
1834
				fclose($fda);
1835
				mwexec("/bin/mkdir -p {$temp_filename}");
1836
				mwexec("/usr/bin/fetch -T 5 -q -o \"{$temp_filename}/aliases\" \"" . $alias_url . "\"");
1837
				/* if the item is tar gzipped then extract */
1838
				if (stristr($alias_url, ".tgz"))
1839
					process_alias_tgz($temp_filename);
1840
				else if (stristr($alias_url, ".zip"))
1841
					process_alias_unzip($temp_filename);
1842
				if (file_exists("{$temp_filename}/aliases")) {
1843
					$file_contents = file_get_contents("{$temp_filename}/aliases");
1844
					$file_contents = str_replace("#", "\n#", $file_contents);
1845
					$file_contents_split = explode("\n", $file_contents);
1846
					foreach ($file_contents_split as $fc) {
1847
						$tmp = trim($fc);
1848
						if (stristr($fc, "#")) {
1849
							$tmp_split = explode("#", $tmp);
1850
							$tmp = trim($tmp_split[0]);
1851
						}
1852
						if (trim($tmp) <> "") {
1853
							if ($isfirst == 1)
1854
								$address .= " ";
1855
							$address .= $tmp;
1856
							$isfirst = 1;
1857
						}
1858
					}
1859
					mwexec("/bin/rm -rf {$temp_filename}");
1860
				}
1861
			}
1862
			if($isfirst > 0) {
1863
				$config['aliases']['alias'][$x]['address'] = $address;
1864
				$updated = true;
1865
			}
1866
		}
1867
	}
1868
	if ($updated)
1869
		write_config();
1870
	unlock($lockkey);
1871
}
1872

    
1873
function process_alias_unzip($temp_filename) {
1874
	if(!file_exists("/usr/local/bin/unzip"))
1875
		return;
1876
	mwexec("/bin/mv {$temp_filename}/aliases {$temp_filename}/aliases.zip");
1877
	mwexec("/usr/local/bin/unzip {$temp_filename}/aliases.tgz -d {$temp_filename}/aliases/");
1878
	unlink("{$temp_filename}/aliases.zip");
1879
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1880
	/* foreach through all extracted files and build up aliases file */
1881
	$fd = fopen("{$temp_filename}/aliases", "w");
1882
	foreach($files_to_process as $f2p) {
1883
		$file_contents = file_get_contents($f2p);
1884
		fwrite($fd, $file_contents);
1885
		unlink($f2p);
1886
	}
1887
	fclose($fd);
1888
}
1889

    
1890
function process_alias_tgz($temp_filename) {
1891
	if(!file_exists("/usr/bin/tar"))
1892
		return;
1893
	mwexec("/bin/mv {$temp_filename}/aliases {$temp_filename}/aliases.tgz");
1894
	mwexec("/usr/bin/tar xzf {$temp_filename}/aliases.tgz -C {$temp_filename}/aliases/");
1895
	unlink("{$temp_filename}/aliases.tgz");
1896
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1897
	/* foreach through all extracted files and build up aliases file */
1898
	$fd = fopen("{$temp_filename}/aliases", "w");
1899
	foreach($files_to_process as $f2p) {
1900
		$file_contents = file_get_contents($f2p);
1901
		fwrite($fd, $file_contents);
1902
		unlink($f2p);
1903
	}
1904
	fclose($fd);
1905
}
1906

    
1907
function version_compare_dates($a, $b) {
1908
	$a_time = strtotime($a);
1909
	$b_time = strtotime($b);
1910

    
1911
	if ((!$a_time) || (!$b_time)) {
1912
		return FALSE;
1913
	} else {
1914
		if ($a_time < $b_time)
1915
			return -1;
1916
		elseif ($$a_time == $b_time)
1917
			return 0;
1918
		else
1919
			return 1;
1920
	}
1921
}
1922
function version_get_string_value($a) {
1923
	$strs = array(
1924
		0 => "ALPHA-ALPHA",
1925
		2 => "ALPHA",
1926
		3 => "BETA",
1927
		4 => "B",
1928
		5 => "C",
1929
		6 => "D",
1930
		7 => "RC",
1931
		8 => "RELEASE"
1932
	);
1933
	$major = 0;
1934
	$minor = 0;
1935
	foreach ($strs as $num => $str) {
1936
		if (substr($a, 0, strlen($str)) == $str) {
1937
			$major = $num;
1938
			$n = substr($a, strlen($str));
1939
			if (is_numeric($n))
1940
				$minor = $n;
1941
			break;
1942
		}
1943
	}
1944
	return "{$major}.{$minor}";
1945
}
1946
function version_compare_string($a, $b) {
1947
	return version_compare_numeric(version_get_string_value($a), version_get_string_value($b));
1948
}
1949
function version_compare_numeric($a, $b) {
1950
	$a_arr = explode('.', rtrim($a, '.0'));
1951
	$b_arr = explode('.', rtrim($b, '.0'));
1952

    
1953
	foreach ($a_arr as $n => $val) {
1954
		if (array_key_exists($n, $b_arr)) {
1955
			// So far so good, both have values at this minor version level. Compare.
1956
			if ($val > $b_arr[$n])
1957
				return 1;
1958
			elseif ($val < $b_arr[$n])
1959
				return -1;
1960
		} else {
1961
			// a is greater, since b doesn't have any minor version here.
1962
			return 1;
1963
		}
1964
	}
1965
	if (count($b_arr) > count($a_arr)) {
1966
		// b is longer than a, so it must be greater.
1967
		return -1;
1968
	} else {
1969
		// Both a and b are of equal length and value.
1970
		return 0;
1971
	}
1972
}
1973
function pfs_version_compare($cur_time, $cur_text, $remote) {
1974
	// First try date compare
1975
	$v = version_compare_dates($cur_time, $remote);
1976
	if ($v === FALSE) {
1977
		// If that fails, try to compare by string
1978
		// Before anything else, simply test if the strings are equal
1979
		if (($cur_text == $remote) || ($cur_time == $remote))
1980
			return 0;
1981
		list($cur_num, $cur_str) = explode('-', $cur_text);
1982
		list($rem_num, $rem_str) = explode('-', $remote);
1983

    
1984
		// First try to compare the numeric parts of the version string.
1985
		$v = version_compare_numeric($cur_num, $rem_num);
1986

    
1987
		// If the numeric parts are the same, compare the string parts.
1988
		if ($v == 0)
1989
			return version_compare_string($cur_str, $rem_str);
1990
	}
1991
	return $v;
1992
}
1993
function process_alias_urltable($name, $url, $freq, $forceupdate=false) {
1994
	$urltable_prefix = "/var/db/aliastables/";
1995
	$urltable_filename = $urltable_prefix . $name . ".txt";
1996

    
1997
	// Make the aliases directory if it doesn't exist
1998
	if (!file_exists($urltable_prefix)) {
1999
		mkdir($urltable_prefix);
2000
	} elseif (!is_dir($urltable_prefix)) {
2001
		unlink($urltable_prefix);
2002
		mkdir($urltable_prefix);
2003
	}
2004

    
2005
	// If the file doesn't exist or is older than update_freq days, fetch a new copy.
2006
	if (!file_exists($urltable_filename)
2007
		|| ((time() - filemtime($urltable_filename)) > ($freq * 86400))
2008
		|| $forceupdate) {
2009

    
2010
		// Try to fetch the URL supplied
2011
		conf_mount_rw();
2012
		unlink_if_exists($urltable_filename . ".tmp");
2013
		// 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.
2014
		mwexec("/usr/bin/fetch -T 5 -q -o " . escapeshellarg($urltable_filename . ".tmp") . " " . escapeshellarg($url));
2015
		// Remove comments. Might need some grep-fu to only allow lines that look like IPs/subnets
2016
		if (file_exists($urltable_filename . ".tmp")) {
2017
			mwexec("/usr/bin/sed 's/\;.*//g' ". escapeshellarg($urltable_filename . ".tmp") . "| /usr/bin/egrep -v '^[[:space:]]*$|^#' > " . escapeshellarg($urltable_filename));
2018
			unlink_if_exists($urltable_filename . ".tmp");
2019
		} else
2020
			mwexec("/usr/bin/touch {$urltable_filename}");
2021
		conf_mount_ro();
2022
		return true;
2023
	} else {
2024
		// File exists, and it doesn't need updated.
2025
		return -1;
2026
	}
2027
}
2028
function get_real_slice_from_glabel($label) {
2029
	$label = escapeshellarg($label);
2030
	return trim(`/sbin/glabel list | /usr/bin/grep -B2 ufs/{$label} | /usr/bin/head -n 1 | /usr/bin/cut -f3 -d' '`);
2031
}
2032
function nanobsd_get_boot_slice() {
2033
	return trim(`/sbin/mount | /usr/bin/grep pfsense | /usr/bin/cut -d'/' -f4 | /usr/bin/cut -d' ' -f1`);
2034
}
2035
function nanobsd_get_boot_drive() {
2036
	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`);
2037
}
2038
function nanobsd_get_active_slice() {
2039
	$boot_drive = nanobsd_get_boot_drive();
2040
	$active = trim(`gpart show $boot_drive | grep '\[active\]' | awk '{print $3;}'`);
2041

    
2042
	return "{$boot_drive}s{$active}";
2043
}
2044
function nanobsd_get_size() {
2045
	return strtoupper(file_get_contents("/etc/nanosize.txt"));
2046
}
2047
function nanobsd_switch_boot_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
	if ($BOOTFLASH == $ACTIVE_SLICE) {
2054
		$slice = $TOFLASH;
2055
	} else {
2056
		$slice = $BOOTFLASH;
2057
	}
2058

    
2059
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
2060
	ob_implicit_flush(1);
2061
	if(strstr($slice, "s2")) {
2062
		$ASLICE="2";
2063
		$AOLDSLICE="1";
2064
		$AGLABEL_SLICE="pfsense1";
2065
		$AUFS_ID="1";
2066
		$AOLD_UFS_ID="0";
2067
	} else {
2068
		$ASLICE="1";
2069
		$AOLDSLICE="2";
2070
		$AGLABEL_SLICE="pfsense0";
2071
		$AUFS_ID="0";
2072
		$AOLD_UFS_ID="1";
2073
	}
2074
	$ATOFLASH="{$BOOT_DRIVE}s{$ASLICE}";
2075
	$ACOMPLETE_PATH="{$BOOT_DRIVE}s{$ASLICE}a";
2076
	$ABOOTFLASH="{$BOOT_DRIVE}s{$AOLDSLICE}";
2077
	conf_mount_rw();
2078
	exec("sysctl kern.geom.debugflags=16");
2079
	exec("gpart set -a active -i {$ASLICE} {$BOOT_DRIVE}");
2080
	exec("/usr/sbin/boot0cfg -s {$ASLICE} -v /dev/{$BOOT_DRIVE}");
2081
	// We can't update these if they are mounted now.
2082
	if ($BOOTFLASH != $slice) {
2083
		exec("/sbin/tunefs -L ${AGLABEL_SLICE} /dev/$ACOMPLETE_PATH");
2084
		nanobsd_update_fstab($AGLABEL_SLICE, $ACOMPLETE_PATH, $AOLD_UFS_ID, $AUFS_ID);
2085
	}
2086
	exec("/sbin/sysctl kern.geom.debugflags=0");
2087
	conf_mount_ro();
2088
}
2089
function nanobsd_clone_slice() {
2090
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2091
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2092
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2093
	nanobsd_detect_slice_info();
2094

    
2095
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
2096
	ob_implicit_flush(1);
2097
	exec("/sbin/sysctl kern.geom.debugflags=16");
2098
	exec("/bin/dd if=/dev/zero of=/dev/{$TOFLASH} bs=1m count=1");
2099
	exec("/bin/dd if=/dev/{$BOOTFLASH} of=/dev/{$TOFLASH} bs=64k");
2100
	exec("/sbin/tunefs -L {$GLABEL_SLICE} /dev/{$COMPLETE_PATH}");
2101
	$status = nanobsd_update_fstab($GLABEL_SLICE, $COMPLETE_PATH, $OLD_UFS_ID, $UFS_ID);
2102
	exec("/sbin/sysctl kern.geom.debugflags=0");
2103
	if($status) {
2104
		return false;
2105
	} else {
2106
		return true;
2107
	}
2108
}
2109
function nanobsd_update_fstab($gslice, $complete_path, $oldufs, $newufs) {
2110
	$tmppath = "/tmp/{$gslice}";
2111
	$fstabpath = "/tmp/{$gslice}/etc/fstab";
2112

    
2113
	exec("/bin/mkdir {$tmppath}");
2114
	exec("/sbin/fsck_ufs -y /dev/{$complete_path}");
2115
	exec("/sbin/mount /dev/ufs/{$gslice} {$tmppath}");
2116
	exec("/bin/cp /etc/fstab {$fstabpath}");
2117

    
2118
	if (!file_exists($fstabpath)) {
2119
		$fstab = <<<EOF
2120
/dev/ufs/{$gslice} / ufs ro,noatime 1 1
2121
/dev/ufs/cf /cf ufs ro,noatime 1 1
2122
EOF;
2123
		if (file_put_contents($fstabpath, $fstab))
2124
			$status = true;
2125
		else
2126
			$status = false;
2127
	} else {
2128
		$status = exec("sed -i \"\" \"s/pfsense{$oldufs}/pfsense{$newufs}/g\" {$fstabpath}");
2129
	}
2130
	exec("/sbin/umount {$tmppath}");
2131
	exec("/bin/rmdir {$tmppath}");
2132

    
2133
	return $status;
2134
}
2135
function nanobsd_detect_slice_info() {
2136
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2137
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2138
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2139

    
2140
	$BOOT_DEVICE=nanobsd_get_boot_slice();
2141
	$REAL_BOOT_DEVICE=get_real_slice_from_glabel($BOOT_DEVICE);
2142
	$BOOT_DRIVE=nanobsd_get_boot_drive();
2143
	$ACTIVE_SLICE=nanobsd_get_active_slice();
2144

    
2145
	// Detect which slice is active and set information.
2146
	if(strstr($REAL_BOOT_DEVICE, "s1")) {
2147
		$SLICE="2";
2148
		$OLDSLICE="1";
2149
		$GLABEL_SLICE="pfsense1";
2150
		$UFS_ID="1";
2151
		$OLD_UFS_ID="0";
2152

    
2153
	} else {
2154
		$SLICE="1";
2155
		$OLDSLICE="2";
2156
		$GLABEL_SLICE="pfsense0";
2157
		$UFS_ID="0";
2158
		$OLD_UFS_ID="1";
2159
	}
2160
	$TOFLASH="{$BOOT_DRIVE}s{$SLICE}";
2161
	$COMPLETE_PATH="{$BOOT_DRIVE}s{$SLICE}a";
2162
	$COMPLETE_BOOT_PATH="{$BOOT_DRIVE}s{$OLDSLICE}";
2163
	$BOOTFLASH="{$BOOT_DRIVE}s{$OLDSLICE}";
2164
}
2165

    
2166
function nanobsd_friendly_slice_name($slicename) {
2167
	global $g;
2168
	return strtolower(str_ireplace('pfsense', $g['product_name'], $slicename));
2169
}
2170

    
2171
function get_include_contents($filename) {
2172
    if (is_file($filename)) {
2173
        ob_start();
2174
        include $filename;
2175
        $contents = ob_get_contents();
2176
        ob_end_clean();
2177
        return $contents;
2178
    }
2179
    return false;
2180
}
2181

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

    
2317
function get_country_name($country_code) {
2318
	if ($country_code != "ALL" && strlen($country_code) != 2)
2319
		return "";
2320

    
2321
	$country_names_xml = "/usr/local/share/mobile-broadband-provider-info/iso_3166-1_list_en.xml";
2322
	$country_names_contents = file_get_contents($country_names_xml);
2323
	$country_names = xml2array($country_names_contents);
2324

    
2325
	if($country_code == "ALL") {
2326
		$country_list = array();
2327
		foreach($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2328
			$country_list[] = array( "code" => $country['ISO_3166-1_Alpha-2_Code_element'],
2329
						 "name" => ucwords(strtolower($country['ISO_3166-1_Country_name'])) );
2330
		}
2331
		return $country_list;
2332
	}
2333

    
2334
	foreach ($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2335
		if ($country['ISO_3166-1_Alpha-2_Code_element'] == strtoupper($country_code)) {
2336
			return ucwords(strtolower($country['ISO_3166-1_Country_name']));
2337
		}
2338
	}
2339
	return "";
2340
}
2341

    
2342
/* sort by interface only, retain the original order of rules that apply to
2343
   the same interface */
2344
function filter_rules_sort() {
2345
	global $config;
2346

    
2347
	/* mark each rule with the sequence number (to retain the order while sorting) */
2348
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2349
		$config['filter']['rule'][$i]['seq'] = $i;
2350

    
2351
	usort($config['filter']['rule'], "filter_rules_compare");
2352

    
2353
	/* strip the sequence numbers again */
2354
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2355
		unset($config['filter']['rule'][$i]['seq']);
2356
}
2357
function filter_rules_compare($a, $b) {
2358
	if (isset($a['floating']) && isset($b['floating']))
2359
		return $a['seq'] - $b['seq'];
2360
	else if (isset($a['floating']))
2361
		return -1;
2362
	else if (isset($b['floating']))
2363
		return 1;
2364
	else if ($a['interface'] == $b['interface'])
2365
		return $a['seq'] - $b['seq'];
2366
	else
2367
		return compare_interface_friendly_names($a['interface'], $b['interface']);
2368
}
2369

    
2370
function generate_ipv6_from_mac($mac) {
2371
	$elements = explode(":", $mac);
2372
	if(count($elements) <> 6)
2373
		return false;
2374

    
2375
	$i = 0;
2376
	$ipv6 = "fe80::";
2377
	foreach($elements as $byte) {
2378
		if($i == 0) {
2379
			$hexadecimal =  substr($byte, 1, 2);
2380
			$bitmap = base_convert($hexadecimal, 16, 2);
2381
			$bitmap = str_pad($bitmap, 4, "0", STR_PAD_LEFT);
2382
			$bitmap = substr($bitmap, 0, 2) ."1". substr($bitmap, 3,4);
2383
			$byte = substr($byte, 0, 1) . base_convert($bitmap, 2, 16);
2384
		}
2385
		$ipv6 .= $byte;
2386
		if($i == 1) {
2387
			$ipv6 .= ":";
2388
		}
2389
		if($i == 3) {
2390
			$ipv6 .= ":";
2391
		}
2392
		if($i == 2) {
2393
			$ipv6 .= "ff:fe";
2394
		}
2395
		
2396
		$i++;
2397
	}	
2398
	return $ipv6;
2399
}
2400

    
2401
/****f* pfsense-utils/load_mac_manufacturer_table
2402
 * NAME
2403
 *   load_mac_manufacturer_table
2404
 * INPUTS
2405
 *   none
2406
 * RESULT
2407
 *   returns associative array with MAC-Manufacturer pairs
2408
 ******/
2409
function load_mac_manufacturer_table() {
2410
	/* load MAC-Manufacture data from the file */
2411
	$macs = false;
2412
	if (file_exists("/usr/local/share/nmap/nmap-mac-prefixes"))
2413
		$macs=file("/usr/local/share/nmap/nmap-mac-prefixes");
2414
	if ($macs){
2415
		foreach ($macs as $line){
2416
			if (preg_match('/([0-9A-Fa-f]{6}) (.*)$/', $line, $matches)){
2417
				/* store values like this $mac_man['000C29']='VMware' */
2418
				$mac_man["$matches[1]"]=$matches[2];
2419
			}
2420
		}
2421
 		return $mac_man;
2422
	} else
2423
		return -1;
2424

    
2425
}
2426

    
2427
/****f* pfsense-utils/is_ipaddr_configured
2428
 * NAME
2429
 *   is_ipaddr_configured
2430
 * INPUTS
2431
 *   IP Address to check.
2432
 * RESULT
2433
 *   returns true if the IP Address is
2434
 *   configured and present on this device.
2435
*/
2436
function is_ipaddr_configured($ipaddr) {
2437
	$interface_list_ips = get_configured_ip_addresses();
2438
	foreach($interface_list_ips as $ilips) {
2439
		if(strcasecmp($ipaddr, $ilips) == 0) 
2440
				return true;
2441
	}	
2442
}
2443

    
2444
/****f* pfsense-utils/pfSense_handle_custom_code
2445
 * NAME
2446
 *   pfSense_handle_custom_code
2447
 * INPUTS
2448
 *   directory name to process
2449
 * RESULT
2450
 *   globs the directory and includes the files
2451
 */
2452
function pfSense_handle_custom_code($src_dir) {
2453
	// Allow extending of the nat edit page and include custom input validation 
2454
	if(is_dir("$src_dir")) {
2455
		$cf = glob($src_dir . "/*.inc");
2456
		foreach($cf as $nf) {
2457
			if($nf == "." || $nf == "..") 
2458
				continue;
2459
			// Include the extra handler
2460
			include("$nf");
2461
		}
2462
	}
2463
}
2464

    
2465
function set_language($lang = 'en_US', $encoding = "ISO8859-1") {
2466
	putenv("LANG={$lang}.{$encoding}");
2467
	setlocale(LC_ALL, "{$lang}.{$encoding}");
2468
	textdomain("pfSense");
2469
	bindtextdomain("pfSense","/usr/local/share/locale");
2470
	bind_textdomain_codeset("pfSense","{$lang}.{$encoding}");
2471
}
2472

    
2473
function get_locale_list() {
2474
	$locales = array(
2475
		"en_US" => gettext("English"),
2476
		"pt_BR" => gettext("Portuguese (Brazil)"),
2477
	);
2478
	asort($locales);
2479
	return $locales;
2480
}
2481

    
2482
function return_hex_ipv4($ipv4) {
2483
	if(!is_ipaddrv4($ipv4))
2484
		return(false);
2485
	
2486
	/* we need the hex form of the interface IPv4 address */
2487
	$ip4arr = explode(".", $ipv4);
2488
	$hexwanv4 = "";
2489
	foreach($ip4arr as $octet)
2490
		$hexwanv4 .= sprintf("%02x", $octet);
2491

    
2492
	return($hexwanv4);
2493
}
2494

    
2495
function convert_ipv6_to_128bit($ipv6) {
2496
	if(!is_ipaddrv6($ipv6))
2497
		return(false);
2498

    
2499
	$ip6arr = array();
2500
	$ip6prefix = Net_IPv6::uncompress($ipv6);
2501
	$ip6arr = explode(":", $ip6prefix);
2502
	/* binary presentation of the prefix for all 128 bits. */
2503
	$ip6prefixbin = "";
2504
	foreach($ip6arr as $element) {
2505
		$ip6prefixbin .= sprintf("%016b", hexdec($element));
2506
	}
2507
	return($ip6prefixbin);
2508
}
2509

    
2510
function convert_128bit_to_ipv6($ip6bin) {
2511
	if(strlen($ip6bin) <> 128)
2512
		return(false);
2513

    
2514
	$ip6arr = array();
2515
	$ip6binarr = array();
2516
	$ip6binarr = str_split($ip6bin, 16);
2517
	foreach($ip6binarr as $binpart)
2518
		$ip6arr[] = dechex(bindec($binpart));
2519
	$ip6addr = Net_IPv6::compress(implode(":", $ip6arr));
2520

    
2521
	return($ip6addr);
2522
}
2523

    
2524

    
2525
/* Returns the calculated bit length of the prefix delegation from the WAN interface */
2526
/* DHCP-PD is variable, calculate from the prefix-len on the WAN interface */
2527
/* 6rd is variable, calculate from 64 - (v6 prefixlen - (32 - v4 prefixlen)) */
2528
/* 6to4 is 16 bits, e.g. 65535 */
2529
function calculate_ipv6_delegation_length($if) {
2530
	global $config;
2531

    
2532
	if(!is_array($config['interfaces'][$if]))
2533
		return false;
2534

    
2535
	switch($config['interfaces'][$if]['ipaddrv6']) {
2536
		case "6to4":
2537
			$pdlen = 16;
2538
			break;
2539
		case "6rd":
2540
			$rd6cfg = $config['interfaces'][$if];
2541
			$rd6plen = explode("/", $rd6cfg['prefix-6rd']);
2542
			$pdlen = (64 - ($rd6plen[1] + (32 - $rd6cfg['prefix-6rd-v4plen'])));
2543
			break;
2544
		case "dhcp6":
2545
			$dhcp6cfg = $config['interfaces'][$if];
2546
			$pdlen = $dhcp6cfg['dhcp6-ia-pd-len'];
2547
			break;
2548
		default:
2549
			$pdlen = 0;
2550
			break;
2551
	}
2552
	return($pdlen);
2553
}
2554

    
2555
function huawei_rssi_to_string($rssi) {
2556
	$dbm = array();
2557
	$i = 0;
2558
	$dbstart = -51;
2559
	while($i < 31) {
2560
		$dbm[$i] = $dbstart - ($i * 2);
2561
		$i++;
2562
	}
2563
	$percent = round(($rssi / 31) * 100);
2564
	$string = "rssi:8 level:{$dbm[$rssi]}dBm percent:{$percent}%";
2565
	return $string;
2566
}
2567

    
2568
function huawei_mode_to_string($mode, $submode) {
2569
	$modes[0] = "None";
2570
	$modes[1] = "AMPS"; 
2571
	$modes[2] = "CDMA";
2572
	$modes[3] = "GSM/GPRS";
2573
	$modes[4] = "HDR";
2574
	$modes[5] = "WCDMA";
2575
	$modes[6] = "GPS"; 
2576

    
2577
	$submodes[0] = "No Service";
2578
	$submodes[1] = "GSM";
2579
	$submodes[2] = "GPRS";
2580
	$submodes[3] = "EDGE";
2581
	$submodes[4] = "WCDMA";
2582
	$submodes[5] = "HSDPA";
2583
	$submodes[6] = "HSUPA";
2584
	$submodes[7] = "HSDPA+HSUPA";
2585
	$submodes[8] = "TD-SCDMA";
2586
	$submodes[9] = "HSPA+";
2587
	$string = "{$modes[$mode]}, {$submodes[$submode]} Mode";
2588
	return $string;
2589
}
2590

    
2591
function huawei_service_to_string($state) {
2592
	$modes[0] = "No";
2593
	$modes[1] = "Restricted"; 
2594
	$modes[2] = "Valid";
2595
	$modes[3] = "Restricted Regional";
2596
	$modes[4] = "Powersaving";
2597
	$string = "{$modes[$state]} Service";
2598
	return $string;
2599
}
2600

    
2601
function huawei_simstate_to_string($state) {
2602
	$modes[0] = "Invalid SIM/locked";
2603
	$modes[1] = "Valid SIM"; 
2604
	$modes[2] = "Invalid SIM CS";
2605
	$modes[3] = "Invalid SIM PS";
2606
	$modes[4] = "Invalid SIM CS/PS";
2607
	$modes[255] = "Missing SIM";
2608
	$string = "{$modes[$state]} State";
2609
	return $string;
2610
}
2611

    
2612
function zte_rssi_to_string($rssi) {
2613
	return huawei_rssi_to_string($rssi);
2614
}
2615

    
2616
function zte_mode_to_string($mode, $submode) {
2617
	$modes[0] = "No Service";
2618
	$modes[1] = "Limited Service"; 
2619
	$modes[2] = "GPRS";
2620
	$modes[3] = "GSM";
2621
	$modes[4] = "UMTS";
2622
	$modes[5] = "EDGE";
2623
	$modes[6] = "HSDPA"; 
2624

    
2625
	$submodes[0] = "CS_ONLY";
2626
	$submodes[1] = "PS_ONLY";
2627
	$submodes[2] = "CS_PS";
2628
	$submodes[3] = "CAMPED";
2629
	$string = "{$modes[$mode]}, {$submodes[$submode]} Mode";
2630
	return $string;
2631
}
2632

    
2633
function zte_service_to_string($state) {
2634
	$modes[0] = "Initializing";
2635
	$modes[1] = "Network Lock error"; 
2636
	$modes[2] = "Network Locked";
2637
	$modes[3] = "Unlocked or correct MCC/MNC";
2638
	$string = "{$modes[$state]} Service";
2639
	return $string;
2640
}
2641

    
2642
function zte_simstate_to_string($state) {
2643
	$modes[0] = "No action";
2644
	$modes[1] = "Network lock"; 
2645
	$modes[2] = "(U)SIM card lock";
2646
	$modes[3] = "Network Lock and (U)SIM card Lock";
2647
	$string = "{$modes[$state]} State";
2648
	return $string;
2649
}
2650
?>
(38-38/66)