Project

General

Profile

Download (40 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, $config;
124
    if(isset($config['system']['do_not_use_nic_microcode']))
125
	return;
126
    if($g['booting']) {
127
	/* translate wan, lan, opt -> real interface if needed */
128
	$int = filter_translate_type_to_real_interface($interface);
129
	if(stristr($int,"lnc"))
130
		return;    	
131
	if($int <> "") $interface = $int;
132
        $int_family = preg_split("/[0-9]+/", $int);
133
	$options = strtolower(`/sbin/ifconfig {$interface} | grep options`);
134
	echo $interface . " ";
135
	$supported_ints = array('fxp');
136
	if (in_array($int_family, $supported_ints))
137
		mwexec("/sbin/ifconfig {$interface} link0");
138
	if(stristr($options, "txcsum") == true)
139
	    mwexec("/sbin/ifconfig {$interface} txcsum 2>/dev/null");
140
	if(stristr($options, "rxcsum") == true)    
141
	    mwexec("/sbin/ifconfig {$interface} rxcsum 2>/dev/null");    
142
	if(stristr($options, "polling") == true)
143
	    mwexec("/sbin/ifconfig {$interface} polling 2>/dev/null");
144
    }
145
    return;
146
}
147

    
148
/****f* pfsense-utils/setup_polling_defaults
149
 * NAME
150
 *   sets up sysctls for pollingS
151
 * INPUTS
152
 *   
153
 * RESULT
154
 *   null
155
 * NOTES
156
 *   
157
 ******/
158
function setup_polling_defaults() {
159
	global $g, $config;
160
	if($config['system']['polling_each_burst'])
161
		mwexec("sysctl kern.polling.each_burst={$config['system']['polling_each_burst']}");
162
	if($config['system']['polling_burst_max'])
163
		mwexec("sysctl kern.polling.burst_max={$config['system']['polling_burst_max']}");
164
	if($config['system']['polling_user_frac'])
165
		mwexec("sysctl kern.polling.user_frac={$config['system']['polling_user_frac']}");		
166
}
167

    
168
/****f* pfsense-utils/setup_polling
169
 * NAME
170
 *   sets up polling
171
 * INPUTS
172
 *   
173
 * RESULT
174
 *   null
175
 * NOTES
176
 *   
177
 ******/
178
function setup_polling() {
179
	setup_polling_defaults();
180
	global $g, $config;
181
	/* build an array of interfaces to work with */
182
	$iflist = array("lan" => "LAN", "wan" => "WAN");
183
	for ($i = 1; isset($config['interfaces']['opt' . $i]); $i++) 
184
	$iflist['opt' . $i] = $config['interfaces']['opt' . $i]['descr'];		
185
	/*    activate polling for interface if it supports it
186
	 *    man polling on a freebsd box for the following list
187
	 */
188
	/* loop through all interfaces and handle pftpx redirections */
189
	foreach ($iflist as $ifent => $ifname) {	
190
		$supported_ints = array('dc', 'em', 'fwe', 'fwip', 'fxp', 'ixgb', 'ste',
191
			'nge', 're', 'rl', 'sf', 'sis', 'ste', 'vge', 'vr', 'xl');
192
		if (in_array($int_family, $supported_ints) and isset($config['system']['polling'])) {
193
			mwexec("/sbin/ifconfig {$interface} polling");
194
		} else {
195
			mwexec("/sbin/ifconfig {$interface} -polling");
196
		}
197
	}
198
}
199

    
200
/****f* pfsense-utils/setup_microcode
201
 * NAME
202
 *   enumerates all interfaces and calls enable_hardware_offloading which
203
 *   enables a NIC's supported hardware features.
204
 * INPUTS
205
 *   
206
 * RESULT
207
 *   null
208
 * NOTES
209
 *   This function only supports the fxp driver's loadable microcode.
210
 ******/
211
function setup_microcode() {
212
   global $config;
213
    $ifdescrs = array('wan', 'lan');
214
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) {
215
	$ifdescrs['opt' . $j] = "opt" . $j;
216
    }
217
    foreach($ifdescrs as $if)
218
	enable_hardware_offloading($if);
219
}
220

    
221
/****f* pfsense-utils/return_filename_as_array
222
 * NAME
223
 *   return_filename_as_array - Return a file's contents as an array.
224
 * INPUTS
225
 *   $filename	- string containing the path to the desired file.
226
 *   $strip	- array of characters to strip - default is '#'.
227
 * RESULT
228
 *   $file	- array containing the file's contents.
229
 * NOTES
230
 *   This function strips lines starting with '#' and leading/trailing whitespace by default.
231
 ******/
232
function return_filename_as_array($filename, $strip = array('#')) {
233
    if(file_exists($filename)) $file = file($filename);
234
    if(is_array($file)) {
235
	foreach($file as $line) $line = trim($line);
236
        foreach($strip as $tostrip) $file = preg_grep("/^{$tostrip}/", $file, PREG_GREP_INVERT);
237
    }
238
    return $file;
239
}
240

    
241
/****f* pfsense-utils/file_put_contents
242
 * NAME
243
 *   file_put_contents - Wrapper for file_put_contents if it doesn't exist
244
 * RESULT
245
 *   none
246
 ******/
247
if(!function_exists("file_put_contents")) {
248
    function file_put_contents($filename, $data) {
249
	$fd = fopen($filename,"w");
250
	fwrite($fd, $data);
251
	fclose($fd);
252
    }
253
}
254

    
255
/****f* pfsense-utils/get_carp_status
256
 * NAME
257
 *   get_carp_status - Return whether CARP is enabled or disabled.
258
 * RESULT
259
 *   boolean	- true if CARP is enabled, false if otherwise.
260
 ******/
261
function get_carp_status() {
262
    /* grab the current status of carp */
263
    $status = `/sbin/sysctl net.inet.carp.allow | cut -d" " -f2`;
264
    if(intval($status) == "0") return false;
265
    return true;
266
}
267

    
268
/****f* pfsense-utils/is_carp_defined
269
 * NAME
270
 *   is_carp_defined - Return whether CARP is detected in the kernel.
271
 * RESULT
272
 *   boolean	- true if CARP is detected, false otherwise.
273
 ******/
