Project

General

Profile

Download (74.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 8b1a7023 smos
               "100.64.0.0/10",
119 5928bd75 Scott Ullrich
               "172.16.0.0/12",
120
               "192.168.0.0/16",
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 409bc1bd jim-p
	if(($g['platform'] != "cdrom") && ($g['platform'] != "nanobsd")) {
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 409bc1bd jim-p
	}
977
	if($g['platform'] != "cdrom") {
978 3076becf Scott Ullrich
		/* serial console - write out /boot/loader.conf */
979 baef6be8 jim-p
		if ($when == "upgrade")
980
			system("echo \"Reading {$loader_conf_file}...\" >> /conf/upgrade_log.txt");
981 196d0085 jim-p
		$boot_config = file_get_contents($loader_conf_file);
982 5f36c658 jim-p
		$boot_config_split = explode("\n", $boot_config);
983
		if(count($boot_config_split) > 0) {
984
			$new_boot_config = array();
985
			// Loop through and only add lines that are not empty, and which
986
			//  do not contain a console directive.
987
			foreach($boot_config_split as $bcs)
988 c1becc31 jim-p
				if(!empty($bcs)
989
					&& (stripos($bcs, "console") === false)
990
					&& (stripos($bcs, "boot_multicons") === false)
991
					&& (stripos($bcs, "boot_serial") === false))
992 5f36c658 jim-p
					$new_boot_config[] = $bcs;
993
994 9d99eb95 jim-p
			$serialspeed = (is_numeric($config['system']['serialspeed'])) ? $config['system']['serialspeed'] : "9600";
995 c1becc31 jim-p
			if(isset($config['system']['enableserial'])) {
996
				$new_boot_config[] = 'boot_multicons="YES"';
997
				$new_boot_config[] = 'boot_serial="YES"';
998
				$new_boot_config[] = 'comconsole_speed="' . $serialspeed . '"';
999
				$new_boot_config[] = 'console="comconsole,vidconsole"';
1000 9d99eb95 jim-p
			} elseif ($g['platform'] == "nanobsd") {
1001 b16d666d jim-p
				$new_boot_config[] = 'comconsole_speed="' . $serialspeed . '"';
1002 c1becc31 jim-p
			}
1003 196d0085 jim-p
			file_put_contents($loader_conf_file, implode("\n", $new_boot_config) . "\n");
1004 0c8c496e Scott Ullrich
		}
1005
	}
1006 3076becf Scott Ullrich
	$ttys = file_get_contents("/etc/ttys");
1007 cfbfd941 smos
	$ttys_split = explode("\n", $ttys);
1008 3076becf Scott Ullrich
	$fd = fopen("/etc/ttys", "w");
1009
	foreach($ttys_split as $tty) {
1010 c1fdf37f sullrich
		if(stristr($tty, "ttyd0") or stristr($tty, "ttyu0")) {
1011 3076becf Scott Ullrich
			if(isset($config['system']['enableserial'])) {
1012 fd946c7e Erik Fonnesbeck
				fwrite($fd, "ttyu0	\"/usr/libexec/getty bootupcli\"	cons25	on	secure\n");
1013 3076becf Scott Ullrich
			} else {
1014 fd946c7e Erik Fonnesbeck
				fwrite($fd, "ttyu0	\"/usr/libexec/getty bootupcli\"	cons25	off	secure\n");
1015 ca8e4ed2 Scott Ullrich
			}
1016 3076becf Scott Ullrich
		} else {
1017
			fwrite($fd, $tty . "\n");
1018
		}
1019
	}
1020
	fclose($fd);
1021 a46e450c Ermal Lu?i
	auto_login();
1022
1023 3076becf Scott Ullrich
	conf_mount_ro();
1024
	return;
1025
}
1026
1027
function print_value_list($list, $count = 10, $separator = ",") {
1028
	$list = implode($separator, array_slice($list, 0, $count));
1029
	if(count($list) < $count) {
1030
		$list .= ".";
1031
	} else {
1032
		$list .= "...";
1033
	}
1034
	return $list;
1035
}
1036
1037 bfe776f0 Ermal Luçi
/* DHCP enabled on any interfaces? */
1038
function is_dhcp_server_enabled() 
1039
{
1040 db9fabf3 Ermal Luçi
	global $config;
1041 bfe776f0 Ermal Luçi
1042 3076becf Scott Ullrich
	$dhcpdenable = false;
1043 bfe776f0 Ermal Luçi
	
1044 a6610d82 smos
	if (!is_array($config['dhcpd']))
1045 bfe776f0 Ermal Luçi
		return false;
1046
1047 db9fabf3 Ermal Luçi
	$Iflist = get_configured_interface_list();
1048
1049 a8a98fb4 Seth Mos
	if(is_array($config['dhcpd'])) {
1050
		foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf) {
1051
			if (isset($dhcpifconf['enable']) && isset($Iflist[$dhcpif])) {
1052
				$dhcpdenable = true;
1053
				break;
1054
			}
1055 db9fabf3 Ermal Luçi
		}
1056 3076becf Scott Ullrich
	}
1057 bfe776f0 Ermal Luçi
1058 a6610d82 smos
	return $dhcpdenable;
1059
}
1060
1061
/* DHCP enabled on any interfaces? */
1062
function is_dhcpv6_server_enabled() 
1063
{
1064
	global $config;
1065
1066
	$dhcpdenable = false;
1067
	
1068
	$Iflist = get_configured_interface_list();
1069
1070
	foreach($Iflist as $ifname) {
1071
		if($config['interfaces'][$ifname]['track6-interface'] <> "") {
1072
			return true;
1073
		}
1074
	}
1075
1076
	if (!is_array($config['dhcpdv6']))
1077
		return false;
1078
1079
1080 a8a98fb4 Seth Mos
	if(is_array($config['dhcpdv6'])) {
1081
		foreach ($config['dhcpdv6'] as $dhcpv6if => $dhcpv6ifconf) {
1082
			if (isset($dhcpv6ifconf['enable']) && isset($Iflist[$dhcpv6if])) {
1083
				$dhcpdenable = true;
1084
				break;
1085
			}
1086 65b1e7d5 Seth Mos
		}
1087
	}
1088
1089 3076becf Scott Ullrich
	return $dhcpdenable;
1090
}
1091
1092 0ed8d746 bcyrill
/* radvd enabled on any interfaces? */
1093
function is_radvd_enabled() {
1094
	global $config;
1095
1096
	if (!is_array($config['dhcpdv6']))
1097
		$config['dhcpdv6'] = array();
1098
1099
	$dhcpdv6cfg = $config['dhcpdv6'];
1100
	$Iflist = get_configured_interface_list();
1101
1102
	/* handle manually configured DHCP6 server settings first */
1103
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1104
		if(!isset($config['interfaces'][$dhcpv6if]['enable']))
1105
			continue;
1106
1107
		if(!isset($dhcpv6ifconf['ramode']))
1108
			$dhcpv6ifconf['ramode'] = $dhcpv6ifconf['mode'];
1109
1110
		if($dhcpv6ifconf['ramode'] == "disabled")
1111
			continue;
1112
1113
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1114
		if(!is_ipaddrv6($ifcfgipv6))
1115
			continue;
1116
1117
		return true;
1118
	}
1119
1120
	/* handle DHCP-PD prefixes and 6RD dynamic interfaces */
1121
	foreach ($Iflist as $if => $ifdescr) {
1122
		if(!isset($config['interfaces'][$if]['track6-interface']))
1123
			continue;
1124
		if(!isset($config['interfaces'][$if]['enable']))
1125
			continue;
1126
1127
		$ifcfgipv6 = get_interface_ipv6($if);
1128
		if(!is_ipaddrv6($ifcfgipv6))
1129
			continue;
1130
1131
		$ifcfgsnv6 = get_interface_subnetv6($if);
1132
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1133
1134
		if(!is_ipaddrv6($subnetv6))
1135
			continue;
1136
1137
		return true;
1138
	}
1139
1140
	return false;
