Project

General

Profile

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