Project

General

Profile

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

    
36
/*
37
	pfSense_BUILDER_BINARIES:	/sbin/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
function hardware_offloading_applyflags($iface) {
147
	global $config;
148

    
149
	$flags_on = 0;
150
	$flags_off = 0;
151
	$options = pfSense_get_interface_addresses($iface);
152

    
153
	if(isset($config['system']['disablechecksumoffloading'])) {
154
		if (isset($options['encaps']['txcsum']))
155
			$flags_off |= IFCAP_TXCSUM;
156
		if (isset($options['encaps']['rxcsum']))
157
			$flags_off |= IFCAP_RXCSUM;
158
	} else {
159
		if (isset($options['caps']['txcsum']))
160
			$flags_on |= IFCAP_TXCSUM;
161
		if (isset($options['caps']['rxcsum']))
162
			$flags_on |= IFCAP_RXCSUM;
163
	}
164

    
165
	if(isset($config['system']['disablesegmentationoffloading']))
166
		$flags_off |= IFCAP_TSO;
167
	else if (isset($options['caps']['tso']) || isset($options['caps']['tso4']) || isset($options['caps']['tso6']))
168
		$flags_on |= IFCAP_TSO;
169

    
170
	if(isset($config['system']['disablelargereceiveoffloading']))
171
		$flags_off |= IFCAP_LRO;
172
	else if (isset($options['caps']['lro']))
173
		$flags_on |= IFCAP_LRO;
174

    
175
	/* if the NIC supports polling *AND* it is enabled in the GUI */
176
	if (!isset($config['system']['polling']))
177
		$flags_off |= IFCAP_POLLING;
178
	else if (isset($options['caps']['polling']))
179
		$flags_on |= IFCAP_POLLING;
180

    
181
	pfSense_interface_capabilities($iface, -$flags_off);
182
	pfSense_interface_capabilities($iface, $flags_on);
183
}
184

    
185
/****f* pfsense-utils/enable_hardware_offloading
186
 * NAME
187
 *   enable_hardware_offloading - Enable a NIC's supported hardware features.
188
 * INPUTS
189
 *   $interface	- string containing the physical interface to work on.
190
 * RESULT
191
 *   null
192
 * NOTES
193
 *   This function only supports the fxp driver's loadable microcode.
194
 ******/
195
function enable_hardware_offloading($interface) {
196
	global $g, $config;
197

    
198
	$int = get_real_interface($interface);
199
	if(empty($int))
200
		return;
201

    
202
	if (!isset($config['system']['do_not_use_nic_microcode'])) {
203
		/* translate wan, lan, opt -> real interface if needed */
204
		$int_family = preg_split("/[0-9]+/", $int);
205
		$supported_ints = array('fxp');
206
		if (in_array($int_family, $supported_ints)) {
207
			if(does_interface_exist($int))
208
				pfSense_interface_flags($int, IFF_LINK0);
209
		}
210
	}
211

    
212
	/* This is mostly for vlans and ppp types */
213
	$realhwif = get_parent_interface($interface);
214
	if ($realhwif[0] == $int)
215
		hardware_offloading_applyflags($int);
216
	else {
217
		hardware_offloading_applyflags($realhwif[0]);
218
		hardware_offloading_applyflags($int);
219
	}
220
}
221

    
222
/****f* pfsense-utils/interface_supports_polling
223
 * NAME
224
 *   checks to see if an interface supports polling according to man polling
225
 * INPUTS
226
 *
227
 * RESULT
228
 *   true or false
229
 * NOTES
230
 *
231
 ******/
232
function interface_supports_polling($iface) {
233
	$opts = pfSense_get_interface_addresses($iface);
234
	if (is_array($opts) && isset($opts['caps']['polling']))
235
		return true;
236

    
237
	return false;
238
}
239

    
240
/****f* pfsense-utils/is_alias_inuse
241
 * NAME
242
 *   checks to see if an alias is currently in use by a rule
243
 * INPUTS
244
 *
245
 * RESULT
246
 *   true or false
247
 * NOTES
248
 *
249
 ******/
250
function is_alias_inuse($alias) {
251
	global $g, $config;
252

    
253
	if($alias == "") return false;
254
	/* loop through firewall rules looking for alias in use */
255
	if(is_array($config['filter']['rule']))
256
		foreach($config['filter']['rule'] as $rule) {
257
			if($rule['source']['address'])
258
				if($rule['source']['address'] == $alias)
259
					return true;
260
			if($rule['destination']['address'])
261
				if($rule['destination']['address'] == $alias)
262
					return true;
263
		}
264
	/* loop through nat rules looking for alias in use */
265
	if(is_array($config['nat']['rule']))
266
		foreach($config['nat']['rule'] as $rule) {
267
			if($rule['target'] && $rule['target'] == $alias)
268
				return true;
269
			if($rule['source']['address'] && $rule['source']['address'] == $alias)
270
				return true;
271
			if($rule['destination']['address'] && $rule['destination']['address'] == $alias)
272
				return true;
273
		}
274
	return false;
275
}
276

    
277
/****f* pfsense-utils/is_schedule_inuse
278
 * NAME
279
 *   checks to see if a schedule is currently in use by a rule
280
 * INPUTS
281
 *
282
 * RESULT
283
 *   true or false
284
 * NOTES
285
 *
286
 ******/
287
function is_schedule_inuse($schedule) {
288
	global $g, $config;
289

    
290
	if($schedule == "") return false;
291
	/* loop through firewall rules looking for schedule in use */
292
	if(is_array($config['filter']['rule']))
293
		foreach($config['filter']['rule'] as $rule) {
294
			if($rule['sched'] == $schedule)
295
				return true;
296
		}
297
	return false;
298
}
299

    
300
/****f* pfsense-utils/setup_polling
301
 * NAME
302
 *   sets up polling
303
 * INPUTS
304
 *
305
 * RESULT
306
 *   null
307
 * NOTES
308
 *
309
 ******/
