Projet

Général

Profil

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

univnautes / etc / inc / pfsense-utils.inc @ 02406801

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

    
328
	/* XXX: Need to fidn a better way for this! */
329
	list ($interface, $vhid) = explode("_vip", $carpinterface);
330
	$interface = get_real_interface($interface);
331
	exec("/sbin/ifconfig $interface | /usr/bin/grep -v grep | /usr/bin/grep carp: | /usr/bin/grep 'vhid {$vhid}'", $carp_query);
332
	foreach($carp_query as $int) {
333
		if(stristr($int, "MASTER"))
334
			return gettext("MASTER");
335
		if(stristr($int, "BACKUP"))
336
			return gettext("BACKUP");
337
		if(stristr($int, "INIT"))
338
			return gettext("INIT");
339
	}
340
	return;
341
}
342

    
343
/*
344
 * get_pfsync_interface_status($pfsyncinterface): returns the status of a pfsync
345
 */
346
function get_pfsync_interface_status($pfsyncinterface) {
347
	if (!does_interface_exist($pfsyncinterface))
348
		return;
349

    
350
	return exec_command("/sbin/ifconfig {$pfsyncinterface} | /usr/bin/awk '/pfsync:/ {print \$5}'");
351
}
352

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

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

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

    
384
		$file_text = implode("\n", $filecontents);
385

    
386
		@file_put_contents($file, $file_text);
387
		return true;
388
	}
389
	return false;
390
}
391

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

    
409
/*
410
 * get_filename_from_url($url): converts a url to its filename.
411
 */
412
function get_filename_from_url($url) {
413
	return basename($url);
414
}
415

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

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

    
440
	for ($a=0; $a < 6; $a++)
441
		$hw_addr .= chr(hexdec($addr_byte[$a]));
442

    
443
	$msg = chr(255).chr(255).chr(255).chr(255).chr(255).chr(255);
444

    
445
	for ($a = 1; $a <= 16; $a++)
446
		$msg .= $hw_addr;
447

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

    
464
	return false;
465
}
466

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

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

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

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

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

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

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

    
572
";
573

    
574
	$errno = "";
575
	$errstr = "";
576
	$fp = fsockopen($server, $port, $errno, $errstr);
577
	if (!$fp) {
578
		return false;
579
	}
580

    
581
	fputs($fp, $headers);
582
	fputs($fp, $urlencoded);
583

    
584
	$ret = "";
585
	while (!feof($fp))
586
		$ret.= fgets($fp, 1024);
587
	fclose($fp);
588

    
589
	return $ret;
590
}
591

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

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

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

    
667
/*
668
 * call_pfsense_method(): Call a method exposed by the pfsense.org XMLRPC server.
669
 */
670
function call_pfsense_method($method, $params, $timeout = 0) {
671
	global $g, $config;
672

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

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

    
715
/*
716
 * check_firmware_version(): Check whether the current firmware installed is the most recently released.
717
 */
718
function check_firmware_version($tocheck = "all", $return_php = true) {
719
	global $g, $config;
720
	
721
	$xmlrpc_base_url = isset($config['system']['altpkgrepo']['enable']) ? $config['system']['altpkgrepo']['xmlrpcbaseurl'] : $g['xmlrpcbaseurl'];
722
	$xmlrpcfqdn = preg_replace("(https?://)", "", $xmlrpc_base_url);
723
	$ip = gethostbyname($xmlrpcfqdn);
724
	if($ip == $xmlrpcfqdn)
725
		return false;
726
	$version = php_uname('r');
727
	$version = explode('-', $version);
728
	$rawparams = array("firmware" => array("version" => trim(file_get_contents('/etc/version'))),
729
		"kernel"   => array("version" => $version[0]),
730
		"base"     => array("version" => $version[0]),
731
		"platform" => trim(file_get_contents('/etc/platform')),
732
		"config_version" => $config['version']
733
		);
734
	unset($version);
735

    
736
	if($tocheck == "all") {
737
		$params = $rawparams;
738
	} else {
739
		foreach($tocheck as $check) {
740
			$params['check'] = $rawparams['check'];
741
			$params['platform'] = $rawparams['platform'];
742
		}
743
	}
744
	if($config['system']['firmware']['branch'])
745
		$params['branch'] = $config['system']['firmware']['branch'];
746

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

    
754
	return $versions;
755
}
756

    
757
/*
758
 * host_firmware_version(): Return the versions used in this install
759
 */
760
function host_firmware_version($tocheck = "") {
761
	global $g, $config;
762

    
763
	$os_version = trim(substr(php_uname("r"), 0, strpos(php_uname("r"), '-')));
764

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

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

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

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

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

    
810
	/* parse config.xml again */
811
	$config = parse_config(true);
812

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

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

    
821
	/* set up interfaces */
822
	interfaces_configure();
823
}
824

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

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

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

    
860
	$g['booting'] = false;
861

    
862
	/* parse config.xml again */
863
	$config = parse_config(true);
864

    
865
	/* set up our timezone */
866
	system_timezone_configure();
867

    
868
	/* set up our hostname */
869
	system_hostname_configure();
870

    
871
	/* make hosts file */
872
	system_hosts_generate();
873

    
874
	/* generate resolv.conf */
875
	system_resolvconf_generate();
876

    
877
	/* enable routing */
878
	system_routing_enable();
879

    
880
	/* set up interfaces */
881
	interfaces_configure();
882

    
883
	/* start dyndns service */
884
	services_dyndns_configure();
885

    
886
	/* configure cron service */
887
	configure_cron();
888

    
889
	/* start the NTP client */
890
	system_ntp_configure();
891

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

    
898
	/* restart sshd */
899
	send_event("service restart sshd");
900

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

    
905
function auto_login() {
906
	global $config;
907

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

    
913
	$gettytab = file_get_contents("/etc/gettytab");
914
	$getty_split = explode("\n", $gettytab);
915
	$getty_update_needed = false;
916
	$getty_search_str = ":ht:np:sp#115200";
917
	$getty_al_str = ":al=root:";
918
	$getty_al_search_str = $getty_search_str . $getty_al_str;
919
	/* Check if gettytab is already OK, if so then do not rewrite it. */
920
	foreach($getty_split as $gs) {
921
		if(stristr($gs, $getty_search_str)) {
922
			if($status == true) {
923
				if(!stristr($gs, $getty_al_search_str)) {
924
					$getty_update_needed = true;
925
				}
926
			} else {
927
				if(stristr($gs, $getty_al_search_str)) {
928
					$getty_update_needed = true;
929
				}
930
			}
931
		}
932
	}
933

    
934
	if (!$getty_update_needed) {
935
		return;
936
	}
937

    
938
	conf_mount_rw();
939
	$fd = false;
940
	$tries = 0;
941
	while (!$fd && $tries < 100) {
942
		$fd = fopen("/etc/gettytab", "w");
943
		$tries++;
944

    
945
	}
946
	if (!$fd) {
947
		conf_mount_ro();
948
		if ($status) {
949
			log_error(gettext("Enabling auto login was not possible."));
950
		} else {
951
			log_error(gettext("Disabling auto login was not possible."));
952
		}
953
		return;
954
	}
955
	foreach($getty_split as $gs) {
956
		if(stristr($gs, $getty_search_str)) {
957
			if($status == true) {
958
				fwrite($fd, "	".$getty_al_search_str."\n");
959
			} else {
960
				fwrite($fd, "	".$getty_search_str."\n");
961
			}
962
		} else {
963
			fwrite($fd, "{$gs}\n");
964
		}
965
	}
966
	fclose($fd);
967

    
968
	if ($status) {
969
		log_error(gettext("Enabled console auto login, console menu is NOT password protected."));
970
	} else {
971
		log_error(gettext("Disabled console auto login, console menu is password protected."));
972
	}
973

    
974
	conf_mount_ro();
975
}
976

    
977
function setup_serial_port($when="save", $path="") {
978
	global $g, $config;
979
	conf_mount_rw();
980
	$prefix = "";
981
	if (($when == "upgrade") && (!empty($path)) && is_dir($path.'/boot/'))
982
		$prefix = "/tmp/{$path}";
983
	$boot_config_file = "{$path}/boot.config";
984
	$loader_conf_file = "{$path}/boot/loader.conf";
985
	/* serial console - write out /boot.config */
986
	if(file_exists($boot_config_file))
987
		$boot_config = file_get_contents($boot_config_file);
988
	else
989
		$boot_config = "";
990

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

    
1027
			$serialspeed = (is_numeric($config['system']['serialspeed'])) ? $config['system']['serialspeed'] : "9600";
1028
			if(isset($config['system']['enableserial']) || $g['enableserial_force']) {
1029
				$new_boot_config[] = 'boot_multicons="YES"';
1030
				$new_boot_config[] = 'boot_serial="YES"';
1031
				$new_boot_config[] = 'comconsole_speed="' . $serialspeed . '"';
1032
				$primaryconsole = isset($g['primaryconsole_force']) ? $g['primaryconsole_force'] : $config['system']['primaryconsole'];
1033
				switch ($primaryconsole) {
1034
					case "video":
1035
						$new_boot_config[] = 'console="vidconsole,comconsole"';
1036
						break;
1037
					case "serial":
1038
					default:
1039
						$new_boot_config[] = 'console="comconsole,vidconsole"';
1040
				}
1041
			} elseif ($g['platform'] == "nanobsd") {
1042
				$new_boot_config[] = 'comconsole_speed="' . $serialspeed . '"';
1043
			}
1044

    
1045
			$new_boot_config[] = 'hw.usb.no_pf="1"';
1046

    
1047
			file_put_contents($loader_conf_file, implode("\n", $new_boot_config) . "\n");
1048
		}
1049
	}
1050
	$ttys = file_get_contents("/etc/ttys");
1051
	$ttys_split = explode("\n", $ttys);
1052
	$fd = fopen("/etc/ttys", "w");
1053
	foreach($ttys_split as $tty) {
1054
		if(stristr($tty, "ttyd0") or stristr($tty, "ttyu0")) {
1055
			if(isset($config['system']['enableserial']) || $g['enableserial_force']) {
1056
				fwrite($fd, "ttyu0	\"/usr/libexec/getty bootupcli\"	cons25	on	secure\n");
1057
			} else {
1058
				fwrite($fd, "ttyu0	\"/usr/libexec/getty bootupcli\"	cons25	off	secure\n");
1059
			}
1060
		} else {
1061
			fwrite($fd, $tty . "\n");
1062
		}
1063
	}
1064
	fclose($fd);
1065
	auto_login();
1066

    
1067
	conf_mount_ro();
1068
	return;
