Project

General

Profile

Download (42.5 KB) Statistics
| Branch: | Tag: | Revision:
1 7b2274cb Scott Ullrich
<?php
2 d884b49c Colin Smith
/****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
 * Copyright (C) 2005 Scott Ullrich (sullrich@gmail.com)
12
 * 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 3a508fe2 Colin Smith
 *
23 d884b49c Colin Smith
 * 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 b63f20c3 Colin Smith
function get_tmp_file() {
37
	return "/tmp/tmp-" . time();
38
}
39
40 ab8caecc Scott Ullrich
/****f* pfsense-utils/get_dns_servers
41
 * NAME
42
 *   get_dns_servres - get system dns servers
43
 * INPUTS
44
 *   $dns_servers - an array of the dns servers
45
 * RESULT
46
 *   null
47
 ******/
48
function get_dns_servers() {
49
	$dns_servers = array();
50
	$dns = `cat /etc/resolv.conf`;
51
	$dns_s = split("\n", $dns);
52
	foreach($dns_s as $dns) {
53
		if (preg_match("/nameserver (.*)/", $dns, $matches))
54
			$dns_servers[] = $matches[1];		
55
	}
56 d9fadeaa Scott Ullrich
	$dns_server_master = array();
57 05d3c4ad Scott Ullrich
	sort($dns_servers);
58 d9fadeaa Scott Ullrich
	foreach($dns_servers as $t) {
59
		if($t <> $lastseen)
60
			if($t <> "")
61
				$dns_server_master[] = $t;
62
		$lastseen = $t;
63
	}
64
	return $dns_server_master;
65 ab8caecc Scott Ullrich
}
66
67 2265659b Colin Smith
/****f* pfsense-utils/log_error
68 a7a594d1 Scott Ullrich
* NAME
69
*   log_error  - Sends a string to syslog.
70
* INPUTS
71
*   $error     - string containing the syslog message.
72
* RESULT
73
*   null
74
******/
75 7b2274cb Scott Ullrich
function log_error($error) {
76 a7a594d1 Scott Ullrich
    $page = $_SERVER['PHP_SELF'];
77
    syslog(LOG_WARNING, "$page: $error");
78 7b2274cb Scott Ullrich
    return;
79
}
80
81 94e8082f Scott Ullrich
/****f* pfsense-utils/get_interface_mac_address
82
 * NAME
83
 *   get_interface_mac_address - Return a interfaces mac address
84
 * INPUTS
85
 *   $interface	- interface to obtain mac address from
86
 * RESULT
87
 *   $mac - the mac address of the interface
88
 ******/
89
function get_interface_mac_address($interface) {
90 4d027492 Colin Smith
    $mac = exec("ifconfig {$interface} | awk '/ether/ {print $2}'");
91
    return trim($mac);
92 94e8082f Scott Ullrich
}
93
94 25192408 Colin Smith
/****f* pfsense-utils/return_dir_as_array
95
 * NAME
96
 *   return_dir_as_array - Return a directory's contents as an array.
97
 * INPUTS
98
 *   $dir	- string containing the path to the desired directory.
99
 * RESULT
100 775433e7 Colin Smith
 *   $dir_array - array containing the directory's contents. This array will be empty if the path specified is invalid.
101 8e362784 Colin Smith
 ******/
102 622fa35a Scott Ullrich
function return_dir_as_array($dir) {
103 174861fd Scott Ullrich
    $dir_array = array();
104 622fa35a Scott Ullrich
    if (is_dir($dir)) {
105 775433e7 Colin Smith
	if ($dh = opendir($dir)) {
106 622fa35a Scott Ullrich
	    while (($file = readdir($dh)) !== false) {
107 174861fd Scott Ullrich
		$canadd = 0;
108
		if($file == ".") $canadd = 1;
109
		if($file == "..") $canadd = 1;
110
		if($canadd == 0)
111
		    array_push($dir_array, $file);
112 622fa35a Scott Ullrich
	    }
113
	    closedir($dh);
114
	}
115
    }
116
    return $dir_array;
117
}
118 7b2274cb Scott Ullrich
119 775433e7 Colin Smith
/****f* pfsense-utils/enable_hardware_offloading
120
 * NAME
121
 *   enable_hardware_offloading - Enable a NIC's supported hardware features.
122
 * INPUTS
123
 *   $interface	- string containing the physical interface to work on.
124
 * RESULT
125
 *   null
126
 * NOTES
127
 *   This function only supports the fxp driver's loadable microcode.
128
 ******/
129 ed059571 Scott Ullrich
function enable_hardware_offloading($interface) {
130 d22669ef Scott Ullrich
    global $g, $config;
131 0c03a1eb Scott Ullrich
    if(isset($config['system']['do_not_use_nic_microcode']))
132 d22669ef Scott Ullrich
	return;
133 31a82233 Scott Ullrich
    if($g['booting']) {
134 af67c4ab Scott Ullrich
	/* translate wan, lan, opt -> real interface if needed */
135
	$int = filter_translate_type_to_real_interface($interface);
136 d641b292 Scott Ullrich
	if(stristr($int,"lnc"))
137
		return;    	
138 8d36fd1d Scott Ullrich
	if($int <> "") $interface = $int;
139 562fca6d Scott Ullrich
        $int_family = preg_split("/[0-9]+/", $int);
140 cc42f645 Scott Ullrich
	$options = strtolower(`/sbin/ifconfig {$interface} | grep options`);
141 7c748413 Scott Ullrich
	echo $interface . " ";
142 027aaef0 Scott Ullrich
	$supported_ints = array('fxp');
143 562fca6d Scott Ullrich
	if (in_array($int_family, $supported_ints))
144
		mwexec("/sbin/ifconfig {$interface} link0");
145 ad7ca08a Scott Ullrich
	if(stristr($options, "txcsum") == true)
146
	    mwexec("/sbin/ifconfig {$interface} txcsum 2>/dev/null");
147
	if(stristr($options, "rxcsum") == true)    
148
	    mwexec("/sbin/ifconfig {$interface} rxcsum 2>/dev/null");    
149
	if(stristr($options, "polling") == true)
150
	    mwexec("/sbin/ifconfig {$interface} polling 2>/dev/null");
151 c9b4da10 Scott Ullrich
    }
152 775433e7 Colin Smith
    return;
153 ed059571 Scott Ullrich
}
154
155 a18b6b97 Scott Ullrich
/****f* pfsense-utils/is_alias_inuse
156
 * NAME
157
 *   checks to see if an alias is currently in use by a rule
158
 * INPUTS
159
 *   
160
 * RESULT
161
 *   true or false
162
 * NOTES
163
 *   
164
 ******/
165
function is_alias_inuse($alias) {
166
    global $g, $config;
167 fde34eb9 Scott Ullrich
    if($alias == "") return false;
168 a18b6b97 Scott Ullrich
    /* loop through firewall rules looking for alias in use */
169 69c30754 Scott Ullrich
    if(is_array($config['nat']['rule']))
170
	    foreach($config['filter']['rule'] as $rule) {
171
			if(is_array($rule['source']['address']))
172 3dad45ad Scott Ullrich
				if($rule['source']['address'] == $alias)
173
					return true;
174 69c30754 Scott Ullrich
			if(is_array($rule['destination']['address']))
175 3dad45ad Scott Ullrich
				if($rule['destination']['address'] == $alias)
176
					return true;
177 69c30754 Scott Ullrich
	    }
178 a18b6b97 Scott Ullrich
    /* loop through nat rules looking for alias in use */
179 69c30754 Scott Ullrich
    if(is_array($config['nat']['rule']))
180
	    foreach($config['nat']['rule'] as $rule) {
181
			if($rule['target'] == $alias)
182 3dad45ad Scott Ullrich
				return true;
183 69c30754 Scott Ullrich
			if($rule['external-address'] == $alias)
184
				return true;	
185
	    }
186 a18b6b97 Scott Ullrich
    return false;
187
}
188
189 562fca6d Scott Ullrich
/****f* pfsense-utils/setup_polling_defaults
190
 * NAME
191
 *   sets up sysctls for pollingS
192
 * INPUTS
193
 *   
194
 * RESULT
195
 *   null
196
 * NOTES
197
 *   
198
 ******/
199
function setup_polling_defaults() {
200
	global $g, $config;
201
	if($config['system']['polling_each_burst'])
202
		mwexec("sysctl kern.polling.each_burst={$config['system']['polling_each_burst']}");
203
	if($config['system']['polling_burst_max'])
204
		mwexec("sysctl kern.polling.burst_max={$config['system']['polling_burst_max']}");
205
	if($config['system']['polling_user_frac'])
206
		mwexec("sysctl kern.polling.user_frac={$config['system']['polling_user_frac']}");		
207
}
208
209
/****f* pfsense-utils/setup_polling
210
 * NAME
211
 *   sets up polling
212
 * INPUTS
213
 *   
214
 * RESULT
215
 *   null
216
 * NOTES
217
 *   
218
 ******/
