Project

General

Profile

Download (34.6 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/****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
 *
23
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
24
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
25
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26
 * AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
27
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31
 * RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32
 * POSSIBILITY OF SUCH DAMAGE.
33
 *
34
 */
35

    
36
function get_tmp_file() {
37
	return "/tmp/tmp-" . time();
38
}
39

    
40
/****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
 	
60
/****f* pfsense-utils/log_error
61
* NAME
62
*   log_error  - Sends a string to syslog.
63
* INPUTS
64
*   $error     - string containing the syslog message.
65
* RESULT
66
*   null
67
******/
68
function log_error($error) {
69
    $page = $_SERVER['PHP_SELF'];
70
    syslog(LOG_WARNING, "$page: $error");
71
    return;
72
}
73

    
74
/****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
    $mac = exec("ifconfig {$interface} | awk '/ether/ {print $2}'");
84
    return trim($mac);
85
}
86

    
87
/****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
 *   $dir_array - array containing the directory's contents. This array will be empty if the path specified is invalid.
94
 ******/
95
function return_dir_as_array($dir) {
96
    $dir_array = array();
97
    if (is_dir($dir)) {
98
	if ($dh = opendir($dir)) {
99
	    while (($file = readdir($dh)) !== false) {
100
		$canadd = 0;
101
		if($file == ".") $canadd = 1;
102
		if($file == "..") $canadd = 1;
103
		if($canadd == 0)
104
		    array_push($dir_array, $file);
105
	    }
106
	    closedir($dh);
107
	}
108
    }
109
    return $dir_array;
110
}
111

    
112
/****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
function enable_hardware_offloading($interface) {
123
    global $g;
124
    if($g['booting']) {
125
	/* translate wan, lan, opt -> real interface if needed */
126
	$int = filter_translate_type_to_real_interface($interface);
127
	if($int <> "") $interface = $int;
128
	$options = strtolower(`/sbin/ifconfig {$interface} | grep options`);
129
	$supported_ints = array('fxp');
130
	foreach($supported_ints as $int) {
131
		if(stristr($interface,$int) != false) {
132
			mwexec("/sbin/ifconfig {$interface} link0");
133
		}
134
	}
135
	if(stristr($options, "txcsum") == true)
136
	    mwexec("/sbin/ifconfig {$interface} txcsum 2>/dev/null");
137
	if(stristr($options, "rxcsum") == true)    
138
	    mwexec("/sbin/ifconfig {$interface} rxcsum 2>/dev/null");    
139
	if(stristr($options, "polling") == true)
140
	    mwexec("/sbin/ifconfig {$interface} polling 2>/dev/null");
141
    }
142
    return;
143
}
144

    
145
/****f* pfsense-utils/setup_microcode
146
 * NAME
147
 *   enumerates all interfaces and calls enable_hardware_offloading which
148
 *   enables a NIC's supported hardware features.
149
 * INPUTS
150
 *   
151
 * RESULT
152
 *   null
153
 * NOTES
154
 *   This function only supports the fxp driver's loadable microcode.
155
 ******/
156
function setup_microcode() {
157
   global $config;
158
    $ifdescrs = array('wan', 'lan');
159
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) {
160
	$ifdescrs['opt' . $j] = "opt" . $j;
161
    }
162
    foreach($ifdescrs as $if)
163
	enable_hardware_offloading($if);
164
}
165

    
166
/****f* pfsense-utils/return_filename_as_array
167
 * NAME
168
 *   return_filename_as_array - Return a file's contents as an array.
169
 * INPUTS
170
 *   $filename	- string containing the path to the desired file.
171
 *   $strip	- array of characters to strip - default is '#'.
172
 * RESULT
173
 *   $file	- array containing the file's contents.
174
 * NOTES
175
 *   This function strips lines starting with '#' and leading/trailing whitespace by default.
176
 ******/
177
function return_filename_as_array($filename, $strip = array('#')) {
178
    if(file_exists($filename)) $file = file($filename);
179
    if(is_array($file)) {
180
	foreach($file as $line) $line = trim($line);
181
        foreach($strip as $tostrip) $file = preg_grep("/^{$tostrip}/", $file, PREG_GREP_INVERT);
182
    }
183
    return $file;
184
}
185

    
186
/****f* pfsense-utils/file_put_contents
187
 * NAME
188
 *   file_put_contents - Wrapper for file_put_contents if it doesn't exist
189
 * RESULT
190
 *   none
191
 ******/
192
if(!function_exists("file_put_contents")) {
193
    function file_put_contents($filename, $data) {
194
	$fd = fopen($filename,"w");
195
	fwrite($fd, $data);
196
	fclose($fd);
197
    }
198
}
199

    
200
/****f* pfsense-utils/get_carp_status
201
 * NAME
202
 *   get_carp_status - Return whether CARP is enabled or disabled.
203
 * RESULT
204
 *   boolean	- true if CARP is enabled, false if otherwise.
205
 ******/
206
function get_carp_status() {
207
    /* grab the current status of carp */
208
    $status = `/sbin/sysctl net.inet.carp.allow | cut -d" " -f2`;
209
    if(intval($status) == "0") return false;
210
    return true;
211
}
212

    
213
/****f* pfsense-utils/is_carp_defined
214
 * NAME
215
 *   is_carp_defined - Return whether CARP is detected in the kernel.
216
 * RESULT
217
 *   boolean	- true if CARP is detected, false otherwise.
218
 ******/
