Project

General

Profile

Download (67.1 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
	pfSense_BUILDER_BINARIES:	/sbin/sysctl	/sbin/ifconfig	/sbin/pfctl	/usr/local/bin/php /usr/bin/netstat
38
	pfSense_BUILDER_BINARIES:	/bin/df	/usr/bin/grep	/usr/bin/awk	/bin/rm	/usr/sbin/pwd_mkdb	/usr/bin/host
39
	pfSense_BUILDER_BINARIES:	/sbin/kldload
40
	pfSense_MODULE:	utils
41
*/
42
43 0397013a Scott Ullrich
/****f* pfsense-utils/have_natonetooneruleint_access
44
 * NAME
45
 *   have_natonetooneruleint_access
46
 * INPUTS
47
 *	 none
48
 * RESULT
49
 *   returns true if user has access to edit a specific firewall nat one to one interface
50
 ******/
51
function have_natonetooneruleint_access($if) {
52
	$security_url = "firewall_nat_1to1_edit.php?if=". strtolower($if);
53 53b30505 sullrich
	if(isAllowedPage($security_url, $_SESSION['Username'])) 
54 0397013a Scott Ullrich
		return true;
55
	return false;
56
}
57
58
/****f* pfsense-utils/have_natpfruleint_access
59
 * NAME
60
 *   have_natpfruleint_access
61
 * INPUTS
62
 *	 none
63
 * RESULT
64
 *   returns true if user has access to edit a specific firewall nat port forward interface
65
 ******/
66
function have_natpfruleint_access($if) {
67
	$security_url = "firewall_nat_edit.php?if=". strtolower($if);
68 45ee90ed Matthew Grooms
	if(isAllowedPage($security_url, $allowed)) 
69 0397013a Scott Ullrich
		return true;
70
	return false;
71
}
72
73 b6742927 Scott Ullrich
/****f* pfsense-utils/have_ruleint_access
74
 * NAME
75
 *   have_ruleint_access
76
 * INPUTS
77
 *	 none
78
 * RESULT
79
 *   returns true if user has access to edit a specific firewall interface
80
 ******/
81
function have_ruleint_access($if) {
82
	$security_url = "firewall_rules.php?if=". strtolower($if);
83 45ee90ed Matthew Grooms
	if(isAllowedPage($security_url)) 
84
		return true;
85 b6742927 Scott Ullrich
	return false;
86
}
87
88 10387862 Scott Ullrich
/****f* pfsense-utils/does_url_exist
89
 * NAME
90
 *   does_url_exist
91
 * INPUTS
92
 *	 none
93
 * RESULT
94
 *   returns true if a url is available
95
 ******/
96
function does_url_exist($url) {
97 3264c13b Scott Ullrich
	$fd = fopen("$url","r");
98 10387862 Scott Ullrich
	if($fd) {
99 4cc6345e Scott Ullrich
		fclose($fd);
100 10387862 Scott Ullrich
   		return true;    
101
	} else {
102
        return false;
103
	}
104
}
105
106 5928bd75 Scott Ullrich
/****f* pfsense-utils/is_private_ip
107
 * NAME
108
 *   is_private_ip
109
 * INPUTS
110
 *	 none
111
 * RESULT
112
 *   returns true if an ip address is in a private range
113
 ******/
114
function is_private_ip($iptocheck) {
115
        $isprivate = false;
116
        $ip_private_list=array(
117
               "10.0.0.0/8",
118
               "172.16.0.0/12",
119
               "192.168.0.0/16",
120
               "99.0.0.0/8"
121
        );
122
        foreach($ip_private_list as $private) {
123
                if(ip_in_subnet($iptocheck,$private)==true)
124
                        $isprivate = true;
125
        }
126
        return $isprivate;
127
}
128
129 8cb370b9 Scott Ullrich
/****f* pfsense-utils/get_tmp_file
130
 * NAME
131
 *   get_tmp_file
132
 * INPUTS
133
 *	 none
134
 * RESULT
135
 *   returns a temporary filename
136
 ******/
137 3076becf Scott Ullrich
function get_tmp_file() {
138 da17d77e Ermal Lu?i
	global $g;
139
	return "{$g['tmp_path']}/tmp-" . time();
140 3076becf Scott Ullrich
}
141
142
/****f* pfsense-utils/get_dns_servers
143
 * NAME
144
 *   get_dns_servres - get system dns servers
145
 * INPUTS
146
 *   $dns_servers - an array of the dns servers
147
 * RESULT
148
 *   null
149
 ******/
150
function get_dns_servers() {
151
	$dns_servers = array();
152 fa112436 Ermal
	$dns_s = file("/etc/resolv.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
153 3076becf Scott Ullrich
	foreach($dns_s as $dns) {
154
		$matches = "";
155
		if (preg_match("/nameserver (.*)/", $dns, $matches))
156
			$dns_servers[] = $matches[1];
157
	}
158 fa112436 Ermal
	return array_unique($dns_servers);
159 3076becf Scott Ullrich
}
160
161
/****f* pfsense-utils/enable_hardware_offloading
162
 * NAME
163
 *   enable_hardware_offloading - Enable a NIC's supported hardware features.
164
 * INPUTS
165
 *   $interface	- string containing the physical interface to work on.
166
 * RESULT
167
 *   null
168
 * NOTES
169
 *   This function only supports the fxp driver's loadable microcode.
170
 ******/
171
function enable_hardware_offloading($interface) {
172
	global $g, $config;
173
174 51d5aad7 Ermal
	if(isset($config['system']['do_not_use_nic_microcode']))
175 d2eb5def Scott Ullrich
		return;
176 4d98f634 Scott Ullrich
177 3076becf Scott Ullrich
	/* translate wan, lan, opt -> real interface if needed */
178 a2934331 Scott Ullrich
	$int = get_real_interface($interface);
179 51d5aad7 Ermal
	if(empty($int)) 
180 3d063391 Ermal
		return;
181 51d5aad7 Ermal
	$int_family = preg_split("/[0-9]+/", $int);
182 3076becf Scott Ullrich
	$supported_ints = array('fxp');
183 a7c6604c Chris Buechler
	if (in_array($int_family, $supported_ints)) {
184 51d5aad7 Ermal
		if(does_interface_exist($int)) 
185
			pfSense_interface_flags($int, IFF_LINK0);
186 a2934331 Scott Ullrich
	}
187 3076becf Scott Ullrich
188
	return;
189
}
190
191 f7eb54e4 Scott Ullrich
/****f* pfsense-utils/interface_supports_polling
192
 * NAME
193
 *   checks to see if an interface supports polling according to man polling
194
 * INPUTS
195
 *
196
 * RESULT
197
 *   true or false
198
 * NOTES
199
 *
200
 ******/
201
function interface_supports_polling($iface) {
202 3d063391 Ermal
	$opts = pfSense_get_interface_addresses($iface);
203
	if (is_array($opts) && isset($opts['caps']['polling']))
204 f7eb54e4 Scott Ullrich
		return true;
205 3d063391 Ermal
206 f7eb54e4 Scott Ullrich
	return false;
207
}
208
209 3076becf Scott Ullrich
/****f* pfsense-utils/is_alias_inuse
210
 * NAME
211
 *   checks to see if an alias is currently in use by a rule
212
 * INPUTS
213
 *
214
 * RESULT
215
 *   true or false
216
 * NOTES
217
 *
218
 ******/
219
function is_alias_inuse($alias) {
220
	global $g, $config;
221
222
	if($alias == "") return false;
223
	/* loop through firewall rules looking for alias in use */
224 346e2e6b Scott Ullrich
	if(is_array($config['filter']['rule']))
225 3076becf Scott Ullrich
		foreach($config['filter']['rule'] as $rule) {
226 00eee841 Scott Ullrich
			if($rule['source']['address'])
227 3076becf Scott Ullrich
				if($rule['source']['address'] == $alias)
228 0c8c496e Scott Ullrich
					return true;
229 00eee841 Scott Ullrich
			if($rule['destination']['address'])
230 3076becf Scott Ullrich
				if($rule['destination']['address'] == $alias)
231 0c8c496e Scott Ullrich
					return true;
232
		}
233 3076becf Scott Ullrich
	/* loop through nat rules looking for alias in use */
234
	if(is_array($config['nat']['rule']))
235
		foreach($config['nat']['rule'] as $rule) {
236 59ecde49 Renato Botelho
			if($rule['target'] && $rule['target'] == $alias)
237 3076becf Scott Ullrich
				return true;
238 59ecde49 Renato Botelho
			if($rule['source']['address'] && $rule['source']['address'] == $alias)
239
				return true;
240
			if($rule['destination']['address'] && $rule['destination']['address'] == $alias)
241 3076becf Scott Ullrich
				return true;
242
		}
243
	return false;
244
}
245
246 63724b02 Scott Dale
/****f* pfsense-utils/is_schedule_inuse
247
 * NAME
248
 *   checks to see if a schedule is currently in use by a rule
249
 * INPUTS
250
 *
251
 * RESULT
252
 *   true or false
253
 * NOTES
254
 *
255
 ******/
256
function is_schedule_inuse($schedule) {
257
	global $g, $config;
258
259
	if($schedule == "") return false;
260
	/* loop through firewall rules looking for schedule in use */
261
	if(is_array($config['filter']['rule']))
262
		foreach($config['filter']['rule'] as $rule) {
263 591ceb32 Scott Dale
			if($rule['sched'] == $schedule)
264
				return true;
265 63724b02 Scott Dale
		}
266
	return false;
267
}
268
269 3076becf Scott Ullrich
/****f* pfsense-utils/setup_polling
270
 * NAME
271
 *   sets up polling
272
 * INPUTS
273
 *
274
 * RESULT
275
 *   null
276
 * NOTES
277
 *
278
 ******/
279
function setup_polling() {
280
	global $g, $config;
281
282 51d5aad7 Ermal
	if (isset($config['system']['polling']))
283
		mwexec("/sbin/sysctl kern.polling.idle_poll=1");
284
	else
285
		mwexec("/sbin/sysctl kern.polling.idle_poll=0");
286 3076becf Scott Ullrich
287 9a4c3eed Ermal
	if($config['system']['polling_each_burst'])
288
		mwexec("/sbin/sysctl kern.polling.each_burst={$config['system']['polling_each_burst']}");
289
	if($config['system']['polling_burst_max'])
290
		mwexec("/sbin/sysctl kern.polling.burst_max={$config['system']['polling_burst_max']}");
291
	if($config['system']['polling_user_frac'])
292
		mwexec("/sbin/sysctl kern.polling.user_frac={$config['system']['polling_user_frac']}");
293 3076becf Scott Ullrich
}
294
295
/****f* pfsense-utils/setup_microcode
296
 * NAME
297
 *   enumerates all interfaces and calls enable_hardware_offloading which
298
 *   enables a NIC's supported hardware features.
299
 * INPUTS
300
 *
301
 * RESULT
302
 *   null
303
 * NOTES
304
 *   This function only supports the fxp driver's loadable microcode.
305
 ******/
306
function setup_microcode() {
307
308 3a4ce87d Ermal Luçi
	/* if list */
309 929a1b15 jim-p
	$ifs = get_interface_arr();
310 e8df4c2f Scott Ullrich
311 929a1b15 jim-p
	foreach($ifs as $if)
312 3076becf Scott Ullrich
		enable_hardware_offloading($if);
313
}
314
315
/****f* pfsense-utils/get_carp_status
316
 * NAME
317
 *   get_carp_status - Return whether CARP is enabled or disabled.
318
 * RESULT
319
 *   boolean	- true if CARP is enabled, false if otherwise.
320
 ******/
321
function get_carp_status() {
322
    /* grab the current status of carp */
323 4ed5ad5a Ermal
    $status = `/sbin/sysctl -n net.inet.carp.allow`;
324
    return (intval($status) > 0);
325 3076becf Scott Ullrich
}
326
327
/*
328
 * convert_ip_to_network_format($ip, $subnet): converts an ip address to network form
329 52947718 Ermal Lu?i
330 3076becf Scott Ullrich
 */
331
function convert_ip_to_network_format($ip, $subnet) {
332
	$ipsplit = split('[.]', $ip);
333
	$string = $ipsplit[0] . "." . $ipsplit[1] . "." . $ipsplit[2] . ".0/" . $subnet;
334
	return $string;
335
}
336
337
/*
338
 * get_carp_interface_status($carpinterface): returns the status of a carp ip
339
 */
340
function get_carp_interface_status($carpinterface) {
341 108cfddf Ermal
	$carp_query = "";
342
	exec("/sbin/ifconfig $carpinterface | /usr/bin/grep -v grep | /usr/bin/grep carp:", $carp_query);
343 3076becf Scott Ullrich
	foreach($carp_query as $int) {
344 27625b39 Scott Ullrich
		if(stristr($int, "MASTER")) 
345 7d1b238c Carlos Eduardo Ramos
			return gettext("MASTER");
346 27625b39 Scott Ullrich
		if(stristr($int, "BACKUP")) 
347 7d1b238c Carlos Eduardo Ramos
			return gettext("BACKUP");
348 27625b39 Scott Ullrich
		if(stristr($int, "INIT")) 
349 7d1b238c Carlos Eduardo Ramos
			return gettext("INIT");
350 3076becf Scott Ullrich
	}
351
	return;
352
}
353
354
/*
355
 * get_pfsync_interface_status($pfsyncinterface): returns the status of a pfsync
356
 */
357
function get_pfsync_interface_status($pfsyncinterface) {
358
    $result = does_interface_exist($pfsyncinterface);
359
    if($result <> true) return;
360 6f76920c thompsa
    $status = exec_command("/sbin/ifconfig {$pfsyncinterface} | /usr/bin/awk '/pfsync:/ {print \$5}'");
361 3076becf Scott Ullrich
    return $status;
362
}
363
364
/*
365
 * add_rule_to_anchor($anchor, $rule): adds the specified rule to an anchor
366
 */
367
function add_rule_to_anchor($anchor, $rule, $label) {
368
	mwexec("echo " . $rule . " | /sbin/pfctl -a " . $anchor . ":" . $label . " -f -");
369
}
370
371
/*
372
 * remove_text_from_file
373
 * remove $text from file $file
374
 */
375
function remove_text_from_file($file, $text) {
376 2addd5b2 Ermal
	if(!file_exists($file) && !is_writable($file))
377
		return;
378 3076becf Scott Ullrich
	$filecontents = file_get_contents($file);
379 2addd5b2 Ermal
	$text = str_replace($text, "", $filecontents);
380
	@file_put_contents($file, $text); 
381 3076becf Scott Ullrich
}
382
383
/*
384
 * add_text_to_file($file, $text): adds $text to $file.
385
 * replaces the text if it already exists.
386
 */
387 5a6f3ca0 Scott Ullrich
function add_text_to_file($file, $text, $replace = false) {
388 3076becf Scott Ullrich
	if(file_exists($file) and is_writable($file)) {
389 5a6f3ca0 Scott Ullrich
		$filecontents = file($file);
390
		$filecontents = array_map('rtrim', $filecontents);
391
		array_push($filecontents, $text);
392
		if ($replace)
393
			$filecontents = array_unique($filecontents);
394
395
		$file_text = implode("\n", $filecontents);
396
397 2addd5b2 Ermal
		@file_put_contents($file, $file_text); 
398 3076becf Scott Ullrich
		return true;
399 0c8c496e Scott Ullrich
	}
400 2addd5b2 Ermal
	return false;
401 3076becf Scott Ullrich
}
402
403
/*
404
 *   after_sync_bump_adv_skew(): create skew values by 1S
405
 */
406
function after_sync_bump_adv_skew() {
407
	global $config, $g;
408
	$processed_skew = 1;
409
	$a_vip = &$config['virtualip']['vip'];
410
	foreach ($a_vip as $vipent) {
411
		if($vipent['advskew'] <> "") {
412
			$processed_skew = 1;
413
			$vipent['advskew'] = $vipent['advskew']+1;
414
		}
415
	}
416
	if($processed_skew == 1)
417 7d1b238c Carlos Eduardo Ramos
		write_config(gettext("After synch increase advertising skew"));
418 3076becf Scott Ullrich
}
419
420
/*
421
 * get_filename_from_url($url): converts a url to its filename.
422
 */
423
function get_filename_from_url($url) {
424
	return basename($url);
425
}
426
427
/*
428
 *   get_dir: return an array of $dir
429
 */
430
function get_dir($dir) {
431
	$dir_array = array();
432
	$d = dir($dir);
433
	while (false !== ($entry = $d->read())) {
434
		array_push($dir_array, $entry);
435
	}
436
	$d->close();
437
	return $dir_array;
438
}
439
440
/****f* pfsense-utils/WakeOnLan
441
 * NAME
442
 *   WakeOnLan - Wake a machine up using the wake on lan format/protocol
443
 * RESULT
444
 *   true/false - true if the operation was successful
445
 ******/
446
function WakeOnLan($addr, $mac)
447
{
448
	$addr_byte = explode(':', $mac);
449
	$hw_addr = '';
450
451
	for ($a=0; $a < 6; $a++)
452
		$hw_addr .= chr(hexdec($addr_byte[$a]));
453
454
	$msg = chr(255).chr(255).chr(255).chr(255).chr(255).chr(255);
455
456
	for ($a = 1; $a <= 16; $a++)
457
		$msg .= $hw_addr;
458
459
	// send it to the broadcast address using UDP
460
	$s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
461
	if ($s == false) {
462 7d1b238c Carlos Eduardo Ramos
		log_error(gettext("Error creating socket!"));
463 addc0439 Renato Botelho
		log_error(sprintf(gettext("Error code is '%1\$s' - %2\$s"), socket_last_error($s), socket_strerror(socket_last_error($s))));
464 3076becf Scott Ullrich
	} else {
465
		// setting a broadcast option to socket:
466
		$opt_ret =  socket_set_option($s, 1, 6, TRUE);
467
		if($opt_ret < 0)
468 7d1b238c Carlos Eduardo Ramos
			log_error(sprintf(gettext("setsockopt() failed, error: %s"), strerror($opt_ret)));
469 3076becf Scott Ullrich
		$e = socket_sendto($s, $msg, strlen($msg), 0, $addr, 2050);
470
		socket_close($s);
471 addc0439 Renato Botelho
		log_error(sprintf(gettext('Magic Packet sent (%1$s) to {%2$s} MAC=%3$s'), $e, $addr, $mac));
472 3076becf Scott Ullrich
		return true;
473 0c8c496e Scott Ullrich
	}
474 3076becf Scott Ullrich
475
	return false;
476
}
477
478
/*
479
 * gather_altq_queue_stats():  gather altq queue stats and return an array that
480
 *                             is queuename|qlength|measured_packets
481
 *                             NOTE: this command takes 5 seconds to run
482
 */
483
function gather_altq_queue_stats($dont_return_root_queues) {
484 f2b8daad Ermal Lu?i
	exec("/sbin/pfctl -vvsq", $stats_array);
485 3076becf Scott Ullrich
	$queue_stats = array();
486
	foreach ($stats_array as $stats_line) {
487
		$match_array = "";
488
		if (preg_match_all("/queue\s+(\w+)\s+/",$stats_line,$match_array))
489
			$queue_name = $match_array[1][0];
490
		if (preg_match_all("/measured:\s+.*packets\/s\,\s(.*)\s+\]/",$stats_line,$match_array))
491
			$speed = $match_array[1][0];
492
		if (preg_match_all("/borrows:\s+(.*)/",$stats_line,$match_array))
493
			$borrows = $match_array[1][0];
494
		if (preg_match_all("/suspends:\s+(.*)/",$stats_line,$match_array))
495
			$suspends = $match_array[1][0];
496
		if (preg_match_all("/dropped pkts:\s+(.*)/",$stats_line,$match_array))
497
			$drops = $match_array[1][0];
498
		if (preg_match_all("/measured:\s+(.*)packets/",$stats_line,$match_array)) {
499
			$measured = $match_array[1][0];
500
			if($dont_return_root_queues == true)
501
				if(stristr($queue_name,"root_") == false)
502
					array_push($queue_stats, "{$queue_name}|{$speed}|{$measured}|{$borrows}|{$suspends}|{$drops}");
503
		}
504
	}
505
	return $queue_stats;
506
}
507
508
/*
509
 * reverse_strrchr($haystack, $needle):  Return everything in $haystack up to the *last* instance of $needle.
510
 *					 Useful for finding paths and stripping file extensions.
511
 */
512
function reverse_strrchr($haystack, $needle) {
513 4824d857 Ermal Lu?i
	if (!is_string($haystack))
514
		return;
515 3076becf Scott Ullrich
	return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) +1 ) : false;
516
}
517
518
/*
519
 *  backup_config_section($section): returns as an xml file string of
520
 *                                   the configuration section
521
 */
