Projet

Général

Profil

Télécharger (76,7 ko) Statistiques
| Branche: | Tag: | Révision:

univnautes / etc / inc / pfsense-utils.inc @ 6657d23c

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_natpfruleint_access
44
 * NAME
45
 *   have_natpfruleint_access
46
 * INPUTS
47
 *	none
48
 * RESULT
49
 *   returns true if user has access to edit a specific firewall nat port forward interface
50
 ******/
51
function have_natpfruleint_access($if) {
52
	$security_url = "firewall_nat_edit.php?if=". strtolower($if);
53
	if(isAllowedPage($security_url, $allowed))
54
		return true;
55
	return false;
56
}
57

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

    
73
/****f* pfsense-utils/does_url_exist
74
 * NAME
75
 *   does_url_exist
76
 * INPUTS
77
 *	none
78
 * RESULT
79
 *   returns true if a url is available
80
 ******/
81
function does_url_exist($url) {
82
	$fd = fopen("$url","r");
83
	if($fd) {
84
		fclose($fd);
85
		return true;
86
	} else {
87
		return false;
88
	}
89
}
90

    
91
/****f* pfsense-utils/is_private_ip
92
 * NAME
93
 *   is_private_ip
94
 * INPUTS
95
 *	none
96
 * RESULT
97
 *   returns true if an ip address is in a private range
98
 ******/
99
function is_private_ip($iptocheck) {
100
	$isprivate = false;
101
	$ip_private_list=array(
102
		"10.0.0.0/8",
103
		"100.64.0.0/10",
104
		"172.16.0.0/12",
105
		"192.168.0.0/16",
106
	);
107
	foreach($ip_private_list as $private) {
108
		if(ip_in_subnet($iptocheck,$private)==true)
109
			$isprivate = true;
110
	}
111
	return $isprivate;
112
}
113

    
114
/****f* pfsense-utils/get_tmp_file
115
 * NAME
116
 *   get_tmp_file
117
 * INPUTS
118
 *	none
119
 * RESULT
120
 *   returns a temporary filename
121
 ******/
122
function get_tmp_file() {
123
	global $g;
124
	return "{$g['tmp_path']}/tmp-" . time();
125
}
126

    
127
/****f* pfsense-utils/get_dns_servers
128
 * NAME
129
 *   get_dns_servres - get system dns servers
130
 * INPUTS
131
 *   $dns_servers - an array of the dns servers
132
 * RESULT
133
 *   null
134
 ******/
135
function get_dns_servers() {
136
	$dns_servers = array();
137
	$dns_s = file("/etc/resolv.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
138
	foreach($dns_s as $dns) {
139
		$matches = "";
140
		if (preg_match("/nameserver (.*)/", $dns, $matches))
141
			$dns_servers[] = $matches[1];
142
	}
143
	return array_unique($dns_servers);
144
}
145

    
146
/****f* pfsense-utils/enable_hardware_offloading
147
 * NAME
148
 *   enable_hardware_offloading - Enable a NIC's supported hardware features.
149
 * INPUTS
150
 *   $interface	- string containing the physical interface to work on.
151
 * RESULT
152
 *   null
153
 * NOTES
154
 *   This function only supports the fxp driver's loadable microcode.
155
 ******/
156
function enable_hardware_offloading($interface) {
157
	global $g, $config;
158

    
159
	if(isset($config['system']['do_not_use_nic_microcode']))
160
		return;
161

    
162
	/* translate wan, lan, opt -> real interface if needed */
163
	$int = get_real_interface($interface);
164
	if(empty($int))
165
		return;
166
	$int_family = preg_split("/[0-9]+/", $int);
167
	$supported_ints = array('fxp');
168
	if (in_array($int_family, $supported_ints)) {
169
		if(does_interface_exist($int))
170
			pfSense_interface_flags($int, IFF_LINK0);
171
	}
172

    
173
	return;
174
}
175

    
176
/****f* pfsense-utils/interface_supports_polling
177
 * NAME
178
 *   checks to see if an interface supports polling according to man polling
179
 * INPUTS
180
 *
181
 * RESULT
182
 *   true or false
183
 * NOTES
184
 *
185
 ******/
186
function interface_supports_polling($iface) {
187
	$opts = pfSense_get_interface_addresses($iface);
188
	if (is_array($opts) && isset($opts['caps']['polling']))
189
		return true;
190

    
191
	return false;
192
}
193

    
194
/****f* pfsense-utils/is_alias_inuse
195
 * NAME
196
 *   checks to see if an alias is currently in use by a rule
197
 * INPUTS
198
 *
199
 * RESULT
200
 *   true or false
201
 * NOTES
202
 *
203
 ******/
204
function is_alias_inuse($alias) {
205
	global $g, $config;
206

    
207
	if($alias == "") return false;
208
	/* loop through firewall rules looking for alias in use */
209
	if(is_array($config['filter']['rule']))
210
		foreach($config['filter']['rule'] as $rule) {
211
			if($rule['source']['address'])
212
				if($rule['source']['address'] == $alias)
213
					return true;
214
			if($rule['destination']['address'])
215
				if($rule['destination']['address'] == $alias)
216
					return true;
217
		}
218
	/* loop through nat rules looking for alias in use */
219
	if(is_array($config['nat']['rule']))
220
		foreach($config['nat']['rule'] as $rule) {
221
			if($rule['target'] && $rule['target'] == $alias)
222
				return true;
223
			if($rule['source']['address'] && $rule['source']['address'] == $alias)
224
				return true;
225
			if($rule['destination']['address'] && $rule['destination']['address'] == $alias)
226
				return true;
227
		}
228
	return false;
229
}
230

    
231
/****f* pfsense-utils/is_schedule_inuse
232
 * NAME
233
 *   checks to see if a schedule is currently in use by a rule
234
 * INPUTS
235
 *
236
 * RESULT
237
 *   true or false
238
 * NOTES
239
 *
240
 ******/
241
function is_schedule_inuse($schedule) {
242
	global $g, $config;
243

    
244
	if($schedule == "") return false;
245
	/* loop through firewall rules looking for schedule in use */
246
	if(is_array($config['filter']['rule']))
247
		foreach($config['filter']['rule'] as $rule) {
248
			if($rule['sched'] == $schedule)
249
				return true;
250
		}
251
	return false;
252
}
253

    
254
/****f* pfsense-utils/setup_polling
255
 * NAME
256
 *   sets up polling
257
 * INPUTS
258
 *
259
 * RESULT
260
 *   null
261
 * NOTES
262
 *
263
 ******/
264
function setup_polling() {
265
	global $g, $config;
266

    
267
	if (isset($config['system']['polling']))
268
		mwexec("/sbin/sysctl kern.polling.idle_poll=1");
269
	else
270
		mwexec("/sbin/sysctl kern.polling.idle_poll=0");
271

    
272
	if($config['system']['polling_each_burst'])
273
		mwexec("/sbin/sysctl kern.polling.each_burst={$config['system']['polling_each_burst']}");
274
	if($config['system']['polling_burst_max'])
275
		mwexec("/sbin/sysctl kern.polling.burst_max={$config['system']['polling_burst_max']}");
276
	if($config['system']['polling_user_frac'])
277
		mwexec("/sbin/sysctl kern.polling.user_frac={$config['system']['polling_user_frac']}");
278
}
279

    
280
/****f* pfsense-utils/setup_microcode
281
 * NAME
282
 *   enumerates all interfaces and calls enable_hardware_offloading which
283
 *   enables a NIC's supported hardware features.
284
 * INPUTS
285
 *
286
 * RESULT
287
 *   null
288
 * NOTES
289
 *   This function only supports the fxp driver's loadable microcode.
290
 ******/
291
function setup_microcode() {
292

    
293
	/* if list */
294
	$ifs = get_interface_arr();
295

    
296
	foreach($ifs as $if)
297
		enable_hardware_offloading($if);
298
}
299

    
300
/****f* pfsense-utils/get_carp_status
301
 * NAME
302
 *   get_carp_status - Return whether CARP is enabled or disabled.
303
 * RESULT
304
 *   boolean	- true if CARP is enabled, false if otherwise.
305
 ******/
306
function get_carp_status() {
307
	/* grab the current status of carp */
308
	$status = `/sbin/sysctl -n net.inet.carp.allow`;
309
	return (intval($status) > 0);
310
}
311

    
312
/*
313
 * convert_ip_to_network_format($ip, $subnet): converts an ip address to network form
314

    
315
 */
316
function convert_ip_to_network_format($ip, $subnet) {
317
	$ipsplit = explode('.', $ip);
318
	$string = $ipsplit[0] . "." . $ipsplit[1] . "." . $ipsplit[2] . ".0/" . $subnet;
319
	return $string;
320
}
321

    
322
/*
323
 * get_carp_interface_status($carpinterface): returns the status of a carp ip
324
 */
325
function get_carp_interface_status($carpinterface) {
326
	$carp_query = "";
327
	exec("/sbin/ifconfig $carpinterface | /usr/bin/grep -v grep | /usr/bin/grep carp:", $carp_query);
328
	foreach($carp_query as $int) {
329
		if(stristr($int, "MASTER"))
330
			return gettext("MASTER");
331
		if(stristr($int, "BACKUP"))
332
			return gettext("BACKUP");
333
		if(stristr($int, "INIT"))
334
			return gettext("INIT");
335
	}
336
	return;
337
}
338

    
339
/*
340
 * get_pfsync_interface_status($pfsyncinterface): returns the status of a pfsync
341
 */
342
function get_pfsync_interface_status($pfsyncinterface) {
343
	if (!does_interface_exist($pfsyncinterface))
344
		return;
345

    
346
	return exec_command("/sbin/ifconfig {$pfsyncinterface} | /usr/bin/awk '/pfsync:/ {print \$5}'");
347
}
348

    
349
/*
350
 * add_rule_to_anchor($anchor, $rule): adds the specified rule to an anchor
351
 */
352
function add_rule_to_anchor($anchor, $rule, $label) {
353
	mwexec("echo " . escapeshellarg($rule) . " | /sbin/pfctl -a " . escapeshellarg($anchor) . ":" . escapeshellarg($label) . " -f -");
354
}
355

    
356
/*
357
 * remove_text_from_file
358
 * remove $text from file $file
359
 */
360
function remove_text_from_file($file, $text) {
361
	if(!file_exists($file) && !is_writable($file))
362
		return;
363
	$filecontents = file_get_contents($file);
364
	$text = str_replace($text, "", $filecontents);
365
	@file_put_contents($file, $text);
366
}
367

    
368
/*
369
 * add_text_to_file($file, $text): adds $text to $file.
370
 * replaces the text if it already exists.
371
 */
372
function add_text_to_file($file, $text, $replace = false) {
373
	if(file_exists($file) and is_writable($file)) {
374
		$filecontents = file($file);
375
		$filecontents = array_map('rtrim', $filecontents);
376
		array_push($filecontents, $text);
377
		if ($replace)
378
			$filecontents = array_unique($filecontents);
379

    
380
		$file_text = implode("\n", $filecontents);
381

    
382
		@file_put_contents($file, $file_text);
383
		return true;
384
	}
385
	return false;
386
}
387

    
388
/*
389
 *   after_sync_bump_adv_skew(): create skew values by 1S
390
 */
391
function after_sync_bump_adv_skew() {
392
	global $config, $g;
393
	$processed_skew = 1;
394
	$a_vip = &$config['virtualip']['vip'];
395
	foreach ($a_vip as $vipent) {
396
		if($vipent['advskew'] <> "") {
397
			$processed_skew = 1;
398
			$vipent['advskew'] = $vipent['advskew']+1;
399
		}
400
	}
401
	if($processed_skew == 1)
402
		write_config(gettext("After synch increase advertising skew"));
403
}
404

    
405
/*
406
 * get_filename_from_url($url): converts a url to its filename.
407
 */
408
function get_filename_from_url($url) {
409
	return basename($url);
410
}
411

    
412
/*
413
 *   get_dir: return an array of $dir
414
 */
415
function get_dir($dir) {
416
	$dir_array = array();
417
	$d = dir($dir);
418
	while (false !== ($entry = $d->read())) {
419
		array_push($dir_array, $entry);
420
	}
421
	$d->close();
422
	return $dir_array;
423
}
424

    
425
/****f* pfsense-utils/WakeOnLan
426
 * NAME
427
 *   WakeOnLan - Wake a machine up using the wake on lan format/protocol
428
 * RESULT
429
 *   true/false - true if the operation was successful
430
 ******/
431
function WakeOnLan($addr, $mac)
432
{
433
	$addr_byte = explode(':', $mac);
434
	$hw_addr = '';
435

    
436
	for ($a=0; $a < 6; $a++)
437
		$hw_addr .= chr(hexdec($addr_byte[$a]));
438

    
439
	$msg = chr(255).chr(255).chr(255).chr(255).chr(255).chr(255);
440

    
441
	for ($a = 1; $a <= 16; $a++)
442
		$msg .= $hw_addr;
443

    
444
	// send it to the broadcast address using UDP
445
	$s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
446
	if ($s == false) {
447
		log_error(gettext("Error creating socket!"));
448
		log_error(sprintf(gettext("Error code is '%1\$s' - %2\$s"), socket_last_error($s), socket_strerror(socket_last_error($s))));
449
	} else {
450
		// setting a broadcast option to socket:
451
		$opt_ret =  socket_set_option($s, 1, 6, TRUE);
452
		if($opt_ret < 0)
453
			log_error(sprintf(gettext("setsockopt() failed, error: %s"), strerror($opt_ret)));
454
		$e = socket_sendto($s, $msg, strlen($msg), 0, $addr, 2050);
455
		socket_close($s);
456
		log_error(sprintf(gettext('Magic Packet sent (%1$s) to {%2$s} MAC=%3$s'), $e, $addr, $mac));
457
		return true;
458
	}
459

    
460
	return false;
461
}
462

    
463
/*
464
 * reverse_strrchr($haystack, $needle):  Return everything in $haystack up to the *last* instance of $needle.
465
 *					 Useful for finding paths and stripping file extensions.
466
 */
467
function reverse_strrchr($haystack, $needle) {
468
	if (!is_string($haystack))
469
		return;
470
	return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) +1 ) : false;
