Project

General

Profile

Download (41 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
	$dns_server_master = array();
57
	sort($dns_servers);
58
	foreach($dns_servers as $t) {
59
		if($t <> $lastseen)
60
			if($t <> "")
61
				$dns_server_master[] = $t;
62
		$lastseen = $t;
63
	}
64
	return $dns_server_master;
65
}
66

    
67
/****f* pfsense-utils/log_error
68
* NAME
69
*   log_error  - Sends a string to syslog.
70
* INPUTS
71
*   $error     - string containing the syslog message.
72
* RESULT
73
*   null
74
******/
75
function log_error($error) {
76
    $page = $_SERVER['PHP_SELF'];
77
    syslog(LOG_WARNING, "$page: $error");
78
    return;
79
}
80

    
81
/****f* pfsense-utils/get_interface_mac_address
82
 * NAME
83
 *   get_interface_mac_address - Return a interfaces mac address
84
 * INPUTS
85
 *   $interface	- interface to obtain mac address from
86
 * RESULT
87
 *   $mac - the mac address of the interface
88
 ******/
89
function get_interface_mac_address($interface) {
90
    $mac = exec("ifconfig {$interface} | awk '/ether/ {print $2}'");
91
    return trim($mac);
92
}
93

    
94
/****f* pfsense-utils/return_dir_as_array
95
 * NAME
96
 *   return_dir_as_array - Return a directory's contents as an array.
97
 * INPUTS
98
 *   $dir	- string containing the path to the desired directory.
99
 * RESULT
100
 *   $dir_array - array containing the directory's contents. This array will be empty if the path specified is invalid.
101
 ******/
102
function return_dir_as_array($dir) {
103
    $dir_array = array();
104
    if (is_dir($dir)) {
105
	if ($dh = opendir($dir)) {
106
	    while (($file = readdir($dh)) !== false) {
107
		$canadd = 0;
108
		if($file == ".") $canadd = 1;
109
		if($file == "..") $canadd = 1;
110
		if($canadd == 0)
111
		    array_push($dir_array, $file);
112
	    }
113
	    closedir($dh);
114
	}
115
    }
116
    return $dir_array;
117
}
118

    
119
/****f* pfsense-utils/enable_hardware_offloading
120
 * NAME
121
 *   enable_hardware_offloading - Enable a NIC's supported hardware features.
122
 * INPUTS
123
 *   $interface	- string containing the physical interface to work on.
124
 * RESULT
125
 *   null
126
 * NOTES
127
 *   This function only supports the fxp driver's loadable microcode.
128
 ******/
129
function enable_hardware_offloading($interface) {
130
    global $g, $config;
131
    if(isset($config['system']['do_not_use_nic_microcode']))
132
	return;
133
    if($g['booting']) {
134
	/* translate wan, lan, opt -> real interface if needed */
135
	$int = filter_translate_type_to_real_interface($interface);
136
	if(stristr($int,"lnc"))
137
		return;    	
138
	if($int <> "") $interface = $int;
139
        $int_family = preg_split("/[0-9]+/", $int);
140
	$options = strtolower(`/sbin/ifconfig {$interface} | grep options`);
141
	echo $interface . " ";
142
	$supported_ints = array('fxp');
143
	if (in_array($int_family, $supported_ints))
144
		mwexec("/sbin/ifconfig {$interface} link0");
145
	if(stristr($options, "txcsum") == true)
146
	    mwexec("/sbin/ifconfig {$interface} txcsum 2>/dev/null");
147
	if(stristr($options, "rxcsum") == true)    
148
	    mwexec("/sbin/ifconfig {$interface} rxcsum 2>/dev/null");    
149
	if(stristr($options, "polling") == true)
150
	    mwexec("/sbin/ifconfig {$interface} polling 2>/dev/null");
151
    }
152
    return;
153
}
154

    
155
/****f* pfsense-utils/is_alias_inuse
156
 * NAME
157
 *   checks to see if an alias is currently in use by a rule
158
 * INPUTS
159
 *   
160
 * RESULT
161
 *   true or false
162
 * NOTES
163
 *   
164
 ******/
165
function is_alias_inuse($alias) {
166
    global $g, $config;
167
    if($alias == "") return false;
168
    /* loop through firewall rules looking for alias in use */
169
    foreach($config['filter']['rule'] as $rule) {
170
	if($rule['source']['address'] == $alias)
171
	    return true;
172
	if($rule['destination']['address'] == $alias)
173
	    return true;
174
    }
175
    /* loop through nat rules looking for alias in use */
176
    foreach($config['nat']['rule'] as $rule) {
177
	if($rule['source']['address'] == $alias)
178
	    return true;
179
	if($rule['destination']['address'] == $alias)
180
	    return true;
181
    }
182
    return false;
183
}
184

    
185
/****f* pfsense-utils/setup_polling_defaults
186
 * NAME
187
 *   sets up sysctls for pollingS
188
 * INPUTS
189
 *   
190
 * RESULT
191
 *   null
192
 * NOTES
193
 *   
194
 ******/
195
function setup_polling_defaults() {
196
	global $g, $config;
197
	if($config['system']['polling_each_burst'])
198
		mwexec("sysctl kern.polling.each_burst={$config['system']['polling_each_burst']}");
199
	if($config['system']['polling_burst_max'])
200
		mwexec("sysctl kern.polling.burst_max={$config['system']['polling_burst_max']}");
201
	if($config['system']['polling_user_frac'])
202
		mwexec("sysctl kern.polling.user_frac={$config['system']['polling_user_frac']}");		
203
}
204

    
205
/****f* pfsense-utils/setup_polling
206
 * NAME
207
 *   sets up polling
208
 * INPUTS
209
 *   
210
 * RESULT
211
 *   null
212
 * NOTES
213
 *   
214
 ******/
215
function setup_polling() {
216
	setup_polling_defaults();
217
	global $g, $config;
218
	/* build an array of interfaces to work with */
219
	$iflist = array("lan" => "LAN", "wan" => "WAN");
220
	for ($i = 1; isset($config['interfaces']['opt' . $i]); $i++) 
221
	$iflist['opt' . $i] = $config['interfaces']['opt' . $i]['descr'];		
222
	/*    activate polling for interface if it supports it
223
	 *    man polling on a freebsd box for the following list
224
	 */
225
	/* loop through all interfaces and handle pftpx redirections */
226
	foreach ($iflist as $ifent => $ifname) {	
227
		$supported_ints = array('dc', 'em', 'fwe', 'fwip', 'fxp', 'ixgb', 'ste',
228
			'nge', 're', 'rl', 'sf', 'sis', 'ste', 'vge', 'vr', 'xl');
229
		if (in_array($int_family, $supported_ints) and isset($config['system']['polling'])) {
230
			mwexec("/sbin/ifconfig {$interface} polling");
231
		} else {
232
			mwexec("/sbin/ifconfig {$interface} -polling");
233
		}
234
	}
235
}
236

    
237
/****f* pfsense-utils/setup_microcode
238
 * NAME
239
 *   enumerates all interfaces and calls enable_hardware_offloading which
240
 *   enables a NIC's supported hardware features.
241
 * INPUTS
242
 *   
243
 * RESULT
244
 *   null
245
 * NOTES
246
 *   This function only supports the fxp driver's loadable microcode.
247
 ******/