274
function is_carp_defined() {
275
    /* is carp compiled into the kernel and userland? */
276
    $command = "/sbin/sysctl -a | grep carp";
277
    $fd = popen($command . " 2>&1 ", "r");
278
    if(!$fd) {
279
	log_error("Warning, could not execute command {$command}");
280
	return 0;
281
    }
282
    while(!feof($fd)) {
283
	$tmp .= fread($fd,49);
284
    }
285
    fclose($fd);
286

    
287
    if($tmp == "")
288
	return false;
289
    else
290
	return true;
291
}
292

    
293
/****f* pfsense-utils/get_interface_mtu
294
 * NAME
295
 *   get_interface_mtu - Return the mtu of an interface
296
 * RESULT
297
 *   $tmp	- Returns the mtu of an interface
298
 ******/
299
function get_interface_mtu($interface) {
300
	$mtu = `/sbin/ifconfig {$interface} | /usr/bin/grep mtu | /usr/bin/cut -d" " -f4`;
301
	return $mtu;
302
}
303

    
304
/****f* pfsense-utils/find_number_of_created_carp_interfaces
305
 * NAME
306
 *   find_number_of_created_carp_interfaces - Return the number of CARP interfaces.
307
 * RESULT
308
 *   $tmp	- Number of currently created CARP interfaces.
309
 ******/
310
function find_number_of_created_carp_interfaces() {
311
    $command = "/sbin/ifconfig | /usr/bin/grep \"carp*:\" | /usr/bin/wc -l";
312
    $fd = popen($command . " 2>&1 ", "r");
313
    if(!$fd) {
314
	log_error("Warning, could not execute command {$command}");
315
	return 0;
316
    }
317
    while(!feof($fd)) {
318
	$tmp .= fread($fd,49);
319
    }
320
    fclose($fd);
321
    $tmp = intval($tmp);
322
    return $tmp;
323
}
324

    
325
/****f* pfsense-utils/link_ip_to_carp_interface
326
 * NAME
327
 *   link_ip_to_carp_interface - Find where a CARP interface links to.
328
 * INPUTS
329
 *   $ip
330
 * RESULT
331
 *   $carp_ints
332
 ******/
333
function link_ip_to_carp_interface($ip) {
334
	global $config;
335
	if($ip == "") return;
336

    
337
	$ifdescrs = array('wan', 'lan');
338
	for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) {
339
		$ifdescrs['opt' . $j] = "opt" . $j;
340
	}
341

    
342
	$ft = split("\.", $ip);
343
	$ft_ip = $ft[0] . "." . $ft[1] . "." . $ft[2] . ".";
344

    
345
	$carp_ints = "";
346
	$num_carp_ints = find_number_of_created_carp_interfaces();
347
	foreach ($ifdescrs as $ifdescr => $ifname) {
348
		for($x=0; $x<$num_carp_ints; $x++) {
349
			$carp_int = "carp{$x}";
350
			$carp_ip = find_interface_ip($carp_int);
351
			$carp_ft = split("\.", $carp_ip);
352
			$carp_ft_ip = $carp_ft[0] . "." . $carp_ft[1] . "." . $carp_ft[2] . ".";
353
			$result = does_interface_exist($carp_int);
354
			if($result <> true) break;
355
			if($ft_ip == $carp_ft_ip)
356
			if(stristr($carp_ints,$carp_int) == false)
357
			$carp_ints .= " " . $carp_int;
358
		}
359
	}
360
	return $carp_ints;
361
}
362

    
363
/****f* pfsense-utils/exec_command
364
 * NAME
365
 *   exec_command - Execute a command and return a string of the result.
366
 * INPUTS
367
 *   $command	- String of the command to be executed.
368
 * RESULT
369
 *   String containing the command's result.
370
 * NOTES
371
 *   This function returns the command's stdout and stderr.
372
 ******/
373
function exec_command($command) {
374
    $output = array();
375
    exec($command . ' 2>&1 ', $output);
376
    return(implode("\n", $output));
377
}
378

    
379
/****f* interfaces/is_jumbo_capable
380
 * NAME
381
 *   is_jumbo_capable - Test if interface is jumbo frame capable.  Useful for determining VLAN capability.
382
 * INPUTS
383
 *   $int             - string containing interface name
384
 * RESULT
385
 *   boolean          - true or false
386
 ******/
387
function is_jumbo_capable($int) {
388
	/* Per:
389
	 * http://www.freebsd.org/cgi/man.cgi?query=vlan&manpath=FreeBSD+6.0-current&format=html
390
	 * Only the following drivers support large frames
391
	 */
392
	$capable = array("bfe", "dc", "de", "fxp", "hme", "rl", "sis", "ste",
393
		"tl", "tx", "xl", "em");
394
	
395
	$int_family = preg_split("/[0-9]+/", $int);
396

    
397
	if (in_array($int_family[0], $capable))
398
		return true;
399
	else
400
		return false;
401
}
402

    
403
/*
404
 * does_interface_exist($interface): return true or false if a interface is detected.
405
 */
406
function does_interface_exist($interface) {
407
    $ints = exec_command("/sbin/ifconfig -l");
408
    if(stristr($ints, $interface) !== false)
409
	return true;
410
    else
411
	return false;
412
}
413

    
414
/*
415
 * convert_ip_to_network_format($ip, $subnet): converts an ip address to network form
416
 */
417
function convert_ip_to_network_format($ip, $subnet) {
418
    $ipsplit = split('[.]', $ip);
419
    $string = $ipsplit[0] . "." . $ipsplit[1] . "." . $ipsplit[2] . ".0/" . $subnet;
420
    return $string;
421
}
422

    
423
/*
424
 * find_interface_ip($interface): return the interface ip (first found)
425
 */
