Project

General

Profile

Download (85.7 KB) Statistics
| Branch: | Tag: | Revision:
1 14227c51 Scott Ullrich
<?php
2 3076becf Scott Ullrich
/****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 69487053 Seth Mos
 * Copyright (C) 2004-2007 Scott Ullrich (sullrich@gmail.com)
12 3076becf Scott Ullrich
 * 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 523855b0 Scott Ullrich
/*
37 971de1f9 Renato Botelho
	pfSense_BUILDER_BINARIES:	/sbin/ifconfig	/sbin/pfctl	/usr/local/bin/php /usr/bin/netstat
38 523855b0 Scott Ullrich
	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 0397013a Scott Ullrich
/****f* pfsense-utils/have_natpfruleint_access
44
 * NAME
45
 *   have_natpfruleint_access
46
 * INPUTS
47 c96e71d1 Renato Botelho
 *	none
48 0397013a Scott Ullrich
 * 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 5fa78adc Renato Botelho
	if(isAllowedPage($security_url, $allowed))
54 0397013a Scott Ullrich
		return true;
55
	return false;
56
}
57
58 b6742927 Scott Ullrich
/****f* pfsense-utils/have_ruleint_access
59
 * NAME
60
 *   have_ruleint_access
61
 * INPUTS
62 c96e71d1 Renato Botelho
 *	none
63 b6742927 Scott Ullrich
 * 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 5fa78adc Renato Botelho
	if(isAllowedPage($security_url))
69 45ee90ed Matthew Grooms
		return true;
70 b6742927 Scott Ullrich
	return false;
71
}
72
73 10387862 Scott Ullrich
/****f* pfsense-utils/does_url_exist
74
 * NAME
75
 *   does_url_exist
76
 * INPUTS
77 c96e71d1 Renato Botelho
 *	none
78 10387862 Scott Ullrich
 * RESULT
79
 *   returns true if a url is available
80
 ******/
81
function does_url_exist($url) {
82 3264c13b Scott Ullrich
	$fd = fopen("$url","r");
83 10387862 Scott Ullrich
	if($fd) {
84 4cc6345e Scott Ullrich
		fclose($fd);
85 5fa78adc Renato Botelho
		return true;
86 10387862 Scott Ullrich
	} else {
87 5fa78adc Renato Botelho
		return false;
88 10387862 Scott Ullrich
	}
89
}
90
91 5928bd75 Scott Ullrich
/****f* pfsense-utils/is_private_ip
92
 * NAME
93
 *   is_private_ip
94
 * INPUTS
95 c96e71d1 Renato Botelho
 *	none
96 5928bd75 Scott Ullrich
 * RESULT
97
 *   returns true if an ip address is in a private range
98
 ******/
99
function is_private_ip($iptocheck) {
100 5fa78adc Renato Botelho
	$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 5928bd75 Scott Ullrich
}
113
114 8cb370b9 Scott Ullrich
/****f* pfsense-utils/get_tmp_file
115
 * NAME
116
 *   get_tmp_file
117
 * INPUTS
118 c96e71d1 Renato Botelho
 *	none
119 8cb370b9 Scott Ullrich
 * RESULT
120
 *   returns a temporary filename
121
 ******/
122 3076becf Scott Ullrich
function get_tmp_file() {
123 da17d77e Ermal Lu?i
	global $g;
124
	return "{$g['tmp_path']}/tmp-" . time();
125 3076becf Scott Ullrich
}
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 fa112436 Ermal
	$dns_s = file("/etc/resolv.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
138 3076becf Scott Ullrich
	foreach($dns_s as $dns) {
139
		$matches = "";
140
		if (preg_match("/nameserver (.*)/", $dns, $matches))
141
			$dns_servers[] = $matches[1];
142
	}
143 fa112436 Ermal
	return array_unique($dns_servers);
144 3076becf Scott Ullrich
}
145
146 43517fcc Ermal LUÇI
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 3076becf Scott Ullrich
/****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 a2934331 Scott Ullrich
	$int = get_real_interface($interface);
199 5fa78adc Renato Botelho
	if(empty($int))
200 3d063391 Ermal
		return;
201 43517fcc Ermal LUÇI
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 a2934331 Scott Ullrich
	}
211 3076becf Scott Ullrich
212 43517fcc Ermal LUÇI
	/* 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 3076becf Scott Ullrich
}
221
222 f7eb54e4 Scott Ullrich
/****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 3d063391 Ermal
	$opts = pfSense_get_interface_addresses($iface);
234
	if (is_array($opts) && isset($opts['caps']['polling']))
235 f7eb54e4 Scott Ullrich
		return true;
236 3d063391 Ermal
237 f7eb54e4 Scott Ullrich
	return false;
238
}
239
240 3076becf Scott Ullrich
/****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 346e2e6b Scott Ullrich
	if(is_array($config['filter']['rule']))
256 3076becf Scott Ullrich
		foreach($config['filter']['rule'] as $rule) {
257 00eee841 Scott Ullrich
			if($rule['source']['address'])
258 3076becf Scott Ullrich
				if($rule['source']['address'] == $alias)
259 0c8c496e Scott Ullrich
					return true;
260 00eee841 Scott Ullrich
			if($rule['destination']['address'])
261 3076becf Scott Ullrich
				if($rule['destination']['address'] == $alias)
262 0c8c496e Scott Ullrich
					return true;
263
		}
264 3076becf Scott Ullrich
	/* loop through nat rules looking for alias in use */
265
	if(is_array($config['nat']['rule']))
266
		foreach($config['nat']['rule'] as $rule) {
267 59ecde49 Renato Botelho
			if($rule['target'] && $rule['target'] == $alias)
268 3076becf Scott Ullrich
				return true;
269 59ecde49 Renato Botelho
			if($rule['source']['address'] && $rule['source']['address'] == $alias)
270
				return true;
271
			if($rule['destination']['address'] && $rule['destination']['address'] == $alias)
272 3076becf Scott Ullrich
				return true;
273
		}
274
	return false;
275
}
276
277 63724b02 Scott Dale
/****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 591ceb32 Scott Dale
			if($rule['sched'] == $schedule)
295
				return true;
296 63724b02 Scott Dale
		}
297
	return false;
298
}
299
300 3076becf Scott Ullrich
/****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 51d5aad7 Ermal
	if (isset($config['system']['polling']))
314 971de1f9 Renato Botelho
		set_single_sysctl("kern.polling.idle_poll", "1");
315 51d5aad7 Ermal
	else
316 971de1f9 Renato Botelho
		set_single_sysctl("kern.polling.idle_poll", "0");
317 3076becf Scott Ullrich
318 9a4c3eed Ermal
	if($config['system']['polling_each_burst'])
319 971de1f9 Renato Botelho
		set_single_sysctl("kern.polling.each_burst", $config['system']['polling_each_burst']);
320 9a4c3eed Ermal
	if($config['system']['polling_burst_max'])
321 971de1f9 Renato Botelho
		set_single_sysctl("kern.polling.burst_max", $config['system']['polling_burst_max']);
322 9a4c3eed Ermal
	if($config['system']['polling_user_frac'])
323 971de1f9 Renato Botelho
		set_single_sysctl("kern.polling.user_frac", $config['system']['polling_user_frac']);
324 3076becf Scott Ullrich
}
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 3a4ce87d Ermal Luçi
	/* if list */
340 43517fcc Ermal LUÇI
	$iflist = get_configured_interface_list(false, true);
341
	foreach($iflist as $if => $ifdescr)
342 3076becf Scott Ullrich
		enable_hardware_offloading($if);
343 dced0dd0 Ermal LUÇI
	unset($iflist);
344 3076becf Scott Ullrich
}
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 5fa78adc Renato Botelho
	/* grab the current status of carp */
354 971de1f9 Renato Botelho
	$status = get_single_sysctl('net.inet.carp.allow');
355 5fa78adc Renato Botelho
	return (intval($status) > 0);
356 3076becf Scott Ullrich
}
357
358
/*
359
 * convert_ip_to_network_format($ip, $subnet): converts an ip address to network form
360 52947718 Ermal Lu?i
361 3076becf Scott Ullrich
 */
362
function convert_ip_to_network_format($ip, $subnet) {
363 2ce660ad smos
	$ipsplit = explode('.', $ip);
364 3076becf Scott Ullrich
	$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 108cfddf Ermal
	$carp_query = "";
373 b6877e06 Ermal
374 42cc62a2 Renato Botelho
	/* XXX: Need to find a better way for this! */
375 0c21eb70 Ermal
	list ($interface, $vhid) = explode("_vip", $carpinterface);
376
	$interface = get_real_interface($interface);
377 b6877e06 Ermal
	exec("/sbin/ifconfig $interface | /usr/bin/grep -v grep | /usr/bin/grep carp: | /usr/bin/grep 'vhid {$vhid}'", $carp_query);
378 3076becf Scott Ullrich
	foreach($carp_query as $int) {
379 5fa78adc Renato Botelho
		if(stristr($int, "MASTER"))
380 42cc62a2 Renato Botelho
			return "MASTER";
381 5fa78adc Renato Botelho
		if(stristr($int, "BACKUP"))
382 42cc62a2 Renato Botelho
			return "BACKUP";
383 5fa78adc Renato Botelho
		if(stristr($int, "INIT"))
384 42cc62a2 Renato Botelho
			return "INIT";
385 3076becf Scott Ullrich
	}
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 306f8556 Renato Botelho
	if (!does_interface_exist($pfsyncinterface))
394
		return;
395
396
	return exec_command("/sbin/ifconfig {$pfsyncinterface} | /usr/bin/awk '/pfsync:/ {print \$5}'");
397 3076becf Scott Ullrich
}
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 873c1701 Renato Botelho
	mwexec("echo " . escapeshellarg($rule) . " | /sbin/pfctl -a " . escapeshellarg($anchor) . ":" . escapeshellarg($label) . " -f -");
404 3076becf Scott Ullrich
}
405
406
/*
407
 * remove_text_from_file
408
 * remove $text from file $file
409
 */
410
function remove_text_from_file($file, $text) {
411 2addd5b2 Ermal
	if(!file_exists($file) && !is_writable($file))
412
		return;
413 3076becf Scott Ullrich
	$filecontents = file_get_contents($file);
414 2addd5b2 Ermal
	$text = str_replace($text, "", $filecontents);
415 5fa78adc Renato Botelho
	@file_put_contents($file, $text);
416 3076becf Scott Ullrich
}
417
418
/*
419
 * add_text_to_file($file, $text): adds $text to $file.
420
 * replaces the text if it already exists.
421
 */
422 5a6f3ca0 Scott Ullrich
function add_text_to_file($file, $text, $replace = false) {
423 3076becf Scott Ullrich
	if(file_exists($file) and is_writable($file)) {
424 5a6f3ca0 Scott Ullrich
		$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 5fa78adc Renato Botelho
		@file_put_contents($file, $file_text);
433 3076becf Scott Ullrich
		return true;
434 0c8c496e Scott Ullrich
	}
435 2addd5b2 Ermal
	return false;
436 3076becf Scott Ullrich
}
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 7d1b238c Carlos Eduardo Ramos
		write_config(gettext("After synch increase advertising skew"));
453 3076becf Scott Ullrich
}
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 7d1b238c Carlos Eduardo Ramos
		log_error(gettext("Error creating socket!"));
498 addc0439 Renato Botelho
		log_error(sprintf(gettext("Error code is '%1\$s' - %2\$s"), socket_last_error($s), socket_strerror(socket_last_error($s))));
499 3076becf Scott Ullrich
	} else {
500
		// setting a broadcast option to socket:
501
		$opt_ret =  socket_set_option($s, 1, 6, TRUE);
502
		if($opt_ret < 0)
503 7d1b238c Carlos Eduardo Ramos
			log_error(sprintf(gettext("setsockopt() failed, error: %s"), strerror($opt_ret)));
504 3076becf Scott Ullrich
		$e = socket_sendto($s, $msg, strlen($msg), 0, $addr, 2050);
505
		socket_close($s);
506 addc0439 Renato Botelho
		log_error(sprintf(gettext('Magic Packet sent (%1$s) to {%2$s} MAC=%3$s'), $e, $addr, $mac));
507 3076becf Scott Ullrich
		return true;
508 0c8c496e Scott Ullrich
	}
509 3076becf Scott Ullrich
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 4824d857 Ermal Lu?i
	if (!is_string($haystack))
519
		return;
520 3076becf Scott Ullrich
	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 8dcca9b5 Darren Embry
function backup_config_section($section_name) {
528 3076becf Scott Ullrich
	global $config;
529 8dcca9b5 Darren Embry
	$new_section = &$config[$section_name];
530 3076becf Scott Ullrich
	/* generate configuration XML */
531 8dcca9b5 Darren Embry
	$xmlconfig = dump_xml_config($new_section, $section_name);
532 3076becf Scott Ullrich
	$xmlconfig = str_replace("<?xml version=\"1.0\"?>", "", $xmlconfig);
533
	return $xmlconfig;
534
}
535
536
/*
537 8dcca9b5 Darren Embry
 *  restore_config_section($section_name, new_contents): restore a configuration section,
538 3076becf Scott Ullrich
 *                                                  and write the configuration out
539
 *                                                  to disk/cf.
540
 */
541 8dcca9b5 Darren Embry
function restore_config_section($section_name, $new_contents) {
542 3076becf Scott Ullrich
	global $config, $g;
543
	conf_mount_rw();
544
	$fout = fopen("{$g['tmp_path']}/tmpxml","w");
545
	fwrite($fout, $new_contents);
546
	fclose($fout);
547 8dcca9b5 Darren Embry
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 541989d5 Ermal
	@unlink($g['tmp_path'] . "/tmpxml");
562 8dcca9b5 Darren Embry
	if ($section_xml === -1) {
563
		return false;
564
	}
565
	$config[$section_name] = &$section_xml;
566 a57d6170 Scott Ullrich
	if(file_exists("{$g['tmp_path']}/config.cache"))
567
		unlink("{$g['tmp_path']}/config.cache");
568 8dcca9b5 Darren Embry
	write_config(sprintf(gettext("Restored %s of config file (maybe from CARP partner)"), $section_name));
569 0f806eca Erik Fonnesbeck
	disable_security_checks();
570 3076becf Scott Ullrich
	conf_mount_ro();
571 8dcca9b5 Darren Embry
	return true;
572 3076becf Scott Ullrich
}
573
574
/*
575 8dcca9b5 Darren Embry
 *  merge_config_section($section_name, new_contents):   restore a configuration section,
576 3076becf Scott Ullrich
 *                                                  and write the configuration out
577
 *                                                  to disk/cf.  But preserve the prior
578
 * 													structure if needed
579
 */
580 8dcca9b5 Darren Embry
function merge_config_section($section_name, $new_contents) {
581 3076becf Scott Ullrich
	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 8dcca9b5 Darren Embry
	$section_xml = parse_xml_config($fname, $section_name);
588
	$config[$section_name] = $section_xml;
589 3076becf Scott Ullrich
	unlink($fname);
590 8dcca9b5 Darren Embry
	write_config(sprintf(gettext("Restored %s of config file (maybe from CARP partner)"), $section_name));
591 0f806eca Erik Fonnesbeck
	disable_security_checks();
592 3076becf Scott Ullrich
	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 0c8c496e Scott Ullrich
		return false;
625
	}
626 3076becf Scott Ullrich
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 da17d77e Ermal Lu?i
	global $g;
643 3076becf Scott Ullrich
	function php_check_syntax($code_to_check, &$errormessage){
644
		return false;
645 da17d77e Ermal Lu?i
		$fout = fopen("{$g['tmp_path']}/codetocheck.php","w");
646 3076becf Scott Ullrich
		$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 0c8c496e Scott Ullrich
		fclose($fout);
653 da17d77e Ermal Lu?i
		$command = "/usr/local/bin/php -l {$g['tmp_path']}/codetocheck.php";
654 3076becf Scott Ullrich
		$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 0c8c496e Scott Ullrich
		}
663
	}