248
function setup_microcode() {
249
   global $config;
250
    $ifdescrs = array('wan', 'lan');
251
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) {
252
	$ifdescrs['opt' . $j] = "opt" . $j;
253
    }
254
    foreach($ifdescrs as $if)
255
	enable_hardware_offloading($if);
256
}
257

    
258
/****f* pfsense-utils/return_filename_as_array
259
 * NAME
260
 *   return_filename_as_array - Return a file's contents as an array.
261
 * INPUTS
262
 *   $filename	- string containing the path to the desired file.
263
 *   $strip	- array of characters to strip - default is '#'.
264
 * RESULT
265
 *   $file	- array containing the file's contents.
266
 * NOTES
267
 *   This function strips lines starting with '#' and leading/trailing whitespace by default.
268
 ******/
269
function return_filename_as_array($filename, $strip = array('#')) {
270
    if(file_exists($filename)) $file = file($filename);
271
    if(is_array($file)) {
272
	foreach($file as $line) $line = trim($line);
273
        foreach($strip as $tostrip) $file = preg_grep("/^{$tostrip}/", $file, PREG_GREP_INVERT);
274
    }
275
    return $file;
276
}
277

    
278
/****f* pfsense-utils/file_put_contents
279
 * NAME
280
 *   file_put_contents - Wrapper for file_put_contents if it doesn't exist
281
 * RESULT
282
 *   none
283
 ******/
284
if(!function_exists("file_put_contents")) {
285
    function file_put_contents($filename, $data) {
286
	$fd = fopen($filename,"w");
287
	fwrite($fd, $data);
288
	fclose($fd);
289
    }
290
}
291

    
292
/****f* pfsense-utils/get_carp_status
293
 * NAME
294
 *   get_carp_status - Return whether CARP is enabled or disabled.
295
 * RESULT
296
 *   boolean	- true if CARP is enabled, false if otherwise.
297
 ******/
298
function get_carp_status() {
299
    /* grab the current status of carp */
300
    $status = `/sbin/sysctl net.inet.carp.allow | cut -d" " -f2`;
301
    if(intval($status) == "0") return false;
302
    return true;
303
}
304

    
305
/****f* pfsense-utils/is_carp_defined
306
 * NAME
307
 *   is_carp_defined - Return whether CARP is detected in the kernel.
308
 * RESULT
309
 *   boolean	- true if CARP is detected, false otherwise.
310
 ******/
311
function is_carp_defined() {
312
    /* is carp compiled into the kernel and userland? */
313
    $command = "/sbin/sysctl -a | grep carp";
314
    $fd = popen($command . " 2>&1 ", "r");
315
    if(!$fd) {
316
	log_error("Warning, could not execute command {$command}");
317
	return 0;
318
    }
319
    while(!feof($fd)) {
320
	$tmp .= fread($fd,49);
321
    }
322
    fclose($fd);
323

    
324
    if($tmp == "")
325
	return false;
326
    else
327
	return true;
328
}
329

    
330
/****f* pfsense-utils/get_interface_mtu
331
 * NAME
332
 *   get_interface_mtu - Return the mtu of an interface
333
 * RESULT
334
 *   $tmp	- Returns the mtu of an interface
335
 ******/
336
function get_interface_mtu($interface) {
337
	$mtu = `/sbin/ifconfig {$interface} | /usr/bin/grep mtu | /usr/bin/cut -d" " -f4`;
338
	return $mtu;
339
}
340

    
341
/****f* pfsense-utils/find_number_of_created_carp_interfaces
342
 * NAME
343
 *   find_number_of_created_carp_interfaces - Return the number of CARP interfaces.
344
 * RESULT
345
 *   $tmp	- Number of currently created CARP interfaces.
346
 ******/
347
function find_number_of_created_carp_interfaces() {
348
    $command = "/sbin/ifconfig | /usr/bin/grep \"carp*:\" | /usr/bin/wc -l";
349
    $fd = popen($command . " 2>&1 ", "r");
350
    if(!$fd) {
351
	log_error("Warning, could not execute command {$command}");
352
	return 0;
353
    }
354
    while(!feof($fd)) {
355
	$tmp .= fread($fd,49);
356
    }
357
    fclose($fd);
358
    $tmp = intval($tmp);
359
    return $tmp;
360
}
361

    
362
/****f* pfsense-utils/link_ip_to_carp_interface
363
 * NAME
364
 *   link_ip_to_carp_interface - Find where a CARP interface links to.
365
 * INPUTS
366
 *   $ip
367
 * RESULT
368
 *   $carp_ints
369
 ******/
370
function link_ip_to_carp_interface($ip) {
371
	global $config;
372
	if($ip == "") return;
373

    
374
	$ifdescrs = array('wan', 'lan');
375
	for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) {
376
		$ifdescrs['opt' . $j] = "opt" . $j;
377
	}
378

    
379
	$ft = split("\.", $ip);
380
	$ft_ip = $ft[0] . "." . $ft[1] . "." . $ft[2] . ".";
381

    
382
	$carp_ints = "";
383
	$num_carp_ints = find_number_of_created_carp_interfaces();
384
	foreach ($ifdescrs as $ifdescr => $ifname) {
385
		for($x=0; $x<$num_carp_ints; $x++) {
386
			$carp_int = "carp{$x}";
387
			$carp_ip = find_interface_ip($carp_int);
388
			$carp_ft = split("\.", $carp_ip);
389
			$carp_ft_ip = $carp_ft[0] . "." . $carp_ft[1] . "." . $carp_ft[2] . ".";
390
			$result = does_interface_exist($carp_int);
391
			if($result <> true) break;
392
			if($ft_ip == $carp_ft_ip)
393
			if(stristr($carp_ints,$carp_int) == false)
394
			$carp_ints .= " " . $carp_int;
395
		}
396
	}
397
	return $carp_ints;