310
function setup_polling() {
311
	global $g, $config;
312

    
313
	if (isset($config['system']['polling']))
314
		set_single_sysctl("kern.polling.idle_poll", "1");
315
	else
316
		set_single_sysctl("kern.polling.idle_poll", "0");
317

    
318
	if($config['system']['polling_each_burst'])
319
		set_single_sysctl("kern.polling.each_burst", $config['system']['polling_each_burst']);
320
	if($config['system']['polling_burst_max'])
321
		set_single_sysctl("kern.polling.burst_max", $config['system']['polling_burst_max']);
322
	if($config['system']['polling_user_frac'])
323
		set_single_sysctl("kern.polling.user_frac", $config['system']['polling_user_frac']);
324
}
325

    
326
/****f* pfsense-utils/setup_microcode
327
 * NAME
328
 *   enumerates all interfaces and calls enable_hardware_offloading which
329
 *   enables a NIC's supported hardware features.
330
 * INPUTS
331
 *
332
 * RESULT
333
 *   null
334
 * NOTES
335
 *   This function only supports the fxp driver's loadable microcode.
336
 ******/
337
function setup_microcode() {
338

    
339
	/* if list */
340
	$iflist = get_configured_interface_list(false, true);
341
	foreach($iflist as $if => $ifdescr)
342
		enable_hardware_offloading($if);
343
	unset($iflist);
344
}
345

    
346
/****f* pfsense-utils/get_carp_status
347
 * NAME
348
 *   get_carp_status - Return whether CARP is enabled or disabled.
349
 * RESULT
350
 *   boolean	- true if CARP is enabled, false if otherwise.
351
 ******/
352
function get_carp_status() {
353
	/* grab the current status of carp */
354
	$status = get_single_sysctl('net.inet.carp.allow');
355
	return (intval($status) > 0);
356
}
357

    
358
/*
359
 * convert_ip_to_network_format($ip, $subnet): converts an ip address to network form
360

    
361
 */
362
function convert_ip_to_network_format($ip, $subnet) {
363
	$ipsplit = explode('.', $ip);
364
	$string = $ipsplit[0] . "." . $ipsplit[1] . "." . $ipsplit[2] . ".0/" . $subnet;
365
	return $string;
366
}
367

    
368
/*
369
 * get_carp_interface_status($carpinterface): returns the status of a carp ip
370
 */
371
function get_carp_interface_status($carpinterface) {
372
	$carp_query = "";
373

    
374
	/* XXX: Need to fidn a better way for this! */
375
	list ($interface, $vhid) = explode("_vip", $carpinterface);
376
	$interface = get_real_interface($interface);
377
	exec("/sbin/ifconfig $interface | /usr/bin/grep -v grep | /usr/bin/grep carp: | /usr/bin/grep 'vhid {$vhid}'", $carp_query);
378
	foreach($carp_query as $int) {
379
		if(stristr($int, "MASTER"))
380
			return gettext("MASTER");
381
		if(stristr($int, "BACKUP"))
382
			return gettext("BACKUP");
383
		if(stristr($int, "INIT"))
384
			return gettext("INIT");
385
	}
386
	return;
387
}
388

    
389
/*
390
 * get_pfsync_interface_status($pfsyncinterface): returns the status of a pfsync
391
 */
392
function get_pfsync_interface_status($pfsyncinterface) {
393
	if (!does_interface_exist($pfsyncinterface))
394
		return;
395

    
396
	return exec_command("/sbin/ifconfig {$pfsyncinterface} | /usr/bin/awk '/pfsync:/ {print \$5}'");
397
}
398

    
399
/*
400
 * add_rule_to_anchor($anchor, $rule): adds the specified rule to an anchor
401
 */
402
function add_rule_to_anchor($anchor, $rule, $label) {
403
	mwexec("echo " . escapeshellarg($rule) . " | /sbin/pfctl -a " . escapeshellarg($anchor) . ":" . escapeshellarg($label) . " -f -");
404
}
405

    
406
/*
407
 * remove_text_from_file
408
 * remove $text from file $file
409
 */
410
function remove_text_from_file($file, $text) {
411
	if(!file_exists($file) && !is_writable($file))
412
		return;
413
	$filecontents = file_get_contents($file);
414
	$text = str_replace($text, "", $filecontents);
415
	@file_put_contents($file, $text);
416
}
417

    
418
/*
419
 * add_text_to_file($file, $text): adds $text to $file.
420
 * replaces the text if it already exists.
421
 */
422
function add_text_to_file($file, $text, $replace = false) {
423
	if(file_exists($file) and is_writable($file)) {
424
		$filecontents = file($file);
425
		$filecontents = array_map('rtrim', $filecontents);
426
		array_push($filecontents, $text);
427
		if ($replace)
428
			$filecontents = array_unique($filecontents);
429

    
430
		$file_text = implode("\n", $filecontents);
431

    
432
		@file_put_contents($file, $file_text);
433
		return true;
434
	}
435
	return false;
436
}
437

    
438
/*
439
 *   after_sync_bump_adv_skew(): create skew values by 1S
440
 */
441
function after_sync_bump_adv_skew() {
442
	global $config, $g;
443
	$processed_skew = 1;
444
	$a_vip = &$config['virtualip']['vip'];
445
	foreach ($a_vip as $vipent) {
446
		if($vipent['advskew'] <> "") {
447
			$processed_skew = 1;
448
			$vipent['advskew'] = $vipent['advskew']+1;
449
		}
450
	}
451
	if($processed_skew == 1)
452
		write_config(gettext("After synch increase advertising skew"));
453
}
454

    
455
/*
456
 * get_filename_from_url($url): converts a url to its filename.
457
 */
458
function get_filename_from_url($url) {
459
	return basename($url);
460
}
461

    
462
/*
463
 *   get_dir: return an array of $dir
464
 */
465
function get_dir($dir) {
466
	$dir_array = array();
467
	$d = dir($dir);
468
	while (false !== ($entry = $d->read())) {
469
		array_push($dir_array, $entry);
470
	}
471
	$d->close();
472
	return $dir_array;
473
}
474

    
475
/****f* pfsense-utils/WakeOnLan
476
 * NAME
477
 *   WakeOnLan - Wake a machine up using the wake on lan format/protocol
478
 * RESULT
479
 *   true/false - true if the operation was successful
480
 ******/