664 3076becf Scott Ullrich
}
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 873c1701 Renato Botelho
		$command = "/usr/local/bin/php -l " . escapeshellarg($code_to_check);
673 3076becf Scott Ullrich
		$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 6613a031 Scott Ullrich
				}
703 3076becf Scott Ullrich
				closedir($dir);
704
				rmdir($workingdir);
705
			} elseif (is_file($workingdir)) {
706
				unlink($workingdir);
707
			}
708 5fa78adc Renato Botelho
		}
709 3076becf Scott Ullrich
	}
710
	return;
711
}
712
713
/*
714 f5e09d92 Chris Buechler
 * call_pfsense_method(): Call a method exposed by the pfsense.org XMLRPC server.
715 3076becf Scott Ullrich
 */
716
function call_pfsense_method($method, $params, $timeout = 0) {
717 cfceefc6 Scott Ullrich
	global $g, $config;
718
719 7c8f3711 jim-p
	$xmlrpc_base_url = get_active_xml_rpc_base_url();
720 3076becf Scott Ullrich
	$xmlrpc_path = $g['xmlrpcpath'];
721 1b92cc61 Chris Buechler
	
722
	$xmlrpcfqdn = preg_replace("(https?://)", "", $xmlrpc_base_url);
723
	$ip = gethostbyname($xmlrpcfqdn);
724
	if($ip == $xmlrpcfqdn)
725
		return false;
726
727 3076becf Scott Ullrich
	$msg = new XML_RPC_Message($method, array(XML_RPC_Encode($params)));
728 42c07003 Ermal
	$port = 0;
729
	$proxyurl = "";
730
	$proxyport = 0;
731
	$proxyuser = "";
732
	$proxypass = "";
733 aa3c4866 Ermal
	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 42c07003 Ermal
	$cli = new XML_RPC_Client($xmlrpc_path, $xmlrpc_base_url, $port, $proxyurl, $proxyport, $proxyuser, $proxypass);
742 16348c36 Scott Ullrich
	// If the ALT PKG Repo has a username/password set, use it.
743 5fa78adc Renato Botelho
	if($config['system']['altpkgrepo']['username'] &&
744 16348c36 Scott Ullrich
	   $config['system']['altpkgrepo']['password']) {
745
		$username = $config['system']['altpkgrepo']['username'];
746
		$password = $config['system']['altpkgrepo']['password'];
747
		$cli->setCredentials($username, $password);
748
	}
749 3076becf Scott Ullrich
	$resp = $cli->send($msg, $timeout);
750 2addd5b2 Ermal
	if(!is_object($resp)) {
751 7d1b238c Carlos Eduardo Ramos
		log_error(sprintf(gettext("XMLRPC communication error: %s"), $cli->errstr));
752 3076becf Scott Ullrich
		return false;
753
	} elseif($resp->faultCode()) {
754 addc0439 Renato Botelho
		log_error(sprintf(gettext('XMLRPC request failed with error %1$s: %2$s'), $resp->faultCode(), $resp->faultString()));
755 3076becf Scott Ullrich
		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 1b92cc61 Chris Buechler
	
767 7c8f3711 jim-p
	$xmlrpc_base_url = get_active_xml_rpc_base_url();
768 1b92cc61 Chris Buechler
	$xmlrpcfqdn = preg_replace("(https?://)", "", $xmlrpc_base_url);
769
	$ip = gethostbyname($xmlrpcfqdn);
770
	if($ip == $xmlrpcfqdn)
771 3076becf Scott Ullrich
		return false;
772 a02fa5ec Ermal
	$version = php_uname('r');
773
	$version = explode('-', $version);
774 3076becf Scott Ullrich
	$rawparams = array("firmware" => array("version" => trim(file_get_contents('/etc/version'))),
775 a02fa5ec Ermal
		"kernel"   => array("version" => $version[0]),
776
		"base"     => array("version" => $version[0]),
777 d064a115 Ermal
		"platform" => trim(file_get_contents('/etc/platform')),
778
		"config_version" => $config['version']
779 3076becf Scott Ullrich
		);
780 a02fa5ec Ermal
	unset($version);
781
782 3076becf Scott Ullrich
	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 d064a115 Ermal
	if($config['system']['firmware']['branch'])
791 3076becf Scott Ullrich
		$params['branch'] = $config['system']['firmware']['branch'];
792 d064a115 Ermal
793
	/* XXX: What is this method? */
794
	if(!($versions = call_pfsense_method('pfsense.get_firmware_version', $params))) {
795 3076becf Scott Ullrich
		return false;
796
	} else {
797
		$versions["current"] = $params;
798
	}
799 d064a115 Ermal
800 3076becf Scott Ullrich
	return $versions;
801
}
802
803 e501de37 Ermal
/*
804
 * host_firmware_version(): Return the versions used in this install
805
 */
806 18be996d Ermal
function host_firmware_version($tocheck = "") {
807 5fa78adc Renato Botelho
	global $g, $config;
808 e501de37 Ermal
809 02406801 jim-p
	$os_version = trim(substr(php_uname("r"), 0, strpos(php_uname("r"), '-')));
810
811 5fa78adc Renato Botelho
	return array(
812 e501de37 Ermal
		"firmware" => array("version" => trim(file_get_contents('/etc/version', " \n"))),
813 02406801 jim-p
		"kernel"   => array("version" => $os_version),
814
		"base"     => array("version" => $os_version),
815 5fa78adc Renato Botelho
		"platform" => trim(file_get_contents('/etc/platform', " \n")),
816
		"config_version" => $config['version']
817
	);
818 e501de37 Ermal
}
819
820 3076becf Scott Ullrich
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 c0836064 Ermal Luçi
	global $config, $g;
852 3076becf Scott Ullrich
853 c0836064 Ermal Luçi
	if($g['debug'])
854 7d1b238c Carlos Eduardo Ramos
		log_error(gettext("reload_interfaces_sync() is starting."));
855 3076becf Scott Ullrich
856
	/* parse config.xml again */
857
	$config = parse_config(true);
858
859 a5d6f60b Ermal Lu?i
	/* enable routing */
860
	system_routing_enable();
861
	if($g['debug'])
862 7d1b238c Carlos Eduardo Ramos
		log_error(gettext("Enabling system routing"));
863 3076becf Scott Ullrich
864 c0836064 Ermal Luçi
	if($g['debug'])
865 7d1b238c Carlos Eduardo Ramos
		log_error(gettext("Cleaning up Interfaces"));
866 3076becf Scott Ullrich
867 67ee1ec5 Ermal Luçi
	/* set up interfaces */
868
	interfaces_configure();
869 3076becf Scott Ullrich
}
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 0ae6daf8 Ermal
	send_event("service reload all");
881 3076becf Scott Ullrich
}
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 5e3a84e2 Ermal
	send_event("interface all reload");
893 3076becf Scott Ullrich
}
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
	/* parse config.xml again */
907
	$config = parse_config(true);
908
909
	/* set up our timezone */
910
	system_timezone_configure();
911
912
	/* set up our hostname */
913
	system_hostname_configure();
914
915
	/* make hosts file */
916
	system_hosts_generate();
917
918
	/* generate resolv.conf */
919
	system_resolvconf_generate();
920
921
	/* enable routing */
922
	system_routing_enable();
923
924 a5d6f60b Ermal Lu?i
	/* set up interfaces */
925
	interfaces_configure();
926 3076becf Scott Ullrich
927
	/* start dyndns service */
928
	services_dyndns_configure();
929
930
	/* configure cron service */
931
	configure_cron();
932
933
	/* start the NTP client */
934
	system_ntp_configure();
935
936
	/* sync pw database */
937
	conf_mount_rw();
938 6b0c5879 Scott Ullrich
	unlink_if_exists("/etc/spwd.db.tmp");
939 3076becf Scott Ullrich
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
940
	conf_mount_ro();
941
942
	/* restart sshd */
943 0ae6daf8 Ermal
	send_event("service restart sshd");
944 3076becf Scott Ullrich
945
	/* restart webConfigurator if needed */
946 0ae6daf8 Ermal
	send_event("service restart webgui");
947 3076becf Scott Ullrich
}
948
949 196d0085 jim-p
function setup_serial_port($when="save", $path="") {
950 3076becf Scott Ullrich
	global $g, $config;
951
	conf_mount_rw();
952 c07cd2ce Renato Botelho
	$ttys_file = "{$path}/etc/ttys";
953 196d0085 jim-p
	$boot_config_file = "{$path}/boot.config";
954
	$loader_conf_file = "{$path}/boot/loader.conf";
955 3076becf Scott Ullrich
	/* serial console - write out /boot.config */
956 196d0085 jim-p
	if(file_exists($boot_config_file))
957
		$boot_config = file_get_contents($boot_config_file);
958 3076becf Scott Ullrich
	else
959
		$boot_config = "";
960
961 4887afa1 Renato Botelho
	$serialspeed = (is_numeric($config['system']['serialspeed'])) ? $config['system']['serialspeed'] : "115200";
962 38c7d42e Renato Botelho
	if ($g['platform'] != "cdrom") {
963 cfbfd941 smos
		$boot_config_split = explode("\n", $boot_config);
964 196d0085 jim-p
		$fd = fopen($boot_config_file,"w");
965 3076becf Scott Ullrich
		if($fd) {
966
			foreach($boot_config_split as $bcs) {
967 38c7d42e Renato Botelho
				if(stristr($bcs, "-D") || stristr($bcs, "-h")) {
968 3076becf Scott Ullrich
					/* DONT WRITE OUT, WE'LL DO IT LATER */
969
				} else {
970
					if($bcs <> "")
971
						fwrite($fd, "{$bcs}\n");
972
				}
973 0c8c496e Scott Ullrich
			}
974 38c7d42e Renato Botelho
			if (($g['platform'] == "nanobsd") && !file_exists("/etc/nano_use_vga.txt"))
975
				fwrite($fd, "-S{$serialspeed} -h");
976
			else if (is_serial_enabled())
977 4887afa1 Renato Botelho
				fwrite($fd, "-S{$serialspeed} -D");
978 3076becf Scott Ullrich
			fclose($fd);
979 0c8c496e Scott Ullrich
		}
980 38c7d42e Renato Botelho
981 3076becf Scott Ullrich
		/* serial console - write out /boot/loader.conf */
982 baef6be8 jim-p
		if ($when == "upgrade")
983
			system("echo \"Reading {$loader_conf_file}...\" >> /conf/upgrade_log.txt");
984 196d0085 jim-p
		$boot_config = file_get_contents($loader_conf_file);
985 5f36c658 jim-p
		$boot_config_split = explode("\n", $boot_config);
986
		if(count($boot_config_split) > 0) {
987
			$new_boot_config = array();
988
			// Loop through and only add lines that are not empty, and which
989
			//  do not contain a console directive.
990
			foreach($boot_config_split as $bcs)
991 c1becc31 jim-p
				if(!empty($bcs)
992
					&& (stripos($bcs, "console") === false)
993
					&& (stripos($bcs, "boot_multicons") === false)
994 48126e25 Renato Botelho
					&& (stripos($bcs, "boot_serial") === false)
995
					&& (stripos($bcs, "hw.usb.no_pf") === false))
996 5f36c658 jim-p
					$new_boot_config[] = $bcs;
997
998 38c7d42e Renato Botelho
			if (($g['platform'] == "nanobsd") && !file_exists("/etc/nano_use_vga.txt")) {
999
				$new_boot_config[] = 'boot_serial="YES"';
1000
				$new_boot_config[] = 'console="comconsole"';
1001
			} else if (is_serial_enabled()) {
1002 c1becc31 jim-p
				$new_boot_config[] = 'boot_multicons="YES"';
1003
				$new_boot_config[] = 'boot_serial="YES"';
1004 bf4e62ac jim-p
				$primaryconsole = isset($g['primaryconsole_force']) ? $g['primaryconsole_force'] : $config['system']['primaryconsole'];
1005
				switch ($primaryconsole) {
1006
					case "video":
1007
						$new_boot_config[] = 'console="vidconsole,comconsole"';
1008
						break;
1009
					case "serial":
1010
					default:
1011
						$new_boot_config[] = 'console="comconsole,vidconsole"';
1012
				}
1013 c1becc31 jim-p
			}
1014 4887afa1 Renato Botelho
			$new_boot_config[] = 'comconsole_speed="' . $serialspeed . '"';
1015 25c088de Renato Botelho
			$new_boot_config[] = 'hw.usb.no_pf="1"';
1016
1017 196d0085 jim-p
			file_put_contents($loader_conf_file, implode("\n", $new_boot_config) . "\n");
1018 0c8c496e Scott Ullrich
		}
1019
	}
1020 c07cd2ce Renato Botelho
	$ttys = file_get_contents($ttys_file);
1021 cfbfd941 smos
	$ttys_split = explode("\n", $ttys);
1022 c07cd2ce Renato Botelho
	$fd = fopen($ttys_file, "w");
1023 c5f9fb72 Renato Botelho
1024 ca127ab7 Renato Botelho
	$on_off = (is_serial_enabled() ? 'onifconsole' : 'off');
1025 c5f9fb72 Renato Botelho
1026 edb4b657 Renato Botelho
	if (isset($config['system']['disableconsolemenu'])) {
1027
		$console_type = 'Pc';
1028
		$serial_type = 'std.' . $serialspeed;
1029
	} else {
1030
		$console_type = 'al.Pc';
1031
		$serial_type = 'al.' . $serialspeed;
1032
	}
1033 3076becf Scott Ullrich
	foreach($ttys_split as $tty) {
1034 edb4b657 Renato Botelho
		if (stristr($tty, "ttyv0"))
1035 d4b1e549 Renato Botelho
			fwrite($fd, "ttyv0	\"/usr/libexec/getty {$console_type}\"	cons25	on	secure\n");
1036 ca127ab7 Renato Botelho
		else if (stristr($tty, "ttyu")) {
1037
			$ttyn = substr($tty, 0, 5);
1038
			fwrite($fd, "{$ttyn}	\"/usr/libexec/getty {$serial_type}\"	cons25	{$on_off}	secure\n");
1039
		} else
1040 3076becf Scott Ullrich
			fwrite($fd, $tty . "\n");
1041
	}
1042 edb4b657 Renato Botelho
	unset($on_off, $console_type, $serial_type);
1043 3076becf Scott Ullrich
	fclose($fd);
1044 c07cd2ce Renato Botelho
	if ($when != "upgrade")
1045
		reload_ttys();
1046 a46e450c Ermal Lu?i
1047 3076becf Scott Ullrich
	conf_mount_ro();
1048
	return;
1049
}
1050
1051 38c7d42e Renato Botelho
function is_serial_enabled() {
1052
	global $g, $config;
1053
1054
	if (!isset($g['enableserial_force']) &&
1055
	    !isset($config['system']['enableserial']) &&
1056
	    ($g['platform'] == "pfSense" || $g['platform'] == "cdrom" || file_exists("/etc/nano_use_vga.txt")))
1057
		return false;
1058
1059
	return true;
1060
}
1061
1062 edb4b657 Renato Botelho
function reload_ttys() {
1063
	// Send a HUP signal to init will make it reload /etc/ttys
1064
	posix_kill(1, SIGHUP);
1065
}
1066
1067 3076becf Scott Ullrich
function print_value_list($list, $count = 10, $separator = ",") {
1068
	$list = implode($separator, array_slice($list, 0, $count));
1069
	if(count($list) < $count) {
1070
		$list .= ".";
1071
	} else {
1072
		$list .= "...";
1073
	}
1074
	return $list;
1075
}
1076
1077 bfe776f0 Ermal Luçi
/* DHCP enabled on any interfaces? */
1078 abdd01f5 Ermal
function is_dhcp_server_enabled() {
1079 db9fabf3 Ermal Luçi
	global $config;
1080 bfe776f0 Ermal Luçi
1081 a6610d82 smos
	if (!is_array($config['dhcpd']))
1082 bfe776f0 Ermal Luçi
		return false;
1083
1084 abdd01f5 Ermal
	foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf) {
1085
		if (isset($dhcpifconf['enable']) && !empty($config['interfaces'][$dhcpif]))
1086
			return true;
1087 3076becf Scott Ullrich
	}
