Projet

Général

Profil

Télécharger (82,6 ko) Statistiques
| Branche: | Tag: | Révision:

univnautes / etc / inc / pfsense-utils.inc @ 26d060bc

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_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
/****f* pfsense-utils/enable_hardware_offloading
147
 * NAME
148
 *   enable_hardware_offloading - Enable a NIC's supported hardware features.
149
 * INPUTS
150
 *   $interface	- string containing the physical interface to work on.
151
 * RESULT
152
 *   null
153
 * NOTES
154
 *   This function only supports the fxp driver's loadable microcode.
155
 ******/
156
function enable_hardware_offloading($interface) {
157
	global $g, $config;
158
159 51d5aad7 Ermal
	if(isset($config['system']['do_not_use_nic_microcode']))
160 d2eb5def Scott Ullrich
		return;
161 4d98f634 Scott Ullrich
162 3076becf Scott Ullrich
	/* translate wan, lan, opt -> real interface if needed */
163 a2934331 Scott Ullrich
	$int = get_real_interface($interface);
164 5fa78adc Renato Botelho
	if(empty($int))
165 3d063391 Ermal
		return;
166 51d5aad7 Ermal
	$int_family = preg_split("/[0-9]+/", $int);
167 3076becf Scott Ullrich
	$supported_ints = array('fxp');
168 a7c6604c Chris Buechler
	if (in_array($int_family, $supported_ints)) {
169 5fa78adc Renato Botelho
		if(does_interface_exist($int))
170 51d5aad7 Ermal
			pfSense_interface_flags($int, IFF_LINK0);
171 a2934331 Scott Ullrich
	}
172 3076becf Scott Ullrich
173
	return;
174
}
175
176 f7eb54e4 Scott Ullrich
/****f* pfsense-utils/interface_supports_polling
177
 * NAME
178
 *   checks to see if an interface supports polling according to man polling
179
 * INPUTS
180
 *
181
 * RESULT
182
 *   true or false
183
 * NOTES
184
 *
185
 ******/
186
function interface_supports_polling($iface) {
187 3d063391 Ermal
	$opts = pfSense_get_interface_addresses($iface);
188
	if (is_array($opts) && isset($opts['caps']['polling']))
189 f7eb54e4 Scott Ullrich
		return true;
190 3d063391 Ermal
191 f7eb54e4 Scott Ullrich
	return false;
192
}
193
194 3076becf Scott Ullrich
/****f* pfsense-utils/is_alias_inuse
195
 * NAME
196
 *   checks to see if an alias is currently in use by a rule
197
 * INPUTS
198
 *
199
 * RESULT
200
 *   true or false
201
 * NOTES
202
 *
203
 ******/
204
function is_alias_inuse($alias) {
205
	global $g, $config;
206
207
	if($alias == "") return false;
208
	/* loop through firewall rules looking for alias in use */
209 346e2e6b Scott Ullrich
	if(is_array($config['filter']['rule']))
210 3076becf Scott Ullrich
		foreach($config['filter']['rule'] as $rule) {
211 00eee841 Scott Ullrich
			if($rule['source']['address'])
212 3076becf Scott Ullrich
				if($rule['source']['address'] == $alias)
213 0c8c496e Scott Ullrich
					return true;
214 00eee841 Scott Ullrich
			if($rule['destination']['address'])
215 3076becf Scott Ullrich
				if($rule['destination']['address'] == $alias)
216 0c8c496e Scott Ullrich
					return true;
217
		}
218 3076becf Scott Ullrich
	/* loop through nat rules looking for alias in use */
219
	if(is_array($config['nat']['rule']))
220
		foreach($config['nat']['rule'] as $rule) {
221 59ecde49 Renato Botelho
			if($rule['target'] && $rule['target'] == $alias)
222 3076becf Scott Ullrich
				return true;
223 59ecde49 Renato Botelho
			if($rule['source']['address'] && $rule['source']['address'] == $alias)
224
				return true;
225
			if($rule['destination']['address'] && $rule['destination']['address'] == $alias)
226 3076becf Scott Ullrich
				return true;
227
		}
228
	return false;
229
}
230
231 63724b02 Scott Dale
/****f* pfsense-utils/is_schedule_inuse
232
 * NAME
233
 *   checks to see if a schedule is currently in use by a rule
234
 * INPUTS
235
 *
236
 * RESULT
237
 *   true or false
238
 * NOTES
239
 *
240
 ******/
241
function is_schedule_inuse($schedule) {
242
	global $g, $config;
243
244
	if($schedule == "") return false;
245
	/* loop through firewall rules looking for schedule in use */
246
	if(is_array($config['filter']['rule']))
247
		foreach($config['filter']['rule'] as $rule) {
248 591ceb32 Scott Dale
			if($rule['sched'] == $schedule)
249
				return true;
250 63724b02 Scott Dale
		}
251
	return false;
252
}
253
254 3076becf Scott Ullrich
/****f* pfsense-utils/setup_polling
255
 * NAME
256
 *   sets up polling
257
 * INPUTS
258
 *
259
 * RESULT
260
 *   null
261
 * NOTES
262
 *
263
 ******/
264
function setup_polling() {
265
	global $g, $config;
266
267 51d5aad7 Ermal
	if (isset($config['system']['polling']))
268
		mwexec("/sbin/sysctl kern.polling.idle_poll=1");
269
	else
270
		mwexec("/sbin/sysctl kern.polling.idle_poll=0");
271 3076becf Scott Ullrich
272 9a4c3eed Ermal
	if($config['system']['polling_each_burst'])
273
		mwexec("/sbin/sysctl kern.polling.each_burst={$config['system']['polling_each_burst']}");
274
	if($config['system']['polling_burst_max'])
275
		mwexec("/sbin/sysctl kern.polling.burst_max={$config['system']['polling_burst_max']}");
276
	if($config['system']['polling_user_frac'])
277
		mwexec("/sbin/sysctl kern.polling.user_frac={$config['system']['polling_user_frac']}");
278 3076becf Scott Ullrich
}
279
280
/****f* pfsense-utils/setup_microcode
281
 * NAME
282
 *   enumerates all interfaces and calls enable_hardware_offloading which
283
 *   enables a NIC's supported hardware features.
284
 * INPUTS
285
 *
286
 * RESULT
287
 *   null
288
 * NOTES
289
 *   This function only supports the fxp driver's loadable microcode.
290
 ******/
291
function setup_microcode() {
292
293 3a4ce87d Ermal Luçi
	/* if list */
294 929a1b15 jim-p
	$ifs = get_interface_arr();
295 e8df4c2f Scott Ullrich
296 929a1b15 jim-p
	foreach($ifs as $if)
297 3076becf Scott Ullrich
		enable_hardware_offloading($if);
298
}
299
300
/****f* pfsense-utils/get_carp_status
301
 * NAME
302
 *   get_carp_status - Return whether CARP is enabled or disabled.
303
 * RESULT
304
 *   boolean	- true if CARP is enabled, false if otherwise.
305
 ******/
306
function get_carp_status() {
307 5fa78adc Renato Botelho
	/* grab the current status of carp */
308
	$status = `/sbin/sysctl -n net.inet.carp.allow`;
309
	return (intval($status) > 0);
310 3076becf Scott Ullrich
}
311
312
/*
313
 * convert_ip_to_network_format($ip, $subnet): converts an ip address to network form
314 52947718 Ermal Lu?i
315 3076becf Scott Ullrich
 */
316
function convert_ip_to_network_format($ip, $subnet) {
317 2ce660ad smos
	$ipsplit = explode('.', $ip);
318 3076becf Scott Ullrich
	$string = $ipsplit[0] . "." . $ipsplit[1] . "." . $ipsplit[2] . ".0/" . $subnet;
319
	return $string;
320
}
321
322
/*
323
 * get_carp_interface_status($carpinterface): returns the status of a carp ip
324
 */
325
function get_carp_interface_status($carpinterface) {
326 108cfddf Ermal
	$carp_query = "";
327 b6877e06 Ermal
328
	/* XXX: Need to fidn a better way for this! */
329 0c21eb70 Ermal
	list ($interface, $vhid) = explode("_vip", $carpinterface);
330
	$interface = get_real_interface($interface);
331 b6877e06 Ermal
	exec("/sbin/ifconfig $interface | /usr/bin/grep -v grep | /usr/bin/grep carp: | /usr/bin/grep 'vhid {$vhid}'", $carp_query);
332 3076becf Scott Ullrich
	foreach($carp_query as $int) {
333 5fa78adc Renato Botelho
		if(stristr($int, "MASTER"))
334 7d1b238c Carlos Eduardo Ramos
			return gettext("MASTER");
335 5fa78adc Renato Botelho
		if(stristr($int, "BACKUP"))
336 7d1b238c Carlos Eduardo Ramos
			return gettext("BACKUP");
337 5fa78adc Renato Botelho
		if(stristr($int, "INIT"))
338 7d1b238c Carlos Eduardo Ramos
			return gettext("INIT");
339 3076becf Scott Ullrich
	}
340
	return;
341
}
342
343
/*
344
 * get_pfsync_interface_status($pfsyncinterface): returns the status of a pfsync
345
 */
346
function get_pfsync_interface_status($pfsyncinterface) {
347 306f8556 Renato Botelho
	if (!does_interface_exist($pfsyncinterface))
348
		return;
349
350
	return exec_command("/sbin/ifconfig {$pfsyncinterface} | /usr/bin/awk '/pfsync:/ {print \$5}'");
351 3076becf Scott Ullrich
}
352
353
/*
354
 * add_rule_to_anchor($anchor, $rule): adds the specified rule to an anchor
355
 */
356
function add_rule_to_anchor($anchor, $rule, $label) {
357 873c1701 Renato Botelho
	mwexec("echo " . escapeshellarg($rule) . " | /sbin/pfctl -a " . escapeshellarg($anchor) . ":" . escapeshellarg($label) . " -f -");
358 3076becf Scott Ullrich
}
359
360
/*
361
 * remove_text_from_file
362
 * remove $text from file $file
363
 */
364
function remove_text_from_file($file, $text) {
365 2addd5b2 Ermal
	if(!file_exists($file) && !is_writable($file))
366
		return;
367 3076becf Scott Ullrich
	$filecontents = file_get_contents($file);
368 2addd5b2 Ermal
	$text = str_replace($text, "", $filecontents);
369 5fa78adc Renato Botelho
	@file_put_contents($file, $text);
370 3076becf Scott Ullrich
}
371
372
/*
373
 * add_text_to_file($file, $text): adds $text to $file.
374
 * replaces the text if it already exists.
375
 */
376 5a6f3ca0 Scott Ullrich
function add_text_to_file($file, $text, $replace = false) {
377 3076becf Scott Ullrich
	if(file_exists($file) and is_writable($file)) {
378 5a6f3ca0 Scott Ullrich
		$filecontents = file($file);
379
		$filecontents = array_map('rtrim', $filecontents);
380
		array_push($filecontents, $text);
381
		if ($replace)
382
			$filecontents = array_unique($filecontents);
383
384
		$file_text = implode("\n", $filecontents);
385
386 5fa78adc Renato Botelho
		@file_put_contents($file, $file_text);
387 3076becf Scott Ullrich
		return true;
388 0c8c496e Scott Ullrich
	}
389 2addd5b2 Ermal
	return false;
390 3076becf Scott Ullrich
}
391
392
/*
393
 *   after_sync_bump_adv_skew(): create skew values by 1S
394
 */
395
function after_sync_bump_adv_skew() {
396
	global $config, $g;
397
	$processed_skew = 1;
398
	$a_vip = &$config['virtualip']['vip'];
399
	foreach ($a_vip as $vipent) {
400
		if($vipent['advskew'] <> "") {
401
			$processed_skew = 1;
402
			$vipent['advskew'] = $vipent['advskew']+1;
403
		}
404
	}
405
	if($processed_skew == 1)
406 7d1b238c Carlos Eduardo Ramos
		write_config(gettext("After synch increase advertising skew"));
407 3076becf Scott Ullrich
}
408
409
/*
410
 * get_filename_from_url($url): converts a url to its filename.
411
 */
412
function get_filename_from_url($url) {
413
	return basename($url);
414
}
415
416
/*
417
 *   get_dir: return an array of $dir
418
 */
419
function get_dir($dir) {
420
	$dir_array = array();
421
	$d = dir($dir);
422
	while (false !== ($entry = $d->read())) {
423
		array_push($dir_array, $entry);
424
	}
425
	$d->close();
426
	return $dir_array;
427
}
428
429
/****f* pfsense-utils/WakeOnLan
430
 * NAME
431
 *   WakeOnLan - Wake a machine up using the wake on lan format/protocol
432
 * RESULT
433
 *   true/false - true if the operation was successful
434
 ******/
435
function WakeOnLan($addr, $mac)
436
{
437
	$addr_byte = explode(':', $mac);
438
	$hw_addr = '';
439
440
	for ($a=0; $a < 6; $a++)
441
		$hw_addr .= chr(hexdec($addr_byte[$a]));
442
443
	$msg = chr(255).chr(255).chr(255).chr(255).chr(255).chr(255);
444
445
	for ($a = 1; $a <= 16; $a++)
446
		$msg .= $hw_addr;
447
448
	// send it to the broadcast address using UDP
449
	$s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
450
	if ($s == false) {
451 7d1b238c Carlos Eduardo Ramos
		log_error(gettext("Error creating socket!"));
452 addc0439 Renato Botelho
		log_error(sprintf(gettext("Error code is '%1\$s' - %2\$s"), socket_last_error($s), socket_strerror(socket_last_error($s))));
453 3076becf Scott Ullrich
	} else {
454
		// setting a broadcast option to socket:
455
		$opt_ret =  socket_set_option($s, 1, 6, TRUE);
456
		if($opt_ret < 0)
457 7d1b238c Carlos Eduardo Ramos
			log_error(sprintf(gettext("setsockopt() failed, error: %s"), strerror($opt_ret)));
458 3076becf Scott Ullrich
		$e = socket_sendto($s, $msg, strlen($msg), 0, $addr, 2050);
459
		socket_close($s);
460 addc0439 Renato Botelho
		log_error(sprintf(gettext('Magic Packet sent (%1$s) to {%2$s} MAC=%3$s'), $e, $addr, $mac));
461 3076becf Scott Ullrich
		return true;
462 0c8c496e Scott Ullrich
	}
463 3076becf Scott Ullrich
464
	return false;
465
}
466
467
/*
468
 * reverse_strrchr($haystack, $needle):  Return everything in $haystack up to the *last* instance of $needle.
469
 *					 Useful for finding paths and stripping file extensions.
470
 */
471
function reverse_strrchr($haystack, $needle) {
472 4824d857 Ermal Lu?i
	if (!is_string($haystack))
473
		return;
474 3076becf Scott Ullrich
	return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) +1 ) : false;
475
}
476
477
/*
478
 *  backup_config_section($section): returns as an xml file string of
479
 *                                   the configuration section
480
 */
481 8dcca9b5 Darren Embry
function backup_config_section($section_name) {
482 3076becf Scott Ullrich
	global $config;
483 8dcca9b5 Darren Embry
	$new_section = &$config[$section_name];
484 3076becf Scott Ullrich
	/* generate configuration XML */
485 8dcca9b5 Darren Embry
	$xmlconfig = dump_xml_config($new_section, $section_name);
486 3076becf Scott Ullrich
	$xmlconfig = str_replace("<?xml version=\"1.0\"?>", "", $xmlconfig);
487
	return $xmlconfig;
488
}
489
490
/*
491 8dcca9b5 Darren Embry
 *  restore_config_section($section_name, new_contents): restore a configuration section,
492 3076becf Scott Ullrich
 *                                                  and write the configuration out
493
 *                                                  to disk/cf.
494
 */