481
function WakeOnLan($addr, $mac)
482
{
483
	$addr_byte = explode(':', $mac);
484
	$hw_addr = '';
485

    
486
	for ($a=0; $a < 6; $a++)
487
		$hw_addr .= chr(hexdec($addr_byte[$a]));
488

    
489
	$msg = chr(255).chr(255).chr(255).chr(255).chr(255).chr(255);
490

    
491
	for ($a = 1; $a <= 16; $a++)
492
		$msg .= $hw_addr;
493

    
494
	// send it to the broadcast address using UDP
495
	$s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
496
	if ($s == false) {
497
		log_error(gettext("Error creating socket!"));
498
		log_error(sprintf(gettext("Error code is '%1\$s' - %2\$s"), socket_last_error($s), socket_strerror(socket_last_error($s))));
499
	} else {
500
		// setting a broadcast option to socket:
501
		$opt_ret =  socket_set_option($s, 1, 6, TRUE);
502
		if($opt_ret < 0)
503
			log_error(sprintf(gettext("setsockopt() failed, error: %s"), strerror($opt_ret)));
504
		$e = socket_sendto($s, $msg, strlen($msg), 0, $addr, 2050);
505
		socket_close($s);
506
		log_error(sprintf(gettext('Magic Packet sent (%1$s) to {%2$s} MAC=%3$s'), $e, $addr, $mac));
507
		return true;
508
	}
509

    
510
	return false;
511
}
512

    
513
/*
514
 * reverse_strrchr($haystack, $needle):  Return everything in $haystack up to the *last* instance of $needle.
515
 *					 Useful for finding paths and stripping file extensions.
516
 */
517
function reverse_strrchr($haystack, $needle) {
518
	if (!is_string($haystack))
519
		return;
520
	return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) +1 ) : false;
521
}
522

    
523
/*
524
 *  backup_config_section($section): returns as an xml file string of
525
 *                                   the configuration section
526
 */
527
function backup_config_section($section_name) {
528
	global $config;
529
	$new_section = &$config[$section_name];
530
	/* generate configuration XML */
531
	$xmlconfig = dump_xml_config($new_section, $section_name);
532
	$xmlconfig = str_replace("<?xml version=\"1.0\"?>", "", $xmlconfig);
533
	return $xmlconfig;
534
}
535

    
536
/*
537
 *  restore_config_section($section_name, new_contents): restore a configuration section,
538
 *                                                  and write the configuration out
539
 *                                                  to disk/cf.
540
 */
541
function restore_config_section($section_name, $new_contents) {
542
	global $config, $g;
543
	conf_mount_rw();
544
	$fout = fopen("{$g['tmp_path']}/tmpxml","w");
545
	fwrite($fout, $new_contents);
546
	fclose($fout);
547

    
548
	$xml = parse_xml_config($g['tmp_path'] . "/tmpxml", null);
549
	if ($xml['pfsense']) {
550
		$xml = $xml['pfsense'];
551
	}
552
	else if ($xml['m0n0wall']) {
553
		$xml = $xml['m0n0wall'];
554
	}
555
	if ($xml[$section_name]) {
556
		$section_xml = $xml[$section_name];
557
	} else {
558
		$section_xml = -1;
559
	}
560

    
561
	@unlink($g['tmp_path'] . "/tmpxml");
562
	if ($section_xml === -1) {
563
		return false;
564
	}
565
	$config[$section_name] = &$section_xml;
566
	if(file_exists("{$g['tmp_path']}/config.cache"))
567
		unlink("{$g['tmp_path']}/config.cache");
568
	write_config(sprintf(gettext("Restored %s of config file (maybe from CARP partner)"), $section_name));
569
	disable_security_checks();
570
	conf_mount_ro();
571
	return true;
572
}
573

    
574
/*
575
 *  merge_config_section($section_name, new_contents):   restore a configuration section,
576
 *                                                  and write the configuration out
577
 *                                                  to disk/cf.  But preserve the prior
578
 * 													structure if needed
579
 */
580
function merge_config_section($section_name, $new_contents) {
581
	global $config;
582
	conf_mount_rw();
583
	$fname = get_tmp_filename();
584
	$fout = fopen($fname, "w");
585
	fwrite($fout, $new_contents);
586
	fclose($fout);
587
	$section_xml = parse_xml_config($fname, $section_name);
588
	$config[$section_name] = $section_xml;
589
	unlink($fname);
590
	write_config(sprintf(gettext("Restored %s of config file (maybe from CARP partner)"), $section_name));
591
	disable_security_checks();
592
	conf_mount_ro();
593
	return;
594
}
595

    
596
/*
597
 * http_post($server, $port, $url, $vars): does an http post to a web server
598
 *                                         posting the vars array.
599
 * written by nf@bigpond.net.au
600
 */
601
function http_post($server, $port, $url, $vars) {
602
	$user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)";
603
	$urlencoded = "";
604
	while (list($key,$value) = each($vars))
605
		$urlencoded.= urlencode($key) . "=" . urlencode($value) . "&";
606
	$urlencoded = substr($urlencoded,0,-1);
607
	$content_length = strlen($urlencoded);
608
	$headers = "POST $url HTTP/1.1
609
Accept: */*
610
Accept-Language: en-au
611
Content-Type: application/x-www-form-urlencoded
612
User-Agent: $user_agent
613
Host: $server
614
Connection: Keep-Alive
615
Cache-Control: no-cache
616
Content-Length: $content_length
617

    
618
";
619

    
620
	$errno = "";
621
	$errstr = "";
622
	$fp = fsockopen($server, $port, $errno, $errstr);
623
	if (!$fp) {
624
		return false;
625
	}
626

    
627
	fputs($fp, $headers);
628
	fputs($fp, $urlencoded);
629

    
630
	$ret = "";
631
	while (!feof($fp))
632
		$ret.= fgets($fp, 1024);
633
	fclose($fp);
634

    
635
	return $ret;
636
}
637

    
638
/*
639
 *  php_check_syntax($code_tocheck, $errormessage): checks $code_to_check for errors
640
 */
641
if (!function_exists('php_check_syntax')){
642
	global $g;
643
	function php_check_syntax($code_to_check, &$errormessage){
644
		return false;
645
		$fout = fopen("{$g['tmp_path']}/codetocheck.php","w");
646
		$code = $_POST['content'];
647
		$code = str_replace("<?php", "", $code);
648
		$code = str_replace("?>", "", $code);
649
		fwrite($fout, "<?php\n\n");
650
		fwrite($fout, $code_to_check);
651
		fwrite($fout, "\n\n?>\n");
652
		fclose($fout);
653
		$command = "/usr/local/bin/php -l {$g['tmp_path']}/codetocheck.php";
654
		$output = exec_command($command);
655
		if (stristr($output, "Errors parsing") == false) {
656
			echo "false\n";
657
			$errormessage = '';
658
			return(false);
659
		} else {
660
			$errormessage = $output;
661
			return(true);
662
		}
663
	}
664
}
665

    
666
/*
667
 *  php_check_filename_syntax($filename, $errormessage): checks the file $filename for errors
668
 */