398
}
399

    
400
/****f* pfsense-utils/exec_command
401
 * NAME
402
 *   exec_command - Execute a command and return a string of the result.
403
 * INPUTS
404
 *   $command	- String of the command to be executed.
405
 * RESULT
406
 *   String containing the command's result.
407
 * NOTES
408
 *   This function returns the command's stdout and stderr.
409
 ******/
410
function exec_command($command) {
411
    $output = array();
412
    exec($command . ' 2>&1 ', $output);
413
    return(implode("\n", $output));
414
}
415

    
416
/****f* interfaces/is_jumbo_capable
417
 * NAME
418
 *   is_jumbo_capable - Test if interface is jumbo frame capable.  Useful for determining VLAN capability.
419
 * INPUTS
420
 *   $int             - string containing interface name
421
 * RESULT
422
 *   boolean          - true or false
423
 ******/
424
function is_jumbo_capable($int) {
425
	/* Per:
426
	 * http://www.freebsd.org/cgi/man.cgi?query=vlan&manpath=FreeBSD+6.0-current&format=html
427
	 * Only the following drivers support large frames
428
	 */
429
	$capable = array("bfe", "dc", "de", "fxp", "hme", "rl", "sis", "ste",
430
		"tl", "tx", "xl", "em");
431
	
432
	$int_family = preg_split("/[0-9]+/", $int);
433

    
434
	if (in_array($int_family[0], $capable))
435
		return true;
436
	else
437
		return false;
438
}
439

    
440
/*
441
 * does_interface_exist($interface): return true or false if a interface is detected.
442
 */
443
function does_interface_exist($interface) {
444
    $ints = exec_command("/sbin/ifconfig -l");
445
    if(stristr($ints, $interface) !== false)
446
	return true;
447
    else
448
	return false;
449
}
450

    
451
/*
452
 * convert_ip_to_network_format($ip, $subnet): converts an ip address to network form
453
 */
454
function convert_ip_to_network_format($ip, $subnet) {
455
    $ipsplit = split('[.]', $ip);
456
    $string = $ipsplit[0] . "." . $ipsplit[1] . "." . $ipsplit[2] . ".0/" . $subnet;
457
    return $string;
458
}
459

    
460
/*
461
 * find_interface_ip($interface): return the interface ip (first found)
462
 */
463
function find_interface_ip($interface) {
464
    if(does_interface_exist($interface) == false) return;
465
    $ip = exec_command("/sbin/ifconfig {$interface} | /usr/bin/grep -w \"inet\" | /usr/bin/cut -d\" \" -f 2");
466
    $ip = str_replace("\n","",$ip);
467
    return $ip;
468
}
469

    
470
function guess_interface_from_ip($ipaddress) {
471
    $ints = `/sbin/ifconfig -l`;
472
    $ints_split = split(" ", $ints);
473
    $ip_subnet_split = split("\.", $ipaddress);
474
    $ip_subnet = $ip_subnet_split[0] . "." . $ip_subnet_split[1] . "." . $ip_subnet_split[2] . ".";
475
    foreach($ints_split as $int) {
476
        $ip = find_interface_ip($int);
477
        $ip_split = split("\.", $ip);
478
        $ip_tocheck = $ip_split[0] . "." . $ip_split[1] . "." . $ip_split[2] . ".";
479
        if(stristr($ip_tocheck, $ip_subnet) != false) return $int;
480
    }
481
}
482

    
483
function filter_opt_interface_to_real($opt) {
484
    global $config;
485
    return $config['interfaces'][$opt]['if'];
486
}
487

    
488
function filter_get_opt_interface_descr($opt) {
489
    global $config;
490
    return $config['interfaces'][$opt]['descr'];
491
}
492

    
493
function get_friendly_interface_list_as_array() {
494
    global $config;
495
    $ints = array();
496
    $ifdescrs = array('wan', 'lan');
497
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) {
498
		$ifdescrs['opt' . $j] = "opt" . $j;
499
    }
500
    $ifdescrs = get_interface_list();
501
    foreach ($ifdescrs as $ifdescr => $ifname) {
502
		array_push($ints,$ifdescr);
503
    }
504
    return $ints;
505
}
506

    
507
/*
508
 * find_ip_interface($ip): return the interface where an ip is defined
509
 */
510
function find_ip_interface($ip) {
511
    global $config;
512
    $ifdescrs = array('wan', 'lan');
513
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) {
514
	$ifdescrs['opt' . $j] = "opt" . $j;
515
    }
516
    foreach ($ifdescrs as $ifdescr => $ifname) {
517
	$int = filter_translate_type_to_real_interface($ifname);
518
	$ifconfig = exec_command("/sbin/ifconfig {$int}");
519
	if(stristr($ifconfig,$ip) <> false)
520
	    return $int;
521
    }
522
    return false;
523
}
524

    
525
/*
526
 *  filter_translate_type_to_real_interface($interface): returns the real interface name
527
 *                                                       for a friendly interface.  ie: wan
528
 */
529
function filter_translate_type_to_real_interface($interface) {
530
    global $config;
531
    if($config['interfaces'][$interface]['if'] <> "") {
532
	return $config['interfaces'][$interface]['if'];
533
    } else {
534
	return $interface;
535
    }
536
}
537

    
538
/*
539
 * get_carp_interface_status($carpinterface): returns the status of a carp ip
540
 */
541
function get_carp_interface_status($carpinterface) {
542
	/* basically cache the contents of ifconfig statement
543
	to speed up this routine */
544
	global $carp_query;
545
	if($carp_query == "")
546
	$carp_query = split("\n", `/sbin/ifconfig | /usr/bin/grep carp`);
547
	$found_interface = 0;
548
	foreach($carp_query as $int) {
549
		if($found_interface == 1) {
550
			if(stristr($int, "MASTER") == true) return "MASTER";
551
			if(stristr($int, "BACKUP") == true) return "BACKUP";
552
			if(stristr($int, "INIT") == true) return "INIT";
553
			return false;
554
		}
555
		if(stristr($int, $carpinterface) == true)
556
		$found_interface=1;
557
	}
558
	return;
559
}
560

    
561
/*
562
 * get_pfsync_interface_status($pfsyncinterface): returns the status of a pfsync
563
 */
564
function get_pfsync_interface_status($pfsyncinterface) {
565
    $result = does_interface_exist($pfsyncinterface);
566
    if($result <> true) return;
567
    $status = exec_command("/sbin/ifconfig {$pfsyncinterface} | /usr/bin/grep \"pfsync:\" | /usr/bin/cut -d\" \" -f5");
568
    return $status;
569
}
570

    
571
/*
572
 * find_carp_interface($ip): return the carp interface where an ip is defined
573
 */