1088 bfe776f0 Ermal Luçi
1089 abdd01f5 Ermal
	return false;
1090 a6610d82 smos
}
1091
1092
/* DHCP enabled on any interfaces? */
1093 abdd01f5 Ermal
function is_dhcpv6_server_enabled() {
1094 a6610d82 smos
	global $config;
1095
1096 abdd01f5 Ermal
	if (is_array($config['interfaces'])) {
1097
		foreach ($config['interfaces'] as $ifcfg) {
1098 7a04cd20 Ermal
			if (isset($ifcfg['enable']) && !empty($ifcfg['track6-interface']))
1099 abdd01f5 Ermal
				return true;
1100 a6610d82 smos
		}
1101
	}
1102
1103
	if (!is_array($config['dhcpdv6']))
1104
		return false;
1105
1106 abdd01f5 Ermal
	foreach ($config['dhcpdv6'] as $dhcpv6if => $dhcpv6ifconf) {
1107 ab873ccd Ermal
		if (isset($dhcpv6ifconf['enable']) && !empty($config['interfaces'][$dhcpv6if]))
1108 abdd01f5 Ermal
			return true;
1109 65b1e7d5 Seth Mos
	}
1110
1111 abdd01f5 Ermal
	return false;
1112 3076becf Scott Ullrich
}
1113
1114 0ed8d746 bcyrill
/* radvd enabled on any interfaces? */
1115
function is_radvd_enabled() {
1116
	global $config;
1117
1118
	if (!is_array($config['dhcpdv6']))
1119
		$config['dhcpdv6'] = array();
1120
1121
	$dhcpdv6cfg = $config['dhcpdv6'];
1122
	$Iflist = get_configured_interface_list();
1123
1124
	/* handle manually configured DHCP6 server settings first */
1125
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1126
		if(!isset($config['interfaces'][$dhcpv6if]['enable']))
1127
			continue;
1128
1129
		if(!isset($dhcpv6ifconf['ramode']))
1130
			$dhcpv6ifconf['ramode'] = $dhcpv6ifconf['mode'];
1131
1132
		if($dhcpv6ifconf['ramode'] == "disabled")
1133
			continue;
1134
1135
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1136
		if(!is_ipaddrv6($ifcfgipv6))
1137
			continue;
1138
1139
		return true;
1140
	}
1141
1142
	/* handle DHCP-PD prefixes and 6RD dynamic interfaces */
1143
	foreach ($Iflist as $if => $ifdescr) {
1144
		if(!isset($config['interfaces'][$if]['track6-interface']))
1145
			continue;
1146
		if(!isset($config['interfaces'][$if]['enable']))
1147
			continue;
1148
1149
		$ifcfgipv6 = get_interface_ipv6($if);
1150
		if(!is_ipaddrv6($ifcfgipv6))
1151
			continue;
1152
1153
		$ifcfgsnv6 = get_interface_subnetv6($if);
1154
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1155
1156
		if(!is_ipaddrv6($subnetv6))
1157
			continue;
1158
1159
		return true;
1160
	}
1161
1162
	return false;
1163
}
1164
1165 93c2c1e6 jim-p
/* Any PPPoE servers enabled? */
1166
function is_pppoe_server_enabled() {
1167
	global $config;
1168
1169
	$pppoeenable = false;
1170
1171
	if (!is_array($config['pppoes']) || !is_array($config['pppoes']['pppoe']))
1172
		return false;
1173
1174
	foreach ($config['pppoes']['pppoe'] as $pppoes)
1175
		if ($pppoes['mode'] == 'server')
1176
			$pppoeenable = true;
1177
1178
	return $pppoeenable;
1179
}
1180
1181 9ebe7028 gnhb
function convert_seconds_to_hms($sec){
1182 63292199 gnhb
	$min=$hrs=0;
1183 9ebe7028 gnhb
	if ($sec != 0){
1184
		$min = floor($sec/60);
1185
		$sec %= 60;
1186
	}
1187
	if ($min != 0){
1188
		$hrs = floor($min/60);
1189
		$min %= 60;
1190
	}
1191
	if ($sec < 10)
1192
		$sec = "0".$sec;
1193
	if ($min < 10)
1194
		$min = "0".$min;
1195
	if ($hrs < 10)
1196
		$hrs = "0".$hrs;
1197
	$result = $hrs.":".$min.":".$sec;
1198
	return $result;
1199
}
1200 8eb2f33a Scott Ullrich
1201 63292199 gnhb
/* Compute the total uptime from the ppp uptime log file in the conf directory */
1202
1203
function get_ppp_uptime($port){
1204
	if (file_exists("/conf/{$port}.log")){
1205 5fa78adc Renato Botelho
		$saved_time = file_get_contents("/conf/{$port}.log");
1206
		$uptime_data = explode("\n",$saved_time);
1207 63292199 gnhb
		$sec=0;
1208
		foreach($uptime_data as $upt) {
1209
			$sec += substr($upt, 1 + strpos($upt, " "));
1210 5fa78adc Renato Botelho
		}
1211 63292199 gnhb
		return convert_seconds_to_hms($sec);
1212
	} else {
1213 7d1b238c Carlos Eduardo Ramos
		$total_time = gettext("No history data found!");
1214 63292199 gnhb
		return $total_time;
1215
	}
1216
}
1217 8eb2f33a Scott Ullrich
1218 6189988d Scott Dale
//returns interface information
1219
function get_interface_info($ifdescr) {
1220 cffe41cb Ermal
	global $config, $g;
1221 6189988d Scott Dale
1222
	$ifinfo = array();
1223 cffe41cb Ermal
	if (empty($config['interfaces'][$ifdescr]))
1224 67ee1ec5 Ermal Luçi
		return;
1225 ebdbdbc2 gnhb
	$ifinfo['hwif'] = $config['interfaces'][$ifdescr]['if'];
1226 cffe41cb Ermal
	$ifinfo['if'] = get_real_interface($ifdescr);
1227 6189988d Scott Dale
1228 cb074893 Ermal Lu?i
	$chkif = $ifinfo['if'];
1229
	$ifinfotmp = pfSense_get_interface_addresses($chkif);
1230
	$ifinfo['status'] = $ifinfotmp['status'];
1231 cffe41cb Ermal
	if (empty($ifinfo['status']))
1232 5fa78adc Renato Botelho
		$ifinfo['status'] = "down";
1233 cb074893 Ermal Lu?i
	$ifinfo['macaddr'] = $ifinfotmp['macaddr'];
1234 2d2e466c Ermal LUÇI
	$ifinfo['mtu'] = $ifinfotmp['mtu'];
1235 cb074893 Ermal Lu?i
	$ifinfo['ipaddr'] = $ifinfotmp['ipaddr'];
1236
	$ifinfo['subnet'] = $ifinfotmp['subnet'];
1237 58418355 smos
	$ifinfo['linklocal'] = get_interface_linklocal($ifdescr);
1238 15cc0894 Seth Mos
	$ifinfo['ipaddrv6'] = get_interface_ipv6($ifdescr);
1239
	$ifinfo['subnetv6'] = get_interface_subnetv6($ifdescr);
1240 a216a03a gnhb
	if (isset($ifinfotmp['link0']))
1241 cb074893 Ermal Lu?i
		$link0 = "down";
1242 cffe41cb Ermal
	$ifinfotmp = pfSense_get_interface_stats($chkif);
1243 5fa78adc Renato Botelho
	// $ifinfo['inpkts'] = $ifinfotmp['inpkts'];
1244
	// $ifinfo['outpkts'] = $ifinfotmp['outpkts'];
1245
	$ifinfo['inerrs'] = $ifinfotmp['inerrs'];
1246
	$ifinfo['outerrs'] = $ifinfotmp['outerrs'];
1247
	$ifinfo['collisions'] = $ifinfotmp['collisions'];
1248 6189988d Scott Dale
1249 01385b0c Scott Ullrich
	/* Use pfctl for non wrapping 64 bit counters */
1250 b5a8483c Seth Mos
	/* Pass */
1251 cb074893 Ermal Lu?i
	exec("/sbin/pfctl -vvsI -i {$chkif}", $pfctlstats);
1252 971eaab5 Seth Mos
	$pf_in4_pass = preg_split("/ +/ ", $pfctlstats[3]);
1253
	$pf_out4_pass = preg_split("/ +/", $pfctlstats[5]);
1254 15cc0894 Seth Mos
	$pf_in6_pass = preg_split("/ +/ ", $pfctlstats[7]);
1255
	$pf_out6_pass = preg_split("/ +/", $pfctlstats[9]);
1256 971eaab5 Seth Mos
	$in4_pass = $pf_in4_pass[5];
1257
	$out4_pass = $pf_out4_pass[5];
1258
	$in4_pass_packets = $pf_in4_pass[3];
1259
	$out4_pass_packets = $pf_out4_pass[3];
1260 15cc0894 Seth Mos
	$in6_pass = $pf_in6_pass[5];
1261
	$out6_pass = $pf_out6_pass[5];
1262
	$in6_pass_packets = $pf_in6_pass[3];
1263
	$out6_pass_packets = $pf_out6_pass[3];
1264
	$ifinfo['inbytespass'] = $in4_pass + $in6_pass;
1265
	$ifinfo['outbytespass'] = $out4_pass + $out6_pass;
1266
	$ifinfo['inpktspass'] = $in4_pass_packets + $in6_pass_packets;
1267 4bdfa5dd Phil Davis
	$ifinfo['outpktspass'] = $out4_pass_packets + $out6_pass_packets;
1268 01385b0c Scott Ullrich
1269 971eaab5 Seth Mos
	/* Block */
1270
	$pf_in4_block = preg_split("/ +/", $pfctlstats[4]);
1271
	$pf_out4_block = preg_split("/ +/", $pfctlstats[6]);
1272 15cc0894 Seth Mos
	$pf_in6_block = preg_split("/ +/", $pfctlstats[8]);
1273
	$pf_out6_block = preg_split("/ +/", $pfctlstats[10]);
1274 971eaab5 Seth Mos
	$in4_block = $pf_in4_block[5];
1275
	$out4_block = $pf_out4_block[5];
1276
	$in4_block_packets = $pf_in4_block[3];
1277
	$out4_block_packets = $pf_out4_block[3];
1278 15cc0894 Seth Mos
	$in6_block = $pf_in6_block[5];
1279
	$out6_block = $pf_out6_block[5];
1280
	$in6_block_packets = $pf_in6_block[3];
1281
	$out6_block_packets = $pf_out6_block[3];
1282
	$ifinfo['inbytesblock'] = $in4_block + $in6_block;
1283
	$ifinfo['outbytesblock'] = $out4_block + $out6_block;
1284
	$ifinfo['inpktsblock'] = $in4_block_packets + $in6_block_packets;
1285
	$ifinfo['outpktsblock'] = $out4_block_packets + $out6_block_packets;
1286
1287
	$ifinfo['inbytes'] = $in4_pass + $in6_pass;
1288
	$ifinfo['outbytes'] = $out4_pass + $out6_pass;
1289
	$ifinfo['inpkts'] = $in4_pass_packets + $in6_pass_packets;
1290 4bdfa5dd Phil Davis
	$ifinfo['outpkts'] = $out4_pass_packets + $out6_pass_packets;
1291 5fa78adc Renato Botelho
1292 63161b3f Ermal Luçi
	$ifconfiginfo = "";
1293 59db783a gnhb
	$link_type = $config['interfaces'][$ifdescr]['ipaddr'];
1294
	switch ($link_type) {
1295 5fa78adc Renato Botelho
	/* DHCP? -> see if dhclient is up */
1296 67ee1ec5 Ermal Luçi
	case "dhcp":
1297 20c79427 Ermal Lu?i
		/* see if dhclient is up */
1298 397e40d5 Renato Botelho
		if (find_dhclient_process($ifinfo['if']) != 0)
1299 20c79427 Ermal Lu?i
			$ifinfo['dhcplink'] = "up";
1300
		else
1301
			$ifinfo['dhcplink'] = "down";
1302 63161b3f Ermal Luçi
1303 67ee1ec5 Ermal Luçi
		break;
1304 febca7e8 Ermal
	/* PPPoE/PPTP/L2TP interface? -> get status from virtual interface */
1305 67ee1ec5 Ermal Luçi
	case "pppoe":
1306 febca7e8 Ermal
	case "pptp":
1307
	case "l2tp":
1308 cffe41cb Ermal
		if ($ifinfo['status'] == "up" && !isset($link0))
1309 59db783a gnhb
			/* get PPPoE link status for dial on demand */
1310 febca7e8 Ermal
			$ifinfo["{$link_type}link"] = "up";
1311 20c79427 Ermal Lu?i
		else
1312 febca7e8 Ermal
			$ifinfo["{$link_type}link"] = "down";
1313 6189988d Scott Dale
1314 67ee1ec5 Ermal Luçi
		break;
1315 8eb2f33a Scott Ullrich
	/* PPP interface? -> get uptime for this session and cumulative uptime from the persistant log file in conf */
1316 9ebe7028 gnhb
	case "ppp":
1317 cffe41cb Ermal
		if ($ifinfo['status'] == "up")
1318 c90f2471 gnhb
			$ifinfo['ppplink'] = "up";
1319
		else
1320
			$ifinfo['ppplink'] = "down" ;
1321
1322
		if (empty($ifinfo['status']))
1323
			$ifinfo['status'] = "down";
1324 5fa78adc Renato Botelho
1325 badbe349 gnhb
		if (is_array($config['ppps']['ppp']) && count($config['ppps']['ppp'])) {
1326
			foreach ($config['ppps']['ppp'] as $pppid => $ppp) {
1327 f7480829 gnhb
				if ($config['interfaces'][$ifdescr]['if'] == $ppp['if'])
1328 badbe349 gnhb
					break;
1329
			}
1330
		}
1331 42809b4a gnhb
		$dev = $ppp['ports'];
1332 f7480829 gnhb
		if ($config['interfaces'][$ifdescr]['if'] != $ppp['if'] || empty($dev))
1333 611ae852 Ermal
			break;
1334 59db783a gnhb
		if (!file_exists($dev)) {
1335 c90f2471 gnhb
			$ifinfo['nodevice'] = 1;
1336 5fa78adc Renato Botelho
			$ifinfo['pppinfo'] = $dev . " " . gettext("device not present! Is the modem attached to the system?");
1337 611ae852 Ermal
		}
1338 5e589685 smos
1339 4adf752c smos
		$usbmodemoutput = array();
1340
		exec("usbconfig", $usbmodemoutput);
1341 852171dd smos
		$mondev = "{$g['tmp_path']}/3gstats.{$ifdescr}";
1342 5e589685 smos
		if(file_exists($mondev)) {
1343
			$cellstats = file($mondev);
1344 d23e157a smos
			/* skip header */
1345 5e589685 smos
			$a_cellstats = explode(",", $cellstats[1]);
1346 4adf752c smos
			if(preg_match("/huawei/i", implode("\n", $usbmodemoutput))) {
1347
				$ifinfo['cell_rssi'] = huawei_rssi_to_string($a_cellstats[1]);
1348
				$ifinfo['cell_mode'] = huawei_mode_to_string($a_cellstats[2], $a_cellstats[3]);
1349
				$ifinfo['cell_simstate'] = huawei_simstate_to_string($a_cellstats[10]);
1350
				$ifinfo['cell_service'] = huawei_service_to_string(trim($a_cellstats[11]));
1351
			}
1352
			if(preg_match("/zte/i", implode("\n", $usbmodemoutput))) {
1353
				$ifinfo['cell_rssi'] = zte_rssi_to_string($a_cellstats[1]);
1354
				$ifinfo['cell_mode'] = zte_mode_to_string($a_cellstats[2], $a_cellstats[3]);
1355
				$ifinfo['cell_simstate'] = zte_simstate_to_string($a_cellstats[10]);
1356
				$ifinfo['cell_service'] = zte_service_to_string(trim($a_cellstats[11]));
1357
			}
1358 d23e157a smos
			$ifinfo['cell_upstream'] = $a_cellstats[4];
1359
			$ifinfo['cell_downstream'] = trim($a_cellstats[5]);
1360
			$ifinfo['cell_sent'] = $a_cellstats[6];
1361
			$ifinfo['cell_received'] = trim($a_cellstats[7]);
1362
			$ifinfo['cell_bwupstream'] = $a_cellstats[8];
1363
			$ifinfo['cell_bwdownstream'] = trim($a_cellstats[9]);
1364 5e589685 smos
		}
1365 611ae852 Ermal
		// Calculate cumulative uptime for PPP link. Useful for connections that have per minute/hour contracts so you don't go over!
1366 59db783a gnhb
		if (isset($ppp['uptime']))
1367
			$ifinfo['ppp_uptime_accumulated'] = "(".get_ppp_uptime($ifinfo['if']).")";
1368 67ee1ec5 Ermal Luçi
		break;
1369 63161b3f Ermal Luçi
	default:
1370
		break;
1371 6189988d Scott Dale
	}
1372 5fa78adc Renato Botelho
1373 59db783a gnhb
	if (file_exists("{$g['varrun_path']}/{$link_type}_{$ifdescr}.pid")) {
1374
		$sec = trim(`/usr/local/sbin/ppp-uptime.sh {$ifinfo['if']}`);
1375
		$ifinfo['ppp_uptime'] = convert_seconds_to_hms($sec);
1376
	}
1377 5fa78adc Renato Botelho
1378 6189988d Scott Dale
	if ($ifinfo['status'] == "up") {
1379
		/* try to determine media with ifconfig */
1380
		unset($ifconfiginfo);
1381 818a6b7d Seth Mos
		exec("/sbin/ifconfig " . $ifinfo['if'], $ifconfiginfo);
1382
		$wifconfiginfo = array();
1383
		if(is_interface_wireless($ifdescr)) {
1384
			exec("/sbin/ifconfig {$ifinfo['if']} list sta", $wifconfiginfo);
1385
			array_shift($wifconfiginfo);
1386
		}
1387 6189988d Scott Dale
		$matches = "";
1388
		foreach ($ifconfiginfo as $ici) {
1389
1390
			/* don't list media/speed for wireless cards, as it always
1391
			   displays 2 Mbps even though clients can connect at 11 Mbps */
1392
			if (preg_match("/media: .*? \((.*?)\)/", $ici, $matches)) {
1393
				$ifinfo['media'] = $matches[1];
1394
			} else if (preg_match("/media: Ethernet (.*)/", $ici, $matches)) {
1395
				$ifinfo['media'] = $matches[1];
1396
			} else if (preg_match("/media: IEEE 802.11 Wireless Ethernet (.*)/", $ici, $matches)) {
1397
				$ifinfo['media'] = $matches[1];
1398
			}
1399
1400
			if (preg_match("/status: (.*)$/", $ici, $matches)) {
1401
				if ($matches[1] != "active")
1402
					$ifinfo['status'] = $matches[1];
1403 7d1b238c Carlos Eduardo Ramos
				if($ifinfo['status'] == gettext("running"))
1404
					$ifinfo['status'] = gettext("up");
1405 6189988d Scott Dale
			}
1406
			if (preg_match("/channel (\S*)/", $ici, $matches)) {
1407
				$ifinfo['channel'] = $matches[1];
1408
			}
1409
			if (preg_match("/ssid (\".*?\"|\S*)/", $ici, $matches)) {
1410
				if ($matches[1][0] == '"')
1411
					$ifinfo['ssid'] = substr($matches[1], 1, -1);
1412
				else
1413
					$ifinfo['ssid'] = $matches[1];
1414
			}
1415 0b29093b jim-p
			if (preg_match("/laggproto (.*)$/", $ici, $matches)) {
1416
				$ifinfo['laggproto'] = $matches[1];
1417
			}
1418
			if (preg_match("/laggport: (.*)$/", $ici, $matches)) {
1419
				$ifinfo['laggport'][] = $matches[1];
1420
			}
1421 6189988d Scott Dale
		}
1422 818a6b7d Seth Mos
		foreach($wifconfiginfo as $ici) {
1423
			$elements = preg_split("/[ ]+/i", $ici);
1424
			if ($elements[0] != "") {
1425
				$ifinfo['bssid'] = $elements[0];
1426
			}
1427
			if ($elements[3] != "") {
1428
				$ifinfo['rate'] = $elements[3];
1429
			}
1430
			if ($elements[4] != "") {
1431
				$ifinfo['rssi'] = $elements[4];
1432
			}
1433
1434
		}
1435 67ee1ec5 Ermal Luçi
		/* lookup the gateway */
1436 2bbb79cb Seth Mos
		if (interface_has_gateway($ifdescr)) {
1437 ebdbdbc2 gnhb
			$ifinfo['gateway'] = get_interface_gateway($ifdescr);
1438 2bbb79cb Seth Mos
			$ifinfo['gatewayv6'] = get_interface_gateway_v6($ifdescr);
1439
		}
1440 6189988d Scott Dale
	}
1441
1442
	$bridge = "";
1443 7ec05d27 Ermal Luçi
	$bridge = link_interface_to_bridge($ifdescr);
1444 6189988d Scott Dale
	if($bridge) {
1445
		$bridge_text = `/sbin/ifconfig {$bridge}`;
1446
		if(stristr($bridge_text, "blocking") <> false) {
1447 7d1b238c Carlos Eduardo Ramos
			$ifinfo['bridge'] = "<b><font color='red'>" . gettext("blocking") . "</font></b> - " . gettext("check for ethernet loops");
1448 6189988d Scott Dale
			$ifinfo['bridgeint'] = $bridge;
1449
		} else if(stristr($bridge_text, "learning") <> false) {
1450 7d1b238c Carlos Eduardo Ramos
			$ifinfo['bridge'] = gettext("learning");
1451 6189988d Scott Dale
			$ifinfo['bridgeint'] = $bridge;
1452
		} else if(stristr($bridge_text, "forwarding") <> false) {
1453 7d1b238c Carlos Eduardo Ramos
			$ifinfo['bridge'] = gettext("forwarding");
1454 6189988d Scott Dale
			$ifinfo['bridgeint'] = $bridge;
1455
		}
1456
	}
1457
1458
	return $ifinfo;
1459
}
1460
1461
//returns cpu speed of processor. Good for determining capabilities of machine
1462
function get_cpu_speed() {
1463 971de1f9 Renato Botelho
	return get_single_sysctl("hw.clockrate");
1464 6189988d Scott Dale
}
1465 fab7ff44 Bill Marquette
1466 df0cb10b Phil Davis
function get_uptime_sec() {
1467
	$boottime = "";
1468
	$matches = "";
1469 971de1f9 Renato Botelho
	$boottime = get_single_sysctl("kern.boottime");
1470
	preg_match("/sec = (\d+)/", $boottime, $matches);
1471 df0cb10b Phil Davis
	$boottime = $matches[1];
1472
	if(intval($boottime) == 0)
1473
		return 0;
1474
1475
	$uptime = time() - $boottime;
1476
	return $uptime;
1477
}
1478
1479 a5f94f14 Scott Ullrich
function add_hostname_to_watch($hostname) {
1480 c941ea1c Seth Mos
	if(!is_dir("/var/db/dnscache")) {
1481
		mkdir("/var/db/dnscache");
1482
	}
1483 2d0c5e3e Renato Botelho
	$result = array();
1484 5f31bf01 Seth Mos
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1485 581e772e Seth Mos
		$domrecords = array();
1486
		$domips = array();
1487 873c1701 Renato Botelho
		exec("host -t A " . escapeshellarg($hostname), $domrecords, $rethost);
1488 581e772e Seth Mos
		if($rethost == 0) {
1489
			foreach($domrecords as $domr) {
1490
				$doml = explode(" ", $domr);
1491
				$domip = $doml[3];
1492
				/* fill array with domain ip addresses */
1493
				if(is_ipaddr($domip)) {
1494
					$domips[] = $domip;
1495
				}
1496
			}
1497
		}
1498
		sort($domips);
1499
		$contents = "";
1500
		if(! empty($domips)) {
1501 162c059e Seth Mos
			foreach($domips as $ip) {
1502
				$contents .= "$ip\n";
1503
			}
1504 581e772e Seth Mos
		}
1505
		file_put_contents("/var/db/dnscache/$hostname", $contents);
1506 aa57f965 Renato Botelho
		/* Remove empty elements */
1507
		$result = array_filter(explode("\n", $contents), 'strlen');
1508 a5f94f14 Scott Ullrich
	}