669
if (!function_exists('php_check_syntax')){
670
	function php_check_syntax($code_to_check, &$errormessage){
671
		return false;
672
		$command = "/usr/local/bin/php -l " . escapeshellarg($code_to_check);
673
		$output = exec_command($command);
674
		if (stristr($output, "Errors parsing") == false) {
675
			echo "false\n";
676
			$errormessage = '';
677
			return(false);
678
		} else {
679
			$errormessage = $output;
680
			return(true);
681
		}
682
	}
683
}
684

    
685
/*
686
 * rmdir_recursive($path,$follow_links=false)
687
 * Recursively remove a directory tree (rm -rf path)
688
 * This is for directories _only_
689
 */
690
function rmdir_recursive($path,$follow_links=false) {
691
	$to_do = glob($path);
692
	if(!is_array($to_do)) $to_do = array($to_do);
693
	foreach($to_do as $workingdir) { // Handle wildcards by foreaching.
694
		if(file_exists($workingdir)) {
695
			if(is_dir($workingdir)) {
696
				$dir = opendir($workingdir);
697
				while ($entry = readdir($dir)) {
698
					if (is_file("$workingdir/$entry") || ((!$follow_links) && is_link("$workingdir/$entry")))
699
						unlink("$workingdir/$entry");
700
					elseif (is_dir("$workingdir/$entry") && $entry!='.' && $entry!='..')
701
						rmdir_recursive("$workingdir/$entry");
702
				}
703
				closedir($dir);
704
				rmdir($workingdir);
705
			} elseif (is_file($workingdir)) {
706
				unlink($workingdir);
707
			}
708
		}
709
	}
710
	return;
711
}
712

    
713
/*
714
 * call_pfsense_method(): Call a method exposed by the pfsense.org XMLRPC server.
715
 */
716
function call_pfsense_method($method, $params, $timeout = 0) {
717
	global $g, $config;
718

    
719
	$xmlrpc_base_url = get_active_xml_rpc_base_url();
720
	$xmlrpc_path = $g['xmlrpcpath'];
721
	
722
	$xmlrpcfqdn = preg_replace("(https?://)", "", $xmlrpc_base_url);
723
	$ip = gethostbyname($xmlrpcfqdn);
724
	if($ip == $xmlrpcfqdn)
725
		return false;
726

    
727
	$msg = new XML_RPC_Message($method, array(XML_RPC_Encode($params)));
728
	$port = 0;
729
	$proxyurl = "";
730
	$proxyport = 0;
731
	$proxyuser = "";
732
	$proxypass = "";
733
	if (!empty($config['system']['proxyurl']))
734
		$proxyurl = $config['system']['proxyurl'];
735
	if (!empty($config['system']['proxyport']) && is_numeric($config['system']['proxyport']))
736
		$proxyport = $config['system']['proxyport'];
737
	if (!empty($config['system']['proxyuser']))
738
		$proxyuser = $config['system']['proxyuser'];
739
	if (!empty($config['system']['proxypass']))
740
		$proxypass = $config['system']['proxypass'];
741
	$cli = new XML_RPC_Client($xmlrpc_path, $xmlrpc_base_url, $port, $proxyurl, $proxyport, $proxyuser, $proxypass);
742
	// If the ALT PKG Repo has a username/password set, use it.
743
	if($config['system']['altpkgrepo']['username'] &&
744
	   $config['system']['altpkgrepo']['password']) {
745
		$username = $config['system']['altpkgrepo']['username'];
746
		$password = $config['system']['altpkgrepo']['password'];
747
		$cli->setCredentials($username, $password);
748
	}
749
	$resp = $cli->send($msg, $timeout);
750
	if(!is_object($resp)) {
751
		log_error(sprintf(gettext("XMLRPC communication error: %s"), $cli->errstr));
752
		return false;
753
	} elseif($resp->faultCode()) {
754
		log_error(sprintf(gettext('XMLRPC request failed with error %1$s: %2$s'), $resp->faultCode(), $resp->faultString()));
755
		return false;
756
	} else {
757
		return XML_RPC_Decode($resp->value());
758
	}
759
}
760

    
761
/*
762
 * check_firmware_version(): Check whether the current firmware installed is the most recently released.
763
 */
764
function check_firmware_version($tocheck = "all", $return_php = true) {
765
	global $g, $config;
766
	
767
	$xmlrpc_base_url = get_active_xml_rpc_base_url();
768
	$xmlrpcfqdn = preg_replace("(https?://)", "", $xmlrpc_base_url);
769
	$ip = gethostbyname($xmlrpcfqdn);
770
	if($ip == $xmlrpcfqdn)
771
		return false;
772
	$version = php_uname('r');
773
	$version = explode('-', $version);
774
	$rawparams = array("firmware" => array("version" => trim(file_get_contents('/etc/version'))),
775
		"kernel"   => array("version" => $version[0]),
776
		"base"     => array("version" => $version[0]),
777
		"platform" => trim(file_get_contents('/etc/platform')),
778
		"config_version" => $config['version']
779
		);
780
	unset($version);
781

    
782
	if($tocheck == "all") {
783
		$params = $rawparams;
784
	} else {
785
		foreach($tocheck as $check) {
786
			$params['check'] = $rawparams['check'];
787
			$params['platform'] = $rawparams['platform'];
788
		}
789
	}
790
	if($config['system']['firmware']['branch'])
791
		$params['branch'] = $config['system']['firmware']['branch'];
792

    
793
	/* XXX: What is this method? */
794
	if(!($versions = call_pfsense_method('pfsense.get_firmware_version', $params))) {
795
		return false;
796
	} else {
797
		$versions["current"] = $params;
798
	}
799

    
800
	return $versions;
801
}
802

    
803
/*
804
 * host_firmware_version(): Return the versions used in this install
805
 */