471
}
472

    
473
/*
474
 *  backup_config_section($section): returns as an xml file string of
475
 *                                   the configuration section
476
 */
477
function backup_config_section($section_name) {
478
	global $config;
479
	$new_section = &$config[$section_name];
480
	/* generate configuration XML */
481
	$xmlconfig = dump_xml_config($new_section, $section_name);
482
	$xmlconfig = str_replace("<?xml version=\"1.0\"?>", "", $xmlconfig);
483
	return $xmlconfig;
484
}
485

    
486
/*
487
 *  restore_config_section($section_name, new_contents): restore a configuration section,
488
 *                                                  and write the configuration out
489
 *                                                  to disk/cf.
490
 */
491
function restore_config_section($section_name, $new_contents) {
492
	global $config, $g;
493
	conf_mount_rw();
494
	$fout = fopen("{$g['tmp_path']}/tmpxml","w");
495
	fwrite($fout, $new_contents);
496
	fclose($fout);
497

    
498
	$xml = parse_xml_config($g['tmp_path'] . "/tmpxml", null);
499
	if ($xml['pfsense']) {
500
		$xml = $xml['pfsense'];
501
	}
502
	else if ($xml['m0n0wall']) {
503
		$xml = $xml['m0n0wall'];
504
	}
505
	if ($xml[$section_name]) {
506
		$section_xml = $xml[$section_name];
507
	} else {
508
		$section_xml = -1;
509
	}
510

    
511
	@unlink($g['tmp_path'] . "/tmpxml");
512
	if ($section_xml === -1) {
513
		return false;
514
	}
515
	$config[$section_name] = &$section_xml;
516
	if(file_exists("{$g['tmp_path']}/config.cache"))
517
		unlink("{$g['tmp_path']}/config.cache");
518
	write_config(sprintf(gettext("Restored %s of config file (maybe from CARP partner)"), $section_name));
519
	disable_security_checks();
520
	conf_mount_ro();
521
	return true;
522
}
523

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

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

    
568
";
569

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

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

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

    
585
	return $ret;
586
}
587

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

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

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

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

    
669
	$xmlrpc_base_url = isset($config['system']['altpkgrepo']['enable']) ? $config['system']['altpkgrepo']['xmlrpcbaseurl'] : $g['xmlrpcbaseurl'];
670
	$xmlrpc_path = $g['xmlrpcpath'];
671
	
672
	$xmlrpcfqdn = preg_replace("(https?://)", "", $xmlrpc_base_url);
673
	$ip = gethostbyname($xmlrpcfqdn);
674
	if($ip == $xmlrpcfqdn)
675
		return false;
676

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

    
711
/*
712
 * check_firmware_version(): Check whether the current firmware installed is the most recently released.
713
 */
714
function check_firmware_version($tocheck = "all", $return_php = true) {
715
	global $g, $config;
716
	
717
	$xmlrpc_base_url = isset($config['system']['altpkgrepo']['enable']) ? $config['system']['altpkgrepo']['xmlrpcbaseurl'] : $g['xmlrpcbaseurl'];
718
	$xmlrpcfqdn = preg_replace("(https?://)", "", $xmlrpc_base_url);
719
	$ip = gethostbyname($xmlrpcfqdn);
720
	if($ip == $xmlrpcfqdn)
721
		return false;
722

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

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

    
747
	return $versions;
748
}
749

    
750
/*
751
 * host_firmware_version(): Return the versions used in this install
752
 */
753
function host_firmware_version($tocheck = "") {
754
	global $g, $config;
755

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

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

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

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

    
798
	if($g['debug'])
799
		log_error(gettext("reload_interfaces_sync() is starting."));
800

    
801
	/* parse config.xml again */
802
	$config = parse_config(true);
803

    
804
	/* enable routing */
805
	system_routing_enable();
806
	if($g['debug'])
807
		log_error(gettext("Enabling system routing"));
808

    
809
	if($g['debug'])
810
		log_error(gettext("Cleaning up Interfaces"));
811

    
812
	/* set up interfaces */
813
	interfaces_configure();
814
}
815

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

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

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

    
851
	$g['booting'] = false;
852

    
853
	/* parse config.xml again */
854
	$config = parse_config(true);
855

    
856
	/* set up our timezone */
857
	system_timezone_configure();
858

    
859
	/* set up our hostname */
860
	system_hostname_configure();
861

    
862
	/* make hosts file */
863
	system_hosts_generate();
864

    
865
	/* generate resolv.conf */
866
	system_resolvconf_generate();
867

    
868
	/* enable routing */
869
	system_routing_enable();
870

    
871
	/* set up interfaces */
872
	interfaces_configure();
873

    
874
	/* start dyndns service */
875
	services_dyndns_configure();
876

    
877
	/* configure cron service */
878
	configure_cron();
879

    
880
	/* start the NTP client */
881
	system_ntp_configure();
882

    
883
	/* sync pw database */
884
	conf_mount_rw();
885
	unlink_if_exists("/etc/spwd.db.tmp");
886
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
887
	conf_mount_ro();
888

    
889
	/* restart sshd */
890
	send_event("service restart sshd");
891

    
892
	/* restart webConfigurator if needed */
893
	send_event("service restart webgui");
