Project

General

Profile

Download (41.7 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
    if(is_array($config['nat']['rule']))
170
	    foreach($config['filter']['rule'] as $rule) {
171
			if(is_array($rule['source']['address']))
172
				if($rule['source']['address'] == $alias)
173
					return true;
174
			if(is_array($rule['destination']['address']))
175
				if($rule['destination']['address'] == $alias)
176
					return true;
177
	    }
178
    /* loop through nat rules looking for alias in use */
179
    if(is_array($config['nat']['rule']))
180
	    foreach($config['nat']['rule'] as $rule) {
181
			if($rule['target'] == $alias)
182
				return true;
183
			if($rule['external-address'] == $alias)
184
				return true;	
185
	    }
186
    return false;
187
}
188

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

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

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

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

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

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

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

    
328
    if($tmp == "")
329
	return false;
330
    else
331
	return true;
332
}
333

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

    
345
/****f* pfsense-utils/is_interface_wireless
346
 * NAME
347
 *   is_interface_wireless - Returns if an interface is wireless
348
 * RESULT
349
 *   $tmp	- Returns if an interface is wireless
350
 ******/
351
function is_interface_wireless($interface) {
352
	global $config, $g;
353
	$interface = convert_real_interface_to_friendly_interface_name($interface);
354
	if(isset($config['interfaces'][$interface]['wireless']))
355
		return true;
356
	else
357
		return false;
358
}
359

    
360
/****f* pfsense-utils/find_number_of_created_carp_interfaces
361
 * NAME
362
 *   find_number_of_created_carp_interfaces - Return the number of CARP interfaces.
363
 * RESULT
364
 *   $tmp	- Number of currently created CARP interfaces.
365
 ******/
366
function find_number_of_created_carp_interfaces() {
367
    $command = "/sbin/ifconfig | /usr/bin/grep \"carp*:\" | /usr/bin/wc -l";
368
    $fd = popen($command . " 2>&1 ", "r");
369
    if(!$fd) {
370
	log_error("Warning, could not execute command {$command}");
371
	return 0;
372
    }
373
    while(!feof($fd)) {
374
	$tmp .= fread($fd,49);
375
    }
376
    fclose($fd);
377
    $tmp = intval($tmp);
378
    return $tmp;
379
}
380

    
381
/****f* pfsense-utils/link_ip_to_carp_interface
382
 * NAME
383
 *   link_ip_to_carp_interface - Find where a CARP interface links to.
384
 * INPUTS
385
 *   $ip
386
 * RESULT
387
 *   $carp_ints
388
 ******/
389
function link_ip_to_carp_interface($ip) {
390
	global $config;
391
	if($ip == "") return;
392

    
393
	$ifdescrs = array('wan', 'lan');
394
	for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) {
395
		$ifdescrs['opt' . $j] = "opt" . $j;
396
	}
397

    
398
	$ft = split("\.", $ip);
399
	$ft_ip = $ft[0] . "." . $ft[1] . "." . $ft[2] . ".";
400

    
401
	$carp_ints = "";
402
	$num_carp_ints = find_number_of_created_carp_interfaces();
403
	foreach ($ifdescrs as $ifdescr => $ifname) {
404
		for($x=0; $x<$num_carp_ints; $x++) {
405
			$carp_int = "carp{$x}";
406
			$carp_ip = find_interface_ip($carp_int);
407
			$carp_ft = split("\.", $carp_ip);
408
			$carp_ft_ip = $carp_ft[0] . "." . $carp_ft[1] . "." . $carp_ft[2] . ".";
409
			$result = does_interface_exist($carp_int);
410
			if($result <> true) break;
411
			if($ft_ip == $carp_ft_ip)
412
			if(stristr($carp_ints,$carp_int) == false)
413
			$carp_ints .= " " . $carp_int;
414
		}
415
	}
416
	return $carp_ints;
417
}
418

    
419
/****f* pfsense-utils/exec_command
420
 * NAME
421
 *   exec_command - Execute a command and return a string of the result.
422
 * INPUTS
423
 *   $command	- String of the command to be executed.
424
 * RESULT
425
 *   String containing the command's result.
426
 * NOTES
427
 *   This function returns the command's stdout and stderr.
428
 ******/
429
function exec_command($command) {
430
    $output = array();
431
    exec($command . ' 2>&1 ', $output);
432
    return(implode("\n", $output));
433
}
434

    
435
/****f* interfaces/is_jumbo_capable
436
 * NAME
437
 *   is_jumbo_capable - Test if interface is jumbo frame capable.  Useful for determining VLAN capability.
438
 * INPUTS
439
 *   $int             - string containing interface name
440
 * RESULT
441
 *   boolean          - true or false
442
 ******/
443
function is_jumbo_capable($int) {
444
	/* Per:
445
	 * http://www.freebsd.org/cgi/man.cgi?query=vlan&manpath=FreeBSD+6.0-current&format=html
446
	 * Only the following drivers support large frames
447
	 */
448
	$capable = array("bfe", "dc", "de", "fxp", "hme", "rl", "sis", "ste",
449
		"tl", "tx", "xl", "em");
450
	
451
	$int_family = preg_split("/[0-9]+/", $int);
452

    
453
	if (in_array($int_family[0], $capable))
454
		return true;
455
	else
456
		return false;
457
}
458

    
459
/*
460
 * does_interface_exist($interface): return true or false if a interface is detected.
461
 */