495 8dcca9b5 Darren Embry
function restore_config_section($section_name, $new_contents) {
496 3076becf Scott Ullrich
	global $config, $g;
497
	conf_mount_rw();
498
	$fout = fopen("{$g['tmp_path']}/tmpxml","w");
499
	fwrite($fout, $new_contents);
500
	fclose($fout);
501 8dcca9b5 Darren Embry
502
	$xml = parse_xml_config($g['tmp_path'] . "/tmpxml", null);
503
	if ($xml['pfsense']) {
504
		$xml = $xml['pfsense'];
505
	}
506
	else if ($xml['m0n0wall']) {
507
		$xml = $xml['m0n0wall'];
508
	}
509
	if ($xml[$section_name]) {
510
		$section_xml = $xml[$section_name];
511
	} else {
512
		$section_xml = -1;
513
	}
514
515 541989d5 Ermal
	@unlink($g['tmp_path'] . "/tmpxml");
516 8dcca9b5 Darren Embry
	if ($section_xml === -1) {
517
		return false;
518
	}
519
	$config[$section_name] = &$section_xml;
520 a57d6170 Scott Ullrich
	if(file_exists("{$g['tmp_path']}/config.cache"))
521
		unlink("{$g['tmp_path']}/config.cache");
522 8dcca9b5 Darren Embry
	write_config(sprintf(gettext("Restored %s of config file (maybe from CARP partner)"), $section_name));
523 0f806eca Erik Fonnesbeck
	disable_security_checks();
524 3076becf Scott Ullrich
	conf_mount_ro();
525 8dcca9b5 Darren Embry
	return true;
526 3076becf Scott Ullrich
}
527
528
/*
529 8dcca9b5 Darren Embry
 *  merge_config_section($section_name, new_contents):   restore a configuration section,
530 3076becf Scott Ullrich
 *                                                  and write the configuration out
531
 *                                                  to disk/cf.  But preserve the prior
532
 * 													structure if needed
533
 */
534 8dcca9b5 Darren Embry
function merge_config_section($section_name, $new_contents) {
535 3076becf Scott Ullrich
	global $config;
536
	conf_mount_rw();
537
	$fname = get_tmp_filename();
538
	$fout = fopen($fname, "w");
539
	fwrite($fout, $new_contents);
540
	fclose($fout);
541 8dcca9b5 Darren Embry
	$section_xml = parse_xml_config($fname, $section_name);
542
	$config[$section_name] = $section_xml;
543 3076becf Scott Ullrich
	unlink($fname);
544 8dcca9b5 Darren Embry
	write_config(sprintf(gettext("Restored %s of config file (maybe from CARP partner)"), $section_name));
545 0f806eca Erik Fonnesbeck
	disable_security_checks();
546 3076becf Scott Ullrich
	conf_mount_ro();
547
	return;
548
}
549
550
/*
551
 * http_post($server, $port, $url, $vars): does an http post to a web server
552
 *                                         posting the vars array.
553
 * written by nf@bigpond.net.au
554
 */
555
function http_post($server, $port, $url, $vars) {
556
	$user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)";
557
	$urlencoded = "";
558
	while (list($key,$value) = each($vars))
559
		$urlencoded.= urlencode($key) . "=" . urlencode($value) . "&";
560
	$urlencoded = substr($urlencoded,0,-1);
561
	$content_length = strlen($urlencoded);
562
	$headers = "POST $url HTTP/1.1
563
Accept: */*
564
Accept-Language: en-au
565
Content-Type: application/x-www-form-urlencoded
566
User-Agent: $user_agent
567
Host: $server
568
Connection: Keep-Alive
569
Cache-Control: no-cache
570
Content-Length: $content_length
571
572
";
573
574
	$errno = "";
575
	$errstr = "";
576
	$fp = fsockopen($server, $port, $errno, $errstr);
577
	if (!$fp) {
578 0c8c496e Scott Ullrich
		return false;
579
	}
580 3076becf Scott Ullrich
581
	fputs($fp, $headers);
582
	fputs($fp, $urlencoded);
583
584
	$ret = "";
585
	while (!feof($fp))
586
		$ret.= fgets($fp, 1024);
587
	fclose($fp);
588
589
	return $ret;
590
}
591
592
/*
593
 *  php_check_syntax($code_tocheck, $errormessage): checks $code_to_check for errors
594
 */
595
if (!function_exists('php_check_syntax')){
596 da17d77e Ermal Lu?i
	global $g;
597 3076becf Scott Ullrich
	function php_check_syntax($code_to_check, &$errormessage){
598
		return false;
599 da17d77e Ermal Lu?i
		$fout = fopen("{$g['tmp_path']}/codetocheck.php","w");
600 3076becf Scott Ullrich
		$code = $_POST['content'];
601
		$code = str_replace("<?php", "", $code);
602
		$code = str_replace("?>", "", $code);
603
		fwrite($fout, "<?php\n\n");
604
		fwrite($fout, $code_to_check);
605
		fwrite($fout, "\n\n?>\n");
606 0c8c496e Scott Ullrich
		fclose($fout);
607 da17d77e Ermal Lu?i
		$command = "/usr/local/bin/php -l {$g['tmp_path']}/codetocheck.php";
608 3076becf Scott Ullrich
		$output = exec_command($command);
609
		if (stristr($output, "Errors parsing") == false) {
610
			echo "false\n";
611
			$errormessage = '';
612
			return(false);
613
		} else {
614
			$errormessage = $output;
615
			return(true);
616 0c8c496e Scott Ullrich
		}
617
	}
618 3076becf Scott Ullrich
}
619
620
/*
621
 *  php_check_filename_syntax($filename, $errormessage): checks the file $filename for errors
622
 */
623
if (!function_exists('php_check_syntax')){
624
	function php_check_syntax($code_to_check, &$errormessage){
625
		return false;
626 873c1701 Renato Botelho
		$command = "/usr/local/bin/php -l " . escapeshellarg($code_to_check);
627 3076becf Scott Ullrich
		$output = exec_command($command);
628
		if (stristr($output, "Errors parsing") == false) {
629
			echo "false\n";
630
			$errormessage = '';
631
			return(false);
632
		} else {
633
			$errormessage = $output;
634
			return(true);
635
		}
636
	}
637
}
638
639
/*
640
 * rmdir_recursive($path,$follow_links=false)
641
 * Recursively remove a directory tree (rm -rf path)
642
 * This is for directories _only_
643
 */
644
function rmdir_recursive($path,$follow_links=false) {
645
	$to_do = glob($path);
646
	if(!is_array($to_do)) $to_do = array($to_do);
647
	foreach($to_do as $workingdir) { // Handle wildcards by foreaching.
648
		if(file_exists($workingdir)) {
649
			if(is_dir($workingdir)) {
650
				$dir = opendir($workingdir);
651
				while ($entry = readdir($dir)) {
652
					if (is_file("$workingdir/$entry") || ((!$follow_links) && is_link("$workingdir/$entry")))
653
						unlink("$workingdir/$entry");
654
					elseif (is_dir("$workingdir/$entry") && $entry!='.' && $entry!='..')
655
						rmdir_recursive("$workingdir/$entry");
656 6613a031 Scott Ullrich
				}
657 3076becf Scott Ullrich
				closedir($dir);
658
				rmdir($workingdir);
659
			} elseif (is_file($workingdir)) {
660
				unlink($workingdir);
661
			}
662 5fa78adc Renato Botelho
		}
663 3076becf Scott Ullrich
	}
664
	return;
665
}
666
667
/*
668 f5e09d92 Chris Buechler
 * call_pfsense_method(): Call a method exposed by the pfsense.org XMLRPC server.
669 3076becf Scott Ullrich
 */
670
function call_pfsense_method($method, $params, $timeout = 0) {
671 cfceefc6 Scott Ullrich
	global $g, $config;
672
673 ffba4976 jim-p
	$xmlrpc_base_url = isset($config['system']['altpkgrepo']['enable']) ? $config['system']['altpkgrepo']['xmlrpcbaseurl'] : $g['xmlrpcbaseurl'];
674 3076becf Scott Ullrich
	$xmlrpc_path = $g['xmlrpcpath'];
675 1b92cc61 Chris Buechler
	
676
	$xmlrpcfqdn = preg_replace("(https?://)", "", $xmlrpc_base_url);
677
	$ip = gethostbyname($xmlrpcfqdn);
678
	if($ip == $xmlrpcfqdn)
679
		return false;
680
681 3076becf Scott Ullrich
	$msg = new XML_RPC_Message($method, array(XML_RPC_Encode($params)));
682 42c07003 Ermal
	$port = 0;
683
	$proxyurl = "";
684
	$proxyport = 0;
685
	$proxyuser = "";
686
	$proxypass = "";
687 aa3c4866 Ermal
	if (!empty($config['system']['proxyurl']))
688
		$proxyurl = $config['system']['proxyurl'];
689
	if (!empty($config['system']['proxyport']) && is_numeric($config['system']['proxyport']))
690
		$proxyport = $config['system']['proxyport'];
691
	if (!empty($config['system']['proxyuser']))
692
		$proxyuser = $config['system']['proxyuser'];
693
	if (!empty($config['system']['proxypass']))
694
		$proxypass = $config['system']['proxypass'];
695 42c07003 Ermal
	$cli = new XML_RPC_Client($xmlrpc_path, $xmlrpc_base_url, $port, $proxyurl, $proxyport, $proxyuser, $proxypass);
696 16348c36 Scott Ullrich
	// If the ALT PKG Repo has a username/password set, use it.
697 5fa78adc Renato Botelho
	if($config['system']['altpkgrepo']['username'] &&
698 16348c36 Scott Ullrich
	   $config['system']['altpkgrepo']['password']) {
699
		$username = $config['system']['altpkgrepo']['username'];
700
		$password = $config['system']['altpkgrepo']['password'];
701
		$cli->setCredentials($username, $password);
702
	}
703 3076becf Scott Ullrich
	$resp = $cli->send($msg, $timeout);
704 2addd5b2 Ermal
	if(!is_object($resp)) {
705 7d1b238c Carlos Eduardo Ramos
		log_error(sprintf(gettext("XMLRPC communication error: %s"), $cli->errstr));
706 3076becf Scott Ullrich
		return false;
707
	} elseif($resp->faultCode()) {
708 addc0439 Renato Botelho
		log_error(sprintf(gettext('XMLRPC request failed with error %1$s: %2$s'), $resp->faultCode(), $resp->faultString()));
709 3076becf Scott Ullrich
		return false;
710
	} else {
711
		return XML_RPC_Decode($resp->value());
712
	}
713
}
714
715
/*
716
 * check_firmware_version(): Check whether the current firmware installed is the most recently released.
717
 */
718
function check_firmware_version($tocheck = "all", $return_php = true) {
719
	global $g, $config;
720 1b92cc61 Chris Buechler
	
721
	$xmlrpc_base_url = isset($config['system']['altpkgrepo']['enable']) ? $config['system']['altpkgrepo']['xmlrpcbaseurl'] : $g['xmlrpcbaseurl'];
722
	$xmlrpcfqdn = preg_replace("(https?://)", "", $xmlrpc_base_url);
723
	$ip = gethostbyname($xmlrpcfqdn);
724
	if($ip == $xmlrpcfqdn)
725 3076becf Scott Ullrich
		return false;
726 a02fa5ec Ermal
	$version = php_uname('r');
727
	$version = explode('-', $version);
728 3076becf Scott Ullrich
	$rawparams = array("firmware" => array("version" => trim(file_get_contents('/etc/version'))),
729 a02fa5ec Ermal
		"kernel"   => array("version" => $version[0]),
730
		"base"     => array("version" => $version[0]),
731 d064a115 Ermal
		"platform" => trim(file_get_contents('/etc/platform')),
732
		"config_version" => $config['version']
733 3076becf Scott Ullrich
		);
734 a02fa5ec Ermal
	unset($version);
735
736 3076becf Scott Ullrich
	if($tocheck == "all") {
737
		$params = $rawparams;
738
	} else {
739
		foreach($tocheck as $check) {
740
			$params['check'] = $rawparams['check'];
741
			$params['platform'] = $rawparams['platform'];
742
		}
743
	}
744 d064a115 Ermal
	if($config['system']['firmware']['branch'])
745 3076becf Scott Ullrich
		$params['branch'] = $config['system']['firmware']['branch'];
746 d064a115 Ermal
747
	/* XXX: What is this method? */
748
	if(!($versions = call_pfsense_method('pfsense.get_firmware_version', $params))) {
749 3076becf Scott Ullrich
		return false;
750
	} else {
751
		$versions["current"] = $params;
752
	}
753 d064a115 Ermal
754 3076becf Scott Ullrich
	return $versions;
755
}
756
757 e501de37 Ermal
/*
758
 * host_firmware_version(): Return the versions used in this install
759
 */
760 18be996d Ermal
function host_firmware_version($tocheck = "") {
761 5fa78adc Renato Botelho
	global $g, $config;
762 e501de37 Ermal
763 5fa78adc Renato Botelho
	return array(
764 e501de37 Ermal
		"firmware" => array("version" => trim(file_get_contents('/etc/version', " \n"))),
765 5fa78adc Renato Botelho
		"kernel"   => array("version" => trim(file_get_contents('/etc/version_kernel', " \n"))),
766
		"base"     => array("version" => trim(file_get_contents('/etc/version_base', " \n"))),
767
		"platform" => trim(file_get_contents('/etc/platform', " \n")),
768
		"config_version" => $config['version']
769
	);
770 e501de37 Ermal
}
771
772 3076becf Scott Ullrich
function get_disk_info() {
773
	$diskout = "";
774
	exec("/bin/df -h | /usr/bin/grep -w '/' | /usr/bin/awk '{ print $2, $3, $4, $5 }'", $diskout);
775
	return explode(' ', $diskout[0]);
776
}
777
778
/****f* pfsense-utils/strncpy
779
 * NAME
780
 *   strncpy - copy strings
781
 * INPUTS
782
 *   &$dst, $src, $length
783
 * RESULT
784
 *   none
785
 ******/
786
function strncpy(&$dst, $src, $length) {
787
	if (strlen($src) > $length) {
788
		$dst = substr($src, 0, $length);
789
	} else {
790
		$dst = $src;
791
	}
792
}
793
794
/****f* pfsense-utils/reload_interfaces_sync
795
 * NAME
796
 *   reload_interfaces - reload all interfaces
797
 * INPUTS
798
 *   none
799
 * RESULT
800
 *   none
801
 ******/
802
function reload_interfaces_sync() {
803 c0836064 Ermal Luçi
	global $config, $g;
804 3076becf Scott Ullrich
805 c0836064 Ermal Luçi
	if($g['debug'])
806 7d1b238c Carlos Eduardo Ramos
		log_error(gettext("reload_interfaces_sync() is starting."));
807 3076becf Scott Ullrich
808
	/* parse config.xml again */
809
	$config = parse_config(true);
810
811 a5d6f60b Ermal Lu?i
	/* enable routing */
812
	system_routing_enable();
813
	if($g['debug'])
814 7d1b238c Carlos Eduardo Ramos
		log_error(gettext("Enabling system routing"));
815 3076becf Scott Ullrich
816 c0836064 Ermal Luçi
	if($g['debug'])
817 7d1b238c Carlos Eduardo Ramos
		log_error(gettext("Cleaning up Interfaces"));
818 3076becf Scott Ullrich
819 67ee1ec5 Ermal Luçi
	/* set up interfaces */
820
	interfaces_configure();
821 3076becf Scott Ullrich
}
822
823
/****f* pfsense-utils/reload_all
824
 * NAME
825
 *   reload_all - triggers a reload of all settings
826
 *   * INPUTS
827
 *   none
828
 * RESULT
829
 *   none
830
 ******/