894
}
895

    
896
function auto_login() {
897
	global $config;
898

    
899
	if(isset($config['system']['disableconsolemenu']))
900
		$status = false;
901
	else
902
		$status = true;
903

    
904
	$gettytab = file_get_contents("/etc/gettytab");
905
	$getty_split = explode("\n", $gettytab);
906
	$getty_update_needed = false;
907
	$getty_search_str = ":ht:np:sp#115200";
908
	$getty_al_str = ":al=root:";
909
	$getty_al_search_str = $getty_search_str . $getty_al_str;
910
	/* Check if gettytab is already OK, if so then do not rewrite it. */
911
	foreach($getty_split as $gs) {
912
		if(stristr($gs, $getty_search_str)) {
913
			if($status == true) {
914
				if(!stristr($gs, $getty_al_search_str)) {
915
					$getty_update_needed = true;
916
				}
917
			} else {
918
				if(stristr($gs, $getty_al_search_str)) {
919
					$getty_update_needed = true;
920
				}
921
			}
922
		}
923
	}
924

    
925
	if (!$getty_update_needed) {
926
		return;
927
	}
928

    
929
	conf_mount_rw();
930
	$fd = false;
931
	$tries = 0;
932
	while (!$fd && $tries < 100) {
933
		$fd = fopen("/etc/gettytab", "w");
934
		$tries++;
935

    
936
	}
937
	if (!$fd) {
938
		conf_mount_ro();
939
		if ($status) {
940
			log_error(gettext("Enabling auto login was not possible."));
941
		} else {
942
			log_error(gettext("Disabling auto login was not possible."));
943
		}
944
		return;
945
	}
946
	foreach($getty_split as $gs) {
947
		if(stristr($gs, $getty_search_str)) {
948
			if($status == true) {
949
				fwrite($fd, "	".$getty_al_search_str."\n");
950
			} else {
951
				fwrite($fd, "	".$getty_search_str."\n");
952
			}
953
		} else {
954
			fwrite($fd, "{$gs}\n");
955
		}
956
	}
957
	fclose($fd);
958

    
959
	if ($status) {
960
		log_error(gettext("Enabled console auto login, console menu is NOT password protected."));
961
	} else {
962
		log_error(gettext("Disabled console auto login, console menu is password protected."));
963
	}
964

    
965
	conf_mount_ro();
966
}
967

    
968
function setup_serial_port($when="save", $path="") {
969
	global $g, $config;
970
	conf_mount_rw();
971
	$prefix = "";
972
	if (($when == "upgrade") && (!empty($path)) && is_dir($path.'/boot/'))
973
		$prefix = "/tmp/{$path}";
974
	$boot_config_file = "{$path}/boot.config";
975
	$loader_conf_file = "{$path}/boot/loader.conf";
976
	/* serial console - write out /boot.config */
977
	if(file_exists($boot_config_file))
978
		$boot_config = file_get_contents($boot_config_file);
979
	else
980
		$boot_config = "";
981

    
982
	if(($g['platform'] != "cdrom") && ($g['platform'] != "nanobsd")) {
983
		$boot_config_split = explode("\n", $boot_config);
984
		$fd = fopen($boot_config_file,"w");
985
		if($fd) {
986
			foreach($boot_config_split as $bcs) {
987
				if(stristr($bcs, "-D")) {
988
					/* DONT WRITE OUT, WE'LL DO IT LATER */
989
				} else {
990
					if($bcs <> "")
991
						fwrite($fd, "{$bcs}\n");
992
				}
993
			}
994
			if(isset($config['system']['enableserial']) || $g['enableserial_force']) {
995
				fwrite($fd, "-D");
996
			}
997
			fclose($fd);
998
		}
999
	}
1000
	if($g['platform'] != "cdrom") {
1001
		/* serial console - write out /boot/loader.conf */
1002
		if ($when == "upgrade")
1003
			system("echo \"Reading {$loader_conf_file}...\" >> /conf/upgrade_log.txt");
1004
		$boot_config = file_get_contents($loader_conf_file);
1005
		$boot_config_split = explode("\n", $boot_config);
1006
		if(count($boot_config_split) > 0) {
1007
			$new_boot_config = array();
1008
			// Loop through and only add lines that are not empty, and which
1009
			//  do not contain a console directive.
1010
			foreach($boot_config_split as $bcs)
1011
				if(!empty($bcs)
1012
					&& (stripos($bcs, "console") === false)
1013
					&& (stripos($bcs, "boot_multicons") === false)
1014
					&& (stripos($bcs, "boot_serial") === false)
1015
					&& (stripos($bcs, "hw.usb.no_pf") === false))
1016
					$new_boot_config[] = $bcs;
1017

    
1018
			$serialspeed = (is_numeric($config['system']['serialspeed'])) ? $config['system']['serialspeed'] : "9600";
1019
			if(isset($config['system']['enableserial']) || $g['enableserial_force']) {
1020
				$new_boot_config[] = 'boot_multicons="YES"';
1021
				$new_boot_config[] = 'boot_serial="YES"';
1022
				$new_boot_config[] = 'comconsole_speed="' . $serialspeed . '"';
1023
				$primaryconsole = isset($g['primaryconsole_force']) ? $g['primaryconsole_force'] : $config['system']['primaryconsole'];
1024
				switch ($primaryconsole) {
1025
					case "video":
1026
						$new_boot_config[] = 'console="vidconsole,comconsole"';
1027
						break;
1028
					case "serial":
1029
					default:
1030
						$new_boot_config[] = 'console="comconsole,vidconsole"';
1031
				}
1032
			} elseif ($g['platform'] == "nanobsd") {
1033
				$new_boot_config[] = 'comconsole_speed="' . $serialspeed . '"';
1034
			}
1035

    
1036
			$new_boot_config[] = 'hw.usb.no_pf="1"';
1037

    
1038
			file_put_contents($loader_conf_file, implode("\n", $new_boot_config) . "\n");
1039
		}
1040
	}
1041
	$ttys = file_get_contents("/etc/ttys");
1042
	$ttys_split = explode("\n", $ttys);
1043
	$fd = fopen("/etc/ttys", "w");
1044
	foreach($ttys_split as $tty) {
1045
		if(stristr($tty, "ttyd0") or stristr($tty, "ttyu0")) {
1046
			if(isset($config['system']['enableserial']) || $g['enableserial_force']) {
1047
				fwrite($fd, "ttyu0	\"/usr/libexec/getty bootupcli\"	cons25	on	secure\n");
1048
			} else {
1049
				fwrite($fd, "ttyu0	\"/usr/libexec/getty bootupcli\"	cons25	off	secure\n");
1050
			}
1051
		} else {
1052
			fwrite($fd, $tty . "\n");
1053
		}
1054
	}
1055
	fclose($fd);
1056
	auto_login();
1057

    
1058
	conf_mount_ro();
1059
	return;
1060
}
1061

    
1062
function print_value_list($list, $count = 10, $separator = ",") {
1063
	$list = implode($separator, array_slice($list, 0, $count));
1064
	if(count($list) < $count) {
1065
		$list .= ".";
1066
	} else {
1067
		$list .= "...";
1068
	}
1069
	return $list;
1070
}
1071

    
1072
/* DHCP enabled on any interfaces? */
1073
function is_dhcp_server_enabled() {
1074
	global $config;
1075

    
1076
	if (!is_array($config['dhcpd']))
1077
		return false;
1078

    
1079
	foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf) {
1080
		if (isset($dhcpifconf['enable']) && !empty($config['interfaces'][$dhcpif]))
1081
			return true;
1082
	}
1083

    
1084
	return false;
1085
}
1086

    
1087
/* DHCP enabled on any interfaces? */
1088
function is_dhcpv6_server_enabled() {
1089
	global $config;
1090

    
1091
	if (is_array($config['interfaces'])) {
1092
		foreach ($config['interfaces'] as $ifcfg) {
1093
			if (isset($ifcfg['enable']) && !empty($ifcfg['track6-interface']))
1094
				return true;
1095
		}
1096
	}
1097

    
1098
	if (!is_array($config['dhcpdv6']))
1099
		return false;
1100

    
1101
	foreach ($config['dhcpdv6'] as $dhcpv6if => $dhcpv6ifconf) {
1102
		if (isset($dhcpv6ifconf['enable']) && !empty($config['interfaces'][$dhcpv6if]))
1103
			return true;
1104
	}
1105

    
1106
	return false;
1107
}
1108

    
1109
/* radvd enabled on any interfaces? */
1110
function is_radvd_enabled() {
1111
	global $config;
1112

    
1113
	if (!is_array($config['dhcpdv6']))
1114
		$config['dhcpdv6'] = array();
1115

    
1116
	$dhcpdv6cfg = $config['dhcpdv6'];
1117
	$Iflist = get_configured_interface_list();
1118

    
1119
	/* handle manually configured DHCP6 server settings first */
1120
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1121
		if(!isset($config['interfaces'][$dhcpv6if]['enable']))
1122
			continue;
1123

    
1124
		if(!isset($dhcpv6ifconf['ramode']))
1125
			$dhcpv6ifconf['ramode'] = $dhcpv6ifconf['mode'];
1126

    
1127
		if($dhcpv6ifconf['ramode'] == "disabled")
1128
			continue;
1129

    
1130
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1131
		if(!is_ipaddrv6($ifcfgipv6))
1132
			continue;
1133

    
1134
		return true;
1135
	}
1136

    
1137
	/* handle DHCP-PD prefixes and 6RD dynamic interfaces */
1138
	foreach ($Iflist as $if => $ifdescr) {
1139
		if(!isset($config['interfaces'][$if]['track6-interface']))
1140
			continue;
1141
		if(!isset($config['interfaces'][$if]['enable']))
1142
			continue;
1143

    
1144
		$ifcfgipv6 = get_interface_ipv6($if);
1145
		if(!is_ipaddrv6($ifcfgipv6))
1146
			continue;
1147

    
1148
		$ifcfgsnv6 = get_interface_subnetv6($if);
1149
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1150

    
1151
		if(!is_ipaddrv6($subnetv6))
1152
			continue;
1153

    
1154
		return true;
1155
	}
1156

    
1157
	return false;