426
function find_interface_ip($interface) {
427
    if(does_interface_exist($interface) == false) return;
428
    $ip = exec_command("/sbin/ifconfig {$interface} | /usr/bin/grep -w \"inet\" | /usr/bin/cut -d\" \" -f 2");
429
    $ip = str_replace("\n","",$ip);
430
    return $ip;
431
}
432

    
433
function guess_interface_from_ip($ipaddress) {
434
    $ints = `/sbin/ifconfig -l`;
435
    $ints_split = split(" ", $ints);
436
    $ip_subnet_split = split("\.", $ipaddress);
437
    $ip_subnet = $ip_subnet_split[0] . "." . $ip_subnet_split[1] . "." . $ip_subnet_split[2] . ".";
438
    foreach($ints_split as $int) {
439
        $ip = find_interface_ip($int);
440
        $ip_split = split("\.", $ip);
441
        $ip_tocheck = $ip_split[0] . "." . $ip_split[1] . "." . $ip_split[2] . ".";
442
        if(stristr($ip_tocheck, $ip_subnet) != false) return $int;
443
    }
444
}
445

    
446
function filter_opt_interface_to_real($opt) {
447
    global $config;
448
    return $config['interfaces'][$opt]['if'];
449
}
450

    
451
function filter_get_opt_interface_descr($opt) {
452
    global $config;
453
    return $config['interfaces'][$opt]['descr'];
454
}
455

    
456
function get_friendly_interface_list_as_array() {
457
    global $config;
458
    $ints = array();
459
    $ifdescrs = array('wan', 'lan');
460
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) {
461
		$ifdescrs['opt' . $j] = "opt" . $j;
462
    }
463
    $ifdescrs = get_interface_list();
464
    foreach ($ifdescrs as $ifdescr => $ifname) {
465
		array_push($ints,$ifdescr);
466
    }
467
    return $ints;
468
}
469

    
470
/*
471
 * find_ip_interface($ip): return the interface where an ip is defined
472
 */
473
function find_ip_interface($ip) {
474
    global $config;
475
    $ifdescrs = array('wan', 'lan');
476
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) {
477
	$ifdescrs['opt' . $j] = "opt" . $j;
478
    }
479
    foreach ($ifdescrs as $ifdescr => $ifname) {
480
	$int = filter_translate_type_to_real_interface($ifname);
481
	$ifconfig = exec_command("/sbin/ifconfig {$int}");
482
	if(stristr($ifconfig,$ip) <> false)
483
	    return $int;
484
    }
485
    return false;
486
}
487

    
488
/*
489
 *  filter_translate_type_to_real_interface($interface): returns the real interface name
490
 *                                                       for a friendly interface.  ie: wan
491
 */
492
function filter_translate_type_to_real_interface($interface) {
493
    global $config;
494
    if($config['interfaces'][$interface]['if'] <> "") {
495
	return $config['interfaces'][$interface]['if'];
496
    } else {
497
	return $interface;
498
    }
499
}
500

    
501
/*
502
 * get_carp_interface_status($carpinterface): returns the status of a carp ip
503
 */
504
function get_carp_interface_status($carpinterface) {
505
	/* basically cache the contents of ifconfig statement
506
	to speed up this routine */
507
	global $carp_query;
508
	if($carp_query == "")
509
	$carp_query = split("\n", `/sbin/ifconfig | /usr/bin/grep carp`);
510
	$found_interface = 0;
511
	foreach($carp_query as $int) {
512
		if($found_interface == 1) {
513
			if(stristr($int, "MASTER") == true) return "MASTER";
514
			if(stristr($int, "BACKUP") == true) return "BACKUP";
515
			if(stristr($int, "INIT") == true) return "INIT";
516
			return false;
517
		}
518
		if(stristr($int, $carpinterface) == true)
519
		$found_interface=1;
520
	}
521
	return;
522
}
523

    
524
/*
525
 * get_pfsync_interface_status($pfsyncinterface): returns the status of a pfsync
526
 */
527
function get_pfsync_interface_status($pfsyncinterface) {
528
    $result = does_interface_exist($pfsyncinterface);
529
    if($result <> true) return;
530
    $status = exec_command("/sbin/ifconfig {$pfsyncinterface} | /usr/bin/grep \"pfsync:\" | /usr/bin/cut -d\" \" -f5");
531
    return $status;
532
}
533

    
534
/*
535
 * find_carp_interface($ip): return the carp interface where an ip is defined
536
 */
537
function find_carp_interface($ip) {
538
    global $find_carp_ifconfig;
539
    if($find_carp_ifconfig == "") {
540
	$find_carp_ifconfig = array();
541
	$num_carp_ints = find_number_of_created_carp_interfaces();
542
	for($x=0; $x<$num_carp_ints; $x++) {
543
	    $find_carp_ifconfig[$x] = exec_command("/sbin/ifconfig carp{$x}");
544
	}
545
    }
546
    $carps = 0;
547
    foreach($find_carp_ifconfig as $fci) {
548
	if(stristr($fci, $ip) == true)
549
	    return "carp{$carps}";
550
	$carps++;
551
    }
552
}
553

    
554
/*
555
 * find_number_of_created_bridges(): returns the number of currently created bridges
556
 */
557
function find_number_of_created_bridges() {
558
    return `/sbin/ifconfig | grep \"bridge[0-999]\:" | wc -l`;
559
}
560

    
561
/*
562
 * add_rule_to_anchor($anchor, $rule): adds the specified rule to an anchor
563
 */
564
function add_rule_to_anchor($anchor, $rule, $label) {
565
    mwexec("echo " . $rule . " | /sbin/pfctl -a " . $anchor . ":" . $label . " -f -");
566
}
567

    
568
/*
569
 * remove_text_from_file
570
 * remove $text from file $file
571
 */
572
function remove_text_from_file($file, $text) {
573
    global $fd_log;
574
    fwrite($fd_log, "Adding needed text items:\n");
575
    $filecontents = exec_command_and_return_text("cat " . $file);
576
    $textTMP = str_replace($text, "", $filecontents);
577
    $text .= $textTMP;
578
    fwrite($fd_log, $text . "\n");
579
    $fd = fopen($file, "w");
580
    fwrite($fd, $text);
581
    fclose($fd);
582
}
583

    
584
/*
585
 * add_text_to_file($file, $text): adds $text to $file.
586
 * replaces the text if it already exists.
587
 */