574
function find_carp_interface($ip) {
575
    global $find_carp_ifconfig;
576
    if($find_carp_ifconfig == "") {
577
	$find_carp_ifconfig = array();
578
	$num_carp_ints = find_number_of_created_carp_interfaces();
579
	for($x=0; $x<$num_carp_ints; $x++) {
580
	    $find_carp_ifconfig[$x] = exec_command("/sbin/ifconfig carp{$x}");
581
	}
582
    }
583
    $carps = 0;
584
    foreach($find_carp_ifconfig as $fci) {
585
	if(stristr($fci, $ip) == true)
586
	    return "carp{$carps}";
587
	$carps++;
588
    }
589
}
590

    
591
/*
592
 * find_number_of_created_bridges(): returns the number of currently created bridges
593
 */
594
function find_number_of_created_bridges() {
595
    return `/sbin/ifconfig | grep \"bridge[0-999]\:" | wc -l`;
596
}
597

    
598
/*
599
 * add_rule_to_anchor($anchor, $rule): adds the specified rule to an anchor
600
 */
601
function add_rule_to_anchor($anchor, $rule, $label) {
602
    mwexec("echo " . $rule . " | /sbin/pfctl -a " . $anchor . ":" . $label . " -f -");
603
}
604

    
605
/*
606
 * remove_text_from_file
607
 * remove $text from file $file
608
 */
609
function remove_text_from_file($file, $text) {
610
    global $fd_log;
611
    fwrite($fd_log, "Adding needed text items:\n");
612
    $filecontents = exec_command_and_return_text("cat " . $file);
613
    $textTMP = str_replace($text, "", $filecontents);
614
    $text .= $textTMP;
615
    fwrite($fd_log, $text . "\n");
616
    $fd = fopen($file, "w");
617
    fwrite($fd, $text);
618
    fclose($fd);
619
}
620

    
621
/*
622
 * add_text_to_file($file, $text): adds $text to $file.
623
 * replaces the text if it already exists.
624
 */
625
function add_text_to_file($file, $text) {
626
	if(file_exists($file) and is_writable($file)) {
627
		$filecontents = file($file);
628
		$filecontents[] = $text;
629
		$tmpfile = get_tmp_file();
630
		$fout = fopen($tmpfile, "w");
631
		foreach($filecontents as $line) {
632
			fwrite($fout, rtrim($line) . "\n");
633
		}
634
		fclose($fout);
635
		rename($tmpfile, $file);
636
		return true;
637
	} else {
638
		return false;
639
	}
640
}
641

    
642
/*
643
 *   after_sync_bump_adv_skew(): create skew values by 1S
644
 */
645
function after_sync_bump_adv_skew() {
646
	global $config, $g;
647
	$processed_skew = 1;
648
	$a_vip = &$config['virtualip']['vip'];
649
	foreach ($a_vip as $vipent) {
650
		if($vipent['advskew'] <> "") {
651
			$processed_skew = 1;
652
			$vipent['advskew'] = $vipent['advskew']+1;
653
		}
654
	}
655
	if($processed_skew == 1)
656
		write_config("After synch increase advertising skew");
657
}
658

    
659
/*
660
 * get_filename_from_url($url): converts a url to its filename.
661
 */
662
function get_filename_from_url($url) {
663
	return basename($url);
664
}
665

    
666
/*
667
 *   update_output_window: update bottom textarea dynamically.
668
 */
669
function update_output_window($text) {
670
    $log = ereg_replace("\n", "\\n", $text);
671
    echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = \"" . $log . "\";</script>";
672
}
673

    
674
/*
675
 *   get_dir: return an array of $dir
676
 */
677
function get_dir($dir) {
678
    $dir_array = array();
679
    $d = dir($dir);
680
    while (false !== ($entry = $d->read())) {
681
	array_push($dir_array, $entry);
682
    }
683
    $d->close();
684
    return $dir_array;
685
}
686

    
687
/*
688
 *   update_output_window: update top textarea dynamically.
689
 */
690
function update_status($status) {
691
    echo "\n<script language=\"JavaScript\">document.forms[0].status.value=\"" . $status . "\";</script>";
692
}
693

    
694
/*
695
 *   exec_command_and_return_text_array: execute command and return output
696
 */
697
function exec_command_and_return_text_array($command) {
698
	$fd = popen($command . " 2>&1 ", "r");
699
	while(!feof($fd)) {
700
		$tmp .= fread($fd,49);
701
	}
702
	fclose($fd);
703
	$temp_array = split("\n", $tmp);
704
	return $temp_array;
705
}
706

    
707
/*
708
 *   exec_command_and_return_text: execute command and return output
709
 */
710
function exec_command_and_return_text($command) {
711
    return exec_command($command);
712
}
713

    
714
/*
715
 *   exec_command_and_return_text: execute command and update output window dynamically
716
 */
717
function execute_command_return_output($command) {
718
    global $fd_log;
719
    $fd = popen($command . " 2>&1 ", "r");
720
    echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = \"\";</script>";
721
    $counter = 0;
722
    $counter2 = 0;
723
    while(!feof($fd)) {
724
	$tmp = fread($fd, 50);
725
	$tmp1 = ereg_replace("\n","\\n", $tmp);
726
	$text = ereg_replace("\"","'", $tmp1);
727
	if($lasttext == "..") {
728
	    $text = "";
729
	    $lasttext = "";
730
	    $counter=$counter-2;
731
	} else {
732
	    $lasttext .= $text;
733
	}
734
	if($counter > 51) {
735
	    $counter = 0;
736
	    $extrabreak = "\\n";
737
	} else {
738
	    $extrabreak = "";
739
	    $counter++;
740
	}
741
	if($counter2 > 600) {
742
	    echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = \"\";</script>";
743
	    $counter2 = 0;
744
	} else
745
	    $counter2++;
746
	echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = this.document.forms[0].output.value + \"" . $text . $extrabreak .  "\"; f('output'); </script>";
747
    }
748
    fclose($fd);
749
}
750

    
751
/*
752
 * convert_friendly_interface_to_real_interface_name($interface): convert WAN to FXP0
753
 */
754
function convert_friendly_interface_to_real_interface_name($interface) {
755
    global $config;
756
    $lc_interface = strtolower($interface);
757
    if($lc_interface == "lan") return $config['interfaces']['lan']['if'];
758
    if($lc_interface == "wan") return $config['interfaces']['wan']['if'];
759
    $ifdescrs = array();
760
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++)
761
	$ifdescrs['opt' . $j] = "opt" . $j;
762
    foreach ($ifdescrs as $ifdescr => $ifname) {
763
	if(strtolower($ifname) == $lc_interface)
764
	    return $config['interfaces'][$ifname]['if'];
765
	if(strtolower($config['interfaces'][$ifname]['descr']) == $lc_interface)
766
	    return $config['interfaces'][$ifname]['if'];
767
    }