806
function host_firmware_version($tocheck = "") {
807
	global $g, $config;
808

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

    
811
	return array(
812
		"firmware" => array("version" => trim(file_get_contents('/etc/version', " \n"))),
813
		"kernel"   => array("version" => $os_version),
814
		"base"     => array("version" => $os_version),
815
		"platform" => trim(file_get_contents('/etc/platform', " \n")),
816
		"config_version" => $config['version']
817
	);
818
}
819

    
820
function get_disk_info() {
821
	$diskout = "";
822
	exec("/bin/df -h | /usr/bin/grep -w '/' | /usr/bin/awk '{ print $2, $3, $4, $5 }'", $diskout);
823
	return explode(' ', $diskout[0]);
824
}
825

    
826
/****f* pfsense-utils/strncpy
827
 * NAME
828
 *   strncpy - copy strings
829
 * INPUTS
830
 *   &$dst, $src, $length
831
 * RESULT
832
 *   none
833
 ******/
834
function strncpy(&$dst, $src, $length) {
835
	if (strlen($src) > $length) {
836
		$dst = substr($src, 0, $length);
837
	} else {
838
		$dst = $src;
839
	}
840
}
841

    
842
/****f* pfsense-utils/reload_interfaces_sync
843
 * NAME
844
 *   reload_interfaces - reload all interfaces
845
 * INPUTS
846
 *   none
847
 * RESULT
848
 *   none
849
 ******/
850
function reload_interfaces_sync() {
851
	global $config, $g;
852

    
853
	if($g['debug'])
854
		log_error(gettext("reload_interfaces_sync() is starting."));
855

    
856
	/* parse config.xml again */
857
	$config = parse_config(true);
858

    
859
	/* enable routing */
860
	system_routing_enable();
861
	if($g['debug'])
862
		log_error(gettext("Enabling system routing"));
863

    
864
	if($g['debug'])
865
		log_error(gettext("Cleaning up Interfaces"));
866

    
867
	/* set up interfaces */
868
	interfaces_configure();
869
}
870

    
871
/****f* pfsense-utils/reload_all
872
 * NAME
873
 *   reload_all - triggers a reload of all settings
874
 *   * INPUTS
875
 *   none
876
 * RESULT
877
 *   none
878
 ******/
879
function reload_all() {
880
	send_event("service reload all");
881
}
882

    
883
/****f* pfsense-utils/reload_interfaces
884
 * NAME
885
 *   reload_interfaces - triggers a reload of all interfaces
886
 * INPUTS
887
 *   none
888
 * RESULT
889
 *   none
890
 ******/
891
function reload_interfaces() {
892
	send_event("interface all reload");
893
}
894

    
895
/****f* pfsense-utils/reload_all_sync
896
 * NAME
897
 *   reload_all - reload all settings
898
 *   * INPUTS
899
 *   none
900
 * RESULT
901
 *   none
902
 ******/
903
function reload_all_sync() {
904
	global $config, $g;
905

    
906
	$g['booting'] = false;
907

    
908
	/* parse config.xml again */
909
	$config = parse_config(true);
910

    
911
	/* set up our timezone */
912
	system_timezone_configure();
913

    
914
	/* set up our hostname */
915
	system_hostname_configure();
916

    
917
	/* make hosts file */
918
	system_hosts_generate();
919

    
920
	/* generate resolv.conf */
921
	system_resolvconf_generate();
922

    
923
	/* enable routing */
924
	system_routing_enable();
925

    
926
	/* set up interfaces */
927
	interfaces_configure();
928

    
929
	/* start dyndns service */
930
	services_dyndns_configure();
931

    
932
	/* configure cron service */
933
	configure_cron();
934

    
935
	/* start the NTP client */
936
	system_ntp_configure();
937

    
938
	/* sync pw database */
939
	conf_mount_rw();
940
	unlink_if_exists("/etc/spwd.db.tmp");
941
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
942
	conf_mount_ro();
943

    
944
	/* restart sshd */
945
	send_event("service restart sshd");
946

    
947
	/* restart webConfigurator if needed */
948
	send_event("service restart webgui");
949
}
950

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

    
965
	$serialspeed = (is_numeric($config['system']['serialspeed'])) ? $config['system']['serialspeed'] : "115200";
966
	if ($g['platform'] != "cdrom") {
967
		$boot_config_split = explode("\n", $boot_config);
968
		$fd = fopen($boot_config_file,"w");
969
		if($fd) {
970
			foreach($boot_config_split as $bcs) {
971
				if(stristr($bcs, "-D") || stristr($bcs, "-h")) {
972
					/* DONT WRITE OUT, WE'LL DO IT LATER */
973
				} else {
974
					if($bcs <> "")
975
						fwrite($fd, "{$bcs}\n");
976
				}
977
			}
978
			if (($g['platform'] == "nanobsd") && !file_exists("/etc/nano_use_vga.txt"))
979
				fwrite($fd, "-S{$serialspeed} -h");
980
			else if (is_serial_enabled())
981
				fwrite($fd, "-S{$serialspeed} -D");
982
			fclose($fd);
983
		}
984

    
985
		/* serial console - write out /boot/loader.conf */
986
		if ($when == "upgrade")
987
			system("echo \"Reading {$loader_conf_file}...\" >> /conf/upgrade_log.txt");
988
		$boot_config = file_get_contents($loader_conf_file);
989
		$boot_config_split = explode("\n", $boot_config);
990
		if(count($boot_config_split) > 0) {
991
			$new_boot_config = array();
992
			// Loop through and only add lines that are not empty, and which
993
			//  do not contain a console directive.
994
			foreach($boot_config_split as $bcs)
995
				if(!empty($bcs)
996
					&& (stripos($bcs, "console") === false)
997
					&& (stripos($bcs, "boot_multicons") === false)
998
					&& (stripos($bcs, "boot_serial") === false)
999
					&& (stripos($bcs, "hw.usb.no_pf") === false))
1000
					$new_boot_config[] = $bcs;
1001

    
1002
			if (($g['platform'] == "nanobsd") && !file_exists("/etc/nano_use_vga.txt")) {
1003
				$new_boot_config[] = 'boot_serial="YES"';
1004
				$new_boot_config[] = 'console="comconsole"';
1005
			} else if (is_serial_enabled()) {
1006
				$new_boot_config[] = 'boot_multicons="YES"';
1007
				$new_boot_config[] = 'boot_serial="YES"';
1008
				$primaryconsole = isset($g['primaryconsole_force']) ? $g['primaryconsole_force'] : $config['system']['primaryconsole'];
1009
				switch ($primaryconsole) {
1010
					case "video":
1011
						$new_boot_config[] = 'console="vidconsole,comconsole"';
1012
						break;
1013
					case "serial":
1014
					default:
1015
						$new_boot_config[] = 'console="comconsole,vidconsole"';
1016
				}
1017
			}
1018
			$new_boot_config[] = 'comconsole_speed="' . $serialspeed . '"';
1019
			$new_boot_config[] = 'hw.usb.no_pf="1"';
1020

    
1021
			file_put_contents($loader_conf_file, implode("\n", $new_boot_config) . "\n");
1022
		}
1023
	}