522
function backup_config_section($section) {
523
	global $config;
524
	$new_section = &$config[$section];
525
	/* generate configuration XML */
526
	$xmlconfig = dump_xml_config($new_section, $section);
527
	$xmlconfig = str_replace("<?xml version=\"1.0\"?>", "", $xmlconfig);
528
	return $xmlconfig;
529
}
530
531
/*
532
 *  restore_config_section($section, new_contents): restore a configuration section,
533
 *                                                  and write the configuration out
534
 *                                                  to disk/cf.
535
 */
536
function restore_config_section($section, $new_contents) {
537
	global $config, $g;
538
	conf_mount_rw();
539
	$fout = fopen("{$g['tmp_path']}/tmpxml","w");
540
	fwrite($fout, $new_contents);
541
	fclose($fout);
542
	$section_xml = parse_xml_config($g['tmp_path'] . "/tmpxml", $section);
543 541989d5 Ermal
	if ($section_xml != -1)
544
		$config[$section] = &$section_xml;
545
	@unlink($g['tmp_path'] . "/tmpxml");
546 a57d6170 Scott Ullrich
	if(file_exists("{$g['tmp_path']}/config.cache"))
547
		unlink("{$g['tmp_path']}/config.cache");
548 7d1b238c Carlos Eduardo Ramos
	write_config(sprintf(gettext("Restored %s of config file (maybe from CARP partner)"), $section));
549 0f806eca Erik Fonnesbeck
	disable_security_checks();
550 3076becf Scott Ullrich
	conf_mount_ro();
551
	return;
552
}
553
554
/*
555
 *  merge_config_section($section, new_contents):   restore a configuration section,
556
 *                                                  and write the configuration out
557
 *                                                  to disk/cf.  But preserve the prior
558
 * 													structure if needed
559
 */
560
function merge_config_section($section, $new_contents) {
561
	global $config;
562
	conf_mount_rw();
563
	$fname = get_tmp_filename();
564
	$fout = fopen($fname, "w");
565
	fwrite($fout, $new_contents);
566
	fclose($fout);
567
	$section_xml = parse_xml_config($fname, $section);
568
	$config[$section] = $section_xml;
569
	unlink($fname);
570 7d1b238c Carlos Eduardo Ramos
	write_config(sprintf(gettext("Restored %s of config file (maybe from CARP partner)"), $section));
571 0f806eca Erik Fonnesbeck
	disable_security_checks();
572 3076becf Scott Ullrich
	conf_mount_ro();
573
	return;
574
}
575
576
/*
577
 * http_post($server, $port, $url, $vars): does an http post to a web server
578
 *                                         posting the vars array.
579
 * written by nf@bigpond.net.au
580
 */
581
function http_post($server, $port, $url, $vars) {
582
	$user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)";
583
	$urlencoded = "";
584
	while (list($key,$value) = each($vars))
585
		$urlencoded.= urlencode($key) . "=" . urlencode($value) . "&";
586
	$urlencoded = substr($urlencoded,0,-1);
587
	$content_length = strlen($urlencoded);
588
	$headers = "POST $url HTTP/1.1
589
Accept: */*
590
Accept-Language: en-au
591
Content-Type: application/x-www-form-urlencoded
592
User-Agent: $user_agent
593
Host: $server
594
Connection: Keep-Alive
595
Cache-Control: no-cache
596
Content-Length: $content_length
597
598
";
599
600
	$errno = "";
601
	$errstr = "";
602
	$fp = fsockopen($server, $port, $errno, $errstr);
603
	if (!$fp) {
604 0c8c496e Scott Ullrich
		return false;
605
	}
606 3076becf Scott Ullrich
607
	fputs($fp, $headers);
608
	fputs($fp, $urlencoded);
609
610
	$ret = "";
611
	while (!feof($fp))
612
		$ret.= fgets($fp, 1024);
613
	fclose($fp);
614
615
	return $ret;
616
}
617
618
/*
619
 *  php_check_syntax($code_tocheck, $errormessage): checks $code_to_check for errors
620
 */
621
if (!function_exists('php_check_syntax')){
622 da17d77e Ermal Lu?i
	global $g;
623 3076becf Scott Ullrich
	function php_check_syntax($code_to_check, &$errormessage){
624
		return false;
625 da17d77e Ermal Lu?i
		$fout = fopen("{$g['tmp_path']}/codetocheck.php","w");
626 3076becf Scott Ullrich
		$code = $_POST['content'];
627
		$code = str_replace("<?php", "", $code);
628
		$code = str_replace("?>", "", $code);
629
		fwrite($fout, "<?php\n\n");
630
		fwrite($fout, $code_to_check);
631
		fwrite($fout, "\n\n?>\n");
632 0c8c496e Scott Ullrich
		fclose($fout);
633 da17d77e Ermal Lu?i
		$command = "/usr/local/bin/php -l {$g['tmp_path']}/codetocheck.php";
634 3076becf Scott Ullrich
		$output = exec_command($command);
635
		if (stristr($output, "Errors parsing") == false) {
636
			echo "false\n";
637
			$errormessage = '';
638
			return(false);
639
		} else {
640
			$errormessage = $output;
641
			return(true);
642 0c8c496e Scott Ullrich
		}
643
	}
644 3076becf Scott Ullrich
}
645
646
/*
647
 *  php_check_filename_syntax($filename, $errormessage): checks the file $filename for errors
648
 */