831
function reload_all() {
832 0ae6daf8 Ermal
	send_event("service reload all");
833 3076becf Scott Ullrich
}
834
835
/****f* pfsense-utils/reload_interfaces
836
 * NAME
837
 *   reload_interfaces - triggers a reload of all interfaces
838
 * INPUTS
839
 *   none
840
 * RESULT
841
 *   none
842
 ******/
843
function reload_interfaces() {
844 5e3a84e2 Ermal
	send_event("interface all reload");
845 3076becf Scott Ullrich
}
846
847
/****f* pfsense-utils/reload_all_sync
848
 * NAME
849
 *   reload_all - reload all settings
850
 *   * INPUTS
851
 *   none
852
 * RESULT
853
 *   none
854
 ******/
855
function reload_all_sync() {
856
	global $config, $g;
857
858
	$g['booting'] = false;
859
860
	/* parse config.xml again */
861
	$config = parse_config(true);
862
863
	/* set up our timezone */
864
	system_timezone_configure();
865
866
	/* set up our hostname */
867
	system_hostname_configure();
868
869
	/* make hosts file */
870
	system_hosts_generate();
871
872
	/* generate resolv.conf */
873
	system_resolvconf_generate();
874
875
	/* enable routing */
876
	system_routing_enable();
877
878 a5d6f60b Ermal Lu?i
	/* set up interfaces */
879
	interfaces_configure();
880 3076becf Scott Ullrich
881
	/* start dyndns service */
882
	services_dyndns_configure();
883
884
	/* configure cron service */
885
	configure_cron();
886
887
	/* start the NTP client */
888
	system_ntp_configure();
889
890
	/* sync pw database */
891
	conf_mount_rw();
892 6b0c5879 Scott Ullrich
	unlink_if_exists("/etc/spwd.db.tmp");
893 3076becf Scott Ullrich
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
894
	conf_mount_ro();
895
896
	/* restart sshd */
897 0ae6daf8 Ermal
	send_event("service restart sshd");
898 3076becf Scott Ullrich
899
	/* restart webConfigurator if needed */
900 0ae6daf8 Ermal
	send_event("service restart webgui");
901 3076becf Scott Ullrich
}
902
903 a46e450c Ermal Lu?i
function auto_login() {
904
	global $config;
905
906
	if(isset($config['system']['disableconsolemenu']))
907 5f81609a Erik Fonnesbeck
		$status = false;
908
	else
909
		$status = true;
910
911 3076becf Scott Ullrich
	$gettytab = file_get_contents("/etc/gettytab");
912 cfbfd941 smos
	$getty_split = explode("\n", $gettytab);
913 adc0f2fe Phil Davis
	$getty_update_needed = false;
914
	$getty_search_str = ":ht:np:sp#115200";
915
	$getty_al_str = ":al=root:";
916
	$getty_al_search_str = $getty_search_str . $getty_al_str;
917
	/* Check if gettytab is already OK, if so then do not rewrite it. */
918
	foreach($getty_split as $gs) {
919
		if(stristr($gs, $getty_search_str)) {
920
			if($status == true) {
921
				if(!stristr($gs, $getty_al_search_str)) {
922
					$getty_update_needed = true;
923
				}
924
			} else {
925
				if(stristr($gs, $getty_al_search_str)) {
926
					$getty_update_needed = true;
927
				}
928
			}
929
		}
930
	}
931
932
	if (!$getty_update_needed) {
933
		return;
934
	}
935
936 3076becf Scott Ullrich
	conf_mount_rw();
937 6480d38f Ermal Lu?i
	$fd = false;
938 e7df76d2 Ermal Lu?i
	$tries = 0;
939
	while (!$fd && $tries < 100) {
940 6480d38f Ermal Lu?i
		$fd = fopen("/etc/gettytab", "w");
941 e7df76d2 Ermal Lu?i
		$tries++;
942 5fa78adc Renato Botelho
943 e7df76d2 Ermal Lu?i
	}
944
	if (!$fd) {
945
		conf_mount_ro();
946 adc0f2fe Phil Davis
		if ($status) {
947
			log_error(gettext("Enabling auto login was not possible."));
948
		} else {
949
			log_error(gettext("Disabling auto login was not possible."));
950
		}
951 e7df76d2 Ermal Lu?i
		return;
952 6480d38f Ermal Lu?i
	}
953 3076becf Scott Ullrich
	foreach($getty_split as $gs) {
954 adc0f2fe Phil Davis
		if(stristr($gs, $getty_search_str)) {
955 3076becf Scott Ullrich
			if($status == true) {
956 adc0f2fe Phil Davis
				fwrite($fd, "	".$getty_al_search_str."\n");
957 3076becf Scott Ullrich
			} else {
958 adc0f2fe Phil Davis
				fwrite($fd, "	".$getty_search_str."\n");
959 ca8e4ed2 Scott Ullrich
			}
960 0c8c496e Scott Ullrich
		} else {
961 3076becf Scott Ullrich
			fwrite($fd, "{$gs}\n");
962
		}
963
	}
964
	fclose($fd);
965 adc0f2fe Phil Davis
966
	if ($status) {
967
		log_error(gettext("Enabled console auto login, console menu is NOT password protected."));
968
	} else {
969
		log_error(gettext("Disabled console auto login, console menu is password protected."));
970
	}
971 5fa78adc Renato Botelho
972 3076becf Scott Ullrich
	conf_mount_ro();
973
}
974
975 196d0085 jim-p
function setup_serial_port($when="save", $path="") {
976 3076becf Scott Ullrich
	global $g, $config;
977
	conf_mount_rw();
978 196d0085 jim-p
	$prefix = "";
979
	if (($when == "upgrade") && (!empty($path)) && is_dir($path.'/boot/'))
980
		$prefix = "/tmp/{$path}";
981
	$boot_config_file = "{$path}/boot.config";
982
	$loader_conf_file = "{$path}/boot/loader.conf";
983 3076becf Scott Ullrich
	/* serial console - write out /boot.config */
984 196d0085 jim-p
	if(file_exists($boot_config_file))
985
		$boot_config = file_get_contents($boot_config_file);
986 3076becf Scott Ullrich
	else
987
		$boot_config = "";
988
989 409bc1bd jim-p
	if(($g['platform'] != "cdrom") && ($g['platform'] != "nanobsd")) {
990 cfbfd941 smos
		$boot_config_split = explode("\n", $boot_config);
991 196d0085 jim-p
		$fd = fopen($boot_config_file,"w");
992 3076becf Scott Ullrich
		if($fd) {
993
			foreach($boot_config_split as $bcs) {
994
				if(stristr($bcs, "-D")) {
995
					/* DONT WRITE OUT, WE'LL DO IT LATER */
996
				} else {
997
					if($bcs <> "")
998
						fwrite($fd, "{$bcs}\n");
999
				}
1000 0c8c496e Scott Ullrich
			}
1001 407fbf45 jim-p
			if(isset($config['system']['enableserial']) || $g['enableserial_force']) {
1002 3076becf Scott Ullrich
				fwrite($fd, "-D");
1003 0c8c496e Scott Ullrich
			}
1004 3076becf Scott Ullrich
			fclose($fd);
1005 0c8c496e Scott Ullrich
		}
1006 409bc1bd jim-p
	}
1007
	if($g['platform'] != "cdrom") {
1008 3076becf Scott Ullrich
		/* serial console - write out /boot/loader.conf */
1009 baef6be8 jim-p
		if ($when == "upgrade")
1010
			system("echo \"Reading {$loader_conf_file}...\" >> /conf/upgrade_log.txt");
1011 196d0085 jim-p
		$boot_config = file_get_contents($loader_conf_file);
1012 5f36c658 jim-p
		$boot_config_split = explode("\n", $boot_config);
1013
		if(count($boot_config_split) > 0) {
1014
			$new_boot_config = array();
1015
			// Loop through and only add lines that are not empty, and which
1016
			//  do not contain a console directive.
1017
			foreach($boot_config_split as $bcs)
1018 c1becc31 jim-p
				if(!empty($bcs)
1019
					&& (stripos($bcs, "console") === false)
1020
					&& (stripos($bcs, "boot_multicons") === false)
1021 48126e25 Renato Botelho
					&& (stripos($bcs, "boot_serial") === false)
1022
					&& (stripos($bcs, "hw.usb.no_pf") === false))
1023 5f36c658 jim-p
					$new_boot_config[] = $bcs;
1024
1025 9d99eb95 jim-p
			$serialspeed = (is_numeric($config['system']['serialspeed'])) ? $config['system']['serialspeed'] : "9600";
1026 407fbf45 jim-p
			if(isset($config['system']['enableserial']) || $g['enableserial_force']) {
1027 c1becc31 jim-p
				$new_boot_config[] = 'boot_multicons="YES"';
1028
				$new_boot_config[] = 'boot_serial="YES"';
1029
				$new_boot_config[] = 'comconsole_speed="' . $serialspeed . '"';
1030 bf4e62ac jim-p
				$primaryconsole = isset($g['primaryconsole_force']) ? $g['primaryconsole_force'] : $config['system']['primaryconsole'];
1031
				switch ($primaryconsole) {
1032
					case "video":
1033
						$new_boot_config[] = 'console="vidconsole,comconsole"';
1034
						break;
1035
					case "serial":
1036
					default:
1037
						$new_boot_config[] = 'console="comconsole,vidconsole"';
1038
				}
1039 9d99eb95 jim-p
			} elseif ($g['platform'] == "nanobsd") {
1040 b16d666d jim-p
				$new_boot_config[] = 'comconsole_speed="' . $serialspeed . '"';
1041 c1becc31 jim-p
			}
1042 25c088de Renato Botelho
1043
			$new_boot_config[] = 'hw.usb.no_pf="1"';
1044
1045 196d0085 jim-p
			file_put_contents($loader_conf_file, implode("\n", $new_boot_config) . "\n");
1046 0c8c496e Scott Ullrich
		}
1047
	}
1048 3076becf Scott Ullrich
	$ttys = file_get_contents("/etc/ttys");
1049 cfbfd941 smos
	$ttys_split = explode("\n", $ttys);
1050 3076becf Scott Ullrich
	$fd = fopen("/etc/ttys", "w");
1051
	foreach($ttys_split as $tty) {
1052 c1fdf37f sullrich
		if(stristr($tty, "ttyd0") or stristr($tty, "ttyu0")) {
1053 407fbf45 jim-p
			if(isset($config['system']['enableserial']) || $g['enableserial_force']) {
1054 fd946c7e Erik Fonnesbeck
				fwrite($fd, "ttyu0	\"/usr/libexec/getty bootupcli\"	cons25	on	secure\n");
1055 3076becf Scott Ullrich
			} else {
1056 fd946c7e Erik Fonnesbeck
				fwrite($fd, "ttyu0	\"/usr/libexec/getty bootupcli\"	cons25	off	secure\n");
1057 ca8e4ed2 Scott Ullrich
			}
1058 3076becf Scott Ullrich
		} else {
1059
			fwrite($fd, $tty . "\n");
1060
		}
1061
	}
1062
	fclose($fd);
1063 a46e450c Ermal Lu?i
	auto_login();
1064
1065 3076becf Scott Ullrich
	conf_mount_ro();
1066
	return;
1067
}
1068
1069
function print_value_list($list, $count = 10, $separator = ",") {
1070
	$list = implode($separator, array_slice($list, 0, $count));
1071
	if(count($list) < $count) {
1072
		$list .= ".";
1073
	} else {
1074
		$list .= "...";
1075
	}
1076
	return $list;
1077
}
1078
1079 bfe776f0 Ermal Luçi
/* DHCP enabled on any interfaces? */
1080 abdd01f5 Ermal
function is_dhcp_server_enabled() {
1081 db9fabf3 Ermal Luçi
	global $config;
1082 bfe776f0 Ermal Luçi
1083 a6610d82 smos
	if (!is_array($config['dhcpd']))
1084 bfe776f0 Ermal Luçi
		return false;
1085
1086 abdd01f5 Ermal
	foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf) {
1087
		if (isset($dhcpifconf['enable']) && !empty($config['interfaces'][$dhcpif]))
1088
			return true;
1089 3076becf Scott Ullrich
	}
1090 bfe776f0 Ermal Luçi
1091 abdd01f5 Ermal
	return false;
1092 a6610d82 smos
}
1093
1094
/* DHCP enabled on any interfaces? */
1095 abdd01f5 Ermal
function is_dhcpv6_server_enabled() {
1096 a6610d82 smos
	global $config;
1097
1098 abdd01f5 Ermal
	if (is_array($config['interfaces'])) {
1099
		foreach ($config['interfaces'] as $ifcfg) {
1100 7a04cd20 Ermal
			if (isset($ifcfg['enable']) && !empty($ifcfg['track6-interface']))
1101 abdd01f5 Ermal
				return true;
1102 a6610d82 smos
		}
1103
	}
1104
1105
	if (!is_array($config['dhcpdv6']))
1106
		return false;
1107
1108 abdd01f5 Ermal
	foreach ($config['dhcpdv6'] as $dhcpv6if => $dhcpv6ifconf) {
1109 ab873ccd Ermal
		if (isset($dhcpv6ifconf['enable']) && !empty($config['interfaces'][$dhcpv6if]))
1110 abdd01f5 Ermal
			return true;
1111 65b1e7d5 Seth Mos
	}
1112
1113 abdd01f5 Ermal
	return false;
1114 3076becf Scott Ullrich
}
1115
1116 0ed8d746 bcyrill
/* radvd enabled on any interfaces? */
1117
function is_radvd_enabled() {
1118
	global $config;
1119
1120
	if (!is_array($config['dhcpdv6']))
1121
		$config['dhcpdv6'] = array();
1122
1123
	$dhcpdv6cfg = $config['dhcpdv6'];
1124
	$Iflist = get_configured_interface_list();
1125
1126
	/* handle manually configured DHCP6 server settings first */
1127
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1128
		if(!isset($config['interfaces'][$dhcpv6if]['enable']))
1129
			continue;
1130
1131
		if(!isset($dhcpv6ifconf['ramode']))
1132
			$dhcpv6ifconf['ramode'] = $dhcpv6ifconf['mode'];
1133
1134
		if($dhcpv6ifconf['ramode'] == "disabled")
1135
			continue;
1136
1137
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1138
		if(!is_ipaddrv6($ifcfgipv6))
1139
			continue;
1140
1141
		return true;
1142
	}
1143
1144
	/* handle DHCP-PD prefixes and 6RD dynamic interfaces */
1145
	foreach ($Iflist as $if => $ifdescr) {
1146
		if(!isset($config['interfaces'][$if]['track6-interface']))
1147
			continue;
1148
		if(!isset($config['interfaces'][$if]['enable']))
1149
			continue;
1150
1151
		$ifcfgipv6 = get_interface_ipv6($if);
1152
		if(!is_ipaddrv6($ifcfgipv6))
1153
			continue;
1154
1155
		$ifcfgsnv6 = get_interface_subnetv6($if);
1156
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1157
1158
		if(!is_ipaddrv6($subnetv6))
1159
			continue;
1160
1161
		return true;
1162
	}
1163
1164
	return false;