462
function does_interface_exist($interface) {
463
    $ints = exec_command("/sbin/ifconfig -l");
464
    if(stristr($ints, $interface) !== false)
465
	return true;
466
    else
467
	return false;
468
}
469

    
470
/*
471
 * convert_ip_to_network_format($ip, $subnet): converts an ip address to network form
472
 */
473
function convert_ip_to_network_format($ip, $subnet) {
474
    $ipsplit = split('[.]', $ip);
475
    $string = $ipsplit[0] . "." . $ipsplit[1] . "." . $ipsplit[2] . ".0/" . $subnet;
476
    return $string;
477
}
478

    
479
/*
480
 * find_interface_ip($interface): return the interface ip (first found)
481
 */
482
function find_interface_ip($interface) {
483
    if(does_interface_exist($interface) == false) return;
484
    $ip = exec_command("/sbin/ifconfig {$interface} | /usr/bin/grep -w \"inet\" | /usr/bin/cut -d\" \" -f 2");
485
    $ip = str_replace("\n","",$ip);
486
    return $ip;
487
}
488

    
489
function guess_interface_from_ip($ipaddress) {
490
    $ints = `/sbin/ifconfig -l`;
491
    $ints_split = split(" ", $ints);
492
    $ip_subnet_split = split("\.", $ipaddress);
493
    $ip_subnet = $ip_subnet_split[0] . "." . $ip_subnet_split[1] . "." . $ip_subnet_split[2] . ".";
494
    foreach($ints_split as $int) {
495
        $ip = find_interface_ip($int);
496
        $ip_split = split("\.", $ip);
497
        $ip_tocheck = $ip_split[0] . "." . $ip_split[1] . "." . $ip_split[2] . ".";
498
        if(stristr($ip_tocheck, $ip_subnet) != false) return $int;
499
    }
500
}
501

    
502
function filter_opt_interface_to_real($opt) {
503
    global $config;
504
    return $config['interfaces'][$opt]['if'];
505
}
506

    
507
function filter_get_opt_interface_descr($opt) {
508
    global $config;
509
    return $config['interfaces'][$opt]['descr'];
510
}
511

    
512
function get_friendly_interface_list_as_array() {
513
    global $config;
514
    $ints = array();
515
    $ifdescrs = array('wan', 'lan');
516
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) {
517
		$ifdescrs['opt' . $j] = "opt" . $j;
518
    }
519
    $ifdescrs = get_interface_list();
520
    foreach ($ifdescrs as $ifdescr => $ifname) {
521
		array_push($ints,$ifdescr);
522
    }
523
    return $ints;
524
}
525

    
526
/*
527
 * find_ip_interface($ip): return the interface where an ip is defined
528
 */
529
function find_ip_interface($ip) {
530
    global $config;
531
    $ifdescrs = array('wan', 'lan');
532
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) {
533
	$ifdescrs['opt' . $j] = "opt" . $j;
534
    }
535
    foreach ($ifdescrs as $ifdescr => $ifname) {
536
	$int = filter_translate_type_to_real_interface($ifname);
537
	$ifconfig = exec_command("/sbin/ifconfig {$int}");
538
	if(stristr($ifconfig,$ip) <> false)
539
	    return $int;
540
    }
541
    return false;
542
}
543

    
544
/*
545
 *  filter_translate_type_to_real_interface($interface): returns the real interface name
546
 *                                                       for a friendly interface.  ie: wan
547
 */
548
function filter_translate_type_to_real_interface($interface) {
549
    global $config;
550
    if($config['interfaces'][$interface]['if'] <> "") {
551
	return $config['interfaces'][$interface]['if'];
552
    } else {
553
	return $interface;
554
    }
555
}
556

    
557
/*
558
 * get_carp_interface_status($carpinterface): returns the status of a carp ip
559
 */
560
function get_carp_interface_status($carpinterface) {
561
	/* basically cache the contents of ifconfig statement
562
	to speed up this routine */
563
	global $carp_query;
564
	if($carp_query == "")
565
	$carp_query = split("\n", `/sbin/ifconfig | /usr/bin/grep carp`);
566
	$found_interface = 0;
567
	foreach($carp_query as $int) {
568
		if($found_interface == 1) {
569
			if(stristr($int, "MASTER") == true) return "MASTER";
570
			if(stristr($int, "BACKUP") == true) return "BACKUP";
571
			if(stristr($int, "INIT") == true) return "INIT";
572
			return false;
573
		}
574
		if(stristr($int, $carpinterface) == true)
575
		$found_interface=1;
576
	}
577
	return;
578
}
579

    
580
/*
581
 * get_pfsync_interface_status($pfsyncinterface): returns the status of a pfsync
582
 */
583
function get_pfsync_interface_status($pfsyncinterface) {
584
    $result = does_interface_exist($pfsyncinterface);
585
    if($result <> true) return;
586
    $status = exec_command("/sbin/ifconfig {$pfsyncinterface} | /usr/bin/grep \"pfsync:\" | /usr/bin/cut -d\" \" -f5");
587
    return $status;
588
}
589

    
590
/*
591
 * find_carp_interface($ip): return the carp interface where an ip is defined
592
 */
593
function find_carp_interface($ip) {
594
    global $find_carp_ifconfig;
595
    if($find_carp_ifconfig == "") {
596
	$find_carp_ifconfig = array();
597
	$num_carp_ints = find_number_of_created_carp_interfaces();
598
	for($x=0; $x<$num_carp_ints; $x++) {
599
	    $find_carp_ifconfig[$x] = exec_command("/sbin/ifconfig carp{$x}");
600
	}
601
    }
602
    $carps = 0;
603
    foreach($find_carp_ifconfig as $fci) {
604
	if(stristr($fci, $ip) == true)
605
	    return "carp{$carps}";
606
	$carps++;
607
    }
608
}
609

    
610
/*
611
 * find_number_of_created_bridges(): returns the number of currently created bridges
612
 */