588
function add_text_to_file($file, $text) {
589
	if(file_exists($file) and is_writable($file)) {
590
		$filecontents = file($file);
591
		$filecontents[] = $text;
592
		$tmpfile = get_tmp_file();
593
		$fout = fopen($tmpfile, "w");
594
		foreach($filecontents as $line) {
595
			fwrite($fout, rtrim($line) . "\n");
596
		}
597
		fclose($fout);
598
		rename($tmpfile, $file);
599
		return true;
600
	} else {
601
		return false;
602
	}
603
}
604

    
605
/*
606
 *   after_sync_bump_adv_skew(): create skew values by 1S
607
 */
608
function after_sync_bump_adv_skew() {
609
	global $config, $g;
610
	$processed_skew = 1;
611
	$a_vip = &$config['virtualip']['vip'];
612
	foreach ($a_vip as $vipent) {
613
		if($vipent['advskew'] <> "") {
614
			$processed_skew = 1;
615
			$vipent['advskew'] = $vipent['advskew']+1;
616
		}
617
	}
618
	if($processed_skew == 1)
619
		write_config("After synch increase advertising skew");
620
}
621

    
622
/*
623
 * get_filename_from_url($url): converts a url to its filename.
624
 */
625
function get_filename_from_url($url) {
626
	return basename($url);
627
}
628

    
629
/*
630
 *   update_output_window: update bottom textarea dynamically.
631
 */
632
function update_output_window($text) {
633
    $log = ereg_replace("\n", "\\n", $text);
634
    echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = \"" . $log . "\";</script>";
635
}
636

    
637
/*
638
 *   get_dir: return an array of $dir
639
 */
640
function get_dir($dir) {
641
    $dir_array = array();
642
    $d = dir($dir);
643
    while (false !== ($entry = $d->read())) {
644
	array_push($dir_array, $entry);
645
    }
646
    $d->close();
647
    return $dir_array;
648
}
649

    
650
/*
651
 *   update_output_window: update top textarea dynamically.
652
 */
653
function update_status($status) {
654
    echo "\n<script language=\"JavaScript\">document.forms[0].status.value=\"" . $status . "\";</script>";
655
}
656

    
657
/*
658
 *   exec_command_and_return_text_array: execute command and return output
659
 */
660
function exec_command_and_return_text_array($command) {
661
	$fd = popen($command . " 2>&1 ", "r");
662
	while(!feof($fd)) {
663
		$tmp .= fread($fd,49);
664
	}
665
	fclose($fd);
666
	$temp_array = split("\n", $tmp);
667
	return $temp_array;
668
}
669

    
670
/*
671
 *   exec_command_and_return_text: execute command and return output
672
 */
673
function exec_command_and_return_text($command) {
674
    return exec_command($command);
675
}
676

    
677
/*
678
 *   exec_command_and_return_text: execute command and update output window dynamically
679
 */
680
function execute_command_return_output($command) {
681
    global $fd_log;
682
    $fd = popen($command . " 2>&1 ", "r");
683
    echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = \"\";</script>";
684
    $counter = 0;
685
    $counter2 = 0;
686
    while(!feof($fd)) {
687
	$tmp = fread($fd, 50);
688
	$tmp1 = ereg_replace("\n","\\n", $tmp);
689
	$text = ereg_replace("\"","'", $tmp1);
690
	if($lasttext == "..") {
691
	    $text = "";
692
	    $lasttext = "";
693
	    $counter=$counter-2;
694
	} else {
695
	    $lasttext .= $text;
696
	}
697
	if($counter > 51) {
698
	    $counter = 0;
699
	    $extrabreak = "\\n";
700
	} else {
701
	    $extrabreak = "";
702
	    $counter++;
703
	}
704
	if($counter2 > 600) {
705
	    echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = \"\";</script>";
706
	    $counter2 = 0;
707
	} else
708
	    $counter2++;
709
	echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = this.document.forms[0].output.value + \"" . $text . $extrabreak .  "\"; f('output'); </script>";
710
    }
711
    fclose($fd);
712
}
713

    
714
/*
715
 * convert_friendly_interface_to_real_interface_name($interface): convert WAN to FXP0
716
 */
717
function convert_friendly_interface_to_real_interface_name($interface) {
718
    global $config;
719
    $lc_interface = strtolower($interface);
720
    if($lc_interface == "lan") return $config['interfaces']['lan']['if'];
721
    if($lc_interface == "wan") return $config['interfaces']['wan']['if'];
722
    $ifdescrs = array();
723
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++)
724
	$ifdescrs['opt' . $j] = "opt" . $j;
725
    foreach ($ifdescrs as $ifdescr => $ifname) {
726
	if(strtolower($ifname) == $lc_interface)
727
	    return $config['interfaces'][$ifname]['if'];
728
	if(strtolower($config['interfaces'][$ifname]['descr']) == $lc_interface)
729
	    return $config['interfaces'][$ifname]['if'];
730
    }
731
    return $interface;
732
}
733

    
734
/*
735
 * convert_real_interface_to_friendly_interface_name($interface): convert fxp0 -> wan, etc.
736
 */
737
function convert_real_interface_to_friendly_interface_name($interface) {
738
    global $config;
739
    $ifdescrs = array('wan', 'lan');
740
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++)
741
	$ifdescrs['opt' . $j] = "opt" . $j;
742
    foreach ($ifdescrs as $ifdescr => $ifname) {
743
	$int = filter_translate_type_to_real_interface($ifname);
744
	if($ifname == $interface) return $ifname;
745
	if($int == $interface) return $ifname;
746
    }
747
    return $interface;
748
}
749

    
750
/*
751
 * update_progress_bar($percent): updates the javascript driven progress bar.
752
 */
753
function update_progress_bar($percent) {
754
    if($percent > 100) $percent = 1;
755
    echo "\n<script type=\"text/javascript\" language=\"javascript\">";
756
    echo "\ndocument.progressbar.style.width='" . $percent . "%';";
757
    echo "\n</script>";
758
}
759

    
760
/*
761
 * gather_altq_queue_stats():  gather alq queue stats and return an array that
762
 *                             is queuename|qlength|measured_packets
763
 *                             NOTE: this command takes 5 seconds to run
764
 */