1069
}
1070

    
1071
function print_value_list($list, $count = 10, $separator = ",") {
1072
	$list = implode($separator, array_slice($list, 0, $count));
1073
	if(count($list) < $count) {
1074
		$list .= ".";
1075
	} else {
1076
		$list .= "...";
1077
	}
1078
	return $list;
1079
}
1080

    
1081
/* DHCP enabled on any interfaces? */
1082
function is_dhcp_server_enabled() {
1083
	global $config;
1084

    
1085
	if (!is_array($config['dhcpd']))
1086
		return false;
1087

    
1088
	foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf) {
1089
		if (isset($dhcpifconf['enable']) && !empty($config['interfaces'][$dhcpif]))
1090
			return true;
1091
	}
1092

    
1093
	return false;
1094
}
1095

    
1096
/* DHCP enabled on any interfaces? */
1097
function is_dhcpv6_server_enabled() {
1098
	global $config;
1099

    
1100
	if (is_array($config['interfaces'])) {
1101
		foreach ($config['interfaces'] as $ifcfg) {
1102
			if (isset($ifcfg['enable']) && !empty($ifcfg['track6-interface']))
1103
				return true;
1104
		}
1105
	}
1106

    
1107
	if (!is_array($config['dhcpdv6']))
1108
		return false;
1109

    
1110
	foreach ($config['dhcpdv6'] as $dhcpv6if => $dhcpv6ifconf) {
1111
		if (isset($dhcpv6ifconf['enable']) && !empty($config['interfaces'][$dhcpv6if]))
1112
			return true;
1113
	}
1114

    
1115
	return false;
1116
}
1117

    
1118
/* radvd enabled on any interfaces? */
1119
function is_radvd_enabled() {
1120
	global $config;
1121

    
1122
	if (!is_array($config['dhcpdv6']))
1123
		$config['dhcpdv6'] = array();
1124

    
1125
	$dhcpdv6cfg = $config['dhcpdv6'];
1126
	$Iflist = get_configured_interface_list();
1127

    
1128
	/* handle manually configured DHCP6 server settings first */
1129
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1130
		if(!isset($config['interfaces'][$dhcpv6if]['enable']))
1131
			continue;
1132

    
1133
		if(!isset($dhcpv6ifconf['ramode']))
1134
			$dhcpv6ifconf['ramode'] = $dhcpv6ifconf['mode'];
1135

    
1136
		if($dhcpv6ifconf['ramode'] == "disabled")
1137
			continue;
1138

    
1139
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1140
		if(!is_ipaddrv6($ifcfgipv6))
1141
			continue;
1142

    
1143
		return true;
1144
	}
1145

    
1146
	/* handle DHCP-PD prefixes and 6RD dynamic interfaces */
1147
	foreach ($Iflist as $if => $ifdescr) {
1148
		if(!isset($config['interfaces'][$if]['track6-interface']))
1149
			continue;
1150
		if(!isset($config['interfaces'][$if]['enable']))
1151
			continue;
1152

    
1153
		$ifcfgipv6 = get_interface_ipv6($if);
1154
		if(!is_ipaddrv6($ifcfgipv6))
1155
			continue;
1156

    
1157
		$ifcfgsnv6 = get_interface_subnetv6($if);
1158
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1159

    
1160
		if(!is_ipaddrv6($subnetv6))
1161
			continue;
1162

    
1163
		return true;
1164
	}
1165

    
1166
	return false;
1167
}
1168

    
1169
/* Any PPPoE servers enabled? */
1170
function is_pppoe_server_enabled() {
1171
	global $config;
1172

    
1173
	$pppoeenable = false;
1174

    
1175
	if (!is_array($config['pppoes']) || !is_array($config['pppoes']['pppoe']))
1176
		return false;
1177

    
1178
	foreach ($config['pppoes']['pppoe'] as $pppoes)
1179
		if ($pppoes['mode'] == 'server')
1180
			$pppoeenable = true;
1181

    
1182
	return $pppoeenable;
1183
}
1184

    
1185
function convert_seconds_to_hms($sec){
1186
	$min=$hrs=0;
1187
	if ($sec != 0){
1188
		$min = floor($sec/60);
1189
		$sec %= 60;
1190
	}
1191
	if ($min != 0){
1192
		$hrs = floor($min/60);
1193
		$min %= 60;
1194
	}
1195
	if ($sec < 10)
1196
		$sec = "0".$sec;
1197
	if ($min < 10)
1198
		$min = "0".$min;
1199
	if ($hrs < 10)
1200
		$hrs = "0".$hrs;
1201
	$result = $hrs.":".$min.":".$sec;
1202
	return $result;
1203
}
1204

    
1205
/* Compute the total uptime from the ppp uptime log file in the conf directory */
1206

    
1207
function get_ppp_uptime($port){
1208
	if (file_exists("/conf/{$port}.log")){
1209
		$saved_time = file_get_contents("/conf/{$port}.log");
1210
		$uptime_data = explode("\n",$saved_time);
1211
		$sec=0;
1212
		foreach($uptime_data as $upt) {
1213
			$sec += substr($upt, 1 + strpos($upt, " "));
1214
		}
1215
		return convert_seconds_to_hms($sec);
1216
	} else {
1217
		$total_time = gettext("No history data found!");
1218
		return $total_time;
1219
	}
1220
}
1221

    
1222
//returns interface information
1223
function get_interface_info($ifdescr) {
1224
	global $config, $g;
1225

    
1226
	$ifinfo = array();
1227
	if (empty($config['interfaces'][$ifdescr]))
1228
		return;
1229
	$ifinfo['hwif'] = $config['interfaces'][$ifdescr]['if'];
1230
	$ifinfo['if'] = get_real_interface($ifdescr);
1231

    
1232
	$chkif = $ifinfo['if'];
1233
	$ifinfotmp = pfSense_get_interface_addresses($chkif);
1234
	$ifinfo['status'] = $ifinfotmp['status'];
1235
	if (empty($ifinfo['status']))
1236
		$ifinfo['status'] = "down";
1237
	$ifinfo['macaddr'] = $ifinfotmp['macaddr'];
1238
	$ifinfo['ipaddr'] = $ifinfotmp['ipaddr'];
1239
	$ifinfo['subnet'] = $ifinfotmp['subnet'];
1240
	$ifinfo['linklocal'] = get_interface_linklocal($ifdescr);
1241
	$ifinfo['ipaddrv6'] = get_interface_ipv6($ifdescr);
1242
	$ifinfo['subnetv6'] = get_interface_subnetv6($ifdescr);
1243
	if (isset($ifinfotmp['link0']))
1244
		$link0 = "down";
1245
	$ifinfotmp = pfSense_get_interface_stats($chkif);
1246
	// $ifinfo['inpkts'] = $ifinfotmp['inpkts'];
1247
	// $ifinfo['outpkts'] = $ifinfotmp['outpkts'];
1248
	$ifinfo['inerrs'] = $ifinfotmp['inerrs'];
1249
	$ifinfo['outerrs'] = $ifinfotmp['outerrs'];
1250
	$ifinfo['collisions'] = $ifinfotmp['collisions'];
1251

    
1252
	/* Use pfctl for non wrapping 64 bit counters */
1253
	/* Pass */
1254
	exec("/sbin/pfctl -vvsI -i {$chkif}", $pfctlstats);
1255
	$pf_in4_pass = preg_split("/ +/ ", $pfctlstats[3]);
1256
	$pf_out4_pass = preg_split("/ +/", $pfctlstats[5]);
1257
	$pf_in6_pass = preg_split("/ +/ ", $pfctlstats[7]);
1258
	$pf_out6_pass = preg_split("/ +/", $pfctlstats[9]);
1259
	$in4_pass = $pf_in4_pass[5];
1260
	$out4_pass = $pf_out4_pass[5];
1261
	$in4_pass_packets = $pf_in4_pass[3];
1262
	$out4_pass_packets = $pf_out4_pass[3];
1263
	$in6_pass = $pf_in6_pass[5];
1264
	$out6_pass = $pf_out6_pass[5];
1265
	$in6_pass_packets = $pf_in6_pass[3];
1266
	$out6_pass_packets = $pf_out6_pass[3];
1267
	$ifinfo['inbytespass'] = $in4_pass + $in6_pass;
1268
	$ifinfo['outbytespass'] = $out4_pass + $out6_pass;
1269
	$ifinfo['inpktspass'] = $in4_pass_packets + $in6_pass_packets;
1270
	$ifinfo['outpktspass'] = $out4_pass_packets + $out6_pass_packets;
1271

    
1272
	/* Block */
1273
	$pf_in4_block = preg_split("/ +/", $pfctlstats[4]);
1274
	$pf_out4_block = preg_split("/ +/", $pfctlstats[6]);
1275
	$pf_in6_block = preg_split("/ +/", $pfctlstats[8]);
1276
	$pf_out6_block = preg_split("/ +/", $pfctlstats[10]);
1277
	$in4_block = $pf_in4_block[5];
1278
	$out4_block = $pf_out4_block[5];
1279
	$in4_block_packets = $pf_in4_block[3];
1280
	$out4_block_packets = $pf_out4_block[3];
1281
	$in6_block = $pf_in6_block[5];
1282
	$out6_block = $pf_out6_block[5];
1283
	$in6_block_packets = $pf_in6_block[3];
1284
	$out6_block_packets = $pf_out6_block[3];
1285
	$ifinfo['inbytesblock'] = $in4_block + $in6_block;
1286
	$ifinfo['outbytesblock'] = $out4_block + $out6_block;
1287
	$ifinfo['inpktsblock'] = $in4_block_packets + $in6_block_packets;
1288
	$ifinfo['outpktsblock'] = $out4_block_packets + $out6_block_packets;
1289

    
1290
	$ifinfo['inbytes'] = $in4_pass + $in6_pass;
1291
	$ifinfo['outbytes'] = $out4_pass + $out6_pass;
1292
	$ifinfo['inpkts'] = $in4_pass_packets + $in6_pass_packets;
1293
	$ifinfo['outpkts'] = $out4_pass_packets + $out6_pass_packets;
1294

    
1295
	$ifconfiginfo = "";
1296
	$link_type = $config['interfaces'][$ifdescr]['ipaddr'];
1297
	switch ($link_type) {
1298
	/* DHCP? -> see if dhclient is up */
1299
	case "dhcp":
1300
		/* see if dhclient is up */
1301
		if (find_dhclient_process($ifinfo['if']) <> "")
1302
			$ifinfo['dhcplink'] = "up";
1303
		else
1304
			$ifinfo['dhcplink'] = "down";
1305

    
1306
		break;
1307
	/* PPPoE/PPTP/L2TP interface? -> get status from virtual interface */
1308
	case "pppoe":
1309
	case "pptp":
1310
	case "l2tp":
1311
		if ($ifinfo['status'] == "up" && !isset($link0))
1312
			/* get PPPoE link status for dial on demand */
1313
			$ifinfo["{$link_type}link"] = "up";
1314
		else
1315
			$ifinfo["{$link_type}link"] = "down";
1316

    
1317
		break;
1318
	/* PPP interface? -> get uptime for this session and cumulative uptime from the persistant log file in conf */
1319
	case "ppp":
1320
		if ($ifinfo['status'] == "up")
1321
			$ifinfo['ppplink'] = "up";
1322
		else
1323
			$ifinfo['ppplink'] = "down" ;
1324

    
1325
		if (empty($ifinfo['status']))
1326
			$ifinfo['status'] = "down";
1327

    
1328
		if (is_array($config['ppps']['ppp']) && count($config['ppps']['ppp'])) {
1329
			foreach ($config['ppps']['ppp'] as $pppid => $ppp) {
1330
				if ($config['interfaces'][$ifdescr]['if'] == $ppp['if'])
1331
					break;
1332
			}
1333
		}
1334
		$dev = $ppp['ports'];
1335
		if ($config['interfaces'][$ifdescr]['if'] != $ppp['if'] || empty($dev))
1336
			break;
1337
		if (!file_exists($dev)) {
1338
			$ifinfo['nodevice'] = 1;
1339
			$ifinfo['pppinfo'] = $dev . " " . gettext("device not present! Is the modem attached to the system?");
1340
		}
1341

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

    
1376
	if (file_exists("{$g['varrun_path']}/{$link_type}_{$ifdescr}.pid")) {
1377
		$sec = trim(`/usr/local/sbin/ppp-uptime.sh {$ifinfo['if']}`);
1378
		$ifinfo['ppp_uptime'] = convert_seconds_to_hms($sec);
1379
	}
1380

    
1381
	if ($ifinfo['status'] == "up") {
1382
		/* try to determine media with ifconfig */
1383
		unset($ifconfiginfo);
1384
		exec("/sbin/ifconfig " . $ifinfo['if'], $ifconfiginfo);
1385
		$wifconfiginfo = array();
1386
		if(is_interface_wireless($ifdescr)) {
1387
			exec("/sbin/ifconfig {$ifinfo['if']} list sta", $wifconfiginfo);
1388
			array_shift($wifconfiginfo);
1389
		}
1390
		$matches = "";
1391
		foreach ($ifconfiginfo as $ici) {
1392

    
1393
			/* don't list media/speed for wireless cards, as it always
1394
			   displays 2 Mbps even though clients can connect at 11 Mbps */
1395
			if (preg_match("/media: .*? \((.*?)\)/", $ici, $matches)) {
1396
				$ifinfo['media'] = $matches[1];
1397
			} else if (preg_match("/media: Ethernet (.*)/", $ici, $matches)) {
1398
				$ifinfo['media'] = $matches[1];
1399
			} else if (preg_match("/media: IEEE 802.11 Wireless Ethernet (.*)/", $ici, $matches)) {
1400
				$ifinfo['media'] = $matches[1];
1401
			}
1402

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

    
1437
		}
1438
		/* lookup the gateway */
1439
		if (interface_has_gateway($ifdescr)) {
1440
			$ifinfo['gateway'] = get_interface_gateway($ifdescr);
1441
			$ifinfo['gatewayv6'] = get_interface_gateway_v6($ifdescr);
1442
		}
1443
	}
1444

    
1445
	$bridge = "";
1446
	$bridge = link_interface_to_bridge($ifdescr);
1447
	if($bridge) {
1448
		$bridge_text = `/sbin/ifconfig {$bridge}`;
1449
		if(stristr($bridge_text, "blocking") <> false) {
1450
			$ifinfo['bridge'] = "<b><font color='red'>" . gettext("blocking") . "</font></b> - " . gettext("check for ethernet loops");
1451
			$ifinfo['bridgeint'] = $bridge;
1452
		} else if(stristr($bridge_text, "learning") <> false) {
1453
			$ifinfo['bridge'] = gettext("learning");
1454
			$ifinfo['bridgeint'] = $bridge;
1455
		} else if(stristr($bridge_text, "forwarding") <> false) {
1456
			$ifinfo['bridge'] = gettext("forwarding");
1457
			$ifinfo['bridgeint'] = $bridge;
1458
		}
1459
	}
1460

    
1461
	return $ifinfo;
1462
}
1463

    
1464
//returns cpu speed of processor. Good for determining capabilities of machine
1465
function get_cpu_speed() {
1466
	return exec("/sbin/sysctl -n hw.clockrate");
1467
}
1468

    
1469
function get_uptime_sec() {
1470
	$boottime = "";
1471
	$matches = "";
1472
	exec("/sbin/sysctl -n kern.boottime", $boottime);
1473
	preg_match("/sec = (\d+)/", $boottime[0], $matches);
1474
	$boottime = $matches[1];
1475
	if(intval($boottime) == 0)
1476
		return 0;
1477

    
1478
	$uptime = time() - $boottime;
1479
	return $uptime;
1480
}
1481

    
1482
function add_hostname_to_watch($hostname) {
1483
	if(!is_dir("/var/db/dnscache")) {
1484
		mkdir("/var/db/dnscache");
1485
	}
1486
	$result = array();
1487
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1488
		$domrecords = array();
1489
		$domips = array();
1490
		exec("host -t A " . escapeshellarg($hostname), $domrecords, $rethost);
1491
		if($rethost == 0) {
1492
			foreach($domrecords as $domr) {
1493
				$doml = explode(" ", $domr);
1494
				$domip = $doml[3];
1495
				/* fill array with domain ip addresses */
1496
				if(is_ipaddr($domip)) {
1497
					$domips[] = $domip;
1498
				}
1499
			}
1500
		}
1501
		sort($domips);
1502
		$contents = "";
1503
		if(! empty($domips)) {
1504
			foreach($domips as $ip) {
1505
				$contents .= "$ip\n";
1506
			}
1507
		}
1508
		file_put_contents("/var/db/dnscache/$hostname", $contents);
1509
		/* Remove empty elements */
1510
		$result = array_filter(explode("\n", $contents), 'strlen');
1511
	}
1512
	return $result;
1513
}
1514

    
1515
function is_fqdn($fqdn) {
1516
	$hostname = false;
1517
	if(preg_match("/[-A-Z0-9\.]+\.[-A-Z0-9\.]+/i", $fqdn)) {
1518
		$hostname = true;
1519
	}
1520
	if(preg_match("/\.\./", $fqdn)) {
1521
		$hostname = false;
1522
	}
1523
	if(preg_match("/^\./i", $fqdn)) {
1524
		$hostname = false;
1525
	}
1526
	if(preg_match("/\//i", $fqdn)) {
1527
		$hostname = false;
1528
	}
1529
	return($hostname);
1530
}
1531

    
1532
function pfsense_default_state_size() {
1533
	/* get system memory amount */
1534
	$memory = get_memory();
1535
	$physmem = $memory[0];
1536
	/* Be cautious and only allocate 10% of system memory to the state table */
1537
	$max_states = (int) ($physmem/10)*1000;
1538
	return $max_states;
1539
}
1540

    
1541
function pfsense_default_tables_size() {
1542
	$current = `pfctl -sm | grep ^tables | awk '{print $4};'`;
1543
	return $current;
1544
}
1545

    
1546
function pfsense_default_table_entries_size() {
1547
	$current = `pfctl -sm | grep table-entries | awk '{print $4};'`;
1548
	return $current;
1549
}
1550

    
1551
/* Compare the current hostname DNS to the DNS cache we made
1552
 * if it has changed we return the old records
1553
 * if no change we return false */