613
function find_number_of_created_bridges() {
614
    return `/sbin/ifconfig | grep \"bridge[0-999]\:" | wc -l`;
615
}
616

    
617
/*
618
 * add_rule_to_anchor($anchor, $rule): adds the specified rule to an anchor
619
 */
620
function add_rule_to_anchor($anchor, $rule, $label) {
621
    mwexec("echo " . $rule . " | /sbin/pfctl -a " . $anchor . ":" . $label . " -f -");
622
}
623

    
624
/*
625
 * remove_text_from_file
626
 * remove $text from file $file
627
 */
628
function remove_text_from_file($file, $text) {
629
    global $fd_log;
630
    fwrite($fd_log, "Adding needed text items:\n");
631
    $filecontents = exec_command_and_return_text("cat " . $file);
632
    $textTMP = str_replace($text, "", $filecontents);
633
    $text .= $textTMP;
634
    fwrite($fd_log, $text . "\n");
635
    $fd = fopen($file, "w");
636
    fwrite($fd, $text);
637
    fclose($fd);
638
}
639

    
640
/*
641
 * add_text_to_file($file, $text): adds $text to $file.
642
 * replaces the text if it already exists.
643
 */
644
function add_text_to_file($file, $text) {
645
	if(file_exists($file) and is_writable($file)) {
646
		$filecontents = file($file);
647
		$filecontents[] = $text;
648
		$tmpfile = get_tmp_file();
649
		$fout = fopen($tmpfile, "w");
650
		foreach($filecontents as $line) {
651
			fwrite($fout, rtrim($line) . "\n");
652
		}
653
		fclose($fout);
654
		rename($tmpfile, $file);
655
		return true;
656
	} else {
657
		return false;
658
	}
659
}
660

    
661
/*
662
 *   after_sync_bump_adv_skew(): create skew values by 1S
663
 */
664
function after_sync_bump_adv_skew() {
665
	global $config, $g;
666
	$processed_skew = 1;
667
	$a_vip = &$config['virtualip']['vip'];
668
	foreach ($a_vip as $vipent) {
669
		if($vipent['advskew'] <> "") {
670
			$processed_skew = 1;
671
			$vipent['advskew'] = $vipent['advskew']+1;
672
		}
673
	}
674
	if($processed_skew == 1)
675
		write_config("After synch increase advertising skew");
676
}
677

    
678
/*
679
 * get_filename_from_url($url): converts a url to its filename.
680
 */
681
function get_filename_from_url($url) {
682
	return basename($url);
683
}
684

    
685
/*
686
 *   update_output_window: update bottom textarea dynamically.
687
 */
688
function update_output_window($text) {
689
    $log = ereg_replace("\n", "\\n", $text);
690
    echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = \"" . $log . "\";</script>";
691
}
692

    
693
/*
694
 *   get_dir: return an array of $dir
695
 */
696
function get_dir($dir) {
697
    $dir_array = array();
698
    $d = dir($dir);
699
    while (false !== ($entry = $d->read())) {
700
	array_push($dir_array, $entry);
701
    }
702
    $d->close();
703
    return $dir_array;
704
}
705

    
706
/*
707
 *   update_output_window: update top textarea dynamically.
708
 */
709
function update_status($status) {
710
    echo "\n<script language=\"JavaScript\">document.forms[0].status.value=\"" . $status . "\";</script>";
711
}
712

    
713
/*
714
 *   exec_command_and_return_text_array: execute command and return output
715
 */
716
function exec_command_and_return_text_array($command) {
717
	$fd = popen($command . " 2>&1 ", "r");
718
	while(!feof($fd)) {
719
		$tmp .= fread($fd,49);
720
	}
721
	fclose($fd);
722
	$temp_array = split("\n", $tmp);
723
	return $temp_array;
724
}
725

    
726
/*
727
 *   exec_command_and_return_text: execute command and return output
728
 */
729
function exec_command_and_return_text($command) {
730
    return exec_command($command);
731
}
732

    
733
/*
734
 *   exec_command_and_return_text: execute command and update output window dynamically
735
 */
736
function execute_command_return_output($command) {
737
    global $fd_log;
738
    $fd = popen($command . " 2>&1 ", "r");
739
    echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = \"\";</script>";
740
    $counter = 0;
741
    $counter2 = 0;
742
    while(!feof($fd)) {
743
	$tmp = fread($fd, 50);
744
	$tmp1 = ereg_replace("\n","\\n", $tmp);
745
	$text = ereg_replace("\"","'", $tmp1);
746
	if($lasttext == "..") {
747
	    $text = "";
748
	    $lasttext = "";
749
	    $counter=$counter-2;
750
	} else {
751
	    $lasttext .= $text;
752
	}
753
	if($counter > 51) {
754
	    $counter = 0;
755
	    $extrabreak = "\\n";
756
	} else {
757
	    $extrabreak = "";
758
	    $counter++;
759
	}
760
	if($counter2 > 600) {
761
	    echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = \"\";</script>";
762
	    $counter2 = 0;
763
	} else
764
	    $counter2++;
765
	echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = this.document.forms[0].output.value + \"" . $text . $extrabreak .  "\"; f('output'); </script>";
766
    }
767
    fclose($fd);
768
}
769

    
770
/*
771
 * convert_friendly_interface_to_real_interface_name($interface): convert WAN to FXP0
772
 */