1158
}
1159

    
1160
/* Any PPPoE servers enabled? */
1161
function is_pppoe_server_enabled() {
1162
	global $config;
1163

    
1164
	$pppoeenable = false;
1165

    
1166
	if (!is_array($config['pppoes']) || !is_array($config['pppoes']['pppoe']))
1167
		return false;
1168

    
1169
	foreach ($config['pppoes']['pppoe'] as $pppoes)
1170
		if ($pppoes['mode'] == 'server')
1171
			$pppoeenable = true;
1172

    
1173
	return $pppoeenable;
1174
}
1175

    
1176
function convert_seconds_to_hms($sec){
1177
	$min=$hrs=0;
1178
	if ($sec != 0){
1179
		$min = floor($sec/60);
1180
		$sec %= 60;
1181
	}
1182
	if ($min != 0){
1183
		$hrs = floor($min/60);
1184
		$min %= 60;
1185
	}
1186
	if ($sec < 10)
1187
		$sec = "0".$sec;
1188
	if ($min < 10)
1189
		$min = "0".$min;
1190
	if ($hrs < 10)
1191
		$hrs = "0".$hrs;
1192
	$result = $hrs.":".$min.":".$sec;
1193
	return $result;
1194
}
1195

    
1196
/* Compute the total uptime from the ppp uptime log file in the conf directory */
1197

    
1198
function get_ppp_uptime($port){
1199
	if (file_exists("/conf/{$port}.log")){
1200
		$saved_time = file_get_contents("/conf/{$port}.log");
1201
		$uptime_data = explode("\n",$saved_time);
1202
		$sec=0;
1203
		foreach($uptime_data as $upt) {
1204
			$sec += substr($upt, 1 + strpos($upt, " "));
1205
		}
1206
		return convert_seconds_to_hms($sec);
1207
	} else {
1208
		$total_time = gettext("No history data found!");
1209
		return $total_time;
1210
	}
1211
}
1212

    
1213
//returns interface information
1214
function get_interface_info($ifdescr) {
1215
	global $config, $g;
1216

    
1217
	$ifinfo = array();
1218
	if (empty($config['interfaces'][$ifdescr]))
1219
		return;
1220
	$ifinfo['hwif'] = $config['interfaces'][$ifdescr]['if'];
1221
	$ifinfo['if'] = get_real_interface($ifdescr);
1222

    
1223
	$chkif = $ifinfo['if'];
1224
	$ifinfotmp = pfSense_get_interface_addresses($chkif);
1225
	$ifinfo['status'] = $ifinfotmp['status'];
1226
	if (empty($ifinfo['status']))
1227
		$ifinfo['status'] = "down";
1228
	$ifinfo['macaddr'] = $ifinfotmp['macaddr'];
1229
	$ifinfo['ipaddr'] = $ifinfotmp['ipaddr'];
1230
	$ifinfo['subnet'] = $ifinfotmp['subnet'];
1231
	$ifinfo['linklocal'] = get_interface_linklocal($ifdescr);
1232
	$ifinfo['ipaddrv6'] = get_interface_ipv6($ifdescr);
1233
	$ifinfo['subnetv6'] = get_interface_subnetv6($ifdescr);
1234
	if (isset($ifinfotmp['link0']))
1235
		$link0 = "down";
1236
	$ifinfotmp = pfSense_get_interface_stats($chkif);
1237
	// $ifinfo['inpkts'] = $ifinfotmp['inpkts'];
1238
	// $ifinfo['outpkts'] = $ifinfotmp['outpkts'];
1239
	$ifinfo['inerrs'] = $ifinfotmp['inerrs'];
1240
	$ifinfo['outerrs'] = $ifinfotmp['outerrs'];
1241
	$ifinfo['collisions'] = $ifinfotmp['collisions'];
1242

    
1243
	/* Use pfctl for non wrapping 64 bit counters */
1244
	/* Pass */
1245
	exec("/sbin/pfctl -vvsI -i {$chkif}", $pfctlstats);
1246
	$pf_in4_pass = preg_split("/ +/ ", $pfctlstats[3]);
1247
	$pf_out4_pass = preg_split("/ +/", $pfctlstats[5]);
1248
	$pf_in6_pass = preg_split("/ +/ ", $pfctlstats[7]);
1249
	$pf_out6_pass = preg_split("/ +/", $pfctlstats[9]);
1250
	$in4_pass = $pf_in4_pass[5];
1251
	$out4_pass = $pf_out4_pass[5];
1252
	$in4_pass_packets = $pf_in4_pass[3];
1253
	$out4_pass_packets = $pf_out4_pass[3];
1254
	$in6_pass = $pf_in6_pass[5];
1255
	$out6_pass = $pf_out6_pass[5];
1256
	$in6_pass_packets = $pf_in6_pass[3];
1257
	$out6_pass_packets = $pf_out6_pass[3];
1258
	$ifinfo['inbytespass'] = $in4_pass + $in6_pass;
1259
	$ifinfo['outbytespass'] = $out4_pass + $out6_pass;
1260
	$ifinfo['inpktspass'] = $in4_pass_packets + $in6_pass_packets;
1261
	$ifinfo['outpktspass'] = $out4_pass_packets + $out6_pass_packets;
1262

    
1263
	/* Block */
1264
	$pf_in4_block = preg_split("/ +/", $pfctlstats[4]);
1265
	$pf_out4_block = preg_split("/ +/", $pfctlstats[6]);
1266
	$pf_in6_block = preg_split("/ +/", $pfctlstats[8]);
1267
	$pf_out6_block = preg_split("/ +/", $pfctlstats[10]);
1268
	$in4_block = $pf_in4_block[5];
1269
	$out4_block = $pf_out4_block[5];
1270
	$in4_block_packets = $pf_in4_block[3];
1271
	$out4_block_packets = $pf_out4_block[3];
1272
	$in6_block = $pf_in6_block[5];
1273
	$out6_block = $pf_out6_block[5];
1274
	$in6_block_packets = $pf_in6_block[3];
1275
	$out6_block_packets = $pf_out6_block[3];
1276
	$ifinfo['inbytesblock'] = $in4_block + $in6_block;
1277
	$ifinfo['outbytesblock'] = $out4_block + $out6_block;
1278
	$ifinfo['inpktsblock'] = $in4_block_packets + $in6_block_packets;
1279
	$ifinfo['outpktsblock'] = $out4_block_packets + $out6_block_packets;
1280

    
1281
	$ifinfo['inbytes'] = $in4_pass + $in6_pass;
1282
	$ifinfo['outbytes'] = $out4_pass + $out6_pass;
1283
	$ifinfo['inpkts'] = $in4_pass_packets + $in6_pass_packets;
1284
	$ifinfo['outpkts'] = $out4_pass_packets + $out6_pass_packets;
1285

    
1286
	$ifconfiginfo = "";
1287
	$link_type = $config['interfaces'][$ifdescr]['ipaddr'];
1288
	switch ($link_type) {
1289
	/* DHCP? -> see if dhclient is up */
1290
	case "dhcp":
1291
		/* see if dhclient is up */
1292
		if (find_dhclient_process($ifinfo['if']) <> "")
1293
			$ifinfo['dhcplink'] = "up";
1294
		else
1295
			$ifinfo['dhcplink'] = "down";
1296

    
1297
		break;
1298
	/* PPPoE/PPTP/L2TP interface? -> get status from virtual interface */
1299
	case "pppoe":
1300
	case "pptp":
1301
	case "l2tp":
1302
		if ($ifinfo['status'] == "up" && !isset($link0))
1303
			/* get PPPoE link status for dial on demand */
1304
			$ifinfo["{$link_type}link"] = "up";
1305
		else
1306
			$ifinfo["{$link_type}link"] = "down";
1307

    
1308
		break;
1309
	/* PPP interface? -> get uptime for this session and cumulative uptime from the persistant log file in conf */
1310
	case "ppp":
1311
		if ($ifinfo['status'] == "up")
1312
			$ifinfo['ppplink'] = "up";
1313
		else
1314
			$ifinfo['ppplink'] = "down" ;
1315

    
1316
		if (empty($ifinfo['status']))
1317
			$ifinfo['status'] = "down";
1318

    
1319
		if (is_array($config['ppps']['ppp']) && count($config['ppps']['ppp'])) {
1320
			foreach ($config['ppps']['ppp'] as $pppid => $ppp) {
1321
				if ($config['interfaces'][$ifdescr]['if'] == $ppp['if'])
1322
					break;
1323
			}
1324
		}
1325
		$dev = $ppp['ports'];
1326
		if ($config['interfaces'][$ifdescr]['if'] != $ppp['if'] || empty($dev))
1327
			break;
1328
		if (!file_exists($dev)) {
1329
			$ifinfo['nodevice'] = 1;
1330
			$ifinfo['pppinfo'] = $dev . " " . gettext("device not present! Is the modem attached to the system?");
1331
		}
1332

    
1333
		$usbmodemoutput = array();
1334
		exec("usbconfig", $usbmodemoutput);
1335
		$mondev = "{$g['tmp_path']}/3gstats.{$ifdescr}";
1336
		if(file_exists($mondev)) {
1337
			$cellstats = file($mondev);
1338
			/* skip header */
1339
			$a_cellstats = explode(",", $cellstats[1]);
1340
			if(preg_match("/huawei/i", implode("\n", $usbmodemoutput))) {
1341
				$ifinfo['cell_rssi'] = huawei_rssi_to_string($a_cellstats[1]);
1342
				$ifinfo['cell_mode'] = huawei_mode_to_string($a_cellstats[2], $a_cellstats[3]);
1343
				$ifinfo['cell_simstate'] = huawei_simstate_to_string($a_cellstats[10]);
1344
				$ifinfo['cell_service'] = huawei_service_to_string(trim($a_cellstats[11]));
1345
			}
1346
			if(preg_match("/zte/i", implode("\n", $usbmodemoutput))) {
1347
				$ifinfo['cell_rssi'] = zte_rssi_to_string($a_cellstats[1]);
1348
				$ifinfo['cell_mode'] = zte_mode_to_string($a_cellstats[2], $a_cellstats[3]);
1349
				$ifinfo['cell_simstate'] = zte_simstate_to_string($a_cellstats[10]);
1350
				$ifinfo['cell_service'] = zte_service_to_string(trim($a_cellstats[11]));
1351
			}
1352
			$ifinfo['cell_upstream'] = $a_cellstats[4];
1353
			$ifinfo['cell_downstream'] = trim($a_cellstats[5]);
1354
			$ifinfo['cell_sent'] = $a_cellstats[6];
1355
			$ifinfo['cell_received'] = trim($a_cellstats[7]);
1356
			$ifinfo['cell_bwupstream'] = $a_cellstats[8];
1357
			$ifinfo['cell_bwdownstream'] = trim($a_cellstats[9]);
1358
		}
1359
		// Calculate cumulative uptime for PPP link. Useful for connections that have per minute/hour contracts so you don't go over!
1360
		if (isset($ppp['uptime']))
1361
			$ifinfo['ppp_uptime_accumulated'] = "(".get_ppp_uptime($ifinfo['if']).")";
1362
		break;
1363
	default:
1364
		break;
1365
	}
1366

    
1367
	if (file_exists("{$g['varrun_path']}/{$link_type}_{$ifdescr}.pid")) {
1368
		$sec = trim(`/usr/local/sbin/ppp-uptime.sh {$ifinfo['if']}`);
1369
		$ifinfo['ppp_uptime'] = convert_seconds_to_hms($sec);
1370
	}
1371

    
1372
	if ($ifinfo['status'] == "up") {
1373
		/* try to determine media with ifconfig */
1374
		unset($ifconfiginfo);
1375
		exec("/sbin/ifconfig " . $ifinfo['if'], $ifconfiginfo);
1376
		$wifconfiginfo = array();
1377
		if(is_interface_wireless($ifdescr)) {
1378
			exec("/sbin/ifconfig {$ifinfo['if']} list sta", $wifconfiginfo);
1379
			array_shift($wifconfiginfo);
1380
		}
1381
		$matches = "";
1382
		foreach ($ifconfiginfo as $ici) {
1383

    
1384
			/* don't list media/speed for wireless cards, as it always
1385
			   displays 2 Mbps even though clients can connect at 11 Mbps */
1386
			if (preg_match("/media: .*? \((.*?)\)/", $ici, $matches)) {
1387
				$ifinfo['media'] = $matches[1];
1388
			} else if (preg_match("/media: Ethernet (.*)/", $ici, $matches)) {
1389
				$ifinfo['media'] = $matches[1];
1390
			} else if (preg_match("/media: IEEE 802.11 Wireless Ethernet (.*)/", $ici, $matches)) {
1391
				$ifinfo['media'] = $matches[1];
1392
			}
1393

    
1394
			if (preg_match("/status: (.*)$/", $ici, $matches)) {
1395
				if ($matches[1] != "active")
1396
					$ifinfo['status'] = $matches[1];
1397
				if($ifinfo['status'] == gettext("running"))
1398
					$ifinfo['status'] = gettext("up");
1399
			}
1400
			if (preg_match("/channel (\S*)/", $ici, $matches)) {
1401
				$ifinfo['channel'] = $matches[1];
1402
			}
1403
			if (preg_match("/ssid (\".*?\"|\S*)/", $ici, $matches)) {
1404
				if ($matches[1][0] == '"')
1405
					$ifinfo['ssid'] = substr($matches[1], 1, -1);
1406
				else
1407
					$ifinfo['ssid'] = $matches[1];
1408
			}
1409
			if (preg_match("/laggproto (.*)$/", $ici, $matches)) {
1410
				$ifinfo['laggproto'] = $matches[1];
1411
			}
1412
			if (preg_match("/laggport: (.*)$/", $ici, $matches)) {
1413
				$ifinfo['laggport'][] = $matches[1];
1414
			}
1415
		}
1416
		foreach($wifconfiginfo as $ici) {
1417
			$elements = preg_split("/[ ]+/i", $ici);
1418
			if ($elements[0] != "") {
1419
				$ifinfo['bssid'] = $elements[0];
1420
			}
1421
			if ($elements[3] != "") {
1422
				$ifinfo['rate'] = $elements[3];
1423
			}
1424
			if ($elements[4] != "") {
1425
				$ifinfo['rssi'] = $elements[4];
1426
			}
1427

    
1428
		}
1429
		/* lookup the gateway */
1430
		if (interface_has_gateway($ifdescr)) {
1431
			$ifinfo['gateway'] = get_interface_gateway($ifdescr);
1432
			$ifinfo['gatewayv6'] = get_interface_gateway_v6($ifdescr);
1433
		}
1434
	}
1435

    
1436
	$bridge = "";
1437
	$bridge = link_interface_to_bridge($ifdescr);
1438
	if($bridge) {
1439
		$bridge_text = `/sbin/ifconfig {$bridge}`;
1440
		if(stristr($bridge_text, "blocking") <> false) {
1441
			$ifinfo['bridge'] = "<b><font color='red'>" . gettext("blocking") . "</font></b> - " . gettext("check for ethernet loops");
1442
			$ifinfo['bridgeint'] = $bridge;
1443
		} else if(stristr($bridge_text, "learning") <> false) {
1444
			$ifinfo['bridge'] = gettext("learning");
1445
			$ifinfo['bridgeint'] = $bridge;
1446
		} else if(stristr($bridge_text, "forwarding") <> false) {
1447
			$ifinfo['bridge'] = gettext("forwarding");
1448
			$ifinfo['bridgeint'] = $bridge;
1449
		}
1450
	}
1451

    
1452
	return $ifinfo;
1453
}
1454

    
1455
//returns cpu speed of processor. Good for determining capabilities of machine
1456
function get_cpu_speed() {
1457
	return exec("/sbin/sysctl -n hw.clockrate");
1458
}
1459

    
1460
function add_hostname_to_watch($hostname) {
1461
	if(!is_dir("/var/db/dnscache")) {
1462
		mkdir("/var/db/dnscache");
1463
	}
1464
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1465
		$domrecords = array();
1466
		$domips = array();
1467
		exec("host -t A " . escapeshellarg($hostname), $domrecords, $rethost);
1468
		if($rethost == 0) {
1469
			foreach($domrecords as $domr) {
1470
				$doml = explode(" ", $domr);
1471
				$domip = $doml[3];
1472
				/* fill array with domain ip addresses */
1473
				if(is_ipaddr($domip)) {
1474
					$domips[] = $domip;
1475
				}
1476
			}
1477
		}
1478
		sort($domips);
1479
		$contents = "";
1480
		if(! empty($domips)) {
1481
			foreach($domips as $ip) {
1482
				$contents .= "$ip\n";
1483
			}
1484
		}
1485
		file_put_contents("/var/db/dnscache/$hostname", $contents);
1486
	}