768
    return $interface;
769
}
770

    
771
/*
772
 * convert_real_interface_to_friendly_interface_name($interface): convert fxp0 -> wan, etc.
773
 */
774
function convert_real_interface_to_friendly_interface_name($interface) {
775
    global $config;
776
    $ifdescrs = array('wan', 'lan');
777
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++)
778
	$ifdescrs['opt' . $j] = "opt" . $j;
779
    foreach ($ifdescrs as $ifdescr => $ifname) {
780
	$int = filter_translate_type_to_real_interface($ifname);
781
	if($ifname == $interface) return $ifname;
782
	if($int == $interface) return $ifname;
783
    }
784
    return $interface;
785
}
786

    
787
/*
788
 * update_progress_bar($percent): updates the javascript driven progress bar.
789
 */
790
function update_progress_bar($percent) {
791
    if($percent > 100) $percent = 1;
792
    echo "\n<script type=\"text/javascript\" language=\"javascript\">";
793
    echo "\ndocument.progressbar.style.width='" . $percent . "%';";
794
    echo "\n</script>";
795
}
796

    
797
/*
798
 * gather_altq_queue_stats():  gather alq queue stats and return an array that
799
 *                             is queuename|qlength|measured_packets
800
 *                             NOTE: this command takes 5 seconds to run
801
 */
802
function gather_altq_queue_stats($dont_return_root_queues) {
803
    mwexec("/usr/bin/killall -9 pfctl");
804
    $stats = `/sbin/pfctl -vvsq & /bin/sleep 5;/usr/bin/killall pfctl 2>/dev/null`;
805
    $stats_array = split("\n", $stats);
806
    $queue_stats = array();
807
    foreach ($stats_array as $stats_line) {
808
        if (preg_match_all("/queue\s+(\w+)\s+/",$stats_line,$match_array))
809
            $queue_name = $match_array[1][0];
810
        if (preg_match_all("/measured:\s+.*packets\/s\,\s(.*)\s+\]/",$stats_line,$match_array))
811
            $speed = $match_array[1][0];
812
        if (preg_match_all("/borrows:\s+(.*)/",$stats_line,$match_array))
813
            $borrows = $match_array[1][0];
814
        if (preg_match_all("/suspends:\s+(.*)/",$stats_line,$match_array))
815
            $suspends = $match_array[1][0];
816
        if (preg_match_all("/dropped pkts:\s+(.*)/",$stats_line,$match_array))
817
            $drops = $match_array[1][0];
818
        if (preg_match_all("/measured:\s+(.*)packets/",$stats_line,$match_array)) {
819
            $measured = $match_array[1][0];
820
	    if($dont_return_root_queues == true)
821
		if(stristr($queue_name,"root_") == false)
822
		    array_push($queue_stats, "{$queue_name}|{$speed}|{$measured}|{$borrows}|{$suspends}|{$drops}");
823
        }
824
    }
825
    return $queue_stats;
826
}
827

    
828
/*
829
 * reverse_strrchr($haystack, $needle):  Return everything in $haystack up to the *last* instance of $needle.
830
 *					 Useful for finding paths and stripping file extensions.
831
 */
832
function reverse_strrchr($haystack, $needle)
833
{
834
               return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) +1 ) : false;
835
}
836

    
837
/*
838
 *  backup_config_section($section): returns as an xml file string of
839
 *                                   the configuration section
840
 */
841
function backup_config_section($section) {
842
    global $config;
843
    $new_section = &$config[$section];
844
    /* generate configuration XML */
845
    $xmlconfig = dump_xml_config($new_section, $section);
846
    $xmlconfig = str_replace("<?xml version=\"1.0\"?>", "", $xmlconfig);
847
    return $xmlconfig;
848
}
849

    
850
/*
851
 *  backup_config_ts_scheduler(): returns the traffic shaper scheduler for backup
852
 */
853
function backup_config_ts_scheduler() {
854
    global $config;
855
    $new_section = &$config['syste']['schedulertype'];
856
    /* generate configuration XML */
857
    $xmlconfig = dump_xml_config($new_section, $section);
858
    $xmlconfig = str_replace("<?xml version=\"1.0\"?>", "", $xmlconfig);
859
    return $xmlconfig;
860
}
861

    
862
/*
863
 *  backup_config_section($section): returns as an xml file string of
864
 *                                   the configuration section
865
 */
866
function backup_vip_config_section() {
867
    global $config;
868
    $new_section = &$config['virtualip'];
869
    foreach($new_section['vip'] as $section) {
870
	if($section['mode'] == "proxyarp") {
871
		unset($section);		
872
	}
873
	if($section['advskew'] <> "") {
874
		$section_val = intval($section['advskew']);
875
		$section_val=$section_val+100;
876
		if($section_val > 255)
877
			$section_val = 255;
878
		$section['advskew'] = $section_val;
879
	}
880
	$temp['vip'][] = $section;
881
    }
882
    return $temp;
883
}
884

    
885
/*
886
 *  restore_config_section($section, new_contents): restore a configuration section,
887
 *                                                  and write the configuration out
888
 *                                                  to disk/cf.
889
 */
890
function restore_config_section($section, $new_contents) {
891
    global $config;
892
    conf_mount_rw();
893
    $fout = fopen("{$g['tmp_path']}/tmpxml","w");
894
    fwrite($fout, $new_contents);
895
    fclose($fout);
896
    $section_xml = parse_xml_config($g['tmp_path'] . "/tmpxml", $section);
897
    $config[$section] = &$section_xml;
898
    unlink($g['tmp_path'] . "/tmpxml");
899
    write_config("Restored {$section} of config file (maybe from CARP partner)");
900
    conf_mount_ro();
901
    return;
902
}
903

    
904
/*
905
 * http_post($server, $port, $url, $vars): does an http post to a web server
906
 *                                         posting the vars array.
907
 * written by nf@bigpond.net.au
908
 */
909
function http_post($server, $port, $url, $vars) {
910
    $user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)";
911
    $urlencoded = "";
912
    while (list($key,$value) = each($vars))
913
	$urlencoded.= urlencode($key) . "=" . urlencode($value) . "&";
914
    $urlencoded = substr($urlencoded,0,-1);
915

    
916
    $content_length = strlen($urlencoded);
917

    
918
    $headers = "POST $url HTTP/1.1