773
function convert_friendly_interface_to_real_interface_name($interface) {
774
    global $config;
775
    $lc_interface = strtolower($interface);
776
    if($lc_interface == "lan") return $config['interfaces']['lan']['if'];
777
    if($lc_interface == "wan") return $config['interfaces']['wan']['if'];
778
    $ifdescrs = array();
779
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++)
780
	$ifdescrs['opt' . $j] = "opt" . $j;
781
    foreach ($ifdescrs as $ifdescr => $ifname) {
782
	if(strtolower($ifname) == $lc_interface)
783
	    return $config['interfaces'][$ifname]['if'];
784
	if(strtolower($config['interfaces'][$ifname]['descr']) == $lc_interface)
785
	    return $config['interfaces'][$ifname]['if'];
786
    }
787
    return $interface;
788
}
789

    
790
/*
791
 * convert_real_interface_to_friendly_interface_name($interface): convert fxp0 -> wan, etc.
792
 */
793
function convert_real_interface_to_friendly_interface_name($interface) {
794
    global $config;
795
    $ifdescrs = array('wan', 'lan');
796
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++)
797
	$ifdescrs['opt' . $j] = "opt" . $j;
798
    foreach ($ifdescrs as $ifdescr => $ifname) {
799
	$int = filter_translate_type_to_real_interface($ifname);
800
	if($ifname == $interface) return $ifname;
801
	if($int == $interface) return $ifname;
802
    }
803
    return $interface;
804
}
805

    
806
/*
807
 * update_progress_bar($percent): updates the javascript driven progress bar.
808
 */
809
function update_progress_bar($percent) {
810
    if($percent > 100) $percent = 1;
811
    echo "\n<script type=\"text/javascript\" language=\"javascript\">";
812
    echo "\ndocument.progressbar.style.width='" . $percent . "%';";
813
    echo "\n</script>";
814
}
815

    
816
/*
817
 * gather_altq_queue_stats():  gather alq queue stats and return an array that
818
 *                             is queuename|qlength|measured_packets
819
 *                             NOTE: this command takes 5 seconds to run
820
 */
821
function gather_altq_queue_stats($dont_return_root_queues) {
822
    mwexec("/usr/bin/killall -9 pfctl");
823
    $stats = `/sbin/pfctl -vvsq & /bin/sleep 5;/usr/bin/killall pfctl 2>/dev/null`;
824
    $stats_array = split("\n", $stats);
825
    $queue_stats = array();
826
    foreach ($stats_array as $stats_line) {
827
        if (preg_match_all("/queue\s+(\w+)\s+/",$stats_line,$match_array))
828
            $queue_name = $match_array[1][0];
829
        if (preg_match_all("/measured:\s+.*packets\/s\,\s(.*)\s+\]/",$stats_line,$match_array))
830
            $speed = $match_array[1][0];
831
        if (preg_match_all("/borrows:\s+(.*)/",$stats_line,$match_array))
832
            $borrows = $match_array[1][0];
833
        if (preg_match_all("/suspends:\s+(.*)/",$stats_line,$match_array))
834
            $suspends = $match_array[1][0];
835
        if (preg_match_all("/dropped pkts:\s+(.*)/",$stats_line,$match_array))
836
            $drops = $match_array[1][0];
837
        if (preg_match_all("/measured:\s+(.*)packets/",$stats_line,$match_array)) {
838
            $measured = $match_array[1][0];
839
	    if($dont_return_root_queues == true)
840
		if(stristr($queue_name,"root_") == false)
841
		    array_push($queue_stats, "{$queue_name}|{$speed}|{$measured}|{$borrows}|{$suspends}|{$drops}");
842
        }
843
    }
844
    return $queue_stats;
845
}
846

    
847
/*
848
 * reverse_strrchr($haystack, $needle):  Return everything in $haystack up to the *last* instance of $needle.
849
 *					 Useful for finding paths and stripping file extensions.
850
 */
851
function reverse_strrchr($haystack, $needle)
852
{
853
               return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) +1 ) : false;
854
}
855

    
856
/*
857
 *  backup_config_section($section): returns as an xml file string of
858
 *                                   the configuration section
859
 */
860
function backup_config_section($section) {
861
    global $config;
862
    $new_section = &$config[$section];
863
    /* generate configuration XML */
864
    $xmlconfig = dump_xml_config($new_section, $section);
865
    $xmlconfig = str_replace("<?xml version=\"1.0\"?>", "", $xmlconfig);
866
    return $xmlconfig;
867
}
868

    
869
/*
870
 *  backup_config_ts_scheduler(): returns the traffic shaper scheduler for backup
871
 */
872
function backup_config_ts_scheduler() {
873
    global $config;
874
    $new_section = &$config['syste']['schedulertype'];
875
    /* generate configuration XML */
876
    $xmlconfig = dump_xml_config($new_section, $section);
877
    $xmlconfig = str_replace("<?xml version=\"1.0\"?>", "", $xmlconfig);
878
    return $xmlconfig;
879
}
880

    
881
/*
882
 *  backup_config_section($section): returns as an xml file string of
883
 *                                   the configuration section
884
 */