1554
function compare_hostname_to_dnscache($hostname) {
1555
	if(!is_dir("/var/db/dnscache")) {
1556
		mkdir("/var/db/dnscache");
1557
	}
1558
	$hostname = trim($hostname);
1559
	if(is_readable("/var/db/dnscache/{$hostname}")) {
1560
		$oldcontents = file_get_contents("/var/db/dnscache/{$hostname}");
1561
	} else {
1562
		$oldcontents = "";
1563
	}
1564
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1565
		$domrecords = array();
1566
		$domips = array();
1567
		exec("host -t A " . escapeshellarg($hostname), $domrecords, $rethost);
1568
		if($rethost == 0) {
1569
			foreach($domrecords as $domr) {
1570
				$doml = explode(" ", $domr);
1571
				$domip = $doml[3];
1572
				/* fill array with domain ip addresses */
1573
				if(is_ipaddr($domip)) {
1574
					$domips[] = $domip;
1575
				}
1576
			}
1577
		}
1578
		sort($domips);
1579
		$contents = "";
1580
		if(! empty($domips)) {
1581
			foreach($domips as $ip) {
1582
				$contents .= "$ip\n";
1583
			}
1584
		}
1585
	}
1586

    
1587
	if(trim($oldcontents) != trim($contents)) {
1588
		if($g['debug']) {
1589
			log_error(sprintf(gettext('DNSCACHE: Found old IP %1$s and new IP %2$s'), $oldcontents, $contents));
1590
		}
1591
		return ($oldcontents);
1592
	} else {
1593
		return false;
1594
	}
1595
}
1596

    
1597
/*
1598
 * load_crypto() - Load crypto modules if enabled in config.
1599
 */
1600
function load_crypto() {
1601
	global $config, $g;
1602
	$crypto_modules = array('glxsb', 'aesni');
1603

    
1604
	if (!in_array($config['system']['crypto_hardware'], $crypto_modules))
1605
		return false;
1606

    
1607
	if (!empty($config['system']['crypto_hardware']) && !is_module_loaded($config['system']['crypto_hardware'])) {
1608
		log_error("Loading {$config['system']['crypto_hardware']} cryptographic accelerator module.");
1609
		mwexec("/sbin/kldload {$config['system']['crypto_hardware']}");
1610
	}
1611
}
1612

    
1613
/*
1614
 * load_thermal_hardware() - Load temperature monitor kernel module
1615
 */
1616
function load_thermal_hardware() {
1617
	global $config, $g;
1618
	$thermal_hardware_modules = array('coretemp', 'amdtemp');
1619

    
1620
	if (!in_array($config['system']['thermal_hardware'], $thermal_hardware_modules))
1621
		return false;
1622

    
1623
	if (!empty($config['system']['thermal_hardware']) && !is_module_loaded($config['system']['thermal_hardware'])) {
1624
		log_error("Loading {$config['system']['thermal_hardware']} thermal monitor module.");
1625
		mwexec("/sbin/kldload {$config['system']['thermal_hardware']}");
1626
	}
1627
}
1628

    
1629
/****f* pfsense-utils/isvm
1630
 * NAME
1631
 *   isvm
1632
 * INPUTS
1633
 *	none
1634
 * RESULT
1635
 *   returns true if machine is running under a virtual environment
1636
 ******/