919
Accept: */*
920
Accept-Language: en-au
921
Content-Type: application/x-www-form-urlencoded
922
User-Agent: $user_agent
923
Host: $server
924
Connection: Keep-Alive
925
Cache-Control: no-cache
926
Content-Length: $content_length
927

    
928
";
929

    
930
    $fp = fsockopen($server, $port, $errno, $errstr);
931
    if (!$fp) {
932
	return false;
933
    }
934

    
935
    fputs($fp, $headers);
936
    fputs($fp, $urlencoded);
937

    
938
    $ret = "";
939
    while (!feof($fp))
940
	$ret.= fgets($fp, 1024);
941

    
942
    fclose($fp);
943

    
944
    return $ret;
945

    
946
}
947

    
948
/*
949
 *  php_check_syntax($code_tocheck, $errormessage): checks $code_to_check for errors
950
 */
951
if (!function_exists('php_check_syntax')){
952
   function php_check_syntax($code_to_check, &$errormessage){
953
	return false;
954
        $fout = fopen("/tmp/codetocheck.php","w");
955
        $code = $_POST['content'];
956
        $code = str_replace("<?php", "", $code);
957
        $code = str_replace("?>", "", $code);
958
        fwrite($fout, "<?php\n\n");
959
        fwrite($fout, $code_to_check);
960
        fwrite($fout, "\n\n?>\n");
961
        fclose($fout);
962
        $command = "/usr/local/bin/php -l /tmp/codetocheck.php";
963
        $output = exec_command($command);
964
        if (stristr($output, "Errors parsing") == false) {
965
            echo "false\n";
966
            $errormessage = '';
967
            return(false);
968
        } else {
969
            $errormessage = $output;
970
            return(true);
971
        }
972
    }
973
}
974

    
975
/*
976
 *  php_check_filename_syntax($filename, $errormessage): checks the file $filename for errors
977
 */
978
if (!function_exists('php_check_syntax')){
979
   function php_check_syntax($code_to_check, &$errormessage){
980
	return false;
981
        $command = "/usr/local/bin/php -l " . $code_to_check;
982
        $output = exec_command($command);
983
        if (stristr($output, "Errors parsing") == false) {
984
            echo "false\n";
985
            $errormessage = '';
986
            return(false);
987
        } else {
988
            $errormessage = $output;
989
            return(true);
990
        }
991
    }
992
}
993

    
994
/*
995
 * rmdir_recursive($path,$follow_links=false)
996
 * Recursively remove a directory tree (rm -rf path)
997
 * This is for directories _only_
998
 */
999
function rmdir_recursive($path,$follow_links=false) {
1000
	$to_do = glob($path);
1001
	if(!is_array($to_do)) $to_do = array($to_do);
1002
	foreach($to_do as $workingdir) { // Handle wildcards by foreaching.
1003
		if(file_exists($workingdir)) {
1004
			if(is_dir($workingdir)) {
1005
				$dir = opendir($workingdir);
1006
				while ($entry = readdir($dir)) {
1007
					if (is_file("$workingdir/$entry") || ((!$follow_links) && is_link("$workingdir/$entry")))
1008
						unlink("$workingdir/$entry");
1009
					elseif (is_dir("$workingdir/$entry") && $entry!='.' && $entry!='..')
1010
						rmdir_recursive("$workingdir/$entry");
1011
				}
1012
				closedir($dir);
1013
				rmdir($workingdir);
1014
			} elseif (is_file($workingdir)) {
1015
				unlink($workingdir);
1016
			}
1017
               	}
1018
	}
1019
	return;
1020
}
1021

    
1022
/*
1023
 *     get_memory()
1024
 *     returns an array listing the amount of
1025
 *     memory installed in the hardware
1026
 *     [0]real and [1]available
1027
 */
1028
function get_memory() {
1029
	if(file_exists("cat /var/log/dmesg.boot")) {
1030
		$mem = `cat /var/log/dmesg.boot | grep memory`;
1031
		if (preg_match_all("/real memory  = .* \((.*) MB/", $mem, $matches))
1032
			$real = $matches[1];
1033
		if (preg_match_all("/avail memory = .* \((.*) MB/", $mem, $matches))
1034
			$avail = $matches[1];
1035
		return array($real[0],$avail[0]);
1036
	}
1037
	return array("64","64");
1038
}
1039

    
1040

    
1041
/*
1042
 *    safe_mkdir($path, $mode = 0755)
1043
 *    create directory if it doesn't already exist and isn't a file!
1044
 */
1045
function safe_mkdir($path, $mode=0755) {
1046
	global $g;
1047

    
1048
	/* cdrom is ro. */
1049
	if($g['platform'] == "cdrom")
1050
		return false;
1051
	
1052
	if (!is_file($path) && !is_dir($path))
1053
		return mkdir($path, $mode);
1054
	else
1055
		return false;
1056
}
1057

    
1058
/*
1059
 * make_dirs($path, $mode = 0755)
1060
 * create directory tree recursively (mkdir -p)
1061
 */
1062
function make_dirs($path, $mode = 0755) {
1063
	/* is dir already created? */
1064
	if(is_dir($path)) return;
1065
	/* create directory in question */
1066
	$to_create = explode("/", $path);
1067
	foreach($to_create as $tc) 
1068
	    if(!is_dir($tc))
1069
		safe_mkdir($path, $mode);
1070
}
1071

    
1072
/*
1073
 * check_firmware_version(): Check whether the current firmware installed is the most recently released.
1074
 */
1075
function check_firmware_version($tocheck = "all", $return_php = true) {
1076
        global $g, $config;
1077
	$xmlrpc_base_url = $g['xmlrpcbaseurl'];
1078
        $xmlrpc_path = $g['xmlrpcpath'];
1079
	$rawparams = array("firmware" => array("version" => trim(file_get_contents('/etc/version'))),
1080
			"kernel"   => array("version" => trim(file_get_contents('/etc/version_kernel'))),
1081
			"base"     => array("version" => trim(file_get_contents('/etc/version_base'))),
1082
			"platform" => trim(file_get_contents('/etc/platform'))
1083
		);
1084
	if($tocheck == "all") {
1085
		$params = $rawparams;
1086
	} else {
1087
		foreach($tocheck as $check) {
1088
			$params['check'] = $rawparams['check'];
1089
			$params['platform'] = $rawparams['platform'];
1090
		}
1091
	}
1092
	if($config['system']['firmware']['branch']) {
1093
		$params['branch'] = $config['system']['firmware']['branch'];
1094
	}
1095
	$xmlparams = php_value_to_xmlrpc($params);
1096
        $msg = new XML_RPC_Message('pfsense.get_firmware_version', array($xmlparams));
1097
        $cli = new XML_RPC_Client($xmlrpc_path, $xmlrpc_base_url);
1098
	//$cli->setDebug(1);
1099
	$resp = $cli->send($msg, 10);
1100
	if(!$resp or $resp->faultCode()) {
1101
		$raw_versions = false;
1102
	} else {
1103
		$raw_versions = XML_RPC_decode($resp->value());
1104
		$raw_versions["current"] = $params;
1105
	}
1106
	return $raw_versions;
1107
}
1108

    
1109
function get_disk_info() {
1110
        exec("df -h | grep -w '/' | awk '{ print $2, $3, $4, $5 }'", $diskout);
1111
        return explode(' ', $diskout[0]);
1112
        // $size, $used, $avail, $cap
1113
}
1114

    
1115
/****f* pfsense-utils/display_top_tabs
1116
 * NAME
1117
 *   display_top_tabs - display tabs with rounded edges
1118
 * INPUTS
1119
 *   $text	- array of tabs
1120
 * RESULT
1121
 *   null
1122
 ******/