765
function gather_altq_queue_stats($dont_return_root_queues) {
766
    mwexec("/usr/bin/killall -9 pfctl");
767
    $stats = `/sbin/pfctl -vvsq & /bin/sleep 5;/usr/bin/killall pfctl 2>/dev/null`;
768
    $stats_array = split("\n", $stats);
769
    $queue_stats = array();
770
    foreach ($stats_array as $stats_line) {
771
        if (preg_match_all("/queue\s+(\w+)\s+/",$stats_line,$match_array))
772
            $queue_name = $match_array[1][0];
773
        if (preg_match_all("/measured:\s+.*packets\/s\,\s(.*)\s+\]/",$stats_line,$match_array))
774
            $speed = $match_array[1][0];
775
        if (preg_match_all("/borrows:\s+(.*)/",$stats_line,$match_array))
776
            $borrows = $match_array[1][0];
777
        if (preg_match_all("/suspends:\s+(.*)/",$stats_line,$match_array))
778
            $suspends = $match_array[1][0];
779
        if (preg_match_all("/dropped pkts:\s+(.*)/",$stats_line,$match_array))
780
            $drops = $match_array[1][0];
781
        if (preg_match_all("/measured:\s+(.*)packets/",$stats_line,$match_array)) {
782
            $measured = $match_array[1][0];
783
	    if($dont_return_root_queues == true)
784
		if(stristr($queue_name,"root_") == false)
785
		    array_push($queue_stats, "{$queue_name}|{$speed}|{$measured}|{$borrows}|{$suspends}|{$drops}");
786
        }
787
    }
788
    return $queue_stats;
789
}
790

    
791
/*
792
 * reverse_strrchr($haystack, $needle):  Return everything in $haystack up to the *last* instance of $needle.
793
 *					 Useful for finding paths and stripping file extensions.
794
 */
795
function reverse_strrchr($haystack, $needle)
796
{
797
               return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) +1 ) : false;
798
}
799

    
800
/*
801
 *  backup_config_section($section): returns as an xml file string of
802
 *                                   the configuration section
803
 */
804
function backup_config_section($section) {
805
    global $config;
806
    $new_section = &$config[$section];
807
    /* generate configuration XML */
808
    $xmlconfig = dump_xml_config($new_section, $section);
809
    $xmlconfig = str_replace("<?xml version=\"1.0\"?>", "", $xmlconfig);
810
    return $xmlconfig;
811
}
812

    
813
/*
814
 *  backup_config_ts_scheduler(): returns the traffic shaper scheduler for backup
815
 */
816
function backup_config_ts_scheduler() {
817
    global $config;
818
    $new_section = &$config['syste']['schedulertype'];
819
    /* generate configuration XML */
820
    $xmlconfig = dump_xml_config($new_section, $section);
821
    $xmlconfig = str_replace("<?xml version=\"1.0\"?>", "", $xmlconfig);
822
    return $xmlconfig;
823
}
824

    
825
/*
826
 *  backup_config_section($section): returns as an xml file string of
827
 *                                   the configuration section
828
 */
829
function backup_vip_config_section() {
830
    global $config;
831
    $new_section = &$config['virtualip'];
832
    foreach($new_section['vip'] as $section) {
833
	if($section['mode'] == "proxyarp") {
834
		unset($section);		
835
	}
836
	if($section['advskew'] <> "") {
837
		$section_val = intval($section['advskew']);
838
		$section_val=$section_val+100;
839
		if($section_val > 255)
840
			$section_val = 255;
841
		$section['advskew'] = $section_val;
842
	}
843
	$temp['vip'][] = $section;
844
    }
845
    return $temp;
846
}
847

    
848
/*
849
 *  restore_config_section($section, new_contents): restore a configuration section,
850
 *                                                  and write the configuration out
851
 *                                                  to disk/cf.
852
 */
853
function restore_config_section($section, $new_contents) {
854
    global $config;
855
    conf_mount_rw();
856
    $fout = fopen("{$g['tmp_path']}/tmpxml","w");
857
    fwrite($fout, $new_contents);
858
    fclose($fout);
859
    $section_xml = parse_xml_config($g['tmp_path'] . "/tmpxml", $section);
860
    $config[$section] = &$section_xml;
861
    unlink($g['tmp_path'] . "/tmpxml");
862
    write_config("Restored {$section} of config file (maybe from CARP partner)");
863
    conf_mount_ro();
864
    return;
865
}
866

    
867
/*
868
 * http_post($server, $port, $url, $vars): does an http post to a web server
869
 *                                         posting the vars array.
870
 * written by nf@bigpond.net.au
871
 */
872
function http_post($server, $port, $url, $vars) {
873
    $user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)";
874
    $urlencoded = "";
875
    while (list($key,$value) = each($vars))
876
	$urlencoded.= urlencode($key) . "=" . urlencode($value) . "&";
877
    $urlencoded = substr($urlencoded,0,-1);
878

    
879
    $content_length = strlen($urlencoded);
880

    
881
    $headers = "POST $url HTTP/1.1
882
Accept: */*
883
Accept-Language: en-au
884
Content-Type: application/x-www-form-urlencoded
885
User-Agent: $user_agent
886
Host: $server
887
Connection: Keep-Alive
888
Cache-Control: no-cache
889
Content-Length: $content_length
890

    
891
";
892

    
893
    $fp = fsockopen($server, $port, $errno, $errstr);
894
    if (!$fp) {
895
	return false;
896
    }
897

    
898
    fputs($fp, $headers);
899
    fputs($fp, $urlencoded);
900

    
901
    $ret = "";
902
    while (!feof($fp))
903
	$ret.= fgets($fp, 1024);
904

    
905
    fclose($fp);
906

    
907
    return $ret;
908

    
909
}
910

    
911
/*
912
 *  php_check_syntax($code_tocheck, $errormessage): checks $code_to_check for errors
913
 */
914
if (!function_exists('php_check_syntax')){
915
   function php_check_syntax($code_to_check, &$errormessage){
916
	return false;
917
        $fout = fopen("/tmp/codetocheck.php","w");
918
        $code = $_POST['content'];
919
        $code = str_replace("<?php", "", $code);
920
        $code = str_replace("?>", "", $code);
921
        fwrite($fout, "<?php\n\n");
922
        fwrite($fout, $code_to_check);
923
        fwrite($fout, "\n\n?>\n");
924
        fclose($fout);
925
        $command = "/usr/local/bin/php -l /tmp/codetocheck.php";
926
        $output = exec_command($command);
927
        if (stristr($output, "Errors parsing") == false) {
928
            echo "false\n";
929
            $errormessage = '';
930
            return(false);
931
        } else {
932
            $errormessage = $output;
933
            return(true);
934
        }
935
    }
936
}
937

    
938
/*
939
 *  php_check_filename_syntax($filename, $errormessage): checks the file $filename for errors
940
 */