1024
	$ttys = file_get_contents("/etc/ttys");
1025
	$ttys_split = explode("\n", $ttys);
1026
	$fd = fopen("/etc/ttys", "w");
1027

    
1028
	$on_off = (is_serial_enabled() ? 'on' : 'off');
1029

    
1030
	if (isset($config['system']['disableconsolemenu'])) {
1031
		$console_type = 'Pc';
1032
		$serial_type = 'std.' . $serialspeed;
1033
	} else {
1034
		$console_type = 'al.Pc';
1035
		$serial_type = 'al.' . $serialspeed;
1036
	}
1037
	foreach($ttys_split as $tty) {
1038
		if (stristr($tty, "ttyv0"))
1039
			fwrite($fd, "ttyv0	\"/usr/libexec/getty {$console_type}\"	cons25	on	secure\n");
1040
		else if (stristr($tty, "ttyu0"))
1041
			fwrite($fd, "ttyu0	\"/usr/libexec/getty {$serial_type}\"	cons25	{$on_off}	secure\n");
1042
		else
1043
			fwrite($fd, $tty . "\n");
1044
	}
1045
	unset($on_off, $console_type, $serial_type);
1046
	fclose($fd);
1047
	reload_ttys();
1048

    
1049
	conf_mount_ro();
1050
	return;
1051
}
1052

    
1053
function is_serial_enabled() {
1054
	global $g, $config;
1055

    
1056
	if (!isset($g['enableserial_force']) &&
1057
	    !isset($config['system']['enableserial']) &&
1058
	    ($g['platform'] == "pfSense" || $g['platform'] == "cdrom" || file_exists("/etc/nano_use_vga.txt")))
1059
		return false;
1060

    
1061
	return true;
1062
}
1063

    
1064
function reload_ttys() {
1065
	// Send a HUP signal to init will make it reload /etc/ttys
1066
	posix_kill(1, SIGHUP);
1067
}
1068

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

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

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

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

    
1091
	return false;
1092
}
1093

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

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

    
1105
	if (!is_array($config['dhcpdv6']))
1106
		return false;
1107

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

    
1113
	return false;
1114
}
1115

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

    
1120
	if (!is_array($config['dhcpdv6']))
1121
		$config['dhcpdv6'] = array();
1122

    
1123
	$dhcpdv6cfg = $config['dhcpdv6'];
1124
	$Iflist = get_configured_interface_list();
1125

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

    
1131
		if(!isset($dhcpv6ifconf['ramode']))
1132
			$dhcpv6ifconf['ramode'] = $dhcpv6ifconf['mode'];
1133

    
1134
		if($dhcpv6ifconf['ramode'] == "disabled")
1135
			continue;
1136

    
1137
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1138
		if(!is_ipaddrv6($ifcfgipv6))
1139
			continue;
1140

    
1141
		return true;
1142
	}
1143

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

    
1151
		$ifcfgipv6 = get_interface_ipv6($if);
1152
		if(!is_ipaddrv6($ifcfgipv6))
1153
			continue;
1154

    
1155
		$ifcfgsnv6 = get_interface_subnetv6($if);
1156
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1157

    
1158
		if(!is_ipaddrv6($subnetv6))
1159
			continue;
1160

    
1161
		return true;
1162
	}
1163

    
1164
	return false;
1165
}
1166

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

    
1171
	$pppoeenable = false;
1172

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

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

    
1180
	return $pppoeenable;
1181
}
1182

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

    
1203
/* Compute the total uptime from the ppp uptime log file in the conf directory */
1204

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1460
	return $ifinfo;
1461
}
1462

    
1463
//returns cpu speed of processor. Good for determining capabilities of machine
1464
function get_cpu_speed() {
1465
	return get_single_sysctl("hw.clockrate");
1466
}
1467

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1643
	return false;
1644
}
1645

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1893
}
1894

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

    
1898
	$updated = false;
1899

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

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

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

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

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

    
1989
	return true;
1990
}
1991

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

    
2021
	return true;
2022
}
2023

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2553
}
2554

    
2555
/****f* pfsense-utils/is_ipaddr_configured
2556
 * NAME
2557
 *   is_ipaddr_configured
2558
 * INPUTS
2559
 *   IP Address to check.
2560
 *   If ignore_if is a VIP (not carp), vip array index is passed after string _virtualip
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
	$pos = strpos($ignore_if, '_virtualip');
2569
	if ($pos !== false) {
2570
		$ignore_vip_id = substr($ignore_if, $pos+10);
2571
		$ignore_vip_if = substr($ignore_if, 0, $pos);
2572
	} else {
2573
		$ignore_vip_id = -1;
2574
		$ignore_vip_if = $ignore_if;
2575
	}
2576

    
2577
	$isipv6 = is_ipaddrv6($ipaddr);
2578

    
2579
	if ($check_subnets) {
2580
		$iflist = get_configured_interface_list();
2581
		foreach ($iflist as $if => $ifname) {
2582
			if ($ignore_if == $if)
2583
				continue;
2584

    
2585
			if ($isipv6 === true) {
2586
				$bitmask = get_interface_subnetv6($if);
2587
				$subnet = gen_subnetv6(get_interface_ipv6($if), $bitmask);
2588
			} else {
2589
				$bitmask = get_interface_subnet($if);
2590
				$subnet = gen_subnet(get_interface_ip($if), $bitmask);
2591
			}
2592

    
2593
			if (ip_in_subnet($ipaddr, $subnet . '/' . $bitmask))
2594
				return true;
2595
		}
2596
	} else {
2597
		if ($isipv6 === true)
2598
			$interface_list_ips = get_configured_ipv6_addresses();
2599
		else
2600
			$interface_list_ips = get_configured_ip_addresses();
2601

    
2602
		foreach($interface_list_ips as $if => $ilips) {
2603
			if ($ignore_if == $if)
2604
				continue;
2605
			if (strcasecmp($ipaddr, $ilips) == 0)
2606
				return true;
2607
		}
2608
	}
2609

    
2610
	$interface_list_vips = get_configured_vips_list(true);
2611
	foreach ($interface_list_vips as $id => $vip) {
2612
		/* Skip CARP interfaces here since they were already checked above */