219
function is_carp_defined() {
220
    /* is carp compiled into the kernel and userland? */
221
    $command = "/sbin/sysctl -a | grep carp";
222
    $fd = popen($command . " 2>&1 ", "r");
223
    if(!$fd) {
224
	log_error("Warning, could not execute command {$command}");
225
	return 0;
226
    }
227
    while(!feof($fd)) {
228
	$tmp .= fread($fd,49);
229
    }
230
    fclose($fd);
231

    
232
    if($tmp == "")
233
	return false;
234
    else
235
	return true;
236
}
237

    
238
/****f* pfsense-utils/find_number_of_created_carp_interfaces
239
 * NAME
240
 *   find_number_of_created_carp_interfaces - Return the number of CARP interfaces.
241
 * RESULT
242
 *   $tmp	- Number of currently created CARP interfaces.
243
 ******/
244
function find_number_of_created_carp_interfaces() {
245
    $command = "/sbin/ifconfig | /usr/bin/grep \"carp*:\" | /usr/bin/wc -l";
246
    $fd = popen($command . " 2>&1 ", "r");
247
    if(!$fd) {
248
	log_error("Warning, could not execute command {$command}");
249
	return 0;
250
    }
251
    while(!feof($fd)) {
252
	$tmp .= fread($fd,49);
253
    }
254
    fclose($fd);
255
    $tmp = intval($tmp);
256
    return $tmp;
257
}
258

    
259
/****f* pfsense-utils/link_ip_to_carp_interface
260
 * NAME
261
 *   link_ip_to_carp_interface - Find where a CARP interface links to.
262
 * INPUTS
263
 *   $ip
264
 * RESULT
265
 *   $carp_ints
266
 ******/
267
function link_ip_to_carp_interface($ip) {
268
	global $config;
269
	if($ip == "") return;
270

    
271
	$ifdescrs = array('wan', 'lan');
272
	for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) {
273
		$ifdescrs['opt' . $j] = "opt" . $j;
274
	}
275

    
276
	$ft = split("\.", $ip);
277
	$ft_ip = $ft[0] . "." . $ft[1] . "." . $ft[2] . ".";
278

    
279
	$carp_ints = "";
280
	$num_carp_ints = find_number_of_created_carp_interfaces();
281
	foreach ($ifdescrs as $ifdescr => $ifname) {
282
		for($x=0; $x<$num_carp_ints; $x++) {
283
			$carp_int = "carp{$x}";
284
			$carp_ip = find_interface_ip($carp_int);
285
			$carp_ft = split("\.", $carp_ip);
286
			$carp_ft_ip = $carp_ft[0] . "." . $carp_ft[1] . "." . $carp_ft[2] . ".";
287
			$result = does_interface_exist($carp_int);
288
			if($result <> true) break;
289
			if($ft_ip == $carp_ft_ip)
290
			if(stristr($carp_ints,$carp_int) == false)
291
			$carp_ints .= " " . $carp_int;
292
		}
293
	}
294
	return $carp_ints;
295
}
296

    
297
/****f* pfsense-utils/exec_command
298
 * NAME
299
 *   exec_command - Execute a command and return a string of the result.
300
 * INPUTS
301
 *   $command	- String of the command to be executed.
302
 * RESULT
303
 *   String containing the command's result.
304
 * NOTES
305
 *   This function returns the command's stdout and stderr.
306
 ******/
307
function exec_command($command) {
308
    $output = array();
309
    exec($command . ' 2>&1 ', $output);
310
    return(implode("\n", $output));
311
}
312

    
313
/*
314
 * does_interface_exist($interface): return true or false if a interface is detected.
315
 */
316
function does_interface_exist($interface) {
317
    $ints = exec_command("/sbin/ifconfig -l");
318
    if(stristr($ints, $interface) !== false)
319
	return true;
320
    else
321
	return false;
322
}
323

    
324
/*
325
 * convert_ip_to_network_format($ip, $subnet): converts an ip address to network form
326
 */
327
function convert_ip_to_network_format($ip, $subnet) {
328
    $ipsplit = split('[.]', $ip);
329
    $string = $ipsplit[0] . "." . $ipsplit[1] . "." . $ipsplit[2] . ".0/" . $subnet;
330
    return $string;
331
}
332

    
333
/*
334
 * find_interface_ip($interface): return the interface ip (first found)
335
 */
336
function find_interface_ip($interface) {
337
    if(does_interface_exist($interface) == false) return;
338
    $ip = exec_command("/sbin/ifconfig {$interface} | /usr/bin/grep -w \"inet\" | /usr/bin/cut -d\" \" -f 2");
339
    $ip = str_replace("\n","",$ip);
340
    return $ip;
341
}
342

    
343
function guess_interface_from_ip($ipaddress) {
344
    $ints = `/sbin/ifconfig -l`;
345
    $ints_split = split(" ", $ints);
346
    $ip_subnet_split = split("\.", $ipaddress);
347
    $ip_subnet = $ip_subnet_split[0] . "." . $ip_subnet_split[1] . "." . $ip_subnet_split[2] . ".";
348
    foreach($ints_split as $int) {
349
        $ip = find_interface_ip($int);
350
        $ip_split = split("\.", $ip);
351
        $ip_tocheck = $ip_split[0] . "." . $ip_split[1] . "." . $ip_split[2] . ".";
352
        if(stristr($ip_tocheck, $ip_subnet) != false) return $int;
353
    }
354
}
355

    
356
function filter_opt_interface_to_real($opt) {
357
    global $config;
358
    return $config['interfaces'][$opt]['if'];
359
}
360

    
361
function filter_get_opt_interface_descr($opt) {
362
    global $config;
363
    return $config['interfaces'][$opt]['descr'];
364
}
365

    
366
function get_friendly_interface_list_as_array() {
367
    global $config;
368
    $ints = array();
369
    $ifdescrs = array('wan', 'lan');
370
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) {
371
		$ifdescrs['opt' . $j] = "opt" . $j;
372
    }