941
if (!function_exists('php_check_syntax')){
942
   function php_check_syntax($code_to_check, &$errormessage){
943
	return false;
944
        $command = "/usr/local/bin/php -l " . $code_to_check;
945
        $output = exec_command($command);
946
        if (stristr($output, "Errors parsing") == false) {
947
            echo "false\n";
948
            $errormessage = '';
949
            return(false);
950
        } else {
951
            $errormessage = $output;
952
            return(true);
953
        }
954
    }
955
}
956

    
957
/*
958
 * rmdir_recursive($path,$follow_links=false)
959
 * Recursively remove a directory tree (rm -rf path)
960
 * This is for directories _only_
961
 */
962
function rmdir_recursive($path,$follow_links=false) {
963
	$to_do = glob($path);
964
	if(!is_array($to_do)) $to_do = array($to_do);
965
	foreach($to_do as $workingdir) { // Handle wildcards by foreaching.
966
		if(file_exists($workingdir)) {
967
			if(is_dir($workingdir)) {
968
				$dir = opendir($workingdir);
969
				while ($entry = readdir($dir)) {
970
					if (is_file("$workingdir/$entry") || ((!$follow_links) && is_link("$workingdir/$entry")))
971
						unlink("$workingdir/$entry");
972
					elseif (is_dir("$workingdir/$entry") && $entry!='.' && $entry!='..')
973
						rmdir_recursive("$workingdir/$entry");
974
				}
975
				closedir($dir);
976
				rmdir($workingdir);
977
			} elseif (is_file($workingdir)) {
978
				unlink($workingdir);
979
			}
980
               	}
981
	}
982
	return;
983
}
984

    
985
/*
986
 *     get_memory()
987
 *     returns an array listing the amount of
988
 *     memory installed in the hardware
989
 *     [0]real and [1]available
990
 */
991
function get_memory() {
992
        $mem = `cat /var/log/dmesg.boot | grep memory`;
993
        if (preg_match_all("/real memory  = .* \((.*) MB/", $mem, $matches))
994
                $real = $matches[1];
995
        if (preg_match_all("/avail memory = .* \((.*) MB/", $mem, $matches))
996
                $avail = $matches[1];
997
        return array($real[0],$avail[0]);
998
}
999

    
1000

    
1001
/*
1002
 *    safe_mkdir($path, $mode = 0755)
1003
 *    create directory if it doesn't already exist and isn't a file!
1004
 */
1005
function safe_mkdir($path, $mode=0755) {
1006
	global $g;
1007

    
1008
	/* cdrom is ro. */
1009
	if($g['platform'] == "cdrom")
1010
		return false;
1011
	
1012
	if (!is_file($path) && !is_dir($path))
1013
		return mkdir($path, $mode);
1014
	else
1015
		return false;
1016
}
1017

    
1018
/*
1019
 * make_dirs($path, $mode = 0755)
1020
 * create directory tree recursively (mkdir -p)
1021
 */
1022
function make_dirs($path, $mode = 0755) {
1023
	/* is dir already created? */
1024
	if(is_dir($path)) return;
1025
	/* create directory in question */
1026
	$to_create = explode("/", $path);
1027
	foreach($to_create as $tc) 
1028
	    if(!is_dir($tc))
1029
		safe_mkdir($path, $mode);
1030
}
1031

    
1032
/*
1033
 * check_firmware_version(): Check whether the current firmware installed is the most recently released.
1034
 */
1035
function check_firmware_version($tocheck = "all", $return_php = true) {
1036
        global $g, $config;
1037
	$xmlrpc_base_url = $g['xmlrpcbaseurl'];
1038
        $xmlrpc_path = $g['xmlrpcpath'];
1039
	$rawparams = array("firmware" => array("version" => trim(file_get_contents('/etc/version'))),
1040
			"kernel"   => array("version" => trim(file_get_contents('/etc/version_kernel'))),
1041
			"base"     => array("version" => trim(file_get_contents('/etc/version_base'))),
1042
			"platform" => trim(file_get_contents('/etc/platform'))
1043
		);
1044
	if($tocheck == "all") {
1045
		$params = $rawparams;
1046
	} else {
1047
		foreach($tocheck as $check) {
1048
			$params['check'] = $rawparams['check'];
1049
			$params['platform'] = $rawparams['platform'];
1050
		}
1051
	}
1052
	if($config['system']['firmware']['branch']) {
1053
		$params['branch'] = $config['system']['firmware']['branch'];
1054
	}
1055
	$xmlparams = php_value_to_xmlrpc($params);
1056
        $msg = new XML_RPC_Message('pfsense.get_firmware_version', array($xmlparams));
1057
        $cli = new XML_RPC_Client($xmlrpc_path, $xmlrpc_base_url);
1058
	//$cli->setDebug(1);
1059
	$resp = $cli->send($msg, 10);
1060
	if(!$resp or $resp->faultCode()) {
1061
		$raw_versions = false;
1062
	} else {
1063
		$raw_versions = XML_RPC_decode($resp->value());
1064
		$raw_versions["current"] = $params;
1065
	}
1066
	return $raw_versions;
1067
}
1068

    
1069
function get_disk_info() {
1070
        exec("df -h | grep -w '/' | awk '{ print $2, $3, $4, $5 }'", $diskout);
1071
        return explode(' ', $diskout[0]);
1072
        // $size, $used, $avail, $cap
1073
}
1074

    
1075
/****f* pfsense-utils/display_top_tabs
1076
 * NAME
1077
 *   display_top_tabs - display tabs with rounded edges
1078
 * INPUTS
1079
 *   $text	- array of tabs
1080
 * RESULT
1081
 *   null
1082
 ******/