1123
    function display_top_tabs($tab_array) {
1124
	    echo "<table cellpadding='0' cellspacing='0'>\n";
1125
	    echo " <tr height='1'>\n";
1126
	    $tabscounter = 0;
1127
	    foreach ($tab_array as $ta) {
1128
		    if($ta[1] == true) {
1129
			    echo "  <td bgcolor='#EEEEEE' onClick=\"document.location='{$ta[2]}'\"><div id='tabactive'></div></td>\n";
1130
		    } else {
1131
			    echo "  <td bgcolor='#777777' onClick=\"document.location='{$ta[2]}'\"><div id='tabdeactive{$tabscounter}'></div></td>\n";
1132
		    }
1133
		    $tabscounter++;
1134
	    }
1135
	    echo "</tr>\n<tr>\n";
1136
	    foreach ($tab_array as $ta) {
1137
		    if($ta[1] == true) {
1138
			    echo "  <td bgcolor='#EEEEEE' onClick=\"document.location='{$ta[2]}'\"><B>&nbsp;&nbsp;&nbsp;{$ta[0]}";
1139
			    echo "&nbsp;&nbsp;&nbsp;";
1140
			    echo "<font size='-12'>&nbsp;</td>\n";
1141
		    } else {
1142
			    echo "  <td bgcolor='#777777' onClick=\"document.location='{$ta[2]}'\"><B>&nbsp;&nbsp;&nbsp;<a href='{$ta[2]}'>";
1143
			    echo "<font color='white'>{$ta[0]}</a>&nbsp;&nbsp;&nbsp;";
1144
			    echo "<font size='-12'>&nbsp;</td>\n";
1145
		    }
1146
	    }
1147
	    echo "</tr>\n<tr height='5px'>\n";
1148
	    foreach ($tab_array as $ta) {
1149
		    if($ta[1] == true) {
1150
			    echo "  <td bgcolor='#EEEEEE' onClick=\"document.location='{$ta[2]}'\"></td>\n";
1151
		    } else {
1152
			    echo "  <td bgcolor='#777777' onClick=\"document.location='{$ta[2]}'\"></td>\n";
1153
		    }
1154
		    $tabscounter++;
1155
	    }
1156
	    echo " </tr>\n";
1157
	    echo "</table>\n";
1158
	    
1159
	    echo "<script type=\"text/javascript\">";
1160
	    echo "NiftyCheck();\n";
1161
	    echo "Rounded(\"div#tabactive\",\"top\",\"#FFF\",\"#EEEEEE\",\"smooth\");\n";
1162
	    for($x=0; $x<$tabscounter; $x++) 
1163
		    echo "Rounded(\"div#tabdeactive{$x}\",\"top\",\"#FFF\",\"#777777\",\"smooth\");\n";
1164
	    echo "</script>";
1165
    }
1166

    
1167

    
1168
/****f* pfsense-utils/display_topbar
1169
 * NAME
1170
 *   display_topbar - top a table off with rounded edges
1171
 * INPUTS
1172
 *   $text	- (optional) Text to include in bar
1173
 * RESULT
1174
 *   null
1175
 ******/
1176
function display_topbar($text = "", $bg_color="#990000", $replace_color="#FFFFFF", $rounding_style="smooth") {	    
1177
	echo "     <table width='100%' cellpadding='0' cellspacing='0'>\n";
1178
	echo "       <tr height='1'>\n";
1179
	echo "         <td width='100%' valign='top' color='{$bg_color}' bgcolor='{$bg_color}'>";
1180
	echo "		<div id='topbar'></div></td>\n";
1181
	echo "       </tr>\n";
1182
	echo "       <tr height='1'>\n";
1183
	if ($text != "")
1184
		echo "         <td height='1' class='listtopic'>{$text}</td>\n";
1185
	else
1186
		echo "         <td height='1' class='listtopic'></td>\n";
1187
	echo "       </tr>\n";
1188
	echo "     </table>";
1189
	echo "<script type=\"text/javascript\">";
1190
	echo "NiftyCheck();\n";
1191
	echo "Rounded(\"div#topbar\",\"top\",\"{$replace_color}\",\"{$bg_color}\",\"{$rounding_style}\");\n";
1192
	echo "</script>";
1193
}
1194

    
1195
/****f* pfsense-utils/generate_random_mac_address
1196
 * NAME
1197
 *   generate_random_mac - generates a random mac address
1198
 * INPUTS
1199
 *   none
1200
 * RESULT
1201
 *   $mac - a random mac address
1202
 ******/
1203
function generate_random_mac_address() {
1204
	$mac = "00:a0:8e";
1205
	for($x=0; $x<3; $x++) 
1206
	    $mac .= ":" . dechex(rand(16, 255));
1207

    
1208
	return $mac;
1209
}
1210

    
1211
/****f* pfsense-utils/strncpy
1212
 * NAME
1213
 *   strncpy - copy strings
1214
 * INPUTS
1215
 *   &$dst, $src, $length
1216
 * RESULT
1217
 *   none
1218
 ******/
1219
function strncpy(&$dst, $src, $length) {
1220
	if (strlen($src) > $length) {
1221
		$dst = substr($src, 0, $length);
1222
	} else {
1223
		$dst = $src;
1224
	}
1225
}
1226

    
1227
/****f* pfsense-utils/reload_interfaces_sync
1228
 * NAME
1229
 *   reload_interfaces - reload all interfaces
1230
 * INPUTS
1231
 *   none
1232
 * RESULT
1233
 *   none
1234
 ******/