373
    $ifdescrs = get_interface_list();
374
    foreach ($ifdescrs as $ifdescr => $ifname) {
375
		array_push($ints,$ifdescr);
376
    }
377
    return $ints;
378
}
379

    
380
/*
381
 * find_ip_interface($ip): return the interface where an ip is defined
382
 */
383
function find_ip_interface($ip) {
384
    global $config;
385
    $ifdescrs = array('wan', 'lan');
386
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) {
387
	$ifdescrs['opt' . $j] = "opt" . $j;
388
    }
389
    foreach ($ifdescrs as $ifdescr => $ifname) {
390
	$int = filter_translate_type_to_real_interface($ifname);
391
	$ifconfig = exec_command("/sbin/ifconfig {$int}");
392
	if(stristr($ifconfig,$ip) <> false)
393
	    return $int;
394
    }
395
    return false;
396
}
397

    
398
/*
399
 *  filter_translate_type_to_real_interface($interface): returns the real interface name
400
 *                                                       for a friendly interface.  ie: wan
401
 */
402
function filter_translate_type_to_real_interface($interface) {
403
    global $config;
404
    return $config['interfaces'][$interface]['if'];
405
}
406

    
407
/*
408
 * get_carp_interface_status($carpinterface): returns the status of a carp ip
409
 */
410
function get_carp_interface_status($carpinterface) {
411
	/* basically cache the contents of ifconfig statement
412
	to speed up this routine */
413
	global $carp_query;
414
	if($carp_query == "")
415
	$carp_query = split("\n", `/sbin/ifconfig | /usr/bin/grep carp`);
416
	$found_interface = 0;
417
	foreach($carp_query as $int) {
418
		if($found_interface == 1) {
419
			if(stristr($int, "MASTER") == true) return "MASTER";
420
			if(stristr($int, "BACKUP") == true) return "BACKUP";
421
			if(stristr($int, "INIT") == true) return "INIT";
422
			return false;
423
		}
424
		if(stristr($int, $carpinterface) == true)
425
		$found_interface=1;
426
	}
427
	return;
428
}
429

    
430
/*
431
 * get_pfsync_interface_status($pfsyncinterface): returns the status of a pfsync
432
 */
433
function get_pfsync_interface_status($pfsyncinterface) {
434
    $result = does_interface_exist($pfsyncinterface);
435
    if($result <> true) return;
436
    $status = exec_command("/sbin/ifconfig {$pfsyncinterface} | /usr/bin/grep \"pfsync:\" | /usr/bin/cut -d\" \" -f5");
437
    return $status;
438
}
439

    
440
/*
441
 * find_carp_interface($ip): return the carp interface where an ip is defined
442
 */
443
function find_carp_interface($ip) {
444
    global $find_carp_ifconfig;
445
    if($find_carp_ifconfig == "") {
446
	$find_carp_ifconfig = array();
447
	$num_carp_ints = find_number_of_created_carp_interfaces();
448
	for($x=0; $x<$num_carp_ints; $x++) {
449
	    $find_carp_ifconfig[$x] = exec_command("/sbin/ifconfig carp{$x}");
450
	}
451
    }
452
    $carps = 0;
453
    foreach($find_carp_ifconfig as $fci) {
454
	if(stristr($fci, $ip) == true)
455
	    return "carp{$carps}";
456
	$carps++;
457
    }
458
}
459

    
460
/*
461
 * find_number_of_created_bridges(): returns the number of currently created bridges
462
 */
463
function find_number_of_created_bridges() {
464
    return `/sbin/ifconfig | grep \"bridge[0-999]\:" | wc -l`;
465
}
466

    
467
/*
468
 * add_rule_to_anchor($anchor, $rule): adds the specified rule to an anchor
469
 */
470
function add_rule_to_anchor($anchor, $rule, $label) {
471
    mwexec("echo " . $rule . " | /sbin/pfctl -a " . $anchor . ":" . $label . " -f -");
472
}
473

    
474
/*
475
 * remove_text_from_file
476
 * remove $text from file $file
477
 */
478
function remove_text_from_file($file, $text) {
479
    global $fd_log;
480
    fwrite($fd_log, "Adding needed text items:\n");
481
    $filecontents = exec_command_and_return_text("cat " . $file);
482
    $textTMP = str_replace($text, "", $filecontents);
483
    $text .= $textTMP;
484
    fwrite($fd_log, $text . "\n");
485
    $fd = fopen($file, "w");
486
    fwrite($fd, $text);
487
    fclose($fd);
488
}
489

    
490
/*
491
 * add_text_to_file($file, $text): adds $text to $file.
492
 * replaces the text if it already exists.
493
 */