649
if (!function_exists('php_check_syntax')){
650
	function php_check_syntax($code_to_check, &$errormessage){
651
		return false;
652
		$command = "/usr/local/bin/php -l " . $code_to_check;
653
		$output = exec_command($command);
654
		if (stristr($output, "Errors parsing") == false) {
655
			echo "false\n";
656
			$errormessage = '';
657
			return(false);
658
		} else {
659
			$errormessage = $output;
660
			return(true);
661
		}
662
	}
663
}
664
665
/*
666
 * rmdir_recursive($path,$follow_links=false)
667
 * Recursively remove a directory tree (rm -rf path)
668
 * This is for directories _only_
669
 */
670
function rmdir_recursive($path,$follow_links=false) {
671
	$to_do = glob($path);
672
	if(!is_array($to_do)) $to_do = array($to_do);
673
	foreach($to_do as $workingdir) { // Handle wildcards by foreaching.
674
		if(file_exists($workingdir)) {
675
			if(is_dir($workingdir)) {
676
				$dir = opendir($workingdir);
677
				while ($entry = readdir($dir)) {
678
					if (is_file("$workingdir/$entry") || ((!$follow_links) && is_link("$workingdir/$entry")))
679
						unlink("$workingdir/$entry");
680
					elseif (is_dir("$workingdir/$entry") && $entry!='.' && $entry!='..')
681
						rmdir_recursive("$workingdir/$entry");
682 6613a031 Scott Ullrich
				}
683 3076becf Scott Ullrich
				closedir($dir);
684
				rmdir($workingdir);
685
			} elseif (is_file($workingdir)) {
686
				unlink($workingdir);
687
			}
688
               	}
689
	}
690
	return;
691
}
692
693
/*
694
 * call_pfsense_method(): Call a method exposed by the pfsense.com XMLRPC server.
695
 */
696
function call_pfsense_method($method, $params, $timeout = 0) {
697 cfceefc6 Scott Ullrich
	global $g, $config;
698
699 36d0358b Scott Ullrich
	$ip = gethostbyname($g['product_website']);
700
	if($ip == $g['product_website'])
701 3076becf Scott Ullrich
		return false;
702 80f8f00c Ermal Lu?i
703 ffba4976 jim-p
	$xmlrpc_base_url = isset($config['system']['altpkgrepo']['enable']) ? $config['system']['altpkgrepo']['xmlrpcbaseurl'] : $g['xmlrpcbaseurl'];
704 3076becf Scott Ullrich
	$xmlrpc_path = $g['xmlrpcpath'];
705
	$msg = new XML_RPC_Message($method, array(XML_RPC_Encode($params)));
706 42c07003 Ermal
	$port = 0;
707
	$proxyurl = "";
708
	$proxyport = 0;
709
	$proxyuser = "";
710
	$proxypass = "";
711 aa3c4866 Ermal
	if (!empty($config['system']['proxyurl']))
712
		$proxyurl = $config['system']['proxyurl'];
713
	if (!empty($config['system']['proxyport']) && is_numeric($config['system']['proxyport']))
714
		$proxyport = $config['system']['proxyport'];
715
	if (!empty($config['system']['proxyuser']))
716
		$proxyuser = $config['system']['proxyuser'];
717
	if (!empty($config['system']['proxypass']))
718
		$proxypass = $config['system']['proxypass'];
719 42c07003 Ermal
	$cli = new XML_RPC_Client($xmlrpc_path, $xmlrpc_base_url, $port, $proxyurl, $proxyport, $proxyuser, $proxypass);
720 16348c36 Scott Ullrich
	// If the ALT PKG Repo has a username/password set, use it.
721
	if($config['system']['altpkgrepo']['username'] && 
722
	   $config['system']['altpkgrepo']['password']) {
723
		$username = $config['system']['altpkgrepo']['username'];
724
		$password = $config['system']['altpkgrepo']['password'];
725
		$cli->setCredentials($username, $password);
726
	}
727 3076becf Scott Ullrich
	$resp = $cli->send($msg, $timeout);
728 2addd5b2 Ermal
	if(!is_object($resp)) {
729 7d1b238c Carlos Eduardo Ramos
		log_error(sprintf(gettext("XMLRPC communication error: %s"), $cli->errstr));
730 3076becf Scott Ullrich
		return false;
731
	} elseif($resp->faultCode()) {
732 addc0439 Renato Botelho
		log_error(sprintf(gettext('XMLRPC request failed with error %1$s: %2$s'), $resp->faultCode(), $resp->faultString()));
733 3076becf Scott Ullrich
		return false;
734
	} else {
735
		return XML_RPC_Decode($resp->value());
736
	}
737
}
738
739
/*
740
 * check_firmware_version(): Check whether the current firmware installed is the most recently released.
741
 */
742
function check_firmware_version($tocheck = "all", $return_php = true) {
743
	global $g, $config;
744 d064a115 Ermal
745 36d0358b Scott Ullrich
	$ip = gethostbyname($g['product_website']);
746
	if($ip == $g['product_website'])
747 3076becf Scott Ullrich
		return false;
748 d064a115 Ermal
749 3076becf Scott Ullrich
	$rawparams = array("firmware" => array("version" => trim(file_get_contents('/etc/version'))),
750
		"kernel"   => array("version" => trim(file_get_contents('/etc/version_kernel'))),
751
		"base"     => array("version" => trim(file_get_contents('/etc/version_base'))),
752 d064a115 Ermal
		"platform" => trim(file_get_contents('/etc/platform')),
753
		"config_version" => $config['version']
754 3076becf Scott Ullrich
		);
755
	if($tocheck == "all") {
756
		$params = $rawparams;
757
	} else {
758
		foreach($tocheck as $check) {
759
			$params['check'] = $rawparams['check'];
760
			$params['platform'] = $rawparams['platform'];
761
		}
762
	}
763 d064a115 Ermal
	if($config['system']['firmware']['branch'])
764 3076becf Scott Ullrich
		$params['branch'] = $config['system']['firmware']['branch'];
765 d064a115 Ermal
766
	/* XXX: What is this method? */
767
	if(!($versions = call_pfsense_method('pfsense.get_firmware_version', $params))) {
768 3076becf Scott Ullrich
		return false;
769
	} else {
770
		$versions["current"] = $params;
771
	}
772 d064a115 Ermal
773 3076becf Scott Ullrich
	return $versions;
774
}
775
776 e501de37 Ermal
/*
777
 * host_firmware_version(): Return the versions used in this install
778
 */
779 18be996d Ermal
function host_firmware_version($tocheck = "") {
780 e501de37 Ermal
        global $g, $config;
781
782
        return array(
783
		"firmware" => array("version" => trim(file_get_contents('/etc/version', " \n"))),
784
                "kernel"   => array("version" => trim(file_get_contents('/etc/version_kernel', " \n"))),
785
                "base"     => array("version" => trim(file_get_contents('/etc/version_base', " \n"))),
786
                "platform" => trim(file_get_contents('/etc/platform', " \n")),
787
                "config_version" => $config['version']
788
                );
789
}
790
791 3076becf Scott Ullrich
function get_disk_info() {
792
	$diskout = "";
793
	exec("/bin/df -h | /usr/bin/grep -w '/' | /usr/bin/awk '{ print $2, $3, $4, $5 }'", $diskout);
794
	return explode(' ', $diskout[0]);
795
}
796
797
/****f* pfsense-utils/strncpy
798
 * NAME
799
 *   strncpy - copy strings
800
 * INPUTS
801
 *   &$dst, $src, $length
802
 * RESULT
803
 *   none
804
 ******/
805
function strncpy(&$dst, $src, $length) {
806
	if (strlen($src) > $length) {
807
		$dst = substr($src, 0, $length);
808
	} else {
809
		$dst = $src;
810
	}
811
}
812
813
/****f* pfsense-utils/reload_interfaces_sync
814
 * NAME
815
 *   reload_interfaces - reload all interfaces
816
 * INPUTS
817
 *   none
818
 * RESULT
819
 *   none
820
 ******/
821
function reload_interfaces_sync() {
822 c0836064 Ermal Luçi
	global $config, $g;
823 3076becf Scott Ullrich
824 c0836064 Ermal Luçi
	if($g['debug'])
825 7d1b238c Carlos Eduardo Ramos
		log_error(gettext("reload_interfaces_sync() is starting."));
826 3076becf Scott Ullrich
827
	/* parse config.xml again */
828
	$config = parse_config(true);
829
830 a5d6f60b Ermal Lu?i
	/* enable routing */
831
	system_routing_enable();
832
	if($g['debug'])
833 7d1b238c Carlos Eduardo Ramos
		log_error(gettext("Enabling system routing"));
834 3076becf Scott Ullrich
835 c0836064 Ermal Luçi
	if($g['debug'])
836 7d1b238c Carlos Eduardo Ramos
		log_error(gettext("Cleaning up Interfaces"));
837 3076becf Scott Ullrich
838 67ee1ec5 Ermal Luçi
	/* set up interfaces */
839
	interfaces_configure();
840 3076becf Scott Ullrich
}
841
842
/****f* pfsense-utils/reload_all
843
 * NAME
844
 *   reload_all - triggers a reload of all settings
845
 *   * INPUTS
846
 *   none
847
 * RESULT
848
 *   none
849
 ******/
850
function reload_all() {
851 0ae6daf8 Ermal
	send_event("service reload all");
852 3076becf Scott Ullrich
}
853
854
/****f* pfsense-utils/reload_interfaces
855
 * NAME
856
 *   reload_interfaces - triggers a reload of all interfaces
857
 * INPUTS
858
 *   none
859
 * RESULT
860
 *   none
861
 ******/
862
function reload_interfaces() {
863 5e3a84e2 Ermal
	send_event("interface all reload");
864 3076becf Scott Ullrich
}
865
866
/****f* pfsense-utils/reload_all_sync
867
 * NAME
868
 *   reload_all - reload all settings
869
 *   * INPUTS
870
 *   none
871
 * RESULT
872
 *   none
873
 ******/