1083
    function display_top_tabs($tab_array) {
1084
	    echo "<table cellpadding='0' cellspacing='0'>\n";
1085
	    echo " <tr height='1'>\n";
1086
	    $tabscounter = 0;
1087
	    foreach ($tab_array as $ta) {
1088
		    if($ta[1] == true) {
1089
			    echo "  <td bgcolor='#EEEEEE' onClick=\"document.location='{$ta[2]}'\"><div id='tabactive'></div></td>\n";
1090
		    } else {
1091
			    echo "  <td bgcolor='#777777' onClick=\"document.location='{$ta[2]}'\"><div id='tabdeactive{$tabscounter}'></div></td>\n";
1092
		    }
1093
		    $tabscounter++;
1094
	    }
1095
	    echo "</tr>\n<tr>\n";
1096
	    foreach ($tab_array as $ta) {
1097
		    if($ta[1] == true) {
1098
			    echo "  <td bgcolor='#EEEEEE' onClick=\"document.location='{$ta[2]}'\"><B>&nbsp;&nbsp;&nbsp;{$ta[0]}";
1099
			    echo "&nbsp;&nbsp;&nbsp;";
1100
			    echo "<font size='-12'>&nbsp;</td>\n";
1101
		    } else {
1102
			    echo "  <td bgcolor='#777777' onClick=\"document.location='{$ta[2]}'\"><B>&nbsp;&nbsp;&nbsp;<a href='{$ta[2]}'>";
1103
			    echo "<font color='white'>{$ta[0]}</a>&nbsp;&nbsp;&nbsp;";
1104
			    echo "<font size='-12'>&nbsp;</td>\n";
1105
		    }
1106
	    }
1107
	    echo "</tr>\n<tr height='5px'>\n";
1108
	    foreach ($tab_array as $ta) {
1109
		    if($ta[1] == true) {
1110
			    echo "  <td bgcolor='#EEEEEE' onClick=\"document.location='{$ta[2]}'\"></td>\n";
1111
		    } else {
1112
			    echo "  <td bgcolor='#777777' onClick=\"document.location='{$ta[2]}'\"></td>\n";
1113
		    }
1114
		    $tabscounter++;
1115
	    }
1116
	    echo " </tr>\n";
1117
	    echo "</table>\n";
1118
	    
1119
	    echo "<script type=\"text/javascript\">";
1120
	    echo "NiftyCheck();\n";
1121
	    echo "Rounded(\"div#tabactive\",\"top\",\"#FFF\",\"#EEEEEE\",\"smooth\");\n";
1122
	    for($x=0; $x<$tabscounter; $x++) 
1123
		    echo "Rounded(\"div#tabdeactive{$x}\",\"top\",\"#FFF\",\"#777777\",\"smooth\");\n";
1124
	    echo "</script>";
1125
    }
1126

    
1127

    
1128
/****f* pfsense-utils/display_topbar
1129
 * NAME
1130
 *   display_topbar - top a table off with rounded edges
1131
 * INPUTS
1132
 *   $text	- (optional) Text to include in bar
1133
 * RESULT
1134
 *   null
1135
 ******/
1136
function display_topbar($text = "", $bg_color="#990000", $replace_color="#FFFFFF", $rounding_style="smooth") {	    
1137
	echo "     <table width='100%' cellpadding='0' cellspacing='0'>\n";
1138
	echo "       <tr height='1'>\n";
1139
	echo "         <td width='100%' valign='top' color='{$bg_color}' bgcolor='{$bg_color}'>";
1140
	echo "		<div id='topbar'></div></td>\n";
1141
	echo "       </tr>\n";
1142
	echo "       <tr height='1'>\n";
1143
	if ($text != "")
1144
		echo "         <td height='1' class='listtopic'>{$text}</td>\n";
1145
	else
1146
		echo "         <td height='1' class='listtopic'></td>\n";
1147
	echo "       </tr>\n";
1148
	echo "     </table>";
1149
	echo "<script type=\"text/javascript\">";
1150
	echo "NiftyCheck();\n";
1151
	echo "Rounded(\"div#topbar\",\"top\",\"{$replace_color}\",\"{$bg_color}\",\"{$rounding_style}\");\n";
1152
	echo "</script>";
1153
}
1154

    
1155
/****f* pfsense-utils/generate_random_mac_address
1156
 * NAME
1157
 *   generate_random_mac - generates a random mac address
1158
 * INPUTS
1159
 *   none
1160
 * RESULT
1161
 *   $mac - a random mac address
1162
 ******/
1163
function generate_random_mac_address() {
1164
	$mac = "00:a0:8e";
1165
	for($x=0; $x<3; $x++) 
1166
	    $mac .= ":" . dechex(rand(16, 255));
1167

    
1168
	return $mac;
1169
}
1170

    
1171
/****f* pfsense-utils/strncpy
1172
 * NAME
1173
 *   strncpy - copy strings
1174
 * INPUTS
1175
 *   &$dst, $src, $length
1176
 * RESULT
1177
 *   none
1178
 ******/
1179
function strncpy(&$dst, $src, $length) {
1180
	if (strlen($src) > $length) {
1181
		$dst = substr($src, 0, $length);
1182
	} else {
1183
		$dst = $src;
1184
	}
1185
}
1186

    
1187
/****f* pfsense-utils/reload_interfaces_sync
1188
 * NAME
1189
 *   reload_interfaces - reload all interfaces
1190
 * INPUTS
1191
 *   none
1192
 * RESULT
1193
 *   none
1194
 ******/
1195
function reload_interfaces_sync() {
1196
	global $config, $g;
1197
	
1198
	if(file_exists("{$g['tmp_path']}/config.cache"))
1199
		unlink("{$g['tmp_path']}/config.cache");
1200
	
1201
	/* parse config.xml again */
1202
	$config = parse_config(true);
1203

    
1204
	/* delete all old interface information */
1205
	$iflist = split(" ", str_replace("\n", "", `/sbin/ifconfig -l`));
1206
	foreach ($iflist as $ifent => $ifname) {
1207
		$ifname_real = convert_friendly_interface_to_real_interface_name($ifname);
1208
		mwexec("/sbin/ifconfig {$ifname_real} down");
1209
		mwexec("/sbin/ifconfig {$ifname_real} delete");
1210
	}
1211

    
1212
	/* set up LAN interface */
1213
	interfaces_lan_configure();
1214

    
1215
	/* set up WAN interface */
1216
	interfaces_wan_configure();
1217

    
1218
	/* set up Optional interfaces */
1219
	interfaces_optional_configure();
1220
        
1221
	/* set up static routes */
1222
	system_routing_configure();
1223
	
1224
	/* enable routing */
1225
	system_routing_enable();
1226
	
1227
	/* setup captive portal if needed */
1228
	captiveportal_configure();	
1229
}
1230

    
1231
/****f* pfsense-utils/reload_all
1232
 * NAME
1233
 *   reload_all - triggers a reload of all settings
1234
 *   * INPUTS
1235
 *   none
1236
 * RESULT
1237
 *   none
1238
 ******/
