Project

General

Profile

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