219
function setup_polling() {
220
	setup_polling_defaults();
221
	global $g, $config;
222
	/* build an array of interfaces to work with */
223
	$iflist = array("lan" => "LAN", "wan" => "WAN");
224
	for ($i = 1; isset($config['interfaces']['opt' . $i]); $i++) 
225
	$iflist['opt' . $i] = $config['interfaces']['opt' . $i]['descr'];		
226
	/*    activate polling for interface if it supports it
227
	 *    man polling on a freebsd box for the following list
228
	 */
229
	/* loop through all interfaces and handle pftpx redirections */
230
	foreach ($iflist as $ifent => $ifname) {	
231
		$supported_ints = array('dc', 'em', 'fwe', 'fwip', 'fxp', 'ixgb', 'ste',
232
			'nge', 're', 'rl', 'sf', 'sis', 'ste', 'vge', 'vr', 'xl');
233
		if (in_array($int_family, $supported_ints) and isset($config['system']['polling'])) {
234
			mwexec("/sbin/ifconfig {$interface} polling");
235
		} else {
236
			mwexec("/sbin/ifconfig {$interface} -polling");
237
		}
238
	}
239
}
240
241 9f6b1429 Scott Ullrich
/****f* pfsense-utils/setup_microcode
242
 * NAME
243
 *   enumerates all interfaces and calls enable_hardware_offloading which
244
 *   enables a NIC's supported hardware features.
245
 * INPUTS
246
 *   
247
 * RESULT
248
 *   null
249
 * NOTES
250
 *   This function only supports the fxp driver's loadable microcode.
251
 ******/
252
function setup_microcode() {
253
   global $config;
254
    $ifdescrs = array('wan', 'lan');
255
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) {
256
	$ifdescrs['opt' . $j] = "opt" . $j;
257
    }
258
    foreach($ifdescrs as $if)
259
	enable_hardware_offloading($if);
260
}
261
262 775433e7 Colin Smith
/****f* pfsense-utils/return_filename_as_array
263
 * NAME
264
 *   return_filename_as_array - Return a file's contents as an array.
265
 * INPUTS
266 158dd870 Colin Smith
 *   $filename	- string containing the path to the desired file.
267
 *   $strip	- array of characters to strip - default is '#'.
268 775433e7 Colin Smith
 * RESULT
269 158dd870 Colin Smith
 *   $file	- array containing the file's contents.
270 775433e7 Colin Smith
 * NOTES
271
 *   This function strips lines starting with '#' and leading/trailing whitespace by default.
272
 ******/
273
function return_filename_as_array($filename, $strip = array('#')) {
274
    if(file_exists($filename)) $file = file($filename);
275
    if(is_array($file)) {
276 b99a7892 Scott Ullrich
	foreach($file as $line) $line = trim($line);
277 775433e7 Colin Smith
        foreach($strip as $tostrip) $file = preg_grep("/^{$tostrip}/", $file, PREG_GREP_INVERT);
278 98b77940 Scott Ullrich
    }
279 0dd62c88 Bill Marquette
    return $file;
280 3ff9d424 Scott Ullrich
}
281
282 e7f2ea12 Scott Ullrich
/****f* pfsense-utils/file_put_contents
283
 * NAME
284
 *   file_put_contents - Wrapper for file_put_contents if it doesn't exist
285
 * RESULT
286
 *   none
287
 ******/
288 5563a2c0 Scott Ullrich
if(!function_exists("file_put_contents")) {
289
    function file_put_contents($filename, $data) {
290
	$fd = fopen($filename,"w");
291
	fwrite($fd, $data);
292
	fclose($fd);
293
    }
294
}
295
296 158dd870 Colin Smith
/****f* pfsense-utils/get_carp_status
297
 * NAME
298
 *   get_carp_status - Return whether CARP is enabled or disabled.
299
 * RESULT
300
 *   boolean	- true if CARP is enabled, false if otherwise.
301
 ******/
302 b1174d02 Scott Ullrich
function get_carp_status() {
303
    /* grab the current status of carp */
304 1a97d17c Scott Ullrich
    $status = `/sbin/sysctl net.inet.carp.allow | cut -d" " -f2`;
305
    if(intval($status) == "0") return false;
306 b1174d02 Scott Ullrich
    return true;
307
}
308
309 158dd870 Colin Smith
/****f* pfsense-utils/is_carp_defined
310
 * NAME
311
 *   is_carp_defined - Return whether CARP is detected in the kernel.
312
 * RESULT
313
 *   boolean	- true if CARP is detected, false otherwise.
314
 ******/
315 a8ac6c98 Scott Ullrich
function is_carp_defined() {
316 0f66804f Scott Ullrich
    /* is carp compiled into the kernel and userland? */
317
    $command = "/sbin/sysctl -a | grep carp";
318
    $fd = popen($command . " 2>&1 ", "r");
319
    if(!$fd) {
320 ef4550f8 Scott Ullrich
	log_error("Warning, could not execute command {$command}");
321
	return 0;
322 0f66804f Scott Ullrich
    }
323
    while(!feof($fd)) {
324 ef4550f8 Scott Ullrich
	$tmp .= fread($fd,49);
325 0f66804f Scott Ullrich
    }
326
    fclose($fd);
327 a8ac6c98 Scott Ullrich
328 0f66804f Scott Ullrich
    if($tmp == "")
329 ef4550f8 Scott Ullrich
	return false;
330 0f66804f Scott Ullrich
    else
331 ef4550f8 Scott Ullrich
	return true;
332 a8ac6c98 Scott Ullrich
}
333
334 ffb4b005 Scott Ullrich
/****f* pfsense-utils/get_interface_mtu
335
 * NAME
336
 *   get_interface_mtu - Return the mtu of an interface
337
 * RESULT
338
 *   $tmp	- Returns the mtu of an interface
339
 ******/
340
function get_interface_mtu($interface) {
341
	$mtu = `/sbin/ifconfig {$interface} | /usr/bin/grep mtu | /usr/bin/cut -d" " -f4`;
342 62739c1c Scott Ullrich
	return $mtu;
343 ffb4b005 Scott Ullrich
}
344
345 df792110 Scott Ullrich
/****f* pfsense-utils/is_interface_wireless
346
 * NAME
347
 *   is_interface_wireless - Returns if an interface is wireless
348
 * RESULT
349
 *   $tmp	- Returns if an interface is wireless
350
 ******/
351
function is_interface_wireless($interface) {
352
	global $config, $g;
353 b5af44a1 Scott Ullrich
	$interface = convert_real_interface_to_friendly_interface_name($interface);
354 df792110 Scott Ullrich
	if(isset($config['interfaces'][$interface]['wireless']))
355
		return true;
356
	else
357
		return false;
358
}
359
360 158dd870 Colin Smith
/****f* pfsense-utils/find_number_of_created_carp_interfaces
361
 * NAME
362
 *   find_number_of_created_carp_interfaces - Return the number of CARP interfaces.
363
 * RESULT
364
 *   $tmp	- Number of currently created CARP interfaces.
365
 ******/
366 ed059571 Scott Ullrich
function find_number_of_created_carp_interfaces() {
367 0f66804f Scott Ullrich
    $command = "/sbin/ifconfig | /usr/bin/grep \"carp*:\" | /usr/bin/wc -l";
368
    $fd = popen($command . " 2>&1 ", "r");
369
    if(!$fd) {
370 ef4550f8 Scott Ullrich
	log_error("Warning, could not execute command {$command}");
371
	return 0;
372 0f66804f Scott Ullrich
    }
373
    while(!feof($fd)) {
374 ef4550f8 Scott Ullrich
	$tmp .= fread($fd,49);
375 0f66804f Scott Ullrich
    }
376
    fclose($fd);
377
    $tmp = intval($tmp);
378
    return $tmp;
379 ed059571 Scott Ullrich
}
380
381 158dd870 Colin Smith
/****f* pfsense-utils/link_ip_to_carp_interface
382
 * NAME
383
 *   link_ip_to_carp_interface - Find where a CARP interface links to.
384
 * INPUTS
385
 *   $ip
386
 * RESULT
387
 *   $carp_ints
388 0c84aff0 Colin Smith
 ******/
389 fa65a62b Scott Ullrich
function link_ip_to_carp_interface($ip) {
390 669e1adb Bill Marquette
	global $config;
391
	if($ip == "") return;
392 fa65a62b Scott Ullrich
393 669e1adb Bill Marquette
	$ifdescrs = array('wan', 'lan');
394
	for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) {
395
		$ifdescrs['opt' . $j] = "opt" . $j;
396
	}
397 fa65a62b Scott Ullrich
398 669e1adb Bill Marquette
	$ft = split("\.", $ip);
399
	$ft_ip = $ft[0] . "." . $ft[1] . "." . $ft[2] . ".";
400 0f66804f Scott Ullrich
401 669e1adb Bill Marquette
	$carp_ints = "";
402
	$num_carp_ints = find_number_of_created_carp_interfaces();