1141
}
1142
1143 93c2c1e6 jim-p
/* Any PPPoE servers enabled? */
1144
function is_pppoe_server_enabled() {
1145
	global $config;
1146
1147
	$pppoeenable = false;
1148
1149
	if (!is_array($config['pppoes']) || !is_array($config['pppoes']['pppoe']))
1150
		return false;
1151
1152
	foreach ($config['pppoes']['pppoe'] as $pppoes)
1153
		if ($pppoes['mode'] == 'server')
1154
			$pppoeenable = true;
1155
1156
	return $pppoeenable;
1157
}
1158
1159 9ebe7028 gnhb
function convert_seconds_to_hms($sec){
1160 63292199 gnhb
	$min=$hrs=0;
1161 9ebe7028 gnhb
	if ($sec != 0){
1162
		$min = floor($sec/60);
1163
		$sec %= 60;
1164
	}
1165
	if ($min != 0){
1166
		$hrs = floor($min/60);
1167
		$min %= 60;
1168
	}
1169
	if ($sec < 10)
1170
		$sec = "0".$sec;
1171
	if ($min < 10)
1172
		$min = "0".$min;
1173
	if ($hrs < 10)
1174
		$hrs = "0".$hrs;
1175
	$result = $hrs.":".$min.":".$sec;
1176
	return $result;
1177
}
1178 8eb2f33a Scott Ullrich
1179 63292199 gnhb
/* Compute the total uptime from the ppp uptime log file in the conf directory */
1180
1181
function get_ppp_uptime($port){
1182
	if (file_exists("/conf/{$port}.log")){
1183
    	$saved_time = file_get_contents("/conf/{$port}.log");
1184
    	$uptime_data = explode("\n",$saved_time);
1185
		$sec=0;
1186
		foreach($uptime_data as $upt) {
1187
			$sec += substr($upt, 1 + strpos($upt, " "));
1188
 		}
1189
		return convert_seconds_to_hms($sec);
1190
	} else {
1191 7d1b238c Carlos Eduardo Ramos
		$total_time = gettext("No history data found!");
1192 63292199 gnhb
		return $total_time;
1193
	}
1194
}
1195 8eb2f33a Scott Ullrich
1196 6189988d Scott Dale
//returns interface information
1197
function get_interface_info($ifdescr) {
1198 cffe41cb Ermal
	global $config, $g;
1199 6189988d Scott Dale
1200
	$ifinfo = array();
1201 cffe41cb Ermal
	if (empty($config['interfaces'][$ifdescr]))
1202 67ee1ec5 Ermal Luçi
		return;
1203 ebdbdbc2 gnhb
	$ifinfo['hwif'] = $config['interfaces'][$ifdescr]['if'];
1204 cffe41cb Ermal
	$ifinfo['if'] = get_real_interface($ifdescr);
1205 6189988d Scott Dale
1206 cb074893 Ermal Lu?i
	$chkif = $ifinfo['if'];
1207
	$ifinfotmp = pfSense_get_interface_addresses($chkif);
1208
	$ifinfo['status'] = $ifinfotmp['status'];
1209 cffe41cb Ermal
	if (empty($ifinfo['status']))
1210
                $ifinfo['status'] = "down";
1211 cb074893 Ermal Lu?i
	$ifinfo['macaddr'] = $ifinfotmp['macaddr'];
1212
	$ifinfo['ipaddr'] = $ifinfotmp['ipaddr'];
1213
	$ifinfo['subnet'] = $ifinfotmp['subnet'];
1214 58418355 smos
	$ifinfo['linklocal'] = get_interface_linklocal($ifdescr);
1215 15cc0894 Seth Mos
	$ifinfo['ipaddrv6'] = get_interface_ipv6($ifdescr);
1216
	$ifinfo['subnetv6'] = get_interface_subnetv6($ifdescr);
1217 a216a03a gnhb
	if (isset($ifinfotmp['link0']))
1218 cb074893 Ermal Lu?i
		$link0 = "down";
1219 cffe41cb Ermal
	$ifinfotmp = pfSense_get_interface_stats($chkif);
1220 15cc0894 Seth Mos
        // $ifinfo['inpkts'] = $ifinfotmp['inpkts'];
1221
        // $ifinfo['outpkts'] = $ifinfotmp['outpkts'];
1222 cffe41cb Ermal
        $ifinfo['inerrs'] = $ifinfotmp['inerrs'];
1223
        $ifinfo['outerrs'] = $ifinfotmp['outerrs'];
1224
        $ifinfo['collisions'] = $ifinfotmp['collisions'];
1225 6189988d Scott Dale
1226 01385b0c Scott Ullrich
	/* Use pfctl for non wrapping 64 bit counters */
1227 b5a8483c Seth Mos
	/* Pass */
1228 cb074893 Ermal Lu?i
	exec("/sbin/pfctl -vvsI -i {$chkif}", $pfctlstats);
1229 971eaab5 Seth Mos
	$pf_in4_pass = preg_split("/ +/ ", $pfctlstats[3]);
1230
	$pf_out4_pass = preg_split("/ +/", $pfctlstats[5]);
1231 15cc0894 Seth Mos
	$pf_in6_pass = preg_split("/ +/ ", $pfctlstats[7]);
1232
	$pf_out6_pass = preg_split("/ +/", $pfctlstats[9]);
1233 971eaab5 Seth Mos
	$in4_pass = $pf_in4_pass[5];
1234
	$out4_pass = $pf_out4_pass[5];
1235
	$in4_pass_packets = $pf_in4_pass[3];
1236
	$out4_pass_packets = $pf_out4_pass[3];
1237 15cc0894 Seth Mos
	$in6_pass = $pf_in6_pass[5];
1238
	$out6_pass = $pf_out6_pass[5];
1239
	$in6_pass_packets = $pf_in6_pass[3];
1240
	$out6_pass_packets = $pf_out6_pass[3];
1241
	$ifinfo['inbytespass'] = $in4_pass + $in6_pass;
1242
	$ifinfo['outbytespass'] = $out4_pass + $out6_pass;
1243
	$ifinfo['inpktspass'] = $in4_pass_packets + $in6_pass_packets;
1244 4bdfa5dd Phil Davis
	$ifinfo['outpktspass'] = $out4_pass_packets + $out6_pass_packets;
1245 01385b0c Scott Ullrich
1246 971eaab5 Seth Mos
	/* Block */
1247
	$pf_in4_block = preg_split("/ +/", $pfctlstats[4]);
1248
	$pf_out4_block = preg_split("/ +/", $pfctlstats[6]);
1249 15cc0894 Seth Mos
	$pf_in6_block = preg_split("/ +/", $pfctlstats[8]);
1250
	$pf_out6_block = preg_split("/ +/", $pfctlstats[10]);
1251 971eaab5 Seth Mos
	$in4_block = $pf_in4_block[5];
1252
	$out4_block = $pf_out4_block[5];
1253
	$in4_block_packets = $pf_in4_block[3];
1254
	$out4_block_packets = $pf_out4_block[3];
1255 15cc0894 Seth Mos
	$in6_block = $pf_in6_block[5];
1256
	$out6_block = $pf_out6_block[5];
1257
	$in6_block_packets = $pf_in6_block[3];
1258
	$out6_block_packets = $pf_out6_block[3];
1259
	$ifinfo['inbytesblock'] = $in4_block + $in6_block;
1260
	$ifinfo['outbytesblock'] = $out4_block + $out6_block;
1261
	$ifinfo['inpktsblock'] = $in4_block_packets + $in6_block_packets;
1262
	$ifinfo['outpktsblock'] = $out4_block_packets + $out6_block_packets;
1263
1264
	$ifinfo['inbytes'] = $in4_pass + $in6_pass;
1265
	$ifinfo['outbytes'] = $out4_pass + $out6_pass;
1266
	$ifinfo['inpkts'] = $in4_pass_packets + $in6_pass_packets;
1267 4bdfa5dd Phil Davis
	$ifinfo['outpkts'] = $out4_pass_packets + $out6_pass_packets;
1268 01385b0c Scott Ullrich
		
1269 63161b3f Ermal Luçi
	$ifconfiginfo = "";
1270 59db783a gnhb
	$link_type = $config['interfaces'][$ifdescr]['ipaddr'];
1271
	switch ($link_type) {
1272 cb074893 Ermal Lu?i
	 /* DHCP? -> see if dhclient is up */
1273 67ee1ec5 Ermal Luçi
	case "dhcp":
1274 20c79427 Ermal Lu?i
		/* see if dhclient is up */
1275 c4f31aca Ermal Lu?i
		if (find_dhclient_process($ifinfo['if']) <> "")
1276 20c79427 Ermal Lu?i
			$ifinfo['dhcplink'] = "up";
1277
		else
1278
			$ifinfo['dhcplink'] = "down";
1279 63161b3f Ermal Luçi
1280 67ee1ec5 Ermal Luçi
		break;
1281 febca7e8 Ermal
	/* PPPoE/PPTP/L2TP interface? -> get status from virtual interface */
1282 67ee1ec5 Ermal Luçi
	case "pppoe":
1283 febca7e8 Ermal
	case "pptp":
1284
	case "l2tp":
1285 cffe41cb Ermal
		if ($ifinfo['status'] == "up" && !isset($link0))
1286 59db783a gnhb
			/* get PPPoE link status for dial on demand */
1287 febca7e8 Ermal
			$ifinfo["{$link_type}link"] = "up";
1288 20c79427 Ermal Lu?i
		else
1289 febca7e8 Ermal
			$ifinfo["{$link_type}link"] = "down";
1290 6189988d Scott Dale
1291 67ee1ec5 Ermal Luçi
		break;
1292 8eb2f33a Scott Ullrich
	/* PPP interface? -> get uptime for this session and cumulative uptime from the persistant log file in conf */
1293 9ebe7028 gnhb
	case "ppp":
1294 cffe41cb Ermal
		if ($ifinfo['status'] == "up")
1295 c90f2471 gnhb
			$ifinfo['ppplink'] = "up";
1296
		else
1297
			$ifinfo['ppplink'] = "down" ;
1298
1299
		if (empty($ifinfo['status']))
1300
			$ifinfo['status'] = "down";
1301 badbe349 gnhb
			
1302
		if (is_array($config['ppps']['ppp']) && count($config['ppps']['ppp'])) {
1303
			foreach ($config['ppps']['ppp'] as $pppid => $ppp) {
1304 f7480829 gnhb
				if ($config['interfaces'][$ifdescr]['if'] == $ppp['if'])
1305 badbe349 gnhb
					break;
1306
			}
1307
		}
1308 42809b4a gnhb
		$dev = $ppp['ports'];
1309 f7480829 gnhb
		if ($config['interfaces'][$ifdescr]['if'] != $ppp['if'] || empty($dev))
1310 611ae852 Ermal
			break;
1311 59db783a gnhb
		if (!file_exists($dev)) {
1312 c90f2471 gnhb
			$ifinfo['nodevice'] = 1;
1313 7d1b238c Carlos Eduardo Ramos
			$ifinfo['pppinfo'] = $dev . " " . gettext("device not present! Is the modem attached to the system?");	
1314 611ae852 Ermal
		}
1315 5e589685 smos
1316 4adf752c smos
		$usbmodemoutput = array();
1317
		exec("usbconfig", $usbmodemoutput);
1318 852171dd smos
		$mondev = "{$g['tmp_path']}/3gstats.{$ifdescr}";
1319 5e589685 smos
		if(file_exists($mondev)) {
1320
			$cellstats = file($mondev);
1321 d23e157a smos
			/* skip header */
1322 5e589685 smos
			$a_cellstats = explode(",", $cellstats[1]);
1323 4adf752c smos
			if(preg_match("/huawei/i", implode("\n", $usbmodemoutput))) {
1324
				$ifinfo['cell_rssi'] = huawei_rssi_to_string($a_cellstats[1]);
1325
				$ifinfo['cell_mode'] = huawei_mode_to_string($a_cellstats[2], $a_cellstats[3]);
1326
				$ifinfo['cell_simstate'] = huawei_simstate_to_string($a_cellstats[10]);
1327
				$ifinfo['cell_service'] = huawei_service_to_string(trim($a_cellstats[11]));
1328
			}
1329
			if(preg_match("/zte/i", implode("\n", $usbmodemoutput))) {
1330
				$ifinfo['cell_rssi'] = zte_rssi_to_string($a_cellstats[1]);
1331
				$ifinfo['cell_mode'] = zte_mode_to_string($a_cellstats[2], $a_cellstats[3]);
1332
				$ifinfo['cell_simstate'] = zte_simstate_to_string($a_cellstats[10]);
1333
				$ifinfo['cell_service'] = zte_service_to_string(trim($a_cellstats[11]));
1334
			}
1335 d23e157a smos
			$ifinfo['cell_upstream'] = $a_cellstats[4];
1336
			$ifinfo['cell_downstream'] = trim($a_cellstats[5]);
1337
			$ifinfo['cell_sent'] = $a_cellstats[6];
1338
			$ifinfo['cell_received'] = trim($a_cellstats[7]);
1339
			$ifinfo['cell_bwupstream'] = $a_cellstats[8];
1340
			$ifinfo['cell_bwdownstream'] = trim($a_cellstats[9]);
1341 5e589685 smos
		}
1342 611ae852 Ermal
		// Calculate cumulative uptime for PPP link. Useful for connections that have per minute/hour contracts so you don't go over!
1343 59db783a gnhb
		if (isset($ppp['uptime']))
1344
			$ifinfo['ppp_uptime_accumulated'] = "(".get_ppp_uptime($ifinfo['if']).")";
1345 67ee1ec5 Ermal Luçi
		break;
1346 63161b3f Ermal Luçi
	default:
1347
		break;
1348 6189988d Scott Dale
	}
1349 59db783a gnhb
	
1350
	if (file_exists("{$g['varrun_path']}/{$link_type}_{$ifdescr}.pid")) {
1351
		$sec = trim(`/usr/local/sbin/ppp-uptime.sh {$ifinfo['if']}`);
1352
		$ifinfo['ppp_uptime'] = convert_seconds_to_hms($sec);
1353
	}
1354
	
1355 6189988d Scott Dale
	if ($ifinfo['status'] == "up") {
1356
		/* try to determine media with ifconfig */
1357
		unset($ifconfiginfo);
1358 818a6b7d Seth Mos
		exec("/sbin/ifconfig " . $ifinfo['if'], $ifconfiginfo);
1359
		$wifconfiginfo = array();
1360
		if(is_interface_wireless($ifdescr)) {
1361
			exec("/sbin/ifconfig {$ifinfo['if']} list sta", $wifconfiginfo);
1362
			array_shift($wifconfiginfo);
1363
		}
1364 6189988d Scott Dale
		$matches = "";
1365
		foreach ($ifconfiginfo as $ici) {
1366
1367
			/* don't list media/speed for wireless cards, as it always
1368
			   displays 2 Mbps even though clients can connect at 11 Mbps */
1369
			if (preg_match("/media: .*? \((.*?)\)/", $ici, $matches)) {
1370
				$ifinfo['media'] = $matches[1];
1371
			} else if (preg_match("/media: Ethernet (.*)/", $ici, $matches)) {
1372
				$ifinfo['media'] = $matches[1];
1373
			} else if (preg_match("/media: IEEE 802.11 Wireless Ethernet (.*)/", $ici, $matches)) {
1374
				$ifinfo['media'] = $matches[1];
1375
			}
1376
1377
			if (preg_match("/status: (.*)$/", $ici, $matches)) {
1378
				if ($matches[1] != "active")
1379
					$ifinfo['status'] = $matches[1];
1380 7d1b238c Carlos Eduardo Ramos
				if($ifinfo['status'] == gettext("running"))
1381
					$ifinfo['status'] = gettext("up");
1382 6189988d Scott Dale
			}
1383
			if (preg_match("/channel (\S*)/", $ici, $matches)) {
1384
				$ifinfo['channel'] = $matches[1];
1385
			}
1386
			if (preg_match("/ssid (\".*?\"|\S*)/", $ici, $matches)) {
1387
				if ($matches[1][0] == '"')
1388
					$ifinfo['ssid'] = substr($matches[1], 1, -1);
1389
				else
1390
					$ifinfo['ssid'] = $matches[1];
1391
			}
1392 0b29093b jim-p
			if (preg_match("/laggproto (.*)$/", $ici, $matches)) {
1393
				$ifinfo['laggproto'] = $matches[1];
1394
			}
1395
			if (preg_match("/laggport: (.*)$/", $ici, $matches)) {
1396
				$ifinfo['laggport'][] = $matches[1];
1397
			}
1398 6189988d Scott Dale
		}
1399 818a6b7d Seth Mos
		foreach($wifconfiginfo as $ici) {
1400
			$elements = preg_split("/[ ]+/i", $ici);
1401
			if ($elements[0] != "") {
1402
				$ifinfo['bssid'] = $elements[0];
1403
			}
1404
			if ($elements[3] != "") {
1405
				$ifinfo['rate'] = $elements[3];
1406
			}
1407
			if ($elements[4] != "") {
1408
				$ifinfo['rssi'] = $elements[4];
1409
			}
1410
1411
		}
1412 67ee1ec5 Ermal Luçi
		/* lookup the gateway */
1413 2bbb79cb Seth Mos
		if (interface_has_gateway($ifdescr)) {
1414 ebdbdbc2 gnhb
			$ifinfo['gateway'] = get_interface_gateway($ifdescr);
1415 2bbb79cb Seth Mos
			$ifinfo['gatewayv6'] = get_interface_gateway_v6($ifdescr);
1416
		}
1417 6189988d Scott Dale
	}
1418
1419
	$bridge = "";
1420 7ec05d27 Ermal Luçi
	$bridge = link_interface_to_bridge($ifdescr);
1421 6189988d Scott Dale
	if($bridge) {
1422
		$bridge_text = `/sbin/ifconfig {$bridge}`;
1423
		if(stristr($bridge_text, "blocking") <> false) {
1424 7d1b238c Carlos Eduardo Ramos
			$ifinfo['bridge'] = "<b><font color='red'>" . gettext("blocking") . "</font></b> - " . gettext("check for ethernet loops");
1425 6189988d Scott Dale
			$ifinfo['bridgeint'] = $bridge;
1426
		} else if(stristr($bridge_text, "learning") <> false) {
1427 7d1b238c Carlos Eduardo Ramos
			$ifinfo['bridge'] = gettext("learning");
1428 6189988d Scott Dale
			$ifinfo['bridgeint'] = $bridge;
1429
		} else if(stristr($bridge_text, "forwarding") <> false) {
1430 7d1b238c Carlos Eduardo Ramos
			$ifinfo['bridge'] = gettext("forwarding");
1431 6189988d Scott Dale
			$ifinfo['bridgeint'] = $bridge;
1432
		}
1433
	}
1434
1435
	return $ifinfo;
1436
}
1437
1438
//returns cpu speed of processor. Good for determining capabilities of machine
1439
function get_cpu_speed() {
1440
	 return exec("sysctl hw.clockrate | awk '{ print $2 }'");
1441
}
1442 fab7ff44 Bill Marquette
1443 a5f94f14 Scott Ullrich
function add_hostname_to_watch($hostname) {
1444 c941ea1c Seth Mos
	if(!is_dir("/var/db/dnscache")) {
1445
		mkdir("/var/db/dnscache");
1446
	}
1447 5f31bf01 Seth Mos
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1448 581e772e Seth Mos
		$domrecords = array();
1449
		$domips = array();
1450
		exec("host -t A $hostname", $domrecords, $rethost);
1451
		if($rethost == 0) {
1452
			foreach($domrecords as $domr) {
1453
				$doml = explode(" ", $domr);
1454
				$domip = $doml[3];
1455
				/* fill array with domain ip addresses */
1456
				if(is_ipaddr($domip)) {
1457
					$domips[] = $domip;
1458
				}
1459
			}
1460
		}
1461
		sort($domips);
1462
		$contents = "";
1463
		if(! empty($domips)) {
1464 162c059e Seth Mos
			foreach($domips as $ip) {
1465
				$contents .= "$ip\n";
1466
			}
1467 581e772e Seth Mos
		}
1468
		file_put_contents("/var/db/dnscache/$hostname", $contents);
1469 a5f94f14 Scott Ullrich
	}