874
function reload_all_sync() {
875
	global $config, $g;
876
877
	$g['booting'] = false;
878
879
	/* parse config.xml again */
880
	$config = parse_config(true);
881
882
	/* set up our timezone */
883
	system_timezone_configure();
884
885
	/* set up our hostname */
886
	system_hostname_configure();
887
888
	/* make hosts file */
889
	system_hosts_generate();
890
891
	/* generate resolv.conf */
892
	system_resolvconf_generate();
893
894
	/* enable routing */
895
	system_routing_enable();
896
897 a5d6f60b Ermal Lu?i
	/* set up interfaces */
898
	interfaces_configure();
899 3076becf Scott Ullrich
900
	/* start dyndns service */
901
	services_dyndns_configure();
902
903
	/* configure cron service */
904
	configure_cron();
905
906
	/* start the NTP client */
907
	system_ntp_configure();
908
909
	/* sync pw database */
910
	conf_mount_rw();
911 6b0c5879 Scott Ullrich
	unlink_if_exists("/etc/spwd.db.tmp");
912 3076becf Scott Ullrich
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
913
	conf_mount_ro();
914
915
	/* restart sshd */
916 0ae6daf8 Ermal
	send_event("service restart sshd");
917 3076becf Scott Ullrich
918
	/* restart webConfigurator if needed */
919 0ae6daf8 Ermal
	send_event("service restart webgui");
920 3076becf Scott Ullrich
}
921
922 a46e450c Ermal Lu?i
function auto_login() {
923
	global $config;
924
925
	if(isset($config['system']['disableconsolemenu']))
926 5f81609a Erik Fonnesbeck
		$status = false;
927
	else
928
		$status = true;
929
930 3076becf Scott Ullrich
	$gettytab = file_get_contents("/etc/gettytab");
931
	$getty_split = split("\n", $gettytab);
932
	conf_mount_rw();
933 6480d38f Ermal Lu?i
	$fd = false;
934 e7df76d2 Ermal Lu?i
	$tries = 0;
935
	while (!$fd && $tries < 100) {
936 6480d38f Ermal Lu?i
		$fd = fopen("/etc/gettytab", "w");
937 e7df76d2 Ermal Lu?i
		$tries++;
938
		
939
	}
940
	if (!$fd) {
941
		conf_mount_ro();
942 7d1b238c Carlos Eduardo Ramos
		log_error(gettext("Enabling auto login was not possible."));
943 e7df76d2 Ermal Lu?i
		return;
944 6480d38f Ermal Lu?i
	}
945 3076becf Scott Ullrich
	foreach($getty_split as $gs) {
946
		if(stristr($gs, ":ht:np:sp#115200") ) {
947
			if($status == true) {
948
				fwrite($fd, "	:ht:np:sp#115200:al=root:\n");
949
			} else {
950
				fwrite($fd, "	:ht:np:sp#115200:\n");
951 ca8e4ed2 Scott Ullrich
			}
952 0c8c496e Scott Ullrich
		} else {
953 3076becf Scott Ullrich
			fwrite($fd, "{$gs}\n");
954
		}
955
	}
956
	fclose($fd);
957
	conf_mount_ro();
958
}
959
960
function setup_serial_port() {
961
	global $g, $config;
962
	conf_mount_rw();
963
	/* serial console - write out /boot.config */
964
	if(file_exists("/boot.config"))
965
		$boot_config = file_get_contents("/boot.config");
966
	else
967
		$boot_config = "";
968
969
	if($g['platform'] <> "cdrom") {
970
		$boot_config_split = split("\n", $boot_config);
971
		$fd = fopen("/boot.config","w");
972
		if($fd) {
973
			foreach($boot_config_split as $bcs) {
974
				if(stristr($bcs, "-D")) {
975
					/* DONT WRITE OUT, WE'LL DO IT LATER */
976
				} else {
977
					if($bcs <> "")
978
						fwrite($fd, "{$bcs}\n");
979
				}
980 0c8c496e Scott Ullrich
			}
981 3076becf Scott Ullrich
			if(isset($config['system']['enableserial'])) {
982
				fwrite($fd, "-D");
983 0c8c496e Scott Ullrich
			}
984 3076becf Scott Ullrich
			fclose($fd);
985 0c8c496e Scott Ullrich
		}
986 3076becf Scott Ullrich
		/* serial console - write out /boot/loader.conf */
987
		$boot_config = file_get_contents("/boot/loader.conf");
988 5f36c658 jim-p
		$boot_config_split = explode("\n", $boot_config);
989
		if(count($boot_config_split) > 0) {
990
			$new_boot_config = array();
991
			// Loop through and only add lines that are not empty, and which
992
			//  do not contain a console directive.
993
			foreach($boot_config_split as $bcs)
994
				if(!empty($bcs) && (stripos($bcs, "console") === false))
995
					$new_boot_config[] = $bcs;
996
997
			if(isset($config['system']['enableserial']))
998 e2d052b6 Ermal
				$new_boot_config[] = 'console="comconsole"';
999 5f36c658 jim-p
			file_put_contents("/boot/loader.conf", implode("\n", $new_boot_config));
1000 0c8c496e Scott Ullrich
		}
1001
	}
1002 3076becf Scott Ullrich
	$ttys = file_get_contents("/etc/ttys");
1003
	$ttys_split = split("\n", $ttys);
1004
	$fd = fopen("/etc/ttys", "w");
1005
	foreach($ttys_split as $tty) {
1006 c1fdf37f sullrich
		if(stristr($tty, "ttyd0") or stristr($tty, "ttyu0")) {
1007 3076becf Scott Ullrich
			if(isset($config['system']['enableserial'])) {
1008 fd946c7e Erik Fonnesbeck
				fwrite($fd, "ttyu0	\"/usr/libexec/getty bootupcli\"	cons25	on	secure\n");
1009 3076becf Scott Ullrich
			} else {
1010 fd946c7e Erik Fonnesbeck
				fwrite($fd, "ttyu0	\"/usr/libexec/getty bootupcli\"	cons25	off	secure\n");
1011 ca8e4ed2 Scott Ullrich
			}
1012 3076becf Scott Ullrich
		} else {
1013
			fwrite($fd, $tty . "\n");
1014
		}
1015
	}
1016
	fclose($fd);
1017 a46e450c Ermal Lu?i
	auto_login();
1018
1019 3076becf Scott Ullrich
	conf_mount_ro();
1020
	return;
1021
}
1022
1023
function print_value_list($list, $count = 10, $separator = ",") {
1024
	$list = implode($separator, array_slice($list, 0, $count));
1025
	if(count($list) < $count) {
1026
		$list .= ".";
1027
	} else {
1028
		$list .= "...";
1029
	}
1030
	return $list;
1031
}
1032
1033 bfe776f0 Ermal Luçi
/* DHCP enabled on any interfaces? */
1034
function is_dhcp_server_enabled() 
1035
{
1036 db9fabf3 Ermal Luçi
	global $config;
1037 bfe776f0 Ermal Luçi
1038 3076becf Scott Ullrich
	$dhcpdenable = false;
1039 bfe776f0 Ermal Luçi
	
1040 65b1e7d5 Seth Mos
	if ((!is_array($config['dhcpd'])) && (!is_array($config['dhcpdv6'])))
1041 bfe776f0 Ermal Luçi
		return false;
1042
1043 db9fabf3 Ermal Luçi
	$Iflist = get_configured_interface_list();
1044
1045 a8a98fb4 Seth Mos
	if(is_array($config['dhcpd'])) {
1046
		foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf) {
1047
			if (isset($dhcpifconf['enable']) && isset($Iflist[$dhcpif])) {
1048
				$dhcpdenable = true;
1049
				break;
1050
			}
1051 db9fabf3 Ermal Luçi
		}
1052 3076becf Scott Ullrich
	}
1053 bfe776f0 Ermal Luçi
1054 a8a98fb4 Seth Mos
	if(is_array($config['dhcpdv6'])) {
1055
		foreach ($config['dhcpdv6'] as $dhcpv6if => $dhcpv6ifconf) {
1056
			if (isset($dhcpv6ifconf['enable']) && isset($Iflist[$dhcpv6if])) {
1057
				$dhcpdenable = true;
1058
				break;
1059
			}
1060 65b1e7d5 Seth Mos
		}
1061
	}
1062
1063 3076becf Scott Ullrich
	return $dhcpdenable;