403
	foreach ($ifdescrs as $ifdescr => $ifname) {
404
		for($x=0; $x<$num_carp_ints; $x++) {
405
			$carp_int = "carp{$x}";
406
			$carp_ip = find_interface_ip($carp_int);
407
			$carp_ft = split("\.", $carp_ip);
408
			$carp_ft_ip = $carp_ft[0] . "." . $carp_ft[1] . "." . $carp_ft[2] . ".";
409
			$result = does_interface_exist($carp_int);
410
			if($result <> true) break;
411
			if($ft_ip == $carp_ft_ip)
412
			if(stristr($carp_ints,$carp_int) == false)
413
			$carp_ints .= " " . $carp_int;
414
		}
415 ef4550f8 Scott Ullrich
	}
416 669e1adb Bill Marquette
	return $carp_ints;
417 fa65a62b Scott Ullrich
}
418
419 158dd870 Colin Smith
/****f* pfsense-utils/exec_command
420
 * NAME
421
 *   exec_command - Execute a command and return a string of the result.
422
 * INPUTS
423
 *   $command	- String of the command to be executed.
424
 * RESULT
425
 *   String containing the command's result.
426
 * NOTES
427
 *   This function returns the command's stdout and stderr.
428
 ******/
429 5ccfea33 Scott Ullrich
function exec_command($command) {
430 158dd870 Colin Smith
    $output = array();
431
    exec($command . ' 2>&1 ', $output);
432
    return(implode("\n", $output));
433 5ccfea33 Scott Ullrich
}
434
435 dc19bcf8 Scott Ullrich
/****f* interfaces/is_jumbo_capable
436 ff02a977 Scott Ullrich
 * NAME
437 dc19bcf8 Scott Ullrich
 *   is_jumbo_capable - Test if interface is jumbo frame capable.  Useful for determining VLAN capability.
438 ff02a977 Scott Ullrich
 * INPUTS
439 dc19bcf8 Scott Ullrich
 *   $int             - string containing interface name
440 ff02a977 Scott Ullrich
 * RESULT
441 dc19bcf8 Scott Ullrich
 *   boolean          - true or false
442 ff02a977 Scott Ullrich
 ******/
443 dc19bcf8 Scott Ullrich
function is_jumbo_capable($int) {
444
	/* Per:
445 784c2947 Scott Ullrich
	 * http://www.freebsd.org/cgi/man.cgi?query=vlan&manpath=FreeBSD+6.0-RELEASE&format=html
446 dc19bcf8 Scott Ullrich
	 * Only the following drivers support large frames
447
	 */
448 a52609a5 Scott Ullrich
	/* 'de' chipset purposely left out of this list
449
	 * requires defining BIG_PACKET in the
450
	 * /usr/src/sys/pci/if_de.c source file and rebuilding the
451
	 * kernel or module.  The hack works only for the 21041,
452
	 * 21140, and 21140A chips.
453
	 */
454
	$capable = array("bfe", "bge", "dc", "em", "fxp", "gem", "hme", 
455 784c2947 Scott Ullrich
		"ixgb", "nge", "re", "rl", "sis", "ste", "ti", "tl", "tx",
456
		"txp", "xl");
457 dc19bcf8 Scott Ullrich
	
458
	$int_family = preg_split("/[0-9]+/", $int);
459
460
	if (in_array($int_family[0], $capable))
461
		return true;
462
	else
463
		return false;
464 ff02a977 Scott Ullrich
}
465
466 fa65a62b Scott Ullrich
/*
467
 * does_interface_exist($interface): return true or false if a interface is detected.
468
 */
469
function does_interface_exist($interface) {
470
    $ints = exec_command("/sbin/ifconfig -l");
471 83661f77 Scott Ullrich
    if(stristr($ints, $interface) !== false)
472 fa65a62b Scott Ullrich
	return true;
473
    else
474
	return false;
475
}
476
477 5ccfea33 Scott Ullrich
/*
478
 * convert_ip_to_network_format($ip, $subnet): converts an ip address to network form
479
 */
480
function convert_ip_to_network_format($ip, $subnet) {
481
    $ipsplit = split('[.]', $ip);
482
    $string = $ipsplit[0] . "." . $ipsplit[1] . "." . $ipsplit[2] . ".0/" . $subnet;
483
    return $string;
484
}
485
486 b04a6ca4 Scott Ullrich
/*
487
 * find_interface_ip($interface): return the interface ip (first found)
488
 */
489
function find_interface_ip($interface) {
490 4983ed8c Scott Ullrich
    if(does_interface_exist($interface) == false) return;
491 e3939e20 Scott Ullrich
    $ip = exec_command("/sbin/ifconfig {$interface} | /usr/bin/grep -w \"inet\" | /usr/bin/cut -d\" \" -f 2");
492 e67f187a Scott Ullrich
    $ip = str_replace("\n","",$ip);
493 b04a6ca4 Scott Ullrich
    return $ip;
494
}
495
496 3314bb92 Scott Ullrich
function guess_interface_from_ip($ipaddress) {
497
    $ints = `/sbin/ifconfig -l`;
498
    $ints_split = split(" ", $ints);
499
    $ip_subnet_split = split("\.", $ipaddress);
500
    $ip_subnet = $ip_subnet_split[0] . "." . $ip_subnet_split[1] . "." . $ip_subnet_split[2] . ".";
501
    foreach($ints_split as $int) {
502
        $ip = find_interface_ip($int);
503
        $ip_split = split("\.", $ip);
504
        $ip_tocheck = $ip_split[0] . "." . $ip_split[1] . "." . $ip_split[2] . ".";
505
        if(stristr($ip_tocheck, $ip_subnet) != false) return $int;
506
    }
507
}
508
509 fa65a62b Scott Ullrich
function filter_opt_interface_to_real($opt) {
510 0f66804f Scott Ullrich
    global $config;
511
    return $config['interfaces'][$opt]['if'];
512 fa65a62b Scott Ullrich
}
513
514
function filter_get_opt_interface_descr($opt) {
515 0f66804f Scott Ullrich
    global $config;
516
    return $config['interfaces'][$opt]['descr'];
517 fa65a62b Scott Ullrich
}
518
519 b73cc056 Scott Ullrich
function get_friendly_interface_list_as_array() {
520 0f66804f Scott Ullrich
    global $config;
521
    $ints = array();
522
    $ifdescrs = array('wan', 'lan');
523
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) {
524 669e1adb Bill Marquette
		$ifdescrs['opt' . $j] = "opt" . $j;
525 0f66804f Scott Ullrich
    }
526
    $ifdescrs = get_interface_list();
527
    foreach ($ifdescrs as $ifdescr => $ifname) {
528 669e1adb Bill Marquette
		array_push($ints,$ifdescr);
529 0f66804f Scott Ullrich
    }
530
    return $ints;
531 b73cc056 Scott Ullrich
}
532
533 5ccfea33 Scott Ullrich
/*
534
 * find_ip_interface($ip): return the interface where an ip is defined
535
 */
536
function find_ip_interface($ip) {
537 0f66804f Scott Ullrich
    global $config;
538
    $ifdescrs = array('wan', 'lan');
539
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) {
540 ef4550f8 Scott Ullrich
	$ifdescrs['opt' . $j] = "opt" . $j;
541 0f66804f Scott Ullrich
    }
542
    foreach ($ifdescrs as $ifdescr => $ifname) {
543
	$int = filter_translate_type_to_real_interface($ifname);
544
	$ifconfig = exec_command("/sbin/ifconfig {$int}");
545
	if(stristr($ifconfig,$ip) <> false)
546
	    return $int;
547
    }
548
    return false;
549 5ccfea33 Scott Ullrich
}
550
551 bc5d2a26 Scott Ullrich
/*
552
 *  filter_translate_type_to_real_interface($interface): returns the real interface name
553
 *                                                       for a friendly interface.  ie: wan
554
 */
555
function filter_translate_type_to_real_interface($interface) {
556 ef4550f8 Scott Ullrich
    global $config;
557 b46dbd5e Scott Ullrich
    if($config['interfaces'][$interface]['if'] <> "") {
558
	return $config['interfaces'][$interface]['if'];
559
    } else {
560
	return $interface;
561
    }
562 bc5d2a26 Scott Ullrich
}
563
564 591afdfd Scott Ullrich
/*
565
 * get_carp_interface_status($carpinterface): returns the status of a carp ip
566
 */
567
function get_carp_interface_status($carpinterface) {
568 669e1adb Bill Marquette
	/* basically cache the contents of ifconfig statement
569
	to speed up this routine */
570
	global $carp_query;
571
	if($carp_query == "")
572 10655b3c Scott Ullrich
	$carp_query = split("\n", `/sbin/ifconfig | /usr/bin/grep carp`);
573 669e1adb Bill Marquette
	$found_interface = 0;
574
	foreach($carp_query as $int) {
575
		if($found_interface == 1) {
576
			if(stristr($int, "MASTER") == true) return "MASTER";
577
			if(stristr($int, "BACKUP") == true) return "BACKUP";
578
			if(stristr($int, "INIT") == true) return "INIT";
579
			return false;
580
		}
581
		if(stristr($int, $carpinterface) == true)
582
		$found_interface=1;
583 10655b3c Scott Ullrich
	}
584 669e1adb Bill Marquette
	return;
585 591afdfd Scott Ullrich
}
586
587 167bcf84 Scott Ullrich
/*
588
 * get_pfsync_interface_status($pfsyncinterface): returns the status of a pfsync
589
 */