1470
}
1471
1472 5ed54b93 Seth Mos
function is_fqdn($fqdn) {
1473
	$hostname = false;
1474
	if(preg_match("/[-A-Z0-9\.]+\.[-A-Z0-9\.]+/i", $fqdn)) {
1475
		$hostname = true;
1476
	}
1477
	if(preg_match("/\.\./", $fqdn)) {
1478
		$hostname = false;
1479
	}
1480 3aae364d Scott Ullrich
	if(preg_match("/^\./i", $fqdn)) { 
1481 5ed54b93 Seth Mos
		$hostname = false;
1482
	}
1483 c941ea1c Seth Mos
	if(preg_match("/\//i", $fqdn)) {
1484
		$hostname = false;
1485
	}
1486 5ed54b93 Seth Mos
	return($hostname);
1487
}
1488
1489 639aaa95 Bill Marquette
function pfsense_default_state_size() {
1490
  /* get system memory amount */
1491
  $memory = get_memory();
1492
  $avail = $memory[0];
1493
  /* Be cautious and only allocate 10% of system memory to the state table */
1494
  $max_states = (int) ($avail/10)*1000;
1495
  return $max_states;
1496
}
1497
1498 84aea606 jim-p
function pfsense_default_tables_size() {
1499
	$current = `pfctl -sm | grep ^tables | awk '{print $4};'`;
1500
	return $current;
1501
}
1502
1503 fb586a16 jim-p
function pfsense_default_table_entries_size() {
1504
	$current = `pfctl -sm | grep table-entries | awk '{print $4};'`;
1505
	return $current;
1506
}
1507
1508 7723c7e0 Seth Mos
/* Compare the current hostname DNS to the DNS cache we made
1509
 * if it has changed we return the old records
1510
 * if no change we return true */