1165
}
1166
1167 93c2c1e6 jim-p
/* Any PPPoE servers enabled? */
1168
function is_pppoe_server_enabled() {
1169
	global $config;
1170
1171
	$pppoeenable = false;
1172
1173
	if (!is_array($config['pppoes']) || !is_array($config['pppoes']['pppoe']))
1174
		return false;
1175
1176
	foreach ($config['pppoes']['pppoe'] as $pppoes)
1177
		if ($pppoes['mode'] == 'server')
1178
			$pppoeenable = true;
1179
1180
	return $pppoeenable;
1181
}
1182
1183 9ebe7028 gnhb
function convert_seconds_to_hms($sec){
1184 63292199 gnhb
	$min=$hrs=0;
1185 9ebe7028 gnhb
	if ($sec != 0){
1186
		$min = floor($sec/60);
1187
		$sec %= 60;
1188
	}
1189
	if ($min != 0){
1190
		$hrs = floor($min/60);
1191
		$min %= 60;
1192
	}
1193
	if ($sec < 10)
1194
		$sec = "0".$sec;
1195
	if ($min < 10)
1196
		$min = "0".$min;
1197
	if ($hrs < 10)
1198
		$hrs = "0".$hrs;
1199
	$result = $hrs.":".$min.":".$sec;
1200
	return $result;
1201
}
1202 8eb2f33a Scott Ullrich
1203 63292199 gnhb
/* Compute the total uptime from the ppp uptime log file in the conf directory */
1204
1205
function get_ppp_uptime($port){
1206
	if (file_exists("/conf/{$port}.log")){
1207 5fa78adc Renato Botelho
		$saved_time = file_get_contents("/conf/{$port}.log");
1208
		$uptime_data = explode("\n",$saved_time);
1209 63292199 gnhb
		$sec=0;
1210
		foreach($uptime_data as $upt) {
1211
			$sec += substr($upt, 1 + strpos($upt, " "));
1212 5fa78adc Renato Botelho
		}
1213 63292199 gnhb
		return convert_seconds_to_hms($sec);
1214
	} else {
1215 7d1b238c Carlos Eduardo Ramos
		$total_time = gettext("No history data found!");
1216 63292199 gnhb
		return $total_time;
1217
	}
1218
}
1219 8eb2f33a Scott Ullrich
1220 6189988d Scott Dale
//returns interface information
1221
function get_interface_info($ifdescr) {
1222 cffe41cb Ermal
	global $config, $g;
1223 6189988d Scott Dale
1224
	$ifinfo = array();
1225 cffe41cb Ermal
	if (empty($config['interfaces'][$ifdescr]))
1226 67ee1ec5 Ermal Luçi
		return;
1227 ebdbdbc2 gnhb
	$ifinfo['hwif'] = $config['interfaces'][$ifdescr]['if'];
1228 cffe41cb Ermal
	$ifinfo['if'] = get_real_interface($ifdescr);
1229 6189988d Scott Dale
1230 cb074893 Ermal Lu?i
	$chkif = $ifinfo['if'];
1231
	$ifinfotmp = pfSense_get_interface_addresses($chkif);
1232
	$ifinfo['status'] = $ifinfotmp['status'];
1233 cffe41cb Ermal
	if (empty($ifinfo['status']))
1234 5fa78adc Renato Botelho
		$ifinfo['status'] = "down";
1235 cb074893 Ermal Lu?i
	$ifinfo['macaddr'] = $ifinfotmp['macaddr'];
1236
	$ifinfo['ipaddr'] = $ifinfotmp['ipaddr'];
1237
	$ifinfo['subnet'] = $ifinfotmp['subnet'];
1238 58418355 smos
	$ifinfo['linklocal'] = get_interface_linklocal($ifdescr);
1239 15cc0894 Seth Mos
	$ifinfo['ipaddrv6'] = get_interface_ipv6($ifdescr);
1240
	$ifinfo['subnetv6'] = get_interface_subnetv6($ifdescr);
1241 a216a03a gnhb
	if (isset($ifinfotmp['link0']))
1242 cb074893 Ermal Lu?i
		$link0 = "down";
1243 cffe41cb Ermal
	$ifinfotmp = pfSense_get_interface_stats($chkif);
1244 5fa78adc Renato Botelho
	// $ifinfo['inpkts'] = $ifinfotmp['inpkts'];
1245
	// $ifinfo['outpkts'] = $ifinfotmp['outpkts'];
1246
	$ifinfo['inerrs'] = $ifinfotmp['inerrs'];
1247
	$ifinfo['outerrs'] = $ifinfotmp['outerrs'];
1248
	$ifinfo['collisions'] = $ifinfotmp['collisions'];
1249 6189988d Scott Dale
1250 01385b0c Scott Ullrich
	/* Use pfctl for non wrapping 64 bit counters */
1251 b5a8483c Seth Mos
	/* Pass */
1252 cb074893 Ermal Lu?i
	exec("/sbin/pfctl -vvsI -i {$chkif}", $pfctlstats);
1253 971eaab5 Seth Mos
	$pf_in4_pass = preg_split("/ +/ ", $pfctlstats[3]);
1254
	$pf_out4_pass = preg_split("/ +/", $pfctlstats[5]);
1255 15cc0894 Seth Mos
	$pf_in6_pass = preg_split("/ +/ ", $pfctlstats[7]);
1256
	$pf_out6_pass = preg_split("/ +/", $pfctlstats[9]);
1257 971eaab5 Seth Mos
	$in4_pass = $pf_in4_pass[5];
1258
	$out4_pass = $pf_out4_pass[5];
1259
	$in4_pass_packets = $pf_in4_pass[3];
1260
	$out4_pass_packets = $pf_out4_pass[3];
1261 15cc0894 Seth Mos
	$in6_pass = $pf_in6_pass[5];
1262
	$out6_pass = $pf_out6_pass[5];
1263
	$in6_pass_packets = $pf_in6_pass[3];
1264
	$out6_pass_packets = $pf_out6_pass[3];
1265
	$ifinfo['inbytespass'] = $in4_pass + $in6_pass;
1266
	$ifinfo['outbytespass'] = $out4_pass + $out6_pass;
1267
	$ifinfo['inpktspass'] = $in4_pass_packets + $in6_pass_packets;
1268 4bdfa5dd Phil Davis
	$ifinfo['outpktspass'] = $out4_pass_packets + $out6_pass_packets;
1269 01385b0c Scott Ullrich
1270 971eaab5 Seth Mos
	/* Block */
1271
	$pf_in4_block = preg_split("/ +/", $pfctlstats[4]);
1272
	$pf_out4_block = preg_split("/ +/", $pfctlstats[6]);
1273 15cc0894 Seth Mos
	$pf_in6_block = preg_split("/ +/", $pfctlstats[8]);
1274
	$pf_out6_block = preg_split("/ +/", $pfctlstats[10]);
1275 971eaab5 Seth Mos
	$in4_block = $pf_in4_block[5];
1276
	$out4_block = $pf_out4_block[5];
1277
	$in4_block_packets = $pf_in4_block[3];
1278
	$out4_block_packets = $pf_out4_block[3];
1279 15cc0894 Seth Mos
	$in6_block = $pf_in6_block[5];
1280
	$out6_block = $pf_out6_block[5];
1281
	$in6_block_packets = $pf_in6_block[3];
1282
	$out6_block_packets = $pf_out6_block[3];
1283
	$ifinfo['inbytesblock'] = $in4_block + $in6_block;
1284
	$ifinfo['outbytesblock'] = $out4_block + $out6_block;
1285
	$ifinfo['inpktsblock'] = $in4_block_packets + $in6_block_packets;
1286
	$ifinfo['outpktsblock'] = $out4_block_packets + $out6_block_packets;
1287
1288
	$ifinfo['inbytes'] = $in4_pass + $in6_pass;
1289
	$ifinfo['outbytes'] = $out4_pass + $out6_pass;
1290
	$ifinfo['inpkts'] = $in4_pass_packets + $in6_pass_packets;
1291 4bdfa5dd Phil Davis
	$ifinfo['outpkts'] = $out4_pass_packets + $out6_pass_packets;
1292 5fa78adc Renato Botelho
1293 63161b3f Ermal Luçi
	$ifconfiginfo = "";
1294 59db783a gnhb
	$link_type = $config['interfaces'][$ifdescr]['ipaddr'];
1295
	switch ($link_type) {
1296 5fa78adc Renato Botelho
	/* DHCP? -> see if dhclient is up */
1297 67ee1ec5 Ermal Luçi
	case "dhcp":
1298 20c79427 Ermal Lu?i
		/* see if dhclient is up */
1299 c4f31aca Ermal Lu?i
		if (find_dhclient_process($ifinfo['if']) <> "")
1300 20c79427 Ermal Lu?i
			$ifinfo['dhcplink'] = "up";
1301
		else
1302
			$ifinfo['dhcplink'] = "down";
1303 63161b3f Ermal Luçi
1304 67ee1ec5 Ermal Luçi
		break;
1305 febca7e8 Ermal
	/* PPPoE/PPTP/L2TP interface? -> get status from virtual interface */
1306 67ee1ec5 Ermal Luçi
	case "pppoe":
1307 febca7e8 Ermal
	case "pptp":
1308
	case "l2tp":
1309 cffe41cb Ermal
		if ($ifinfo['status'] == "up" && !isset($link0))
1310 59db783a gnhb
			/* get PPPoE link status for dial on demand */
1311 febca7e8 Ermal
			$ifinfo["{$link_type}link"] = "up";
1312 20c79427 Ermal Lu?i
		else
1313 febca7e8 Ermal
			$ifinfo["{$link_type}link"] = "down";
1314 6189988d Scott Dale
1315 67ee1ec5 Ermal Luçi
		break;
1316 8eb2f33a Scott Ullrich
	/* PPP interface? -> get uptime for this session and cumulative uptime from the persistant log file in conf */
1317 9ebe7028 gnhb
	case "ppp":
1318 cffe41cb Ermal
		if ($ifinfo['status'] == "up")
1319 c90f2471 gnhb
			$ifinfo['ppplink'] = "up";
1320
		else
1321
			$ifinfo['ppplink'] = "down" ;
1322
1323
		if (empty($ifinfo['status']))
1324
			$ifinfo['status'] = "down";
1325 5fa78adc Renato Botelho
1326 badbe349 gnhb
		if (is_array($config['ppps']['ppp']) && count($config['ppps']['ppp'])) {
1327
			foreach ($config['ppps']['ppp'] as $pppid => $ppp) {
1328 f7480829 gnhb
				if ($config['interfaces'][$ifdescr]['if'] == $ppp['if'])
1329 badbe349 gnhb
					break;
1330
			}
1331
		}
1332 42809b4a gnhb
		$dev = $ppp['ports'];
1333 f7480829 gnhb
		if ($config['interfaces'][$ifdescr]['if'] != $ppp['if'] || empty($dev))
1334 611ae852 Ermal
			break;
1335 59db783a gnhb
		if (!file_exists($dev)) {
1336 c90f2471 gnhb
			$ifinfo['nodevice'] = 1;
1337 5fa78adc Renato Botelho
			$ifinfo['pppinfo'] = $dev . " " . gettext("device not present! Is the modem attached to the system?");
1338 611ae852 Ermal
		}
1339 5e589685 smos
1340 4adf752c smos
		$usbmodemoutput = array();
1341
		exec("usbconfig", $usbmodemoutput);
1342 852171dd smos
		$mondev = "{$g['tmp_path']}/3gstats.{$ifdescr}";
1343 5e589685 smos
		if(file_exists($mondev)) {
1344
			$cellstats = file($mondev);
1345 d23e157a smos
			/* skip header */
1346 5e589685 smos
			$a_cellstats = explode(",", $cellstats[1]);
1347 4adf752c smos
			if(preg_match("/huawei/i", implode("\n", $usbmodemoutput))) {
1348
				$ifinfo['cell_rssi'] = huawei_rssi_to_string($a_cellstats[1]);
1349
				$ifinfo['cell_mode'] = huawei_mode_to_string($a_cellstats[2], $a_cellstats[3]);
1350
				$ifinfo['cell_simstate'] = huawei_simstate_to_string($a_cellstats[10]);
1351
				$ifinfo['cell_service'] = huawei_service_to_string(trim($a_cellstats[11]));
1352
			}
1353
			if(preg_match("/zte/i", implode("\n", $usbmodemoutput))) {
1354
				$ifinfo['cell_rssi'] = zte_rssi_to_string($a_cellstats[1]);
1355
				$ifinfo['cell_mode'] = zte_mode_to_string($a_cellstats[2], $a_cellstats[3]);
1356
				$ifinfo['cell_simstate'] = zte_simstate_to_string($a_cellstats[10]);
1357
				$ifinfo['cell_service'] = zte_service_to_string(trim($a_cellstats[11]));
1358
			}
1359 d23e157a smos
			$ifinfo['cell_upstream'] = $a_cellstats[4];
1360
			$ifinfo['cell_downstream'] = trim($a_cellstats[5]);
1361
			$ifinfo['cell_sent'] = $a_cellstats[6];
1362
			$ifinfo['cell_received'] = trim($a_cellstats[7]);
1363
			$ifinfo['cell_bwupstream'] = $a_cellstats[8];
1364
			$ifinfo['cell_bwdownstream'] = trim($a_cellstats[9]);
1365 5e589685 smos
		}
1366 611ae852 Ermal
		// Calculate cumulative uptime for PPP link. Useful for connections that have per minute/hour contracts so you don't go over!
1367 59db783a gnhb
		if (isset($ppp['uptime']))
1368
			$ifinfo['ppp_uptime_accumulated'] = "(".get_ppp_uptime($ifinfo['if']).")";
1369 67ee1ec5 Ermal Luçi
		break;
1370 63161b3f Ermal Luçi
	default:
1371
		break;
1372 6189988d Scott Dale
	}
1373 5fa78adc Renato Botelho
1374 59db783a gnhb
	if (file_exists("{$g['varrun_path']}/{$link_type}_{$ifdescr}.pid")) {
1375
		$sec = trim(`/usr/local/sbin/ppp-uptime.sh {$ifinfo['if']}`);
1376
		$ifinfo['ppp_uptime'] = convert_seconds_to_hms($sec);
1377
	}
1378 5fa78adc Renato Botelho
1379 6189988d Scott Dale
	if ($ifinfo['status'] == "up") {
1380
		/* try to determine media with ifconfig */
1381
		unset($ifconfiginfo);
1382 818a6b7d Seth Mos
		exec("/sbin/ifconfig " . $ifinfo['if'], $ifconfiginfo);
1383
		$wifconfiginfo = array();
1384
		if(is_interface_wireless($ifdescr)) {
1385
			exec("/sbin/ifconfig {$ifinfo['if']} list sta", $wifconfiginfo);
1386
			array_shift($wifconfiginfo);
1387
		}
1388 6189988d Scott Dale
		$matches = "";
1389
		foreach ($ifconfiginfo as $ici) {
1390
1391
			/* don't list media/speed for wireless cards, as it always
1392
			   displays 2 Mbps even though clients can connect at 11 Mbps */
1393
			if (preg_match("/media: .*? \((.*?)\)/", $ici, $matches)) {
1394
				$ifinfo['media'] = $matches[1];
1395
			} else if (preg_match("/media: Ethernet (.*)/", $ici, $matches)) {
1396
				$ifinfo['media'] = $matches[1];
1397
			} else if (preg_match("/media: IEEE 802.11 Wireless Ethernet (.*)/", $ici, $matches)) {
1398
				$ifinfo['media'] = $matches[1];
1399
			}
1400
1401
			if (preg_match("/status: (.*)$/", $ici, $matches)) {
1402
				if ($matches[1] != "active")
1403
					$ifinfo['status'] = $matches[1];
1404 7d1b238c Carlos Eduardo Ramos
				if($ifinfo['status'] == gettext("running"))
1405
					$ifinfo['status'] = gettext("up");
1406 6189988d Scott Dale
			}
1407
			if (preg_match("/channel (\S*)/", $ici, $matches)) {
1408
				$ifinfo['channel'] = $matches[1];
1409
			}
1410
			if (preg_match("/ssid (\".*?\"|\S*)/", $ici, $matches)) {
1411
				if ($matches[1][0] == '"')
1412
					$ifinfo['ssid'] = substr($matches[1], 1, -1);
1413
				else
1414
					$ifinfo['ssid'] = $matches[1];
1415
			}
1416 0b29093b jim-p
			if (preg_match("/laggproto (.*)$/", $ici, $matches)) {
1417
				$ifinfo['laggproto'] = $matches[1];
1418
			}
1419
			if (preg_match("/laggport: (.*)$/", $ici, $matches)) {
1420
				$ifinfo['laggport'][] = $matches[1];
1421
			}
1422 6189988d Scott Dale
		}
1423 818a6b7d Seth Mos
		foreach($wifconfiginfo as $ici) {
1424
			$elements = preg_split("/[ ]+/i", $ici);
1425
			if ($elements[0] != "") {
1426
				$ifinfo['bssid'] = $elements[0];
1427
			}
1428
			if ($elements[3] != "") {
1429
				$ifinfo['rate'] = $elements[3];
1430
			}
1431
			if ($elements[4] != "") {
1432
				$ifinfo['rssi'] = $elements[4];
1433
			}
1434
1435
		}
1436 67ee1ec5 Ermal Luçi
		/* lookup the gateway */
1437 2bbb79cb Seth Mos
		if (interface_has_gateway($ifdescr)) {
1438 ebdbdbc2 gnhb
			$ifinfo['gateway'] = get_interface_gateway($ifdescr);
1439 2bbb79cb Seth Mos
			$ifinfo['gatewayv6'] = get_interface_gateway_v6($ifdescr);
1440
		}
1441 6189988d Scott Dale
	}
1442
1443
	$bridge = "";
1444 7ec05d27 Ermal Luçi
	$bridge = link_interface_to_bridge($ifdescr);
1445 6189988d Scott Dale
	if($bridge) {
1446
		$bridge_text = `/sbin/ifconfig {$bridge}`;
1447
		if(stristr($bridge_text, "blocking") <> false) {
1448 7d1b238c Carlos Eduardo Ramos
			$ifinfo['bridge'] = "<b><font color='red'>" . gettext("blocking") . "</font></b> - " . gettext("check for ethernet loops");
1449 6189988d Scott Dale
			$ifinfo['bridgeint'] = $bridge;
1450
		} else if(stristr($bridge_text, "learning") <> false) {
1451 7d1b238c Carlos Eduardo Ramos
			$ifinfo['bridge'] = gettext("learning");
1452 6189988d Scott Dale
			$ifinfo['bridgeint'] = $bridge;
1453
		} else if(stristr($bridge_text, "forwarding") <> false) {
1454 7d1b238c Carlos Eduardo Ramos
			$ifinfo['bridge'] = gettext("forwarding");
1455 6189988d Scott Dale
			$ifinfo['bridgeint'] = $bridge;
1456
		}
1457
	}
1458
1459
	return $ifinfo;
1460
}
1461
1462
//returns cpu speed of processor. Good for determining capabilities of machine
1463
function get_cpu_speed() {
1464 1d9b51c6 Renato Botelho
	return exec("/sbin/sysctl -n hw.clockrate");
1465 6189988d Scott Dale
}
1466 fab7ff44 Bill Marquette
1467 df0cb10b Phil Davis
function get_uptime_sec() {
1468
	$boottime = "";
1469
	$matches = "";
1470
	exec("/sbin/sysctl -n kern.boottime", $boottime);
1471
	preg_match("/sec = (\d+)/", $boottime[0], $matches);
1472
	$boottime = $matches[1];
1473
	if(intval($boottime) == 0)
1474
		return 0;
1475
1476
	$uptime = time() - $boottime;
1477
	return $uptime;
1478
}
1479
1480 a5f94f14 Scott Ullrich
function add_hostname_to_watch($hostname) {
1481 c941ea1c Seth Mos
	if(!is_dir("/var/db/dnscache")) {
1482
		mkdir("/var/db/dnscache");
1483
	}
1484 2d0c5e3e Renato Botelho
	$result = array();
1485 5f31bf01 Seth Mos
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1486 581e772e Seth Mos
		$domrecords = array();
1487
		$domips = array();
1488 873c1701 Renato Botelho
		exec("host -t A " . escapeshellarg($hostname), $domrecords, $rethost);
1489 581e772e Seth Mos
		if($rethost == 0) {
1490
			foreach($domrecords as $domr) {
1491
				$doml = explode(" ", $domr);
1492
				$domip = $doml[3];
1493
				/* fill array with domain ip addresses */
1494
				if(is_ipaddr($domip)) {
1495
					$domips[] = $domip;
1496
				}
1497
			}
1498
		}
1499
		sort($domips);
1500
		$contents = "";
1501
		if(! empty($domips)) {
1502 162c059e Seth Mos
			foreach($domips as $ip) {
1503
				$contents .= "$ip\n";
1504
			}
1505 581e772e Seth Mos
		}
1506
		file_put_contents("/var/db/dnscache/$hostname", $contents);
1507 aa57f965 Renato Botelho
		/* Remove empty elements */
1508
		$result = array_filter(explode("\n", $contents), 'strlen');
1509 a5f94f14 Scott Ullrich
	}