494
function add_text_to_file($file, $text) {
495
	if(file_exists($file) and is_writable($file)) {
496
		$filecontents = file($file);
497
		$filecontents[] = $text;
498
		$tmpfile = get_tmp_file();
499
		$fout = fopen($tmpfile, "w");
500
		foreach($filecontents as $line) {
501
			fwrite($fout, rtrim($line) . "\n");
502
		}
503
		fclose($fout);
504
		rename($tmpfile, $file);
505
		return true;
506
	} else {
507
		return false;
508
	}
509
}
510

    
511
/*
512
 *   after_sync_bump_adv_skew(): create skew values by 1S
513
 */
514
function after_sync_bump_adv_skew() {
515
	global $config, $g;
516
	$processed_skew = 1;
517
	$a_vip = &$config['virtualip']['vip'];
518
	foreach ($a_vip as $vipent) {
519
		if($vipent['advskew'] <> "") {
520
			$processed_skew = 1;
521
			$vipent['advskew'] = $vipent['advskew']+1;
522
		}
523
	}
524
	if($processed_skew == 1)
525
		write_config("After synch increase advertising skew");
526
}
527

    
528
/*
529
 * get_filename_from_url($url): converts a url to its filename.
530
 */
531
function get_filename_from_url($url) {
532
	return basename($url);
533
}
534

    
535
/*
536
 *   update_output_window: update bottom textarea dynamically.
537
 */
538
function update_output_window($text) {
539
    $log = ereg_replace("\n", "\\n", $text);
540
    echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = \"" . $log . "\";</script>";
541
}
542

    
543
/*
544
 *   get_dir: return an array of $dir
545
 */
546
function get_dir($dir) {
547
    $dir_array = array();
548
    $d = dir($dir);
549
    while (false !== ($entry = $d->read())) {
550
	array_push($dir_array, $entry);
551
    }
552
    $d->close();
553
    return $dir_array;
554
}
555

    
556
/*
557
 *   update_output_window: update top textarea dynamically.
558
 */
559
function update_status($status) {
560
    echo "\n<script language=\"JavaScript\">document.forms[0].status.value=\"" . $status . "\";</script>";
561
}
562

    
563
/*
564
 *   exec_command_and_return_text_array: execute command and return output
565
 */
566
function exec_command_and_return_text_array($command) {
567
	$fd = popen($command . " 2>&1 ", "r");
568
	while(!feof($fd)) {
569
		$tmp .= fread($fd,49);
570
	}
571
	fclose($fd);
572
	$temp_array = split("\n", $tmp);
573
	return $temp_array;
574
}
575

    
576
/*
577
 *   exec_command_and_return_text: execute command and return output
578
 */
579
function exec_command_and_return_text($command) {
580
    return exec_command($command);
581
}
582

    
583
/*
584
 *   exec_command_and_return_text: execute command and update output window dynamically
585
 */
586
function execute_command_return_output($command) {
587
    global $fd_log;
588
    $fd = popen($command . " 2>&1 ", "r");
589
    echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = \"\";</script>";
590
    $counter = 0;
591
    $counter2 = 0;
592
    while(!feof($fd)) {
593
	$tmp = fread($fd, 50);
594
	$tmp1 = ereg_replace("\n","\\n", $tmp);
595
	$text = ereg_replace("\"","'", $tmp1);
596
	if($lasttext == "..") {
597
	    $text = "";
598
	    $lasttext = "";
599
	    $counter=$counter-2;
600
	} else {
601
	    $lasttext .= $text;
602
	}
603
	if($counter > 51) {
604
	    $counter = 0;
605
	    $extrabreak = "\\n";
606
	} else {
607
	    $extrabreak = "";
608
	    $counter++;
609
	}
610
	if($counter2 > 600) {
611
	    echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = \"\";</script>";
612
	    $counter2 = 0;
613
	} else
614
	    $counter2++;
615
	echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = this.document.forms[0].output.value + \"" . $text . $extrabreak .  "\"; f('output'); </script>";
616
    }
617
    fclose($fd);
618
}
619

    
620
/*
621
 * convert_friendly_interface_to_real_interface_name($interface): convert WAN to FXP0
622
 */
623
function convert_friendly_interface_to_real_interface_name($interface) {
624
    global $config;
625
    $lc_interface = strtolower($interface);
626
    if($lc_interface == "lan") return $config['interfaces']['lan']['if'];
627
    if($lc_interface == "wan") return $config['interfaces']['wan']['if'];
628
    $ifdescrs = array();
629
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++)
630
	$ifdescrs['opt' . $j] = "opt" . $j;
631
    foreach ($ifdescrs as $ifdescr => $ifname) {
632
	if(strtolower($ifname) == $lc_interface)
633
	    return $config['interfaces'][$ifname]['if'];
634
	if(strtolower($config['interfaces'][$ifname]['descr']) == $lc_interface)
635
	    return $config['interfaces'][$ifname]['if'];
636
    }
637
    return $interface;
638
}
639

    
640
/*
641
 * convert_real_interface_to_friendly_interface_name($interface): convert fxp0 -> wan, etc.
642
 */
643
function convert_real_interface_to_friendly_interface_name($interface) {
644
    global $config;
645
    $ifdescrs = array('wan', 'lan');
646
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++)
647
	$ifdescrs['opt' . $j] = "opt" . $j;
648
    foreach ($ifdescrs as $ifdescr => $ifname) {
649
	$int = filter_translate_type_to_real_interface($ifname);
650
	if($ifname == $interface) return $ifname;
651
	if($int == $interface) return $ifname;
652
    }
653
    return $interface;
654
}
655

    
656
/*
657
 * update_progress_bar($percent): updates the javascript driven progress bar.
658
 */