1509 2d0c5e3e Renato Botelho
	return $result;
1510 a5f94f14 Scott Ullrich
}
1511
1512 5ed54b93 Seth Mos
function is_fqdn($fqdn) {
1513
	$hostname = false;
1514
	if(preg_match("/[-A-Z0-9\.]+\.[-A-Z0-9\.]+/i", $fqdn)) {
1515
		$hostname = true;
1516
	}
1517
	if(preg_match("/\.\./", $fqdn)) {
1518
		$hostname = false;
1519
	}
1520 5fa78adc Renato Botelho
	if(preg_match("/^\./i", $fqdn)) {
1521 5ed54b93 Seth Mos
		$hostname = false;
1522
	}
1523 c941ea1c Seth Mos
	if(preg_match("/\//i", $fqdn)) {
1524
		$hostname = false;
1525
	}
1526 5ed54b93 Seth Mos
	return($hostname);
1527
}
1528
1529 639aaa95 Bill Marquette
function pfsense_default_state_size() {
1530 5fa78adc Renato Botelho
	/* get system memory amount */
1531
	$memory = get_memory();
1532 386758bb Phil Davis
	$physmem = $memory[0];
1533 5fa78adc Renato Botelho
	/* Be cautious and only allocate 10% of system memory to the state table */
1534 386758bb Phil Davis
	$max_states = (int) ($physmem/10)*1000;
1535 5fa78adc Renato Botelho
	return $max_states;
1536 639aaa95 Bill Marquette
}
1537
1538 84aea606 jim-p
function pfsense_default_tables_size() {
1539
	$current = `pfctl -sm | grep ^tables | awk '{print $4};'`;
1540
	return $current;
1541
}
1542
1543 fb586a16 jim-p
function pfsense_default_table_entries_size() {
1544
	$current = `pfctl -sm | grep table-entries | awk '{print $4};'`;
1545
	return $current;
1546
}
1547
1548 7723c7e0 Seth Mos
/* Compare the current hostname DNS to the DNS cache we made
1549
 * if it has changed we return the old records
1550 046b8ba6 Renato Botelho
 * if no change we return false */
1551 7723c7e0 Seth Mos
function compare_hostname_to_dnscache($hostname) {
1552
	if(!is_dir("/var/db/dnscache")) {
1553
		mkdir("/var/db/dnscache");
1554
	}
1555
	$hostname = trim($hostname);
1556
	if(is_readable("/var/db/dnscache/{$hostname}")) {
1557
		$oldcontents = file_get_contents("/var/db/dnscache/{$hostname}");
1558
	} else {
1559
		$oldcontents = "";
1560
	}
1561
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1562
		$domrecords = array();
1563
		$domips = array();
1564 873c1701 Renato Botelho
		exec("host -t A " . escapeshellarg($hostname), $domrecords, $rethost);
1565 7723c7e0 Seth Mos
		if($rethost == 0) {
1566
			foreach($domrecords as $domr) {
1567
				$doml = explode(" ", $domr);
1568
				$domip = $doml[3];
1569
				/* fill array with domain ip addresses */
1570
				if(is_ipaddr($domip)) {
1571
					$domips[] = $domip;
1572
				}
1573
			}
1574
		}
1575
		sort($domips);
1576
		$contents = "";
1577
		if(! empty($domips)) {
1578
			foreach($domips as $ip) {
1579
				$contents .= "$ip\n";
1580
			}
1581
		}
1582
	}
1583
1584
	if(trim($oldcontents) != trim($contents)) {
1585 a5f91ef4 Seth Mos
		if($g['debug']) {
1586 addc0439 Renato Botelho
			log_error(sprintf(gettext('DNSCACHE: Found old IP %1$s and new IP %2$s'), $oldcontents, $contents));
1587 a5f91ef4 Seth Mos
		}
1588 7723c7e0 Seth Mos
		return ($oldcontents);
1589
	} else {
1590
		return false;
1591
	}
1592
}
1593
1594 09f18f59 jim-p
/*
1595 7530177c jim-p
 * load_crypto() - Load crypto modules if enabled in config.
1596 09f18f59 jim-p
 */
1597 7530177c jim-p
function load_crypto() {
1598 09f18f59 jim-p
	global $config, $g;
1599 7530177c jim-p
	$crypto_modules = array('glxsb', 'aesni');
1600
1601
	if (!in_array($config['system']['crypto_hardware'], $crypto_modules))
1602
		return false;
1603
1604 3d74b803 jim-p
	if (!empty($config['system']['crypto_hardware']) && !is_module_loaded($config['system']['crypto_hardware'])) {
1605 7530177c jim-p
		log_error("Loading {$config['system']['crypto_hardware']} cryptographic accelerator module.");
1606
		mwexec("/sbin/kldload {$config['system']['crypto_hardware']}");
1607 09f18f59 jim-p
	}
1608
}
1609
1610 f60156f6 jim-p
/*
1611
 * load_thermal_hardware() - Load temperature monitor kernel module
1612
 */
1613
function load_thermal_hardware() {
1614
	global $config, $g;
1615
	$thermal_hardware_modules = array('coretemp', 'amdtemp');
1616
1617
	if (!in_array($config['system']['thermal_hardware'], $thermal_hardware_modules))
1618
		return false;
1619
1620 3d74b803 jim-p
	if (!empty($config['system']['thermal_hardware']) && !is_module_loaded($config['system']['thermal_hardware'])) {
1621 f60156f6 jim-p
		log_error("Loading {$config['system']['thermal_hardware']} thermal monitor module.");
1622
		mwexec("/sbin/kldload {$config['system']['thermal_hardware']}");
1623
	}
1624
}
1625
1626 cde4f5d3 Scott Ullrich
/****f* pfsense-utils/isvm
1627
 * NAME
1628
 *   isvm
1629
 * INPUTS
1630 c96e71d1 Renato Botelho
 *	none
1631 cde4f5d3 Scott Ullrich
 * RESULT
1632
 *   returns true if machine is running under a virtual environment
1633
 ******/
1634
function isvm() {
1635
	$virtualenvs = array("vmware", "parallels", "qemu", "bochs", "plex86");
1636 928dc66a Ermal
	$bios_product = trim(`/bin/kenv smbios.system.product`);
1637 58897b8c Warren Baker
	foreach ($virtualenvs as $virtualenv)
1638
		if (stripos($bios_product, $virtualenv) !== false)
1639
			return true;
1640
1641
	return false;
1642 cde4f5d3 Scott Ullrich
}
1643
1644 e0d0eb71 Scott Ullrich
function get_freebsd_version() {
1645 54597012 Renato Botelho
	$version = explode(".", php_uname("r"));
1646
	return $version[0];
1647 e0d0eb71 Scott Ullrich
}
1648
1649 ffd7802a Renato Botelho
function download_file($url, $destination, $verify_ssl = false, $connect_timeout = 60, $timeout = 0) {
1650
	global $config, $g;
1651
1652
	$fp = fopen($destination, "wb");
1653
1654
	if (!$fp)
1655
		return false;
1656
1657
	$ch = curl_init();
1658
	curl_setopt($ch, CURLOPT_URL, $url);
1659
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $verify_ssl);
1660
	curl_setopt($ch, CURLOPT_FILE, $fp);
1661
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connect_timeout);
1662
	curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1663
	curl_setopt($ch, CURLOPT_HEADER, false);
1664
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1665
	curl_setopt($ch, CURLOPT_USERAGENT, $g['product_name'] . '/' . rtrim(file_get_contents("/etc/version")));
1666
1667
	if (!empty($config['system']['proxyurl'])) {
1668
		curl_setopt($ch, CURLOPT_PROXY, $config['system']['proxyurl']);
1669
		if (!empty($config['system']['proxyport']))
1670
			curl_setopt($ch, CURLOPT_PROXYPORT, $config['system']['proxyport']);
1671
		if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
1672
			@curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY | CURLAUTH_ANYSAFE);