1239
function reload_all() {
1240
	touch("/tmp/reload_all");
1241
}
1242

    
1243
/****f* pfsense-utils/reload_interfaces
1244
 * NAME
1245
 *   reload_interfaces - triggers a reload of all interfaces
1246
 * INPUTS
1247
 *   none
1248
 * RESULT
1249
 *   none
1250
 ******/
1251
function reload_interfaces() {
1252
	touch("/tmp/reload_interfaces");
1253
}
1254

    
1255
/****f* pfsense-utils/sync_webgui_passwords
1256
 * NAME
1257
 *   sync_webgui_passwords - syncs webgui and ssh passwords
1258
 * INPUTS
1259
 *   none
1260
 * RESULT
1261
 *   none
1262
 ******/
1263
function sync_webgui_passwords() {
1264
	global $config, $g;
1265
	conf_mount_rw();
1266
	$fd = fopen("{$g['varrun_path']}/htpasswd", "w");
1267
	if (!$fd) {
1268
		printf("Error: cannot open htpasswd in system_password_configure().\n");
1269
		return 1;
1270
	}
1271
	/* set admin account */
1272
	$username = $config['system']['username'];
1273
	
1274
	/* set defined user account */
1275
	if($username <> "admin") {
1276
		$username = $config['system']['username'];
1277
		fwrite($fd, $username . ":" . $config['system']['password'] . "\n");
1278
	} else {
1279
		fwrite($fd, $username . ":" . $config['system']['password'] . "\n");	
1280
	}	
1281
	fclose($fd);
1282
	chmod("{$g['varrun_path']}/htpasswd", 0600);	
1283
	$crypted_pw = $config['system']['password'];
1284
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
1285
	mwexec("/usr/sbin/pwd_mkdb /etc/master.passwd");
1286
	/* sync root */
1287
	$fd = popen("/usr/sbin/pw usermod -n root -H 0", "w");
1288
	fwrite($fd, $crypted_pw);
1289
	pclose($fd);
1290
	mwexec("/usr/sbin/pw usermod -n root -s /bin/sh");
1291
	/* sync admin */
1292
	$fd = popen("/usr/sbin/pw usermod -n admin -H 0", "w");
1293
	fwrite($fd, $crypted_pw);
1294
	pclose($fd);
1295
	mwexec("/usr/sbin/pw usermod -n admin -s /etc/rc.initial");
1296
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
1297
	mwexec("/usr/sbin/pwd_mkdb /etc/master.passwd");
1298
	conf_mount_ro();
1299
}
1300

    
1301
/****f* pfsense-utils/reload_all_sync
1302
 * NAME
1303
 *   reload_all - reload all settings
1304
 *   * INPUTS
1305
 *   none
1306
 * RESULT
1307
 *   none
1308
 ******/
1309
function reload_all_sync() {
1310
	global $config, $g;
1311
	
1312
	if(file_exists("{$g['tmp_path']}/config.cache"))
1313
		unlink("{$g['tmp_path']}/config.cache");
1314
	
1315
	/* parse config.xml again */
1316
	$config = parse_config(true);
1317

    
1318
	/* set up our timezone */
1319
	system_timezone_configure();
1320

    
1321
	/* set up our hostname */
1322
	system_hostname_configure();
1323

    
1324
	/* make hosts file */
1325
	system_hosts_generate();
1326

    
1327
	/* generate resolv.conf */
1328
	system_resolvconf_generate();
1329

    
1330
	/* delete all old interface information */
1331
	$iflist = split(" ", str_replace("\n", "", `/sbin/ifconfig -l`));
1332
	foreach ($iflist as $ifent => $ifname) {
1333
		$ifname_real = convert_friendly_interface_to_real_interface_name($ifname);
1334
		mwexec("/sbin/ifconfig {$ifname_real} down");
1335
		mwexec("/sbin/ifconfig {$ifname_real} delete");
1336
	}
1337

    
1338
	/* set up LAN interface */
1339
	interfaces_lan_configure();
1340

    
1341
	/* set up WAN interface */
1342
	interfaces_wan_configure();
1343

    
1344
	/* set up Optional interfaces */
1345
	interfaces_optional_configure();
1346
        
1347
	/* bring up carp interfaces */
1348
	interfaces_carp_configure();
1349
	
1350
	/* set up static routes */
1351
	system_routing_configure();
1352

    
1353
	/* enable routing */
1354
	system_routing_enable();
1355
	
1356
	/* ensure passwords are sync'd */
1357
	system_password_configure();
1358

    
1359
	/* start dnsmasq service */
1360
	services_dnsmasq_configure();
1361

    
1362
	/* start dyndns service */
1363
	services_dyndns_configure();
1364

    
1365
	/* start DHCP service */
1366
	services_dhcpd_configure();
1367

    
1368
	/* start the NTP client */
1369
	system_ntp_configure();
1370

    
1371
	/* start ftp proxy helpers if they are enabled */
1372
	system_start_ftp_helpers();
1373
	
1374
	/* start the captive portal */
1375
	captiveportal_configure();
1376

    
1377
        /* reload the filter */
1378
	filter_configure_sync();
1379

    
1380
	/* bring up carp interfaces*/
1381
	interfaces_carp_bring_up_final();
1382

    
1383
	/* sync pw database */
1384
	conf_mount_rw();
1385
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
1386
	conf_mount_ro();
1387

    
1388
	/* restart sshd */
1389
	touch("/tmp/start_sshd");
1390
	
1391
}
1392

    
1393
?>
(14-14/26)