590
function get_pfsync_interface_status($pfsyncinterface) {
591 962f7d25 Scott Ullrich
    $result = does_interface_exist($pfsyncinterface);
592 4983ed8c Scott Ullrich
    if($result <> true) return;
593 e3939e20 Scott Ullrich
    $status = exec_command("/sbin/ifconfig {$pfsyncinterface} | /usr/bin/grep \"pfsync:\" | /usr/bin/cut -d\" \" -f5");
594 167bcf84 Scott Ullrich
    return $status;
595
}
596
597 5ccfea33 Scott Ullrich
/*
598
 * find_carp_interface($ip): return the carp interface where an ip is defined
599
 */
600
function find_carp_interface($ip) {
601 d6caad17 Scott Ullrich
    global $find_carp_ifconfig;
602
    if($find_carp_ifconfig == "") {
603
	$find_carp_ifconfig = array();
604
	$num_carp_ints = find_number_of_created_carp_interfaces();
605
	for($x=0; $x<$num_carp_ints; $x++) {
606
	    $find_carp_ifconfig[$x] = exec_command("/sbin/ifconfig carp{$x}");
607
	}
608
    }
609
    $carps = 0;
610
    foreach($find_carp_ifconfig as $fci) {
611
	if(stristr($fci, $ip) == true)
612
	    return "carp{$carps}";
613
	$carps++;
614 5ccfea33 Scott Ullrich
    }
615
}
616
617 3962b070 Scott Ullrich
/*
618
 * setup_filter_bridge(): toggle filtering bridge
619
 */
620
function setup_filter_bridge() {
621
	global $config, $g;
622
	if(isset($config['bridge']['filteringbridge'])) {
623 3f82e64d Scott Ullrich
		mwexec("/sbin/sysctl net.link.bridge.pfil_member=1");
624
		mwexec("/sbin/sysctl net.link.bridge.pfil_bridge=1");
625 3962b070 Scott Ullrich
	} else {		
626 3f82e64d Scott Ullrich
		mwexec("/sbin/sysctl net.link.bridge.pfil_member=0");
627
		mwexec("/sbin/sysctl net.link.bridge.pfil_bridge=0");
628 3962b070 Scott Ullrich
	}
629
}
630
631 335978db Scott Ullrich
/*
632
 * find_number_of_created_bridges(): returns the number of currently created bridges
633
 */
634
function find_number_of_created_bridges() {
635
    return `/sbin/ifconfig | grep \"bridge[0-999]\:" | wc -l`;
636
}
637
638 5ccfea33 Scott Ullrich
/*
639
 * add_rule_to_anchor($anchor, $rule): adds the specified rule to an anchor
640
 */
641 a35f1242 Scott Ullrich
function add_rule_to_anchor($anchor, $rule, $label) {
642 8c8e6792 Scott Ullrich
    mwexec("echo " . $rule . " | /sbin/pfctl -a " . $anchor . ":" . $label . " -f -");
643 5ccfea33 Scott Ullrich
}
644
645 06e2627e Scott Ullrich
/*
646
 * remove_text_from_file
647
 * remove $text from file $file
648
 */
649
function remove_text_from_file($file, $text) {
650
    global $fd_log;
651
    fwrite($fd_log, "Adding needed text items:\n");
652
    $filecontents = exec_command_and_return_text("cat " . $file);
653
    $textTMP = str_replace($text, "", $filecontents);
654
    $text .= $textTMP;
655
    fwrite($fd_log, $text . "\n");
656
    $fd = fopen($file, "w");
657
    fwrite($fd, $text);
658
    fclose($fd);
659
}
660
661
/*
662
 * add_text_to_file($file, $text): adds $text to $file.
663
 * replaces the text if it already exists.
664
 */
665
function add_text_to_file($file, $text) {
666 b63f20c3 Colin Smith
	if(file_exists($file) and is_writable($file)) {
667
		$filecontents = file($file);
668 ee3a5827 Colin Smith
		$filecontents[] = $text;
669 b63f20c3 Colin Smith
		$tmpfile = get_tmp_file();
670
		$fout = fopen($tmpfile, "w");
671
		foreach($filecontents as $line) {
672 ee3a5827 Colin Smith
			fwrite($fout, rtrim($line) . "\n");
673 b63f20c3 Colin Smith
		}
674 ee3a5827 Colin Smith
		fclose($fout);
675 b63f20c3 Colin Smith
		rename($tmpfile, $file);
676
		return true;
677
	} else {
678
		return false;
679
	}
680 06e2627e Scott Ullrich
}
681
682 b9716104 Scott Ullrich
/*
683
 *   after_sync_bump_adv_skew(): create skew values by 1S
684
 */
685
function after_sync_bump_adv_skew() {
686
	global $config, $g;
687
	$processed_skew = 1;
688
	$a_vip = &$config['virtualip']['vip'];
689
	foreach ($a_vip as $vipent) {
690
		if($vipent['advskew'] <> "") {
691
			$processed_skew = 1;
692
			$vipent['advskew'] = $vipent['advskew']+1;
693
		}
694
	}
695
	if($processed_skew == 1)
696
		write_config("After synch increase advertising skew");
697
}
698
699 06e2627e Scott Ullrich
/*
700
 * get_filename_from_url($url): converts a url to its filename.
701
 */
702
function get_filename_from_url($url) {
703 8072f087 Colin Smith
	return basename($url);
704 06e2627e Scott Ullrich
}
705
706
/*
707
 *   update_output_window: update bottom textarea dynamically.
708
 */
709
function update_output_window($text) {
710 0f66804f Scott Ullrich
    $log = ereg_replace("\n", "\\n", $text);
711
    echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = \"" . $log . "\";</script>";
712 06e2627e Scott Ullrich
}
713
714
/*
715
 *   get_dir: return an array of $dir
716
 */
717
function get_dir($dir) {
718 0f66804f Scott Ullrich
    $dir_array = array();
719
    $d = dir($dir);
720
    while (false !== ($entry = $d->read())) {
721 ef4550f8 Scott Ullrich
	array_push($dir_array, $entry);
722 0f66804f Scott Ullrich
    }
723
    $d->close();
724
    return $dir_array;
725 06e2627e Scott Ullrich
}
726
727
/*
728
 *   update_output_window: update top textarea dynamically.
729
 */
730
function update_status($status) {
731 ef4550f8 Scott Ullrich
    echo "\n<script language=\"JavaScript\">document.forms[0].status.value=\"" . $status . "\";</script>";
732 06e2627e Scott Ullrich
}
733
734
/*
735
 *   exec_command_and_return_text_array: execute command and return output
736
 */
737
function exec_command_and_return_text_array($command) {
738 669e1adb Bill Marquette
	$fd = popen($command . " 2>&1 ", "r");
739
	while(!feof($fd)) {
740
		$tmp .= fread($fd,49);
741
	}
742
	fclose($fd);
743
	$temp_array = split("\n", $tmp);
744
	return $temp_array;
745 06e2627e Scott Ullrich
}
746
747
/*
748
 *   exec_command_and_return_text: execute command and return output
749
 */
750
function exec_command_and_return_text($command) {
751 ef4550f8 Scott Ullrich
    return exec_command($command);
752 06e2627e Scott Ullrich
}
753
754
/*
755
 *   exec_command_and_return_text: execute command and update output window dynamically
756
 */
757
function execute_command_return_output($command) {
758
    global $fd_log;
759
    $fd = popen($command . " 2>&1 ", "r");
760
    echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = \"\";</script>";
761
    $counter = 0;
762
    $counter2 = 0;
763
    while(!feof($fd)) {
764
	$tmp = fread($fd, 50);
765
	$tmp1 = ereg_replace("\n","\\n", $tmp);
766
	$text = ereg_replace("\"","'", $tmp1);
767
	if($lasttext == "..") {
768
	    $text = "";
769
	    $lasttext = "";
770
	    $counter=$counter-2;
771
	} else {
772
	    $lasttext .= $text;
773
	}
774
	if($counter > 51) {
775
	    $counter = 0;
776
	    $extrabreak = "\\n";
777
	} else {
778
	    $extrabreak = "";
779
	    $counter++;
780
	}
781
	if($counter2 > 600) {
782
	    echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = \"\";</script>";
783
	    $counter2 = 0;
784
	} else
785
	    $counter2++;
786
	echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = this.document.forms[0].output.value + \"" . $text . $extrabreak .  "\"; f('output'); </script>";
787
    }
788
    fclose($fd);
789
}
790
791 55be70e6 Scott Ullrich
/*
792
 * convert_friendly_interface_to_real_interface_name($interface): convert WAN to FXP0
793
 */
794
function convert_friendly_interface_to_real_interface_name($interface) {
795 54f4caed Scott Ullrich
    global $config;
796 a7f5febb Scott Ullrich
    $lc_interface = strtolower($interface);
797 303831c6 Scott Ullrich
    if($lc_interface == "lan") return $config['interfaces']['lan']['if'];
798
    if($lc_interface == "wan") return $config['interfaces']['wan']['if'];
799
    $ifdescrs = array();
800
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++)
801
	$ifdescrs['opt' . $j] = "opt" . $j;