885
function backup_vip_config_section() {
886
    global $config;
887
    $new_section = &$config['virtualip'];
888
    foreach($new_section['vip'] as $section) {
889
	if($section['mode'] == "proxyarp") {
890
		unset($section);		
891
	}
892
	if($section['advskew'] <> "") {
893
		$section_val = intval($section['advskew']);
894
		$section_val=$section_val+100;
895
		if($section_val > 255)
896
			$section_val = 255;
897
		$section['advskew'] = $section_val;
898
	}
899
	$temp['vip'][] = $section;
900
    }
901
    return $temp;
902
}
903

    
904
/*
905
 *  restore_config_section($section, new_contents): restore a configuration section,
906
 *                                                  and write the configuration out
907
 *                                                  to disk/cf.
908
 */
909
function restore_config_section($section, $new_contents) {
910
    global $config;
911
    conf_mount_rw();
912
    $fout = fopen("{$g['tmp_path']}/tmpxml","w");
913
    fwrite($fout, $new_contents);
914
    fclose($fout);
915
    $section_xml = parse_xml_config($g['tmp_path'] . "/tmpxml", $section);
916
    $config[$section] = &$section_xml;
917
    unlink($g['tmp_path'] . "/tmpxml");
918
    write_config("Restored {$section} of config file (maybe from CARP partner)");
919
    conf_mount_ro();
920
    return;
921
}
922

    
923
/*
924
 * http_post($server, $port, $url, $vars): does an http post to a web server
925
 *                                         posting the vars array.
926
 * written by nf@bigpond.net.au
927
 */
928
function http_post($server, $port, $url, $vars) {
929
    $user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)";
930
    $urlencoded = "";
931
    while (list($key,$value) = each($vars))
932
	$urlencoded.= urlencode($key) . "=" . urlencode($value) . "&";
933
    $urlencoded = substr($urlencoded,0,-1);
934

    
935
    $content_length = strlen($urlencoded);
936

    
937
    $headers = "POST $url HTTP/1.1
938
Accept: */*
939
Accept-Language: en-au
940
Content-Type: application/x-www-form-urlencoded
941
User-Agent: $user_agent
942
Host: $server
943
Connection: Keep-Alive
944
Cache-Control: no-cache
945
Content-Length: $content_length
946

    
947
";
948

    
949
    $fp = fsockopen($server, $port, $errno, $errstr);
950
    if (!$fp) {
951
	return false;
952
    }
953

    
954
    fputs($fp, $headers);
955
    fputs($fp, $urlencoded);
956

    
957
    $ret = "";
958
    while (!feof($fp))
959
	$ret.= fgets($fp, 1024);
960

    
961
    fclose($fp);
962

    
963
    return $ret;
964

    
965
}
966

    
967
/*
968
 *  php_check_syntax($code_tocheck, $errormessage): checks $code_to_check for errors
969
 */