659
function update_progress_bar($percent) {
660
    if($percent > 100) $percent = 1;
661
    echo "\n<script type=\"text/javascript\" language=\"javascript\">";
662
    echo "\ndocument.progressbar.style.width='" . $percent . "%';";
663
    echo "\n</script>";
664
}
665

    
666
/*
667
 * gather_altq_queue_stats():  gather alq queue stats and return an array that
668
 *                             is queuename|qlength|measured_packets
669
 *                             NOTE: this command takes 5 seconds to run
670
 */
671
function gather_altq_queue_stats($dont_return_root_queues) {
672
    mwexec("/usr/bin/killall -9 pfctl");
673
    $stats = `/sbin/pfctl -vvsq & /bin/sleep 5;/usr/bin/killall pfctl 2>/dev/null`;
674
    $stats_array = split("\n", $stats);
675
    $queue_stats = array();
676
    foreach ($stats_array as $stats_line) {
677
        if (preg_match_all("/queue\s+(\w+)\s+/",$stats_line,$match_array))
678
            $queue_name = $match_array[1][0];
679
        if (preg_match_all("/measured:\s+.*packets\/s\,\s(.*)\s+\]/",$stats_line,$match_array))
680
            $speed = $match_array[1][0];
681
        if (preg_match_all("/borrows:\s+(.*)/",$stats_line,$match_array))
682
            $borrows = $match_array[1][0];
683
        if (preg_match_all("/suspends:\s+(.*)/",$stats_line,$match_array))
684
            $suspends = $match_array[1][0];
685
        if (preg_match_all("/dropped pkts:\s+(.*)/",$stats_line,$match_array))
686
            $drops = $match_array[1][0];
687
        if (preg_match_all("/measured:\s+(.*)packets/",$stats_line,$match_array)) {
688
            $measured = $match_array[1][0];
689
	    if($dont_return_root_queues == true)
690
		if(stristr($queue_name,"root_") == false)
691
		    array_push($queue_stats, "{$queue_name}|{$speed}|{$measured}|{$borrows}|{$suspends}|{$drops}");
692
        }
693
    }
694
    return $queue_stats;
695
}
696

    
697
/*
698
 * reverse_strrchr($haystack, $needle):  Return everything in $haystack up to the *last* instance of $needle.
699
 *					 Useful for finding paths and stripping file extensions.
700
 */
701
function reverse_strrchr($haystack, $needle)
702
{
703
               return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) +1 ) : false;
704
}
705

    
706
/*
707
 *  backup_config_section($section): returns as an xml file string of
708
 *                                   the configuration section
709
 */
710
function backup_config_section($section) {
711
    global $config;
712
    $new_section = &$config[$section];
713
    /* generate configuration XML */
714
    $xmlconfig = dump_xml_config($new_section, $section);
715
    $xmlconfig = str_replace("<?xml version=\"1.0\"?>", "", $xmlconfig);
716
    return $xmlconfig;
717
}
718

    
719
/*
720
 *  backup_config_section($section): returns as an xml file string of
721
 *                                   the configuration section
722
 */
723
function backup_vip_config_section() {
724
    global $config;
725
    $new_section = &$config['virtualip'];
726
    foreach($new_section['vip'] as $section) {
727
	if($section['mode'] == "proxyarp") {
728
		unset($section);		
729
	}
730
	if($section['advskew'] <> "") {
731
		$section['advskew']++;
732
	}
733
	$temp['vip'][] = $section;
734
    }
735
    
736
    /* generate configuration XML */
737
    $xmlconfig = dump_xml_config($temp, "virtualip");
738
    $xmlconfig = str_replace("<?xml version=\"1.0\"?>", "", $xmlconfig);
739
    return $xmlconfig;
740
}
741

    
742
/*
743
 *  restore_config_section($section, new_contents): restore a configuration section,
744
 *                                                  and write the configuration out
745
 *                                                  to disk/cf.
746
 */
747
function restore_config_section($section, $new_contents) {
748
    global $config;
749
    conf_mount_rw();
750
    $fout = fopen("{$g['tmp_path']}/tmpxml","w");
751
    fwrite($fout, $new_contents);
752
    fclose($fout);
753
    $section_xml = parse_xml_config($g['tmp_path'] . "/tmpxml", $section);
754
    $config[$section] = &$section_xml;
755
    unlink($g['tmp_path'] . "/tmpxml");
756
    write_config("Restored {$section} of config file (maybe from CARP partner)");
757
    conf_mount_ro();
758
    return;
759
}
760

    
761
/*
762
 * http_post($server, $port, $url, $vars): does an http post to a web server
763
 *                                         posting the vars array.
764
 * written by nf@bigpond.net.au
765
 */
766
function http_post($server, $port, $url, $vars) {
767
    $user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)";
768
    $urlencoded = "";
769
    while (list($key,$value) = each($vars))
770
	$urlencoded.= urlencode($key) . "=" . urlencode($value) . "&";
771
    $urlencoded = substr($urlencoded,0,-1);
772

    
773
    $content_length = strlen($urlencoded);
774

    
775
    $headers = "POST $url HTTP/1.1