1511
function compare_hostname_to_dnscache($hostname) {
1512
	if(!is_dir("/var/db/dnscache")) {
1513
		mkdir("/var/db/dnscache");
1514
	}
1515
	$hostname = trim($hostname);
1516
	if(is_readable("/var/db/dnscache/{$hostname}")) {
1517
		$oldcontents = file_get_contents("/var/db/dnscache/{$hostname}");
1518
	} else {
1519
		$oldcontents = "";
1520
	}
1521
	if((is_fqdn($hostname)) && (!is_ipaddr($hostname))) {
1522
		$domrecords = array();
1523
		$domips = array();
1524
		exec("host -t A $hostname", $domrecords, $rethost);
1525
		if($rethost == 0) {
1526
			foreach($domrecords as $domr) {
1527
				$doml = explode(" ", $domr);
1528
				$domip = $doml[3];
1529
				/* fill array with domain ip addresses */
1530
				if(is_ipaddr($domip)) {
1531
					$domips[] = $domip;
1532
				}
1533
			}
1534
		}
1535
		sort($domips);
1536
		$contents = "";
1537
		if(! empty($domips)) {
1538
			foreach($domips as $ip) {
1539
				$contents .= "$ip\n";
1540
			}
1541
		}
1542
	}
1543
1544
	if(trim($oldcontents) != trim($contents)) {
1545 a5f91ef4 Seth Mos
		if($g['debug']) {
1546 addc0439 Renato Botelho
			log_error(sprintf(gettext('DNSCACHE: Found old IP %1$s and new IP %2$s'), $oldcontents, $contents));
1547 a5f91ef4 Seth Mos
		}
1548 7723c7e0 Seth Mos
		return ($oldcontents);
1549
	} else {
1550
		return false;
1551
	}
1552
}
1553
1554 09f18f59 jim-p
/*
1555 7530177c jim-p
 * load_crypto() - Load crypto modules if enabled in config.
1556 09f18f59 jim-p
 */
1557 7530177c jim-p
function load_crypto() {
1558 09f18f59 jim-p
	global $config, $g;
1559 7530177c jim-p
	$crypto_modules = array('glxsb', 'aesni');
1560
1561
	if (!in_array($config['system']['crypto_hardware'], $crypto_modules))
1562
		return false;
1563
1564
	$is_loaded = `/sbin/kldstat | /usr/bin/grep -c {$config['system']['crypto_hardware']}`;
1565
	if (!empty($config['system']['crypto_hardware']) && ($is_loaded == 0)) {
1566
		log_error("Loading {$config['system']['crypto_hardware']} cryptographic accelerator module.");
1567
		mwexec("/sbin/kldload {$config['system']['crypto_hardware']}");
1568 09f18f59 jim-p
	}
1569
}
1570
1571 f60156f6 jim-p
/*
1572
 * load_thermal_hardware() - Load temperature monitor kernel module
1573
 */
1574
function load_thermal_hardware() {
1575
	global $config, $g;
1576
	$thermal_hardware_modules = array('coretemp', 'amdtemp');
1577
1578
	if (!in_array($config['system']['thermal_hardware'], $thermal_hardware_modules))
1579
		return false;
1580
1581
	$is_loaded = `/sbin/kldstat | /usr/bin/grep -c {$config['system']['thermal_hardware']}`;
1582
	if (!empty($config['system']['thermal_hardware']) && ($is_loaded == 0)) {
1583
		log_error("Loading {$config['system']['thermal_hardware']} thermal monitor module.");
1584
		mwexec("/sbin/kldload {$config['system']['thermal_hardware']}");
1585
	}
1586
}
1587
1588 cde4f5d3 Scott Ullrich
/****f* pfsense-utils/isvm
1589
 * NAME
1590
 *   isvm
1591
 * INPUTS
1592
 *	 none
1593
 * RESULT
1594
 *   returns true if machine is running under a virtual environment
1595
 ******/
1596
function isvm() {
1597
	$virtualenvs = array("vmware", "parallels", "qemu", "bochs", "plex86");
1598 6f76920c thompsa
	$bios_vendor = strtolower(`/bin/kenv | /usr/bin/awk -F= '/smbios.bios.vendor/ {print $2}'`);
1599 cde4f5d3 Scott Ullrich
	if(in_array($bios_vendor, $virtualenvs)) 
1600
		return true;
1601
	else
1602
		return false;
1603
}
1604
1605 e0d0eb71 Scott Ullrich
function get_freebsd_version() {
1606 9a7f6731 Ermal
	$version = php_uname("r");
1607
	return $version[0];
1608 e0d0eb71 Scott Ullrich
}
1609
1610 d164643a jim-p
function download_file_with_progress_bar($url_file, $destination_file, $readbody = 'read_body', $connect_timeout=60, $timeout=0) {
1611 e961bd67 phildd
        global $ch, $fout, $file_size, $downloaded, $config, $first_progress_update;
1612 b31da21e Scott Ullrich
        $file_size  = 1;
1613
        $downloaded = 1;
1614 e961bd67 phildd
	$first_progress_update = TRUE;
1615 b31da21e Scott Ullrich
        /* open destination file */
1616
        $fout = fopen($destination_file, "wb");
1617
1618
        /*
1619
         *      Originally by Author: Keyvan Minoukadeh
1620
         *      Modified by Scott Ullrich to return Content-Length size
1621
         */
1622
1623
        $ch = curl_init();
1624
        curl_setopt($ch, CURLOPT_URL, $url_file);
1625
        curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
1626 0f280d2a jim-p
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
1627
        /* Don't verify SSL peers since we don't have the certificates to do so. */
1628
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1629 b31da21e Scott Ullrich
        curl_setopt($ch, CURLOPT_WRITEFUNCTION, $readbody);
1630
        curl_setopt($ch, CURLOPT_NOPROGRESS, '1');
1631 d164643a jim-p
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connect_timeout);
1632
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1633 b31da21e Scott Ullrich
1634 42c07003 Ermal
	if (!empty($config['system']['proxyurl'])) {
1635
		curl_setopt($ch, CURLOPT_PROXY, $config['system']['proxyurl']);
1636
		if (!empty($config['system']['proxyport']))
1637
			curl_setopt($ch, CURLOPT_PROXYPORT, $config['system']['proxyport']);
1638
		if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
1639
			@curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_ANY | CURLAUTH_ANYSAFE);
1640 2a57a4d1 Ermal
			curl_setopt($ch, CURLOPT_PROXYUSERPWD, "{$config['system']['proxyuser']}:{$config['system']['proxypass']}");
1641 42c07003 Ermal
		}
1642
	}
1643
1644 4c37209a jim-p
        @curl_exec($ch);
1645 b31da21e Scott Ullrich
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
1646
        if($fout)
1647
                fclose($fout);
1648
        curl_close($ch);
1649
        return ($http_code == 200) ? true : $http_code;
1650
}
1651
1652
function read_header($ch, $string) {
1653
        global $file_size, $fout;
1654
        $length = strlen($string);
1655
        $regs = "";
1656 72c59dd8 ccesario
        preg_match("/(Content-Length:) (.*)/", $string, $regs);
1657 b31da21e Scott Ullrich
        if($regs[2] <> "") {
1658
                $file_size = intval($regs[2]);
1659
        }
1660
        ob_flush();
1661
        return $length;
1662
}
1663
1664
function read_body($ch, $string) {
1665 e961bd67 phildd
        global $fout, $file_size, $downloaded, $sendto, $static_status, $static_output, $lastseen, $first_progress_update;
1666 a0e157e9 Scott Ullrich
		global $pkg_interface;
1667 b31da21e Scott Ullrich
        $length = strlen($string);
1668
        $downloaded += intval($length);
1669 f444c396 Erik Fonnesbeck
        if($file_size > 0) {
1670
                $downloadProgress = round(100 * (1 - $downloaded / $file_size), 0);
1671
                $downloadProgress = 100 - $downloadProgress;
1672
        } else
1673
                $downloadProgress = 0;
1674 b31da21e Scott Ullrich
        if($lastseen <> $downloadProgress and $downloadProgress < 101) {
1675
                if($sendto == "status") {
1676 03b2cab6 Ermal
			if($pkg_interface == "console") {
1677 2a315bee Phil Davis
				if(($downloadProgress % 10) == 0 || $downloadProgress < 10) {
1678 03b2cab6 Ermal
					$tostatus = $static_status . $downloadProgress . "%";
1679 2a315bee Phil Davis
					if ($downloadProgress == 100) {
1680 a3da8f50 Ermal
						$tostatus = $tostatus . "\r";
1681 2a315bee Phil Davis
					}
1682 03b2cab6 Ermal
					update_status($tostatus);
1683
				}
1684
			} else {
1685
				$tostatus = $static_status . $downloadProgress . "%";
1686
				update_status($tostatus);						
1687
			}
1688 b31da21e Scott Ullrich
                } else {
1689 03b2cab6 Ermal
			if($pkg_interface == "console") {
1690 2a315bee Phil Davis
				if(($downloadProgress % 10) == 0 || $downloadProgress < 10) {
1691 03b2cab6 Ermal
					$tooutput = $static_output . $downloadProgress . "%";
1692 2a315bee Phil Davis
					if ($downloadProgress == 100) {
1693 a3da8f50 Ermal
						$tooutput = $tooutput . "\r";
1694 2a315bee Phil Davis
					}
1695 03b2cab6 Ermal
					update_output_window($tooutput);
1696
				}
1697
			} else {
1698
				$tooutput = $static_output . $downloadProgress . "%";
1699
				update_output_window($tooutput);
1700
			}
1701 b31da21e Scott Ullrich
                }
1702 82acb8b3 Phil Davis
				if(($pkg_interface != "console") || (($downloadProgress % 10) == 0) || ($downloadProgress < 10)) {
1703 e961bd67 phildd
					update_progress_bar($downloadProgress, $first_progress_update);
1704
					$first_progress_update = FALSE;
1705 82acb8b3 Phil Davis
				}
1706 b31da21e Scott Ullrich
                $lastseen = $downloadProgress;
1707
        }
1708
        if($fout)
1709
                fwrite($fout, $string);
1710
        ob_flush();
1711
        return $length;
1712
}
1713
1714 84677257 Scott Ullrich
/*
1715
 *   update_output_window: update bottom textarea dynamically.
1716
 */
1717
function update_output_window($text) {
1718
        global $pkg_interface;
1719 41fe9ef0 ccesario
        $log = preg_replace("/\n/", "\\n", $text);
1720 fa15f4ae Ermal
        if($pkg_interface != "console") {
1721 c2272d6d Scott Ullrich
                echo "\n<script language=\"JavaScript\">\nthis.document.forms[0].output.value = \"" . $log . "\";\n";
1722
				echo "this.document.forms[0].output.scrollTop = this.document.forms[0].output.scrollHeight;\n";	
1723
				echo "</script>";
1724 84677257 Scott Ullrich
        }
1725
        /* ensure that contents are written out */
1726
        ob_flush();
1727
}
1728
1729
/*
1730 82acb8b3 Phil Davis
 *   update_status: update top textarea dynamically.
1731 84677257 Scott Ullrich
 */