1064
}
1065
1066 93c2c1e6 jim-p
/* Any PPPoE servers enabled? */
1067
function is_pppoe_server_enabled() {
1068
	global $config;
1069
1070
	$pppoeenable = false;
1071
1072
	if (!is_array($config['pppoes']) || !is_array($config['pppoes']['pppoe']))
1073
		return false;
1074
1075
	foreach ($config['pppoes']['pppoe'] as $pppoes)
1076
		if ($pppoes['mode'] == 'server')
1077
			$pppoeenable = true;
1078
1079
	return $pppoeenable;
1080
}
1081
1082 9ebe7028 gnhb
function convert_seconds_to_hms($sec){
1083 63292199 gnhb
	$min=$hrs=0;
1084 9ebe7028 gnhb
	if ($sec != 0){
1085
		$min = floor($sec/60);
1086
		$sec %= 60;
1087
	}
1088
	if ($min != 0){
1089
		$hrs = floor($min/60);
1090
		$min %= 60;
1091
	}
1092
	if ($sec < 10)
1093
		$sec = "0".$sec;
1094
	if ($min < 10)
1095
		$min = "0".$min;
1096
	if ($hrs < 10)
1097
		$hrs = "0".$hrs;
1098
	$result = $hrs.":".$min.":".$sec;
1099
	return $result;
1100
}
1101 8eb2f33a Scott Ullrich
1102 63292199 gnhb
/* Compute the total uptime from the ppp uptime log file in the conf directory */
1103
1104
function get_ppp_uptime($port){
1105
	if (file_exists("/conf/{$port}.log")){
1106
    	$saved_time = file_get_contents("/conf/{$port}.log");
1107
    	$uptime_data = explode("\n",$saved_time);
1108
		$sec=0;
1109
		foreach($uptime_data as $upt) {
1110
			$sec += substr($upt, 1 + strpos($upt, " "));
1111
 		}
1112
		return convert_seconds_to_hms($sec);
1113
	} else {
1114 7d1b238c Carlos Eduardo Ramos
		$total_time = gettext("No history data found!");
1115 63292199 gnhb
		return $total_time;
1116
	}
1117
}
1118 8eb2f33a Scott Ullrich
1119 6189988d Scott Dale
//returns interface information
1120
function get_interface_info($ifdescr) {
1121 cffe41cb Ermal
	global $config, $g;
1122 6189988d Scott Dale
1123
	$ifinfo = array();
1124 cffe41cb Ermal
	if (empty($config['interfaces'][$ifdescr]))
1125 67ee1ec5 Ermal Luçi
		return;
1126 ebdbdbc2 gnhb
	$ifinfo['hwif'] = $config['interfaces'][$ifdescr]['if'];
1127 cffe41cb Ermal
	$ifinfo['if'] = get_real_interface($ifdescr);
1128 6189988d Scott Dale
1129 cb074893 Ermal Lu?i
	$chkif = $ifinfo['if'];
1130
	$ifinfotmp = pfSense_get_interface_addresses($chkif);
1131
	$ifinfo['status'] = $ifinfotmp['status'];
1132 cffe41cb Ermal
	if (empty($ifinfo['status']))
1133
                $ifinfo['status'] = "down";
1134 cb074893 Ermal Lu?i
	$ifinfo['macaddr'] = $ifinfotmp['macaddr'];
1135
	$ifinfo['ipaddr'] = $ifinfotmp['ipaddr'];
1136
	$ifinfo['subnet'] = $ifinfotmp['subnet'];
1137 15cc0894 Seth Mos
	$ifinfo['ipaddrv6'] = get_interface_ipv6($ifdescr);
1138
	$ifinfo['subnetv6'] = get_interface_subnetv6($ifdescr);
1139 a216a03a gnhb
	if (isset($ifinfotmp['link0']))
1140 cb074893 Ermal Lu?i
		$link0 = "down";
1141 cffe41cb Ermal
	$ifinfotmp = pfSense_get_interface_stats($chkif);
1142 15cc0894 Seth Mos
        // $ifinfo['inpkts'] = $ifinfotmp['inpkts'];
1143
        // $ifinfo['outpkts'] = $ifinfotmp['outpkts'];
1144 cffe41cb Ermal
        $ifinfo['inerrs'] = $ifinfotmp['inerrs'];
1145
        $ifinfo['outerrs'] = $ifinfotmp['outerrs'];
1146
        $ifinfo['collisions'] = $ifinfotmp['collisions'];
1147 6189988d Scott Dale
1148 01385b0c Scott Ullrich
	/* Use pfctl for non wrapping 64 bit counters */
1149 b5a8483c Seth Mos
	/* Pass */
1150 cb074893 Ermal Lu?i
	exec("/sbin/pfctl -vvsI -i {$chkif}", $pfctlstats);
1151 971eaab5 Seth Mos
	$pf_in4_pass = preg_split("/ +/ ", $pfctlstats[3]);
1152
	$pf_out4_pass = preg_split("/ +/", $pfctlstats[5]);
1153 15cc0894 Seth Mos
	$pf_in6_pass = preg_split("/ +/ ", $pfctlstats[7]);
1154
	$pf_out6_pass = preg_split("/ +/", $pfctlstats[9]);
1155 971eaab5 Seth Mos
	$in4_pass = $pf_in4_pass[5];
1156
	$out4_pass = $pf_out4_pass[5];
1157
	$in4_pass_packets = $pf_in4_pass[3];
1158
	$out4_pass_packets = $pf_out4_pass[3];
1159 15cc0894 Seth Mos
	$in6_pass = $pf_in6_pass[5];
1160
	$out6_pass = $pf_out6_pass[5];
1161
	$in6_pass_packets = $pf_in6_pass[3];
1162
	$out6_pass_packets = $pf_out6_pass[3];
1163
	$ifinfo['inbytespass'] = $in4_pass + $in6_pass;
1164
	$ifinfo['outbytespass'] = $out4_pass + $out6_pass;
1165
	$ifinfo['inpktspass'] = $in4_pass_packets + $in6_pass_packets;
1166
	$ifinfo['outpktspass'] = $out4_pass_packets + $in6_pass_packets;
1167 01385b0c Scott Ullrich
1168 971eaab5 Seth Mos
	/* Block */
1169
	$pf_in4_block = preg_split("/ +/", $pfctlstats[4]);
1170
	$pf_out4_block = preg_split("/ +/", $pfctlstats[6]);
1171 15cc0894 Seth Mos
	$pf_in6_block = preg_split("/ +/", $pfctlstats[8]);
1172
	$pf_out6_block = preg_split("/ +/", $pfctlstats[10]);
1173 971eaab5 Seth Mos
	$in4_block = $pf_in4_block[5];
1174
	$out4_block = $pf_out4_block[5];
1175
	$in4_block_packets = $pf_in4_block[3];
1176
	$out4_block_packets = $pf_out4_block[3];
1177 15cc0894 Seth Mos
	$in6_block = $pf_in6_block[5];
1178
	$out6_block = $pf_out6_block[5];
1179
	$in6_block_packets = $pf_in6_block[3];
1180
	$out6_block_packets = $pf_out6_block[3];
1181
	$ifinfo['inbytesblock'] = $in4_block + $in6_block;
1182
	$ifinfo['outbytesblock'] = $out4_block + $out6_block;
1183
	$ifinfo['inpktsblock'] = $in4_block_packets + $in6_block_packets;
1184
	$ifinfo['outpktsblock'] = $out4_block_packets + $out6_block_packets;
1185
1186
	$ifinfo['inbytes'] = $in4_pass + $in6_pass;
1187
	$ifinfo['outbytes'] = $out4_pass + $out6_pass;
1188
	$ifinfo['inpkts'] = $in4_pass_packets + $in6_pass_packets;
1189
	$ifinfo['outpkts'] = $in4_pass_packets + $out6_pass_packets;
1190 01385b0c Scott Ullrich
		
1191 63161b3f Ermal Luçi
	$ifconfiginfo = "";
1192 59db783a gnhb
	$link_type = $config['interfaces'][$ifdescr]['ipaddr'];
1193
	switch ($link_type) {
1194 cb074893 Ermal Lu?i
	 /* DHCP? -> see if dhclient is up */
1195 67ee1ec5 Ermal Luçi
	case "dhcp":
1196
	case "carpdev-dhcp":
1197 20c79427 Ermal Lu?i
		/* see if dhclient is up */
1198 c4f31aca Ermal Lu?i
		if (find_dhclient_process($ifinfo['if']) <> "")
1199 20c79427 Ermal Lu?i
			$ifinfo['dhcplink'] = "up";
1200
		else
1201
			$ifinfo['dhcplink'] = "down";
1202 63161b3f Ermal Luçi
1203 67ee1ec5 Ermal Luçi
		break;
1204 febca7e8 Ermal
	/* PPPoE/PPTP/L2TP interface? -> get status from virtual interface */
1205 67ee1ec5 Ermal Luçi
	case "pppoe":
1206 febca7e8 Ermal
	case "pptp":
1207
	case "l2tp":
1208 cffe41cb Ermal
		if ($ifinfo['status'] == "up" && !isset($link0))
1209 59db783a gnhb
			/* get PPPoE link status for dial on demand */
1210 febca7e8 Ermal
			$ifinfo["{$link_type}link"] = "up";
1211 20c79427 Ermal Lu?i
		else
1212 febca7e8 Ermal
			$ifinfo["{$link_type}link"] = "down";
1213 6189988d Scott Dale
1214 67ee1ec5 Ermal Luçi
		break;
1215 8eb2f33a Scott Ullrich
	/* PPP interface? -> get uptime for this session and cumulative uptime from the persistant log file in conf */
1216 9ebe7028 gnhb
	case "ppp":
1217 cffe41cb Ermal
		if ($ifinfo['status'] == "up")
1218 c90f2471 gnhb
			$ifinfo['ppplink'] = "up";
1219
		else
1220
			$ifinfo['ppplink'] = "down" ;
1221
1222
		if (empty($ifinfo['status']))
1223
			$ifinfo['status'] = "down";
1224 badbe349 gnhb
			
1225
		if (is_array($config['ppps']['ppp']) && count($config['ppps']['ppp'])) {
1226
			foreach ($config['ppps']['ppp'] as $pppid => $ppp) {
1227 f7480829 gnhb
				if ($config['interfaces'][$ifdescr]['if'] == $ppp['if'])
1228 badbe349 gnhb
					break;
1229
			}
1230
		}
1231 42809b4a gnhb
		$dev = $ppp['ports'];
1232 f7480829 gnhb
		if ($config['interfaces'][$ifdescr]['if'] != $ppp['if'] || empty($dev))
1233 611ae852 Ermal
			break;
1234 59db783a gnhb
		if (!file_exists($dev)) {
1235 c90f2471 gnhb
			$ifinfo['nodevice'] = 1;
1236 7d1b238c Carlos Eduardo Ramos
			$ifinfo['pppinfo'] = $dev . " " . gettext("device not present! Is the modem attached to the system?");	
1237 611ae852 Ermal
		}
1238
		// Calculate cumulative uptime for PPP link. Useful for connections that have per minute/hour contracts so you don't go over!
1239 59db783a gnhb
		if (isset($ppp['uptime']))
1240
			$ifinfo['ppp_uptime_accumulated'] = "(".get_ppp_uptime($ifinfo['if']).")";
1241 67ee1ec5 Ermal Luçi
		break;
1242 63161b3f Ermal Luçi
	default:
1243
		break;
1244 6189988d Scott Dale
	}
1245 59db783a gnhb
	
1246
	if (file_exists("{$g['varrun_path']}/{$link_type}_{$ifdescr}.pid")) {
1247
		$sec = trim(`/usr/local/sbin/ppp-uptime.sh {$ifinfo['if']}`);
1248
		$ifinfo['ppp_uptime'] = convert_seconds_to_hms($sec);
1249
	}
1250
	
1251 6189988d Scott Dale
	if ($ifinfo['status'] == "up") {
1252
		/* try to determine media with ifconfig */
1253
		unset($ifconfiginfo);
1254 818a6b7d Seth Mos
		exec("/sbin/ifconfig " . $ifinfo['if'], $ifconfiginfo);
1255
		$wifconfiginfo = array();
1256
		if(is_interface_wireless($ifdescr)) {
1257
			exec("/sbin/ifconfig {$ifinfo['if']} list sta", $wifconfiginfo);
1258
			array_shift($wifconfiginfo);
1259
		}
1260 6189988d Scott Dale
		$matches = "";
1261
		foreach ($ifconfiginfo as $ici) {
1262
1263
			/* don't list media/speed for wireless cards, as it always
1264
			   displays 2 Mbps even though clients can connect at 11 Mbps */
1265
			if (preg_match("/media: .*? \((.*?)\)/", $ici, $matches)) {
1266
				$ifinfo['media'] = $matches[1];
1267
			} else if (preg_match("/media: Ethernet (.*)/", $ici, $matches)) {
1268
				$ifinfo['media'] = $matches[1];
1269
			} else if (preg_match("/media: IEEE 802.11 Wireless Ethernet (.*)/", $ici, $matches)) {
1270
				$ifinfo['media'] = $matches[1];
1271
			}
1272
1273
			if (preg_match("/status: (.*)$/", $ici, $matches)) {
1274
				if ($matches[1] != "active")
1275
					$ifinfo['status'] = $matches[1];
1276 7d1b238c Carlos Eduardo Ramos
				if($ifinfo['status'] == gettext("running"))
1277
					$ifinfo['status'] = gettext("up");
1278 6189988d Scott Dale
			}
1279
			if (preg_match("/channel (\S*)/", $ici, $matches)) {
1280
				$ifinfo['channel'] = $matches[1];
1281
			}
1282
			if (preg_match("/ssid (\".*?\"|\S*)/", $ici, $matches)) {
1283
				if ($matches[1][0] == '"')
1284
					$ifinfo['ssid'] = substr($matches[1], 1, -1);
1285
				else
1286
					$ifinfo['ssid'] = $matches[1];
1287
			}
1288
		}
1289 818a6b7d Seth Mos
		foreach($wifconfiginfo as $ici) {
1290
			$elements = preg_split("/[ ]+/i", $ici);
1291
			if ($elements[0] != "") {
1292
				$ifinfo['bssid'] = $elements[0];
1293
			}
1294
			if ($elements[3] != "") {
1295
				$ifinfo['rate'] = $elements[3];
1296
			}
1297
			if ($elements[4] != "") {
1298
				$ifinfo['rssi'] = $elements[4];
1299
			}
1300
1301
		}
1302 67ee1ec5 Ermal Luçi
		/* lookup the gateway */
1303 2bbb79cb Seth Mos
		if (interface_has_gateway($ifdescr)) {
1304 ebdbdbc2 gnhb
			$ifinfo['gateway'] = get_interface_gateway($ifdescr);
1305 2bbb79cb Seth Mos
			$ifinfo['gatewayv6'] = get_interface_gateway_v6($ifdescr);
1306
		}
1307 6189988d Scott Dale
	}
1308
1309
	$bridge = "";
1310 7ec05d27 Ermal Luçi
	$bridge = link_interface_to_bridge($ifdescr);
1311 6189988d Scott Dale
	if($bridge) {
1312
		$bridge_text = `/sbin/ifconfig {$bridge}`;
1313
		if(stristr($bridge_text, "blocking") <> false) {
1314 7d1b238c Carlos Eduardo Ramos
			$ifinfo['bridge'] = "<b><font color='red'>" . gettext("blocking") . "</font></b> - " . gettext("check for ethernet loops");
1315 6189988d Scott Dale
			$ifinfo['bridgeint'] = $bridge;
1316
		} else if(stristr($bridge_text, "learning") <> false) {
1317 7d1b238c Carlos Eduardo Ramos
			$ifinfo['bridge'] = gettext("learning");
1318 6189988d Scott Dale
			$ifinfo['bridgeint'] = $bridge;
1319
		} else if(stristr($bridge_text, "forwarding") <> false) {
1320 7d1b238c Carlos Eduardo Ramos
			$ifinfo['bridge'] = gettext("forwarding");
1321 6189988d Scott Dale
			$ifinfo['bridgeint'] = $bridge;
1322
		}
1323
	}
1324
1325
	return $ifinfo;
1326
}
1327
1328
//returns cpu speed of processor. Good for determining capabilities of machine
1329
function get_cpu_speed() {
1330
	 return exec("sysctl hw.clockrate | awk '{ print $2 }'");
1331
}
1332 fab7ff44 Bill Marquette
1333 a5f94f14 Scott Ullrich
function add_hostname_to_watch($hostname) {
1334 c941ea1c Seth Mos
	if(!is_dir("/var/db/dnscache")) {
1335
		mkdir("/var/db/dnscache");
1336
	}
1337 5f31bf01 Seth Mos
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1338 581e772e Seth Mos
		$domrecords = array();
1339
		$domips = array();
1340
		exec("host -t A $hostname", $domrecords, $rethost);
1341
		if($rethost == 0) {
1342
			foreach($domrecords as $domr) {
1343
				$doml = explode(" ", $domr);
1344
				$domip = $doml[3];
1345
				/* fill array with domain ip addresses */
1346
				if(is_ipaddr($domip)) {
1347
					$domips[] = $domip;
1348
				}
1349
			}
1350
		}
1351
		sort($domips);
1352
		$contents = "";
1353
		if(! empty($domips)) {
1354 162c059e Seth Mos
			foreach($domips as $ip) {
1355
				$contents .= "$ip\n";
1356
			}
1357 581e772e Seth Mos
		}
1358
		file_put_contents("/var/db/dnscache/$hostname", $contents);
1359 a5f94f14 Scott Ullrich
	}
1360
}
1361
1362 5ed54b93 Seth Mos
function is_fqdn($fqdn) {
1363
	$hostname = false;
1364
	if(preg_match("/[-A-Z0-9\.]+\.[-A-Z0-9\.]+/i", $fqdn)) {
1365
		$hostname = true;
1366
	}
1367
	if(preg_match("/\.\./", $fqdn)) {
1368
		$hostname = false;
1369
	}
1370 3aae364d Scott Ullrich
	if(preg_match("/^\./i", $fqdn)) { 
1371 5ed54b93 Seth Mos
		$hostname = false;
1372
	}
1373 c941ea1c Seth Mos
	if(preg_match("/\//i", $fqdn)) {
1374
		$hostname = false;
1375
	}
1376 5ed54b93 Seth Mos
	return($hostname);
1377
}
1378
1379 639aaa95 Bill Marquette
function pfsense_default_state_size() {
1380
  /* get system memory amount */
1381
  $memory = get_memory();
1382
  $avail = $memory[0];
1383
  /* Be cautious and only allocate 10% of system memory to the state table */
1384
  $max_states = (int) ($avail/10)*1000;
1385
  return $max_states;
1386
}
1387
1388 fb586a16 jim-p
function pfsense_default_table_entries_size() {
1389
	$current = `pfctl -sm | grep table-entries | awk '{print $4};'`;
1390
	return $current;
1391
}
1392
1393 7723c7e0 Seth Mos
/* Compare the current hostname DNS to the DNS cache we made
1394
 * if it has changed we return the old records
1395
 * if no change we return true */
1396
function compare_hostname_to_dnscache($hostname) {
1397
	if(!is_dir("/var/db/dnscache")) {
1398
		mkdir("/var/db/dnscache");
1399
	}
1400
	$hostname = trim($hostname);
1401
	if(is_readable("/var/db/dnscache/{$hostname}")) {
1402
		$oldcontents = file_get_contents("/var/db/dnscache/{$hostname}");
1403
	} else {
1404
		$oldcontents = "";
1405
	}
1406
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1407
		$domrecords = array();
1408
		$domips = array();
1409
		exec("host -t A $hostname", $domrecords, $rethost);
1410
		if($rethost == 0) {
1411
			foreach($domrecords as $domr) {
1412
				$doml = explode(" ", $domr);
1413
				$domip = $doml[3];
1414
				/* fill array with domain ip addresses */
1415
				if(is_ipaddr($domip)) {
1416
					$domips[] = $domip;
1417
				}
1418
			}
1419
		}
1420
		sort($domips);
1421
		$contents = "";
1422
		if(! empty($domips)) {
1423
			foreach($domips as $ip) {
1424
				$contents .= "$ip\n";
1425
			}
1426
		}
1427
	}
1428
1429
	if(trim($oldcontents) != trim($contents)) {
1430 a5f91ef4 Seth Mos
		if($g['debug']) {
1431 addc0439 Renato Botelho
			log_error(sprintf(gettext('DNSCACHE: Found old IP %1$s and new IP %2$s'), $oldcontents, $contents));
1432 a5f91ef4 Seth Mos
		}
1433 7723c7e0 Seth Mos
		return ($oldcontents);
1434
	} else {
1435
		return false;
1436
	}