802 401e59a9 Scott Ullrich
    foreach ($ifdescrs as $ifdescr => $ifname) {
803 303831c6 Scott Ullrich
	if(strtolower($ifname) == $lc_interface)
804
	    return $config['interfaces'][$ifname]['if'];
805
	if(strtolower($config['interfaces'][$ifname]['descr']) == $lc_interface)
806 401e59a9 Scott Ullrich
	    return $config['interfaces'][$ifname]['if'];
807
    }
808
    return $interface;
809 55be70e6 Scott Ullrich
}
810
811 cc869478 Scott Ullrich
/*
812
 * convert_real_interface_to_friendly_interface_name($interface): convert fxp0 -> wan, etc.
813
 */
814
function convert_real_interface_to_friendly_interface_name($interface) {
815 0f66804f Scott Ullrich
    global $config;
816
    $ifdescrs = array('wan', 'lan');
817
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++)
818
	$ifdescrs['opt' . $j] = "opt" . $j;
819
    foreach ($ifdescrs as $ifdescr => $ifname) {
820
	$int = filter_translate_type_to_real_interface($ifname);
821
	if($ifname == $interface) return $ifname;
822
	if($int == $interface) return $ifname;
823
    }
824
    return $interface;
825 cc869478 Scott Ullrich
}
826
827 06e2627e Scott Ullrich
/*
828
 * update_progress_bar($percent): updates the javascript driven progress bar.
829
 */
830
function update_progress_bar($percent) {
831 0f66804f Scott Ullrich
    if($percent > 100) $percent = 1;
832
    echo "\n<script type=\"text/javascript\" language=\"javascript\">";
833
    echo "\ndocument.progressbar.style.width='" . $percent . "%';";
834
    echo "\n</script>";
835 06e2627e Scott Ullrich
}
836
837 b45ea709 Scott Ullrich
/*
838 76177335 Scott Ullrich
 * gather_altq_queue_stats():  gather alq queue stats and return an array that
839 b45ea709 Scott Ullrich
 *                             is queuename|qlength|measured_packets
840 fbc24b62 Colin Smith
 *                             NOTE: this command takes 5 seconds to run
841 b45ea709 Scott Ullrich
 */
842 6a153733 Scott Ullrich
function gather_altq_queue_stats($dont_return_root_queues) {
843 e90bc39f Scott Ullrich
    mwexec("/usr/bin/killall -9 pfctl");
844 9c0ad35c Scott Ullrich
    $stats = `/sbin/pfctl -vvsq & /bin/sleep 5;/usr/bin/killall pfctl 2>/dev/null`;
845 b45ea709 Scott Ullrich
    $stats_array = split("\n", $stats);
846
    $queue_stats = array();
847
    foreach ($stats_array as $stats_line) {
848
        if (preg_match_all("/queue\s+(\w+)\s+/",$stats_line,$match_array))
849
            $queue_name = $match_array[1][0];
850 fccb044c Scott Ullrich
        if (preg_match_all("/measured:\s+.*packets\/s\,\s(.*)\s+\]/",$stats_line,$match_array))
851
            $speed = $match_array[1][0];
852 e90bc39f Scott Ullrich
        if (preg_match_all("/borrows:\s+(.*)/",$stats_line,$match_array))
853
            $borrows = $match_array[1][0];
854 4bed294c Bill Marquette
        if (preg_match_all("/suspends:\s+(.*)/",$stats_line,$match_array))
855
            $suspends = $match_array[1][0];
856 04e6e7b7 Bill Marquette
        if (preg_match_all("/dropped pkts:\s+(.*)/",$stats_line,$match_array))
857
            $drops = $match_array[1][0];
858 b45ea709 Scott Ullrich
        if (preg_match_all("/measured:\s+(.*)packets/",$stats_line,$match_array)) {
859
            $measured = $match_array[1][0];
860 6a153733 Scott Ullrich
	    if($dont_return_root_queues == true)
861
		if(stristr($queue_name,"root_") == false)
862 122a9c39 Scott Ullrich
		    array_push($queue_stats, "{$queue_name}|{$speed}|{$measured}|{$borrows}|{$suspends}|{$drops}");
863 b45ea709 Scott Ullrich
        }
864
    }
865
    return $queue_stats;
866
}
867 fa35df12 Scott Ullrich
868 fbc24b62 Colin Smith
/*
869 0ad0f98c Scott Ullrich
 * reverse_strrchr($haystack, $needle):  Return everything in $haystack up to the *last* instance of $needle.
870 fbc24b62 Colin Smith
 *					 Useful for finding paths and stripping file extensions.
871
 */
872 29c3c942 Colin Smith
function reverse_strrchr($haystack, $needle)
873
{
874
               return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) +1 ) : false;
875 fbc24b62 Colin Smith
}
876
877 f8891a0f Scott Ullrich
/*
878 832f1b83 Scott Ullrich
 *  backup_config_section($section): returns as an xml file string of
879
 *                                   the configuration section
880 f8891a0f Scott Ullrich
 */
881
function backup_config_section($section) {
882
    global $config;
883 6d501961 Scott Ullrich
    $new_section = &$config[$section];
884 832f1b83 Scott Ullrich
    /* generate configuration XML */
885
    $xmlconfig = dump_xml_config($new_section, $section);
886 8602b9f6 Scott Ullrich
    $xmlconfig = str_replace("<?xml version=\"1.0\"?>", "", $xmlconfig);
887 014beac3 Scott Ullrich
    return $xmlconfig;
888 f8891a0f Scott Ullrich
}
889
890 5ea0509e Colin Smith
/*
891
 *  backup_config_ts_scheduler(): returns the traffic shaper scheduler for backup
892
 */
893
function backup_config_ts_scheduler() {
894
    global $config;
895
    $new_section = &$config['syste']['schedulertype'];
896
    /* generate configuration XML */
897
    $xmlconfig = dump_xml_config($new_section, $section);
898
    $xmlconfig = str_replace("<?xml version=\"1.0\"?>", "", $xmlconfig);
899
    return $xmlconfig;
900
}
901
902 7c4990af Scott Ullrich
/*
903
 *  backup_config_section($section): returns as an xml file string of
904
 *                                   the configuration section
905
 */
906 20091784 Scott Ullrich
function backup_vip_config_section() {
907 7c4990af Scott Ullrich
    global $config;
908
    $new_section = &$config['virtualip'];
909 dd7f4560 Scott Ullrich
    foreach($new_section['vip'] as $section) {
910
	if($section['mode'] == "proxyarp") {
911 7c4990af Scott Ullrich
		unset($section);		
912
	}
913 dd7f4560 Scott Ullrich
	if($section['advskew'] <> "") {
914 afb3b079 Scott Ullrich
		$section_val = intval($section['advskew']);
915 ec2a000e Scott Ullrich
		$section_val=$section_val+100;
916 afb3b079 Scott Ullrich
		if($section_val > 255)
917
			$section_val = 255;
918
		$section['advskew'] = $section_val;
919 02ed6c8f Scott Ullrich
	}
920 dd7f4560 Scott Ullrich
	$temp['vip'][] = $section;
921 7c4990af Scott Ullrich
    }
922 1a94ea6c Scott Ullrich
    return $temp;
923 7c4990af Scott Ullrich
}
924
925 f8891a0f Scott Ullrich
/*
926
 *  restore_config_section($section, new_contents): restore a configuration section,
927
 *                                                  and write the configuration out
928
 *                                                  to disk/cf.
929
 */
930
function restore_config_section($section, $new_contents) {
931
    global $config;
932 ee096757 Scott Ullrich
    conf_mount_rw();
933 832f1b83 Scott Ullrich
    $fout = fopen("{$g['tmp_path']}/tmpxml","w");
934 014beac3 Scott Ullrich
    fwrite($fout, $new_contents);
935 832f1b83 Scott Ullrich
    fclose($fout);
936 bb4f8f8a Colin Smith
    $section_xml = parse_xml_config($g['tmp_path'] . "/tmpxml", $section);
937 832f1b83 Scott Ullrich
    $config[$section] = &$section_xml;
938
    unlink($g['tmp_path'] . "/tmpxml");
939 782c32a7 Bill Marquette
    write_config("Restored {$section} of config file (maybe from CARP partner)");
940 ee096757 Scott Ullrich
    conf_mount_ro();
941 46624b94 Scott Ullrich
    return;
942 f8891a0f Scott Ullrich
}
943
944 e99d11e3 Scott Ullrich
/*
945 c70c4e8a Colin Smith
 * http_post($server, $port, $url, $vars): does an http post to a web server
946
 *                                         posting the vars array.
947 e99d11e3 Scott Ullrich
 * written by nf@bigpond.net.au
948
 */
949
function http_post($server, $port, $url, $vars) {
950 0f66804f Scott Ullrich
    $user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)";
951
    $urlencoded = "";
952
    while (list($key,$value) = each($vars))
953 ef4550f8 Scott Ullrich
	$urlencoded.= urlencode($key) . "=" . urlencode($value) . "&";