970
if (!function_exists('php_check_syntax')){
971
   function php_check_syntax($code_to_check, &$errormessage){
972
	return false;
973
        $fout = fopen("/tmp/codetocheck.php","w");
974
        $code = $_POST['content'];
975
        $code = str_replace("<?php", "", $code);
976
        $code = str_replace("?>", "", $code);
977
        fwrite($fout, "<?php\n\n");
978
        fwrite($fout, $code_to_check);
979
        fwrite($fout, "\n\n?>\n");
980
        fclose($fout);
981
        $command = "/usr/local/bin/php -l /tmp/codetocheck.php";
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
 *  php_check_filename_syntax($filename, $errormessage): checks the file $filename for errors
996
 */
997
if (!function_exists('php_check_syntax')){
998
   function php_check_syntax($code_to_check, &$errormessage){
999
	return false;
1000
        $command = "/usr/local/bin/php -l " . $code_to_check;
1001
        $output = exec_command($command);
1002
        if (stristr($output, "Errors parsing") == false) {
1003
            echo "false\n";
1004
            $errormessage = '';
1005
            return(false);
1006
        } else {
1007
            $errormessage = $output;
1008
            return(true);
1009
        }
1010
    }
1011
}
1012

    
1013
/*
1014
 * rmdir_recursive($path,$follow_links=false)
1015
 * Recursively remove a directory tree (rm -rf path)
1016
 * This is for directories _only_
1017
 */
1018
function rmdir_recursive($path,$follow_links=false) {
1019
	$to_do = glob($path);
1020
	if(!is_array($to_do)) $to_do = array($to_do);
1021
	foreach($to_do as $workingdir) { // Handle wildcards by foreaching.
1022
		if(file_exists($workingdir)) {
1023
			if(is_dir($workingdir)) {
1024
				$dir = opendir($workingdir);
1025
				while ($entry = readdir($dir)) {
1026
					if (is_file("$workingdir/$entry") || ((!$follow_links) && is_link("$workingdir/$entry")))
1027
						unlink("$workingdir/$entry");
1028
					elseif (is_dir("$workingdir/$entry") && $entry!='.' && $entry!='..')
1029
						rmdir_recursive("$workingdir/$entry");
1030
				}
1031
				closedir($dir);
1032
				rmdir($workingdir);
1033
			} elseif (is_file($workingdir)) {
1034
				unlink($workingdir);
1035
			}
1036
               	}
1037
	}
1038
	return;
1039
}
1040

    
1041
/*
1042
 *     get_memory()
1043
 *     returns an array listing the amount of
1044
 *     memory installed in the hardware
1045
 *     [0]real and [1]available
1046
 */
1047
function get_memory() {
1048
	if(file_exists("cat /var/log/dmesg.boot")) {
1049
		$mem = `cat /var/log/dmesg.boot | grep memory`;
1050
		if (preg_match_all("/real memory  = .* \((.*) MB/", $mem, $matches))
1051
			$real = $matches[1];
1052
		if (preg_match_all("/avail memory = .* \((.*) MB/", $mem, $matches))
1053
			$avail = $matches[1];
1054
		return array($real[0],$avail[0]);
1055
	}
1056
	return array("64","64");
1057
}
1058

    
1059

    
1060
/*
1061
 *    safe_mkdir($path, $mode = 0755)
1062
 *    create directory if it doesn't already exist and isn't a file!
1063
 */
1064
function safe_mkdir($path, $mode=0755) {
1065
	global $g;
1066

    
1067
	/* cdrom is ro. */
1068
	if($g['platform'] == "cdrom")
1069
		return false;
1070
	
1071
	if (!is_file($path) && !is_dir($path))
1072
		return mkdir($path, $mode);
1073
	else
1074
		return false;
1075
}
1076

    
1077
/*
1078
 * make_dirs($path, $mode = 0755)
1079
 * create directory tree recursively (mkdir -p)
1080
 */
1081
function make_dirs($path, $mode = 0755) {
1082
	/* is dir already created? */
1083
	if(is_dir($path)) return;
1084
	/* create directory in question */
1085
	$to_create = explode("/", $path);
1086
	foreach($to_create as $tc) 
1087
	    if(!is_dir($tc))
1088
		safe_mkdir($path, $mode);
1089
}
1090

    
1091
/*
1092
 * check_firmware_version(): Check whether the current firmware installed is the most recently released.
1093
 */
1094
function check_firmware_version($tocheck = "all", $return_php = true) {
1095
        global $g, $config;
1096
	$xmlrpc_base_url = $g['xmlrpcbaseurl'];
1097
        $xmlrpc_path = $g['xmlrpcpath'];
1098
	$rawparams = array("firmware" => array("version" => trim(file_get_contents('/etc/version'))),
1099
			"kernel"   => array("version" => trim(file_get_contents('/etc/version_kernel'))),
1100
			"base"     => array("version" => trim(file_get_contents('/etc/version_base'))),
1101
			"platform" => trim(file_get_contents('/etc/platform'))
1102
		);
1103
	if($tocheck == "all") {
1104
		$params = $rawparams;
1105
	} else {
1106
		foreach($tocheck as $check) {
1107
			$params['check'] = $rawparams['check'];
1108
			$params['platform'] = $rawparams['platform'];
1109
		}
1110
	}
1111
	if($config['system']['firmware']['branch']) {
1112
		$params['branch'] = $config['system']['firmware']['branch'];
1113
	}
1114
	$xmlparams = php_value_to_xmlrpc($params);
1115
        $msg = new XML_RPC_Message('pfsense.get_firmware_version', array($xmlparams));
1116
        $cli = new XML_RPC_Client($xmlrpc_path, $xmlrpc_base_url);
1117
	//$cli->setDebug(1);
1118
	$resp = $cli->send($msg, 10);
1119
	if(!$resp or $resp->faultCode()) {
1120
		$raw_versions = false;
1121
	} else {
1122
		$raw_versions = XML_RPC_decode($resp->value());
1123
		$raw_versions["current"] = $params;
1124
	}
1125
	return $raw_versions;
1126
}
1127

    
1128
function get_disk_info() {
1129
        exec("df -h | grep -w '/' | awk '{ print $2, $3, $4, $5 }'", $diskout);
1130
        return explode(' ', $diskout[0]);
1131
        // $size, $used, $avail, $cap
1132
}
1133

    
1134
/****f* pfsense-utils/display_top_tabs
1135
 * NAME
1136
 *   display_top_tabs - display tabs with rounded edges
1137
 * INPUTS
1138
 *   $text	- array of tabs
1139
 * RESULT
1140
 *   null
1141
 ******/
1142
    function display_top_tabs($tab_array) {
1143
	    echo "<table cellpadding='0' cellspacing='0'>\n";
1144
	    echo " <tr height='1'>\n";
1145
	    $tabscounter = 0;
1146
	    foreach ($tab_array as $ta) {
1147
		    if($ta[1] == true) {
1148
			    echo "  <td bgcolor='#EEEEEE' onClick=\"document.location='{$ta[2]}'\"><div id='tabactive'></div></td>\n";
1149
		    } else {
1150
			    echo "  <td bgcolor='#777777' onClick=\"document.location='{$ta[2]}'\"><div id='tabdeactive{$tabscounter}'></div></td>\n";
1151
		    }
1152
		    $tabscounter++;
1153
	    }
1154
	    echo "</tr>\n<tr>\n";
1155
	    foreach ($tab_array as $ta) {
1156
		    if($ta[1] == true) {
1157
			    echo "  <td bgcolor='#EEEEEE' onClick=\"document.location='{$ta[2]}'\"><B>&nbsp;&nbsp;&nbsp;{$ta[0]}";
1158
			    echo "&nbsp;&nbsp;&nbsp;";
1159
			    echo "<font size='-12'>&nbsp;</td>\n";
1160
		    } else {
1161
			    echo "  <td bgcolor='#777777' onClick=\"document.location='{$ta[2]}'\"><B>&nbsp;&nbsp;&nbsp;<a href='{$ta[2]}'>";
1162
			    echo "<font color='white'>{$ta[0]}</a>&nbsp;&nbsp;&nbsp;";
1163
			    echo "<font size='-12'>&nbsp;</td>\n";
1164
		    }
1165
	    }
1166
	    echo "</tr>\n<tr height='5px'>\n";
1167
	    foreach ($tab_array as $ta) {
1168
		    if($ta[1] == true) {
1169
			    echo "  <td bgcolor='#EEEEEE' onClick=\"document.location='{$ta[2]}'\"></td>\n";
1170
		    } else {
1171
			    echo "  <td bgcolor='#777777' onClick=\"document.location='{$ta[2]}'\"></td>\n";
1172
		    }
1173
		    $tabscounter++;
1174
	    }
1175
	    echo " </tr>\n";
1176
	    echo "</table>\n";
1177
	    
1178
	    echo "<script type=\"text/javascript\">";
1179
	    echo "NiftyCheck();\n";
1180
	    echo "Rounded(\"div#tabactive\",\"top\",\"#FFF\",\"#EEEEEE\",\"smooth\");\n";
1181
	    for($x=0; $x<$tabscounter; $x++) 
1182
		    echo "Rounded(\"div#tabdeactive{$x}\",\"top\",\"#FFF\",\"#777777\",\"smooth\");\n";
1183
	    echo "</script>";
1184
    }
1185

    
1186

    
1187
/****f* pfsense-utils/display_topbar
1188
 * NAME
1189
 *   display_topbar - top a table off with rounded edges
1190
 * INPUTS
1191
 *   $text	- (optional) Text to include in bar
1192
 * RESULT
1193
 *   null
1194
 ******/
1195
function display_topbar($text = "", $bg_color="#990000", $replace_color="#FFFFFF", $rounding_style="smooth") {	    
1196
	echo "     <table width='100%' cellpadding='0' cellspacing='0'>\n";
1197
	echo "       <tr height='1'>\n";
1198
	echo "         <td width='100%' valign='top' color='{$bg_color}' bgcolor='{$bg_color}'>";
1199
	echo "		<div id='topbar'></div></td>\n";
1200
	echo "       </tr>\n";
1201
	echo "       <tr height='1'>\n";
1202
	if ($text != "")
1203
		echo "         <td height='1' class='listtopic'>{$text}</td>\n";
1204
	else
1205
		echo "         <td height='1' class='listtopic'></td>\n";
1206
	echo "       </tr>\n";
1207
	echo "     </table>";
1208
	echo "<script type=\"text/javascript\">";
1209
	echo "NiftyCheck();\n";
1210
	echo "Rounded(\"div#topbar\",\"top\",\"{$replace_color}\",\"{$bg_color}\",\"{$rounding_style}\");\n";
1211
	echo "</script>";
1212
}
1213

    
1214
/****f* pfsense-utils/generate_random_mac_address
1215
 * NAME
1216
 *   generate_random_mac - generates a random mac address
1217
 * INPUTS
1218
 *   none
1219
 * RESULT
1220
 *   $mac - a random mac address
1221
 ******/
1222
function generate_random_mac_address() {
1223
	$mac = "00:a0:8e";
1224
	for($x=0; $x<3; $x++) 
1225
	    $mac .= ":" . dechex(rand(16, 255));
1226

    
1227
	return $mac;
1228
}
1229

    
1230
/****f* pfsense-utils/strncpy
1231
 * NAME
1232
 *   strncpy - copy strings
1233
 * INPUTS
1234
 *   &$dst, $src, $length
1235
 * RESULT
1236
 *   none
1237
 ******/
1238
function strncpy(&$dst, $src, $length) {
1239
	if (strlen($src) > $length) {
1240
		$dst = substr($src, 0, $length);
1241
	} else {
1242
		$dst = $src;
1243
	}
1244
}
1245

    
1246
/****f* pfsense-utils/reload_interfaces_sync
1247
 * NAME
1248
 *   reload_interfaces - reload all interfaces
1249
 * INPUTS
1250
 *   none
1251
 * RESULT
1252
 *   none
1253
 ******/
1254
function reload_interfaces_sync() {
1255
	global $config, $g;
1256
	
1257
	if(file_exists("{$g['tmp_path']}/config.cache"))
1258
		unlink("{$g['tmp_path']}/config.cache");
1259
	
1260
	/* parse config.xml again */
1261
	$config = parse_config(true);
1262

    
1263
	/* delete all old interface information */
1264
	$iflist = split(" ", str_replace("\n", "", `/sbin/ifconfig -l`));
1265
	foreach ($iflist as $ifent => $ifname) {
1266
		$ifname_real = convert_friendly_interface_to_real_interface_name($ifname);
1267
		mwexec("/sbin/ifconfig {$ifname_real} down");
1268
		mwexec("/sbin/ifconfig {$ifname_real} delete");
1269
	}
1270

    
1271
	/* set up LAN interface */
1272
	interfaces_lan_configure();
1273

    
1274
	/* set up WAN interface */
1275
	interfaces_wan_configure();
1276

    
1277
	/* set up Optional interfaces */
1278
	interfaces_optional_configure();
1279
        
1280
	/* set up static routes */
1281
	system_routing_configure();
1282
	
1283
	/* enable routing */
1284
	system_routing_enable();
1285
	
1286
	/* setup captive portal if needed */
1287
	captiveportal_configure();
1288
	
1289
	/* bring up carp interfaces */
1290
	interfaces_carp_configure();
1291
	
1292
	/* bring up carp interfaces*/
1293
	interfaces_carp_bring_up_final();	
1294
}
1295

    
1296
/****f* pfsense-utils/reload_all
1297
 * NAME
1298
 *   reload_all - triggers a reload of all settings
1299
 *   * INPUTS
1300
 *   none
1301
 * RESULT
1302
 *   none
1303
 ******/
1304
function reload_all() {
1305
	touch("/tmp/reload_all");
1306
}
1307

    
1308
/****f* pfsense-utils/reload_interfaces
1309
 * NAME
1310
 *   reload_interfaces - triggers a reload of all interfaces
1311
 * INPUTS
1312
 *   none
1313
 * RESULT
1314
 *   none
1315
 ******/
1316
function reload_interfaces() {
1317
	touch("/tmp/reload_interfaces");
1318
}
1319

    
1320
/****f* pfsense-utils/sync_webgui_passwords
1321
 * NAME
1322
 *   sync_webgui_passwords - syncs webgui and ssh passwords
1323
 * INPUTS
1324
 *   none
1325
 * RESULT
1326
 *   none
1327
 ******/
1328
function sync_webgui_passwords() {
1329
	global $config, $g;
1330
	conf_mount_rw();
1331
	$fd = fopen("{$g['varrun_path']}/htpasswd", "w");
1332
	if (!$fd) {
1333
		printf("Error: cannot open htpasswd in system_password_configure().\n");
1334
		return 1;
1335
	}
1336
	/* set admin account */
1337
	$username = $config['system']['username'];
1338
	
1339
	/* set defined user account */
1340
	if($username <> "admin") {
1341
		$username = $config['system']['username'];
1342
		fwrite($fd, $username . ":" . $config['system']['password'] . "\n");
1343
	} else {
1344
		fwrite($fd, $username . ":" . $config['system']['password'] . "\n");	
1345
	}	
1346
	fclose($fd);
1347
	chmod("{$g['varrun_path']}/htpasswd", 0600);	
1348
	$crypted_pw = $config['system']['password'];
1349
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
1350
	mwexec("/usr/sbin/pwd_mkdb /etc/master.passwd");
1351
	/* sync root */
1352
	$fd = popen("/usr/sbin/pw usermod -n root -H 0", "w");
1353
	fwrite($fd, $crypted_pw);
1354
	pclose($fd);
1355
	mwexec("/usr/sbin/pw usermod -n root -s /bin/sh");
1356
	/* sync admin */
1357
	$fd = popen("/usr/sbin/pw usermod -n admin -H 0", "w");
1358
	fwrite($fd, $crypted_pw);
1359
	pclose($fd);
1360
	mwexec("/usr/sbin/pw usermod -n admin -s /etc/rc.initial");
1361
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
1362
	mwexec("/usr/sbin/pwd_mkdb /etc/master.passwd");
1363
	conf_mount_ro();
1364
}
1365

    
1366
/****f* pfsense-utils/reload_all_sync
1367
 * NAME
1368
 *   reload_all - reload all settings
1369
 *   * INPUTS
1370
 *   none
1371
 * RESULT
1372
 *   none
1373
 ******/
1374
function reload_all_sync() {
1375
	global $config, $g;
1376
	
1377
	if(file_exists("{$g['tmp_path']}/config.cache"))
1378
		unlink("{$g['tmp_path']}/config.cache");
1379
	
1380
	/* parse config.xml again */
1381
	$config = parse_config(true);
1382

    
1383
	/* set up our timezone */
1384
	system_timezone_configure();
1385

    
1386
	/* set up our hostname */
1387
	system_hostname_configure();
1388

    
1389
	/* make hosts file */
1390
	system_hosts_generate();
1391

    
1392
	/* generate resolv.conf */
1393
	system_resolvconf_generate();
1394

    
1395
	/* delete all old interface information */
1396
	$iflist = split(" ", str_replace("\n", "", `/sbin/ifconfig -l`));
1397
	foreach ($iflist as $ifent => $ifname) {
1398
		$ifname_real = convert_friendly_interface_to_real_interface_name($ifname);
1399
		mwexec("/sbin/ifconfig {$ifname_real} down");
1400
		mwexec("/sbin/ifconfig {$ifname_real} delete");
1401
	}
1402

    
1403
	/* set up LAN interface */
1404
	interfaces_lan_configure();
1405

    
1406
	/* set up WAN interface */
1407
	interfaces_wan_configure();
1408

    
1409
	/* set up Optional interfaces */
1410
	interfaces_optional_configure();
1411
        
1412
	/* bring up carp interfaces */
1413
	interfaces_carp_configure();
1414
	
1415
	/* set up static routes */
1416
	system_routing_configure();
1417

    
1418
	/* enable routing */
1419
	system_routing_enable();
1420
	
1421
	/* ensure passwords are sync'd */
1422
	system_password_configure();
1423

    
1424
	/* start dnsmasq service */
1425
	services_dnsmasq_configure();
1426

    
1427
	/* start dyndns service */
1428
	services_dyndns_configure();
1429

    
1430
	/* start DHCP service */
1431
	services_dhcpd_configure();
1432

    
1433
	/* start the NTP client */
1434
	system_ntp_configure();
1435

    
1436
	/* start ftp proxy helpers if they are enabled */
1437
	system_start_ftp_helpers();
1438
	
1439
	/* start the captive portal */
1440
	captiveportal_configure();
1441

    
1442
        /* reload the filter */
1443
	filter_configure_sync();
1444

    
1445
	/* bring up carp interfaces*/
1446
	interfaces_carp_bring_up_final();
1447

    
1448
	/* sync pw database */
1449
	conf_mount_rw();
1450
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
1451
	conf_mount_ro();
1452

    
1453
	/* restart sshd */
1454
	touch("/tmp/start_sshd");
1455
	
1456
}
1457

    
1458
?>
(14-14/26)