1637
function isvm() {
1638
	$virtualenvs = array("vmware", "parallels", "qemu", "bochs", "plex86");
1639
	$bios_product = trim(`/bin/kenv smbios.system.product`);
1640
	foreach ($virtualenvs as $virtualenv)
1641
		if (stripos($bios_product, $virtualenv) !== false)
1642
			return true;
1643

    
1644
	return false;
1645
}
1646

    
1647
function get_freebsd_version() {
1648
	$version = explode(".", php_uname("r"));
1649
	return $version[0];
1650
}
1651

    
1652
function download_file($url, $destination, $verify_ssl = false, $connect_timeout = 60, $timeout = 0) {
1653
	global $config, $g;
1654

    
1655
	$fp = fopen($destination, "wb");
1656

    
1657
	if (!$fp)
1658
		return false;
1659

    
1660
	$ch = curl_init();
1661
	curl_setopt($ch, CURLOPT_URL, $url);
1662
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $verify_ssl);
1663
	curl_setopt($ch, CURLOPT_FILE, $fp);
1664
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connect_timeout);
1665
	curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1666
	curl_setopt($ch, CURLOPT_HEADER, false);
1667
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1668
	curl_setopt($ch, CURLOPT_USERAGENT, $g['product_name'] . '/' . rtrim(file_get_contents("/etc/version")));
1669

    
1670
	if (!empty($config['system']['proxyurl'])) {
1671
		curl_setopt($ch, CURLOPT_PROXY, $config['system']['proxyurl']);
1672
		if (!empty($config['system']['proxyport']))
1673
			curl_setopt($ch, CURLOPT_PROXYPORT, $config['system']['proxyport']);
1674
		if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
1675
			@curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY | CURLAUTH_ANYSAFE);
1676
			curl_setopt($ch, CURLOPT_PROXYUSERPWD, "{$config['system']['proxyuser']}:{$config['system']['proxypass']}");
1677
		}
1678
	}
1679

    
1680
	@curl_exec($ch);
1681
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1682
	fclose($fp);
1683
	curl_close($ch);
1684
	return ($http_code == 200) ? true : $http_code;
1685
}
1686

    
1687
function download_file_with_progress_bar($url_file, $destination_file, $readbody = 'read_body', $connect_timeout=60, $timeout=0) {
1688
	global $ch, $fout, $file_size, $downloaded, $config, $first_progress_update;
1689
	$file_size  = 1;
1690
	$downloaded = 1;
1691
	$first_progress_update = TRUE;
1692
	/* open destination file */
1693
	$fout = fopen($destination_file, "wb");
1694

    
1695
	/*
1696
	 *      Originally by Author: Keyvan Minoukadeh
1697
	 *      Modified by Scott Ullrich to return Content-Length size
1698
	 */
1699

    
1700
	$ch = curl_init();
1701
	curl_setopt($ch, CURLOPT_URL, $url_file);
1702
	curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
1703
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1704
	/* Don't verify SSL peers since we don't have the certificates to do so. */
1705
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1706
	curl_setopt($ch, CURLOPT_WRITEFUNCTION, $readbody);
1707
	curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
1708
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connect_timeout);
1709
	curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1710
	curl_setopt($ch, CURLOPT_USERAGENT, $g['product_name'] . '/' . rtrim(file_get_contents("/etc/version")));
1711

    
1712
	if (!empty($config['system']['proxyurl'])) {
1713
		curl_setopt($ch, CURLOPT_PROXY, $config['system']['proxyurl']);
1714
		if (!empty($config['system']['proxyport']))
1715
			curl_setopt($ch, CURLOPT_PROXYPORT, $config['system']['proxyport']);
1716
		if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
1717
			@curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY | CURLAUTH_ANYSAFE);
1718
			curl_setopt($ch, CURLOPT_PROXYUSERPWD, "{$config['system']['proxyuser']}:{$config['system']['proxypass']}");
1719
		}
1720
	}
1721

    
1722
	@curl_exec($ch);
1723
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1724
	if($fout)
1725
		fclose($fout);
1726
	curl_close($ch);
1727
	return ($http_code == 200) ? true : $http_code;
1728
}
1729

    
1730
function read_header($ch, $string) {
1731
	global $file_size, $fout;
1732
	$length = strlen($string);
1733
	$regs = "";
1734
	preg_match("/(Content-Length:) (.*)/", $string, $regs);
1735
	if($regs[2] <> "") {
1736
		$file_size = intval($regs[2]);
1737
	}
1738
	ob_flush();
1739
	return $length;
1740
}
1741

    
1742
function read_body($ch, $string) {
1743
	global $fout, $file_size, $downloaded, $sendto, $static_status, $static_output, $lastseen, $first_progress_update;
1744
	global $pkg_interface;
1745
	$length = strlen($string);
1746
	$downloaded += intval($length);
1747
	if($file_size > 0) {
1748
		$downloadProgress = round(100 * (1 - $downloaded / $file_size), 0);
1749
		$downloadProgress = 100 - $downloadProgress;
1750
	} else
1751
		$downloadProgress = 0;
1752
	if($lastseen <> $downloadProgress and $downloadProgress < 101) {
1753
		if($sendto == "status") {
1754
			if($pkg_interface == "console") {
1755
				if(($downloadProgress % 10) == 0 || $downloadProgress < 10) {
1756
					$tostatus = $static_status . $downloadProgress . "%";
1757
					if ($downloadProgress == 100) {
1758
						$tostatus = $tostatus . "\r";
1759
					}
1760
					update_status($tostatus);
1761
				}
1762
			} else {
1763
				$tostatus = $static_status . $downloadProgress . "%";
1764
				update_status($tostatus);
1765
			}
1766
		} else {
1767
			if($pkg_interface == "console") {
1768
				if(($downloadProgress % 10) == 0 || $downloadProgress < 10) {
1769
					$tooutput = $static_output . $downloadProgress . "%";
1770
					if ($downloadProgress == 100) {
1771
						$tooutput = $tooutput . "\r";
1772
					}
1773
					update_output_window($tooutput);
1774
				}
1775
			} else {
1776
				$tooutput = $static_output . $downloadProgress . "%";
1777
				update_output_window($tooutput);
1778
			}
1779
		}
1780
				if(($pkg_interface != "console") || (($downloadProgress % 10) == 0) || ($downloadProgress < 10)) {
1781
					update_progress_bar($downloadProgress, $first_progress_update);
1782
					$first_progress_update = FALSE;
1783
				}
1784
		$lastseen = $downloadProgress;
1785
	}
1786
	if($fout)
1787
		fwrite($fout, $string);
1788
	ob_flush();
1789
	return $length;
1790
}
1791

    
1792
/*
1793
 *   update_output_window: update bottom textarea dynamically.
1794
 */
1795
function update_output_window($text) {
1796
	global $pkg_interface;
1797
	$log = preg_replace("/\n/", "\\n", $text);
1798
	if($pkg_interface != "console") {
1799
		echo "\n<script type=\"text/javascript\">";
1800
		echo "\n//<![CDATA[";
1801
		echo "\nthis.document.forms[0].output.value = \"" . $log . "\";";
1802
		echo "\nthis.document.forms[0].output.scrollTop = this.document.forms[0].output.scrollHeight;";
1803
		echo "\n//]]>";
1804
		echo "\n</script>";
1805
	}
1806
	/* ensure that contents are written out */
1807
	ob_flush();
1808
}
1809

    
1810
/*
1811
 *   update_status: update top textarea dynamically.
1812
 */
1813
function update_status($status) {
1814
	global $pkg_interface;
1815
	if($pkg_interface == "console") {
1816
		echo "\r{$status}";
1817
	} else {
1818
		echo "\n<script type=\"text/javascript\">";
1819
		echo "\n//<![CDATA[";
1820
		echo "\nthis.document.forms[0].status.value=\"" . $status . "\";";
1821
		echo "\n//]]>";
1822
		echo "\n</script>";
1823
	}
1824
	/* ensure that contents are written out */
1825
	ob_flush();
1826
}
1827

    
1828
/*
1829
 * update_progress_bar($percent, $first_time): updates the javascript driven progress bar.
1830
 */