954 0f66804f Scott Ullrich
    $urlencoded = substr($urlencoded,0,-1);
955 e99d11e3 Scott Ullrich
956 0f66804f Scott Ullrich
    $content_length = strlen($urlencoded);
957 e99d11e3 Scott Ullrich
958 0f66804f Scott Ullrich
    $headers = "POST $url HTTP/1.1
959 e99d11e3 Scott Ullrich
Accept: */*
960
Accept-Language: en-au
961
Content-Type: application/x-www-form-urlencoded
962
User-Agent: $user_agent
963
Host: $server
964
Connection: Keep-Alive
965
Cache-Control: no-cache
966
Content-Length: $content_length
967
968
";
969
970 0f66804f Scott Ullrich
    $fp = fsockopen($server, $port, $errno, $errstr);
971
    if (!$fp) {
972 ef4550f8 Scott Ullrich
	return false;
973 0f66804f Scott Ullrich
    }
974 e99d11e3 Scott Ullrich
975 0f66804f Scott Ullrich
    fputs($fp, $headers);
976
    fputs($fp, $urlencoded);
977 e99d11e3 Scott Ullrich
978 0f66804f Scott Ullrich
    $ret = "";
979
    while (!feof($fp))
980 ef4550f8 Scott Ullrich
	$ret.= fgets($fp, 1024);
981 e99d11e3 Scott Ullrich
982 0f66804f Scott Ullrich
    fclose($fp);
983 e99d11e3 Scott Ullrich
984 0f66804f Scott Ullrich
    return $ret;
985 e99d11e3 Scott Ullrich
986
}
987 f8891a0f Scott Ullrich
988 ee8f4a58 Scott Ullrich
/*
989
 *  php_check_syntax($code_tocheck, $errormessage): checks $code_to_check for errors
990
 */
991
if (!function_exists('php_check_syntax')){
992
   function php_check_syntax($code_to_check, &$errormessage){
993 c177d6ad Scott Ullrich
	return false;
994 7197df7d Scott Ullrich
        $fout = fopen("/tmp/codetocheck.php","w");
995
        $code = $_POST['content'];
996
        $code = str_replace("<?php", "", $code);
997
        $code = str_replace("?>", "", $code);
998
        fwrite($fout, "<?php\n\n");
999 669e1adb Bill Marquette
        fwrite($fout, $code_to_check);
1000 7197df7d Scott Ullrich
        fwrite($fout, "\n\n?>\n");
1001
        fclose($fout);
1002
        $command = "/usr/local/bin/php -l /tmp/codetocheck.php";
1003
        $output = exec_command($command);
1004
        if (stristr($output, "Errors parsing") == false) {
1005
            echo "false\n";
1006
            $errormessage = '';
1007
            return(false);
1008
        } else {
1009
            $errormessage = $output;
1010
            return(true);
1011
        }
1012 ee8f4a58 Scott Ullrich
    }
1013
}
1014
1015
/*
1016
 *  php_check_filename_syntax($filename, $errormessage): checks the file $filename for errors
1017
 */
1018 7197df7d Scott Ullrich
if (!function_exists('php_check_syntax')){
1019
   function php_check_syntax($code_to_check, &$errormessage){
1020 c177d6ad Scott Ullrich
	return false;
1021 7197df7d Scott Ullrich
        $command = "/usr/local/bin/php -l " . $code_to_check;
1022
        $output = exec_command($command);
1023
        if (stristr($output, "Errors parsing") == false) {
1024
            echo "false\n";
1025
            $errormessage = '';
1026
            return(false);
1027
        } else {
1028
            $errormessage = $output;
1029
            return(true);
1030
        }
1031
    }
1032 ee8f4a58 Scott Ullrich
}
1033
1034 bebb9d4d Bill Marquette
/*
1035 7eb2e498 Colin Smith
 * rmdir_recursive($path,$follow_links=false)
1036 6f2e9d7f Bill Marquette
 * Recursively remove a directory tree (rm -rf path)
1037
 * This is for directories _only_
1038
 */
1039
function rmdir_recursive($path,$follow_links=false) {
1040 7eb2e498 Colin Smith
	$to_do = glob($path);
1041 ed919b11 Colin Smith
	if(!is_array($to_do)) $to_do = array($to_do);
1042
	foreach($to_do as $workingdir) { // Handle wildcards by foreaching.
1043
		if(file_exists($workingdir)) {
1044
			if(is_dir($workingdir)) {
1045 0fdf1eaa Colin Smith
				$dir = opendir($workingdir);
1046
				while ($entry = readdir($dir)) {
1047
					if (is_file("$workingdir/$entry") || ((!$follow_links) && is_link("$workingdir/$entry")))
1048 ed919b11 Colin Smith
						unlink("$workingdir/$entry");
1049 0fdf1eaa Colin Smith
					elseif (is_dir("$workingdir/$entry") && $entry!='.' && $entry!='..')
1050 ed919b11 Colin Smith
						rmdir_recursive("$workingdir/$entry");
1051 0fdf1eaa Colin Smith
				}
1052
				closedir($dir);
1053
				rmdir($workingdir);
1054 ed919b11 Colin Smith
			} elseif (is_file($workingdir)) {
1055
				unlink($workingdir);
1056
			}
1057
               	}
1058 6f2e9d7f Bill Marquette
	}
1059 0a44a421 Colin Smith
	return;
1060 6f2e9d7f Bill Marquette
}
1061
1062 1682dc1e Bill Marquette
/*
1063 27f58699 Scott Ullrich
 *     get_memory()
1064
 *     returns an array listing the amount of
1065
 *     memory installed in the hardware
1066
 *     [0]real and [1]available
1067
 */
1068
function get_memory() {
1069 b84d1b32 Scott Ullrich
	if(file_exists("/var/log/dmesg.boot")) {
1070 6562edb8 Scott Ullrich
		$mem = `cat /var/log/dmesg.boot | grep memory`;
1071
		if (preg_match_all("/real memory  = .* \((.*) MB/", $mem, $matches))
1072
			$real = $matches[1];
1073
		if (preg_match_all("/avail memory = .* \((.*) MB/", $mem, $matches))
1074
			$avail = $matches[1];
1075
		return array($real[0],$avail[0]);
1076
	}
1077
	return array("64","64");
1078 27f58699 Scott Ullrich
}
1079
1080
1081
/*
1082
 *    safe_mkdir($path, $mode = 0755)
1083
 *    create directory if it doesn't already exist and isn't a file!
1084 1682dc1e Bill Marquette
 */
1085
function safe_mkdir($path, $mode=0755) {
1086 aaea2643 Scott Ullrich
	global $g;
1087 29f9dd52 Scott Ullrich
1088
	/* cdrom is ro. */
1089 7316a702 Colin Smith
	if($g['platform'] == "cdrom")
1090 3fb1a788 Scott Ullrich
		return false;
1091 27273870 Colin Smith
	
1092
	if (!is_file($path) && !is_dir($path))
1093
		return mkdir($path, $mode);
1094
	else
1095
		return false;
1096 1682dc1e Bill Marquette
}
1097
1098
/*
1099
 * make_dirs($path, $mode = 0755)
1100
 * create directory tree recursively (mkdir -p)
1101
 */
1102 3fb1a788 Scott Ullrich
function make_dirs($path, $mode = 0755) {
1103 cc5ae6bc Scott Ullrich
	/* is dir already created? */
1104
	if(is_dir($path)) return;
1105
	/* create directory in question */
1106 27273870 Colin Smith
	$to_create = explode("/", $path);
1107 29f9dd52 Scott Ullrich
	foreach($to_create as $tc) 
1108
	    if(!is_dir($tc))
1109 27273870 Colin Smith
		safe_mkdir($path, $mode);
1110 1682dc1e Bill Marquette
}
1111
1112 c7934653 Colin Smith
/*
1113
 * check_firmware_version(): Check whether the current firmware installed is the most recently released.
1114
 */