1437
}
1438
1439 09f18f59 jim-p
/*
1440
 * load_glxsb() - Load the glxsb crypto module if enabled in config.
1441
 */
1442
function load_glxsb() {
1443
	global $config, $g;
1444
	$is_loaded = `/sbin/kldstat | /usr/bin/grep -c glxsb`;
1445
	if (isset($config['system']['glxsb_enable']) && ($is_loaded == 0)) {
1446
		mwexec("/sbin/kldload glxsb");
1447
	}
1448
}
1449
1450 cde4f5d3 Scott Ullrich
/****f* pfsense-utils/isvm
1451
 * NAME
1452
 *   isvm
1453
 * INPUTS
1454
 *	 none
1455
 * RESULT
1456
 *   returns true if machine is running under a virtual environment
1457
 ******/
1458
function isvm() {
1459
	$virtualenvs = array("vmware", "parallels", "qemu", "bochs", "plex86");
1460 6f76920c thompsa
	$bios_vendor = strtolower(`/bin/kenv | /usr/bin/awk -F= '/smbios.bios.vendor/ {print $2}'`);
1461 cde4f5d3 Scott Ullrich
	if(in_array($bios_vendor, $virtualenvs)) 
1462
		return true;
1463
	else
1464
		return false;
1465
}
1466
1467 e0d0eb71 Scott Ullrich
function get_freebsd_version() {
1468 9a7f6731 Ermal
	$version = php_uname("r");
1469
	return $version[0];
1470 e0d0eb71 Scott Ullrich
}
1471
1472 d164643a jim-p
function download_file_with_progress_bar($url_file, $destination_file, $readbody = 'read_body', $connect_timeout=60, $timeout=0) {
1473 42c07003 Ermal
        global $ch, $fout, $file_size, $downloaded, $config;
1474 b31da21e Scott Ullrich
        $file_size  = 1;
1475
        $downloaded = 1;
1476
        /* open destination file */
1477
        $fout = fopen($destination_file, "wb");
1478
1479
        /*
1480
         *      Originally by Author: Keyvan Minoukadeh
1481
         *      Modified by Scott Ullrich to return Content-Length size
1482
         */
1483
1484
        $ch = curl_init();
1485
        curl_setopt($ch, CURLOPT_URL, $url_file);
1486
        curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
1487 0f280d2a jim-p
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1488
        /* Don't verify SSL peers since we don't have the certificates to do so. */
1489
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1490 b31da21e Scott Ullrich
        curl_setopt($ch, CURLOPT_WRITEFUNCTION, $readbody);
1491
        curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
1492 d164643a jim-p
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connect_timeout);
1493
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1494 b31da21e Scott Ullrich
1495 42c07003 Ermal
	if (!empty($config['system']['proxyurl'])) {
1496
		curl_setopt($ch, CURLOPT_PROXY, $config['system']['proxyurl']);
1497
		if (!empty($config['system']['proxyport']))
1498
			curl_setopt($ch, CURLOPT_PROXYPORT, $config['system']['proxyport']);
1499
		if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
1500
			@curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY | CURLAUTH_ANYSAFE);
1501 2a57a4d1 Ermal
			curl_setopt($ch, CURLOPT_PROXYUSERPWD, "{$config['system']['proxyuser']}:{$config['system']['proxypass']}");
1502 42c07003 Ermal
		}
1503
	}
1504
1505 4c37209a jim-p
        @curl_exec($ch);
1506 b31da21e Scott Ullrich
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1507
        if($fout)
1508
                fclose($fout);
1509
        curl_close($ch);
1510
        return ($http_code == 200) ? true : $http_code;
1511
}
1512
1513
function read_header($ch, $string) {
1514
        global $file_size, $fout;
1515
        $length = strlen($string);
1516
        $regs = "";
1517
        ereg("(Content-Length:) (.*)", $string, $regs);
1518
        if($regs[2] <> "") {
1519
                $file_size = intval($regs[2]);
1520
        }
1521
        ob_flush();
1522
        return $length;
1523
}
1524
1525
function read_body($ch, $string) {
1526
        global $fout, $file_size, $downloaded, $sendto, $static_status, $static_output, $lastseen;
1527 a0e157e9 Scott Ullrich
		global $pkg_interface;
1528 b31da21e Scott Ullrich
        $length = strlen($string);
1529
        $downloaded += intval($length);
1530 f444c396 Erik Fonnesbeck
        if($file_size > 0) {
1531
                $downloadProgress = round(100 * (1 - $downloaded / $file_size), 0);
1532
                $downloadProgress = 100 - $downloadProgress;
1533
        } else
1534
                $downloadProgress = 0;
1535 b31da21e Scott Ullrich
        if($lastseen <> $downloadProgress and $downloadProgress < 101) {
1536
                if($sendto == "status") {
1537 a0e157e9 Scott Ullrich
					if($pkg_interface == "console") {
1538 61f0a115 Scott Ullrich
						if(substr($downloadProgress,2,1) == "0" || count($downloadProgress) < 2) {
1539 a0e157e9 Scott Ullrich
                        	$tostatus = $static_status . $downloadProgress . "%";
1540
                        	update_status($tostatus);
1541
						}
1542
					} else {
1543 b31da21e Scott Ullrich
                        $tostatus = $static_status . $downloadProgress . "%";
1544 a0e157e9 Scott Ullrich
                        update_status($tostatus);						
1545
					}
1546 b31da21e Scott Ullrich
                } else {
1547 a0e157e9 Scott Ullrich
					if($pkg_interface == "console") {
1548 61f0a115 Scott Ullrich
						if(substr($downloadProgress,2,1) == "0" || count($downloadProgress) < 2) {
1549 a0e157e9 Scott Ullrich
                        	$tooutput = $static_output . $downloadProgress . "%";
1550
                        	update_output_window($tooutput);
1551
						}
1552
					} else {
1553 b31da21e Scott Ullrich
                        $tooutput = $static_output . $downloadProgress . "%";
1554
                        update_output_window($tooutput);
1555 a0e157e9 Scott Ullrich
					}
1556 b31da21e Scott Ullrich
                }
1557
                update_progress_bar($downloadProgress);
1558
                $lastseen = $downloadProgress;
1559
        }
1560
        if($fout)
1561
                fwrite($fout, $string);
1562
        ob_flush();
1563
        return $length;
1564
}
1565
1566 84677257 Scott Ullrich
/*
1567
 *   update_output_window: update bottom textarea dynamically.
1568
 */
1569
function update_output_window($text) {
1570
        global $pkg_interface;
1571
        $log = ereg_replace("\n", "\\n", $text);
1572 fa15f4ae Ermal
        if($pkg_interface != "console") {
1573 c2272d6d Scott Ullrich
                echo "\n<script language=\"JavaScript\">\nthis.document.forms[0].output.value = \"" . $log . "\";\n";
1574
				echo "this.document.forms[0].output.scrollTop = this.document.forms[0].output.scrollHeight;\n";	
1575
				echo "</script>";
1576 84677257 Scott Ullrich
        }
1577
        /* ensure that contents are written out */
1578
        ob_flush();
1579
}
1580
1581
/*
1582
 *   update_output_window: update top textarea dynamically.
1583
 */
1584
function update_status($status) {
1585
        global $pkg_interface;
1586
        if($pkg_interface == "console") {
1587
                echo $status . "\n";
1588
        } else {
1589
                echo "\n<script type=\"text/javascript\">this.document.forms[0].status.value=\"" . $status . "\";</script>";
1590
        }
1591
        /* ensure that contents are written out */
1592
        ob_flush();
1593
}
1594
1595
/*
1596
 * update_progress_bar($percent): updates the javascript driven progress bar.
1597
 */