1510 2d0c5e3e Renato Botelho
	return $result;
1511 a5f94f14 Scott Ullrich
}
1512
1513 5ed54b93 Seth Mos
function is_fqdn($fqdn) {
1514
	$hostname = false;
1515
	if(preg_match("/[-A-Z0-9\.]+\.[-A-Z0-9\.]+/i", $fqdn)) {
1516
		$hostname = true;
1517
	}
1518
	if(preg_match("/\.\./", $fqdn)) {
1519
		$hostname = false;
1520
	}
1521 5fa78adc Renato Botelho
	if(preg_match("/^\./i", $fqdn)) {
1522 5ed54b93 Seth Mos
		$hostname = false;
1523
	}
1524 c941ea1c Seth Mos
	if(preg_match("/\//i", $fqdn)) {
1525
		$hostname = false;
1526
	}
1527 5ed54b93 Seth Mos
	return($hostname);
1528
}
1529
1530 639aaa95 Bill Marquette
function pfsense_default_state_size() {
1531 5fa78adc Renato Botelho
	/* get system memory amount */
1532
	$memory = get_memory();
1533 386758bb Phil Davis
	$physmem = $memory[0];
1534 5fa78adc Renato Botelho
	/* Be cautious and only allocate 10% of system memory to the state table */
1535 386758bb Phil Davis
	$max_states = (int) ($physmem/10)*1000;
1536 5fa78adc Renato Botelho
	return $max_states;
1537 639aaa95 Bill Marquette
}
1538
1539 84aea606 jim-p
function pfsense_default_tables_size() {
1540
	$current = `pfctl -sm | grep ^tables | awk '{print $4};'`;
1541
	return $current;
1542
}
1543
1544 fb586a16 jim-p
function pfsense_default_table_entries_size() {
1545
	$current = `pfctl -sm | grep table-entries | awk '{print $4};'`;
1546
	return $current;
1547
}
1548
1549 7723c7e0 Seth Mos
/* Compare the current hostname DNS to the DNS cache we made
1550
 * if it has changed we return the old records
1551 046b8ba6 Renato Botelho
 * if no change we return false */
1552 7723c7e0 Seth Mos
function compare_hostname_to_dnscache($hostname) {
1553
	if(!is_dir("/var/db/dnscache")) {
1554
		mkdir("/var/db/dnscache");
1555
	}
1556
	$hostname = trim($hostname);
1557
	if(is_readable("/var/db/dnscache/{$hostname}")) {
1558
		$oldcontents = file_get_contents("/var/db/dnscache/{$hostname}");
1559
	} else {
1560
		$oldcontents = "";
1561
	}
1562
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1563
		$domrecords = array();
1564
		$domips = array();
1565 873c1701 Renato Botelho
		exec("host -t A " . escapeshellarg($hostname), $domrecords, $rethost);
1566 7723c7e0 Seth Mos
		if($rethost == 0) {
1567
			foreach($domrecords as $domr) {
1568
				$doml = explode(" ", $domr);
1569
				$domip = $doml[3];
1570
				/* fill array with domain ip addresses */
1571
				if(is_ipaddr($domip)) {
1572
					$domips[] = $domip;
1573
				}
1574
			}
1575
		}
1576
		sort($domips);
1577
		$contents = "";
1578
		if(! empty($domips)) {
1579
			foreach($domips as $ip) {
1580
				$contents .= "$ip\n";
1581
			}
1582
		}
1583
	}
1584
1585
	if(trim($oldcontents) != trim($contents)) {
1586 a5f91ef4 Seth Mos
		if($g['debug']) {
1587 addc0439 Renato Botelho
			log_error(sprintf(gettext('DNSCACHE: Found old IP %1$s and new IP %2$s'), $oldcontents, $contents));
1588 a5f91ef4 Seth Mos
		}
1589 7723c7e0 Seth Mos
		return ($oldcontents);
1590
	} else {
1591
		return false;
1592
	}
1593
}
1594
1595 09f18f59 jim-p
/*
1596 7530177c jim-p
 * load_crypto() - Load crypto modules if enabled in config.
1597 09f18f59 jim-p
 */
1598 7530177c jim-p
function load_crypto() {
1599 09f18f59 jim-p
	global $config, $g;
1600 7530177c jim-p
	$crypto_modules = array('glxsb', 'aesni');
1601
1602
	if (!in_array($config['system']['crypto_hardware'], $crypto_modules))
1603
		return false;
1604
1605 3d74b803 jim-p
	if (!empty($config['system']['crypto_hardware']) && !is_module_loaded($config['system']['crypto_hardware'])) {
1606 7530177c jim-p
		log_error("Loading {$config['system']['crypto_hardware']} cryptographic accelerator module.");
1607
		mwexec("/sbin/kldload {$config['system']['crypto_hardware']}");
1608 09f18f59 jim-p
	}
1609
}
1610
1611 f60156f6 jim-p
/*
1612
 * load_thermal_hardware() - Load temperature monitor kernel module
1613
 */
1614
function load_thermal_hardware() {
1615
	global $config, $g;
1616
	$thermal_hardware_modules = array('coretemp', 'amdtemp');
1617
1618
	if (!in_array($config['system']['thermal_hardware'], $thermal_hardware_modules))
1619
		return false;
1620
1621 3d74b803 jim-p
	if (!empty($config['system']['thermal_hardware']) && !is_module_loaded($config['system']['thermal_hardware'])) {
1622 f60156f6 jim-p
		log_error("Loading {$config['system']['thermal_hardware']} thermal monitor module.");
1623
		mwexec("/sbin/kldload {$config['system']['thermal_hardware']}");
1624
	}
1625
}
1626
1627 cde4f5d3 Scott Ullrich
/****f* pfsense-utils/isvm
1628
 * NAME
1629
 *   isvm
1630
 * INPUTS
1631 c96e71d1 Renato Botelho
 *	none
1632 cde4f5d3 Scott Ullrich
 * RESULT
1633
 *   returns true if machine is running under a virtual environment
1634
 ******/
1635
function isvm() {
1636
	$virtualenvs = array("vmware", "parallels", "qemu", "bochs", "plex86");
1637 928dc66a Ermal
	$bios_product = trim(`/bin/kenv smbios.system.product`);
1638 58897b8c Warren Baker
	foreach ($virtualenvs as $virtualenv)
1639
		if (stripos($bios_product, $virtualenv) !== false)
1640
			return true;
1641
1642
	return false;
1643 cde4f5d3 Scott Ullrich
}
1644
1645 e0d0eb71 Scott Ullrich
function get_freebsd_version() {
1646 54597012 Renato Botelho
	$version = explode(".", php_uname("r"));
1647
	return $version[0];
1648 e0d0eb71 Scott Ullrich
}
1649
1650 ffd7802a Renato Botelho
function download_file($url, $destination, $verify_ssl = false, $connect_timeout = 60, $timeout = 0) {
1651
	global $config, $g;
1652
1653
	$fp = fopen($destination, "wb");
1654
1655
	if (!$fp)
1656
		return false;
1657
1658
	$ch = curl_init();
1659
	curl_setopt($ch, CURLOPT_URL, $url);
1660
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $verify_ssl);
1661
	curl_setopt($ch, CURLOPT_FILE, $fp);
1662
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connect_timeout);
1663
	curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1664
	curl_setopt($ch, CURLOPT_HEADER, false);
1665
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1666
	curl_setopt($ch, CURLOPT_USERAGENT, $g['product_name'] . '/' . rtrim(file_get_contents("/etc/version")));
1667
1668
	if (!empty($config['system']['proxyurl'])) {
1669
		curl_setopt($ch, CURLOPT_PROXY, $config['system']['proxyurl']);
1670
		if (!empty($config['system']['proxyport']))
1671
			curl_setopt($ch, CURLOPT_PROXYPORT, $config['system']['proxyport']);
1672
		if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
1673
			@curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY | CURLAUTH_ANYSAFE);
1674
			curl_setopt($ch, CURLOPT_PROXYUSERPWD, "{$config['system']['proxyuser']}:{$config['system']['proxypass']}");
1675
		}
1676
	}
1677
1678
	@curl_exec($ch);
1679
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1680
	fclose($fp);
1681
	curl_close($ch);
1682
	return ($http_code == 200) ? true : $http_code;