776
Accept: */*
777
Accept-Language: en-au
778
Content-Type: application/x-www-form-urlencoded
779
User-Agent: $user_agent
780
Host: $server
781
Connection: Keep-Alive
782
Cache-Control: no-cache
783
Content-Length: $content_length
784

    
785
";
786

    
787
    $fp = fsockopen($server, $port, $errno, $errstr);
788
    if (!$fp) {
789
	return false;
790
    }
791

    
792
    fputs($fp, $headers);
793
    fputs($fp, $urlencoded);
794

    
795
    $ret = "";
796
    while (!feof($fp))
797
	$ret.= fgets($fp, 1024);
798

    
799
    fclose($fp);
800

    
801
    return $ret;
802

    
803
}
804

    
805
/*
806
 *  php_check_syntax($code_tocheck, $errormessage): checks $code_to_check for errors
807
 */
808
if (!function_exists('php_check_syntax')){
809
   function php_check_syntax($code_to_check, &$errormessage){
810
	return false;
811
        $fout = fopen("/tmp/codetocheck.php","w");
812
        $code = $_POST['content'];
813
        $code = str_replace("<?php", "", $code);
814
        $code = str_replace("?>", "", $code);
815
        fwrite($fout, "<?php\n\n");
816
        fwrite($fout, $code_to_check);
817
        fwrite($fout, "\n\n?>\n");
818
        fclose($fout);
819
        $command = "/usr/local/bin/php -l /tmp/codetocheck.php";
820
        $output = exec_command($command);
821
        if (stristr($output, "Errors parsing") == false) {
822
            echo "false\n";
823
            $errormessage = '';
824
            return(false);
825
        } else {
826
            $errormessage = $output;
827
            return(true);
828
        }
829
    }
830
}
831

    
832
/*
833
 *  php_check_filename_syntax($filename, $errormessage): checks the file $filename for errors
834
 */
835
if (!function_exists('php_check_syntax')){
836
   function php_check_syntax($code_to_check, &$errormessage){
837
	return false;
838
        $command = "/usr/local/bin/php -l " . $code_to_check;
839
        $output = exec_command($command);
840
        if (stristr($output, "Errors parsing") == false) {
841
            echo "false\n";
842
            $errormessage = '';
843
            return(false);
844
        } else {
845
            $errormessage = $output;
846
            return(true);
847
        }
848
    }
849
}
850

    
851
/*
852
 * rmdir_recursive($path,$follow_links=false)
853
 * Recursively remove a directory tree (rm -rf path)
854
 * This is for directories _only_
855
 */
856
function rmdir_recursive($path,$follow_links=false) {
857
	$to_do = glob($path);
858
	if(!is_array($to_do)) $to_do = array($to_do);
859
	foreach($to_do as $workingdir) { // Handle wildcards by foreaching.
860
		if(file_exists($workingdir)) {
861
			if(is_dir($workingdir)) {
862
				$dir = opendir($workingdir);
863
				while ($entry = readdir($dir)) {
864
					if (is_file("$workingdir/$entry") || ((!$follow_links) && is_link("$workingdir/$entry")))
865
						unlink("$workingdir/$entry");
866
					elseif (is_dir("$workingdir/$entry") && $entry!='.' && $entry!='..')
867
						rmdir_recursive("$workingdir/$entry");
868
				}
869
				closedir($dir);
870
				rmdir($workingdir);
871
			} elseif (is_file($workingdir)) {
872
				unlink($workingdir);
873
			}
874
               	}
875
	}
876
	return;
877
}
878

    
879
/*
880
 * safe_mkdir($path, $mode = 0755)
881
 * create directory if it doesn't already exist and isn't a file!
882
 */
883
function safe_mkdir($path, $mode=0755) {
884
	global $g;
885

    
886
	/* cdrom is ro. */
887
	if($g['platform'] == "cdrom")
888
		return false;
889
	
890
	if (!is_file($path) && !is_dir($path))
891
		return mkdir($path, $mode);
892
	else
893
		return false;
894
}
895

    
896
/*
897
 * make_dirs($path, $mode = 0755)
898
 * create directory tree recursively (mkdir -p)
899
 */
900
function make_dirs($path, $mode = 0755) {
901
	/* is dir already created? */
902
	if(is_dir($path)) return;
903
	/* create directory in question */
904
	$to_create = explode("/", $path);
905
	foreach($to_create as $tc) 
906
	    if(!is_dir($tc))
907
		safe_mkdir($path, $mode);
908
}
909

    
910
/*
911
 * check_firmware_version(): Check whether the current firmware installed is the most recently released.
912
 */
913
function check_firmware_version($tocheck = "all", $return_php = true) {
914
        global $g, $config;
915
	$xmlrpc_base_url = $g['xmlrpcbaseurl'];
916
        $xmlrpc_path = $g['xmlrpcpath'];
917
	$rawparams = array("firmware" => array("version" => trim(file_get_contents('/etc/version'))),
918
			"kernel"   => array("version" => trim(file_get_contents('/etc/version_kernel'))),
919
			"base"     => array("version" => trim(file_get_contents('/etc/version_base'))),
920
			"platform" => trim(file_get_contents('/etc/platform'))
921
		);
922
	if($tocheck == "all") {
923
		$params = $rawparams;
924
	} else {
925
		foreach($tocheck as $check) {
926
			$params['check'] = $rawparams['check'];
927
			$params['platform'] = $rawparams['platform'];
928
		}
929
	}
930
	if($config['system']['firmware']['branch']) {
931
		$params['branch'] = $config['system']['firmware']['branch'];
932
	}
933
	$xmlparams = php_value_to_xmlrpc($params);
934
        $msg = new XML_RPC_Message('pfsense.get_firmware_version', array($xmlparams));
935
        $cli = new XML_RPC_Client($xmlrpc_path, $xmlrpc_base_url);
936
	//$cli->setDebug(1);
937
	$resp = $cli->send($msg, 10);
938
	if(!$resp or $resp->faultCode()) {
939
		$raw_versions = false;
940
	} else {
941
		$raw_versions = xmlrpc_value_to_php($resp->value());
942
		$raw_versions["current"] = $params;
943
	}
944
	return $raw_versions;
945
}
946

    
947
function get_disk_info() {
948
        exec("df -h | grep -w '/' | awk '{ print $2, $3, $4, $5 }'", $diskout);
949
        return explode(' ', $diskout[0]);
950
        // $size, $used, $avail, $cap
951
}
952

    
953
/****f* pfsense-utils/display_top_tabs
954
 * NAME
955
 *   display_top_tabs - display tabs with rounded edges
956
 * INPUTS
957
 *   $text	- array of tabs
958
 * RESULT
959
 *   null
960
 ******/