1115 bd21e2b7 Colin Smith
function check_firmware_version($tocheck = "all", $return_php = true) {
1116 335c7b2a Colin Smith
        global $g, $config;
1117 bb4f8f8a Colin Smith
	$xmlrpc_base_url = $g['xmlrpcbaseurl'];
1118
        $xmlrpc_path = $g['xmlrpcpath'];
1119 bd21e2b7 Colin Smith
	$rawparams = array("firmware" => array("version" => trim(file_get_contents('/etc/version'))),
1120 79020a5e Colin Smith
			"kernel"   => array("version" => trim(file_get_contents('/etc/version_kernel'))),
1121
			"base"     => array("version" => trim(file_get_contents('/etc/version_base'))),
1122
			"platform" => trim(file_get_contents('/etc/platform'))
1123
		);
1124 39a7c0c3 Bill Marquette
	if($tocheck == "all") {
1125 bd21e2b7 Colin Smith
		$params = $rawparams;
1126
	} else {
1127
		foreach($tocheck as $check) {
1128
			$params['check'] = $rawparams['check'];
1129
			$params['platform'] = $rawparams['platform'];
1130
		}
1131
	}
1132 335c7b2a Colin Smith
	if($config['system']['firmware']['branch']) {
1133
		$params['branch'] = $config['system']['firmware']['branch'];
1134 52621d32 Colin Smith
	}
1135 79020a5e Colin Smith
	$xmlparams = php_value_to_xmlrpc($params);
1136
        $msg = new XML_RPC_Message('pfsense.get_firmware_version', array($xmlparams));
1137 bb4f8f8a Colin Smith
        $cli = new XML_RPC_Client($xmlrpc_path, $xmlrpc_base_url);
1138 335c7b2a Colin Smith
	//$cli->setDebug(1);
1139 8ac0a4de Colin Smith
	$resp = $cli->send($msg, 10);
1140
	if(!$resp or $resp->faultCode()) {
1141
		$raw_versions = false;
1142
	} else {
1143 d1779cc4 Colin Smith
		$raw_versions = XML_RPC_decode($resp->value());
1144 8ac0a4de Colin Smith
		$raw_versions["current"] = $params;
1145
	}
1146 79020a5e Colin Smith
	return $raw_versions;
1147 c7934653 Colin Smith
}
1148
1149 12eb7056 Colin Smith
function get_disk_info() {
1150
        exec("df -h | grep -w '/' | awk '{ print $2, $3, $4, $5 }'", $diskout);
1151
        return explode(' ', $diskout[0]);
1152
        // $size, $used, $avail, $cap
1153 64092c34 Scott Ullrich
}
1154
1155 90fd355f Bill Marquette
/****f* pfsense-utils/display_top_tabs
1156
 * NAME
1157
 *   display_top_tabs - display tabs with rounded edges
1158
 * INPUTS
1159
 *   $text	- array of tabs
1160
 * RESULT
1161
 *   null
1162
 ******/
1163 a8726a3d Scott Ullrich
    function display_top_tabs($tab_array) {
1164
	    echo "<table cellpadding='0' cellspacing='0'>\n";
1165
	    echo " <tr height='1'>\n";
1166
	    $tabscounter = 0;
1167
	    foreach ($tab_array as $ta) {
1168
		    if($ta[1] == true) {
1169 6948fa96 Bill Marquette
			    echo "  <td bgcolor='#EEEEEE' onClick=\"document.location='{$ta[2]}'\"><div id='tabactive'></div></td>\n";
1170 a8726a3d Scott Ullrich
		    } else {
1171 6948fa96 Bill Marquette
			    echo "  <td bgcolor='#777777' onClick=\"document.location='{$ta[2]}'\"><div id='tabdeactive{$tabscounter}'></div></td>\n";
1172 a8726a3d Scott Ullrich
		    }
1173
		    $tabscounter++;
1174
	    }
1175 0366b748 Scott Ullrich
	    echo "</tr>\n<tr>\n";
1176 a8726a3d Scott Ullrich
	    foreach ($tab_array as $ta) {
1177
		    if($ta[1] == true) {
1178 6948fa96 Bill Marquette
			    echo "  <td bgcolor='#EEEEEE' onClick=\"document.location='{$ta[2]}'\"><B>&nbsp;&nbsp;&nbsp;{$ta[0]}";
1179 63586b79 Scott Ullrich
			    echo "&nbsp;&nbsp;&nbsp;";
1180 2f4809ea Bill Marquette
			    echo "<font size='-12'>&nbsp;</td>\n";
1181 a8726a3d Scott Ullrich
		    } else {
1182 6948fa96 Bill Marquette
			    echo "  <td bgcolor='#777777' onClick=\"document.location='{$ta[2]}'\"><B>&nbsp;&nbsp;&nbsp;<a href='{$ta[2]}'>";
1183 63586b79 Scott Ullrich
			    echo "<font color='white'>{$ta[0]}</a>&nbsp;&nbsp;&nbsp;";
1184 2f4809ea Bill Marquette
			    echo "<font size='-12'>&nbsp;</td>\n";
1185 a8726a3d Scott Ullrich
		    }
1186
	    }
1187 2f4809ea Bill Marquette
	    echo "</tr>\n<tr height='5px'>\n";
1188
	    foreach ($tab_array as $ta) {
1189
		    if($ta[1] == true) {
1190
			    echo "  <td bgcolor='#EEEEEE' onClick=\"document.location='{$ta[2]}'\"></td>\n";
1191
		    } else {
1192
			    echo "  <td bgcolor='#777777' onClick=\"document.location='{$ta[2]}'\"></td>\n";
1193
		    }
1194
		    $tabscounter++;
1195
	    }
1196 a8726a3d Scott Ullrich
	    echo " </tr>\n";
1197
	    echo "</table>\n";
1198
	    
1199
	    echo "<script type=\"text/javascript\">";
1200
	    echo "NiftyCheck();\n";
1201 0366b748 Scott Ullrich
	    echo "Rounded(\"div#tabactive\",\"top\",\"#FFF\",\"#EEEEEE\",\"smooth\");\n";
1202 a8726a3d Scott Ullrich
	    for($x=0; $x<$tabscounter; $x++) 
1203 0366b748 Scott Ullrich
		    echo "Rounded(\"div#tabdeactive{$x}\",\"top\",\"#FFF\",\"#777777\",\"smooth\");\n";
1204 a8726a3d Scott Ullrich
	    echo "</script>";
1205
    }
1206 305eae3c Bill Marquette
1207
1208 90fd355f Bill Marquette
/****f* pfsense-utils/display_topbar
1209
 * NAME
1210
 *   display_topbar - top a table off with rounded edges
1211
 * INPUTS
1212
 *   $text	- (optional) Text to include in bar
1213
 * RESULT
1214
 *   null
1215
 ******/
1216 411528e9 Scott Ullrich
function display_topbar($text = "", $bg_color="#990000", $replace_color="#FFFFFF", $rounding_style="smooth") {	    
1217 305eae3c Bill Marquette
	echo "     <table width='100%' cellpadding='0' cellspacing='0'>\n";
1218
	echo "       <tr height='1'>\n";
1219 411528e9 Scott Ullrich
	echo "         <td width='100%' valign='top' color='{$bg_color}' bgcolor='{$bg_color}'>";
1220
	echo "		<div id='topbar'></div></td>\n";
1221 305eae3c Bill Marquette
	echo "       </tr>\n";
1222
	echo "       <tr height='1'>\n";
1223
	if ($text != "")
1224
		echo "         <td height='1' class='listtopic'>{$text}</td>\n";
1225
	else
1226
		echo "         <td height='1' class='listtopic'></td>\n";
1227
	echo "       </tr>\n";
1228
	echo "     </table>";
1229
	echo "<script type=\"text/javascript\">";
1230
	echo "NiftyCheck();\n";
1231 411528e9 Scott Ullrich
	echo "Rounded(\"div#topbar\",\"top\",\"{$replace_color}\",\"{$bg_color}\",\"{$rounding_style}\");\n";
1232 305eae3c Bill Marquette
	echo "</script>";
1233
}
1234 730768f7 Colin Smith
1235 c615128d Scott Ullrich
/****f* pfsense-utils/generate_random_mac_address
1236 94e8082f Scott Ullrich
 * NAME
1237
 *   generate_random_mac - generates a random mac address
1238
 * INPUTS
1239
 *   none
1240
 * RESULT
1241
 *   $mac - a random mac address
1242
 ******/
1243 c615128d Scott Ullrich
function generate_random_mac_address() {
1244 e8dd289e Scott Ullrich
	$mac = "00:a0:8e";
1245
	for($x=0; $x<3; $x++) 
1246 a57a45cb Colin Smith
	    $mac .= ":" . dechex(rand(16, 255));
1247 ac1bb69d Scott Ullrich
1248 730768f7 Colin Smith
	return $mac;
1249
}
1250 94e8082f Scott Ullrich
1251 d6fbd4ca Bill Marquette
/****f* pfsense-utils/strncpy
1252
 * NAME
1253
 *   strncpy - copy strings
1254
 * INPUTS
1255
 *   &$dst, $src, $length
1256
 * RESULT
1257
 *   none
1258
 ******/
1259
function strncpy(&$dst, $src, $length) {
1260
	if (strlen($src) > $length) {
1261
		$dst = substr($src, 0, $length);
1262
	} else {
1263
		$dst = $src;
1264
	}
1265
}
1266
1267 39a85258 Scott Ullrich
/****f* pfsense-utils/reload_interfaces_sync
1268 182c30de Scott Ullrich
 * NAME
1269
 *   reload_interfaces - reload all interfaces
1270
 * INPUTS
1271
 *   none
1272
 * RESULT
1273
 *   none
1274
 ******/