1487
}
1488

    
1489
function is_fqdn($fqdn) {
1490
	$hostname = false;
1491
	if(preg_match("/[-A-Z0-9\.]+\.[-A-Z0-9\.]+/i", $fqdn)) {
1492
		$hostname = true;
1493
	}
1494
	if(preg_match("/\.\./", $fqdn)) {
1495
		$hostname = false;
1496
	}
1497
	if(preg_match("/^\./i", $fqdn)) {
1498
		$hostname = false;
1499
	}
1500
	if(preg_match("/\//i", $fqdn)) {
1501
		$hostname = false;
1502
	}
1503
	return($hostname);
1504
}
1505

    
1506
function pfsense_default_state_size() {
1507
	/* get system memory amount */
1508
	$memory = get_memory();
1509
	$physmem = $memory[0];
1510
	/* Be cautious and only allocate 10% of system memory to the state table */
1511
	$max_states = (int) ($physmem/10)*1000;
1512
	return $max_states;
1513
}
1514

    
1515
function pfsense_default_tables_size() {
1516
	$current = `pfctl -sm | grep ^tables | awk '{print $4};'`;
1517
	return $current;
1518
}
1519

    
1520
function pfsense_default_table_entries_size() {
1521
	$current = `pfctl -sm | grep table-entries | awk '{print $4};'`;
1522
	return $current;
1523
}
1524

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

    
1561
	if(trim($oldcontents) != trim($contents)) {
1562
		if($g['debug']) {
1563
			log_error(sprintf(gettext('DNSCACHE: Found old IP %1$s and new IP %2$s'), $oldcontents, $contents));
1564
		}
1565
		return ($oldcontents);
1566
	} else {
1567
		return false;
1568
	}
1569
}
1570

    
1571
/*
1572
 * load_crypto() - Load crypto modules if enabled in config.
1573
 */
1574
function load_crypto() {
1575
	global $config, $g;
1576
	$crypto_modules = array('glxsb', 'aesni');
1577

    
1578
	if (!in_array($config['system']['crypto_hardware'], $crypto_modules))
1579
		return false;
1580

    
1581
	if (!empty($config['system']['crypto_hardware']) && !is_module_loaded($config['system']['crypto_hardware'])) {
1582
		log_error("Loading {$config['system']['crypto_hardware']} cryptographic accelerator module.");
1583
		mwexec("/sbin/kldload {$config['system']['crypto_hardware']}");
1584
	}
1585
}
1586

    
1587
/*
1588
 * load_thermal_hardware() - Load temperature monitor kernel module
1589
 */
1590
function load_thermal_hardware() {
1591
	global $config, $g;
1592
	$thermal_hardware_modules = array('coretemp', 'amdtemp');
1593

    
1594
	if (!in_array($config['system']['thermal_hardware'], $thermal_hardware_modules))
1595
		return false;
1596

    
1597
	if (!empty($config['system']['thermal_hardware']) && !is_module_loaded($config['system']['thermal_hardware'])) {
1598
		log_error("Loading {$config['system']['thermal_hardware']} thermal monitor module.");
1599
		mwexec("/sbin/kldload {$config['system']['thermal_hardware']}");
1600
	}
1601
}
1602

    
1603
/****f* pfsense-utils/isvm
1604
 * NAME
1605
 *   isvm
1606
 * INPUTS
1607
 *	none
1608
 * RESULT
1609
 *   returns true if machine is running under a virtual environment
1610
 ******/
1611
function isvm() {
1612
	$virtualenvs = array("vmware", "parallels", "qemu", "bochs", "plex86");
1613
	$bios_product = trim(`/bin/kenv | /usr/bin/awk -F= '/smbios.system.product/ {print $2}'`);
1614
	foreach ($virtualenvs as $virtualenv)
1615
		if (stripos($bios_product, $virtualenv) !== false)
1616
			return true;
1617

    
1618
	return false;
1619
}
1620

    
1621
function get_freebsd_version() {
1622
	$version = php_uname("r");
1623
	return $version[0];
1624
}
1625

    
1626
function download_file_with_progress_bar($url_file, $destination_file, $readbody = 'read_body', $connect_timeout=60, $timeout=0) {
1627
	global $ch, $fout, $file_size, $downloaded, $config, $first_progress_update;
1628
	$file_size  = 1;
1629
	$downloaded = 1;
1630
	$first_progress_update = TRUE;
1631
	/* open destination file */
1632
	$fout = fopen($destination_file, "wb");
1633

    
1634
	/*
1635
	 *      Originally by Author: Keyvan Minoukadeh
1636
	 *      Modified by Scott Ullrich to return Content-Length size
1637
	 */
1638

    
1639
	$ch = curl_init();
1640
	curl_setopt($ch, CURLOPT_URL, $url_file);
1641
	curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
1642
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1643
	/* Don't verify SSL peers since we don't have the certificates to do so. */
1644
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1645
	curl_setopt($ch, CURLOPT_WRITEFUNCTION, $readbody);
1646
	curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
1647
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connect_timeout);
1648
	curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1649

    
1650
	if (!empty($config['system']['proxyurl'])) {
1651
		curl_setopt($ch, CURLOPT_PROXY, $config['system']['proxyurl']);
1652
		if (!empty($config['system']['proxyport']))
1653
			curl_setopt($ch, CURLOPT_PROXYPORT, $config['system']['proxyport']);
1654
		if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
1655
			@curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY | CURLAUTH_ANYSAFE);
1656
			curl_setopt($ch, CURLOPT_PROXYUSERPWD, "{$config['system']['proxyuser']}:{$config['system']['proxypass']}");
1657
		}
1658
	}
1659

    
1660
	@curl_exec($ch);
1661
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1662
	if($fout)
1663
		fclose($fout);
1664
	curl_close($ch);
1665
	return ($http_code == 200) ? true : $http_code;
1666
}
1667

    
1668
function read_header($ch, $string) {
1669
	global $file_size, $fout;
1670
	$length = strlen($string);
1671
	$regs = "";
1672
	preg_match("/(Content-Length:) (.*)/", $string, $regs);
1673
	if($regs[2] <> "") {
1674
		$file_size = intval($regs[2]);
1675
	}
1676
	ob_flush();
1677
	return $length;
1678
}
1679

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

    
1730
/*
1731
 *   update_output_window: update bottom textarea dynamically.
1732
 */
1733
function update_output_window($text) {
1734
	global $pkg_interface;
1735
	$log = preg_replace("/\n/", "\\n", $text);
1736
	if($pkg_interface != "console") {
1737
		echo "\n<script type=\"text/javascript\">";
1738
		echo "\n//<![CDATA[";
1739
		echo "\nthis.document.forms[0].output.value = \"" . $log . "\";";
1740
		echo "\nthis.document.forms[0].output.scrollTop = this.document.forms[0].output.scrollHeight;";
1741
		echo "\n//]]>";
1742
		echo "\n</script>";
1743
	}
1744
	/* ensure that contents are written out */
1745
	ob_flush();
1746
}
1747

    
1748
/*
1749
 *   update_status: update top textarea dynamically.
1750
 */
1751
function update_status($status) {
1752
	global $pkg_interface;
1753
	if($pkg_interface == "console") {
1754
		echo "\r{$status}";
1755
	} else {
1756
		echo "\n<script type=\"text/javascript\">";
1757
		echo "\n//<![CDATA[";
1758
		echo "\nthis.document.forms[0].status.value=\"" . $status . "\";";
1759
		echo "\n//]]>";
1760
		echo "\n</script>";
1761
	}
1762
	/* ensure that contents are written out */
1763
	ob_flush();
1764
}
1765

    
1766
/*
1767
 * update_progress_bar($percent, $first_time): updates the javascript driven progress bar.
1768
 */