2613
		if ($id == $ignore_vip_id || (strstr($ignore_if, '_vip') && $ignore_vip_if == $vip['if']))
2614
			continue;
2615
		if (strcasecmp($ipaddr, $vip['ipaddr']) == 0)
2616
			return true;
2617
	}
2618

    
2619
	if ($check_localip) {
2620
		if (is_array($config['pptpd']) && !empty($config['pptpd']['localip']) && (strcasecmp($ipaddr, $config['pptpd']['localip']) == 0))
2621
			return true;
2622

    
2623
		if (!is_array($config['l2tp']) && !empty($config['l2tp']['localip']) && (strcasecmp($ipaddr, $config['l2tp']['localip']) == 0))
2624
			return true;
2625
	}
2626

    
2627
	return false;
2628
}
2629

    
2630
/****f* pfsense-utils/pfSense_handle_custom_code
2631
 * NAME
2632
 *   pfSense_handle_custom_code
2633
 * INPUTS
2634
 *   directory name to process
2635
 * RESULT
2636
 *   globs the directory and includes the files
2637
 */
2638
function pfSense_handle_custom_code($src_dir) {
2639
	// Allow extending of the nat edit page and include custom input validation
2640
	if(is_dir("$src_dir")) {
2641
		$cf = glob($src_dir . "/*.inc");
2642
		foreach($cf as $nf) {
2643
			if($nf == "." || $nf == "..")
2644
				continue;
2645
			// Include the extra handler
2646
			include("$nf");
2647
		}
2648
	}
2649
}
2650

    
2651
function set_language($lang = 'en_US', $encoding = "UTF-8") {
2652
	putenv("LANG={$lang}.{$encoding}");
2653
	setlocale(LC_ALL, "{$lang}.{$encoding}");
2654
	textdomain("pfSense");
2655
	bindtextdomain("pfSense","/usr/local/share/locale");
2656
	bind_textdomain_codeset("pfSense","{$lang}.{$encoding}");
2657
}
2658

    
2659
function get_locale_list() {
2660
	$locales = array(
2661
		"en_US" => gettext("English"),
2662
		"pt_BR" => gettext("Portuguese (Brazil)"),
2663
		"tr" => gettext("Turkish"),
2664
	);
2665
	asort($locales);
2666
	return $locales;
2667
}
2668

    
2669
function system_get_language_code() {
2670
	global $config, $g_languages;
2671

    
2672
	// a language code, as per [RFC3066]
2673
	$language = $config['system']['language'];
2674
	//$code = $g_languages[$language]['code'];
2675
	$code = str_replace("_", "-", $language);
2676

    
2677
	if (empty($code))
2678
		$code = "en-US"; // Set default code.
2679

    
2680
	return $code;
2681
}
2682

    
2683
function system_get_language_codeset() {
2684
	global $config, $g_languages;
2685

    
2686
	$language = $config['system']['language'];
2687
	$codeset = $g_languages[$language]['codeset'];
2688

    
2689
	if (empty($codeset))
2690
		$codeset = "UTF-8"; // Set default codeset.
2691

    
2692
	return $codeset;
2693
}
2694

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

    
2727
function return_hex_ipv4($ipv4) {
2728
	if(!is_ipaddrv4($ipv4))
2729
		return(false);
2730

    
2731
	/* we need the hex form of the interface IPv4 address */
2732
	$ip4arr = explode(".", $ipv4);
2733
	return (sprintf("%02x%02x%02x%02x", $ip4arr[0], $ip4arr[1], $ip4arr[2], $ip4arr[3]));
2734
}
2735

    
2736
function convert_ipv6_to_128bit($ipv6) {
2737
	if(!is_ipaddrv6($ipv6))
2738
		return(false);
2739

    
2740
	$ip6arr = array();
2741
	$ip6prefix = Net_IPv6::uncompress($ipv6);
2742
	$ip6arr = explode(":", $ip6prefix);
2743
	/* binary presentation of the prefix for all 128 bits. */
2744
	$ip6prefixbin = "";
2745
	foreach($ip6arr as $element) {
2746
		$ip6prefixbin .= sprintf("%016b", hexdec($element));
2747
	}
2748
	return($ip6prefixbin);
2749
}
2750

    
2751
function convert_128bit_to_ipv6($ip6bin) {
2752
	if(strlen($ip6bin) <> 128)
2753
		return(false);
2754

    
2755
	$ip6arr = array();
2756
	$ip6binarr = array();
2757
	$ip6binarr = str_split($ip6bin, 16);
2758
	foreach($ip6binarr as $binpart)
2759
		$ip6arr[] = dechex(bindec($binpart));
2760
	$ip6addr = Net_IPv6::compress(implode(":", $ip6arr));
2761

    
2762
	return($ip6addr);
2763
}
2764

    
2765

    
2766
/* Returns the calculated bit length of the prefix delegation from the WAN interface */
2767
/* DHCP-PD is variable, calculate from the prefix-len on the WAN interface */
2768
/* 6rd is variable, calculate from 64 - (v6 prefixlen - (32 - v4 prefixlen)) */
2769
/* 6to4 is 16 bits, e.g. 65535 */
2770
function calculate_ipv6_delegation_length($if) {
2771
	global $config;
2772

    
2773
	if(!is_array($config['interfaces'][$if]))
2774
		return false;
2775

    
2776
	switch($config['interfaces'][$if]['ipaddrv6']) {
2777
		case "6to4":
2778
			$pdlen = 16;
2779
			break;
2780
		case "6rd":
2781
			$rd6cfg = $config['interfaces'][$if];
2782
			$rd6plen = explode("/", $rd6cfg['prefix-6rd']);
2783
			$pdlen = (64 - ($rd6plen[1] + (32 - $rd6cfg['prefix-6rd-v4plen'])));
2784
			break;
2785
		case "dhcp6":
2786
			$dhcp6cfg = $config['interfaces'][$if];
2787
			$pdlen = $dhcp6cfg['dhcp6-ia-pd-len'];
2788
			break;
2789
		default:
2790
			$pdlen = 0;
2791
			break;
2792
	}
2793
	return($pdlen);
2794
}
2795

    
2796
function huawei_rssi_to_string($rssi) {
2797
	$dbm = array();
2798
	$i = 0;
2799
	$dbstart = -113;
2800
	while($i < 32) {
2801
		$dbm[$i] = $dbstart + ($i * 2);
2802
		$i++;
2803
	}
2804
	$percent = round(($rssi / 31) * 100);
2805
	$string = "rssi:{$rssi} level:{$dbm[$rssi]}dBm percent:{$percent}%";
2806
	return $string;
2807
}
2808

    
2809
function huawei_mode_to_string($mode, $submode) {
2810
	$modes[0] = "None";
2811
	$modes[1] = "AMPS";
2812
	$modes[2] = "CDMA";
2813
	$modes[3] = "GSM/GPRS";
2814
	$modes[4] = "HDR";
2815
	$modes[5] = "WCDMA";
2816
	$modes[6] = "GPS";
2817

    
2818
	$submodes[0] = "No Service";
2819
	$submodes[1] = "GSM";
2820
	$submodes[2] = "GPRS";
2821
	$submodes[3] = "EDGE";
2822
	$submodes[4] = "WCDMA";
2823
	$submodes[5] = "HSDPA";
2824
	$submodes[6] = "HSUPA";
2825
	$submodes[7] = "HSDPA+HSUPA";
2826
	$submodes[8] = "TD-SCDMA";
2827
	$submodes[9] = "HSPA+";
2828
	$string = "{$modes[$mode]}, {$submodes[$submode]} Mode";
2829
	return $string;
2830
}
2831

    
2832
function huawei_service_to_string($state) {
2833
	$modes[0] = "No";
2834
	$modes[1] = "Restricted";
2835
	$modes[2] = "Valid";
2836
	$modes[3] = "Restricted Regional";
2837
	$modes[4] = "Powersaving";
2838
	$string = "{$modes[$state]} Service";
2839
	return $string;
2840
}
2841

    
2842
function huawei_simstate_to_string($state) {
2843
	$modes[0] = "Invalid SIM/locked";
2844
	$modes[1] = "Valid SIM";
2845
	$modes[2] = "Invalid SIM CS";
2846
	$modes[3] = "Invalid SIM PS";
2847
	$modes[4] = "Invalid SIM CS/PS";
2848
	$modes[255] = "Missing SIM";
2849
	$string = "{$modes[$state]} State";
2850
	return $string;
2851
}
2852

    
2853
function zte_rssi_to_string($rssi) {
2854
	return huawei_rssi_to_string($rssi);
2855
}
2856

    
2857
function zte_mode_to_string($mode, $submode) {
2858
	$modes[0] = "No Service";
2859
	$modes[1] = "Limited Service";
2860
	$modes[2] = "GPRS";
2861
	$modes[3] = "GSM";
2862
	$modes[4] = "UMTS";
2863
	$modes[5] = "EDGE";
2864
	$modes[6] = "HSDPA";
2865

    
2866
	$submodes[0] = "CS_ONLY";
2867
	$submodes[1] = "PS_ONLY";
2868
	$submodes[2] = "CS_PS";
2869
	$submodes[3] = "CAMPED";
2870
	$string = "{$modes[$mode]}, {$submodes[$submode]} Mode";
2871
	return $string;
2872
}
2873

    
2874
function zte_service_to_string($state) {
2875
	$modes[0] = "Initializing";
2876
	$modes[1] = "Network Lock error";
2877
	$modes[2] = "Network Locked";
2878
	$modes[3] = "Unlocked or correct MCC/MNC";
2879
	$string = "{$modes[$state]} Service";
2880
	return $string;
2881
}
2882

    
2883
function zte_simstate_to_string($state) {
2884
	$modes[0] = "No action";
2885
	$modes[1] = "Network lock";
2886
	$modes[2] = "(U)SIM card lock";
2887
	$modes[3] = "Network Lock and (U)SIM card Lock";
2888
	$string = "{$modes[$state]} State";
2889
	return $string;
2890
}
2891

    
2892
function get_configured_pppoe_server_interfaces() {
2893
	global $config;
2894
	$iflist = array();
2895
	if (is_array($config['pppoes']['pppoe'])) {
2896
		foreach($config['pppoes']['pppoe'] as $pppoe) {
2897
			if ($pppoe['mode'] == "server") {
2898
				$int = "poes". $pppoe['pppoeid'];
2899
				$iflist[$int] = strtoupper($int);
2900
			}
2901
		}
2902
	}
2903
	return $iflist;
2904
}
2905

    
2906
function get_pppoes_child_interfaces($ifpattern) {
2907
	$if_arr = array();
2908
	if($ifpattern == "")
2909
		return;
2910

    
2911
	exec("ifconfig", $out, $ret);
2912
	foreach($out as $line) {
2913
		if(preg_match("/^({$ifpattern}[0-9]+):/i", $line, $match)) {
2914
			$if_arr[] = $match[1];
2915
		}
2916
	}
2917
	return $if_arr;
2918

    
2919
}
2920

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

    
2957
/* Function to find and return the active XML RPC base URL to avoid code duplication */
2958
function get_active_xml_rpc_base_url() {
2959
	global $config, $g;
2960
	/* If the user has activated the option to enable an alternate xmlrpcbaseurl, and it's not empty, then use it */
2961
	if (isset($config['system']['altpkgrepo']['enable']) && !empty($config['system']['altpkgrepo']['xmlrpcbaseurl'])) {
2962
		return $config['system']['altpkgrepo']['xmlrpcbaseurl'];
2963
	} else {
2964
		return $g['xmlrpcbaseurl'];
2965
	}
2966
}
2967

    
2968
?>
(40-40/68)