1831
function update_progress_bar($percent, $first_time) {
1832
	global $pkg_interface;
1833
	if($percent > 100) $percent = 1;
1834
	if($pkg_interface <> "console") {
1835
		echo "\n<script type=\"text/javascript\">";
1836
		echo "\n//<![CDATA[";
1837
		echo "\ndocument.progressbar.style.width='" . $percent . "%';";
1838
		echo "\n//]]>";
1839
		echo "\n</script>";
1840
	} else {
1841
		if(!($first_time))
1842
			echo "\x08\x08\x08\x08\x08";
1843
		echo sprintf("%4d%%", $percent);
1844
	}
1845
}
1846

    
1847
/* 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. */
1848
if(!function_exists("split")) {
1849
	function split($separator, $haystack, $limit = null) {
1850
		log_error("deprecated split() call with separator '{$separator}'");
1851
		return preg_split($separator, $haystack, $limit);
1852
	}
1853
}
1854

    
1855
function update_alias_names_upon_change($section, $field, $new_alias_name, $origname) {
1856
	global $g, $config, $pconfig, $debug;
1857
	if(!$origname)
1858
		return;
1859

    
1860
	$sectionref = &$config;
1861
	foreach($section as $sectionname) {
1862
		if(is_array($sectionref) && isset($sectionref[$sectionname]))
1863
			$sectionref = &$sectionref[$sectionname];
1864
		else
1865
			return;
1866
	}
1867

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

    
1871
	if(is_array($sectionref)) {
1872
		foreach($sectionref as $itemkey => $item) {
1873
			if($debug) fwrite($fd, "$itemkey\n");
1874

    
1875
			$fieldfound = true;
1876
			$fieldref = &$sectionref[$itemkey];
1877
			foreach($field as $fieldname) {
1878
				if(is_array($fieldref) && isset($fieldref[$fieldname]))
1879
					$fieldref = &$fieldref[$fieldname];
1880
				else {
1881
					$fieldfound = false;
1882
					break;
1883
				}
1884
			}
1885
			if($fieldfound && $fieldref == $origname) {
1886
				if($debug) fwrite($fd, "Setting old alias value $origname to $new_alias_name\n");
1887
				$fieldref = $new_alias_name;
1888
			}
1889
		}
1890
	}
1891

    
1892
	if($debug) fclose($fd);
1893

    
1894
}
1895

    
1896
function update_alias_url_data() {
1897
	global $config, $g;
1898

    
1899
	$updated = false;
1900

    
1901
	/* item is a url type */
1902
	$lockkey = lock('aliasurl');
1903
	if (is_array($config['aliases']['alias'])) {
1904
		foreach ($config['aliases']['alias'] as $x => $alias) {
1905
			if (empty($alias['aliasurl']))
1906
				continue;
1907

    
1908
			$address = "";
1909
			$isfirst = 0;
1910
			foreach ($alias['aliasurl'] as $alias_url) {
1911
				/* fetch down and add in */
1912
				$temp_filename = tempnam("{$g['tmp_path']}/", "alias_import");
1913
				unlink($temp_filename);
1914
				$verify_ssl = isset($config['system']['checkaliasesurlcert']);
1915
				mkdir($temp_filename);
1916
				download_file($alias_url, $temp_filename . "/aliases", $verify_ssl);
1917

    
1918
				/* if the item is tar gzipped then extract */
1919
				if (stripos($alias_url, '.tgz')) {
1920
					if (!process_alias_tgz($temp_filename))
1921
						continue;
1922
				} else if (stripos($alias_url, '.zip')) {
1923
					if (!process_alias_unzip($temp_filename))
1924
						continue;
1925
				}
1926
				if (file_exists("{$temp_filename}/aliases")) {
1927
					$fd = @fopen("{$temp_filename}/aliases", 'r');
1928
					if (!$fd) {
1929
						log_error(gettext("Could not process aliases from alias: {$alias_url}"));
1930
						continue;
1931
					}
1932
					/* NOTE: fgetss() is not a typo RTFM before being smart */
1933
					while (($fc = fgetss($fd)) !== FALSE) {
1934
						$tmp = trim($fc, " \t\n\r");
1935
						if (empty($tmp))
1936
							continue;
1937
						$tmp_str = strstr($tmp, '#', true);
1938
						if (!empty($tmp_str))
1939
							$tmp = $tmp_str;
1940
						if ($isfirst == 1)
1941
							$address .= ' ';
1942
						$address .= $tmp;
1943
						$isfirst = 1;
1944
					}
1945
					fclose($fd);
1946
					mwexec("/bin/rm -rf {$temp_filename}");
1947
				}
1948
			}
1949
			if (!empty($address)) {
1950
				$config['aliases']['alias'][$x]['address'] = $address;
1951
				$updated = true;
1952
			}
1953
		}
1954
	}
1955
	unlock($lockkey);
1956

    
1957
	/* Report status to callers as well */
1958
	return $updated;
1959
}
1960

    
1961
function process_alias_unzip($temp_filename) {
1962
	if(!file_exists("/usr/local/bin/unzip")) {
1963
		log_error(gettext("Alias archive is a .zip file which cannot be decompressed because utility is missing!"));
1964
		return false;
1965
	}
1966
	rename("{$temp_filename}/aliases", "{$temp_filename}/aliases.zip");
1967
	mwexec("/usr/local/bin/unzip {$temp_filename}/aliases.tgz -d {$temp_filename}/aliases/");
1968
	unlink("{$temp_filename}/aliases.zip");
1969
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1970
	/* foreach through all extracted files and build up aliases file */
1971
	$fd = @fopen("{$temp_filename}/aliases", "w");
1972
	if (!$fd) {
1973
		log_error(gettext("Could not open {$temp_filename}/aliases for writing!"));
1974
		return false;
1975
	}
1976
	foreach($files_to_process as $f2p) {
1977
		$tmpfd = @fopen($f2p, 'r');
1978
		if (!$tmpfd) {
1979
			log_error(gettext("The following file could not be read {$f2p} from {$temp_filename}"));
1980
			continue;
1981
		}
1982
		while (($tmpbuf = fread($tmpfd, 65536)) !== FALSE)
1983
			fwrite($fd, $tmpbuf);
1984
		fclose($tmpfd);
1985
		unlink($f2p);
1986
	}
1987
	fclose($fd);
1988
	unset($tmpbuf);
1989

    
1990
	return true;
1991
}
1992

    
1993
function process_alias_tgz($temp_filename) {
1994
	if(!file_exists('/usr/bin/tar')) {
1995
		log_error(gettext("Alias archive is a .tar/tgz file which cannot be decompressed because utility is missing!"));
1996
		return false;
1997
	}
1998
	rename("{$temp_filename}/aliases", "{$temp_filename}/aliases.tgz");
1999
	mwexec("/usr/bin/tar xzf {$temp_filename}/aliases.tgz -C {$temp_filename}/aliases/");
2000
	unlink("{$temp_filename}/aliases.tgz");
2001
	$files_to_process = return_dir_as_array("{$temp_filename}/");
2002
	/* foreach through all extracted files and build up aliases file */
2003
	$fd = @fopen("{$temp_filename}/aliases", "w");
2004
	if (!$fd) {
2005
		log_error(gettext("Could not open {$temp_filename}/aliases for writing!"));
2006
		return false;
2007
	}
2008
	foreach($files_to_process as $f2p) {
2009
		$tmpfd = @fopen($f2p, 'r');
2010
		if (!$tmpfd) {
2011
			log_error(gettext("The following file could not be read {$f2p} from {$temp_filename}"));
2012
			continue;
2013
		}
2014
		while (($tmpbuf = fread($tmpfd, 65536)) !== FALSE)
2015
			fwrite($fd, $tmpbuf);
2016
		fclose($tmpfd);
2017
		unlink($f2p);
2018
	}
2019
	fclose($fd);
2020
	unset($tmpbuf);
2021

    
2022
	return true;
2023
}
2024

    
2025
function version_compare_dates($a, $b) {
2026
	$a_time = strtotime($a);
2027
	$b_time = strtotime($b);
2028

    
2029
	if ((!$a_time) || (!$b_time)) {
2030
		return FALSE;
2031
	} else {
2032
		if ($a_time < $b_time)
2033
			return -1;
2034
		elseif ($a_time == $b_time)
2035
			return 0;
2036
		else
2037
			return 1;
2038
	}
2039
}
2040
function version_get_string_value($a) {
2041
	$strs = array(
2042
		0 => "ALPHA-ALPHA",
2043
		2 => "ALPHA",
2044
		3 => "BETA",
2045
		4 => "B",
2046
		5 => "C",
2047
		6 => "D",
2048
		7 => "RC",
2049
		8 => "RELEASE",
2050
		9 => "*"			// Matches all release levels
2051
	);
2052
	$major = 0;
2053
	$minor = 0;
2054
	foreach ($strs as $num => $str) {
2055
		if (substr($a, 0, strlen($str)) == $str) {
2056
			$major = $num;
2057
			$n = substr($a, strlen($str));
2058
			if (is_numeric($n))
2059
				$minor = $n;
2060
			break;
2061
		}
2062
	}
2063
	return "{$major}.{$minor}";
2064
}
2065
function version_compare_string($a, $b) {
2066
	// Only compare string parts if both versions give a specific release
2067
	// (If either version lacks a string part, assume intended to match all release levels)
2068
	if (isset($a) && isset($b))
2069
		return version_compare_numeric(version_get_string_value($a), version_get_string_value($b));
2070
	else
2071
		return 0;
2072
}
2073
function version_compare_numeric($a, $b) {
2074
	$a_arr = explode('.', rtrim($a, '.0'));
2075
	$b_arr = explode('.', rtrim($b, '.0'));
2076

    
2077
	foreach ($a_arr as $n => $val) {
2078
		if (array_key_exists($n, $b_arr)) {
2079
			// So far so good, both have values at this minor version level. Compare.
2080
			if ($val > $b_arr[$n])
2081
				return 1;
2082
			elseif ($val < $b_arr[$n])
2083
				return -1;
2084
		} else {
2085
			// a is greater, since b doesn't have any minor version here.
2086
			return 1;
2087
		}
2088
	}
2089
	if (count($b_arr) > count($a_arr)) {
2090
		// b is longer than a, so it must be greater.
2091
		return -1;
2092
	} else {
2093
		// Both a and b are of equal length and value.
2094
		return 0;
2095
	}
2096
}
2097
function pfs_version_compare($cur_time, $cur_text, $remote) {
2098
	// First try date compare
2099
	$v = version_compare_dates($cur_time, $remote);
2100
	if ($v === FALSE) {
2101
		// If that fails, try to compare by string
2102
		// Before anything else, simply test if the strings are equal
2103
		if (($cur_text == $remote) || ($cur_time == $remote))
2104
			return 0;
2105
		list($cur_num, $cur_str) = explode('-', $cur_text);
2106
		list($rem_num, $rem_str) = explode('-', $remote);
2107

    
2108
		// First try to compare the numeric parts of the version string.
2109
		$v = version_compare_numeric($cur_num, $rem_num);
2110

    
2111
		// If the numeric parts are the same, compare the string parts.
2112
		if ($v == 0)
2113
			return version_compare_string($cur_str, $rem_str);
2114
	}
2115
	return $v;
2116
}
2117
function process_alias_urltable($name, $url, $freq, $forceupdate=false) {
2118
	global $config;
2119

    
2120
	$urltable_prefix = "/var/db/aliastables/";
2121
	$urltable_filename = $urltable_prefix . $name . ".txt";
2122

    
2123
	// Make the aliases directory if it doesn't exist
2124
	if (!file_exists($urltable_prefix)) {
2125
		mkdir($urltable_prefix);
2126
	} elseif (!is_dir($urltable_prefix)) {
2127
		unlink($urltable_prefix);
2128
		mkdir($urltable_prefix);
2129
	}
2130

    
2131
	// If the file doesn't exist or is older than update_freq days, fetch a new copy.
2132
	if (!file_exists($urltable_filename)
2133
		|| ((time() - filemtime($urltable_filename)) > ($freq * 86400 - 90))
2134
		|| $forceupdate) {
2135

    
2136
		// Try to fetch the URL supplied
2137
		conf_mount_rw();
2138
		unlink_if_exists($urltable_filename . ".tmp");
2139
		$verify_ssl = isset($config['system']['checkaliasesurlcert']);
2140
		if (download_file($url, $urltable_filename . ".tmp", $verify_ssl)) {
2141
			mwexec("/usr/bin/sed -E 's/\;.*//g; /^[[:space:]]*($|#)/d' ". escapeshellarg($urltable_filename . ".tmp") . " > " . escapeshellarg($urltable_filename));
2142
			if (alias_get_type($name) == "urltable_ports") {
2143
				$ports = explode("\n", file_get_contents($urltable_filename));
2144
				$ports = group_ports($ports);
2145
				file_put_contents($urltable_filename, implode("\n", $ports));
2146
			}
2147
			unlink_if_exists($urltable_filename . ".tmp");
2148
		} else
2149
			touch($urltable_filename);
2150
		conf_mount_ro();
2151
		return true;
2152
	} else {
2153
		// File exists, and it doesn't need updated.
2154
		return -1;
2155
	}
2156
}
2157
function get_real_slice_from_glabel($label) {
2158
	$label = escapeshellarg($label);
2159
	return trim(`/sbin/glabel list | /usr/bin/grep -B2 ufs/{$label} | /usr/bin/head -n 1 | /usr/bin/cut -f3 -d' '`);
2160
}
2161
function nanobsd_get_boot_slice() {
2162
	return trim(`/sbin/mount | /usr/bin/grep pfsense | /usr/bin/cut -d'/' -f4 | /usr/bin/cut -d' ' -f1`);
2163
}
2164
function nanobsd_get_boot_drive() {
2165
	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`);
2166
}
2167
function nanobsd_get_active_slice() {
2168
	$boot_drive = nanobsd_get_boot_drive();
2169
	$active = trim(`gpart show $boot_drive | grep '\[active\]' | awk '{print $3;}'`);
2170

    
2171
	return "{$boot_drive}s{$active}";
2172
}
2173
function nanobsd_get_size() {
2174
	return strtoupper(file_get_contents("/etc/nanosize.txt"));
2175
}
2176
function nanobsd_switch_boot_slice() {
2177
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2178
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2179
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2180
	nanobsd_detect_slice_info();
2181

    
2182
	if ($BOOTFLASH == $ACTIVE_SLICE) {
2183
		$slice = $TOFLASH;
2184
	} else {
2185
		$slice = $BOOTFLASH;
2186
	}
2187

    
2188
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
2189
	ob_implicit_flush(1);
2190
	if(strstr($slice, "s2")) {
2191
		$ASLICE="2";
2192
		$AOLDSLICE="1";
2193
		$AGLABEL_SLICE="pfsense1";
2194
		$AUFS_ID="1";
2195
		$AOLD_UFS_ID="0";
2196
	} else {
2197
		$ASLICE="1";
2198
		$AOLDSLICE="2";
2199
		$AGLABEL_SLICE="pfsense0";
2200
		$AUFS_ID="0";
2201
		$AOLD_UFS_ID="1";
2202
	}
2203
	$ATOFLASH="{$BOOT_DRIVE}s{$ASLICE}";
2204
	$ACOMPLETE_PATH="{$BOOT_DRIVE}s{$ASLICE}a";
2205
	$ABOOTFLASH="{$BOOT_DRIVE}s{$AOLDSLICE}";
2206
	conf_mount_rw();
2207
	exec("sysctl kern.geom.debugflags=16");
2208
	exec("gpart set -a active -i {$ASLICE} {$BOOT_DRIVE}");
2209
	exec("/usr/sbin/boot0cfg -s {$ASLICE} -v /dev/{$BOOT_DRIVE}");
2210
	// We can't update these if they are mounted now.
2211
	if ($BOOTFLASH != $slice) {
2212
		exec("/sbin/tunefs -L ${AGLABEL_SLICE} /dev/$ACOMPLETE_PATH");
2213
		nanobsd_update_fstab($AGLABEL_SLICE, $ACOMPLETE_PATH, $AOLD_UFS_ID, $AUFS_ID);
2214
	}
2215
	exec("/sbin/sysctl kern.geom.debugflags=0");
2216
	conf_mount_ro();
2217
}
2218
function nanobsd_clone_slice() {
2219
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2220
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2221
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2222
	nanobsd_detect_slice_info();
2223

    
2224
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
2225
	ob_implicit_flush(1);
2226
	exec("/sbin/sysctl kern.geom.debugflags=16");
2227
	exec("/bin/dd if=/dev/zero of=/dev/{$TOFLASH} bs=1m count=1");
2228
	exec("/bin/dd if=/dev/{$BOOTFLASH} of=/dev/{$TOFLASH} bs=64k");
2229
	exec("/sbin/tunefs -L {$GLABEL_SLICE} /dev/{$COMPLETE_PATH}");
2230
	$status = nanobsd_update_fstab($GLABEL_SLICE, $COMPLETE_PATH, $OLD_UFS_ID, $UFS_ID);
2231
	exec("/sbin/sysctl kern.geom.debugflags=0");
2232
	if($status) {
2233
		return false;
2234
	} else {
2235
		return true;
2236
	}
2237
}
2238
function nanobsd_update_fstab($gslice, $complete_path, $oldufs, $newufs) {
2239
	$tmppath = "/tmp/{$gslice}";
2240
	$fstabpath = "/tmp/{$gslice}/etc/fstab";
2241

    
2242
	mkdir($tmppath);
2243
	exec("/sbin/fsck_ufs -y /dev/{$complete_path}");
2244
	exec("/sbin/mount /dev/ufs/{$gslice} {$tmppath}");
2245
	copy("/etc/fstab", $fstabpath);
2246

    
2247
	if (!file_exists($fstabpath)) {
2248
		$fstab = <<<EOF
2249
/dev/ufs/{$gslice} / ufs ro,noatime 1 1
2250
/dev/ufs/cf /cf ufs ro,noatime 1 1
2251
EOF;
2252
		if (file_put_contents($fstabpath, $fstab))
2253
			$status = true;
2254
		else
2255
			$status = false;
2256
	} else {
2257
		$status = exec("sed -i \"\" \"s/pfsense{$oldufs}/pfsense{$newufs}/g\" {$fstabpath}");
2258
	}
2259
	exec("/sbin/umount {$tmppath}");
2260
	rmdir($tmppath);
2261

    
2262
	return $status;
2263
}
2264
function nanobsd_detect_slice_info() {
2265
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2266
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2267
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2268

    
2269
	$BOOT_DEVICE=nanobsd_get_boot_slice();
2270
	$REAL_BOOT_DEVICE=get_real_slice_from_glabel($BOOT_DEVICE);
2271
	$BOOT_DRIVE=nanobsd_get_boot_drive();
2272
	$ACTIVE_SLICE=nanobsd_get_active_slice();
2273

    
2274
	// Detect which slice is active and set information.
2275
	if(strstr($REAL_BOOT_DEVICE, "s1")) {
2276
		$SLICE="2";
2277
		$OLDSLICE="1";
2278
		$GLABEL_SLICE="pfsense1";
2279
		$UFS_ID="1";
2280
		$OLD_UFS_ID="0";
2281

    
2282
	} else {
2283
		$SLICE="1";
2284
		$OLDSLICE="2";
2285
		$GLABEL_SLICE="pfsense0";
2286
		$UFS_ID="0";
2287
		$OLD_UFS_ID="1";
2288
	}
2289
	$TOFLASH="{$BOOT_DRIVE}s{$SLICE}";
2290
	$COMPLETE_PATH="{$BOOT_DRIVE}s{$SLICE}a";
2291
	$COMPLETE_BOOT_PATH="{$BOOT_DRIVE}s{$OLDSLICE}";
2292
	$BOOTFLASH="{$BOOT_DRIVE}s{$OLDSLICE}";
2293
}
2294

    
2295
function nanobsd_friendly_slice_name($slicename) {
2296
	global $g;
2297
	return strtolower(str_ireplace('pfsense', $g['product_name'], $slicename));
2298
}
2299

    
2300
function get_include_contents($filename) {
2301
	if (is_file($filename)) {
2302
		ob_start();
2303
		include $filename;
2304
		$contents = ob_get_contents();
2305
		ob_end_clean();
2306
		return $contents;
2307
	}
2308
	return false;
2309
}
2310

    
2311
/* This xml 2 array function is courtesy of the php.net comment section on xml_parse.
2312
 * it is roughly 4 times faster then our existing pfSense parser but due to the large
2313
 * size of the RRD xml dumps this is required.
2314
 * The reason we do not use it for pfSense is that it does not know about array fields
2315
 * which causes it to fail on array fields with single items. Possible Todo?
2316
 */
2317
function xml2array($contents, $get_attributes = 1, $priority = 'tag')
2318
{
2319
	if (!function_exists('xml_parser_create'))
2320
	{
2321
		return array ();
2322
	}
2323
	$parser = xml_parser_create('');
2324
	xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
2325
	xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
2326
	xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
2327
	xml_parse_into_struct($parser, trim($contents), $xml_values);
2328
	xml_parser_free($parser);
2329
	if (!$xml_values)
2330
		return; //Hmm...
2331
	$xml_array = array ();
2332
	$parents = array ();
2333
	$opened_tags = array ();
2334
	$arr = array ();
2335
	$current = & $xml_array;
2336
	$repeated_tag_index = array ();
2337
	foreach ($xml_values as $data)
2338
	{
2339
		unset ($attributes, $value);
2340
		extract($data);
2341
		$result = array ();
2342
		$attributes_data = array ();
2343
		if (isset ($value))
2344
		{
2345
			if ($priority == 'tag')
2346
				$result = $value;
2347
			else
2348
				$result['value'] = $value;
2349
		}
2350
		if (isset ($attributes) and $get_attributes)
2351
		{
2352
			foreach ($attributes as $attr => $val)
2353
			{
2354
				if ($priority == 'tag')
2355
					$attributes_data[$attr] = $val;
2356
				else
2357
					$result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
2358
			}
2359
		}
2360
		if ($type == "open")
2361
		{
2362
			$parent[$level -1] = & $current;
2363
			if (!is_array($current) or (!in_array($tag, array_keys($current))))
2364
			{
2365
				$current[$tag] = $result;
2366
				if ($attributes_data)
2367
					$current[$tag . '_attr'] = $attributes_data;
2368
				$repeated_tag_index[$tag . '_' . $level] = 1;
2369
				$current = & $current[$tag];
2370
			}
2371
			else
2372
			{
2373
				if (isset ($current[$tag][0]))
2374
				{
2375
					$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
2376
					$repeated_tag_index[$tag . '_' . $level]++;
2377
				}
2378
				else
2379
				{
2380
					$current[$tag] = array (
2381
						$current[$tag],
2382
						$result
2383
						);
2384
					$repeated_tag_index[$tag . '_' . $level] = 2;
2385
					if (isset ($current[$tag . '_attr']))
2386
					{
2387
						$current[$tag]['0_attr'] = $current[$tag . '_attr'];
2388
						unset ($current[$tag . '_attr']);
2389
					}
2390
				}
2391
				$last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
2392
				$current = & $current[$tag][$last_item_index];
2393
			}
2394
		}
2395
		elseif ($type == "complete")
2396
		{
2397
			if (!isset ($current[$tag]))
2398
			{
2399
				$current[$tag] = $result;
2400
				$repeated_tag_index[$tag . '_' . $level] = 1;
2401
				if ($priority == 'tag' and $attributes_data)
2402
					$current[$tag . '_attr'] = $attributes_data;
2403
			}
2404
			else
2405
			{
2406
				if (isset ($current[$tag][0]) and is_array($current[$tag]))
2407
				{
2408
					$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
2409
					if ($priority == 'tag' and $get_attributes and $attributes_data)
2410
					{
2411
						$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
2412
					}
2413
					$repeated_tag_index[$tag . '_' . $level]++;
2414
				}
2415
				else
2416
				{
2417
					$current[$tag] = array (
2418
						$current[$tag],
2419
						$result
2420
						);
2421
					$repeated_tag_index[$tag . '_' . $level] = 1;
2422
					if ($priority == 'tag' and $get_attributes)
2423
					{
2424
						if (isset ($current[$tag . '_attr']))
2425
						{
2426
							$current[$tag]['0_attr'] = $current[$tag . '_attr'];
2427
							unset ($current[$tag . '_attr']);
2428
						}
2429
						if ($attributes_data)
2430
						{
2431
							$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
2432
						}
2433
					}
2434
					$repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
2435
				}
2436
			}
2437
		}
2438
		elseif ($type == 'close')
2439
		{
2440
			$current = & $parent[$level -1];
2441
		}
2442
	}
2443
	return ($xml_array);
2444
}
2445

    
2446
function get_country_name($country_code) {
2447
	if ($country_code != "ALL" && strlen($country_code) != 2)
2448
		return "";
2449

    
2450
	$country_names_xml = "/usr/local/share/mobile-broadband-provider-info/iso_3166-1_list_en.xml";
2451
	$country_names_contents = file_get_contents($country_names_xml);
2452
	$country_names = xml2array($country_names_contents);
2453

    
2454
	if($country_code == "ALL") {
2455
		$country_list = array();
2456
		foreach($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2457
			$country_list[] = array("code" => $country['ISO_3166-1_Alpha-2_Code_element'],
2458
						"name" => ucwords(strtolower($country['ISO_3166-1_Country_name'])) );
2459
		}
2460
		return $country_list;
2461
	}
2462

    
2463
	foreach ($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2464
		if ($country['ISO_3166-1_Alpha-2_Code_element'] == strtoupper($country_code)) {
2465
			return ucwords(strtolower($country['ISO_3166-1_Country_name']));
2466
		}
2467
	}
2468
	return "";
2469
}
2470

    
2471
/* sort by interface only, retain the original order of rules that apply to
2472
   the same interface */
2473
function filter_rules_sort() {
2474
	global $config;
2475

    
2476
	/* mark each rule with the sequence number (to retain the order while sorting) */
2477
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2478
		$config['filter']['rule'][$i]['seq'] = $i;
2479

    
2480
	usort($config['filter']['rule'], "filter_rules_compare");
2481

    
2482
	/* strip the sequence numbers again */
2483
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2484
		unset($config['filter']['rule'][$i]['seq']);
2485
}
2486
function filter_rules_compare($a, $b) {
2487
	if (isset($a['floating']) && isset($b['floating']))
2488
		return $a['seq'] - $b['seq'];
2489
	else if (isset($a['floating']))
2490
		return -1;
2491
	else if (isset($b['floating']))
2492
		return 1;
2493
	else if ($a['interface'] == $b['interface'])
2494
		return $a['seq'] - $b['seq'];
2495
	else
2496
		return compare_interface_friendly_names($a['interface'], $b['interface']);
2497
}
2498

    
2499
function generate_ipv6_from_mac($mac) {
2500
	$elements = explode(":", $mac);
2501
	if(count($elements) <> 6)
2502
		return false;
2503

    
2504
	$i = 0;
2505
	$ipv6 = "fe80::";
2506
	foreach($elements as $byte) {
2507
		if($i == 0) {
2508
			$hexadecimal =  substr($byte, 1, 2);
2509
			$bitmap = base_convert($hexadecimal, 16, 2);
2510
			$bitmap = str_pad($bitmap, 4, "0", STR_PAD_LEFT);
2511
			$bitmap = substr($bitmap, 0, 2) ."1". substr($bitmap, 3,4);
2512
			$byte = substr($byte, 0, 1) . base_convert($bitmap, 2, 16);
2513
		}
2514
		$ipv6 .= $byte;
2515
		if($i == 1) {
2516
			$ipv6 .= ":";
2517
		}
2518
		if($i == 3) {
2519
			$ipv6 .= ":";
2520
		}
2521
		if($i == 2) {
2522
			$ipv6 .= "ff:fe";
2523
		}
2524

    
2525
		$i++;
2526
	}
2527
	return $ipv6;
2528
}
2529

    
2530
/****f* pfsense-utils/load_mac_manufacturer_table
2531
 * NAME
2532
 *   load_mac_manufacturer_table
2533
 * INPUTS
2534
 *   none
2535
 * RESULT
2536
 *   returns associative array with MAC-Manufacturer pairs
2537
 ******/
2538
function load_mac_manufacturer_table() {
2539
	/* load MAC-Manufacture data from the file */
2540
	$macs = false;
2541
	if (file_exists("/usr/local/share/nmap/nmap-mac-prefixes"))
2542
		$macs=file("/usr/local/share/nmap/nmap-mac-prefixes");
2543
	if ($macs){
2544
		foreach ($macs as $line){
2545
			if (preg_match('/([0-9A-Fa-f]{6}) (.*)$/', $line, $matches)){
2546
				/* store values like this $mac_man['000C29']='VMware' */
2547
				$mac_man["$matches[1]"]=$matches[2];
2548
			}
2549
		}
2550
		return $mac_man;
2551
	} else
2552
		return -1;
2553

    
2554
}
2555

    
2556
/****f* pfsense-utils/is_ipaddr_configured
2557
 * NAME
2558
 *   is_ipaddr_configured
2559
 * INPUTS
2560
 *   IP Address to check.
2561
 * RESULT
2562
 *   returns true if the IP Address is
2563
 *   configured and present on this device.
2564
*/
2565
function is_ipaddr_configured($ipaddr, $ignore_if = "", $check_localip = false, $check_subnets = false) {
2566
	global $config;
2567

    
2568
	$isipv6 = is_ipaddrv6($ipaddr);
2569

    
2570
	if ($check_subnets) {
2571
		$iflist = get_configured_interface_list();
2572
		foreach ($iflist as $if => $ifname) {
2573
			if ($ignore_if == $if)
2574
				continue;
2575

    
2576
			if ($isipv6 === true) {
2577
				$bitmask = get_interface_subnetv6($if);
2578
				$subnet = gen_subnetv6(get_interface_ipv6($if), $bitmask);
2579
			} else {
2580
				$bitmask = get_interface_subnet($if);
2581
				$subnet = gen_subnet(get_interface_ip($if), $bitmask);
2582
			}
2583

    
2584
			if (ip_in_subnet($ipaddr, $subnet . '/' . $bitmask))
2585
				return true;
2586
		}
2587
	} else {
2588
		if ($isipv6 === true)
2589
			$interface_list_ips = get_configured_ipv6_addresses();
2590
		else
2591
			$interface_list_ips = get_configured_ip_addresses();
2592

    
2593
		foreach($interface_list_ips as $if => $ilips) {
2594
			/* Also ignore CARP interfaces, it'll be checked below */
2595
			if ($ignore_if == $if || strstr($ignore_if, "_vip"))
2596
				continue;
2597
			if (strcasecmp($ipaddr, $ilips) == 0)
2598
				return true;
2599
		}
2600
	}
2601

    
2602
	$interface_list_vips = get_configured_vips_list(true);
2603
	foreach ($interface_list_vips as $id => $vip) {
2604
		if ($ignore_if == $vip['if'])
2605
			continue;
2606
		if (strcasecmp($ipaddr, $vip['ipaddr']) == 0)
2607
			return true;
2608
	}
2609

    
2610
	if ($check_localip) {
2611
		if (is_array($config['pptpd']) && !empty($config['pptpd']['localip']) && (strcasecmp($ipaddr, $config['pptpd']['localip']) == 0))
2612
			return true;
2613

    
2614
		if (!is_array($config['l2tp']) && !empty($config['l2tp']['localip']) && (strcasecmp($ipaddr, $config['l2tp']['localip']) == 0))
2615
			return true;
2616
	}
2617

    
2618
	return false;
2619
}
2620

    
2621
/****f* pfsense-utils/pfSense_handle_custom_code
2622
 * NAME
2623
 *   pfSense_handle_custom_code
2624
 * INPUTS
2625
 *   directory name to process
2626
 * RESULT
2627
 *   globs the directory and includes the files
2628
 */
2629
function pfSense_handle_custom_code($src_dir) {
2630
	// Allow extending of the nat edit page and include custom input validation
2631
	if(is_dir("$src_dir")) {
2632
		$cf = glob($src_dir . "/*.inc");
2633
		foreach($cf as $nf) {
2634
			if($nf == "." || $nf == "..")
2635
				continue;
2636
			// Include the extra handler
2637
			include("$nf");
2638
		}
2639
	}
2640
}
2641

    
2642
function set_language($lang = 'en_US', $encoding = "UTF-8") {
2643
	putenv("LANG={$lang}.{$encoding}");
2644
	setlocale(LC_ALL, "{$lang}.{$encoding}");
2645
	textdomain("pfSense");
2646
	bindtextdomain("pfSense","/usr/local/share/locale");
2647
	bind_textdomain_codeset("pfSense","{$lang}.{$encoding}");
2648
}
2649

    
2650
function get_locale_list() {
2651
	$locales = array(
2652
		"en_US" => gettext("English"),
2653
		"pt_BR" => gettext("Portuguese (Brazil)"),
2654
		"tr" => gettext("Turkish"),
2655
	);
2656
	asort($locales);
2657
	return $locales;
2658
}
2659

    
2660
function system_get_language_code() {
2661
	global $config, $g_languages;
2662

    
2663
	// a language code, as per [RFC3066]
2664
	$language = $config['system']['language'];
2665
	//$code = $g_languages[$language]['code'];
2666
	$code = str_replace("_", "-", $language);
2667

    
2668
	if (empty($code))
2669
		$code = "en-US"; // Set default code.
2670

    
2671
	return $code;
2672
}
2673

    
2674
function system_get_language_codeset() {
2675
	global $config, $g_languages;
2676

    
2677
	$language = $config['system']['language'];
2678
	$codeset = $g_languages[$language]['codeset'];
2679

    
2680
	if (empty($codeset))
2681
		$codeset = "UTF-8"; // Set default codeset.
2682

    
2683
	return $codeset;
2684
}
2685

    
2686
/* Available languages/locales */
2687
$g_languages = array (
2688
	"sq"    => array("codeset" => "UTF-8", "desc" => gettext("Albanian")),
2689
	"bg"    => array("codeset" => "UTF-8", "desc" => gettext("Bulgarian")),
2690
	"zh_CN" => array("codeset" => "UTF-8", "desc" => gettext("Chinese (Simplified)")),
2691
	"zh_TW" => array("codeset" => "UTF-8", "desc" => gettext("Chinese (Traditional)")),
2692
	"nl"    => array("codeset" => "UTF-8", "desc" => gettext("Dutch")),
2693
	"da"    => array("codeset" => "UTF-8", "desc" => gettext("Danish")),
2694
	"en_US" => array("codeset" => "UTF-8", "desc" => gettext("English")),
2695
	"fi"    => array("codeset" => "UTF-8", "desc" => gettext("Finnish")),
2696
	"fr"    => array("codeset" => "UTF-8", "desc" => gettext("French")),
2697
	"de"    => array("codeset" => "UTF-8", "desc" => gettext("German")),
2698
	"el"    => array("codeset" => "UTF-8", "desc" => gettext("Greek")),
2699
	"hu"    => array("codeset" => "UTF-8", "desc" => gettext("Hungarian")),
2700
	"it"    => array("codeset" => "UTF-8", "desc" => gettext("Italian")),
2701
	"ja"    => array("codeset" => "UTF-8", "desc" => gettext("Japanese")),
2702
	"ko"    => array("codeset" => "UTF-8", "desc" => gettext("Korean")),
2703
	"lv"    => array("codeset" => "UTF-8", "desc" => gettext("Latvian")),
2704
	"nb"    => array("codeset" => "UTF-8", "desc" => gettext("Norwegian (Bokmal)")),
2705
	"pl"    => array("codeset" => "UTF-8", "desc" => gettext("Polish")),
2706
	"pt_BR" => array("codeset" => "ISO-8859-1", "desc" => gettext("Portuguese (Brazil)")),
2707
	"pt"    => array("codeset" => "UTF-8", "desc" => gettext("Portuguese (Portugal)")),
2708
	"ro"    => array("codeset" => "UTF-8", "desc" => gettext("Romanian")),
2709
	"ru"    => array("codeset" => "UTF-8", "desc" => gettext("Russian")),
2710
	"sl"    => array("codeset" => "UTF-8", "desc" => gettext("Slovenian")),
2711
	"tr"    => array("codeset" => "UTF-8", "desc" => gettext("Turkish")),
2712
	"es"    => array("codeset" => "UTF-8", "desc" => gettext("Spanish")),
2713
	"sv"    => array("codeset" => "UTF-8", "desc" => gettext("Swedish")),
2714
	"sk"    => array("codeset" => "UTF-8", "desc" => gettext("Slovak")),
2715
	"cs"    => array("codeset" => "UTF-8", "desc" => gettext("Czech"))
2716
);
2717

    
2718
function return_hex_ipv4($ipv4) {
2719
	if(!is_ipaddrv4($ipv4))
2720
		return(false);
2721

    
2722
	/* we need the hex form of the interface IPv4 address */
2723
	$ip4arr = explode(".", $ipv4);
2724
	return (sprintf("%02x%02x%02x%02x", $ip4arr[0], $ip4arr[1], $ip4arr[2], $ip4arr[3]));
2725
}
2726

    
2727
function convert_ipv6_to_128bit($ipv6) {
2728
	if(!is_ipaddrv6($ipv6))
2729
		return(false);
2730

    
2731
	$ip6arr = array();
2732
	$ip6prefix = Net_IPv6::uncompress($ipv6);
2733
	$ip6arr = explode(":", $ip6prefix);
2734
	/* binary presentation of the prefix for all 128 bits. */
2735
	$ip6prefixbin = "";
2736
	foreach($ip6arr as $element) {
2737
		$ip6prefixbin .= sprintf("%016b", hexdec($element));
2738
	}
2739
	return($ip6prefixbin);
2740
}
2741

    
2742
function convert_128bit_to_ipv6($ip6bin) {
2743
	if(strlen($ip6bin) <> 128)
2744
		return(false);
2745

    
2746
	$ip6arr = array();
2747
	$ip6binarr = array();
2748
	$ip6binarr = str_split($ip6bin, 16);
2749
	foreach($ip6binarr as $binpart)
2750
		$ip6arr[] = dechex(bindec($binpart));
2751
	$ip6addr = Net_IPv6::compress(implode(":", $ip6arr));
2752

    
2753
	return($ip6addr);
2754
}
2755

    
2756

    
2757
/* Returns the calculated bit length of the prefix delegation from the WAN interface */
2758
/* DHCP-PD is variable, calculate from the prefix-len on the WAN interface */
2759
/* 6rd is variable, calculate from 64 - (v6 prefixlen - (32 - v4 prefixlen)) */
2760
/* 6to4 is 16 bits, e.g. 65535 */
2761
function calculate_ipv6_delegation_length($if) {
2762
	global $config;
2763

    
2764
	if(!is_array($config['interfaces'][$if]))
2765
		return false;
2766

    
2767
	switch($config['interfaces'][$if]['ipaddrv6']) {
2768
		case "6to4":
2769
			$pdlen = 16;
2770
			break;
2771
		case "6rd":
2772
			$rd6cfg = $config['interfaces'][$if];
2773
			$rd6plen = explode("/", $rd6cfg['prefix-6rd']);
2774
			$pdlen = (64 - ($rd6plen[1] + (32 - $rd6cfg['prefix-6rd-v4plen'])));
2775
			break;
2776
		case "dhcp6":
2777
			$dhcp6cfg = $config['interfaces'][$if];
2778
			$pdlen = $dhcp6cfg['dhcp6-ia-pd-len'];
2779
			break;
2780
		default:
2781
			$pdlen = 0;
2782
			break;
2783
	}
2784
	return($pdlen);
2785
}
2786

    
2787
function huawei_rssi_to_string($rssi) {
2788
	$dbm = array();
2789
	$i = 0;
2790
	$dbstart = -113;
2791
	while($i < 32) {
2792
		$dbm[$i] = $dbstart + ($i * 2);
2793
		$i++;
2794
	}
2795
	$percent = round(($rssi / 31) * 100);
2796
	$string = "rssi:{$rssi} level:{$dbm[$rssi]}dBm percent:{$percent}%";
2797
	return $string;
2798
}
2799

    
2800
function huawei_mode_to_string($mode, $submode) {
2801
	$modes[0] = "None";
2802
	$modes[1] = "AMPS";
2803
	$modes[2] = "CDMA";
2804
	$modes[3] = "GSM/GPRS";
2805
	$modes[4] = "HDR";
2806
	$modes[5] = "WCDMA";
2807
	$modes[6] = "GPS";
2808

    
2809
	$submodes[0] = "No Service";
2810
	$submodes[1] = "GSM";
2811
	$submodes[2] = "GPRS";
2812
	$submodes[3] = "EDGE";
2813
	$submodes[4] = "WCDMA";
2814
	$submodes[5] = "HSDPA";
2815
	$submodes[6] = "HSUPA";
2816
	$submodes[7] = "HSDPA+HSUPA";
2817
	$submodes[8] = "TD-SCDMA";
2818
	$submodes[9] = "HSPA+";
2819
	$string = "{$modes[$mode]}, {$submodes[$submode]} Mode";
2820
	return $string;
2821
}
2822

    
2823
function huawei_service_to_string($state) {
2824
	$modes[0] = "No";
2825
	$modes[1] = "Restricted";
2826
	$modes[2] = "Valid";
2827
	$modes[3] = "Restricted Regional";
2828
	$modes[4] = "Powersaving";
2829
	$string = "{$modes[$state]} Service";
2830
	return $string;
2831
}
2832

    
2833
function huawei_simstate_to_string($state) {
2834
	$modes[0] = "Invalid SIM/locked";
2835
	$modes[1] = "Valid SIM";
2836
	$modes[2] = "Invalid SIM CS";
2837
	$modes[3] = "Invalid SIM PS";
2838
	$modes[4] = "Invalid SIM CS/PS";
2839
	$modes[255] = "Missing SIM";
2840
	$string = "{$modes[$state]} State";
2841
	return $string;
2842
}
2843

    
2844
function zte_rssi_to_string($rssi) {
2845
	return huawei_rssi_to_string($rssi);
2846
}
2847

    
2848
function zte_mode_to_string($mode, $submode) {
2849
	$modes[0] = "No Service";
2850
	$modes[1] = "Limited Service";
2851
	$modes[2] = "GPRS";
2852
	$modes[3] = "GSM";
2853
	$modes[4] = "UMTS";
2854
	$modes[5] = "EDGE";
2855
	$modes[6] = "HSDPA";
2856

    
2857
	$submodes[0] = "CS_ONLY";
2858
	$submodes[1] = "PS_ONLY";
2859
	$submodes[2] = "CS_PS";
2860
	$submodes[3] = "CAMPED";
2861
	$string = "{$modes[$mode]}, {$submodes[$submode]} Mode";
2862
	return $string;
2863
}
2864

    
2865
function zte_service_to_string($state) {
2866
	$modes[0] = "Initializing";
2867
	$modes[1] = "Network Lock error";
2868
	$modes[2] = "Network Locked";
2869
	$modes[3] = "Unlocked or correct MCC/MNC";
2870
	$string = "{$modes[$state]} Service";
2871
	return $string;
2872
}
2873

    
2874
function zte_simstate_to_string($state) {
2875
	$modes[0] = "No action";
2876
	$modes[1] = "Network lock";
2877
	$modes[2] = "(U)SIM card lock";
2878
	$modes[3] = "Network Lock and (U)SIM card Lock";
2879
	$string = "{$modes[$state]} State";
2880
	return $string;
2881
}
2882

    
2883
function get_configured_pppoe_server_interfaces() {
2884
	global $config;
2885
	$iflist = array();
2886
	if (is_array($config['pppoes']['pppoe'])) {
2887
		foreach($config['pppoes']['pppoe'] as $pppoe) {
2888
			if ($pppoe['mode'] == "server") {
2889
				$int = "poes". $pppoe['pppoeid'];
2890
				$iflist[$int] = strtoupper($int);
2891
			}
2892
		}
2893
	}
2894
	return $iflist;
2895
}
2896

    
2897
function get_pppoes_child_interfaces($ifpattern) {
2898
	$if_arr = array();
2899
	if($ifpattern == "")
2900
		return;
2901

    
2902
	exec("ifconfig", $out, $ret);
2903
	foreach($out as $line) {
2904
		if(preg_match("/^({$ifpattern}[0-9]+):/i", $line, $match)) {
2905
			$if_arr[] = $match[1];
2906
		}
2907
	}
2908
	return $if_arr;
2909

    
2910
}
2911

    
2912
/****f* pfsense-utils/pkg_call_plugins
2913
 * NAME
2914
 *   pkg_call_plugins
2915
 * INPUTS
2916
 *   $plugin_type value used to search in package configuration if the plugin is used, also used to create the function name
2917
 *   $plugin_params parameters to pass to the plugin function for passing multiple parameters a array can be used.
2918
 * RESULT
2919
 *   returns associative array results from the plugin calls for each package
2920
 * NOTES
2921
 *   This generic function can be used to notify or retrieve results from functions that are defined in packages.
2922
 ******/
2923
function pkg_call_plugins($plugin_type, $plugin_params) {
2924
	global $g, $config;
2925
	$results = array();
2926
	if (!is_array($config['installedpackages']['package']))
2927
		return $results;
2928
	foreach ($config['installedpackages']['package'] as $package) {
2929
		if(!file_exists("/usr/local/pkg/" . $package['configurationfile']))
2930
			continue;
2931
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], 'packagegui');
2932
		$pkgname = substr(reverse_strrchr($package['configurationfile'], "."),0,-1);
2933
		if (is_array($pkg_config['plugins']['item']))
2934
			foreach ($pkg_config['plugins']['item'] as $plugin) {
2935
				if ($plugin['type'] == $plugin_type) {
2936
					if (file_exists($pkg_config['include_file']))
2937
						require_once($pkg_config['include_file']);
2938
					else
2939
						continue;
2940
					$plugin_function = $pkgname . '_'. $plugin_type;
2941
					$results[$pkgname] = @eval($plugin_function($plugin_params));
2942
				}
2943
			}
2944
	}
2945
	return $results;
2946
}
2947

    
2948
?>
(39-39/67)