1769
function update_progress_bar($percent, $first_time) {
1770
	global $pkg_interface;
1771
	if($percent > 100) $percent = 1;
1772
	if($pkg_interface <> "console") {
1773
		echo "\n<script type=\"text/javascript\">";
1774
		echo "\n//<![CDATA[";
1775
		echo "\ndocument.progressbar.style.width='" . $percent . "%';";
1776
		echo "\n//]]>";
1777
		echo "\n</script>";
1778
	} else {
1779
		if(!($first_time))
1780
			echo "\x08\x08\x08\x08\x08";
1781
		echo sprintf("%4d%%", $percent);
1782
	}
1783
}
1784

    
1785
/* 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. */
1786
if(!function_exists("split")) {
1787
	function split($separator, $haystack, $limit = null) {
1788
		log_error("deprecated split() call with separator '{$separator}'");
1789
		return preg_split($separator, $haystack, $limit);
1790
	}
1791
}
1792

    
1793
function update_alias_names_upon_change($section, $field, $new_alias_name, $origname) {
1794
	global $g, $config, $pconfig, $debug;
1795
	if(!$origname)
1796
		return;
1797

    
1798
	$sectionref = &$config;
1799
	foreach($section as $sectionname) {
1800
		if(is_array($sectionref) && isset($sectionref[$sectionname]))
1801
			$sectionref = &$sectionref[$sectionname];
1802
		else
1803
			return;
1804
	}
1805

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

    
1809
	if(is_array($sectionref)) {
1810
		foreach($sectionref as $itemkey => $item) {
1811
			if($debug) fwrite($fd, "$itemkey\n");
1812

    
1813
			$fieldfound = true;
1814
			$fieldref = &$sectionref[$itemkey];
1815
			foreach($field as $fieldname) {
1816
				if(is_array($fieldref) && isset($fieldref[$fieldname]))
1817
					$fieldref = &$fieldref[$fieldname];
1818
				else {
1819
					$fieldfound = false;
1820
					break;
1821
				}
1822
			}
1823
			if($fieldfound && $fieldref == $origname) {
1824
				if($debug) fwrite($fd, "Setting old alias value $origname to $new_alias_name\n");
1825
				$fieldref = $new_alias_name;
1826
			}
1827
		}
1828
	}
1829

    
1830
	if($debug) fclose($fd);
1831

    
1832
}
1833

    
1834
function update_alias_url_data() {
1835
	global $config, $g;
1836

    
1837
	/* item is a url type */
1838
	$lockkey = lock('config');
1839
	if (is_array($config['aliases']['alias'])) {
1840
		foreach ($config['aliases']['alias'] as $x => $alias) {
1841
			if (empty($alias['aliasurl']))
1842
				continue;
1843

    
1844
			$address = "";
1845
			$isfirst = 0;
1846
			foreach ($alias['aliasurl'] as $alias_url) {
1847
				/* fetch down and add in */
1848
				$temp_filename = tempnam("{$g['tmp_path']}/", "alias_import");
1849
				unlink($temp_filename);
1850
				mwexec("/bin/mkdir -p {$temp_filename}");
1851
				mwexec("/usr/bin/fetch -T 5 -q -o \"{$temp_filename}/aliases\" \"" . $alias_url . "\"");
1852
				/* if the item is tar gzipped then extract */
1853
				if (stristr($alias_url, ".tgz"))
1854
					process_alias_tgz($temp_filename);
1855
				else if (stristr($alias_url, ".zip"))
1856
					process_alias_unzip($temp_filename);
1857
				if (file_exists("{$temp_filename}/aliases")) {
1858
					$file_contents = file_get_contents("{$temp_filename}/aliases");
1859
					$file_contents = str_replace("#", "\n#", $file_contents);
1860
					$file_contents_split = explode("\n", $file_contents);
1861
					foreach ($file_contents_split as $fc) {
1862
						$tmp = trim($fc);
1863
						if (stristr($fc, "#")) {
1864
							$tmp_split = explode("#", $tmp);
1865
							$tmp = trim($tmp_split[0]);
1866
						}
1867
						if (trim($tmp) <> "") {
1868
							if ($isfirst == 1)
1869
								$address .= " ";
1870
							$address .= $tmp;
1871
							$isfirst = 1;
1872
						}
1873
					}
1874
					mwexec("/bin/rm -rf {$temp_filename}");
1875
				}
1876
			}
1877
			if($isfirst > 0) {
1878
				$config['aliases']['alias'][$x]['address'] = $address;
1879
				$updated = true;
1880
			}
1881
		}
1882
	}
1883
	unlock($lockkey);
1884
	if ($updated) {
1885
		write_config();
1886
		send_event("filter reload");
1887
	}
1888
}
1889

    
1890
function process_alias_unzip($temp_filename) {
1891
	if(!file_exists("/usr/local/bin/unzip"))
1892
		return;
1893
	rename("{$temp_filename}/aliases", "{$temp_filename}/aliases.zip");
1894
	mwexec("/usr/local/bin/unzip {$temp_filename}/aliases.tgz -d {$temp_filename}/aliases/");
1895
	unlink("{$temp_filename}/aliases.zip");
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 process_alias_tgz($temp_filename) {
1908
	if(!file_exists("/usr/bin/tar"))
1909
		return;
1910
	rename("{$temp_filename}/aliases", "{$temp_filename}/aliases.tgz");
1911
	mwexec("/usr/bin/tar xzf {$temp_filename}/aliases.tgz -C {$temp_filename}/aliases/");
1912
	unlink("{$temp_filename}/aliases.tgz");
1913
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1914
	/* foreach through all extracted files and build up aliases file */
1915
	$fd = fopen("{$temp_filename}/aliases", "w");
1916
	foreach($files_to_process as $f2p) {
1917
		$file_contents = file_get_contents($f2p);
1918
		fwrite($fd, $file_contents);
1919
		unlink($f2p);
1920
	}
1921
	fclose($fd);
1922
}
1923

    
1924
function version_compare_dates($a, $b) {
1925
	$a_time = strtotime($a);
1926
	$b_time = strtotime($b);
1927

    
1928
	if ((!$a_time) || (!$b_time)) {
1929
		return FALSE;
1930
	} else {
1931
		if ($a_time < $b_time)
1932
			return -1;
1933
		elseif ($a_time == $b_time)
1934
			return 0;
1935
		else
1936
			return 1;
1937
	}
1938
}
1939
function version_get_string_value($a) {
1940
	$strs = array(
1941
		0 => "ALPHA-ALPHA",
1942
		2 => "ALPHA",
1943
		3 => "BETA",
1944
		4 => "B",
1945
		5 => "C",
1946
		6 => "D",
1947
		7 => "RC",
1948
		8 => "RELEASE",
1949
		9 => "*"			// Matches all release levels
1950
	);
1951
	$major = 0;
1952
	$minor = 0;
1953
	foreach ($strs as $num => $str) {
1954
		if (substr($a, 0, strlen($str)) == $str) {
1955
			$major = $num;
1956
			$n = substr($a, strlen($str));
1957
			if (is_numeric($n))
1958
				$minor = $n;
1959
			break;
1960
		}
1961
	}
1962
	return "{$major}.{$minor}";
1963
}
1964
function version_compare_string($a, $b) {
1965
	// Only compare string parts if both versions give a specific release
1966
	// (If either version lacks a string part, assume intended to match all release levels)
1967
	if (isset($a) && isset($b))
1968
		return version_compare_numeric(version_get_string_value($a), version_get_string_value($b));
1969
	else
1970
		return 0;
1971
}
1972
function version_compare_numeric($a, $b) {
1973
	$a_arr = explode('.', rtrim($a, '.0'));
1974
	$b_arr = explode('.', rtrim($b, '.0'));
1975

    
1976
	foreach ($a_arr as $n => $val) {
1977
		if (array_key_exists($n, $b_arr)) {
1978
			// So far so good, both have values at this minor version level. Compare.
1979
			if ($val > $b_arr[$n])
1980
				return 1;
1981
			elseif ($val < $b_arr[$n])
1982
				return -1;
1983
		} else {
1984
			// a is greater, since b doesn't have any minor version here.
1985
			return 1;
1986
		}
1987
	}
1988
	if (count($b_arr) > count($a_arr)) {
1989
		// b is longer than a, so it must be greater.
1990
		return -1;
1991
	} else {
1992
		// Both a and b are of equal length and value.
1993
		return 0;
1994
	}
1995
}
1996
function pfs_version_compare($cur_time, $cur_text, $remote) {
1997
	// First try date compare
1998
	$v = version_compare_dates($cur_time, $remote);
1999
	if ($v === FALSE) {
2000
		// If that fails, try to compare by string
2001
		// Before anything else, simply test if the strings are equal
2002
		if (($cur_text == $remote) || ($cur_time == $remote))
2003
			return 0;
2004
		list($cur_num, $cur_str) = explode('-', $cur_text);
2005
		list($rem_num, $rem_str) = explode('-', $remote);
2006

    
2007
		// First try to compare the numeric parts of the version string.
2008
		$v = version_compare_numeric($cur_num, $rem_num);
2009

    
2010
		// If the numeric parts are the same, compare the string parts.
2011
		if ($v == 0)
2012
			return version_compare_string($cur_str, $rem_str);
2013
	}
2014
	return $v;
2015
}
2016
function process_alias_urltable($name, $url, $freq, $forceupdate=false) {
2017
	$urltable_prefix = "/var/db/aliastables/";
2018
	$urltable_filename = $urltable_prefix . $name . ".txt";
2019

    
2020
	// Make the aliases directory if it doesn't exist
2021
	if (!file_exists($urltable_prefix)) {
2022
		mkdir($urltable_prefix);
2023
	} elseif (!is_dir($urltable_prefix)) {
2024
		unlink($urltable_prefix);
2025
		mkdir($urltable_prefix);
2026
	}
2027

    
2028
	// If the file doesn't exist or is older than update_freq days, fetch a new copy.
2029
	if (!file_exists($urltable_filename)
2030
		|| ((time() - filemtime($urltable_filename)) > ($freq * 86400 - 90))
2031
		|| $forceupdate) {
2032

    
2033
		// Try to fetch the URL supplied
2034
		conf_mount_rw();
2035
		unlink_if_exists($urltable_filename . ".tmp");
2036
		// 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.
2037
		mwexec("/usr/bin/fetch -T 5 -q -o " . escapeshellarg($urltable_filename . ".tmp") . " " . escapeshellarg($url));
2038
		// Remove comments. Might need some grep-fu to only allow lines that look like IPs/subnets
2039
		if (file_exists($urltable_filename . ".tmp")) {
2040
			mwexec("/usr/bin/sed 's/\;.*//g' ". escapeshellarg($urltable_filename . ".tmp") . "| /usr/bin/egrep -v '^[[:space:]]*$|^#' > " . escapeshellarg($urltable_filename));
2041
			unlink_if_exists($urltable_filename . ".tmp");
2042
		} else
2043
			touch($urltable_filename);
2044
		conf_mount_ro();
2045
		return true;
2046
	} else {
2047
		// File exists, and it doesn't need updated.
2048
		return -1;
2049
	}
2050
}
2051
function get_real_slice_from_glabel($label) {
2052
	$label = escapeshellarg($label);
2053
	return trim(`/sbin/glabel list | /usr/bin/grep -B2 ufs/{$label} | /usr/bin/head -n 1 | /usr/bin/cut -f3 -d' '`);
2054
}
2055
function nanobsd_get_boot_slice() {
2056
	return trim(`/sbin/mount | /usr/bin/grep pfsense | /usr/bin/cut -d'/' -f4 | /usr/bin/cut -d' ' -f1`);
2057
}
2058
function nanobsd_get_boot_drive() {
2059
	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`);
2060
}
2061
function nanobsd_get_active_slice() {
2062
	$boot_drive = nanobsd_get_boot_drive();
2063
	$active = trim(`gpart show $boot_drive | grep '\[active\]' | awk '{print $3;}'`);
2064

    
2065
	return "{$boot_drive}s{$active}";
2066
}
2067
function nanobsd_get_size() {
2068
	return strtoupper(file_get_contents("/etc/nanosize.txt"));
2069
}
2070
function nanobsd_switch_boot_slice() {
2071
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2072
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2073
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2074
	nanobsd_detect_slice_info();
2075

    
2076
	if ($BOOTFLASH == $ACTIVE_SLICE) {
2077
		$slice = $TOFLASH;
2078
	} else {
2079
		$slice = $BOOTFLASH;
2080
	}
2081

    
2082
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
2083
	ob_implicit_flush(1);
2084
	if(strstr($slice, "s2")) {
2085
		$ASLICE="2";
2086
		$AOLDSLICE="1";
2087
		$AGLABEL_SLICE="pfsense1";
2088
		$AUFS_ID="1";
2089
		$AOLD_UFS_ID="0";
2090
	} else {
2091
		$ASLICE="1";
2092
		$AOLDSLICE="2";
2093
		$AGLABEL_SLICE="pfsense0";
2094
		$AUFS_ID="0";
2095
		$AOLD_UFS_ID="1";
2096
	}
2097
	$ATOFLASH="{$BOOT_DRIVE}s{$ASLICE}";
2098
	$ACOMPLETE_PATH="{$BOOT_DRIVE}s{$ASLICE}a";
2099
	$ABOOTFLASH="{$BOOT_DRIVE}s{$AOLDSLICE}";
2100
	conf_mount_rw();
2101
	exec("sysctl kern.geom.debugflags=16");
2102
	exec("gpart set -a active -i {$ASLICE} {$BOOT_DRIVE}");
2103
	exec("/usr/sbin/boot0cfg -s {$ASLICE} -v /dev/{$BOOT_DRIVE}");
2104
	// We can't update these if they are mounted now.
2105
	if ($BOOTFLASH != $slice) {
2106
		exec("/sbin/tunefs -L ${AGLABEL_SLICE} /dev/$ACOMPLETE_PATH");
2107
		nanobsd_update_fstab($AGLABEL_SLICE, $ACOMPLETE_PATH, $AOLD_UFS_ID, $AUFS_ID);
2108
	}
2109
	exec("/sbin/sysctl kern.geom.debugflags=0");
2110
	conf_mount_ro();
2111
}
2112
function nanobsd_clone_slice() {
2113
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2114
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2115
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2116
	nanobsd_detect_slice_info();
2117

    
2118
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
2119
	ob_implicit_flush(1);
2120
	exec("/sbin/sysctl kern.geom.debugflags=16");
2121
	exec("/bin/dd if=/dev/zero of=/dev/{$TOFLASH} bs=1m count=1");
2122
	exec("/bin/dd if=/dev/{$BOOTFLASH} of=/dev/{$TOFLASH} bs=64k");
2123
	exec("/sbin/tunefs -L {$GLABEL_SLICE} /dev/{$COMPLETE_PATH}");
2124
	$status = nanobsd_update_fstab($GLABEL_SLICE, $COMPLETE_PATH, $OLD_UFS_ID, $UFS_ID);
2125
	exec("/sbin/sysctl kern.geom.debugflags=0");
2126
	if($status) {
2127
		return false;
2128
	} else {
2129
		return true;
2130
	}
2131
}
2132
function nanobsd_update_fstab($gslice, $complete_path, $oldufs, $newufs) {
2133
	$tmppath = "/tmp/{$gslice}";
2134
	$fstabpath = "/tmp/{$gslice}/etc/fstab";
2135

    
2136
	mkdir($tmppath);
2137
	exec("/sbin/fsck_ufs -y /dev/{$complete_path}");
2138
	exec("/sbin/mount /dev/ufs/{$gslice} {$tmppath}");
2139
	copy("/etc/fstab", $fstabpath);
2140

    
2141
	if (!file_exists($fstabpath)) {
2142
		$fstab = <<<EOF
2143
/dev/ufs/{$gslice} / ufs ro,noatime 1 1
2144
/dev/ufs/cf /cf ufs ro,noatime 1 1
2145
EOF;
2146
		if (file_put_contents($fstabpath, $fstab))
2147
			$status = true;
2148
		else
2149
			$status = false;
2150
	} else {
2151
		$status = exec("sed -i \"\" \"s/pfsense{$oldufs}/pfsense{$newufs}/g\" {$fstabpath}");
2152
	}
2153
	exec("/sbin/umount {$tmppath}");
2154
	rmdir($tmppath);
2155

    
2156
	return $status;
2157
}
2158
function nanobsd_detect_slice_info() {
2159
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2160
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2161
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2162

    
2163
	$BOOT_DEVICE=nanobsd_get_boot_slice();
2164
	$REAL_BOOT_DEVICE=get_real_slice_from_glabel($BOOT_DEVICE);
2165
	$BOOT_DRIVE=nanobsd_get_boot_drive();
2166
	$ACTIVE_SLICE=nanobsd_get_active_slice();
2167

    
2168
	// Detect which slice is active and set information.
2169
	if(strstr($REAL_BOOT_DEVICE, "s1")) {
2170
		$SLICE="2";
2171
		$OLDSLICE="1";
2172
		$GLABEL_SLICE="pfsense1";
2173
		$UFS_ID="1";
2174
		$OLD_UFS_ID="0";
2175

    
2176
	} else {
2177
		$SLICE="1";
2178
		$OLDSLICE="2";
2179
		$GLABEL_SLICE="pfsense0";
2180
		$UFS_ID="0";
2181
		$OLD_UFS_ID="1";
2182
	}
2183
	$TOFLASH="{$BOOT_DRIVE}s{$SLICE}";
2184
	$COMPLETE_PATH="{$BOOT_DRIVE}s{$SLICE}a";
2185
	$COMPLETE_BOOT_PATH="{$BOOT_DRIVE}s{$OLDSLICE}";
2186
	$BOOTFLASH="{$BOOT_DRIVE}s{$OLDSLICE}";
2187
}
2188

    
2189
function nanobsd_friendly_slice_name($slicename) {
2190
	global $g;
2191
	return strtolower(str_ireplace('pfsense', $g['product_name'], $slicename));
2192
}
2193

    
2194
function get_include_contents($filename) {
2195
	if (is_file($filename)) {
2196
		ob_start();
2197
		include $filename;
2198
		$contents = ob_get_contents();
2199
		ob_end_clean();
2200
		return $contents;
2201
	}
2202
	return false;
2203
}
2204

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

    
2340
function get_country_name($country_code) {
2341
	if ($country_code != "ALL" && strlen($country_code) != 2)
2342
		return "";
2343

    
2344
	$country_names_xml = "/usr/local/share/mobile-broadband-provider-info/iso_3166-1_list_en.xml";
2345
	$country_names_contents = file_get_contents($country_names_xml);
2346
	$country_names = xml2array($country_names_contents);
2347

    
2348
	if($country_code == "ALL") {
2349
		$country_list = array();
2350
		foreach($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2351
			$country_list[] = array("code" => $country['ISO_3166-1_Alpha-2_Code_element'],
2352
						"name" => ucwords(strtolower($country['ISO_3166-1_Country_name'])) );
2353
		}
2354
		return $country_list;
2355
	}
2356

    
2357
	foreach ($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2358
		if ($country['ISO_3166-1_Alpha-2_Code_element'] == strtoupper($country_code)) {
2359
			return ucwords(strtolower($country['ISO_3166-1_Country_name']));
2360
		}
2361
	}
2362
	return "";
2363
}
2364

    
2365
/* sort by interface only, retain the original order of rules that apply to
2366
   the same interface */
2367
function filter_rules_sort() {
2368
	global $config;
2369

    
2370
	/* mark each rule with the sequence number (to retain the order while sorting) */
2371
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2372
		$config['filter']['rule'][$i]['seq'] = $i;
2373

    
2374
	usort($config['filter']['rule'], "filter_rules_compare");
2375

    
2376
	/* strip the sequence numbers again */
2377
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2378
		unset($config['filter']['rule'][$i]['seq']);
2379
}
2380
function filter_rules_compare($a, $b) {
2381
	if (isset($a['floating']) && isset($b['floating']))
2382
		return $a['seq'] - $b['seq'];
2383
	else if (isset($a['floating']))
2384
		return -1;
2385
	else if (isset($b['floating']))
2386
		return 1;
2387
	else if ($a['interface'] == $b['interface'])
2388
		return $a['seq'] - $b['seq'];
2389
	else
2390
		return compare_interface_friendly_names($a['interface'], $b['interface']);
2391
}
2392

    
2393
function generate_ipv6_from_mac($mac) {
2394
	$elements = explode(":", $mac);
2395
	if(count($elements) <> 6)
2396
		return false;
2397

    
2398
	$i = 0;
2399
	$ipv6 = "fe80::";
2400
	foreach($elements as $byte) {
2401
		if($i == 0) {
2402
			$hexadecimal =  substr($byte, 1, 2);
2403
			$bitmap = base_convert($hexadecimal, 16, 2);
2404
			$bitmap = str_pad($bitmap, 4, "0", STR_PAD_LEFT);
2405
			$bitmap = substr($bitmap, 0, 2) ."1". substr($bitmap, 3,4);
2406
			$byte = substr($byte, 0, 1) . base_convert($bitmap, 2, 16);
2407
		}
2408
		$ipv6 .= $byte;
2409
		if($i == 1) {
2410
			$ipv6 .= ":";
2411
		}
2412
		if($i == 3) {
2413
			$ipv6 .= ":";
2414
		}
2415
		if($i == 2) {
2416
			$ipv6 .= "ff:fe";
2417
		}
2418

    
2419
		$i++;
2420
	}
2421
	return $ipv6;
2422
}
2423

    
2424
/****f* pfsense-utils/load_mac_manufacturer_table
2425
 * NAME
2426
 *   load_mac_manufacturer_table
2427
 * INPUTS
2428
 *   none
2429
 * RESULT
2430
 *   returns associative array with MAC-Manufacturer pairs
2431
 ******/
2432
function load_mac_manufacturer_table() {
2433
	/* load MAC-Manufacture data from the file */
2434
	$macs = false;
2435
	if (file_exists("/usr/local/share/nmap/nmap-mac-prefixes"))
2436
		$macs=file("/usr/local/share/nmap/nmap-mac-prefixes");
2437
	if ($macs){
2438
		foreach ($macs as $line){
2439
			if (preg_match('/([0-9A-Fa-f]{6}) (.*)$/', $line, $matches)){
2440
				/* store values like this $mac_man['000C29']='VMware' */
2441
				$mac_man["$matches[1]"]=$matches[2];
2442
			}
2443
		}
2444
		return $mac_man;
2445
	} else
2446
		return -1;
2447

    
2448
}
2449

    
2450
/****f* pfsense-utils/is_ipaddr_configured
2451
 * NAME
2452
 *   is_ipaddr_configured
2453
 * INPUTS
2454
 *   IP Address to check.
2455
 * RESULT
2456
 *   returns true if the IP Address is
2457
 *   configured and present on this device.
2458
*/
2459
function is_ipaddr_configured($ipaddr, $ignore_if = "", $check_localip = false, $check_subnets = false) {
2460
	global $config;
2461

    
2462
	$isipv6 = is_ipaddrv6($ipaddr);
2463

    
2464
	if ($check_subnets) {
2465
		$iflist = get_configured_interface_list();
2466
		foreach ($iflist as $if => $ifname) {
2467
			if ($ignore_if == $if)
2468
				continue;
2469

    
2470
			if ($isipv6 === true) {
2471
				$bitmask = get_interface_subnetv6($if);
2472
				$subnet = gen_subnetv6(get_interface_ipv6($if), $bitmask);
2473
			} else {
2474
				$bitmask = get_interface_subnet($if);
2475
				$subnet = gen_subnet(get_interface_ip($if), $bitmask);
2476
			}
2477

    
2478
			if (ip_in_subnet($ipaddr, $subnet . '/' . $bitmask))
2479
				return true;
2480
		}
2481
	} else {
2482
		if ($isipv6 === true)
2483
			$interface_list_ips = get_configured_ipv6_addresses();
2484
		else
2485
			$interface_list_ips = get_configured_ip_addresses();
2486

    
2487
		foreach($interface_list_ips as $if => $ilips) {
2488
			/* Also ignore CARP interfaces, it'll be checked below */
2489
			if (($ignore_if == $if) || preg_match('/_vip[0-9]/', $if))
2490
				continue;
2491
			if (strcasecmp($ipaddr, $ilips) == 0)
2492
				return true;
2493
		}
2494
	}
2495

    
2496
	$interface_list_vips = get_configured_vips_list(true);
2497
	foreach ($interface_list_vips as $id => $vip) {
2498
		if ($ignore_if == "vip_{$id}")
2499
			continue;
2500
		if (strcasecmp($ipaddr, $vip['ipaddr']) == 0)
2501
			return true;
2502
	}
2503

    
2504
	if ($check_localip) {
2505
		if (is_array($config['pptpd']) && !empty($config['pptpd']['localip']) && (strcasecmp($ipaddr, $config['pptpd']['localip']) == 0))
2506
			return true;
2507

    
2508
		if (!is_array($config['l2tp']) && !empty($config['l2tp']['localip']) && (strcasecmp($ipaddr, $config['l2tp']['localip']) == 0))
2509
			return true;
2510
	}
2511

    
2512
	return false;
2513
}
2514

    
2515
/****f* pfsense-utils/pfSense_handle_custom_code
2516
 * NAME
2517
 *   pfSense_handle_custom_code
2518
 * INPUTS
2519
 *   directory name to process
2520
 * RESULT
2521
 *   globs the directory and includes the files
2522
 */
2523
function pfSense_handle_custom_code($src_dir) {
2524
	// Allow extending of the nat edit page and include custom input validation
2525
	if(is_dir("$src_dir")) {
2526
		$cf = glob($src_dir . "/*.inc");
2527
		foreach($cf as $nf) {
2528
			if($nf == "." || $nf == "..")
2529
				continue;
2530
			// Include the extra handler
2531
			include("$nf");
2532
		}
2533
	}
2534
}
2535

    
2536
function set_language($lang = 'en_US', $encoding = "ISO8859-1") {
2537
	putenv("LANG={$lang}.{$encoding}");
2538
	setlocale(LC_ALL, "{$lang}.{$encoding}");
2539
	textdomain("pfSense");
2540
	bindtextdomain("pfSense","/usr/local/share/locale");
2541
	bind_textdomain_codeset("pfSense","{$lang}.{$encoding}");
2542
}
2543

    
2544
function get_locale_list() {
2545
	$locales = array(
2546
		"en_US" => gettext("English"),
2547
		"pt_BR" => gettext("Portuguese (Brazil)"),
2548
	);
2549
	asort($locales);
2550
	return $locales;
2551
}
2552

    
2553
function return_hex_ipv4($ipv4) {
2554
	if(!is_ipaddrv4($ipv4))
2555
		return(false);
2556

    
2557
	/* we need the hex form of the interface IPv4 address */
2558
	$ip4arr = explode(".", $ipv4);
2559
	return (sprintf("%02x%02x%02x%02x", $ip4arr[0], $ip4arr[1], $ip4arr[2], $ip4arr[3]));
2560
}
2561

    
2562
function convert_ipv6_to_128bit($ipv6) {
2563
	if(!is_ipaddrv6($ipv6))
2564
		return(false);
2565

    
2566
	$ip6arr = array();
2567
	$ip6prefix = Net_IPv6::uncompress($ipv6);
2568
	$ip6arr = explode(":", $ip6prefix);
2569
	/* binary presentation of the prefix for all 128 bits. */
2570
	$ip6prefixbin = "";
2571
	foreach($ip6arr as $element) {
2572
		$ip6prefixbin .= sprintf("%016b", hexdec($element));
2573
	}
2574
	return($ip6prefixbin);
2575
}
2576

    
2577
function convert_128bit_to_ipv6($ip6bin) {
2578
	if(strlen($ip6bin) <> 128)
2579
		return(false);
2580

    
2581
	$ip6arr = array();
2582
	$ip6binarr = array();
2583
	$ip6binarr = str_split($ip6bin, 16);
2584
	foreach($ip6binarr as $binpart)
2585
		$ip6arr[] = dechex(bindec($binpart));
2586
	$ip6addr = Net_IPv6::compress(implode(":", $ip6arr));
2587

    
2588
	return($ip6addr);
2589
}
2590

    
2591

    
2592
/* Returns the calculated bit length of the prefix delegation from the WAN interface */
2593
/* DHCP-PD is variable, calculate from the prefix-len on the WAN interface */
2594
/* 6rd is variable, calculate from 64 - (v6 prefixlen - (32 - v4 prefixlen)) */
2595
/* 6to4 is 16 bits, e.g. 65535 */
2596
function calculate_ipv6_delegation_length($if) {
2597
	global $config;
2598

    
2599
	if(!is_array($config['interfaces'][$if]))
2600
		return false;
2601

    
2602
	switch($config['interfaces'][$if]['ipaddrv6']) {
2603
		case "6to4":
2604
			$pdlen = 16;
2605
			break;
2606
		case "6rd":
2607
			$rd6cfg = $config['interfaces'][$if];
2608
			$rd6plen = explode("/", $rd6cfg['prefix-6rd']);
2609
			$pdlen = (64 - ($rd6plen[1] + (32 - $rd6cfg['prefix-6rd-v4plen'])));
2610
			break;
2611
		case "dhcp6":
2612
			$dhcp6cfg = $config['interfaces'][$if];
2613
			$pdlen = $dhcp6cfg['dhcp6-ia-pd-len'];
2614
			break;
2615
		default:
2616
			$pdlen = 0;
2617
			break;
2618
	}
2619
	return($pdlen);
2620
}
2621

    
2622
function huawei_rssi_to_string($rssi) {
2623
	$dbm = array();
2624
	$i = 0;
2625
	$dbstart = -113;
2626
	while($i < 32) {
2627
		$dbm[$i] = $dbstart + ($i * 2);
2628
		$i++;
2629
	}
2630
	$percent = round(($rssi / 31) * 100);
2631
	$string = "rssi:{$rssi} level:{$dbm[$rssi]}dBm percent:{$percent}%";
2632
	return $string;
2633
}
2634

    
2635
function huawei_mode_to_string($mode, $submode) {
2636
	$modes[0] = "None";
2637
	$modes[1] = "AMPS";
2638
	$modes[2] = "CDMA";
2639
	$modes[3] = "GSM/GPRS";
2640
	$modes[4] = "HDR";
2641
	$modes[5] = "WCDMA";
2642
	$modes[6] = "GPS";
2643

    
2644
	$submodes[0] = "No Service";
2645
	$submodes[1] = "GSM";
2646
	$submodes[2] = "GPRS";
2647
	$submodes[3] = "EDGE";
2648
	$submodes[4] = "WCDMA";
2649
	$submodes[5] = "HSDPA";
2650
	$submodes[6] = "HSUPA";
2651
	$submodes[7] = "HSDPA+HSUPA";
2652
	$submodes[8] = "TD-SCDMA";
2653
	$submodes[9] = "HSPA+";
2654
	$string = "{$modes[$mode]}, {$submodes[$submode]} Mode";
2655
	return $string;
2656
}
2657

    
2658
function huawei_service_to_string($state) {
2659
	$modes[0] = "No";
2660
	$modes[1] = "Restricted";
2661
	$modes[2] = "Valid";
2662
	$modes[3] = "Restricted Regional";
2663
	$modes[4] = "Powersaving";
2664
	$string = "{$modes[$state]} Service";
2665
	return $string;
2666
}
2667

    
2668
function huawei_simstate_to_string($state) {
2669
	$modes[0] = "Invalid SIM/locked";
2670
	$modes[1] = "Valid SIM";
2671
	$modes[2] = "Invalid SIM CS";
2672
	$modes[3] = "Invalid SIM PS";
2673
	$modes[4] = "Invalid SIM CS/PS";
2674
	$modes[255] = "Missing SIM";
2675
	$string = "{$modes[$state]} State";
2676
	return $string;
2677
}
2678

    
2679
function zte_rssi_to_string($rssi) {
2680
	return huawei_rssi_to_string($rssi);
2681
}
2682

    
2683
function zte_mode_to_string($mode, $submode) {
2684
	$modes[0] = "No Service";
2685
	$modes[1] = "Limited Service";
2686
	$modes[2] = "GPRS";
2687
	$modes[3] = "GSM";
2688
	$modes[4] = "UMTS";
2689
	$modes[5] = "EDGE";
2690
	$modes[6] = "HSDPA";
2691

    
2692
	$submodes[0] = "CS_ONLY";
2693
	$submodes[1] = "PS_ONLY";
2694
	$submodes[2] = "CS_PS";
2695
	$submodes[3] = "CAMPED";
2696
	$string = "{$modes[$mode]}, {$submodes[$submode]} Mode";
2697
	return $string;
2698
}
2699

    
2700
function zte_service_to_string($state) {
2701
	$modes[0] = "Initializing";
2702
	$modes[1] = "Network Lock error";
2703
	$modes[2] = "Network Locked";
2704
	$modes[3] = "Unlocked or correct MCC/MNC";
2705
	$string = "{$modes[$state]} Service";
2706
	return $string;
2707
}
2708

    
2709
function zte_simstate_to_string($state) {
2710
	$modes[0] = "No action";
2711
	$modes[1] = "Network lock";
2712
	$modes[2] = "(U)SIM card lock";
2713
	$modes[3] = "Network Lock and (U)SIM card Lock";
2714
	$string = "{$modes[$state]} State";
2715
	return $string;
2716
}
2717

    
2718
function get_configured_pppoe_server_interfaces() {
2719
	global $config;
2720
	$iflist = array();
2721
	if (is_array($config['pppoes']['pppoe'])) {
2722
		foreach($config['pppoes']['pppoe'] as $pppoe) {
2723
			if ($pppoe['mode'] == "server") {
2724
				$int = "poes". $pppoe['pppoeid'];
2725
				$iflist[$int] = strtoupper($int);
2726
			}
2727
		}
2728
	}
2729
	return $iflist;
2730
}
2731

    
2732
function get_pppoes_child_interfaces($ifpattern) {
2733
	$if_arr = array();
2734
	if($ifpattern == "")
2735
		return;
2736

    
2737
	exec("ifconfig", $out, $ret);
2738
	foreach($out as $line) {
2739
		if(preg_match("/^({$ifpattern}[0-9]+):/i", $line, $match)) {
2740
			$if_arr[] = $match[1];
2741
		}
2742
	}
2743
	return $if_arr;
2744

    
2745
}
2746

    
2747
?>
(39-39/66)