1673
			curl_setopt($ch, CURLOPT_PROXYUSERPWD, "{$config['system']['proxyuser']}:{$config['system']['proxypass']}");
1674
		}
1675
	}
1676
1677
	@curl_exec($ch);
1678
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1679
	fclose($fp);
1680
	curl_close($ch);
1681
	return ($http_code == 200) ? true : $http_code;
1682
}
1683
1684 d164643a jim-p
function download_file_with_progress_bar($url_file, $destination_file, $readbody = 'read_body', $connect_timeout=60, $timeout=0) {
1685 5fa78adc Renato Botelho
	global $ch, $fout, $file_size, $downloaded, $config, $first_progress_update;
1686
	$file_size  = 1;
1687
	$downloaded = 1;
1688 e961bd67 phildd
	$first_progress_update = TRUE;
1689 5fa78adc Renato Botelho
	/* open destination file */
1690
	$fout = fopen($destination_file, "wb");
1691
1692
	/*
1693
	 *      Originally by Author: Keyvan Minoukadeh
1694
	 *      Modified by Scott Ullrich to return Content-Length size
1695
	 */
1696
1697
	$ch = curl_init();
1698
	curl_setopt($ch, CURLOPT_URL, $url_file);
1699
	curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
1700
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1701
	/* Don't verify SSL peers since we don't have the certificates to do so. */
1702
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1703
	curl_setopt($ch, CURLOPT_WRITEFUNCTION, $readbody);
1704
	curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
1705
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connect_timeout);
1706
	curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1707 0ae4f3fa Manuel Silvoso
	curl_setopt($ch, CURLOPT_USERAGENT, $g['product_name'] . '/' . rtrim(file_get_contents("/etc/version")));
1708 b31da21e Scott Ullrich
1709 42c07003 Ermal
	if (!empty($config['system']['proxyurl'])) {
1710
		curl_setopt($ch, CURLOPT_PROXY, $config['system']['proxyurl']);
1711
		if (!empty($config['system']['proxyport']))
1712
			curl_setopt($ch, CURLOPT_PROXYPORT, $config['system']['proxyport']);
1713
		if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
1714
			@curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY | CURLAUTH_ANYSAFE);
1715 2a57a4d1 Ermal
			curl_setopt($ch, CURLOPT_PROXYUSERPWD, "{$config['system']['proxyuser']}:{$config['system']['proxypass']}");
1716 42c07003 Ermal
		}
1717
	}
1718
1719 5fa78adc Renato Botelho
	@curl_exec($ch);
1720
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1721
	if($fout)
1722
		fclose($fout);
1723
	curl_close($ch);
1724
	return ($http_code == 200) ? true : $http_code;
1725 b31da21e Scott Ullrich
}
1726
1727
function read_header($ch, $string) {
1728 5fa78adc Renato Botelho
	global $file_size, $fout;
1729
	$length = strlen($string);
1730
	$regs = "";
1731
	preg_match("/(Content-Length:) (.*)/", $string, $regs);
1732
	if($regs[2] <> "") {
1733
		$file_size = intval($regs[2]);
1734
	}
1735
	ob_flush();
1736
	return $length;
1737 b31da21e Scott Ullrich
}
1738
1739
function read_body($ch, $string) {
1740 5fa78adc Renato Botelho
	global $fout, $file_size, $downloaded, $sendto, $static_status, $static_output, $lastseen, $first_progress_update;
1741
	global $pkg_interface;
1742
	$length = strlen($string);
1743
	$downloaded += intval($length);
1744
	if($file_size > 0) {
1745
		$downloadProgress = round(100 * (1 - $downloaded / $file_size), 0);
1746
		$downloadProgress = 100 - $downloadProgress;
1747
	} else
1748
		$downloadProgress = 0;
1749
	if($lastseen <> $downloadProgress and $downloadProgress < 101) {
1750
		if($sendto == "status") {
1751 03b2cab6 Ermal
			if($pkg_interface == "console") {
1752 2a315bee Phil Davis
				if(($downloadProgress % 10) == 0 || $downloadProgress < 10) {
1753 03b2cab6 Ermal
					$tostatus = $static_status . $downloadProgress . "%";
1754 2a315bee Phil Davis
					if ($downloadProgress == 100) {
1755 a3da8f50 Ermal
						$tostatus = $tostatus . "\r";
1756 2a315bee Phil Davis
					}
1757 03b2cab6 Ermal
					update_status($tostatus);
1758
				}
1759
			} else {
1760
				$tostatus = $static_status . $downloadProgress . "%";
1761 5fa78adc Renato Botelho
				update_status($tostatus);
1762 03b2cab6 Ermal
			}
1763 5fa78adc Renato Botelho
		} else {
1764 03b2cab6 Ermal
			if($pkg_interface == "console") {
1765 2a315bee Phil Davis
				if(($downloadProgress % 10) == 0 || $downloadProgress < 10) {
1766 03b2cab6 Ermal
					$tooutput = $static_output . $downloadProgress . "%";
1767 2a315bee Phil Davis
					if ($downloadProgress == 100) {
1768 a3da8f50 Ermal
						$tooutput = $tooutput . "\r";
1769 2a315bee Phil Davis
					}
1770 03b2cab6 Ermal
					update_output_window($tooutput);
1771
				}
1772
			} else {
1773
				$tooutput = $static_output . $downloadProgress . "%";
1774
				update_output_window($tooutput);
1775
			}
1776 5fa78adc Renato Botelho
		}
1777 82acb8b3 Phil Davis
				if(($pkg_interface != "console") || (($downloadProgress % 10) == 0) || ($downloadProgress < 10)) {
1778 e961bd67 phildd
					update_progress_bar($downloadProgress, $first_progress_update);
1779
					$first_progress_update = FALSE;
1780 82acb8b3 Phil Davis
				}
1781 5fa78adc Renato Botelho
		$lastseen = $downloadProgress;
1782
	}
1783
	if($fout)
1784
		fwrite($fout, $string);
1785
	ob_flush();
1786
	return $length;
1787 b31da21e Scott Ullrich
}
1788
1789 84677257 Scott Ullrich
/*
1790
 *   update_output_window: update bottom textarea dynamically.
1791
 */
1792
function update_output_window($text) {
1793 5fa78adc Renato Botelho
	global $pkg_interface;
1794
	$log = preg_replace("/\n/", "\\n", $text);
1795
	if($pkg_interface != "console") {
1796 6e4e6286 Colin Fleming
		echo "\n<script type=\"text/javascript\">";
1797
		echo "\n//<![CDATA[";
1798
		echo "\nthis.document.forms[0].output.value = \"" . $log . "\";";
1799
		echo "\nthis.document.forms[0].output.scrollTop = this.document.forms[0].output.scrollHeight;";
1800
		echo "\n//]]>";
1801
		echo "\n</script>";
1802 5fa78adc Renato Botelho
	}
1803
	/* ensure that contents are written out */
1804
	ob_flush();
1805 84677257 Scott Ullrich
}
1806
1807
/*
1808 82acb8b3 Phil Davis
 *   update_status: update top textarea dynamically.
1809 84677257 Scott Ullrich
 */
1810
function update_status($status) {
1811 5fa78adc Renato Botelho
	global $pkg_interface;
1812
	if($pkg_interface == "console") {
1813
		echo "\r{$status}";
1814
	} else {
1815 6e4e6286 Colin Fleming
		echo "\n<script type=\"text/javascript\">";
1816
		echo "\n//<![CDATA[";
1817
		echo "\nthis.document.forms[0].status.value=\"" . $status . "\";";
1818
		echo "\n//]]>";
1819
		echo "\n</script>";
1820 5fa78adc Renato Botelho
	}
1821
	/* ensure that contents are written out */
1822
	ob_flush();
1823 84677257 Scott Ullrich
}
1824
1825
/*
1826 e961bd67 phildd
 * update_progress_bar($percent, $first_time): updates the javascript driven progress bar.
1827 84677257 Scott Ullrich
 */