961
    function display_top_tabs($tab_array) {
962
	    echo "<table cellpadding='0' cellspacing='0'>\n";
963
	    echo " <tr height='1'>\n";
964
	    $tabscounter = 0;
965
	    foreach ($tab_array as $ta) {
966
		    if($ta[1] == true) {
967
			    echo "  <td bgcolor='#EEEEEE' onClick=\"document.location='{$ta[2]}'\"><div id='tabactive'></div></td>\n";
968
		    } else {
969
			    echo "  <td bgcolor='#777777' onClick=\"document.location='{$ta[2]}'\"><div id='tabdeactive{$tabscounter}'></div></td>\n";
970
		    }
971
		    $tabscounter++;
972
	    }
973
	    echo "</tr>\n<tr>\n";
974
	    foreach ($tab_array as $ta) {
975
		    if($ta[1] == true) {
976
			    echo "  <td bgcolor='#EEEEEE' onClick=\"document.location='{$ta[2]}'\"><B>&nbsp;&nbsp;&nbsp;{$ta[0]}";
977
			    echo "&nbsp;&nbsp;&nbsp;";
978
			    echo "<font size='-12'>&nbsp;</td>\n";
979
		    } else {
980
			    echo "  <td bgcolor='#777777' onClick=\"document.location='{$ta[2]}'\"><B>&nbsp;&nbsp;&nbsp;<a href='{$ta[2]}'>";
981
			    echo "<font color='white'>{$ta[0]}</a>&nbsp;&nbsp;&nbsp;";
982
			    echo "<font size='-12'>&nbsp;</td>\n";
983
		    }
984
	    }
985
	    echo "</tr>\n<tr height='5px'>\n";
986
	    foreach ($tab_array as $ta) {
987
		    if($ta[1] == true) {
988
			    echo "  <td bgcolor='#EEEEEE' onClick=\"document.location='{$ta[2]}'\"></td>\n";
989
		    } else {
990
			    echo "  <td bgcolor='#777777' onClick=\"document.location='{$ta[2]}'\"></td>\n";
991
		    }
992
		    $tabscounter++;
993
	    }
994
	    echo " </tr>\n";
995
	    echo "</table>\n";
996
	    
997
	    echo "<script type=\"text/javascript\">";
998
	    echo "NiftyCheck();\n";
999
	    echo "Rounded(\"div#tabactive\",\"top\",\"#FFF\",\"#EEEEEE\",\"smooth\");\n";
1000
	    for($x=0; $x<$tabscounter; $x++) 
1001
		    echo "Rounded(\"div#tabdeactive{$x}\",\"top\",\"#FFF\",\"#777777\",\"smooth\");\n";
1002
	    echo "</script>";
1003
    }
1004

    
1005

    
1006
/****f* pfsense-utils/display_topbar
1007
 * NAME
1008
 *   display_topbar - top a table off with rounded edges
1009
 * INPUTS
1010
 *   $text	- (optional) Text to include in bar
1011
 * RESULT
1012
 *   null
1013
 ******/
1014
function display_topbar($text = "", $bg_color="#990000", $replace_color="#FFFFFF", $rounding_style="smooth") {	    
1015
	echo "     <table width='100%' cellpadding='0' cellspacing='0'>\n";
1016
	echo "       <tr height='1'>\n";
1017
	echo "         <td width='100%' valign='top' color='{$bg_color}' bgcolor='{$bg_color}'>";
1018
	echo "		<div id='topbar'></div></td>\n";
1019
	echo "       </tr>\n";
1020
	echo "       <tr height='1'>\n";
1021
	if ($text != "")
1022
		echo "         <td height='1' class='listtopic'>{$text}</td>\n";
1023
	else
1024
		echo "         <td height='1' class='listtopic'></td>\n";
1025
	echo "       </tr>\n";
1026
	echo "     </table>";
1027
	echo "<script type=\"text/javascript\">";
1028
	echo "NiftyCheck();\n";
1029
	echo "Rounded(\"div#topbar\",\"top\",\"{$replace_color}\",\"{$bg_color}\",\"{$rounding_style}\");\n";
1030
	echo "</script>";
1031
}
1032

    
1033
/****f* pfsense-utils/generate_random_mac_address
1034
 * NAME
1035
 *   generate_random_mac - generates a random mac address
1036
 * INPUTS
1037
 *   none
1038
 * RESULT
1039
 *   $mac - a random mac address
1040
 ******/