1275 39a85258 Scott Ullrich
function reload_interfaces_sync() {
1276 4f1252d5 Scott Ullrich
	global $config, $g;
1277
	
1278
	if(file_exists("{$g['tmp_path']}/config.cache"))
1279
		unlink("{$g['tmp_path']}/config.cache");
1280
	
1281
	/* parse config.xml again */
1282 12886b41 Scott Ullrich
	$config = parse_config(true);
1283 a5489081 Scott Ullrich
1284 e4b6977d Scott Ullrich
	/* delete all old interface information */
1285
	$iflist = split(" ", str_replace("\n", "", `/sbin/ifconfig -l`));
1286 a5489081 Scott Ullrich
	foreach ($iflist as $ifent => $ifname) {
1287
		$ifname_real = convert_friendly_interface_to_real_interface_name($ifname);
1288
		mwexec("/sbin/ifconfig {$ifname_real} down");
1289 01ea39c8 Scott Ullrich
		mwexec("/sbin/ifconfig {$ifname_real} delete");
1290 a5489081 Scott Ullrich
	}
1291
1292 898f9144 Scott Ullrich
	/* set up VLAN virtual interfaces */
1293
	interfaces_vlan_configure();
1294
1295 182c30de Scott Ullrich
	/* set up LAN interface */
1296
	interfaces_lan_configure();
1297
1298
	/* set up WAN interface */
1299
	interfaces_wan_configure();
1300
1301
	/* set up Optional interfaces */
1302
	interfaces_optional_configure();
1303
        
1304
	/* set up static routes */
1305
	system_routing_configure();
1306 835c9f4a Scott Ullrich
	
1307 182c30de Scott Ullrich
	/* enable routing */
1308
	system_routing_enable();
1309 d7be682d Scott Ullrich
	
1310
	/* setup captive portal if needed */
1311 3674284c Scott Ullrich
	captiveportal_configure();
1312
	
1313
	/* bring up carp interfaces */
1314
	interfaces_carp_configure();
1315
	
1316
	/* bring up carp interfaces*/
1317
	interfaces_carp_bring_up_final();	
1318 182c30de Scott Ullrich
}
1319
1320
/****f* pfsense-utils/reload_all
1321
 * NAME
1322 39a85258 Scott Ullrich
 *   reload_all - triggers a reload of all settings
1323 182c30de Scott Ullrich
 *   * INPUTS
1324
 *   none
1325
 * RESULT
1326
 *   none
1327
 ******/
1328
function reload_all() {
1329 39a85258 Scott Ullrich
	touch("/tmp/reload_all");
1330
}
1331
1332
/****f* pfsense-utils/reload_interfaces
1333
 * NAME
1334
 *   reload_interfaces - triggers a reload of all interfaces
1335
 * INPUTS
1336
 *   none
1337
 * RESULT
1338
 *   none
1339
 ******/
1340
function reload_interfaces() {
1341
	touch("/tmp/reload_interfaces");
1342
}
1343
1344 7872051e Scott Ullrich
/****f* pfsense-utils/sync_webgui_passwords
1345
 * NAME
1346
 *   sync_webgui_passwords - syncs webgui and ssh passwords
1347
 * INPUTS
1348
 *   none
1349
 * RESULT
1350
 *   none
1351
 ******/
1352
function sync_webgui_passwords() {
1353 f7594142 Scott Ullrich
	global $config, $g;
1354 12f23f46 Scott Ullrich
	conf_mount_rw();
1355 f7594142 Scott Ullrich
	$fd = fopen("{$g['varrun_path']}/htpasswd", "w");
1356
	if (!$fd) {
1357
		printf("Error: cannot open htpasswd in system_password_configure().\n");
1358
		return 1;
1359
	}
1360
	/* set admin account */
1361 9604ac1f Scott Ullrich
	$username = $config['system']['username'];
1362 5bfc9fdf Scott Ullrich
	
1363 f7594142 Scott Ullrich
	/* set defined user account */
1364
	if($username <> "admin") {
1365
		$username = $config['system']['username'];
1366
		fwrite($fd, $username . ":" . $config['system']['password'] . "\n");
1367 5bfc9fdf Scott Ullrich
	} else {
1368
		fwrite($fd, $username . ":" . $config['system']['password'] . "\n");	
1369
	}	
1370 f7594142 Scott Ullrich
	fclose($fd);
1371
	chmod("{$g['varrun_path']}/htpasswd", 0600);	
1372 caa72e06 Scott Ullrich
	$crypted_pw = $config['system']['password'];
1373 71bee409 Scott Ullrich
	mwexec("/usr/sbin/pwd_mkdb -d /etc -p /etc/master.passwd");
1374
	mwexec("/usr/sbin/pwd_mkdb -p /etc/master.passwd");
1375 f53c7cd0 Scott Ullrich
	/* sync root */
1376
	$fd = popen("/usr/sbin/pw usermod -n root -H 0", "w");
1377 72183413 Scott Ullrich
	fwrite($fd, $crypted_pw);
1378
	pclose($fd);
1379 ac21b329 Scott Ullrich
	mwexec("/usr/sbin/pw usermod -n root -s /bin/sh");
1380 72183413 Scott Ullrich
	/* sync admin */
1381
	$fd = popen("/usr/sbin/pw usermod -n admin -H 0", "w");
1382
	fwrite($fd, $crypted_pw);
1383 2c24977e Scott Ullrich
	pclose($fd);
1384 b3a88dd6 Scott Ullrich
	mwexec("/usr/sbin/pw usermod -n admin -s /etc/rc.initial");
1385 71bee409 Scott Ullrich
	mwexec("/usr/sbin/pwd_mkdb -d /etc -p /etc/master.passwd");
1386
	mwexec("/usr/sbin/pwd_mkdb -p /etc/master.passwd");
1387 12f23f46 Scott Ullrich
	conf_mount_ro();
1388 7872051e Scott Ullrich
}
1389
1390 39a85258 Scott Ullrich
/****f* pfsense-utils/reload_all_sync
1391
 * NAME
1392
 *   reload_all - reload all settings
1393
 *   * INPUTS
1394
 *   none
1395
 * RESULT
1396
 *   none
1397
 ******/
1398
function reload_all_sync() {
1399 4f1252d5 Scott Ullrich
	global $config, $g;
1400
	
1401
	if(file_exists("{$g['tmp_path']}/config.cache"))
1402
		unlink("{$g['tmp_path']}/config.cache");
1403
	
1404
	/* parse config.xml again */
1405 12886b41 Scott Ullrich
	$config = parse_config(true);
1406
1407 182c30de Scott Ullrich
	/* set up our timezone */
1408
	system_timezone_configure();
1409
1410
	/* set up our hostname */
1411
	system_hostname_configure();
1412
1413
	/* make hosts file */
1414
	system_hosts_generate();
1415
1416
	/* generate resolv.conf */
1417
	system_resolvconf_generate();
1418
1419 e4b6977d Scott Ullrich
	/* delete all old interface information */
1420
	$iflist = split(" ", str_replace("\n", "", `/sbin/ifconfig -l`));
1421 a5489081 Scott Ullrich
	foreach ($iflist as $ifent => $ifname) {
1422
		$ifname_real = convert_friendly_interface_to_real_interface_name($ifname);
1423
		mwexec("/sbin/ifconfig {$ifname_real} down");
1424 1120ff57 Scott Ullrich
		mwexec("/sbin/ifconfig {$ifname_real} delete");
1425 a5489081 Scott Ullrich
	}
1426
1427 898f9144 Scott Ullrich
	/* set up VLAN virtual interfaces */
1428
	interfaces_vlan_configure();
1429
1430 182c30de Scott Ullrich
	/* set up LAN interface */
1431
	interfaces_lan_configure();
1432
1433
	/* set up WAN interface */
1434
	interfaces_wan_configure();
1435
1436
	/* set up Optional interfaces */
1437
	interfaces_optional_configure();
1438
        
1439
	/* bring up carp interfaces */
1440 835c9f4a Scott Ullrich
	interfaces_carp_configure();
1441 182c30de Scott Ullrich
	
1442
	/* set up static routes */
1443
	system_routing_configure();
1444
1445
	/* enable routing */
1446
	system_routing_enable();
1447
	
1448
	/* ensure passwords are sync'd */
1449
	system_password_configure();
1450
1451
	/* start dnsmasq service */
1452
	services_dnsmasq_configure();
1453
1454
	/* start dyndns service */
1455
	services_dyndns_configure();
1456
1457
	/* start DHCP service */
1458
	services_dhcpd_configure();
1459
1460
	/* start the NTP client */
1461
	system_ntp_configure();
1462
1463
	/* start ftp proxy helpers if they are enabled */
1464
	system_start_ftp_helpers();
1465 375f907e Scott Ullrich
	
1466 a64f14a2 Scott Ullrich
	/* start the captive portal */
1467
	captiveportal_configure();
1468 721a2c10 Scott Ullrich
1469
        /* reload the filter */
1470 c7c7be3f Scott Ullrich
	filter_configure_sync();
1471 933e1032 Scott Ullrich
1472
	/* bring up carp interfaces*/
1473
	interfaces_carp_bring_up_final();
1474
1475 375f907e Scott Ullrich
	/* sync pw database */
1476
	conf_mount_rw();
1477
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
1478
	conf_mount_ro();
1479 ef4a2962 Scott Ullrich
1480
	/* restart sshd */
1481
	touch("/tmp/start_sshd");
1482 375f907e Scott Ullrich
	
1483 182c30de Scott Ullrich
}
1484
1485 71bee409 Scott Ullrich
?>