1828 e961bd67 phildd
function update_progress_bar($percent, $first_time) {
1829 5fa78adc Renato Botelho
	global $pkg_interface;
1830
	if($percent > 100) $percent = 1;
1831
	if($pkg_interface <> "console") {
1832 6e4e6286 Colin Fleming
		echo "\n<script type=\"text/javascript\">";
1833
		echo "\n//<![CDATA[";
1834 5fa78adc Renato Botelho
		echo "\ndocument.progressbar.style.width='" . $percent . "%';";
1835 6e4e6286 Colin Fleming
		echo "\n//]]>";
1836 5fa78adc Renato Botelho
		echo "\n</script>";
1837
	} else {
1838 e961bd67 phildd
		if(!($first_time))
1839
			echo "\x08\x08\x08\x08\x08";
1840
		echo sprintf("%4d%%", $percent);
1841 5fa78adc Renato Botelho
	}
1842 84677257 Scott Ullrich
}
1843
1844 f5d637bc Scott Ullrich
/* 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. */
1845
if(!function_exists("split")) {
1846 5aa68a55 Renato Botelho
	function split($separator, $haystack, $limit = null) {
1847
		log_error("deprecated split() call with separator '{$separator}'");
1848
		return preg_split($separator, $haystack, $limit);
1849 f5d637bc Scott Ullrich
	}
1850
}
1851
1852 f1ac1733 Erik Fonnesbeck
function update_alias_names_upon_change($section, $field, $new_alias_name, $origname) {
1853 978fd2e8 Scott Ullrich
	global $g, $config, $pconfig, $debug;
1854 5fa78adc Renato Botelho
	if(!$origname)
1855 b6db8ea3 sullrich
		return;
1856
1857 f1ac1733 Erik Fonnesbeck
	$sectionref = &$config;
1858
	foreach($section as $sectionname) {
1859
		if(is_array($sectionref) && isset($sectionref[$sectionname]))
1860
			$sectionref = &$sectionref[$sectionname];
1861
		else
1862
			return;
1863
	}
1864
1865 b6db8ea3 sullrich
	if($debug) $fd = fopen("{$g['tmp_path']}/print_r", "a");
1866
	if($debug) fwrite($fd, print_r($pconfig, true));
1867
1868 f1ac1733 Erik Fonnesbeck
	if(is_array($sectionref)) {
1869
		foreach($sectionref as $itemkey => $item) {
1870
			if($debug) fwrite($fd, "$itemkey\n");
1871
1872
			$fieldfound = true;
1873
			$fieldref = &$sectionref[$itemkey];
1874
			foreach($field as $fieldname) {
1875
				if(is_array($fieldref) && isset($fieldref[$fieldname]))
1876
					$fieldref = &$fieldref[$fieldname];
1877
				else {
1878
					$fieldfound = false;
1879
					break;
1880
				}
1881 b6db8ea3 sullrich
			}
1882 f1ac1733 Erik Fonnesbeck
			if($fieldfound && $fieldref == $origname) {
1883 b6db8ea3 sullrich
				if($debug) fwrite($fd, "Setting old alias value $origname to $new_alias_name\n");
1884 f1ac1733 Erik Fonnesbeck
				$fieldref = $new_alias_name;
1885 b6db8ea3 sullrich
			}
1886
		}
1887
	}
1888
1889
	if($debug) fclose($fd);
1890
1891
}
1892 f6ba4bd1 Scott Ullrich
1893 7c1c70d5 Renato Botelho
function parse_aliases_file($filename, $type = "url", $max_items = -1) {
1894
	/*
1895
	 * $filename = file to process for example blocklist like DROP:  http://www.spamhaus.org/drop/drop.txt
1896
	 * $type = if set to 'url' then subnets and ips will be returned,
1897
	 *         if set to 'url_ports' port-ranges and ports will be returned
1898
	 * $max_items = sets the maximum amount of valid items to load, -1 the default defines there is no limit.
1899
	 *
1900
	 * RETURNS an array of ip subnets and ip's or ports and port-ranges, returns NULL upon a error conditions (file not found)
1901
	 */
1902
1903
	$fd = @fopen($filename, 'r');
1904
	if (!$fd) {
1905
		log_error(gettext("Could not process aliases from alias: {$alias_url}"));
1906
		return null;
1907
	}
1908
	$items = array();
1909
	/* NOTE: fgetss() is not a typo RTFM before being smart */
1910
	while (($fc = fgetss($fd)) !== FALSE) {
1911
		$tmp = trim($fc, " \t\n\r");
1912
		if (empty($tmp))
1913
			continue;
1914
		$tmp_str = strstr($tmp, '#', true);
1915
		if (!empty($tmp_str))
1916
			$tmp = $tmp_str;
1917
		$tmp_str = strstr($tmp, ' ', true);
1918
		if (!empty($tmp_str))
1919
			$tmp = $tmp_str;
1920
		$valid = ($type == "url" && (is_ipaddr($tmp) || is_subnet($tmp))) ||
1921
		         ($type == "url_ports" && (is_port($tmp) || is_portrange($tmp)));
1922
		if ($valid) {
1923
			$items[] = $tmp;
1924
			if (count($items) == $max_items)
1925
				break;
1926
		}
1927
	}
1928
	fclose($fd);
1929
	return $items;
1930
}
1931
1932 f6ba4bd1 Scott Ullrich
function update_alias_url_data() {
1933
	global $config, $g;
1934 e5953c68 Ermal
1935 8422cdd5 Ermal
	$updated = false;
1936
1937 f6ba4bd1 Scott Ullrich
	/* item is a url type */
1938 8422cdd5 Ermal
	$lockkey = lock('aliasurl');
1939 e5953c68 Ermal
	if (is_array($config['aliases']['alias'])) {
1940
		foreach ($config['aliases']['alias'] as $x => $alias) {
1941
			if (empty($alias['aliasurl']))
1942
				continue;
1943
1944 7c1c70d5 Renato Botelho
			$address = null;
1945 2ef16014 bcyrill
			foreach ($alias['aliasurl'] as $alias_url) {
1946
				/* fetch down and add in */
1947
				$temp_filename = tempnam("{$g['tmp_path']}/", "alias_import");
1948
				unlink($temp_filename);
1949 76590ffe Renato Botelho
				$verify_ssl = isset($config['system']['checkaliasesurlcert']);
1950 873c1701 Renato Botelho
				mkdir($temp_filename);
1951 76590ffe Renato Botelho
				download_file($alias_url, $temp_filename . "/aliases", $verify_ssl);
1952
1953 2ef16014 bcyrill
				/* if the item is tar gzipped then extract */
1954 e45bae34 Ermal
				if (stripos($alias_url, '.tgz')) {
1955
					if (!process_alias_tgz($temp_filename))
1956
						continue;
1957
				} else if (stripos($alias_url, '.zip')) {
1958
					if (!process_alias_unzip($temp_filename))
1959
						continue;
1960
				}
1961 2ef16014 bcyrill
				if (file_exists("{$temp_filename}/aliases")) {
1962 7c1c70d5 Renato Botelho
					$address = parse_aliases_file("{$temp_filename}/aliases", $alias['type'], 3000);
1963 2ef16014 bcyrill
					mwexec("/bin/rm -rf {$temp_filename}");
1964 f6ba4bd1 Scott Ullrich
				}
1965 2ef16014 bcyrill
			}
1966 7c1c70d5 Renato Botelho
			if ($address != null) {
1967
				$config['aliases']['alias'][$x]['address'] = implode(" ", $address);
1968 2ef16014 bcyrill
				$updated = true;
1969 f6ba4bd1 Scott Ullrich
			}
1970
		}
1971
	}
1972 26d060bc Ermal
	unlock($lockkey);
1973 8422cdd5 Ermal
1974
	/* Report status to callers as well */
1975
	return $updated;
1976 f6ba4bd1 Scott Ullrich
}
1977
1978 10189b2a Scott Ullrich
function process_alias_unzip($temp_filename) {
1979 e45bae34 Ermal
	if(!file_exists("/usr/local/bin/unzip")) {
1980
		log_error(gettext("Alias archive is a .zip file which cannot be decompressed because utility is missing!"));
1981
		return false;
1982
	}
1983 873c1701 Renato Botelho
	rename("{$temp_filename}/aliases", "{$temp_filename}/aliases.zip");
1984 10189b2a Scott Ullrich
	mwexec("/usr/local/bin/unzip {$temp_filename}/aliases.tgz -d {$temp_filename}/aliases/");
1985
	unlink("{$temp_filename}/aliases.zip");
1986
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1987
	/* foreach through all extracted files and build up aliases file */
1988 e45bae34 Ermal
	$fd = @fopen("{$temp_filename}/aliases", "w");
1989
	if (!$fd) {
1990
		log_error(gettext("Could not open {$temp_filename}/aliases for writing!"));
1991
		return false;
1992
	}
1993 10189b2a Scott Ullrich
	foreach($files_to_process as $f2p) {
1994 e45bae34 Ermal
		$tmpfd = @fopen($f2p, 'r');
1995
		if (!$tmpfd) {
1996
			log_error(gettext("The following file could not be read {$f2p} from {$temp_filename}"));
1997
			continue;
1998
		}
1999
		while (($tmpbuf = fread($tmpfd, 65536)) !== FALSE)
2000
			fwrite($fd, $tmpbuf);
2001
		fclose($tmpfd);
2002 10189b2a Scott Ullrich
		unlink($f2p);
2003
	}
2004
	fclose($fd);
2005 e45bae34 Ermal
	unset($tmpbuf);
2006
2007
	return true;
2008 10189b2a Scott Ullrich
}
2009
2010 f6ba4bd1 Scott Ullrich
function process_alias_tgz($temp_filename) {
2011 e45bae34 Ermal
	if(!file_exists('/usr/bin/tar')) {
2012
		log_error(gettext("Alias archive is a .tar/tgz file which cannot be decompressed because utility is missing!"));
2013
		return false;
2014
	}
2015 873c1701 Renato Botelho
	rename("{$temp_filename}/aliases", "{$temp_filename}/aliases.tgz");
2016 f6ba4bd1 Scott Ullrich
	mwexec("/usr/bin/tar xzf {$temp_filename}/aliases.tgz -C {$temp_filename}/aliases/");
2017
	unlink("{$temp_filename}/aliases.tgz");
2018
	$files_to_process = return_dir_as_array("{$temp_filename}/");
2019
	/* foreach through all extracted files and build up aliases file */
2020 e45bae34 Ermal
	$fd = @fopen("{$temp_filename}/aliases", "w");
2021
	if (!$fd) {
2022
		log_error(gettext("Could not open {$temp_filename}/aliases for writing!"));
2023
		return false;
2024
	}
2025 f6ba4bd1 Scott Ullrich
	foreach($files_to_process as $f2p) {
2026 e45bae34 Ermal
		$tmpfd = @fopen($f2p, 'r');
2027
		if (!$tmpfd) {
2028
			log_error(gettext("The following file could not be read {$f2p} from {$temp_filename}"));
2029
			continue;
2030
		}
2031
		while (($tmpbuf = fread($tmpfd, 65536)) !== FALSE)
2032
			fwrite($fd, $tmpbuf);
2033
		fclose($tmpfd);
2034 f6ba4bd1 Scott Ullrich
		unlink($f2p);
2035
	}
2036
	fclose($fd);
2037 e45bae34 Ermal
	unset($tmpbuf);
2038
2039
	return true;
2040 f6ba4bd1 Scott Ullrich
}
2041
2042 a76c1c45 jim-p
function version_compare_dates($a, $b) {
2043
	$a_time = strtotime($a);
2044
	$b_time = strtotime($b);
2045
2046
	if ((!$a_time) || (!$b_time)) {
2047
		return FALSE;
2048
	} else {
2049 bda131b2 jim-p
		if ($a_time < $b_time)
2050 a76c1c45 jim-p
			return -1;
2051 ba6a4606 jim-p
		elseif ($a_time == $b_time)
2052 a76c1c45 jim-p
			return 0;
2053
		else
2054
			return 1;
2055
	}
2056
}
2057
function version_get_string_value($a) {
2058
	$strs = array(
2059
		0 => "ALPHA-ALPHA",
2060
		2 => "ALPHA",
2061
		3 => "BETA",
2062
		4 => "B",
2063 5eb03383 jim-p
		5 => "C",
2064
		6 => "D",
2065
		7 => "RC",
2066 f8c8d65c Stilez
		8 => "RELEASE",
2067
		9 => "*"			// Matches all release levels
2068 a76c1c45 jim-p
	);
2069
	$major = 0;
2070
	$minor = 0;
2071
	foreach ($strs as $num => $str) {
2072
		if (substr($a, 0, strlen($str)) == $str) {
2073
			$major = $num;
2074
			$n = substr($a, strlen($str));
2075
			if (is_numeric($n))
2076
				$minor = $n;
2077
			break;
2078
		}
2079
	}
2080
	return "{$major}.{$minor}";
2081
}
2082
function version_compare_string($a, $b) {
2083 f8c8d65c Stilez
	// Only compare string parts if both versions give a specific release
2084
	// (If either version lacks a string part, assume intended to match all release levels)
2085 c96e71d1 Renato Botelho
	if (isset($a) && isset($b))
2086
		return version_compare_numeric(version_get_string_value($a), version_get_string_value($b));
2087
	else
2088
		return 0;
2089 a76c1c45 jim-p
}
2090
function version_compare_numeric($a, $b) {
2091
	$a_arr = explode('.', rtrim($a, '.0'));
2092
	$b_arr = explode('.', rtrim($b, '.0'));
2093
2094
	foreach ($a_arr as $n => $val) {
2095
		if (array_key_exists($n, $b_arr)) {
2096
			// So far so good, both have values at this minor version level. Compare.
2097
			if ($val > $b_arr[$n])
2098
				return 1;
2099
			elseif ($val < $b_arr[$n])
2100
				return -1;
2101
		} else {
2102
			// a is greater, since b doesn't have any minor version here.
2103
			return 1;
2104
		}
2105
	}
2106
	if (count($b_arr) > count($a_arr)) {
2107
		// b is longer than a, so it must be greater.
2108
		return -1;
2109
	} else {
2110
		// Both a and b are of equal length and value.
2111
		return 0;
2112
	}
2113
}
2114
function pfs_version_compare($cur_time, $cur_text, $remote) {
2115
	// First try date compare
2116 bda131b2 jim-p
	$v = version_compare_dates($cur_time, $remote);
2117 a76c1c45 jim-p
	if ($v === FALSE) {
2118
		// If that fails, try to compare by string
2119
		// Before anything else, simply test if the strings are equal
2120 b009b153 jim-p
		if (($cur_text == $remote) || ($cur_time == $remote))
2121 a76c1c45 jim-p
			return 0;
2122
		list($cur_num, $cur_str) = explode('-', $cur_text);
2123
		list($rem_num, $rem_str) = explode('-', $remote);
2124
2125
		// First try to compare the numeric parts of the version string.
2126
		$v = version_compare_numeric($cur_num, $rem_num);
2127
2128
		// If the numeric parts are the same, compare the string parts.
2129
		if ($v == 0)
2130
			return version_compare_string($cur_str, $rem_str);
2131
	}
2132
	return $v;
2133
}
2134 c7de8be4 jim-p
function process_alias_urltable($name, $url, $freq, $forceupdate=false) {
2135 dd042c51 Renato Botelho
	global $config;
2136
2137 c7de8be4 jim-p
	$urltable_prefix = "/var/db/aliastables/";
2138
	$urltable_filename = $urltable_prefix . $name . ".txt";
2139
2140
	// Make the aliases directory if it doesn't exist
2141
	if (!file_exists($urltable_prefix)) {
2142
		mkdir($urltable_prefix);
2143
	} elseif (!is_dir($urltable_prefix)) {
2144
		unlink($urltable_prefix);
2145
		mkdir($urltable_prefix);
2146
	}
2147
2148
	// If the file doesn't exist or is older than update_freq days, fetch a new copy.
2149
	if (!file_exists($urltable_filename)
2150 e09da6c2 Renato Botelho
		|| ((time() - filemtime($urltable_filename)) > ($freq * 86400 - 90))
2151 c7de8be4 jim-p
		|| $forceupdate) {
2152
2153
		// Try to fetch the URL supplied
2154
		conf_mount_rw();
2155
		unlink_if_exists($urltable_filename . ".tmp");
2156 dd042c51 Renato Botelho
		$verify_ssl = isset($config['system']['checkaliasesurlcert']);
2157
		if (download_file($url, $urltable_filename . ".tmp", $verify_ssl)) {
2158
			mwexec("/usr/bin/sed -E 's/\;.*//g; /^[[:space:]]*($|#)/d' ". escapeshellarg($urltable_filename . ".tmp") . " > " . escapeshellarg($urltable_filename));
2159
			if (alias_get_type($name) == "urltable_ports") {
2160
				$ports = explode("\n", file_get_contents($urltable_filename));
2161
				$ports = group_ports($ports);
2162
				file_put_contents($urltable_filename, implode("\n", $ports));
2163
			}
2164 4aa0979f Ermal
			unlink_if_exists($urltable_filename . ".tmp");
2165
		} else
2166 873c1701 Renato Botelho
			touch($urltable_filename);
2167 c7de8be4 jim-p
		conf_mount_ro();
2168 966f359e Ermal
		return true;
2169 c7de8be4 jim-p
	} else {
2170
		// File exists, and it doesn't need updated.
2171
		return -1;
2172
	}
2173
}
2174 08fd5444 jim-p
function get_real_slice_from_glabel($label) {
2175
	$label = escapeshellarg($label);
2176
	return trim(`/sbin/glabel list | /usr/bin/grep -B2 ufs/{$label} | /usr/bin/head -n 1 | /usr/bin/cut -f3 -d' '`);
2177
}
2178
function nanobsd_get_boot_slice() {
2179
	return trim(`/sbin/mount | /usr/bin/grep pfsense | /usr/bin/cut -d'/' -f4 | /usr/bin/cut -d' ' -f1`);
2180
}
2181
function nanobsd_get_boot_drive() {
2182
	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`);
2183
}
2184
function nanobsd_get_active_slice() {
2185
	$boot_drive = nanobsd_get_boot_drive();
2186
	$active = trim(`gpart show $boot_drive | grep '\[active\]' | awk '{print $3;}'`);
2187
2188
	return "{$boot_drive}s{$active}";
2189
}
2190
function nanobsd_get_size() {
2191
	return strtoupper(file_get_contents("/etc/nanosize.txt"));
2192
}
2193 2b5f276f jim-p
function nanobsd_switch_boot_slice() {
2194 08fd5444 jim-p
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2195
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2196
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2197
	nanobsd_detect_slice_info();
2198
2199 2b5f276f jim-p
	if ($BOOTFLASH == $ACTIVE_SLICE) {
2200
		$slice = $TOFLASH;
2201
	} else {
2202
		$slice = $BOOTFLASH;
2203
	}
2204
2205 08fd5444 jim-p
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
2206
	ob_implicit_flush(1);
2207
	if(strstr($slice, "s2")) {
2208
		$ASLICE="2";
2209
		$AOLDSLICE="1";
2210
		$AGLABEL_SLICE="pfsense1";
2211
		$AUFS_ID="1";
2212
		$AOLD_UFS_ID="0";
2213
	} else {
2214
		$ASLICE="1";
2215
		$AOLDSLICE="2";
2216
		$AGLABEL_SLICE="pfsense0";
2217
		$AUFS_ID="0";
2218
		$AOLD_UFS_ID="1";
2219
	}
2220
	$ATOFLASH="{$BOOT_DRIVE}s{$ASLICE}";
2221
	$ACOMPLETE_PATH="{$BOOT_DRIVE}s{$ASLICE}a";
2222
	$ABOOTFLASH="{$BOOT_DRIVE}s{$AOLDSLICE}";
2223
	conf_mount_rw();
2224 971de1f9 Renato Botelho
	set_single_sysctl("kern.geom.debugflags", "16");
2225 08fd5444 jim-p
	exec("gpart set -a active -i {$ASLICE} {$BOOT_DRIVE}");
2226
	exec("/usr/sbin/boot0cfg -s {$ASLICE} -v /dev/{$BOOT_DRIVE}");
2227 2b5f276f jim-p
	// We can't update these if they are mounted now.
2228
	if ($BOOTFLASH != $slice) {
2229
		exec("/sbin/tunefs -L ${AGLABEL_SLICE} /dev/$ACOMPLETE_PATH");
2230
		nanobsd_update_fstab($AGLABEL_SLICE, $ACOMPLETE_PATH, $AOLD_UFS_ID, $AUFS_ID);
2231
	}
2232 971de1f9 Renato Botelho
	set_single_sysctl("kern.geom.debugflags", "0");
2233 08fd5444 jim-p
	conf_mount_ro();
2234
}
2235 2b5f276f jim-p
function nanobsd_clone_slice() {
2236 08fd5444 jim-p
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2237
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2238
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2239
	nanobsd_detect_slice_info();
2240
2241
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
2242
	ob_implicit_flush(1);
2243 971de1f9 Renato Botelho
	set_single_sysctl("kern.geom.debugflags", "16");
2244 08fd5444 jim-p
	exec("/bin/dd if=/dev/zero of=/dev/{$TOFLASH} bs=1m count=1");
2245
	exec("/bin/dd if=/dev/{$BOOTFLASH} of=/dev/{$TOFLASH} bs=64k");
2246
	exec("/sbin/tunefs -L {$GLABEL_SLICE} /dev/{$COMPLETE_PATH}");
2247 2b5f276f jim-p
	$status = nanobsd_update_fstab($GLABEL_SLICE, $COMPLETE_PATH, $OLD_UFS_ID, $UFS_ID);
2248 971de1f9 Renato Botelho
	set_single_sysctl("kern.geom.debugflags", "0");
2249 08fd5444 jim-p
	if($status) {
2250
		return false;
2251
	} else {
2252
		return true;
2253
	}
2254
}
2255 2b5f276f jim-p
function nanobsd_update_fstab($gslice, $complete_path, $oldufs, $newufs) {
2256
	$tmppath = "/tmp/{$gslice}";
2257
	$fstabpath = "/tmp/{$gslice}/etc/fstab";
2258
2259 873c1701 Renato Botelho
	mkdir($tmppath);
2260 2b5f276f jim-p
	exec("/sbin/fsck_ufs -y /dev/{$complete_path}");
2261
	exec("/sbin/mount /dev/ufs/{$gslice} {$tmppath}");
2262 873c1701 Renato Botelho
	copy("/etc/fstab", $fstabpath);
2263 2b5f276f jim-p
2264
	if (!file_exists($fstabpath)) {
2265
		$fstab = <<<EOF
2266 9b1a8d98 Ermal
/dev/ufs/{$gslice} / ufs ro,noatime 1 1
2267
/dev/ufs/cf /cf ufs ro,noatime 1 1
2268 2b5f276f jim-p
EOF;
2269
		if (file_put_contents($fstabpath, $fstab))
2270
			$status = true;
2271
		else
2272
			$status = false;
2273
	} else {
2274
		$status = exec("sed -i \"\" \"s/pfsense{$oldufs}/pfsense{$newufs}/g\" {$fstabpath}");
2275
	}
2276
	exec("/sbin/umount {$tmppath}");
2277 873c1701 Renato Botelho
	rmdir($tmppath);
2278 2b5f276f jim-p
2279
	return $status;
2280
}
2281 08fd5444 jim-p
function nanobsd_detect_slice_info() {
2282
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2283
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2284
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2285 a76c1c45 jim-p
2286 08fd5444 jim-p
	$BOOT_DEVICE=nanobsd_get_boot_slice();
2287
	$REAL_BOOT_DEVICE=get_real_slice_from_glabel($BOOT_DEVICE);
2288
	$BOOT_DRIVE=nanobsd_get_boot_drive();
2289
	$ACTIVE_SLICE=nanobsd_get_active_slice();
2290
2291
	// Detect which slice is active and set information.
2292
	if(strstr($REAL_BOOT_DEVICE, "s1")) {
2293
		$SLICE="2";
2294
		$OLDSLICE="1";
2295
		$GLABEL_SLICE="pfsense1";
2296
		$UFS_ID="1";
2297
		$OLD_UFS_ID="0";
2298 a76c1c45 jim-p
2299 08fd5444 jim-p
	} else {
2300
		$SLICE="1";
2301
		$OLDSLICE="2";
2302
		$GLABEL_SLICE="pfsense0";
2303
		$UFS_ID="0";
2304
		$OLD_UFS_ID="1";
2305
	}
2306
	$TOFLASH="{$BOOT_DRIVE}s{$SLICE}";
2307
	$COMPLETE_PATH="{$BOOT_DRIVE}s{$SLICE}a";
2308
	$COMPLETE_BOOT_PATH="{$BOOT_DRIVE}s{$OLDSLICE}";
2309
	$BOOTFLASH="{$BOOT_DRIVE}s{$OLDSLICE}";
2310
}
2311 38080cc1 Scott Ullrich
2312 26c8cc72 jim-p
function nanobsd_friendly_slice_name($slicename) {
2313
	global $g;
2314
	return strtolower(str_ireplace('pfsense', $g['product_name'], $slicename));
2315
}
2316
2317 38080cc1 Scott Ullrich
function get_include_contents($filename) {
2318 5fa78adc Renato Botelho
	if (is_file($filename)) {
2319
		ob_start();
2320
		include $filename;
2321
		$contents = ob_get_contents();
2322
		ob_end_clean();
2323
		return $contents;
2324
	}
2325
	return false;
2326 38080cc1 Scott Ullrich
}
2327
2328 3ffa8318 Renato Botelho
/* This xml 2 array function is courtesy of the php.net comment section on xml_parse.
2329
 * it is roughly 4 times faster then our existing pfSense parser but due to the large
2330
 * size of the RRD xml dumps this is required.
2331
 * The reason we do not use it for pfSense is that it does not know about array fields
2332
 * which causes it to fail on array fields with single items. Possible Todo?
2333
 */
2334
function xml2array($contents, $get_attributes = 1, $priority = 'tag')
2335
{
2336 86c707f3 Darren Embry
	if (!function_exists('xml_parser_create'))
2337
	{
2338
		return array ();
2339
	}
2340
	$parser = xml_parser_create('');
2341
	xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
2342
	xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
2343
	xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
2344
	xml_parse_into_struct($parser, trim($contents), $xml_values);
2345
	xml_parser_free($parser);
2346
	if (!$xml_values)
2347
		return; //Hmm...
2348
	$xml_array = array ();
2349
	$parents = array ();
2350
	$opened_tags = array ();
2351
	$arr = array ();
2352
	$current = & $xml_array;
2353
	$repeated_tag_index = array ();
2354
	foreach ($xml_values as $data)
2355
	{
2356
		unset ($attributes, $value);
2357
		extract($data);
2358
		$result = array ();
2359
		$attributes_data = array ();
2360
		if (isset ($value))
2361
		{
2362
			if ($priority == 'tag')
2363
				$result = $value;
2364
			else
2365
				$result['value'] = $value;
2366
		}
2367
		if (isset ($attributes) and $get_attributes)
2368
		{
2369
			foreach ($attributes as $attr => $val)
2370
			{
2371
				if ($priority == 'tag')
2372
					$attributes_data[$attr] = $val;
2373
				else
2374
					$result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
2375
			}
2376
		}
2377
		if ($type == "open")
2378
		{
2379
			$parent[$level -1] = & $current;
2380
			if (!is_array($current) or (!in_array($tag, array_keys($current))))
2381
			{
2382
				$current[$tag] = $result;
2383
				if ($attributes_data)
2384
					$current[$tag . '_attr'] = $attributes_data;
2385
				$repeated_tag_index[$tag . '_' . $level] = 1;
2386
				$current = & $current[$tag];
2387
			}
2388
			else
2389
			{
2390
				if (isset ($current[$tag][0]))
2391
				{
2392
					$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
2393
					$repeated_tag_index[$tag . '_' . $level]++;
2394
				}
2395
				else
2396
				{
2397
					$current[$tag] = array (
2398
						$current[$tag],
2399
						$result
2400
						);
2401
					$repeated_tag_index[$tag . '_' . $level] = 2;
2402
					if (isset ($current[$tag . '_attr']))
2403
					{
2404
						$current[$tag]['0_attr'] = $current[$tag . '_attr'];
2405
						unset ($current[$tag . '_attr']);
2406
					}
2407
				}
2408
				$last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
2409
				$current = & $current[$tag][$last_item_index];
2410
			}
2411
		}
2412
		elseif ($type == "complete")
2413
		{
2414
			if (!isset ($current[$tag]))
2415
			{
2416
				$current[$tag] = $result;
2417
				$repeated_tag_index[$tag . '_' . $level] = 1;
2418
				if ($priority == 'tag' and $attributes_data)
2419
					$current[$tag . '_attr'] = $attributes_data;
2420
			}
2421
			else
2422
			{
2423
				if (isset ($current[$tag][0]) and is_array($current[$tag]))
2424
				{
2425
					$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
2426
					if ($priority == 'tag' and $get_attributes and $attributes_data)
2427
					{
2428
						$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
2429
					}
2430
					$repeated_tag_index[$tag . '_' . $level]++;
2431
				}
2432
				else
2433
				{
2434
					$current[$tag] = array (
2435
						$current[$tag],
2436
						$result
2437
						);
2438
					$repeated_tag_index[$tag . '_' . $level] = 1;
2439
					if ($priority == 'tag' and $get_attributes)
2440
					{
2441
						if (isset ($current[$tag . '_attr']))
2442
						{
2443
							$current[$tag]['0_attr'] = $current[$tag . '_attr'];
2444
							unset ($current[$tag . '_attr']);
2445
						}
2446
						if ($attributes_data)
2447
						{
2448
							$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
2449
						}
2450
					}
2451
					$repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
2452
				}
2453
			}
2454
		}
2455
		elseif ($type == 'close')
2456
		{
2457
			$current = & $parent[$level -1];
2458
		}
2459
	}
2460
	return ($xml_array);
2461 3ffa8318 Renato Botelho
}
2462
2463
function get_country_name($country_code) {
2464
	if ($country_code != "ALL" && strlen($country_code) != 2)
2465
		return "";
2466
2467
	$country_names_xml = "/usr/local/share/mobile-broadband-provider-info/iso_3166-1_list_en.xml";
2468
	$country_names_contents = file_get_contents($country_names_xml);
2469
	$country_names = xml2array($country_names_contents);
2470
2471
	if($country_code == "ALL") {
2472
		$country_list = array();
2473
		foreach($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2474 c96e71d1 Renato Botelho
			$country_list[] = array("code" => $country['ISO_3166-1_Alpha-2_Code_element'],
2475
						"name" => ucwords(strtolower($country['ISO_3166-1_Country_name'])) );
2476 3ffa8318 Renato Botelho
		}
2477
		return $country_list;
2478
	}
2479
2480
	foreach ($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2481
		if ($country['ISO_3166-1_Alpha-2_Code_element'] == strtoupper($country_code)) {
2482
			return ucwords(strtolower($country['ISO_3166-1_Country_name']));
2483
		}
2484
	}
2485
	return "";
2486
}
2487
2488 baaa8bb1 Erik Fonnesbeck
/* sort by interface only, retain the original order of rules that apply to
2489
   the same interface */
2490
function filter_rules_sort() {
2491
	global $config;
2492
2493
	/* mark each rule with the sequence number (to retain the order while sorting) */
2494
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2495
		$config['filter']['rule'][$i]['seq'] = $i;
2496
2497
	usort($config['filter']['rule'], "filter_rules_compare");
2498
2499
	/* strip the sequence numbers again */
2500
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2501
		unset($config['filter']['rule'][$i]['seq']);
2502
}
2503
function filter_rules_compare($a, $b) {
2504 cea355a5 Erik Fonnesbeck
	if (isset($a['floating']) && isset($b['floating']))
2505 baaa8bb1 Erik Fonnesbeck
		return $a['seq'] - $b['seq'];
2506
	else if (isset($a['floating']))
2507
		return -1;
2508
	else if (isset($b['floating']))
2509
		return 1;
2510 cea355a5 Erik Fonnesbeck
	else if ($a['interface'] == $b['interface'])
2511
		return $a['seq'] - $b['seq'];
2512 baaa8bb1 Erik Fonnesbeck
	else
2513
		return compare_interface_friendly_names($a['interface'], $b['interface']);
2514
}
2515
2516 22dae853 Seth Mos
function generate_ipv6_from_mac($mac) {
2517
	$elements = explode(":", $mac);
2518
	if(count($elements) <> 6)
2519
		return false;
2520
2521
	$i = 0;
2522 5aa28c86 Seth Mos
	$ipv6 = "fe80::";
2523 22dae853 Seth Mos
	foreach($elements as $byte) {
2524
		if($i == 0) {
2525
			$hexadecimal =  substr($byte, 1, 2);
2526
			$bitmap = base_convert($hexadecimal, 16, 2);
2527
			$bitmap = str_pad($bitmap, 4, "0", STR_PAD_LEFT);
2528
			$bitmap = substr($bitmap, 0, 2) ."1". substr($bitmap, 3,4);
2529
			$byte = substr($byte, 0, 1) . base_convert($bitmap, 2, 16);
2530
		}
2531
		$ipv6 .= $byte;
2532
		if($i == 1) {
2533
			$ipv6 .= ":";
2534
		}
2535
		if($i == 3) {
2536
			$ipv6 .= ":";
2537
		}
2538
		if($i == 2) {
2539
			$ipv6 .= "ff:fe";
2540
		}
2541 5fa78adc Renato Botelho
2542 22dae853 Seth Mos
		$i++;
2543 5fa78adc Renato Botelho
	}
2544 fcdc8943 Seth Mos
	return $ipv6;
2545 22dae853 Seth Mos
}
2546 325e3163 Bill Marquette
2547 57f2840e Evgeny
/****f* pfsense-utils/load_mac_manufacturer_table
2548
 * NAME
2549
 *   load_mac_manufacturer_table
2550
 * INPUTS
2551
 *   none
2552
 * RESULT
2553
 *   returns associative array with MAC-Manufacturer pairs
2554
 ******/
2555
function load_mac_manufacturer_table() {
2556
	/* load MAC-Manufacture data from the file */
2557 62a29fe3 Ermal
	$macs = false;
2558
	if (file_exists("/usr/local/share/nmap/nmap-mac-prefixes"))
2559
		$macs=file("/usr/local/share/nmap/nmap-mac-prefixes");
2560 57f2840e Evgeny
	if ($macs){
2561
		foreach ($macs as $line){
2562
			if (preg_match('/([0-9A-Fa-f]{6}) (.*)$/', $line, $matches)){
2563 4450527f Evgeny
				/* store values like this $mac_man['000C29']='VMware' */
2564 57f2840e Evgeny
				$mac_man["$matches[1]"]=$matches[2];
2565
			}
2566
		}
2567 5fa78adc Renato Botelho
		return $mac_man;
2568 57f2840e Evgeny
	} else
2569
		return -1;
2570
2571
}
2572
2573 474f36d1 Scott Ullrich
/****f* pfsense-utils/is_ipaddr_configured
2574
 * NAME
2575
 *   is_ipaddr_configured
2576
 * INPUTS
2577
 *   IP Address to check.
2578 4665dbdd Renato Botelho
 *   If ignore_if is a VIP (not carp), vip array index is passed after string _virtualip
2579 474f36d1 Scott Ullrich
 * RESULT
2580
 *   returns true if the IP Address is
2581
 *   configured and present on this device.
2582
*/
2583 e6c60013 Renato Botelho
function is_ipaddr_configured($ipaddr, $ignore_if = "", $check_localip = false, $check_subnets = false) {
2584
	global $config;
2585
2586 4665dbdd Renato Botelho
	$pos = strpos($ignore_if, '_virtualip');
2587
	if ($pos !== false) {
2588
		$ignore_vip_id = substr($ignore_if, $pos+10);
2589
		$ignore_vip_if = substr($ignore_if, 0, $pos);
2590
	} else {
2591
		$ignore_vip_id = -1;
2592
		$ignore_vip_if = $ignore_if;
2593
	}
2594
2595 1e5da31d Ermal
	$isipv6 = is_ipaddrv6($ipaddr);
2596
2597 e6c60013 Renato Botelho
	if ($check_subnets) {
2598
		$iflist = get_configured_interface_list();
2599
		foreach ($iflist as $if => $ifname) {
2600
			if ($ignore_if == $if)
2601
				continue;
2602 2c98a935 Renato Botelho
2603 1e5da31d Ermal
			if ($isipv6 === true) {
2604
				$bitmask = get_interface_subnetv6($if);
2605
				$subnet = gen_subnetv6(get_interface_ipv6($if), $bitmask);
2606
			} else {
2607
				$bitmask = get_interface_subnet($if);
2608
				$subnet = gen_subnet(get_interface_ip($if), $bitmask);
2609
			}
2610 2c98a935 Renato Botelho
2611
			if (ip_in_subnet($ipaddr, $subnet . '/' . $bitmask))
2612
				return true;
2613 e6c60013 Renato Botelho
		}
2614
	} else {
2615 2c98a935 Renato Botelho
		if ($isipv6 === true)
2616
			$interface_list_ips = get_configured_ipv6_addresses();
2617
		else
2618
			$interface_list_ips = get_configured_ip_addresses();
2619
2620 e6c60013 Renato Botelho
		foreach($interface_list_ips as $if => $ilips) {
2621 4665dbdd Renato Botelho
			if ($ignore_if == $if)
2622 e6c60013 Renato Botelho
				continue;
2623
			if (strcasecmp($ipaddr, $ilips) == 0)
2624
				return true;
2625
		}
2626 5fa78adc Renato Botelho
	}
2627 a1613b62 Renato Botelho
2628 4021ec36 Renato Botelho
	$interface_list_vips = get_configured_vips_list(true);
2629
	foreach ($interface_list_vips as $id => $vip) {
2630 4665dbdd Renato Botelho
		/* Skip CARP interfaces here since they were already checked above */
2631
		if ($id == $ignore_vip_id || (strstr($ignore_if, '_vip') && $ignore_vip_if == $vip['if']))
2632 4021ec36 Renato Botelho
			continue;
2633
		if (strcasecmp($ipaddr, $vip['ipaddr']) == 0)
2634
			return true;
2635
	}
2636
2637 e6c60013 Renato Botelho
	if ($check_localip) {
2638 a1e4e2a7 Ermal
		if (is_array($config['pptpd']) && !empty($config['pptpd']['localip']) && (strcasecmp($ipaddr, $config['pptpd']['localip']) == 0))
2639 e6c60013 Renato Botelho
			return true;
2640
2641 a1e4e2a7 Ermal
		if (!is_array($config['l2tp']) && !empty($config['l2tp']['localip']) && (strcasecmp($ipaddr, $config['l2tp']['localip']) == 0))
2642 a1613b62 Renato Botelho
			return true;
2643
	}
2644
2645
	return false;
2646 474f36d1 Scott Ullrich
}
2647
2648 e4a8ed97 Scott Ullrich
/****f* pfsense-utils/pfSense_handle_custom_code
2649
 * NAME
2650
 *   pfSense_handle_custom_code
2651
 * INPUTS
2652
 *   directory name to process
2653
 * RESULT
2654
 *   globs the directory and includes the files
2655
 */
2656 d65962a7 Scott Ullrich
function pfSense_handle_custom_code($src_dir) {
2657 5fa78adc Renato Botelho
	// Allow extending of the nat edit page and include custom input validation
2658 d65962a7 Scott Ullrich
	if(is_dir("$src_dir")) {
2659 3dbceb92 Scott Ullrich
		$cf = glob($src_dir . "/*.inc");
2660 d65962a7 Scott Ullrich
		foreach($cf as $nf) {
2661 5fa78adc Renato Botelho
			if($nf == "." || $nf == "..")
2662 d65962a7 Scott Ullrich
				continue;
2663
			// Include the extra handler
2664 3dbceb92 Scott Ullrich
			include("$nf");
2665 d65962a7 Scott Ullrich
		}
2666
	}
2667
}
2668
2669 000a8d1d Renato Botelho
function set_language($lang = 'en_US', $encoding = "UTF-8") {
2670 3e139f90 Vinicius Coque
	putenv("LANG={$lang}.{$encoding}");
2671
	setlocale(LC_ALL, "{$lang}.{$encoding}");
2672
	textdomain("pfSense");
2673 a94c4e1f Vinicius Coque
	bindtextdomain("pfSense","/usr/local/share/locale");
2674 3e139f90 Vinicius Coque
	bind_textdomain_codeset("pfSense","{$lang}.{$encoding}");
2675
}
2676
2677
function get_locale_list() {
2678
	$locales = array(
2679
		"en_US" => gettext("English"),
2680 2e2eb012 Vinicius Coque
		"pt_BR" => gettext("Portuguese (Brazil)"),
2681 f079b676 technical50
		"tr" => gettext("Turkish"),
2682 3e139f90 Vinicius Coque
	);
2683
	asort($locales);
2684
	return $locales;
2685
}
2686 20a7cb15 smos
2687 f079b676 technical50
function system_get_language_code() {
2688
	global $config, $g_languages;
2689
2690
	// a language code, as per [RFC3066]
2691
	$language = $config['system']['language'];
2692
	//$code = $g_languages[$language]['code'];
2693
	$code = str_replace("_", "-", $language);
2694
2695
	if (empty($code))
2696
		$code = "en-US"; // Set default code.
2697
2698
	return $code;
2699
}
2700
2701
function system_get_language_codeset() {
2702
	global $config, $g_languages;
2703
2704
	$language = $config['system']['language'];
2705
	$codeset = $g_languages[$language]['codeset'];
2706
2707
	if (empty($codeset))
2708
		$codeset = "UTF-8"; // Set default codeset.
2709
2710
	return $codeset;
2711
}
2712
2713
/* Available languages/locales */
2714
$g_languages = array (
2715
	"sq"    => array("codeset" => "UTF-8", "desc" => gettext("Albanian")),
2716
	"bg"    => array("codeset" => "UTF-8", "desc" => gettext("Bulgarian")),
2717
	"zh_CN" => array("codeset" => "UTF-8", "desc" => gettext("Chinese (Simplified)")),
2718
	"zh_TW" => array("codeset" => "UTF-8", "desc" => gettext("Chinese (Traditional)")),
2719
	"nl"    => array("codeset" => "UTF-8", "desc" => gettext("Dutch")),
2720
	"da"    => array("codeset" => "UTF-8", "desc" => gettext("Danish")),
2721 000a8d1d Renato Botelho
	"en_US" => array("codeset" => "UTF-8", "desc" => gettext("English")),
2722 f079b676 technical50
	"fi"    => array("codeset" => "UTF-8", "desc" => gettext("Finnish")),
2723
	"fr"    => array("codeset" => "UTF-8", "desc" => gettext("French")),
2724
	"de"    => array("codeset" => "UTF-8", "desc" => gettext("German")),
2725
	"el"    => array("codeset" => "UTF-8", "desc" => gettext("Greek")),
2726
	"hu"    => array("codeset" => "UTF-8", "desc" => gettext("Hungarian")),
2727
	"it"    => array("codeset" => "UTF-8", "desc" => gettext("Italian")),
2728
	"ja"    => array("codeset" => "UTF-8", "desc" => gettext("Japanese")),
2729
	"ko"    => array("codeset" => "UTF-8", "desc" => gettext("Korean")),
2730
	"lv"    => array("codeset" => "UTF-8", "desc" => gettext("Latvian")),
2731
	"nb"    => array("codeset" => "UTF-8", "desc" => gettext("Norwegian (Bokmal)")),
2732
	"pl"    => array("codeset" => "UTF-8", "desc" => gettext("Polish")),
2733
	"pt_BR" => array("codeset" => "ISO-8859-1", "desc" => gettext("Portuguese (Brazil)")),
2734
	"pt"    => array("codeset" => "UTF-8", "desc" => gettext("Portuguese (Portugal)")),
2735
	"ro"    => array("codeset" => "UTF-8", "desc" => gettext("Romanian")),
2736
	"ru"    => array("codeset" => "UTF-8", "desc" => gettext("Russian")),
2737
	"sl"    => array("codeset" => "UTF-8", "desc" => gettext("Slovenian")),
2738
	"tr"    => array("codeset" => "UTF-8", "desc" => gettext("Turkish")),
2739
	"es"    => array("codeset" => "UTF-8", "desc" => gettext("Spanish")),
2740
	"sv"    => array("codeset" => "UTF-8", "desc" => gettext("Swedish")),
2741
	"sk"    => array("codeset" => "UTF-8", "desc" => gettext("Slovak")),
2742
	"cs"    => array("codeset" => "UTF-8", "desc" => gettext("Czech"))
2743
);
2744
2745 20a7cb15 smos
function return_hex_ipv4($ipv4) {
2746
	if(!is_ipaddrv4($ipv4))
2747
		return(false);
2748 5fa78adc Renato Botelho
2749 20a7cb15 smos
	/* we need the hex form of the interface IPv4 address */
2750
	$ip4arr = explode(".", $ipv4);
2751 733c6f89 Ermal
	return (sprintf("%02x%02x%02x%02x", $ip4arr[0], $ip4arr[1], $ip4arr[2], $ip4arr[3]));
2752 20a7cb15 smos
}
2753
2754
function convert_ipv6_to_128bit($ipv6) {
2755
	if(!is_ipaddrv6($ipv6))
2756
		return(false);
2757
2758
	$ip6arr = array();
2759
	$ip6prefix = Net_IPv6::uncompress($ipv6);
2760
	$ip6arr = explode(":", $ip6prefix);
2761
	/* binary presentation of the prefix for all 128 bits. */
2762
	$ip6prefixbin = "";
2763
	foreach($ip6arr as $element) {
2764
		$ip6prefixbin .= sprintf("%016b", hexdec($element));
2765
	}
2766
	return($ip6prefixbin);
2767
}
2768
2769
function convert_128bit_to_ipv6($ip6bin) {
2770
	if(strlen($ip6bin) <> 128)
2771
		return(false);
2772
2773
	$ip6arr = array();
2774
	$ip6binarr = array();
2775
	$ip6binarr = str_split($ip6bin, 16);
2776
	foreach($ip6binarr as $binpart)
2777
		$ip6arr[] = dechex(bindec($binpart));
2778
	$ip6addr = Net_IPv6::compress(implode(":", $ip6arr));
2779
2780
	return($ip6addr);
2781
}
2782
2783 8b198c64 smos
2784
/* Returns the calculated bit length of the prefix delegation from the WAN interface */
2785
/* DHCP-PD is variable, calculate from the prefix-len on the WAN interface */
2786
/* 6rd is variable, calculate from 64 - (v6 prefixlen - (32 - v4 prefixlen)) */
2787
/* 6to4 is 16 bits, e.g. 65535 */
2788
function calculate_ipv6_delegation_length($if) {
2789
	global $config;
2790
2791
	if(!is_array($config['interfaces'][$if]))
2792
		return false;
2793
2794
	switch($config['interfaces'][$if]['ipaddrv6']) {
2795
		case "6to4":
2796
			$pdlen = 16;
2797
			break;
2798
		case "6rd":
2799
			$rd6cfg = $config['interfaces'][$if];
2800
			$rd6plen = explode("/", $rd6cfg['prefix-6rd']);
2801
			$pdlen = (64 - ($rd6plen[1] + (32 - $rd6cfg['prefix-6rd-v4plen'])));
2802
			break;
2803
		case "dhcp6":
2804
			$dhcp6cfg = $config['interfaces'][$if];
2805
			$pdlen = $dhcp6cfg['dhcp6-ia-pd-len'];
2806
			break;
2807
		default:
2808
			$pdlen = 0;
2809
			break;
2810
	}
2811
	return($pdlen);
2812
}
2813 d23e157a smos
2814
function huawei_rssi_to_string($rssi) {
2815
	$dbm = array();
2816
	$i = 0;
2817 145cc518 smos
	$dbstart = -113;
2818
	while($i < 32) {
2819
		$dbm[$i] = $dbstart + ($i * 2);
2820 d23e157a smos
		$i++;
2821
	}
2822
	$percent = round(($rssi / 31) * 100);
2823 145cc518 smos
	$string = "rssi:{$rssi} level:{$dbm[$rssi]}dBm percent:{$percent}%";
2824 d23e157a smos
	return $string;
2825
}
2826
2827
function huawei_mode_to_string($mode, $submode) {
2828
	$modes[0] = "None";
2829 5fa78adc Renato Botelho
	$modes[1] = "AMPS";
2830 d23e157a smos
	$modes[2] = "CDMA";
2831
	$modes[3] = "GSM/GPRS";
2832
	$modes[4] = "HDR";
2833
	$modes[5] = "WCDMA";
2834 5fa78adc Renato Botelho
	$modes[6] = "GPS";
2835 d23e157a smos
2836
	$submodes[0] = "No Service";
2837
	$submodes[1] = "GSM";
2838
	$submodes[2] = "GPRS";
2839
	$submodes[3] = "EDGE";
2840
	$submodes[4] = "WCDMA";
2841
	$submodes[5] = "HSDPA";
2842
	$submodes[6] = "HSUPA";
2843 e313da37 smos
	$submodes[7] = "HSDPA+HSUPA";
2844 d23e157a smos
	$submodes[8] = "TD-SCDMA";
2845
	$submodes[9] = "HSPA+";
2846
	$string = "{$modes[$mode]}, {$submodes[$submode]} Mode";
2847
	return $string;
2848
}
2849
2850
function huawei_service_to_string($state) {
2851
	$modes[0] = "No";
2852 5fa78adc Renato Botelho
	$modes[1] = "Restricted";
2853 d23e157a smos
	$modes[2] = "Valid";
2854
	$modes[3] = "Restricted Regional";
2855
	$modes[4] = "Powersaving";
2856
	$string = "{$modes[$state]} Service";
2857
	return $string;
2858
}
2859
2860
function huawei_simstate_to_string($state) {
2861
	$modes[0] = "Invalid SIM/locked";
2862 5fa78adc Renato Botelho
	$modes[1] = "Valid SIM";
2863 d23e157a smos
	$modes[2] = "Invalid SIM CS";
2864
	$modes[3] = "Invalid SIM PS";
2865
	$modes[4] = "Invalid SIM CS/PS";
2866
	$modes[255] = "Missing SIM";
2867
	$string = "{$modes[$state]} State";
2868
	return $string;
2869
}
2870 4adf752c smos
2871
function zte_rssi_to_string($rssi) {
2872
	return huawei_rssi_to_string($rssi);
2873
}
2874
2875
function zte_mode_to_string($mode, $submode) {
2876
	$modes[0] = "No Service";
2877 5fa78adc Renato Botelho
	$modes[1] = "Limited Service";
2878 4adf752c smos
	$modes[2] = "GPRS";
2879
	$modes[3] = "GSM";
2880
	$modes[4] = "UMTS";
2881
	$modes[5] = "EDGE";
2882 5fa78adc Renato Botelho
	$modes[6] = "HSDPA";
2883 4adf752c smos
2884
	$submodes[0] = "CS_ONLY";
2885
	$submodes[1] = "PS_ONLY";
2886
	$submodes[2] = "CS_PS";
2887
	$submodes[3] = "CAMPED";
2888
	$string = "{$modes[$mode]}, {$submodes[$submode]} Mode";
2889
	return $string;
2890
}
2891
2892
function zte_service_to_string($state) {
2893
	$modes[0] = "Initializing";
2894 5fa78adc Renato Botelho
	$modes[1] = "Network Lock error";
2895 4adf752c smos
	$modes[2] = "Network Locked";
2896
	$modes[3] = "Unlocked or correct MCC/MNC";
2897
	$string = "{$modes[$state]} Service";
2898
	return $string;
2899
}
2900
2901
function zte_simstate_to_string($state) {
2902
	$modes[0] = "No action";
2903 5fa78adc Renato Botelho
	$modes[1] = "Network lock";
2904 4adf752c smos
	$modes[2] = "(U)SIM card lock";
2905
	$modes[3] = "Network Lock and (U)SIM card Lock";
2906
	$string = "{$modes[$state]} State";
2907
	return $string;
2908
}
2909 e9ab2ddb smos
2910
function get_configured_pppoe_server_interfaces() {
2911
	global $config;
2912
	$iflist = array();
2913
	if (is_array($config['pppoes']['pppoe'])) {
2914
		foreach($config['pppoes']['pppoe'] as $pppoe) {
2915
			if ($pppoe['mode'] == "server") {
2916
				$int = "poes". $pppoe['pppoeid'];
2917
				$iflist[$int] = strtoupper($int);
2918
			}
2919
		}
2920
	}
2921
	return $iflist;
2922
}
2923
2924
function get_pppoes_child_interfaces($ifpattern) {
2925
	$if_arr = array();
2926
	if($ifpattern == "")
2927
		return;
2928
2929
	exec("ifconfig", $out, $ret);
2930
	foreach($out as $line) {
2931
		if(preg_match("/^({$ifpattern}[0-9]+):/i", $line, $match)) {
2932
			$if_arr[] = $match[1];
2933
		}
2934
	}
2935
	return $if_arr;
2936
2937
}
2938
2939 331166a8 PiBa-NL
/****f* pfsense-utils/pkg_call_plugins
2940
 * NAME
2941
 *   pkg_call_plugins
2942
 * INPUTS
2943
 *   $plugin_type value used to search in package configuration if the plugin is used, also used to create the function name
2944
 *   $plugin_params parameters to pass to the plugin function for passing multiple parameters a array can be used.
2945
 * RESULT
2946
 *   returns associative array results from the plugin calls for each package
2947
 * NOTES
2948
 *   This generic function can be used to notify or retrieve results from functions that are defined in packages.
2949
 ******/
2950
function pkg_call_plugins($plugin_type, $plugin_params) {
2951 eaee3af6 PiBa-NL
	global $g, $config;
2952
	$results = array();
2953 331166a8 PiBa-NL
	if (!is_array($config['installedpackages']['package']))
2954
		return $results;
2955 eaee3af6 PiBa-NL
	foreach ($config['installedpackages']['package'] as $package) {
2956
		if(!file_exists("/usr/local/pkg/" . $package['configurationfile']))
2957
			continue;
2958
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], 'packagegui');
2959
		$pkgname = substr(reverse_strrchr($package['configurationfile'], "."),0,-1);
2960 3fe73243 PiBa-NL
		if (is_array($pkg_config['plugins']['item']))
2961
			foreach ($pkg_config['plugins']['item'] as $plugin) {
2962 331166a8 PiBa-NL
				if ($plugin['type'] == $plugin_type) {
2963 eaee3af6 PiBa-NL
					if (file_exists($pkg_config['include_file']))
2964
						require_once($pkg_config['include_file']);
2965
					else
2966
						continue;
2967
					$plugin_function = $pkgname . '_'. $plugin_type;
2968
					$results[$pkgname] = @eval($plugin_function($plugin_params));
2969
				}
2970
			}
2971
	}
2972
	return $results;
2973
}
2974
2975 7c8f3711 jim-p
/* Function to find and return the active XML RPC base URL to avoid code duplication */
2976
function get_active_xml_rpc_base_url() {
2977
	global $config, $g;
2978
	/* If the user has activated the option to enable an alternate xmlrpcbaseurl, and it's not empty, then use it */
2979
	if (isset($config['system']['altpkgrepo']['enable']) && !empty($config['system']['altpkgrepo']['xmlrpcbaseurl'])) {
2980
		return $config['system']['altpkgrepo']['xmlrpcbaseurl'];
2981
	} else {
2982
		return $g['xmlrpcbaseurl'];
2983
	}
2984
}
2985
2986 58005e52 jim-p
?>