1683
}
1684
1685 d164643a jim-p
function download_file_with_progress_bar($url_file, $destination_file, $readbody = 'read_body', $connect_timeout=60, $timeout=0) {
1686 5fa78adc Renato Botelho
	global $ch, $fout, $file_size, $downloaded, $config, $first_progress_update;
1687
	$file_size  = 1;
1688
	$downloaded = 1;
1689 e961bd67 phildd
	$first_progress_update = TRUE;
1690 5fa78adc Renato Botelho
	/* open destination file */
1691
	$fout = fopen($destination_file, "wb");
1692
1693
	/*
1694
	 *      Originally by Author: Keyvan Minoukadeh
1695
	 *      Modified by Scott Ullrich to return Content-Length size
1696
	 */
1697
1698
	$ch = curl_init();
1699
	curl_setopt($ch, CURLOPT_URL, $url_file);
1700
	curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
1701
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1702
	/* Don't verify SSL peers since we don't have the certificates to do so. */
1703
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1704
	curl_setopt($ch, CURLOPT_WRITEFUNCTION, $readbody);
1705
	curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
1706
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connect_timeout);
1707
	curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
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
function update_alias_url_data() {
1894
	global $config, $g;
1895 e5953c68 Ermal
1896 f6ba4bd1 Scott Ullrich
	/* item is a url type */
1897
	$lockkey = lock('config');
1898 e5953c68 Ermal
	if (is_array($config['aliases']['alias'])) {
1899
		foreach ($config['aliases']['alias'] as $x => $alias) {
1900
			if (empty($alias['aliasurl']))
1901
				continue;
1902
1903 2ef16014 bcyrill
			$address = "";
1904 f6ba4bd1 Scott Ullrich
			$isfirst = 0;
1905 2ef16014 bcyrill
			foreach ($alias['aliasurl'] as $alias_url) {
1906
				/* fetch down and add in */
1907
				$temp_filename = tempnam("{$g['tmp_path']}/", "alias_import");
1908
				unlink($temp_filename);
1909 76590ffe Renato Botelho
				$verify_ssl = isset($config['system']['checkaliasesurlcert']);
1910 873c1701 Renato Botelho
				mkdir($temp_filename);
1911 76590ffe Renato Botelho
				download_file($alias_url, $temp_filename . "/aliases", $verify_ssl);
1912
1913 2ef16014 bcyrill
				/* if the item is tar gzipped then extract */
1914
				if (stristr($alias_url, ".tgz"))
1915
					process_alias_tgz($temp_filename);
1916
				else if (stristr($alias_url, ".zip"))
1917
					process_alias_unzip($temp_filename);
1918
				if (file_exists("{$temp_filename}/aliases")) {
1919
					$file_contents = file_get_contents("{$temp_filename}/aliases");
1920
					$file_contents = str_replace("#", "\n#", $file_contents);
1921
					$file_contents_split = explode("\n", $file_contents);
1922
					foreach ($file_contents_split as $fc) {
1923
						$tmp = trim($fc);
1924
						if (stristr($fc, "#")) {
1925
							$tmp_split = explode("#", $tmp);
1926
							$tmp = trim($tmp_split[0]);
1927
						}
1928
						if (trim($tmp) <> "") {
1929
							if ($isfirst == 1)
1930
								$address .= " ";
1931
							$address .= $tmp;
1932
							$isfirst = 1;
1933
						}
1934 f6ba4bd1 Scott Ullrich
					}
1935 2ef16014 bcyrill
					mwexec("/bin/rm -rf {$temp_filename}");
1936 f6ba4bd1 Scott Ullrich
				}
1937 2ef16014 bcyrill
			}
1938
			if($isfirst > 0) {
1939
				$config['aliases']['alias'][$x]['address'] = $address;
1940
				$updated = true;
1941 f6ba4bd1 Scott Ullrich
			}
1942
		}
1943
	}
1944 26d060bc Ermal
	unlock($lockkey);
1945 2ef16014 bcyrill
	if ($updated)
1946 f6ba4bd1 Scott Ullrich
		write_config();
1947
}
1948
1949 10189b2a Scott Ullrich
function process_alias_unzip($temp_filename) {
1950
	if(!file_exists("/usr/local/bin/unzip"))
1951
		return;
1952 873c1701 Renato Botelho
	rename("{$temp_filename}/aliases", "{$temp_filename}/aliases.zip");
1953 10189b2a Scott Ullrich
	mwexec("/usr/local/bin/unzip {$temp_filename}/aliases.tgz -d {$temp_filename}/aliases/");
1954
	unlink("{$temp_filename}/aliases.zip");
1955
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1956
	/* foreach through all extracted files and build up aliases file */
1957
	$fd = fopen("{$temp_filename}/aliases", "w");
1958
	foreach($files_to_process as $f2p) {
1959
		$file_contents = file_get_contents($f2p);
1960
		fwrite($fd, $file_contents);
1961
		unlink($f2p);
1962
	}
1963
	fclose($fd);
1964
}
1965
1966 f6ba4bd1 Scott Ullrich
function process_alias_tgz($temp_filename) {
1967 10189b2a Scott Ullrich
	if(!file_exists("/usr/bin/tar"))
1968
		return;
1969 873c1701 Renato Botelho
	rename("{$temp_filename}/aliases", "{$temp_filename}/aliases.tgz");
1970 f6ba4bd1 Scott Ullrich
	mwexec("/usr/bin/tar xzf {$temp_filename}/aliases.tgz -C {$temp_filename}/aliases/");
1971
	unlink("{$temp_filename}/aliases.tgz");
1972
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1973
	/* foreach through all extracted files and build up aliases file */
1974
	$fd = fopen("{$temp_filename}/aliases", "w");
1975
	foreach($files_to_process as $f2p) {
1976
		$file_contents = file_get_contents($f2p);
1977
		fwrite($fd, $file_contents);
1978
		unlink($f2p);
1979
	}
1980
	fclose($fd);
1981
}
1982
1983 a76c1c45 jim-p
function version_compare_dates($a, $b) {
1984
	$a_time = strtotime($a);
1985
	$b_time = strtotime($b);
1986
1987
	if ((!$a_time) || (!$b_time)) {
1988
		return FALSE;
1989
	} else {
1990 bda131b2 jim-p
		if ($a_time < $b_time)
1991 a76c1c45 jim-p
			return -1;
1992 ba6a4606 jim-p
		elseif ($a_time == $b_time)
1993 a76c1c45 jim-p
			return 0;
1994
		else
1995
			return 1;
1996
	}
1997
}
1998
function version_get_string_value($a) {
1999
	$strs = array(
2000
		0 => "ALPHA-ALPHA",
2001
		2 => "ALPHA",
2002
		3 => "BETA",
2003
		4 => "B",
2004 5eb03383 jim-p
		5 => "C",
2005
		6 => "D",
2006
		7 => "RC",
2007 f8c8d65c Stilez
		8 => "RELEASE",
2008
		9 => "*"			// Matches all release levels
2009 a76c1c45 jim-p
	);
2010
	$major = 0;
2011
	$minor = 0;
2012
	foreach ($strs as $num => $str) {
2013
		if (substr($a, 0, strlen($str)) == $str) {
2014
			$major = $num;
2015
			$n = substr($a, strlen($str));
2016
			if (is_numeric($n))
2017
				$minor = $n;
2018
			break;
2019
		}
2020
	}
2021
	return "{$major}.{$minor}";
2022
}
2023
function version_compare_string($a, $b) {
2024 f8c8d65c Stilez
	// Only compare string parts if both versions give a specific release
2025
	// (If either version lacks a string part, assume intended to match all release levels)
2026 c96e71d1 Renato Botelho
	if (isset($a) && isset($b))
2027
		return version_compare_numeric(version_get_string_value($a), version_get_string_value($b));
2028
	else
2029
		return 0;
2030 a76c1c45 jim-p
}
2031
function version_compare_numeric($a, $b) {
2032
	$a_arr = explode('.', rtrim($a, '.0'));
2033
	$b_arr = explode('.', rtrim($b, '.0'));
2034
2035
	foreach ($a_arr as $n => $val) {
2036
		if (array_key_exists($n, $b_arr)) {
2037
			// So far so good, both have values at this minor version level. Compare.
2038
			if ($val > $b_arr[$n])
2039
				return 1;
2040
			elseif ($val < $b_arr[$n])
2041
				return -1;
2042
		} else {
2043
			// a is greater, since b doesn't have any minor version here.
2044
			return 1;
2045
		}
2046
	}
2047
	if (count($b_arr) > count($a_arr)) {
2048
		// b is longer than a, so it must be greater.
2049
		return -1;
2050
	} else {
2051
		// Both a and b are of equal length and value.
2052
		return 0;
2053
	}
2054
}
2055
function pfs_version_compare($cur_time, $cur_text, $remote) {
2056
	// First try date compare
2057 bda131b2 jim-p
	$v = version_compare_dates($cur_time, $remote);
2058 a76c1c45 jim-p
	if ($v === FALSE) {
2059
		// If that fails, try to compare by string
2060
		// Before anything else, simply test if the strings are equal
2061 b009b153 jim-p
		if (($cur_text == $remote) || ($cur_time == $remote))
2062 a76c1c45 jim-p
			return 0;
2063
		list($cur_num, $cur_str) = explode('-', $cur_text);
2064
		list($rem_num, $rem_str) = explode('-', $remote);
2065
2066
		// First try to compare the numeric parts of the version string.
2067
		$v = version_compare_numeric($cur_num, $rem_num);
2068
2069
		// If the numeric parts are the same, compare the string parts.
2070
		if ($v == 0)
2071
			return version_compare_string($cur_str, $rem_str);
2072
	}
2073
	return $v;
2074
}
2075 c7de8be4 jim-p
function process_alias_urltable($name, $url, $freq, $forceupdate=false) {
2076 dd042c51 Renato Botelho
	global $config;
2077
2078 c7de8be4 jim-p
	$urltable_prefix = "/var/db/aliastables/";
2079
	$urltable_filename = $urltable_prefix . $name . ".txt";
2080
2081
	// Make the aliases directory if it doesn't exist
2082
	if (!file_exists($urltable_prefix)) {
2083
		mkdir($urltable_prefix);
2084
	} elseif (!is_dir($urltable_prefix)) {
2085
		unlink($urltable_prefix);
2086
		mkdir($urltable_prefix);
2087
	}
2088
2089
	// If the file doesn't exist or is older than update_freq days, fetch a new copy.
2090
	if (!file_exists($urltable_filename)
2091 e09da6c2 Renato Botelho
		|| ((time() - filemtime($urltable_filename)) > ($freq * 86400 - 90))
2092 c7de8be4 jim-p
		|| $forceupdate) {
2093
2094
		// Try to fetch the URL supplied
2095
		conf_mount_rw();
2096
		unlink_if_exists($urltable_filename . ".tmp");
2097 dd042c51 Renato Botelho
		$verify_ssl = isset($config['system']['checkaliasesurlcert']);
2098
		if (download_file($url, $urltable_filename . ".tmp", $verify_ssl)) {
2099
			mwexec("/usr/bin/sed -E 's/\;.*//g; /^[[:space:]]*($|#)/d' ". escapeshellarg($urltable_filename . ".tmp") . " > " . escapeshellarg($urltable_filename));
2100
			if (alias_get_type($name) == "urltable_ports") {
2101
				$ports = explode("\n", file_get_contents($urltable_filename));
2102
				$ports = group_ports($ports);
2103
				file_put_contents($urltable_filename, implode("\n", $ports));
2104
			}
2105 4aa0979f Ermal
			unlink_if_exists($urltable_filename . ".tmp");
2106
		} else
2107 873c1701 Renato Botelho
			touch($urltable_filename);
2108 c7de8be4 jim-p
		conf_mount_ro();
2109 966f359e Ermal
		return true;
2110 c7de8be4 jim-p
	} else {
2111
		// File exists, and it doesn't need updated.
2112
		return -1;
2113
	}
2114
}
2115 08fd5444 jim-p
function get_real_slice_from_glabel($label) {
2116
	$label = escapeshellarg($label);
2117
	return trim(`/sbin/glabel list | /usr/bin/grep -B2 ufs/{$label} | /usr/bin/head -n 1 | /usr/bin/cut -f3 -d' '`);
2118
}
2119
function nanobsd_get_boot_slice() {
2120
	return trim(`/sbin/mount | /usr/bin/grep pfsense | /usr/bin/cut -d'/' -f4 | /usr/bin/cut -d' ' -f1`);
2121
}
2122
function nanobsd_get_boot_drive() {
2123
	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`);
2124
}
2125
function nanobsd_get_active_slice() {
2126
	$boot_drive = nanobsd_get_boot_drive();
2127
	$active = trim(`gpart show $boot_drive | grep '\[active\]' | awk '{print $3;}'`);
2128
2129
	return "{$boot_drive}s{$active}";
2130
}
2131
function nanobsd_get_size() {
2132
	return strtoupper(file_get_contents("/etc/nanosize.txt"));
2133
}
2134 2b5f276f jim-p
function nanobsd_switch_boot_slice() {
2135 08fd5444 jim-p
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2136
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2137
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2138
	nanobsd_detect_slice_info();
2139
2140 2b5f276f jim-p
	if ($BOOTFLASH == $ACTIVE_SLICE) {
2141
		$slice = $TOFLASH;
2142
	} else {
2143
		$slice = $BOOTFLASH;
2144
	}
2145
2146 08fd5444 jim-p
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
2147
	ob_implicit_flush(1);
2148
	if(strstr($slice, "s2")) {
2149
		$ASLICE="2";
2150
		$AOLDSLICE="1";
2151
		$AGLABEL_SLICE="pfsense1";
2152
		$AUFS_ID="1";
2153
		$AOLD_UFS_ID="0";
2154
	} else {
2155
		$ASLICE="1";
2156
		$AOLDSLICE="2";
2157
		$AGLABEL_SLICE="pfsense0";
2158
		$AUFS_ID="0";
2159
		$AOLD_UFS_ID="1";
2160
	}
2161
	$ATOFLASH="{$BOOT_DRIVE}s{$ASLICE}";
2162
	$ACOMPLETE_PATH="{$BOOT_DRIVE}s{$ASLICE}a";
2163
	$ABOOTFLASH="{$BOOT_DRIVE}s{$AOLDSLICE}";
2164
	conf_mount_rw();
2165
	exec("sysctl kern.geom.debugflags=16");
2166
	exec("gpart set -a active -i {$ASLICE} {$BOOT_DRIVE}");
2167
	exec("/usr/sbin/boot0cfg -s {$ASLICE} -v /dev/{$BOOT_DRIVE}");
2168 2b5f276f jim-p
	// We can't update these if they are mounted now.
2169
	if ($BOOTFLASH != $slice) {
2170
		exec("/sbin/tunefs -L ${AGLABEL_SLICE} /dev/$ACOMPLETE_PATH");
2171
		nanobsd_update_fstab($AGLABEL_SLICE, $ACOMPLETE_PATH, $AOLD_UFS_ID, $AUFS_ID);
2172
	}
2173 08fd5444 jim-p
	exec("/sbin/sysctl kern.geom.debugflags=0");
2174
	conf_mount_ro();
2175
}
2176 2b5f276f jim-p
function nanobsd_clone_slice() {
2177 08fd5444 jim-p
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2178
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2179
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2180
	nanobsd_detect_slice_info();
2181
2182
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
2183
	ob_implicit_flush(1);
2184
	exec("/sbin/sysctl kern.geom.debugflags=16");
2185
	exec("/bin/dd if=/dev/zero of=/dev/{$TOFLASH} bs=1m count=1");
2186
	exec("/bin/dd if=/dev/{$BOOTFLASH} of=/dev/{$TOFLASH} bs=64k");
2187
	exec("/sbin/tunefs -L {$GLABEL_SLICE} /dev/{$COMPLETE_PATH}");
2188 2b5f276f jim-p
	$status = nanobsd_update_fstab($GLABEL_SLICE, $COMPLETE_PATH, $OLD_UFS_ID, $UFS_ID);
2189 08fd5444 jim-p
	exec("/sbin/sysctl kern.geom.debugflags=0");
2190
	if($status) {
2191
		return false;
2192
	} else {
2193
		return true;
2194
	}
2195
}
2196 2b5f276f jim-p
function nanobsd_update_fstab($gslice, $complete_path, $oldufs, $newufs) {
2197
	$tmppath = "/tmp/{$gslice}";
2198
	$fstabpath = "/tmp/{$gslice}/etc/fstab";
2199
2200 873c1701 Renato Botelho
	mkdir($tmppath);
2201 2b5f276f jim-p
	exec("/sbin/fsck_ufs -y /dev/{$complete_path}");
2202
	exec("/sbin/mount /dev/ufs/{$gslice} {$tmppath}");
2203 873c1701 Renato Botelho
	copy("/etc/fstab", $fstabpath);
2204 2b5f276f jim-p
2205
	if (!file_exists($fstabpath)) {
2206
		$fstab = <<<EOF
2207 9b1a8d98 Ermal
/dev/ufs/{$gslice} / ufs ro,noatime 1 1
2208
/dev/ufs/cf /cf ufs ro,noatime 1 1
2209 2b5f276f jim-p
EOF;
2210
		if (file_put_contents($fstabpath, $fstab))
2211
			$status = true;
2212
		else
2213
			$status = false;
2214
	} else {
2215
		$status = exec("sed -i \"\" \"s/pfsense{$oldufs}/pfsense{$newufs}/g\" {$fstabpath}");
2216
	}
2217
	exec("/sbin/umount {$tmppath}");
2218 873c1701 Renato Botelho
	rmdir($tmppath);
2219 2b5f276f jim-p
2220
	return $status;
2221
}
2222 08fd5444 jim-p
function nanobsd_detect_slice_info() {
2223
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2224
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2225
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2226 a76c1c45 jim-p
2227 08fd5444 jim-p
	$BOOT_DEVICE=nanobsd_get_boot_slice();
2228
	$REAL_BOOT_DEVICE=get_real_slice_from_glabel($BOOT_DEVICE);
2229
	$BOOT_DRIVE=nanobsd_get_boot_drive();
2230
	$ACTIVE_SLICE=nanobsd_get_active_slice();
2231
2232
	// Detect which slice is active and set information.
2233
	if(strstr($REAL_BOOT_DEVICE, "s1")) {
2234
		$SLICE="2";
2235
		$OLDSLICE="1";
2236
		$GLABEL_SLICE="pfsense1";
2237
		$UFS_ID="1";
2238
		$OLD_UFS_ID="0";
2239 a76c1c45 jim-p
2240 08fd5444 jim-p
	} else {
2241
		$SLICE="1";
2242
		$OLDSLICE="2";
2243
		$GLABEL_SLICE="pfsense0";
2244
		$UFS_ID="0";
2245
		$OLD_UFS_ID="1";
2246
	}
2247
	$TOFLASH="{$BOOT_DRIVE}s{$SLICE}";
2248
	$COMPLETE_PATH="{$BOOT_DRIVE}s{$SLICE}a";
2249
	$COMPLETE_BOOT_PATH="{$BOOT_DRIVE}s{$OLDSLICE}";
2250
	$BOOTFLASH="{$BOOT_DRIVE}s{$OLDSLICE}";
2251
}
2252 38080cc1 Scott Ullrich
2253 26c8cc72 jim-p
function nanobsd_friendly_slice_name($slicename) {
2254
	global $g;
2255
	return strtolower(str_ireplace('pfsense', $g['product_name'], $slicename));
2256
}
2257
2258 38080cc1 Scott Ullrich
function get_include_contents($filename) {
2259 5fa78adc Renato Botelho
	if (is_file($filename)) {
2260
		ob_start();
2261
		include $filename;
2262
		$contents = ob_get_contents();
2263
		ob_end_clean();
2264
		return $contents;
2265
	}
2266
	return false;
2267 38080cc1 Scott Ullrich
}
2268
2269 3ffa8318 Renato Botelho
/* This xml 2 array function is courtesy of the php.net comment section on xml_parse.
2270
 * it is roughly 4 times faster then our existing pfSense parser but due to the large
2271
 * size of the RRD xml dumps this is required.
2272
 * The reason we do not use it for pfSense is that it does not know about array fields
2273
 * which causes it to fail on array fields with single items. Possible Todo?
2274
 */
2275
function xml2array($contents, $get_attributes = 1, $priority = 'tag')
2276
{
2277 86c707f3 Darren Embry
	if (!function_exists('xml_parser_create'))
2278
	{
2279
		return array ();
2280
	}
2281
	$parser = xml_parser_create('');
2282
	xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
2283
	xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
2284
	xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
2285
	xml_parse_into_struct($parser, trim($contents), $xml_values);
2286
	xml_parser_free($parser);
2287
	if (!$xml_values)
2288
		return; //Hmm...
2289
	$xml_array = array ();
2290
	$parents = array ();
2291
	$opened_tags = array ();
2292
	$arr = array ();
2293
	$current = & $xml_array;
2294
	$repeated_tag_index = array ();
2295
	foreach ($xml_values as $data)
2296
	{
2297
		unset ($attributes, $value);
2298
		extract($data);
2299
		$result = array ();
2300
		$attributes_data = array ();
2301
		if (isset ($value))
2302
		{
2303
			if ($priority == 'tag')
2304
				$result = $value;
2305
			else
2306
				$result['value'] = $value;
2307
		}
2308
		if (isset ($attributes) and $get_attributes)
2309
		{
2310
			foreach ($attributes as $attr => $val)
2311
			{
2312
				if ($priority == 'tag')
2313
					$attributes_data[$attr] = $val;
2314
				else
2315
					$result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
2316
			}
2317
		}
2318
		if ($type == "open")
2319
		{
2320
			$parent[$level -1] = & $current;
2321
			if (!is_array($current) or (!in_array($tag, array_keys($current))))
2322
			{
2323
				$current[$tag] = $result;
2324
				if ($attributes_data)
2325
					$current[$tag . '_attr'] = $attributes_data;
2326
				$repeated_tag_index[$tag . '_' . $level] = 1;
2327
				$current = & $current[$tag];
2328
			}
2329
			else
2330
			{
2331
				if (isset ($current[$tag][0]))
2332
				{
2333
					$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
2334
					$repeated_tag_index[$tag . '_' . $level]++;
2335
				}
2336
				else
2337
				{
2338
					$current[$tag] = array (
2339
						$current[$tag],
2340
						$result
2341
						);
2342
					$repeated_tag_index[$tag . '_' . $level] = 2;
2343
					if (isset ($current[$tag . '_attr']))
2344
					{
2345
						$current[$tag]['0_attr'] = $current[$tag . '_attr'];
2346
						unset ($current[$tag . '_attr']);
2347
					}
2348
				}
2349
				$last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
2350
				$current = & $current[$tag][$last_item_index];
2351
			}
2352
		}
2353
		elseif ($type == "complete")
2354
		{
2355
			if (!isset ($current[$tag]))
2356
			{
2357
				$current[$tag] = $result;
2358
				$repeated_tag_index[$tag . '_' . $level] = 1;
2359
				if ($priority == 'tag' and $attributes_data)
2360
					$current[$tag . '_attr'] = $attributes_data;
2361
			}
2362
			else
2363
			{
2364
				if (isset ($current[$tag][0]) and is_array($current[$tag]))
2365
				{
2366
					$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
2367
					if ($priority == 'tag' and $get_attributes and $attributes_data)
2368
					{
2369
						$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
2370
					}
2371
					$repeated_tag_index[$tag . '_' . $level]++;
2372
				}
2373
				else
2374
				{
2375
					$current[$tag] = array (
2376
						$current[$tag],
2377
						$result
2378
						);
2379
					$repeated_tag_index[$tag . '_' . $level] = 1;
2380
					if ($priority == 'tag' and $get_attributes)
2381
					{
2382
						if (isset ($current[$tag . '_attr']))
2383
						{
2384
							$current[$tag]['0_attr'] = $current[$tag . '_attr'];
2385
							unset ($current[$tag . '_attr']);
2386
						}
2387
						if ($attributes_data)
2388
						{
2389
							$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
2390
						}
2391
					}
2392
					$repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
2393
				}
2394
			}
2395
		}
2396
		elseif ($type == 'close')
2397
		{
2398
			$current = & $parent[$level -1];
2399
		}
2400
	}
2401
	return ($xml_array);
2402 3ffa8318 Renato Botelho
}
2403
2404
function get_country_name($country_code) {
2405
	if ($country_code != "ALL" && strlen($country_code) != 2)
2406
		return "";
2407
2408
	$country_names_xml = "/usr/local/share/mobile-broadband-provider-info/iso_3166-1_list_en.xml";
2409
	$country_names_contents = file_get_contents($country_names_xml);
2410
	$country_names = xml2array($country_names_contents);
2411
2412
	if($country_code == "ALL") {
2413
		$country_list = array();
2414
		foreach($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2415 c96e71d1 Renato Botelho
			$country_list[] = array("code" => $country['ISO_3166-1_Alpha-2_Code_element'],
2416
						"name" => ucwords(strtolower($country['ISO_3166-1_Country_name'])) );
2417 3ffa8318 Renato Botelho
		}
2418
		return $country_list;
2419
	}
2420
2421
	foreach ($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2422
		if ($country['ISO_3166-1_Alpha-2_Code_element'] == strtoupper($country_code)) {
2423
			return ucwords(strtolower($country['ISO_3166-1_Country_name']));
2424
		}
2425
	}
2426
	return "";
2427
}
2428
2429 baaa8bb1 Erik Fonnesbeck
/* sort by interface only, retain the original order of rules that apply to
2430
   the same interface */
2431
function filter_rules_sort() {
2432
	global $config;
2433
2434
	/* mark each rule with the sequence number (to retain the order while sorting) */
2435
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2436
		$config['filter']['rule'][$i]['seq'] = $i;
2437
2438
	usort($config['filter']['rule'], "filter_rules_compare");
2439
2440
	/* strip the sequence numbers again */
2441
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2442
		unset($config['filter']['rule'][$i]['seq']);
2443
}
2444
function filter_rules_compare($a, $b) {
2445 cea355a5 Erik Fonnesbeck
	if (isset($a['floating']) && isset($b['floating']))
2446 baaa8bb1 Erik Fonnesbeck
		return $a['seq'] - $b['seq'];
2447
	else if (isset($a['floating']))
2448
		return -1;
2449
	else if (isset($b['floating']))
2450
		return 1;
2451 cea355a5 Erik Fonnesbeck
	else if ($a['interface'] == $b['interface'])
2452
		return $a['seq'] - $b['seq'];
2453 baaa8bb1 Erik Fonnesbeck
	else
2454
		return compare_interface_friendly_names($a['interface'], $b['interface']);
2455
}
2456
2457 22dae853 Seth Mos
function generate_ipv6_from_mac($mac) {
2458
	$elements = explode(":", $mac);
2459
	if(count($elements) <> 6)
2460
		return false;
2461
2462
	$i = 0;
2463 5aa28c86 Seth Mos
	$ipv6 = "fe80::";
2464 22dae853 Seth Mos
	foreach($elements as $byte) {
2465
		if($i == 0) {
2466
			$hexadecimal =  substr($byte, 1, 2);
2467
			$bitmap = base_convert($hexadecimal, 16, 2);
2468
			$bitmap = str_pad($bitmap, 4, "0", STR_PAD_LEFT);
2469
			$bitmap = substr($bitmap, 0, 2) ."1". substr($bitmap, 3,4);
2470
			$byte = substr($byte, 0, 1) . base_convert($bitmap, 2, 16);
2471
		}
2472
		$ipv6 .= $byte;
2473
		if($i == 1) {
2474
			$ipv6 .= ":";
2475
		}
2476
		if($i == 3) {
2477
			$ipv6 .= ":";
2478
		}
2479
		if($i == 2) {
2480
			$ipv6 .= "ff:fe";
2481
		}
2482 5fa78adc Renato Botelho
2483 22dae853 Seth Mos
		$i++;
2484 5fa78adc Renato Botelho
	}
2485 fcdc8943 Seth Mos
	return $ipv6;
2486 22dae853 Seth Mos
}
2487 325e3163 Bill Marquette
2488 57f2840e Evgeny
/****f* pfsense-utils/load_mac_manufacturer_table
2489
 * NAME
2490
 *   load_mac_manufacturer_table
2491
 * INPUTS
2492
 *   none
2493
 * RESULT
2494
 *   returns associative array with MAC-Manufacturer pairs
2495
 ******/
2496
function load_mac_manufacturer_table() {
2497
	/* load MAC-Manufacture data from the file */
2498 62a29fe3 Ermal
	$macs = false;
2499
	if (file_exists("/usr/local/share/nmap/nmap-mac-prefixes"))
2500
		$macs=file("/usr/local/share/nmap/nmap-mac-prefixes");
2501 57f2840e Evgeny
	if ($macs){
2502
		foreach ($macs as $line){
2503
			if (preg_match('/([0-9A-Fa-f]{6}) (.*)$/', $line, $matches)){
2504 4450527f Evgeny
				/* store values like this $mac_man['000C29']='VMware' */
2505 57f2840e Evgeny
				$mac_man["$matches[1]"]=$matches[2];
2506
			}
2507
		}
2508 5fa78adc Renato Botelho
		return $mac_man;
2509 57f2840e Evgeny
	} else
2510
		return -1;
2511
2512
}
2513
2514 474f36d1 Scott Ullrich
/****f* pfsense-utils/is_ipaddr_configured
2515
 * NAME
2516
 *   is_ipaddr_configured
2517
 * INPUTS
2518
 *   IP Address to check.
2519
 * RESULT
2520
 *   returns true if the IP Address is
2521
 *   configured and present on this device.
2522
*/
2523 e6c60013 Renato Botelho
function is_ipaddr_configured($ipaddr, $ignore_if = "", $check_localip = false, $check_subnets = false) {
2524
	global $config;
2525
2526 1e5da31d Ermal
	$isipv6 = is_ipaddrv6($ipaddr);
2527
2528 e6c60013 Renato Botelho
	if ($check_subnets) {
2529
		$iflist = get_configured_interface_list();
2530
		foreach ($iflist as $if => $ifname) {
2531
			if ($ignore_if == $if)
2532
				continue;
2533 2c98a935 Renato Botelho
2534 1e5da31d Ermal
			if ($isipv6 === true) {
2535
				$bitmask = get_interface_subnetv6($if);
2536
				$subnet = gen_subnetv6(get_interface_ipv6($if), $bitmask);
2537
			} else {
2538
				$bitmask = get_interface_subnet($if);
2539
				$subnet = gen_subnet(get_interface_ip($if), $bitmask);
2540
			}
2541 2c98a935 Renato Botelho
2542
			if (ip_in_subnet($ipaddr, $subnet . '/' . $bitmask))
2543
				return true;
2544 e6c60013 Renato Botelho
		}
2545
	} else {
2546 2c98a935 Renato Botelho
		if ($isipv6 === true)
2547
			$interface_list_ips = get_configured_ipv6_addresses();
2548
		else
2549
			$interface_list_ips = get_configured_ip_addresses();
2550
2551 e6c60013 Renato Botelho
		foreach($interface_list_ips as $if => $ilips) {
2552 4021ec36 Renato Botelho
			/* Also ignore CARP interfaces, it'll be checked below */
2553 0c21eb70 Ermal
			if ($ignore_if == $if || strstr($ignore_if, "_vip"))
2554 e6c60013 Renato Botelho
				continue;
2555
			if (strcasecmp($ipaddr, $ilips) == 0)
2556
				return true;
2557
		}
2558 5fa78adc Renato Botelho
	}
2559 a1613b62 Renato Botelho
2560 4021ec36 Renato Botelho
	$interface_list_vips = get_configured_vips_list(true);
2561
	foreach ($interface_list_vips as $id => $vip) {
2562 0c21eb70 Ermal
		if ($ignore_if == $vip['if'])
2563 4021ec36 Renato Botelho
			continue;
2564
		if (strcasecmp($ipaddr, $vip['ipaddr']) == 0)
2565
			return true;
2566
	}
2567
2568 e6c60013 Renato Botelho
	if ($check_localip) {
2569 a1e4e2a7 Ermal
		if (is_array($config['pptpd']) && !empty($config['pptpd']['localip']) && (strcasecmp($ipaddr, $config['pptpd']['localip']) == 0))
2570 e6c60013 Renato Botelho
			return true;
2571
2572 a1e4e2a7 Ermal
		if (!is_array($config['l2tp']) && !empty($config['l2tp']['localip']) && (strcasecmp($ipaddr, $config['l2tp']['localip']) == 0))
2573 a1613b62 Renato Botelho
			return true;
2574
	}
2575
2576
	return false;
2577 474f36d1 Scott Ullrich
}
2578
2579 e4a8ed97 Scott Ullrich
/****f* pfsense-utils/pfSense_handle_custom_code
2580
 * NAME
2581
 *   pfSense_handle_custom_code
2582
 * INPUTS
2583
 *   directory name to process
2584
 * RESULT
2585
 *   globs the directory and includes the files
2586
 */
2587 d65962a7 Scott Ullrich
function pfSense_handle_custom_code($src_dir) {
2588 5fa78adc Renato Botelho
	// Allow extending of the nat edit page and include custom input validation
2589 d65962a7 Scott Ullrich
	if(is_dir("$src_dir")) {
2590 3dbceb92 Scott Ullrich
		$cf = glob($src_dir . "/*.inc");
2591 d65962a7 Scott Ullrich
		foreach($cf as $nf) {
2592 5fa78adc Renato Botelho
			if($nf == "." || $nf == "..")
2593 d65962a7 Scott Ullrich
				continue;
2594
			// Include the extra handler
2595 3dbceb92 Scott Ullrich
			include("$nf");
2596 d65962a7 Scott Ullrich
		}
2597
	}
2598
}
2599
2600 000a8d1d Renato Botelho
function set_language($lang = 'en_US', $encoding = "UTF-8") {
2601 3e139f90 Vinicius Coque
	putenv("LANG={$lang}.{$encoding}");
2602
	setlocale(LC_ALL, "{$lang}.{$encoding}");
2603
	textdomain("pfSense");
2604 a94c4e1f Vinicius Coque
	bindtextdomain("pfSense","/usr/local/share/locale");
2605 3e139f90 Vinicius Coque
	bind_textdomain_codeset("pfSense","{$lang}.{$encoding}");
2606
}
2607
2608
function get_locale_list() {
2609
	$locales = array(
2610
		"en_US" => gettext("English"),
2611 2e2eb012 Vinicius Coque
		"pt_BR" => gettext("Portuguese (Brazil)"),
2612 f079b676 technical50
		"tr" => gettext("Turkish"),
2613 3e139f90 Vinicius Coque
	);
2614
	asort($locales);
2615
	return $locales;
2616
}
2617 20a7cb15 smos
2618 f079b676 technical50
function system_get_language_code() {
2619
	global $config, $g_languages;
2620
2621
	// a language code, as per [RFC3066]
2622
	$language = $config['system']['language'];
2623
	//$code = $g_languages[$language]['code'];
2624
	$code = str_replace("_", "-", $language);
2625
2626
	if (empty($code))
2627
		$code = "en-US"; // Set default code.
2628
2629
	return $code;
2630
}
2631
2632
function system_get_language_codeset() {
2633
	global $config, $g_languages;
2634
2635
	$language = $config['system']['language'];
2636
	$codeset = $g_languages[$language]['codeset'];
2637
2638
	if (empty($codeset))
2639
		$codeset = "UTF-8"; // Set default codeset.
2640
2641
	return $codeset;
2642
}
2643
2644
/* Available languages/locales */
2645
$g_languages = array (
2646
	"sq"    => array("codeset" => "UTF-8", "desc" => gettext("Albanian")),
2647
	"bg"    => array("codeset" => "UTF-8", "desc" => gettext("Bulgarian")),
2648
	"zh_CN" => array("codeset" => "UTF-8", "desc" => gettext("Chinese (Simplified)")),
2649
	"zh_TW" => array("codeset" => "UTF-8", "desc" => gettext("Chinese (Traditional)")),
2650
	"nl"    => array("codeset" => "UTF-8", "desc" => gettext("Dutch")),
2651
	"da"    => array("codeset" => "UTF-8", "desc" => gettext("Danish")),
2652 000a8d1d Renato Botelho
	"en_US" => array("codeset" => "UTF-8", "desc" => gettext("English")),
2653 f079b676 technical50
	"fi"    => array("codeset" => "UTF-8", "desc" => gettext("Finnish")),
2654
	"fr"    => array("codeset" => "UTF-8", "desc" => gettext("French")),
2655
	"de"    => array("codeset" => "UTF-8", "desc" => gettext("German")),
2656
	"el"    => array("codeset" => "UTF-8", "desc" => gettext("Greek")),
2657
	"hu"    => array("codeset" => "UTF-8", "desc" => gettext("Hungarian")),
2658
	"it"    => array("codeset" => "UTF-8", "desc" => gettext("Italian")),
2659
	"ja"    => array("codeset" => "UTF-8", "desc" => gettext("Japanese")),
2660
	"ko"    => array("codeset" => "UTF-8", "desc" => gettext("Korean")),
2661
	"lv"    => array("codeset" => "UTF-8", "desc" => gettext("Latvian")),
2662
	"nb"    => array("codeset" => "UTF-8", "desc" => gettext("Norwegian (Bokmal)")),
2663
	"pl"    => array("codeset" => "UTF-8", "desc" => gettext("Polish")),
2664
	"pt_BR" => array("codeset" => "ISO-8859-1", "desc" => gettext("Portuguese (Brazil)")),
2665
	"pt"    => array("codeset" => "UTF-8", "desc" => gettext("Portuguese (Portugal)")),
2666
	"ro"    => array("codeset" => "UTF-8", "desc" => gettext("Romanian")),
2667
	"ru"    => array("codeset" => "UTF-8", "desc" => gettext("Russian")),
2668
	"sl"    => array("codeset" => "UTF-8", "desc" => gettext("Slovenian")),
2669
	"tr"    => array("codeset" => "UTF-8", "desc" => gettext("Turkish")),
2670
	"es"    => array("codeset" => "UTF-8", "desc" => gettext("Spanish")),
2671
	"sv"    => array("codeset" => "UTF-8", "desc" => gettext("Swedish")),
2672
	"sk"    => array("codeset" => "UTF-8", "desc" => gettext("Slovak")),
2673
	"cs"    => array("codeset" => "UTF-8", "desc" => gettext("Czech"))
2674
);
2675
2676 20a7cb15 smos
function return_hex_ipv4($ipv4) {
2677
	if(!is_ipaddrv4($ipv4))
2678
		return(false);
2679 5fa78adc Renato Botelho
2680 20a7cb15 smos
	/* we need the hex form of the interface IPv4 address */
2681
	$ip4arr = explode(".", $ipv4);
2682 733c6f89 Ermal
	return (sprintf("%02x%02x%02x%02x", $ip4arr[0], $ip4arr[1], $ip4arr[2], $ip4arr[3]));
2683 20a7cb15 smos
}
2684
2685
function convert_ipv6_to_128bit($ipv6) {
2686
	if(!is_ipaddrv6($ipv6))
2687
		return(false);
2688
2689
	$ip6arr = array();
2690
	$ip6prefix = Net_IPv6::uncompress($ipv6);
2691
	$ip6arr = explode(":", $ip6prefix);
2692
	/* binary presentation of the prefix for all 128 bits. */
2693
	$ip6prefixbin = "";
2694
	foreach($ip6arr as $element) {
2695
		$ip6prefixbin .= sprintf("%016b", hexdec($element));
2696
	}
2697
	return($ip6prefixbin);
2698
}
2699
2700
function convert_128bit_to_ipv6($ip6bin) {
2701
	if(strlen($ip6bin) <> 128)
2702
		return(false);
2703
2704
	$ip6arr = array();
2705
	$ip6binarr = array();
2706
	$ip6binarr = str_split($ip6bin, 16);
2707
	foreach($ip6binarr as $binpart)
2708
		$ip6arr[] = dechex(bindec($binpart));
2709
	$ip6addr = Net_IPv6::compress(implode(":", $ip6arr));
2710
2711
	return($ip6addr);
2712
}
2713
2714 8b198c64 smos
2715
/* Returns the calculated bit length of the prefix delegation from the WAN interface */
2716
/* DHCP-PD is variable, calculate from the prefix-len on the WAN interface */
2717
/* 6rd is variable, calculate from 64 - (v6 prefixlen - (32 - v4 prefixlen)) */
2718
/* 6to4 is 16 bits, e.g. 65535 */
2719
function calculate_ipv6_delegation_length($if) {
2720
	global $config;
2721
2722
	if(!is_array($config['interfaces'][$if]))
2723
		return false;
2724
2725
	switch($config['interfaces'][$if]['ipaddrv6']) {
2726
		case "6to4":
2727
			$pdlen = 16;
2728
			break;
2729
		case "6rd":
2730
			$rd6cfg = $config['interfaces'][$if];
2731
			$rd6plen = explode("/", $rd6cfg['prefix-6rd']);
2732
			$pdlen = (64 - ($rd6plen[1] + (32 - $rd6cfg['prefix-6rd-v4plen'])));
2733
			break;
2734
		case "dhcp6":
2735
			$dhcp6cfg = $config['interfaces'][$if];
2736
			$pdlen = $dhcp6cfg['dhcp6-ia-pd-len'];
2737
			break;
2738
		default:
2739
			$pdlen = 0;
2740
			break;
2741
	}
2742
	return($pdlen);
2743
}
2744 d23e157a smos
2745
function huawei_rssi_to_string($rssi) {
2746
	$dbm = array();
2747
	$i = 0;
2748 145cc518 smos
	$dbstart = -113;
2749
	while($i < 32) {
2750
		$dbm[$i] = $dbstart + ($i * 2);
2751 d23e157a smos
		$i++;
2752
	}
2753
	$percent = round(($rssi / 31) * 100);
2754 145cc518 smos
	$string = "rssi:{$rssi} level:{$dbm[$rssi]}dBm percent:{$percent}%";
2755 d23e157a smos
	return $string;
2756
}
2757
2758
function huawei_mode_to_string($mode, $submode) {
2759
	$modes[0] = "None";
2760 5fa78adc Renato Botelho
	$modes[1] = "AMPS";
2761 d23e157a smos
	$modes[2] = "CDMA";
2762
	$modes[3] = "GSM/GPRS";
2763
	$modes[4] = "HDR";
2764
	$modes[5] = "WCDMA";
2765 5fa78adc Renato Botelho
	$modes[6] = "GPS";
2766 d23e157a smos
2767
	$submodes[0] = "No Service";
2768
	$submodes[1] = "GSM";
2769
	$submodes[2] = "GPRS";
2770
	$submodes[3] = "EDGE";
2771
	$submodes[4] = "WCDMA";
2772
	$submodes[5] = "HSDPA";
2773
	$submodes[6] = "HSUPA";
2774 e313da37 smos
	$submodes[7] = "HSDPA+HSUPA";
2775 d23e157a smos
	$submodes[8] = "TD-SCDMA";
2776
	$submodes[9] = "HSPA+";
2777
	$string = "{$modes[$mode]}, {$submodes[$submode]} Mode";
2778
	return $string;
2779
}
2780
2781
function huawei_service_to_string($state) {
2782
	$modes[0] = "No";
2783 5fa78adc Renato Botelho
	$modes[1] = "Restricted";
2784 d23e157a smos
	$modes[2] = "Valid";
2785
	$modes[3] = "Restricted Regional";
2786
	$modes[4] = "Powersaving";
2787
	$string = "{$modes[$state]} Service";
2788
	return $string;
2789
}
2790
2791
function huawei_simstate_to_string($state) {
2792
	$modes[0] = "Invalid SIM/locked";
2793 5fa78adc Renato Botelho
	$modes[1] = "Valid SIM";
2794 d23e157a smos
	$modes[2] = "Invalid SIM CS";
2795
	$modes[3] = "Invalid SIM PS";
2796
	$modes[4] = "Invalid SIM CS/PS";
2797
	$modes[255] = "Missing SIM";
2798
	$string = "{$modes[$state]} State";
2799
	return $string;
2800
}
2801 4adf752c smos
2802
function zte_rssi_to_string($rssi) {
2803
	return huawei_rssi_to_string($rssi);
2804
}
2805
2806
function zte_mode_to_string($mode, $submode) {
2807
	$modes[0] = "No Service";
2808 5fa78adc Renato Botelho
	$modes[1] = "Limited Service";
2809 4adf752c smos
	$modes[2] = "GPRS";
2810
	$modes[3] = "GSM";
2811
	$modes[4] = "UMTS";
2812
	$modes[5] = "EDGE";
2813 5fa78adc Renato Botelho
	$modes[6] = "HSDPA";
2814 4adf752c smos
2815
	$submodes[0] = "CS_ONLY";
2816
	$submodes[1] = "PS_ONLY";
2817
	$submodes[2] = "CS_PS";
2818
	$submodes[3] = "CAMPED";
2819
	$string = "{$modes[$mode]}, {$submodes[$submode]} Mode";
2820
	return $string;
2821
}
2822
2823
function zte_service_to_string($state) {
2824
	$modes[0] = "Initializing";
2825 5fa78adc Renato Botelho
	$modes[1] = "Network Lock error";
2826 4adf752c smos
	$modes[2] = "Network Locked";
2827
	$modes[3] = "Unlocked or correct MCC/MNC";
2828
	$string = "{$modes[$state]} Service";
2829
	return $string;
2830
}
2831
2832
function zte_simstate_to_string($state) {
2833
	$modes[0] = "No action";
2834 5fa78adc Renato Botelho
	$modes[1] = "Network lock";
2835 4adf752c smos
	$modes[2] = "(U)SIM card lock";
2836
	$modes[3] = "Network Lock and (U)SIM card Lock";
2837
	$string = "{$modes[$state]} State";
2838
	return $string;
2839
}
2840 e9ab2ddb smos
2841
function get_configured_pppoe_server_interfaces() {
2842
	global $config;
2843
	$iflist = array();
2844
	if (is_array($config['pppoes']['pppoe'])) {
2845
		foreach($config['pppoes']['pppoe'] as $pppoe) {
2846
			if ($pppoe['mode'] == "server") {
2847
				$int = "poes". $pppoe['pppoeid'];
2848
				$iflist[$int] = strtoupper($int);
2849
			}
2850
		}
2851
	}
2852
	return $iflist;
2853
}
2854
2855
function get_pppoes_child_interfaces($ifpattern) {
2856
	$if_arr = array();
2857
	if($ifpattern == "")
2858
		return;
2859
2860
	exec("ifconfig", $out, $ret);
2861
	foreach($out as $line) {
2862
		if(preg_match("/^({$ifpattern}[0-9]+):/i", $line, $match)) {
2863
			$if_arr[] = $match[1];
2864
		}
2865
	}
2866
	return $if_arr;
2867
2868
}
2869
2870 331166a8 PiBa-NL
/****f* pfsense-utils/pkg_call_plugins
2871
 * NAME
2872
 *   pkg_call_plugins
2873
 * INPUTS
2874
 *   $plugin_type value used to search in package configuration if the plugin is used, also used to create the function name
2875
 *   $plugin_params parameters to pass to the plugin function for passing multiple parameters a array can be used.
2876
 * RESULT
2877
 *   returns associative array results from the plugin calls for each package
2878
 * NOTES
2879
 *   This generic function can be used to notify or retrieve results from functions that are defined in packages.
2880
 ******/
2881
function pkg_call_plugins($plugin_type, $plugin_params) {
2882 eaee3af6 PiBa-NL
	global $g, $config;
2883
	$results = array();
2884 331166a8 PiBa-NL
	if (!is_array($config['installedpackages']['package']))
2885
		return $results;
2886 eaee3af6 PiBa-NL
	foreach ($config['installedpackages']['package'] as $package) {
2887
		if(!file_exists("/usr/local/pkg/" . $package['configurationfile']))
2888
			continue;
2889
		$pkg_config = parse_xml_config_pkg("/usr/local/pkg/" . $package['configurationfile'], 'packagegui');
2890
		$pkgname = substr(reverse_strrchr($package['configurationfile'], "."),0,-1);
2891 3fe73243 PiBa-NL
		if (is_array($pkg_config['plugins']['item']))
2892
			foreach ($pkg_config['plugins']['item'] as $plugin) {
2893 331166a8 PiBa-NL
				if ($plugin['type'] == $plugin_type) {
2894 eaee3af6 PiBa-NL
					if (file_exists($pkg_config['include_file']))
2895
						require_once($pkg_config['include_file']);
2896
					else
2897
						continue;
2898
					$plugin_function = $pkgname . '_'. $plugin_type;
2899
					$results[$pkgname] = @eval($plugin_function($plugin_params));
2900
				}
2901
			}
2902
	}
2903
	return $results;
2904
}
2905
2906 58005e52 jim-p
?>