1732
function update_status($status) {
1733
        global $pkg_interface;
1734
        if($pkg_interface == "console") {
1735 03b2cab6 Ermal
                echo "\r{$status}";
1736 84677257 Scott Ullrich
        } else {
1737
                echo "\n<script type=\"text/javascript\">this.document.forms[0].status.value=\"" . $status . "\";</script>";
1738
        }
1739
        /* ensure that contents are written out */
1740
        ob_flush();
1741
}
1742
1743
/*
1744 e961bd67 phildd
 * update_progress_bar($percent, $first_time): updates the javascript driven progress bar.
1745 84677257 Scott Ullrich
 */
1746 e961bd67 phildd
function update_progress_bar($percent, $first_time) {
1747 84677257 Scott Ullrich
        global $pkg_interface;
1748
        if($percent > 100) $percent = 1;
1749
        if($pkg_interface <> "console") {
1750
                echo "\n<script type=\"text/javascript\" language=\"javascript\">";
1751
                echo "\ndocument.progressbar.style.width='" . $percent . "%';";
1752
                echo "\n</script>";
1753
        } else {
1754 e961bd67 phildd
		if(!($first_time))
1755
			echo "\x08\x08\x08\x08\x08";
1756
		echo sprintf("%4d%%", $percent);
1757 84677257 Scott Ullrich
        }
1758
}
1759
1760 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. */
1761
if(!function_exists("split")) {
1762
	function split($seperator, $haystack, $limit = null) {
1763 cfbfd941 smos
		log_error("deprecated split() call with seperator '{$seperator}'");
1764 f5d637bc Scott Ullrich
		return preg_split($seperator, $haystack, $limit);
1765
	}
1766
}
1767
1768 f1ac1733 Erik Fonnesbeck
function update_alias_names_upon_change($section, $field, $new_alias_name, $origname) {
1769 978fd2e8 Scott Ullrich
	global $g, $config, $pconfig, $debug;
1770 b6db8ea3 sullrich
	if(!$origname) 
1771
		return;
1772
1773 f1ac1733 Erik Fonnesbeck
	$sectionref = &$config;
1774
	foreach($section as $sectionname) {
1775
		if(is_array($sectionref) && isset($sectionref[$sectionname]))
1776
			$sectionref = &$sectionref[$sectionname];
1777
		else
1778
			return;
1779
	}
1780
1781 b6db8ea3 sullrich
	if($debug) $fd = fopen("{$g['tmp_path']}/print_r", "a");
1782
	if($debug) fwrite($fd, print_r($pconfig, true));
1783
1784 f1ac1733 Erik Fonnesbeck
	if(is_array($sectionref)) {
1785
		foreach($sectionref as $itemkey => $item) {
1786
			if($debug) fwrite($fd, "$itemkey\n");
1787
1788
			$fieldfound = true;
1789
			$fieldref = &$sectionref[$itemkey];
1790
			foreach($field as $fieldname) {
1791
				if(is_array($fieldref) && isset($fieldref[$fieldname]))
1792
					$fieldref = &$fieldref[$fieldname];
1793
				else {
1794
					$fieldfound = false;
1795
					break;
1796
				}
1797 b6db8ea3 sullrich
			}
1798 f1ac1733 Erik Fonnesbeck
			if($fieldfound && $fieldref == $origname) {
1799 b6db8ea3 sullrich
				if($debug) fwrite($fd, "Setting old alias value $origname to $new_alias_name\n");
1800 f1ac1733 Erik Fonnesbeck
				$fieldref = $new_alias_name;
1801 b6db8ea3 sullrich
			}
1802
		}
1803
	}
1804
1805
	if($debug) fclose($fd);
1806
1807
}
1808 f6ba4bd1 Scott Ullrich
1809
function update_alias_url_data() {
1810
	global $config, $g;
1811 e5953c68 Ermal
1812 f6ba4bd1 Scott Ullrich
	/* item is a url type */
1813
	$lockkey = lock('config');
1814 e5953c68 Ermal
	if (is_array($config['aliases']['alias'])) {
1815
		foreach ($config['aliases']['alias'] as $x => $alias) {
1816
			if (empty($alias['aliasurl']))
1817
				continue;
1818
1819 2ef16014 bcyrill
			$address = "";
1820 f6ba4bd1 Scott Ullrich
			$isfirst = 0;
1821 2ef16014 bcyrill
			foreach ($alias['aliasurl'] as $alias_url) {
1822
				/* fetch down and add in */
1823
				$temp_filename = tempnam("{$g['tmp_path']}/", "alias_import");
1824
				unlink($temp_filename);
1825
				$fda = fopen("{$g['tmp_path']}/tmpfetch","w");
1826
				fwrite($fda, "/usr/bin/fetch -T 5 -q -o \"{$temp_filename}/aliases\" \"" . $alias_url . "\"");
1827
				fclose($fda);
1828
				mwexec("/bin/mkdir -p {$temp_filename}");
1829
				mwexec("/usr/bin/fetch -T 5 -q -o \"{$temp_filename}/aliases\" \"" . $alias_url . "\"");
1830
				/* if the item is tar gzipped then extract */
1831
				if (stristr($alias_url, ".tgz"))
1832
					process_alias_tgz($temp_filename);
1833
				else if (stristr($alias_url, ".zip"))
1834
					process_alias_unzip($temp_filename);
1835
				if (file_exists("{$temp_filename}/aliases")) {
1836
					$file_contents = file_get_contents("{$temp_filename}/aliases");
1837
					$file_contents = str_replace("#", "\n#", $file_contents);
1838
					$file_contents_split = explode("\n", $file_contents);
1839
					foreach ($file_contents_split as $fc) {
1840
						$tmp = trim($fc);
1841
						if (stristr($fc, "#")) {
1842
							$tmp_split = explode("#", $tmp);
1843
							$tmp = trim($tmp_split[0]);
1844
						}
1845
						if (trim($tmp) <> "") {
1846
							if ($isfirst == 1)
1847
								$address .= " ";
1848
							$address .= $tmp;
1849
							$isfirst = 1;
1850
						}
1851 f6ba4bd1 Scott Ullrich
					}
1852 2ef16014 bcyrill
					mwexec("/bin/rm -rf {$temp_filename}");
1853 f6ba4bd1 Scott Ullrich
				}
1854 2ef16014 bcyrill
			}
1855
			if($isfirst > 0) {
1856
				$config['aliases']['alias'][$x]['address'] = $address;
1857
				$updated = true;
1858 f6ba4bd1 Scott Ullrich
			}
1859
		}
1860
	}
1861 2ef16014 bcyrill
	if ($updated)
1862 f6ba4bd1 Scott Ullrich
		write_config();
1863
	unlock($lockkey);
1864
}
1865
1866 10189b2a Scott Ullrich
function process_alias_unzip($temp_filename) {
1867
	if(!file_exists("/usr/local/bin/unzip"))
1868
		return;
1869
	mwexec("/bin/mv {$temp_filename}/aliases {$temp_filename}/aliases.zip");
1870
	mwexec("/usr/local/bin/unzip {$temp_filename}/aliases.tgz -d {$temp_filename}/aliases/");
1871
	unlink("{$temp_filename}/aliases.zip");
1872
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1873
	/* foreach through all extracted files and build up aliases file */
1874
	$fd = fopen("{$temp_filename}/aliases", "w");
1875
	foreach($files_to_process as $f2p) {
1876
		$file_contents = file_get_contents($f2p);
1877
		fwrite($fd, $file_contents);
1878
		unlink($f2p);
1879
	}
1880
	fclose($fd);
1881
}
1882
1883 f6ba4bd1 Scott Ullrich
function process_alias_tgz($temp_filename) {
1884 10189b2a Scott Ullrich
	if(!file_exists("/usr/bin/tar"))
1885
		return;
1886 f6ba4bd1 Scott Ullrich
	mwexec("/bin/mv {$temp_filename}/aliases {$temp_filename}/aliases.tgz");
1887
	mwexec("/usr/bin/tar xzf {$temp_filename}/aliases.tgz -C {$temp_filename}/aliases/");
1888
	unlink("{$temp_filename}/aliases.tgz");
1889
	$files_to_process = return_dir_as_array("{$temp_filename}/");
1890
	/* foreach through all extracted files and build up aliases file */
1891
	$fd = fopen("{$temp_filename}/aliases", "w");
1892
	foreach($files_to_process as $f2p) {
1893
		$file_contents = file_get_contents($f2p);
1894
		fwrite($fd, $file_contents);
1895
		unlink($f2p);
1896
	}
1897
	fclose($fd);
1898
}
1899
1900 a76c1c45 jim-p
function version_compare_dates($a, $b) {
1901
	$a_time = strtotime($a);
1902
	$b_time = strtotime($b);
1903
1904
	if ((!$a_time) || (!$b_time)) {
1905
		return FALSE;
1906
	} else {
1907 bda131b2 jim-p
		if ($a_time < $b_time)
1908 a76c1c45 jim-p
			return -1;
1909 bda131b2 jim-p
		elseif ($$a_time == $b_time)
1910 a76c1c45 jim-p
			return 0;
1911
		else
1912
			return 1;
1913
	}
1914
}
1915
function version_get_string_value($a) {
1916
	$strs = array(
1917
		0 => "ALPHA-ALPHA",
1918
		2 => "ALPHA",
1919
		3 => "BETA",
1920
		4 => "B",
1921 5eb03383 jim-p
		5 => "C",
1922
		6 => "D",
1923
		7 => "RC",
1924
		8 => "RELEASE"
1925 a76c1c45 jim-p
	);
1926
	$major = 0;
1927
	$minor = 0;
1928
	foreach ($strs as $num => $str) {
1929
		if (substr($a, 0, strlen($str)) == $str) {
1930
			$major = $num;
1931
			$n = substr($a, strlen($str));
1932
			if (is_numeric($n))
1933
				$minor = $n;
1934
			break;
1935
		}
1936
	}
1937
	return "{$major}.{$minor}";
1938
}
1939
function version_compare_string($a, $b) {
1940
	return version_compare_numeric(version_get_string_value($a), version_get_string_value($b));
1941
}
1942
function version_compare_numeric($a, $b) {
1943
	$a_arr = explode('.', rtrim($a, '.0'));
1944
	$b_arr = explode('.', rtrim($b, '.0'));
1945
1946
	foreach ($a_arr as $n => $val) {
1947
		if (array_key_exists($n, $b_arr)) {
1948
			// So far so good, both have values at this minor version level. Compare.
1949
			if ($val > $b_arr[$n])
1950
				return 1;
1951
			elseif ($val < $b_arr[$n])
1952
				return -1;
1953
		} else {
1954
			// a is greater, since b doesn't have any minor version here.
1955
			return 1;
1956
		}
1957
	}
1958
	if (count($b_arr) > count($a_arr)) {
1959
		// b is longer than a, so it must be greater.
1960
		return -1;
1961
	} else {
1962
		// Both a and b are of equal length and value.
1963
		return 0;
1964
	}
1965
}
1966
function pfs_version_compare($cur_time, $cur_text, $remote) {
1967
	// First try date compare
1968 bda131b2 jim-p
	$v = version_compare_dates($cur_time, $remote);
1969 a76c1c45 jim-p
	if ($v === FALSE) {
1970
		// If that fails, try to compare by string
1971
		// Before anything else, simply test if the strings are equal
1972 b009b153 jim-p
		if (($cur_text == $remote) || ($cur_time == $remote))
1973 a76c1c45 jim-p
			return 0;
1974
		list($cur_num, $cur_str) = explode('-', $cur_text);
1975
		list($rem_num, $rem_str) = explode('-', $remote);
1976
1977
		// First try to compare the numeric parts of the version string.
1978
		$v = version_compare_numeric($cur_num, $rem_num);
1979
1980
		// If the numeric parts are the same, compare the string parts.
1981
		if ($v == 0)
1982
			return version_compare_string($cur_str, $rem_str);
1983
	}
1984
	return $v;
1985
}
1986 c7de8be4 jim-p
function process_alias_urltable($name, $url, $freq, $forceupdate=false) {
1987
	$urltable_prefix = "/var/db/aliastables/";
1988
	$urltable_filename = $urltable_prefix . $name . ".txt";
1989
1990
	// Make the aliases directory if it doesn't exist
1991
	if (!file_exists($urltable_prefix)) {
1992
		mkdir($urltable_prefix);
1993
	} elseif (!is_dir($urltable_prefix)) {
1994
		unlink($urltable_prefix);
1995
		mkdir($urltable_prefix);
1996
	}
1997
1998
	// If the file doesn't exist or is older than update_freq days, fetch a new copy.
1999
	if (!file_exists($urltable_filename)
2000
		|| ((time() - filemtime($urltable_filename)) > ($freq * 86400))
2001
		|| $forceupdate) {
2002
2003
		// Try to fetch the URL supplied
2004
		conf_mount_rw();
2005
		unlink_if_exists($urltable_filename . ".tmp");
2006
		// 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.
2007 83773d85 Marcello Coutinho
		mwexec("/usr/bin/fetch -T 5 -q -o " . escapeshellarg($urltable_filename . ".tmp") . " " . escapeshellarg($url));
2008 c7de8be4 jim-p
		// Remove comments. Might need some grep-fu to only allow lines that look like IPs/subnets
2009 4aa0979f Ermal
		if (file_exists($urltable_filename . ".tmp")) {
2010 8c4ac110 Warren Baker
			mwexec("/usr/bin/sed 's/\;.*//g' ". escapeshellarg($urltable_filename . ".tmp") . "| /usr/bin/egrep -v '^[[:space:]]*$|^#' > " . escapeshellarg($urltable_filename));
2011 4aa0979f Ermal
			unlink_if_exists($urltable_filename . ".tmp");
2012
		} else
2013
			mwexec("/usr/bin/touch {$urltable_filename}");
2014 c7de8be4 jim-p
		conf_mount_ro();
2015 966f359e Ermal
		return true;
2016 c7de8be4 jim-p
	} else {
2017
		// File exists, and it doesn't need updated.
2018
		return -1;
2019
	}
2020
}
2021 08fd5444 jim-p
function get_real_slice_from_glabel($label) {
2022
	$label = escapeshellarg($label);
2023
	return trim(`/sbin/glabel list | /usr/bin/grep -B2 ufs/{$label} | /usr/bin/head -n 1 | /usr/bin/cut -f3 -d' '`);
2024
}
2025
function nanobsd_get_boot_slice() {
2026
	return trim(`/sbin/mount | /usr/bin/grep pfsense | /usr/bin/cut -d'/' -f4 | /usr/bin/cut -d' ' -f1`);
2027
}
2028
function nanobsd_get_boot_drive() {
2029
	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`);
2030
}
2031
function nanobsd_get_active_slice() {
2032
	$boot_drive = nanobsd_get_boot_drive();
2033
	$active = trim(`gpart show $boot_drive | grep '\[active\]' | awk '{print $3;}'`);
2034
2035
	return "{$boot_drive}s{$active}";
2036
}
2037
function nanobsd_get_size() {
2038
	return strtoupper(file_get_contents("/etc/nanosize.txt"));
2039
}
2040 2b5f276f jim-p
function nanobsd_switch_boot_slice() {
2041 08fd5444 jim-p
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2042
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2043
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2044
	nanobsd_detect_slice_info();
2045
2046 2b5f276f jim-p
	if ($BOOTFLASH == $ACTIVE_SLICE) {
2047
		$slice = $TOFLASH;
2048
	} else {
2049
		$slice = $BOOTFLASH;
2050
	}
2051
2052 08fd5444 jim-p
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
2053
	ob_implicit_flush(1);
2054
	if(strstr($slice, "s2")) {
2055
		$ASLICE="2";
2056
		$AOLDSLICE="1";
2057
		$AGLABEL_SLICE="pfsense1";
2058
		$AUFS_ID="1";
2059
		$AOLD_UFS_ID="0";
2060
	} else {
2061
		$ASLICE="1";
2062
		$AOLDSLICE="2";
2063
		$AGLABEL_SLICE="pfsense0";
2064
		$AUFS_ID="0";
2065
		$AOLD_UFS_ID="1";
2066
	}
2067
	$ATOFLASH="{$BOOT_DRIVE}s{$ASLICE}";
2068
	$ACOMPLETE_PATH="{$BOOT_DRIVE}s{$ASLICE}a";
2069
	$ABOOTFLASH="{$BOOT_DRIVE}s{$AOLDSLICE}";
2070
	conf_mount_rw();
2071
	exec("sysctl kern.geom.debugflags=16");
2072
	exec("gpart set -a active -i {$ASLICE} {$BOOT_DRIVE}");
2073
	exec("/usr/sbin/boot0cfg -s {$ASLICE} -v /dev/{$BOOT_DRIVE}");
2074 2b5f276f jim-p
	// We can't update these if they are mounted now.
2075
	if ($BOOTFLASH != $slice) {
2076
		exec("/sbin/tunefs -L ${AGLABEL_SLICE} /dev/$ACOMPLETE_PATH");
2077
		nanobsd_update_fstab($AGLABEL_SLICE, $ACOMPLETE_PATH, $AOLD_UFS_ID, $AUFS_ID);
2078
	}
2079 08fd5444 jim-p
	exec("/sbin/sysctl kern.geom.debugflags=0");
2080
	conf_mount_ro();
2081
}
2082 2b5f276f jim-p
function nanobsd_clone_slice() {
2083 08fd5444 jim-p
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2084
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2085
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2086
	nanobsd_detect_slice_info();
2087
2088
	for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
2089
	ob_implicit_flush(1);
2090
	exec("/sbin/sysctl kern.geom.debugflags=16");
2091
	exec("/bin/dd if=/dev/zero of=/dev/{$TOFLASH} bs=1m count=1");
2092
	exec("/bin/dd if=/dev/{$BOOTFLASH} of=/dev/{$TOFLASH} bs=64k");
2093
	exec("/sbin/tunefs -L {$GLABEL_SLICE} /dev/{$COMPLETE_PATH}");
2094 2b5f276f jim-p
	$status = nanobsd_update_fstab($GLABEL_SLICE, $COMPLETE_PATH, $OLD_UFS_ID, $UFS_ID);
2095 08fd5444 jim-p
	exec("/sbin/sysctl kern.geom.debugflags=0");
2096
	if($status) {
2097
		return false;
2098
	} else {
2099
		return true;
2100
	}
2101
}
2102 2b5f276f jim-p
function nanobsd_update_fstab($gslice, $complete_path, $oldufs, $newufs) {
2103
	$tmppath = "/tmp/{$gslice}";
2104
	$fstabpath = "/tmp/{$gslice}/etc/fstab";
2105
2106
	exec("/bin/mkdir {$tmppath}");
2107
	exec("/sbin/fsck_ufs -y /dev/{$complete_path}");
2108
	exec("/sbin/mount /dev/ufs/{$gslice} {$tmppath}");
2109
	exec("/bin/cp /etc/fstab {$fstabpath}");
2110
2111
	if (!file_exists($fstabpath)) {
2112
		$fstab = <<<EOF
2113 9b1a8d98 Ermal
/dev/ufs/{$gslice} / ufs ro,noatime 1 1
2114
/dev/ufs/cf /cf ufs ro,noatime 1 1
2115 2b5f276f jim-p
EOF;
2116
		if (file_put_contents($fstabpath, $fstab))
2117
			$status = true;
2118
		else
2119
			$status = false;
2120
	} else {
2121
		$status = exec("sed -i \"\" \"s/pfsense{$oldufs}/pfsense{$newufs}/g\" {$fstabpath}");
2122
	}
2123
	exec("/sbin/umount {$tmppath}");
2124
	exec("/bin/rmdir {$tmppath}");
2125
2126
	return $status;
2127
}
2128 08fd5444 jim-p
function nanobsd_detect_slice_info() {
2129
	global $SLICE, $OLDSLICE, $TOFLASH, $COMPLETE_PATH, $COMPLETE_BOOT_PATH;
2130
	global $GLABEL_SLICE, $UFS_ID, $OLD_UFS_ID, $BOOTFLASH;
2131
	global $BOOT_DEVICE, $REAL_BOOT_DEVICE, $BOOT_DRIVE, $ACTIVE_SLICE;
2132 a76c1c45 jim-p
2133 08fd5444 jim-p
	$BOOT_DEVICE=nanobsd_get_boot_slice();
2134
	$REAL_BOOT_DEVICE=get_real_slice_from_glabel($BOOT_DEVICE);
2135
	$BOOT_DRIVE=nanobsd_get_boot_drive();
2136
	$ACTIVE_SLICE=nanobsd_get_active_slice();
2137
2138
	// Detect which slice is active and set information.
2139
	if(strstr($REAL_BOOT_DEVICE, "s1")) {
2140
		$SLICE="2";
2141
		$OLDSLICE="1";
2142
		$GLABEL_SLICE="pfsense1";
2143
		$UFS_ID="1";
2144
		$OLD_UFS_ID="0";
2145 a76c1c45 jim-p
2146 08fd5444 jim-p
	} else {
2147
		$SLICE="1";
2148
		$OLDSLICE="2";
2149
		$GLABEL_SLICE="pfsense0";
2150
		$UFS_ID="0";
2151
		$OLD_UFS_ID="1";
2152
	}
2153
	$TOFLASH="{$BOOT_DRIVE}s{$SLICE}";
2154
	$COMPLETE_PATH="{$BOOT_DRIVE}s{$SLICE}a";
2155
	$COMPLETE_BOOT_PATH="{$BOOT_DRIVE}s{$OLDSLICE}";
2156
	$BOOTFLASH="{$BOOT_DRIVE}s{$OLDSLICE}";
2157
}
2158 38080cc1 Scott Ullrich
2159 26c8cc72 jim-p
function nanobsd_friendly_slice_name($slicename) {
2160
	global $g;
2161
	return strtolower(str_ireplace('pfsense', $g['product_name'], $slicename));
2162
}
2163
2164 38080cc1 Scott Ullrich
function get_include_contents($filename) {
2165
    if (is_file($filename)) {
2166
        ob_start();
2167
        include $filename;
2168
        $contents = ob_get_contents();
2169
        ob_end_clean();
2170
        return $contents;
2171
    }
2172
    return false;
2173
}
2174
2175 3ffa8318 Renato Botelho
/* This xml 2 array function is courtesy of the php.net comment section on xml_parse.
2176
 * it is roughly 4 times faster then our existing pfSense parser but due to the large
2177
 * size of the RRD xml dumps this is required.
2178
 * The reason we do not use it for pfSense is that it does not know about array fields
2179
 * which causes it to fail on array fields with single items. Possible Todo?
2180
 */
2181
function xml2array($contents, $get_attributes = 1, $priority = 'tag')
2182
{
2183 86c707f3 Darren Embry
	if (!function_exists('xml_parser_create'))
2184
	{
2185
		return array ();
2186
	}
2187
	$parser = xml_parser_create('');
2188
	xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
2189
	xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
2190
	xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
2191
	xml_parse_into_struct($parser, trim($contents), $xml_values);
2192
	xml_parser_free($parser);
2193
	if (!$xml_values)
2194
		return; //Hmm...
2195
	$xml_array = array ();
2196
	$parents = array ();
2197
	$opened_tags = array ();
2198
	$arr = array ();
2199
	$current = & $xml_array;
2200
	$repeated_tag_index = array ();
2201
	foreach ($xml_values as $data)
2202
	{
2203
		unset ($attributes, $value);
2204
		extract($data);
2205
		$result = array ();
2206
		$attributes_data = array ();
2207
		if (isset ($value))
2208
		{
2209
			if ($priority == 'tag')
2210
				$result = $value;
2211
			else
2212
				$result['value'] = $value;
2213
		}
2214
		if (isset ($attributes) and $get_attributes)
2215
		{
2216
			foreach ($attributes as $attr => $val)
2217
			{
2218
				if ($priority == 'tag')
2219
					$attributes_data[$attr] = $val;
2220
				else
2221
					$result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
2222
			}
2223
		}
2224
		if ($type == "open")
2225
		{
2226
			$parent[$level -1] = & $current;
2227
			if (!is_array($current) or (!in_array($tag, array_keys($current))))
2228
			{
2229
				$current[$tag] = $result;
2230
				if ($attributes_data)
2231
					$current[$tag . '_attr'] = $attributes_data;
2232
				$repeated_tag_index[$tag . '_' . $level] = 1;
2233
				$current = & $current[$tag];
2234
			}
2235
			else
2236
			{
2237
				if (isset ($current[$tag][0]))
2238
				{
2239
					$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
2240
					$repeated_tag_index[$tag . '_' . $level]++;
2241
				}
2242
				else
2243
				{
2244
					$current[$tag] = array (
2245
						$current[$tag],
2246
						$result
2247
						);
2248
					$repeated_tag_index[$tag . '_' . $level] = 2;
2249
					if (isset ($current[$tag . '_attr']))
2250
					{
2251
						$current[$tag]['0_attr'] = $current[$tag . '_attr'];
2252
						unset ($current[$tag . '_attr']);
2253
					}
2254
				}
2255
				$last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
2256
				$current = & $current[$tag][$last_item_index];
2257
			}
2258
		}
2259
		elseif ($type == "complete")
2260
		{
2261
			if (!isset ($current[$tag]))
2262
			{
2263
				$current[$tag] = $result;
2264
				$repeated_tag_index[$tag . '_' . $level] = 1;
2265
				if ($priority == 'tag' and $attributes_data)
2266
					$current[$tag . '_attr'] = $attributes_data;
2267
			}
2268
			else
2269
			{
2270
				if (isset ($current[$tag][0]) and is_array($current[$tag]))
2271
				{
2272
					$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
2273
					if ($priority == 'tag' and $get_attributes and $attributes_data)
2274
					{
2275
						$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
2276
					}
2277
					$repeated_tag_index[$tag . '_' . $level]++;
2278
				}
2279
				else
2280
				{
2281
					$current[$tag] = array (
2282
						$current[$tag],
2283
						$result
2284
						);
2285
					$repeated_tag_index[$tag . '_' . $level] = 1;
2286
					if ($priority == 'tag' and $get_attributes)
2287
					{
2288
						if (isset ($current[$tag . '_attr']))
2289
						{
2290
							$current[$tag]['0_attr'] = $current[$tag . '_attr'];
2291
							unset ($current[$tag . '_attr']);
2292
						}
2293
						if ($attributes_data)
2294
						{
2295
							$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
2296
						}
2297
					}
2298
					$repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
2299
				}
2300
			}
2301
		}
2302
		elseif ($type == 'close')
2303
		{
2304
			$current = & $parent[$level -1];
2305
		}
2306
	}
2307
	return ($xml_array);
2308 3ffa8318 Renato Botelho
}
2309
2310
function get_country_name($country_code) {
2311
	if ($country_code != "ALL" && strlen($country_code) != 2)
2312
		return "";
2313
2314
	$country_names_xml = "/usr/local/share/mobile-broadband-provider-info/iso_3166-1_list_en.xml";
2315
	$country_names_contents = file_get_contents($country_names_xml);
2316
	$country_names = xml2array($country_names_contents);
2317
2318
	if($country_code == "ALL") {
2319
		$country_list = array();
2320
		foreach($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2321
			$country_list[] = array( "code" => $country['ISO_3166-1_Alpha-2_Code_element'],
2322
						 "name" => ucwords(strtolower($country['ISO_3166-1_Country_name'])) );
2323
		}
2324
		return $country_list;
2325
	}
2326
2327
	foreach ($country_names['ISO_3166-1_List_en']['ISO_3166-1_Entry'] as $country) {
2328
		if ($country['ISO_3166-1_Alpha-2_Code_element'] == strtoupper($country_code)) {
2329
			return ucwords(strtolower($country['ISO_3166-1_Country_name']));
2330
		}
2331
	}
2332
	return "";
2333
}
2334
2335 baaa8bb1 Erik Fonnesbeck
/* sort by interface only, retain the original order of rules that apply to
2336
   the same interface */
2337
function filter_rules_sort() {
2338
	global $config;
2339
2340
	/* mark each rule with the sequence number (to retain the order while sorting) */
2341
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2342
		$config['filter']['rule'][$i]['seq'] = $i;
2343
2344
	usort($config['filter']['rule'], "filter_rules_compare");
2345
2346
	/* strip the sequence numbers again */
2347
	for ($i = 0; isset($config['filter']['rule'][$i]); $i++)
2348
		unset($config['filter']['rule'][$i]['seq']);
2349
}
2350
function filter_rules_compare($a, $b) {
2351 cea355a5 Erik Fonnesbeck
	if (isset($a['floating']) && isset($b['floating']))
2352 baaa8bb1 Erik Fonnesbeck
		return $a['seq'] - $b['seq'];
2353
	else if (isset($a['floating']))
2354
		return -1;
2355
	else if (isset($b['floating']))
2356
		return 1;
2357 cea355a5 Erik Fonnesbeck
	else if ($a['interface'] == $b['interface'])
2358
		return $a['seq'] - $b['seq'];
2359 baaa8bb1 Erik Fonnesbeck
	else
2360
		return compare_interface_friendly_names($a['interface'], $b['interface']);
2361
}
2362
2363 22dae853 Seth Mos
function generate_ipv6_from_mac($mac) {
2364
	$elements = explode(":", $mac);
2365
	if(count($elements) <> 6)
2366
		return false;
2367
2368
	$i = 0;
2369 5aa28c86 Seth Mos
	$ipv6 = "fe80::";
2370 22dae853 Seth Mos
	foreach($elements as $byte) {
2371
		if($i == 0) {
2372
			$hexadecimal =  substr($byte, 1, 2);
2373
			$bitmap = base_convert($hexadecimal, 16, 2);
2374
			$bitmap = str_pad($bitmap, 4, "0", STR_PAD_LEFT);
2375
			$bitmap = substr($bitmap, 0, 2) ."1". substr($bitmap, 3,4);
2376
			$byte = substr($byte, 0, 1) . base_convert($bitmap, 2, 16);
2377
		}
2378
		$ipv6 .= $byte;
2379
		if($i == 1) {
2380
			$ipv6 .= ":";
2381
		}
2382
		if($i == 3) {
2383
			$ipv6 .= ":";
2384
		}
2385
		if($i == 2) {
2386
			$ipv6 .= "ff:fe";
2387
		}
2388
		
2389
		$i++;
2390
	}	
2391 fcdc8943 Seth Mos
	return $ipv6;
2392 22dae853 Seth Mos
}
2393 325e3163 Bill Marquette
2394 57f2840e Evgeny
/****f* pfsense-utils/load_mac_manufacturer_table
2395
 * NAME
2396
 *   load_mac_manufacturer_table
2397
 * INPUTS
2398
 *   none
2399
 * RESULT
2400
 *   returns associative array with MAC-Manufacturer pairs
2401
 ******/
2402
function load_mac_manufacturer_table() {
2403
	/* load MAC-Manufacture data from the file */
2404 62a29fe3 Ermal
	$macs = false;
2405
	if (file_exists("/usr/local/share/nmap/nmap-mac-prefixes"))
2406
		$macs=file("/usr/local/share/nmap/nmap-mac-prefixes");
2407 57f2840e Evgeny
	if ($macs){
2408
		foreach ($macs as $line){
2409
			if (preg_match('/([0-9A-Fa-f]{6}) (.*)$/', $line, $matches)){
2410 4450527f Evgeny
				/* store values like this $mac_man['000C29']='VMware' */
2411 57f2840e Evgeny
				$mac_man["$matches[1]"]=$matches[2];
2412
			}
2413
		}
2414
 		return $mac_man;
2415
	} else
2416
		return -1;
2417
2418
}
2419
2420 474f36d1 Scott Ullrich
/****f* pfsense-utils/is_ipaddr_configured
2421
 * NAME
2422
 *   is_ipaddr_configured
2423
 * INPUTS
2424
 *   IP Address to check.
2425
 * RESULT
2426
 *   returns true if the IP Address is
2427
 *   configured and present on this device.
2428
*/
2429
function is_ipaddr_configured($ipaddr) {
2430
	$interface_list_ips = get_configured_ip_addresses();
2431
	foreach($interface_list_ips as $ilips) {
2432
		if(strcasecmp($ipaddr, $ilips) == 0) 
2433
				return true;
2434
	}	
2435
}
2436
2437 e4a8ed97 Scott Ullrich
/****f* pfsense-utils/pfSense_handle_custom_code
2438
 * NAME
2439
 *   pfSense_handle_custom_code
2440
 * INPUTS
2441
 *   directory name to process
2442
 * RESULT
2443
 *   globs the directory and includes the files
2444
 */
2445 d65962a7 Scott Ullrich
function pfSense_handle_custom_code($src_dir) {
2446
	// Allow extending of the nat edit page and include custom input validation 
2447
	if(is_dir("$src_dir")) {
2448 3dbceb92 Scott Ullrich
		$cf = glob($src_dir . "/*.inc");
2449 d65962a7 Scott Ullrich
		foreach($cf as $nf) {
2450
			if($nf == "." || $nf == "..") 
2451
				continue;
2452
			// Include the extra handler
2453 3dbceb92 Scott Ullrich
			include("$nf");
2454 d65962a7 Scott Ullrich
		}
2455
	}
2456
}
2457
2458 3e139f90 Vinicius Coque
function set_language($lang = 'en_US', $encoding = "ISO8859-1") {
2459
	putenv("LANG={$lang}.{$encoding}");
2460
	setlocale(LC_ALL, "{$lang}.{$encoding}");
2461
	textdomain("pfSense");
2462 a94c4e1f Vinicius Coque
	bindtextdomain("pfSense","/usr/local/share/locale");
2463 3e139f90 Vinicius Coque
	bind_textdomain_codeset("pfSense","{$lang}.{$encoding}");
2464
}
2465
2466
function get_locale_list() {
2467
	$locales = array(
2468
		"en_US" => gettext("English"),
2469 2e2eb012 Vinicius Coque
		"pt_BR" => gettext("Portuguese (Brazil)"),
2470 3e139f90 Vinicius Coque
	);
2471
	asort($locales);
2472
	return $locales;
2473
}
2474 20a7cb15 smos
2475
function return_hex_ipv4($ipv4) {
2476
	if(!is_ipaddrv4($ipv4))
2477
		return(false);
2478
	
2479
	/* we need the hex form of the interface IPv4 address */
2480
	$ip4arr = explode(".", $ipv4);
2481
	$hexwanv4 = "";
2482
	foreach($ip4arr as $octet)
2483
		$hexwanv4 .= sprintf("%02x", $octet);
2484
2485
	return($hexwanv4);
2486
}
2487
2488
function convert_ipv6_to_128bit($ipv6) {
2489
	if(!is_ipaddrv6($ipv6))
2490
		return(false);
2491
2492
	$ip6arr = array();
2493
	$ip6prefix = Net_IPv6::uncompress($ipv6);
2494
	$ip6arr = explode(":", $ip6prefix);
2495
	/* binary presentation of the prefix for all 128 bits. */
2496
	$ip6prefixbin = "";
2497
	foreach($ip6arr as $element) {
2498
		$ip6prefixbin .= sprintf("%016b", hexdec($element));
2499
	}
2500
	return($ip6prefixbin);
2501
}
2502
2503
function convert_128bit_to_ipv6($ip6bin) {
2504
	if(strlen($ip6bin) <> 128)
2505
		return(false);
2506
2507
	$ip6arr = array();
2508
	$ip6binarr = array();
2509
	$ip6binarr = str_split($ip6bin, 16);
2510
	foreach($ip6binarr as $binpart)
2511
		$ip6arr[] = dechex(bindec($binpart));
2512
	$ip6addr = Net_IPv6::compress(implode(":", $ip6arr));
2513
2514
	return($ip6addr);
2515
}
2516
2517 8b198c64 smos
2518
/* Returns the calculated bit length of the prefix delegation from the WAN interface */
2519
/* DHCP-PD is variable, calculate from the prefix-len on the WAN interface */
2520
/* 6rd is variable, calculate from 64 - (v6 prefixlen - (32 - v4 prefixlen)) */
2521
/* 6to4 is 16 bits, e.g. 65535 */
2522
function calculate_ipv6_delegation_length($if) {
2523
	global $config;
2524
2525
	if(!is_array($config['interfaces'][$if]))
2526
		return false;
2527
2528
	switch($config['interfaces'][$if]['ipaddrv6']) {
2529
		case "6to4":
2530
			$pdlen = 16;
2531
			break;
2532
		case "6rd":
2533
			$rd6cfg = $config['interfaces'][$if];
2534
			$rd6plen = explode("/", $rd6cfg['prefix-6rd']);
2535
			$pdlen = (64 - ($rd6plen[1] + (32 - $rd6cfg['prefix-6rd-v4plen'])));
2536
			break;
2537
		case "dhcp6":
2538
			$dhcp6cfg = $config['interfaces'][$if];
2539
			$pdlen = $dhcp6cfg['dhcp6-ia-pd-len'];
2540
			break;
2541
		default:
2542
			$pdlen = 0;
2543
			break;
2544
	}
2545
	return($pdlen);
2546
}
2547 d23e157a smos
2548
function huawei_rssi_to_string($rssi) {
2549
	$dbm = array();
2550
	$i = 0;
2551
	$dbstart = -51;
2552
	while($i < 31) {
2553
		$dbm[$i] = $dbstart - ($i * 2);
2554
		$i++;
2555
	}
2556
	$percent = round(($rssi / 31) * 100);
2557
	$string = "rssi:8 level:{$dbm[$rssi]}dBm percent:{$percent}%";
2558
	return $string;
2559
}
2560
2561
function huawei_mode_to_string($mode, $submode) {
2562
	$modes[0] = "None";
2563
	$modes[1] = "AMPS"; 
2564
	$modes[2] = "CDMA";
2565
	$modes[3] = "GSM/GPRS";
2566
	$modes[4] = "HDR";
2567
	$modes[5] = "WCDMA";
2568
	$modes[6] = "GPS"; 
2569
2570
	$submodes[0] = "No Service";
2571
	$submodes[1] = "GSM";
2572
	$submodes[2] = "GPRS";
2573
	$submodes[3] = "EDGE";
2574
	$submodes[4] = "WCDMA";
2575
	$submodes[5] = "HSDPA";
2576
	$submodes[6] = "HSUPA";
2577 e313da37 smos
	$submodes[7] = "HSDPA+HSUPA";
2578 d23e157a smos
	$submodes[8] = "TD-SCDMA";
2579
	$submodes[9] = "HSPA+";
2580
	$string = "{$modes[$mode]}, {$submodes[$submode]} Mode";
2581
	return $string;
2582
}
2583
2584
function huawei_service_to_string($state) {
2585
	$modes[0] = "No";
2586
	$modes[1] = "Restricted"; 
2587
	$modes[2] = "Valid";
2588
	$modes[3] = "Restricted Regional";
2589
	$modes[4] = "Powersaving";
2590
	$string = "{$modes[$state]} Service";
2591
	return $string;
2592
}
2593
2594
function huawei_simstate_to_string($state) {
2595
	$modes[0] = "Invalid SIM/locked";
2596
	$modes[1] = "Valid SIM"; 
2597
	$modes[2] = "Invalid SIM CS";
2598
	$modes[3] = "Invalid SIM PS";
2599
	$modes[4] = "Invalid SIM CS/PS";
2600
	$modes[255] = "Missing SIM";
2601
	$string = "{$modes[$state]} State";
2602
	return $string;
2603
}
2604 4adf752c smos
2605
function zte_rssi_to_string($rssi) {
2606
	return huawei_rssi_to_string($rssi);
2607
}
2608
2609
function zte_mode_to_string($mode, $submode) {
2610
	$modes[0] = "No Service";
2611
	$modes[1] = "Limited Service"; 
2612
	$modes[2] = "GPRS";
2613
	$modes[3] = "GSM";
2614
	$modes[4] = "UMTS";
2615
	$modes[5] = "EDGE";
2616
	$modes[6] = "HSDPA"; 
2617
2618
	$submodes[0] = "CS_ONLY";
2619
	$submodes[1] = "PS_ONLY";
2620
	$submodes[2] = "CS_PS";
2621
	$submodes[3] = "CAMPED";
2622
	$string = "{$modes[$mode]}, {$submodes[$submode]} Mode";
2623
	return $string;
2624
}
2625
2626
function zte_service_to_string($state) {
2627
	$modes[0] = "Initializing";
2628
	$modes[1] = "Network Lock error"; 
2629
	$modes[2] = "Network Locked";
2630
	$modes[3] = "Unlocked or correct MCC/MNC";
2631
	$string = "{$modes[$state]} Service";
2632
	return $string;
2633
}
2634
2635
function zte_simstate_to_string($state) {
2636
	$modes[0] = "No action";
2637
	$modes[1] = "Network lock"; 
2638
	$modes[2] = "(U)SIM card lock";
2639
	$modes[3] = "Network Lock and (U)SIM card Lock";
2640
	$string = "{$modes[$state]} State";
2641
	return $string;
2642
}
2643 58005e52 jim-p
?>