1598
function update_progress_bar($percent) {
1599
        global $pkg_interface;
1600
        if($percent > 100) $percent = 1;
1601
        if($pkg_interface <> "console") {
1602
                echo "\n<script type=\"text/javascript\" language=\"javascript\">";
1603
                echo "\ndocument.progressbar.style.width='" . $percent . "%';";
1604
                echo "\n</script>";
1605
        } else {
1606
                echo " {$percent}%";
1607
        }
1608
}
1609
1610 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. */
1611
if(!function_exists("split")) {
1612
	function split($seperator, $haystack, $limit = null) {
1613
		return preg_split($seperator, $haystack, $limit);
1614
	}
1615
}
1616
1617 f1ac1733 Erik Fonnesbeck
function update_alias_names_upon_change($section, $field, $new_alias_name, $origname) {
1618 978fd2e8 Scott Ullrich
	global $g, $config, $pconfig, $debug;
1619 b6db8ea3 sullrich
	if(!$origname) 
1620
		return;
1621
1622 f1ac1733 Erik Fonnesbeck
	$sectionref = &$config;
1623
	foreach($section as $sectionname) {
1624
		if(is_array($sectionref) && isset($sectionref[$sectionname]))
1625
			$sectionref = &$sectionref[$sectionname];
1626
		else
1627
			return;
1628
	}
1629
1630 b6db8ea3 sullrich
	if($debug) $fd = fopen("{$g['tmp_path']}/print_r", "a");
1631
	if($debug) fwrite($fd, print_r($pconfig, true));
1632
1633 f1ac1733 Erik Fonnesbeck
	if(is_array($sectionref)) {
1634
		foreach($sectionref as $itemkey => $item) {
1635
			if($debug) fwrite($fd, "$itemkey\n");
1636
1637
			$fieldfound = true;
1638
			$fieldref = &$sectionref[$itemkey];
1639
			foreach($field as $fieldname) {
1640
				if(is_array($fieldref) && isset($fieldref[$fieldname]))
1641
					$fieldref = &$fieldref[$fieldname];
1642
				else {
1643
					$fieldfound = false;
1644
					break;
1645
				}
1646 b6db8ea3 sullrich
			}
1647 f1ac1733 Erik Fonnesbeck
			if($fieldfound && $fieldref == $origname) {
1648 b6db8ea3 sullrich
				if($debug) fwrite($fd, "Setting old alias value $origname to $new_alias_name\n");
1649 f1ac1733 Erik Fonnesbeck
				$fieldref = $new_alias_name;
1650 b6db8ea3 sullrich
			}
1651
		}
1652
	}
1653
1654
	if($debug) fclose($fd);
1655
1656
}
1657 f6ba4bd1 Scott Ullrich
1658
function update_alias_url_data() {
1659
	global $config, $g;
1660 e5953c68 Ermal
1661 f6ba4bd1 Scott Ullrich
	/* item is a url type */
1662
	$lockkey = lock('config');
1663 e5953c68 Ermal
	if (is_array($config['aliases']['alias'])) {
1664
		foreach ($config['aliases']['alias'] as $x => $alias) {
1665
			if (empty($alias['aliasurl']))
1666
				continue;
1667
1668 f6ba4bd1 Scott Ullrich
			/* fetch down and add in */
1669
			$isfirst = 0;
1670
			$temp_filename = tempnam("{$g['tmp_path']}/", "alias_import");
1671
			unlink($temp_filename);
1672
			$fda = fopen("{$g['tmp_path']}/tmpfetch","w");
1673
			fwrite($fda, "/usr/bin/fetch -q -o \"{$temp_filename}/aliases\" \"" . $config['aliases']['alias'][$x]['aliasurl'] . "\"");
1674
			fclose($fda);
1675
			mwexec("/bin/mkdir -p {$temp_filename}");
1676
			mwexec("/usr/bin/fetch -q -o \"{$temp_filename}/aliases\" \"" . $config['aliases']['alias'][$x]['aliasurl'] . "\"");
1677
			/* if the item is tar gzipped then extract */
1678 e5953c68 Ermal
			if(stristr($alias['aliasurl'], ".tgz"))
1679 f6ba4bd1 Scott Ullrich
				process_alias_tgz($temp_filename);
1680 e5953c68 Ermal
			else if(stristr($alias['aliasurl'], ".zip"))
1681 10189b2a Scott Ullrich
				process_alias_unzip($temp_filename);
1682 f6ba4bd1 Scott Ullrich
			if(file_exists("{$temp_filename}/aliases")) {
1683
				$file_contents = file_get_contents("{$temp_filename}/aliases");
1684
				$file_contents = str_replace("#", "\n#", $file_contents);
1685
				$file_contents_split = split("\n", $file_contents);
1686
				foreach($file_contents_split as $fc) {
1687
					$tmp = trim($fc);
1688
					if(stristr($fc, "#")) {
1689
						$tmp_split = split("#", $tmp);
1690
						$tmp = trim($tmp_split[0]);
1691
					}
1692
					if(trim($tmp) <> "") {
1693
						if($isfirst == 1)
1694
							$address .= " ";
1695
						$address .= $tmp;
1696
						$isfirst = 1;
1697
					}
1698
				}
1699 e5953c68 Ermal
				if($isfirst > 0) {
1700 f6ba4bd1 Scott Ullrich
					$config['aliases']['alias'][$x]['address'] = $address;
1701
					$updated = true;
1702
				}
1703
				mwexec("/bin/rm -rf {$temp_filename}");
1704
			}
1705
		}
1706
	}
1707
	if($updated)
1708
		write_config();
1709
	unlock($lockkey);
1710
}
1711
1712 10189b2a Scott Ullrich
function process_alias_unzip($temp_filename) {
1713
	if(!file_exists("/usr/local/bin/unzip"))
1714
		return;
1715
	mwexec("/bin/mv {$temp_filename}/aliases {$temp_filename}/aliases.zip");
1716
	mwexec("/usr/local/bin/unzip {$temp_filename}/aliases.tgz -d {$temp_filename}/aliases/");
1717
	unlink("{$temp_filename}/aliases.zip");
1718
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1719
	/* foreach through all extracted files and build up aliases file */
1720
	$fd = fopen("{$temp_filename}/aliases", "w");
1721
	foreach($files_to_process as $f2p) {
1722
		$file_contents = file_get_contents($f2p);
1723
		fwrite($fd, $file_contents);
1724
		unlink($f2p);
1725
	}
1726
	fclose($fd);
1727
}
1728
1729 f6ba4bd1 Scott Ullrich
function process_alias_tgz($temp_filename) {
1730 10189b2a Scott Ullrich
	if(!file_exists("/usr/bin/tar"))
1731
		return;
1732 f6ba4bd1 Scott Ullrich
	mwexec("/bin/mv {$temp_filename}/aliases {$temp_filename}/aliases.tgz");
1733
	mwexec("/usr/bin/tar xzf {$temp_filename}/aliases.tgz -C {$temp_filename}/aliases/");
1734
	unlink("{$temp_filename}/aliases.tgz");
1735
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1736
	/* foreach through all extracted files and build up aliases file */
1737
	$fd = fopen("{$temp_filename}/aliases", "w");
1738
	foreach($files_to_process as $f2p) {
1739
		$file_contents = file_get_contents($f2p);
1740
		fwrite($fd, $file_contents);
1741
		unlink($f2p);
1742
	}
1743
	fclose($fd);
1744
}
1745
1746 a76c1c45 jim-p
function version_compare_dates($a, $b) {
1747
	$a_time = strtotime($a);
1748
	$b_time = strtotime($b);
1749
1750
	if ((!$a_time) || (!$b_time)) {
1751
		return FALSE;
1752
	} else {
1753 bda131b2 jim-p
		if ($a_time < $b_time)
1754 a76c1c45 jim-p
			return -1;
1755 bda131b2 jim-p
		elseif ($$a_time == $b_time)
1756 a76c1c45 jim-p
			return 0;
1757
		else
1758
			return 1;
1759
	}
1760
}
1761
function version_get_string_value($a) {
1762
	$strs = array(
1763
		0 => "ALPHA-ALPHA",
1764
		2 => "ALPHA",
1765
		3 => "BETA",
1766
		4 => "B",
1767 5eb03383 jim-p
		5 => "C",
1768
		6 => "D",
1769
		7 => "RC",
1770
		8 => "RELEASE"
1771 a76c1c45 jim-p
	);
1772
	$major = 0;
1773
	$minor = 0;
1774
	foreach ($strs as $num => $str) {
1775
		if (substr($a, 0, strlen($str)) == $str) {
1776
			$major = $num;
1777
			$n = substr($a, strlen($str));
1778
			if (is_numeric($n))
1779
				$minor = $n;
1780
			break;
1781
		}
1782
	}
1783
	return "{$major}.{$minor}";
1784
}
1785
function version_compare_string($a, $b) {
1786
	return version_compare_numeric(version_get_string_value($a), version_get_string_value($b));
1787
}
1788
function version_compare_numeric($a, $b) {
1789
	$a_arr = explode('.', rtrim($a, '.0'));
1790
	$b_arr = explode('.', rtrim($b, '.0'));
1791
1792
	foreach ($a_arr as $n => $val) {
1793
		if (array_key_exists($n, $b_arr)) {
1794
			// So far so good, both have values at this minor version level. Compare.
1795
			if ($val > $b_arr[$n])
1796
				return 1;
1797
			elseif ($val < $b_arr[$n])
1798
				return -1;
1799
		} else {
1800
			// a is greater, since b doesn't have any minor version here.
1801
			return 1;
1802
		}
1803
	}
1804
	if (count($b_arr) > count($a_arr)) {
1805
		// b is longer than a, so it must be greater.
1806
		return -1;
1807
	} else {
1808
		// Both a and b are of equal length and value.
1809
		return 0;
1810
	}
1811
}
1812
function pfs_version_compare($cur_time, $cur_text, $remote) {
1813
	// First try date compare
1814 bda131b2 jim-p
	$v = version_compare_dates($cur_time, $remote);
1815 a76c1c45 jim-p
	if ($v === FALSE) {
1816
		// If that fails, try to compare by string
1817
		// Before anything else, simply test if the strings are equal
1818 b009b153 jim-p
		if (($cur_text == $remote) || ($cur_time == $remote))
1819 a76c1c45 jim-p
			return 0;
1820
		list($cur_num, $cur_str) = explode('-', $cur_text);
1821
		list($rem_num, $rem_str) = explode('-', $remote);
1822
1823
		// First try to compare the numeric parts of the version string.
1824
		$v = version_compare_numeric($cur_num, $rem_num);
1825
1826
		// If the numeric parts are the same, compare the string parts.
1827
		if ($v == 0)
1828
			return version_compare_string($cur_str, $rem_str);
1829
	}
1830
	return $v;
1831
}
1832 c7de8be4 jim-p
function process_alias_urltable($name, $url, $freq, $forceupdate=false) {
1833
	$urltable_prefix = "/var/db/aliastables/";
1834
	$urltable_filename = $urltable_prefix . $name . ".txt";
1835
1836
	// Make the aliases directory if it doesn't exist
1837
	if (!file_exists($urltable_prefix)) {
1838
		mkdir($urltable_prefix);
1839
	} elseif (!is_dir($urltable_prefix)) {
1840
		unlink($urltable_prefix);
1841
		mkdir($urltable_prefix);
1842
	}
1843
1844
	// If the file doesn't exist or is older than update_freq days, fetch a new copy.
1845
	if (!file_exists($urltable_filename)
1846
		|| ((time() - filemtime($urltable_filename)) > ($freq * 86400))
1847
		|| $forceupdate) {
1848
1849
		// Try to fetch the URL supplied
1850
		conf_mount_rw();
1851
		unlink_if_exists($urltable_filename . ".tmp");
1852
		// Use fetch to grab data since these may be large files, we don't want to process them through PHP if we can help it.
1853
		mwexec("/usr/bin/fetch -q -o " . escapeshellarg($urltable_filename . ".tmp") . " " . escapeshellarg($url));
1854
		// Remove comments. Might need some grep-fu to only allow lines that look like IPs/subnets
1855
		mwexec("/usr/bin/grep -v '^#' " . escapeshellarg($urltable_filename . ".tmp") . " > " . escapeshellarg($urltable_filename));
1856
		unlink_if_exists($urltable_filename . ".tmp");
1857
		conf_mount_ro();
1858
		if (filesize($urltable_filename)) {
1859
			return true;
1860
		} else {
1861
			// If it's unfetchable or an empty file, bail
1862
			return false;
1863
		}
1864
	} else {
1865
		// File exists, and it doesn't need updated.
1866
		return -1;
1867
	}
1868
}
1869 08fd5444 jim-p
function get_real_slice_from_glabel($label) {
1870
	$label = escapeshellarg($label);
1871
	return trim(`/sbin/glabel list | /usr/bin/grep -B2 ufs/{$label} | /usr/bin/head -n 1 | /usr/bin/cut -f3 -d' '`);
1872
}
1873
function nanobsd_get_boot_slice() {
1874
	return trim(`/sbin/mount | /usr/bin/grep pfsense | /usr/bin/cut -d'/' -f4 | /usr/bin/cut -d' ' -f1`);
1875
}
1876
function nanobsd_get_boot_drive() {
1877
	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`);
1878
}
1879
function nanobsd_get_active_slice() {
1880
	$boot_drive = nanobsd_get_boot_drive();
1881
	$active = trim(`gpart show $boot_drive | grep '\[active\]' | awk '{print $3;}'`);
1882
1883
	return "{$boot_drive}s{$active}";
1884
}
1885
function nanobsd_get_size() {
1886
	return strtoupper(file_get_contents("/etc/nanosize.txt"));
1887
}
1888 2b5f276f jim-p
function nanobsd_switch_boot_slice() {
1889 08fd5444 jim-p
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
1890
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
1891
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
1892
	nanobsd_detect_slice_info();
1893
1894 2b5f276f jim-p
	if ($BOOTFLASH == $ACTIVE_SLICE) {
1895
		$slice = $TOFLASH;
1896
	} else {
1897
		$slice = $BOOTFLASH;
1898
	}
1899
1900 08fd5444 jim-p
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
1901
	ob_implicit_flush(1);
1902
	if(strstr($slice, "s2")) {
1903
		$ASLICE="2";
1904
		$AOLDSLICE="1";
1905
		$AGLABEL_SLICE="pfsense1";
1906
		$AUFS_ID="1";
1907
		$AOLD_UFS_ID="0";
1908
	} else {
1909
		$ASLICE="1";
1910
		$AOLDSLICE="2";
1911
		$AGLABEL_SLICE="pfsense0";
1912
		$AUFS_ID="0";
1913
		$AOLD_UFS_ID="1";
1914
	}
1915
	$ATOFLASH="{$BOOT_DRIVE}s{$ASLICE}";
1916
	$ACOMPLETE_PATH="{$BOOT_DRIVE}s{$ASLICE}a";
1917
	$ABOOTFLASH="{$BOOT_DRIVE}s{$AOLDSLICE}";
1918
	conf_mount_rw();
1919
	exec("sysctl kern.geom.debugflags=16");
1920
	exec("gpart set -a active -i {$ASLICE} {$BOOT_DRIVE}");
1921
	exec("/usr/sbin/boot0cfg -s {$ASLICE} -v /dev/{$BOOT_DRIVE}");
1922 2b5f276f jim-p
	// We can't update these if they are mounted now.
1923
	if ($BOOTFLASH != $slice) {
1924
		exec("/sbin/tunefs -L ${AGLABEL_SLICE} /dev/$ACOMPLETE_PATH");
1925
		nanobsd_update_fstab($AGLABEL_SLICE, $ACOMPLETE_PATH, $AOLD_UFS_ID, $AUFS_ID);
1926
	}
1927 08fd5444 jim-p
	exec("/sbin/sysctl kern.geom.debugflags=0");
1928
	conf_mount_ro();
1929
}
1930 2b5f276f jim-p
function nanobsd_clone_slice() {
1931 08fd5444 jim-p
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
1932
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
1933
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
1934
	nanobsd_detect_slice_info();
1935
1936
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
1937
	ob_implicit_flush(1);
1938
	exec("/sbin/sysctl kern.geom.debugflags=16");
1939
	exec("/bin/dd if=/dev/zero of=/dev/{$TOFLASH} bs=1m count=1");
1940
	exec("/bin/dd if=/dev/{$BOOTFLASH} of=/dev/{$TOFLASH} bs=64k");
1941
	exec("/sbin/tunefs -L {$GLABEL_SLICE} /dev/{$COMPLETE_PATH}");
1942 2b5f276f jim-p
	$status = nanobsd_update_fstab($GLABEL_SLICE, $COMPLETE_PATH, $OLD_UFS_ID, $UFS_ID);
1943 08fd5444 jim-p
	exec("/sbin/sysctl kern.geom.debugflags=0");
1944
	if($status) {
1945
		return false;
1946
	} else {
1947
		return true;
1948
	}
1949
}
1950 2b5f276f jim-p
function nanobsd_update_fstab($gslice, $complete_path, $oldufs, $newufs) {
1951
	$tmppath = "/tmp/{$gslice}";
1952
	$fstabpath = "/tmp/{$gslice}/etc/fstab";
1953
1954
	exec("/bin/mkdir {$tmppath}");
1955
	exec("/sbin/fsck_ufs -y /dev/{$complete_path}");
1956
	exec("/sbin/mount /dev/ufs/{$gslice} {$tmppath}");
1957
	exec("/bin/cp /etc/fstab {$fstabpath}");
1958
1959
	if (!file_exists($fstabpath)) {
1960
		$fstab = <<<EOF
1961 9b1a8d98 Ermal
/dev/ufs/{$gslice} / ufs ro,noatime 1 1
1962
/dev/ufs/cf /cf ufs ro,noatime 1 1
1963 2b5f276f jim-p
EOF;
1964
		if (file_put_contents($fstabpath, $fstab))
1965
			$status = true;
1966
		else
1967
			$status = false;
1968
	} else {
1969
		$status = exec("sed -i \"\" \"s/pfsense{$oldufs}/pfsense{$newufs}/g\" {$fstabpath}");
1970
	}
1971
	exec("/sbin/umount {$tmppath}");
1972
	exec("/bin/rmdir {$tmppath}");
1973
1974
	return $status;
1975
}
1976 08fd5444 jim-p
function nanobsd_detect_slice_info() {
1977
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
1978
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
1979
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
1980 a76c1c45 jim-p
1981 08fd5444 jim-p
	$BOOT_DEVICE=nanobsd_get_boot_slice();
1982
	$REAL_BOOT_DEVICE=get_real_slice_from_glabel($BOOT_DEVICE);
1983
	$BOOT_DRIVE=nanobsd_get_boot_drive();
1984
	$ACTIVE_SLICE=nanobsd_get_active_slice();
1985
1986
	// Detect which slice is active and set information.
1987
	if(strstr($REAL_BOOT_DEVICE, "s1")) {
1988
		$SLICE="2";
1989
		$OLDSLICE="1";
1990
		$GLABEL_SLICE="pfsense1";
1991
		$UFS_ID="1";
1992
		$OLD_UFS_ID="0";
1993 a76c1c45 jim-p
1994 08fd5444 jim-p
	} else {
1995
		$SLICE="1";
1996
		$OLDSLICE="2";
1997
		$GLABEL_SLICE="pfsense0";
1998
		$UFS_ID="0";
1999
		$OLD_UFS_ID="1";
2000
	}
2001
	$TOFLASH="{$BOOT_DRIVE}s{$SLICE}";
2002
	$COMPLETE_PATH="{$BOOT_DRIVE}s{$SLICE}a";
2003
	$COMPLETE_BOOT_PATH="{$BOOT_DRIVE}s{$OLDSLICE}";
2004
	$BOOTFLASH="{$BOOT_DRIVE}s{$OLDSLICE}";
2005
}
2006 38080cc1 Scott Ullrich
2007 26c8cc72 jim-p
function nanobsd_friendly_slice_name($slicename) {
2008
	global $g;
2009
	return strtolower(str_ireplace('pfsense', $g['product_name'], $slicename));
2010
}
2011
2012 38080cc1 Scott Ullrich
function get_include_contents($filename) {
2013
    if (is_file($filename)) {
2014
        ob_start();
2015
        include $filename;
2016
        $contents = ob_get_contents();
2017
        ob_end_clean();
2018
        return $contents;
2019
    }
2020
    return false;
2021
}
2022
2023 3ffa8318 Renato Botelho
/* This xml 2 array function is courtesy of the php.net comment section on xml_parse.
2024
 * it is roughly 4 times faster then our existing pfSense parser but due to the large
2025
 * size of the RRD xml dumps this is required.
2026
 * The reason we do not use it for pfSense is that it does not know about array fields
2027
 * which causes it to fail on array fields with single items. Possible Todo?
2028
 */
2029
function xml2array($contents, $get_attributes = 1, $priority = 'tag')
2030
{
2031
    if (!function_exists('xml_parser_create'))
2032
    {
2033
        return array ();
2034
    }
2035
    $parser = xml_parser_create('');
2036
    xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
2037
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
2038
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
2039
    xml_parse_into_struct($parser, trim($contents), $xml_values);
2040
    xml_parser_free($parser);
2041
    if (!$xml_values)
2042
        return; //Hmm...
2043
    $xml_array = array ();
2044
    $parents = array ();
2045
    $opened_tags = array ();
2046
    $arr = array ();
2047
    $current = & $xml_array;
2048
    $repeated_tag_index = array ();
2049
    foreach ($xml_values as $data)
2050
    {
2051
        unset ($attributes, $value);
2052
        extract($data);
2053
        $result = array ();
2054
        $attributes_data = array ();
2055
        if (isset ($value))
2056
        {
2057
            if ($priority == 'tag')
2058
                $result = $value;
2059
            else
2060
                $result['value'] = $value;
2061
        }
2062
        if (isset ($attributes) and $get_attributes)
2063
        {
2064
            foreach ($attributes as $attr => $val)
2065
            {
2066
                if ($priority == 'tag')
2067
                    $attributes_data[$attr] = $val;
2068
                else
2069
                    $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
2070
            }
2071
        }
2072
        if ($type == "open")
2073
        {
2074
            $parent[$level -1] = & $current;
2075
            if (!is_array($current) or (!in_array($tag, array_keys($current))))
2076
            {
2077
                $current[$tag] = $result;
2078
                if ($attributes_data)
2079
                    $current[$tag . '_attr'] = $attributes_data;
2080
                $repeated_tag_index[$tag . '_' . $level] = 1;
2081
                $current = & $current[$tag];
2082
            }
2083
            else
2084
            {
2085
                if (isset ($current[$tag][0]))
2086
                {
2087
                    $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
2088
                    $repeated_tag_index[$tag . '_' . $level]++;
2089
                }
2090
                else
2091
                {
2092
                    $current[$tag] = array (
2093
                        $current[$tag],
2094
                        $result
2095
                    );
2096
                    $repeated_tag_index[$tag . '_' . $level] = 2;
2097
                    if (isset ($current[$tag . '_attr']))
2098
                    {
2099
                        $current[$tag]['0_attr'] = $current[$tag . '_attr'];
2100
                        unset ($current[$tag . '_attr']);
2101
                    }
2102
                }
2103
                $last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
2104
                $current = & $current[$tag][$last_item_index];
2105
            }
2106
        }
2107
        elseif ($type == "complete")
2108
        {
2109
            if (!isset ($current[$tag]))
2110
            {
2111
                $current[$tag] = $result;
2112
                $repeated_tag_index[$tag . '_' . $level] = 1;
2113
                if ($priority == 'tag' and $attributes_data)
2114
                    $current[$tag . '_attr'] = $attributes_data;
2115
            }
2116
            else
2117
            {
2118
                if (isset ($current[$tag][0]) and is_array($current[$tag]))
2119
                {
2120
                    $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
2121
                    if ($priority == 'tag' and $get_attributes and $attributes_data)
2122
                    {
2123
                        $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
2124
                    }
2125
                    $repeated_tag_index[$tag . '_' . $level]++;
2126
                }
2127
                else
2128
                {
2129
                    $current[$tag] = array (
2130
                        $current[$tag],
2131
                        $result
2132
                    );
2133
                    $repeated_tag_index[$tag . '_' . $level] = 1;
2134
                    if ($priority == 'tag' and $get_attributes)
2135
                    {
2136
                        if (isset ($current[$tag . '_attr']))
2137
                        {
2138
                            $current[$tag]['0_attr'] = $current[$tag . '_attr'];
2139
                            unset ($current[$tag . '_attr']);
2140
                        }
2141
                        if ($attributes_data)
2142
                        {
2143
                            $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
2144
                        }
2145
                    }
2146
                    $repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
2147
                }
2148
            }
2149
        }
2150
        elseif ($type == 'close')
2151
        {
2152
            $current = & $parent[$level -1];
2153
        }
2154
    }
2155
    return ($xml_array);
2156
}
2157
2158
function get_country_name($country_code) {
2159
	if ($country_code != "ALL" && strlen($country_code) != 2)
2160
		return "";
2161
2162
	$country_names_xml = "/usr/local/share/mobile-broadband-provider-info/iso_3166-1_list_en.xml";
2163
	$country_names_contents = file_get_contents($country_names_xml);
2164
	$country_names = xml2array($country_names_contents);
2165
2166
	if($country_code == "ALL") {
2167
		$country_list = array();
2168
		foreach($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2169
			$country_list[] = array( "code" => $country['ISO_3166-1_Alpha-2_Code_element'],
2170
						 "name" => ucwords(strtolower($country['ISO_3166-1_Country_name'])) );
2171
		}
2172
		return $country_list;
2173
	}
2174
2175
	foreach ($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2176
		if ($country['ISO_3166-1_Alpha-2_Code_element'] == strtoupper($country_code)) {
2177
			return ucwords(strtolower($country['ISO_3166-1_Country_name']));
2178
		}
2179
	}
2180
	return "";
2181
}
2182
2183 baaa8bb1 Erik Fonnesbeck
/* sort by interface only, retain the original order of rules that apply to
2184
   the same interface */
2185
function filter_rules_sort() {
2186
	global $config;
2187
2188
	/* mark each rule with the sequence number (to retain the order while sorting) */
2189
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2190
		$config['filter']['rule'][$i]['seq'] = $i;
2191
2192
	usort($config['filter']['rule'], "filter_rules_compare");
2193
2194
	/* strip the sequence numbers again */
2195
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2196
		unset($config['filter']['rule'][$i]['seq']);
2197
}
2198
function filter_rules_compare($a, $b) {
2199 cea355a5 Erik Fonnesbeck
	if (isset($a['floating']) && isset($b['floating']))
2200 baaa8bb1 Erik Fonnesbeck
		return $a['seq'] - $b['seq'];
2201
	else if (isset($a['floating']))
2202
		return -1;
2203
	else if (isset($b['floating']))
2204
		return 1;
2205 cea355a5 Erik Fonnesbeck
	else if ($a['interface'] == $b['interface'])
2206
		return $a['seq'] - $b['seq'];
2207 baaa8bb1 Erik Fonnesbeck
	else
2208
		return compare_interface_friendly_names($a['interface'], $b['interface']);
2209
}
2210
2211 22dae853 Seth Mos
function generate_ipv6_from_mac($mac) {
2212
	$elements = explode(":", $mac);
2213
	if(count($elements) <> 6)
2214
		return false;
2215
2216
	$i = 0;
2217 5aa28c86 Seth Mos
	$ipv6 = "fe80::";
2218 22dae853 Seth Mos
	foreach($elements as $byte) {
2219
		if($i == 0) {
2220
			$hexadecimal =  substr($byte, 1, 2);
2221
			$bitmap = base_convert($hexadecimal, 16, 2);
2222
			$bitmap = str_pad($bitmap, 4, "0", STR_PAD_LEFT);
2223
			$bitmap = substr($bitmap, 0, 2) ."1". substr($bitmap, 3,4);
2224
			$byte = substr($byte, 0, 1) . base_convert($bitmap, 2, 16);
2225
		}
2226
		$ipv6 .= $byte;
2227
		if($i == 1) {
2228
			$ipv6 .= ":";
2229
		}
2230
		if($i == 3) {
2231
			$ipv6 .= ":";
2232
		}
2233
		if($i == 2) {
2234
			$ipv6 .= "ff:fe";
2235
		}
2236
		
2237
		$i++;
2238
	}	
2239 fcdc8943 Seth Mos
	return $ipv6;
2240 22dae853 Seth Mos
}
2241 325e3163 Bill Marquette
2242 57f2840e Evgeny
/****f* pfsense-utils/load_mac_manufacturer_table
2243
 * NAME
2244
 *   load_mac_manufacturer_table
2245
 * INPUTS
2246
 *   none
2247
 * RESULT
2248
 *   returns associative array with MAC-Manufacturer pairs
2249
 ******/
2250
function load_mac_manufacturer_table() {
2251
	/* load MAC-Manufacture data from the file */
2252 62a29fe3 Ermal
	$macs = false;
2253
	if (file_exists("/usr/local/share/nmap/nmap-mac-prefixes"))
2254
		$macs=file("/usr/local/share/nmap/nmap-mac-prefixes");
2255 57f2840e Evgeny
	if ($macs){
2256
		foreach ($macs as $line){
2257
			if (preg_match('/([0-9A-Fa-f]{6}) (.*)$/', $line, $matches)){
2258 4450527f Evgeny
				/* store values like this $mac_man['000C29']='VMware' */
2259 57f2840e Evgeny
				$mac_man["$matches[1]"]=$matches[2];
2260
			}
2261
		}
2262
 		return $mac_man;
2263
	} else
2264
		return -1;
2265
2266
}
2267
2268 474f36d1 Scott Ullrich
/****f* pfsense-utils/is_ipaddr_configured
2269
 * NAME
2270
 *   is_ipaddr_configured
2271
 * INPUTS
2272
 *   IP Address to check.
2273
 * RESULT
2274
 *   returns true if the IP Address is
2275
 *   configured and present on this device.
2276
*/
2277
function is_ipaddr_configured($ipaddr) {
2278
	$interface_list_ips = get_configured_ip_addresses();
2279
	foreach($interface_list_ips as $ilips) {
2280
		if(strcasecmp($ipaddr, $ilips) == 0) 
2281
				return true;
2282
	}	
2283
}
2284
2285 e4a8ed97 Scott Ullrich
/****f* pfsense-utils/pfSense_handle_custom_code
2286
 * NAME
2287
 *   pfSense_handle_custom_code
2288
 * INPUTS
2289
 *   directory name to process
2290
 * RESULT
2291
 *   globs the directory and includes the files
2292
 */
2293 d65962a7 Scott Ullrich
function pfSense_handle_custom_code($src_dir) {
2294
	// Allow extending of the nat edit page and include custom input validation 
2295
	if(is_dir("$src_dir")) {
2296 3dbceb92 Scott Ullrich
		$cf = glob($src_dir . "/*.inc");
2297 d65962a7 Scott Ullrich
		foreach($cf as $nf) {
2298
			if($nf == "." || $nf == "..") 
2299
				continue;
2300
			// Include the extra handler
2301 3dbceb92 Scott Ullrich
			include("$nf");
2302 d65962a7 Scott Ullrich
		}
2303
	}
2304
}
2305
2306 58005e52 jim-p
?>