1041
function generate_random_mac_address() {
1042
	$mac = "00:a0:8e";
1043
	for($x=0; $x<3; $x++) 
1044
	    $mac .= ":" . dechex(rand(16, 255));
1045

    
1046
	return $mac;
1047
}
1048

    
1049
/****f* pfsense-utils/strncpy
1050
 * NAME
1051
 *   strncpy - copy strings
1052
 * INPUTS
1053
 *   &$dst, $src, $length
1054
 * RESULT
1055
 *   none
1056
 ******/
1057
function strncpy(&$dst, $src, $length) {
1058
	if (strlen($src) > $length) {
1059
		$dst = substr($src, 0, $length);
1060
	} else {
1061
		$dst = $src;
1062
	}
1063
}
1064

    
1065
/****f* pfsense-utils/reload_interfaces_sync
1066
 * NAME
1067
 *   reload_interfaces - reload all interfaces
1068
 * INPUTS
1069
 *   none
1070
 * RESULT
1071
 *   none
1072
 ******/
1073
function reload_interfaces_sync() {
1074
	global $config, $g;
1075
	
1076
	if(file_exists("{$g['tmp_path']}/config.cache"))
1077
		unlink("{$g['tmp_path']}/config.cache");
1078
	
1079
	/* parse config.xml again */
1080
	$config = parse_config(true);
1081
	
1082
	/* set up LAN interface */
1083
	interfaces_lan_configure();
1084

    
1085
	/* set up WAN interface */
1086
	interfaces_wan_configure();
1087

    
1088
	/* set up Optional interfaces */
1089
	interfaces_optional_configure();
1090
        
1091
	/* set up static routes */
1092
	system_routing_configure();
1093
	
1094
	/* bring up carp interfaces */
1095
	interfaces_carp_bringup();
1096

    
1097
	/* enable routing */
1098
	system_routing_enable();
1099
}
1100

    
1101
/****f* pfsense-utils/reload_all
1102
 * NAME
1103
 *   reload_all - triggers a reload of all settings
1104
 *   * INPUTS
1105
 *   none
1106
 * RESULT
1107
 *   none
1108
 ******/
1109
function reload_all() {
1110
	touch("/tmp/reload_all");
1111
}
1112

    
1113
/****f* pfsense-utils/reload_interfaces
1114
 * NAME
1115
 *   reload_interfaces - triggers a reload of all interfaces
1116
 * INPUTS
1117
 *   none
1118
 * RESULT
1119
 *   none
1120
 ******/
1121
function reload_interfaces() {
1122
	touch("/tmp/reload_interfaces");
1123
}
1124

    
1125
/****f* pfsense-utils/sync_webgui_passwords
1126
 * NAME
1127
 *   sync_webgui_passwords - syncs webgui and ssh passwords
1128
 * INPUTS
1129
 *   none
1130
 * RESULT
1131
 *   none
1132
 ******/
1133
function sync_webgui_passwords() {
1134
	conf_mount_rw();
1135
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
1136
	mwexec("/usr/sbin/pwd_mkdb /etc/master.passwd");
1137
	conf_mount_ro();
1138
}
1139

    
1140
/****f* pfsense-utils/reload_all_sync
1141
 * NAME
1142
 *   reload_all - reload all settings
1143
 *   * INPUTS
1144
 *   none
1145
 * RESULT
1146
 *   none
1147
 ******/
1148
function reload_all_sync() {
1149
	global $config, $g;
1150
	
1151
	if(file_exists("{$g['tmp_path']}/config.cache"))
1152
		unlink("{$g['tmp_path']}/config.cache");
1153
	
1154
	/* parse config.xml again */
1155
	$config = parse_config(true);
1156

    
1157
	/* set up our timezone */
1158
	system_timezone_configure();
1159

    
1160
	/* set up our hostname */
1161
	system_hostname_configure();
1162

    
1163
	/* make hosts file */
1164
	system_hosts_generate();
1165

    
1166
	/* generate resolv.conf */
1167
	system_resolvconf_generate();
1168

    
1169
	/* set up LAN interface */
1170
	interfaces_lan_configure();
1171

    
1172
	/* set up WAN interface */
1173
	interfaces_wan_configure();
1174

    
1175
	/* set up Optional interfaces */
1176
	interfaces_optional_configure();
1177
        
1178
	/* bring up carp interfaces */
1179
	interfaces_carp_configure();
1180
	
1181
	/* set up static routes */
1182
	system_routing_configure();
1183

    
1184
	/* enable routing */
1185
	system_routing_enable();
1186
	
1187
	/* ensure passwords are sync'd */
1188
	system_password_configure();
1189

    
1190
	/* start dnsmasq service */
1191
	services_dnsmasq_configure();
1192

    
1193
	/* start dyndns service */
1194
	services_dyndns_configure();
1195

    
1196
	/* start DHCP service */
1197
	services_dhcpd_configure();
1198

    
1199
	/* start the NTP client */
1200
	system_ntp_configure();
1201

    
1202
	/* start ftp proxy helpers if they are enabled */
1203
	system_start_ftp_helpers();
1204

    
1205
	/* bring up carp interfaces */
1206
	interfaces_carp_bringup();
1207

    
1208
        /* reload the filter */
1209
	filter_configure();
1210
	
1211
	/* sync pw database */
1212
	conf_mount_rw();
1213
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
1214
	mwexec("/usr/sbin/pwd_mkdb /etc/master.passwd");
1215
	conf_mount_ro();
1216
	
1217
}
1218

    
1219
?>
(12-12/23)