1235
function reload_interfaces_sync() {
1236
	global $config, $g;
1237
	
1238
	if(file_exists("{$g['tmp_path']}/config.cache"))
1239
		unlink("{$g['tmp_path']}/config.cache");
1240
	
1241
	/* parse config.xml again */
1242
	$config = parse_config(true);
1243

    
1244
	/* delete all old interface information */
1245
	$iflist = split(" ", str_replace("\n", "", `/sbin/ifconfig -l`));
1246
	foreach ($iflist as $ifent => $ifname) {
1247
		$ifname_real = convert_friendly_interface_to_real_interface_name($ifname);
1248
		mwexec("/sbin/ifconfig {$ifname_real} down");
1249
		mwexec("/sbin/ifconfig {$ifname_real} delete");
1250
	}
1251

    
1252
	/* set up LAN interface */
1253
	interfaces_lan_configure();
1254

    
1255
	/* set up WAN interface */
1256
	interfaces_wan_configure();
1257

    
1258
	/* set up Optional interfaces */
1259
	interfaces_optional_configure();
1260
        
1261
	/* set up static routes */
1262
	system_routing_configure();
1263
	
1264
	/* enable routing */
1265
	system_routing_enable();
1266
	
1267
	/* setup captive portal if needed */
1268
	captiveportal_configure();	
1269
}
1270

    
1271
/****f* pfsense-utils/reload_all
1272
 * NAME
1273
 *   reload_all - triggers a reload of all settings
1274
 *   * INPUTS
1275
 *   none
1276
 * RESULT
1277
 *   none
1278
 ******/
1279
function reload_all() {
1280
	touch("/tmp/reload_all");
1281
}
1282

    
1283
/****f* pfsense-utils/reload_interfaces
1284
 * NAME
1285
 *   reload_interfaces - triggers a reload of all interfaces
1286
 * INPUTS
1287
 *   none
1288
 * RESULT
1289
 *   none
1290
 ******/
1291
function reload_interfaces() {
1292
	touch("/tmp/reload_interfaces");
1293
}
1294

    
1295
/****f* pfsense-utils/sync_webgui_passwords
1296
 * NAME
1297
 *   sync_webgui_passwords - syncs webgui and ssh passwords
1298
 * INPUTS
1299
 *   none
1300
 * RESULT
1301
 *   none
1302
 ******/
1303
function sync_webgui_passwords() {
1304
	global $config, $g;
1305
	conf_mount_rw();
1306
	$fd = fopen("{$g['varrun_path']}/htpasswd", "w");
1307
	if (!$fd) {
1308
		printf("Error: cannot open htpasswd in system_password_configure().\n");
1309
		return 1;
1310
	}
1311
	/* set admin account */
1312
	$username = $config['system']['username'];
1313
	
1314
	/* set defined user account */
1315
	if($username <> "admin") {
1316
		$username = $config['system']['username'];
1317
		fwrite($fd, $username . ":" . $config['system']['password'] . "\n");
1318
	} else {
1319
		fwrite($fd, $username . ":" . $config['system']['password'] . "\n");	
1320
	}	
1321
	fclose($fd);
1322
	chmod("{$g['varrun_path']}/htpasswd", 0600);	
1323
	$crypted_pw = $config['system']['password'];
1324
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
1325
	mwexec("/usr/sbin/pwd_mkdb /etc/master.passwd");
1326
	/* sync root */
1327
	$fd = popen("/usr/sbin/pw usermod -n root -H 0", "w");
1328
	fwrite($fd, $crypted_pw);
1329
	pclose($fd);
1330
	mwexec("/usr/sbin/pw usermod -n root -s /bin/sh");
1331
	/* sync admin */
1332
	$fd = popen("/usr/sbin/pw usermod -n admin -H 0", "w");
1333
	fwrite($fd, $crypted_pw);
1334
	pclose($fd);
1335
	mwexec("/usr/sbin/pw usermod -n admin -s /etc/rc.initial");
1336
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
1337
	mwexec("/usr/sbin/pwd_mkdb /etc/master.passwd");
1338
	conf_mount_ro();
1339
}
1340

    
1341
/****f* pfsense-utils/reload_all_sync
1342
 * NAME
1343
 *   reload_all - reload all settings
1344
 *   * INPUTS
1345
 *   none
1346
 * RESULT
1347
 *   none
1348
 ******/
1349
function reload_all_sync() {
1350
	global $config, $g;
1351
	
1352
	if(file_exists("{$g['tmp_path']}/config.cache"))
1353
		unlink("{$g['tmp_path']}/config.cache");
1354
	
1355
	/* parse config.xml again */
1356
	$config = parse_config(true);
1357

    
1358
	/* set up our timezone */
1359
	system_timezone_configure();
1360

    
1361
	/* set up our hostname */
1362
	system_hostname_configure();
1363

    
1364
	/* make hosts file */
1365
	system_hosts_generate();
1366

    
1367
	/* generate resolv.conf */
1368
	system_resolvconf_generate();
1369

    
1370
	/* delete all old interface information */
1371
	$iflist = split(" ", str_replace("\n", "", `/sbin/ifconfig -l`));
1372
	foreach ($iflist as $ifent => $ifname) {
1373
		$ifname_real = convert_friendly_interface_to_real_interface_name($ifname);
1374
		mwexec("/sbin/ifconfig {$ifname_real} down");
1375
		mwexec("/sbin/ifconfig {$ifname_real} delete");
1376
	}
1377

    
1378
	/* set up LAN interface */
1379
	interfaces_lan_configure();
1380

    
1381
	/* set up WAN interface */
1382
	interfaces_wan_configure();
1383

    
1384
	/* set up Optional interfaces */
1385
	interfaces_optional_configure();
1386
        
1387
	/* bring up carp interfaces */
1388
	interfaces_carp_configure();
1389
	
1390
	/* set up static routes */
1391
	system_routing_configure();
1392

    
1393
	/* enable routing */
1394
	system_routing_enable();
1395
	
1396
	/* ensure passwords are sync'd */
1397
	system_password_configure();
1398

    
1399
	/* start dnsmasq service */
1400
	services_dnsmasq_configure();
1401

    
1402
	/* start dyndns service */
1403
	services_dyndns_configure();
1404

    
1405
	/* start DHCP service */
1406
	services_dhcpd_configure();
1407

    
1408
	/* start the NTP client */
1409
	system_ntp_configure();
1410

    
1411
	/* start ftp proxy helpers if they are enabled */
1412
	system_start_ftp_helpers();
1413
	
1414
	/* start the captive portal */
1415
	captiveportal_configure();
1416

    
1417
        /* reload the filter */
1418
	filter_configure_sync();
1419

    
1420
	/* bring up carp interfaces*/
1421
	interfaces_carp_bring_up_final();
1422

    
1423
	/* sync pw database */
1424
	conf_mount_rw();
1425
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
1426
	conf_mount_ro();
1427

    
1428
	/* restart sshd */
1429
	touch("/tmp/start_sshd");
1430
	
1431
}
1432

    
1433
?>
(14-14/26)