Project

General

Profile

Download (42.5 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-RELEASE&format=html
446
	 * Only the following drivers support large frames
447
	 */
448
	/* 'de' chipset purposely left out of this list
449
	 * requires defining BIG_PACKET in the
450
	 * /usr/src/sys/pci/if_de.c source file and rebuilding the
451
	 * kernel or module.  The hack works only for the 21041,
452
	 * 21140, and 21140A chips.
453
	 */
454
	$capable = array("bfe", "bge", "dc", "em", "fxp", "gem", "hme", 
455
		"ixgb", "nge", "re", "rl", "sis", "ste", "ti", "tl", "tx",
456
		"txp", "xl");
457
	
458
	$int_family = preg_split("/[0-9]+/", $int);
459

    
460
	if (in_array($int_family[0], $capable))
461
		return true;
462
	else
463
		return false;
464
}
465

    
466
/*
467
 * does_interface_exist($interface): return true or false if a interface is detected.
468
 */
469
function does_interface_exist($interface) {
470
    $ints = exec_command("/sbin/ifconfig -l");
471
    if(stristr($ints, $interface) !== false)
472
	return true;
473
    else
474
	return false;
475
}
476

    
477
/*
478
 * convert_ip_to_network_format($ip, $subnet): converts an ip address to network form
479
 */
480
function convert_ip_to_network_format($ip, $subnet) {
481
    $ipsplit = split('[.]', $ip);
482
    $string = $ipsplit[0] . "." . $ipsplit[1] . "." . $ipsplit[2] . ".0/" . $subnet;
483
    return $string;
484
}
485

    
486
/*
487
 * find_interface_ip($interface): return the interface ip (first found)
488
 */
489
function find_interface_ip($interface) {
490
    if(does_interface_exist($interface) == false) return;
491
    $ip = exec_command("/sbin/ifconfig {$interface} | /usr/bin/grep -w \"inet\" | /usr/bin/cut -d\" \" -f 2");
492
    $ip = str_replace("\n","",$ip);
493
    return $ip;
494
}
495

    
496
function guess_interface_from_ip($ipaddress) {
497
    $ints = `/sbin/ifconfig -l`;
498
    $ints_split = split(" ", $ints);
499
    $ip_subnet_split = split("\.", $ipaddress);
500
    $ip_subnet = $ip_subnet_split[0] . "." . $ip_subnet_split[1] . "." . $ip_subnet_split[2] . ".";
501
    foreach($ints_split as $int) {
502
        $ip = find_interface_ip($int);
503
        $ip_split = split("\.", $ip);
504
        $ip_tocheck = $ip_split[0] . "." . $ip_split[1] . "." . $ip_split[2] . ".";
505
        if(stristr($ip_tocheck, $ip_subnet) != false) return $int;
506
    }
507
}
508

    
509
function filter_opt_interface_to_real($opt) {
510
    global $config;
511
    return $config['interfaces'][$opt]['if'];
512
}
513

    
514
function filter_get_opt_interface_descr($opt) {
515
    global $config;
516
    return $config['interfaces'][$opt]['descr'];
517
}
518

    
519
function get_friendly_interface_list_as_array() {
520
    global $config;
521
    $ints = array();
522
    $ifdescrs = array('wan', 'lan');
523
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++) {
524
		$ifdescrs['opt' . $j] = "opt" . $j;
525
    }
526
    $ifdescrs = get_interface_list();
527
    foreach ($ifdescrs as $ifdescr => $ifname) {
528
		array_push($ints,$ifdescr);
529
    }
530
    return $ints;
531
}
532

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

    
551
/*
552
 *  filter_translate_type_to_real_interface($interface): returns the real interface name
553
 *                                                       for a friendly interface.  ie: wan
554
 */
555
function filter_translate_type_to_real_interface($interface) {
556
    global $config;
557
    if($config['interfaces'][$interface]['if'] <> "") {
558
	return $config['interfaces'][$interface]['if'];
559
    } else {
560
	return $interface;
561
    }
562
}
563

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

    
587
/*
588
 * get_pfsync_interface_status($pfsyncinterface): returns the status of a pfsync
589
 */
590
function get_pfsync_interface_status($pfsyncinterface) {
591
    $result = does_interface_exist($pfsyncinterface);
592
    if($result <> true) return;
593
    $status = exec_command("/sbin/ifconfig {$pfsyncinterface} | /usr/bin/grep \"pfsync:\" | /usr/bin/cut -d\" \" -f5");
594
    return $status;
595
}
596

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

    
617
/*
618
 * setup_filter_bridge(): toggle filtering bridge
619
 */
620
function setup_filter_bridge() {
621
	global $config, $g;
622
	if(isset($config['bridge']['filteringbridge'])) {
623
		mwexec("/sbin/sysctl net.link.bridge.pfil_member=1");
624
		mwexec("/sbin/sysctl net.link.bridge.pfil_bridge=1");
625
	} else {		
626
		mwexec("/sbin/sysctl net.link.bridge.pfil_member=0");
627
		mwexec("/sbin/sysctl net.link.bridge.pfil_bridge=0");
628
	}
629
}
630

    
631
/*
632
 * find_number_of_created_bridges(): returns the number of currently created bridges
633
 */
634
function find_number_of_created_bridges() {
635
    return `/sbin/ifconfig | grep \"bridge[0-999]\:" | wc -l`;
636
}
637

    
638
/*
639
 * add_rule_to_anchor($anchor, $rule): adds the specified rule to an anchor
640
 */
641
function add_rule_to_anchor($anchor, $rule, $label) {
642
    mwexec("echo " . $rule . " | /sbin/pfctl -a " . $anchor . ":" . $label . " -f -");
643
}
644

    
645
/*
646
 * remove_text_from_file
647
 * remove $text from file $file
648
 */
649
function remove_text_from_file($file, $text) {
650
    global $fd_log;
651
    fwrite($fd_log, "Adding needed text items:\n");
652
    $filecontents = exec_command_and_return_text("cat " . $file);
653
    $textTMP = str_replace($text, "", $filecontents);
654
    $text .= $textTMP;
655
    fwrite($fd_log, $text . "\n");
656
    $fd = fopen($file, "w");
657
    fwrite($fd, $text);
658
    fclose($fd);
659
}
660

    
661
/*
662
 * add_text_to_file($file, $text): adds $text to $file.
663
 * replaces the text if it already exists.
664
 */
665
function add_text_to_file($file, $text) {
666
	if(file_exists($file) and is_writable($file)) {
667
		$filecontents = file($file);
668
		$filecontents[] = $text;
669
		$tmpfile = get_tmp_file();
670
		$fout = fopen($tmpfile, "w");
671
		foreach($filecontents as $line) {
672
			fwrite($fout, rtrim($line) . "\n");
673
		}
674
		fclose($fout);
675
		rename($tmpfile, $file);
676
		return true;
677
	} else {
678
		return false;
679
	}
680
}
681

    
682
/*
683
 *   after_sync_bump_adv_skew(): create skew values by 1S
684
 */
685
function after_sync_bump_adv_skew() {
686
	global $config, $g;
687
	$processed_skew = 1;
688
	$a_vip = &$config['virtualip']['vip'];
689
	foreach ($a_vip as $vipent) {
690
		if($vipent['advskew'] <> "") {
691
			$processed_skew = 1;
692
			$vipent['advskew'] = $vipent['advskew']+1;
693
		}
694
	}
695
	if($processed_skew == 1)
696
		write_config("After synch increase advertising skew");
697
}
698

    
699
/*
700
 * get_filename_from_url($url): converts a url to its filename.
701
 */
702
function get_filename_from_url($url) {
703
	return basename($url);
704
}
705

    
706
/*
707
 *   update_output_window: update bottom textarea dynamically.
708
 */
709
function update_output_window($text) {
710
    $log = ereg_replace("\n", "\\n", $text);
711
    echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = \"" . $log . "\";</script>";
712
}
713

    
714
/*
715
 *   get_dir: return an array of $dir
716
 */
717
function get_dir($dir) {
718
    $dir_array = array();
719
    $d = dir($dir);
720
    while (false !== ($entry = $d->read())) {
721
	array_push($dir_array, $entry);
722
    }
723
    $d->close();
724
    return $dir_array;
725
}
726

    
727
/*
728
 *   update_output_window: update top textarea dynamically.
729
 */
730
function update_status($status) {
731
    echo "\n<script language=\"JavaScript\">document.forms[0].status.value=\"" . $status . "\";</script>";
732
}
733

    
734
/*
735
 *   exec_command_and_return_text_array: execute command and return output
736
 */
737
function exec_command_and_return_text_array($command) {
738
	$fd = popen($command . " 2>&1 ", "r");
739
	while(!feof($fd)) {
740
		$tmp .= fread($fd,49);
741
	}
742
	fclose($fd);
743
	$temp_array = split("\n", $tmp);
744
	return $temp_array;
745
}
746

    
747
/*
748
 *   exec_command_and_return_text: execute command and return output
749
 */
750
function exec_command_and_return_text($command) {
751
    return exec_command($command);
752
}
753

    
754
/*
755
 *   exec_command_and_return_text: execute command and update output window dynamically
756
 */
757
function execute_command_return_output($command) {
758
    global $fd_log;
759
    $fd = popen($command . " 2>&1 ", "r");
760
    echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = \"\";</script>";
761
    $counter = 0;
762
    $counter2 = 0;
763
    while(!feof($fd)) {
764
	$tmp = fread($fd, 50);
765
	$tmp1 = ereg_replace("\n","\\n", $tmp);
766
	$text = ereg_replace("\"","'", $tmp1);
767
	if($lasttext == "..") {
768
	    $text = "";
769
	    $lasttext = "";
770
	    $counter=$counter-2;
771
	} else {
772
	    $lasttext .= $text;
773
	}
774
	if($counter > 51) {
775
	    $counter = 0;
776
	    $extrabreak = "\\n";
777
	} else {
778
	    $extrabreak = "";
779
	    $counter++;
780
	}
781
	if($counter2 > 600) {
782
	    echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = \"\";</script>";
783
	    $counter2 = 0;
784
	} else
785
	    $counter2++;
786
	echo "\n<script language=\"JavaScript\">this.document.forms[0].output.value = this.document.forms[0].output.value + \"" . $text . $extrabreak .  "\"; f('output'); </script>";
787
    }
788
    fclose($fd);
789
}
790

    
791
/*
792
 * convert_friendly_interface_to_real_interface_name($interface): convert WAN to FXP0
793
 */
794
function convert_friendly_interface_to_real_interface_name($interface) {
795
    global $config;
796
    $lc_interface = strtolower($interface);
797
    if($lc_interface == "lan") return $config['interfaces']['lan']['if'];
798
    if($lc_interface == "wan") return $config['interfaces']['wan']['if'];
799
    $ifdescrs = array();
800
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++)
801
	$ifdescrs['opt' . $j] = "opt" . $j;
802
    foreach ($ifdescrs as $ifdescr => $ifname) {
803
	if(strtolower($ifname) == $lc_interface)
804
	    return $config['interfaces'][$ifname]['if'];
805
	if(strtolower($config['interfaces'][$ifname]['descr']) == $lc_interface)
806
	    return $config['interfaces'][$ifname]['if'];
807
    }
808
    return $interface;
809
}
810

    
811
/*
812
 * convert_real_interface_to_friendly_interface_name($interface): convert fxp0 -> wan, etc.
813
 */
814
function convert_real_interface_to_friendly_interface_name($interface) {
815
    global $config;
816
    $ifdescrs = array('wan', 'lan');
817
    for ($j = 1; isset($config['interfaces']['opt' . $j]); $j++)
818
	$ifdescrs['opt' . $j] = "opt" . $j;
819
    foreach ($ifdescrs as $ifdescr => $ifname) {
820
	$int = filter_translate_type_to_real_interface($ifname);
821
	if($ifname == $interface) return $ifname;
822
	if($int == $interface) return $ifname;
823
    }
824
    return $interface;
825
}
826

    
827
/*
828
 * update_progress_bar($percent): updates the javascript driven progress bar.
829
 */
830
function update_progress_bar($percent) {
831
    if($percent > 100) $percent = 1;
832
    echo "\n<script type=\"text/javascript\" language=\"javascript\">";
833
    echo "\ndocument.progressbar.style.width='" . $percent . "%';";
834
    echo "\n</script>";
835
}
836

    
837
/*
838
 * gather_altq_queue_stats():  gather alq queue stats and return an array that
839
 *                             is queuename|qlength|measured_packets
840
 *                             NOTE: this command takes 5 seconds to run
841
 */
842
function gather_altq_queue_stats($dont_return_root_queues) {
843
    mwexec("/usr/bin/killall -9 pfctl");
844
    $stats = `/sbin/pfctl -vvsq & /bin/sleep 5;/usr/bin/killall pfctl 2>/dev/null`;
845
    $stats_array = split("\n", $stats);
846
    $queue_stats = array();
847
    foreach ($stats_array as $stats_line) {
848
        if (preg_match_all("/queue\s+(\w+)\s+/",$stats_line,$match_array))
849
            $queue_name = $match_array[1][0];
850
        if (preg_match_all("/measured:\s+.*packets\/s\,\s(.*)\s+\]/",$stats_line,$match_array))
851
            $speed = $match_array[1][0];
852
        if (preg_match_all("/borrows:\s+(.*)/",$stats_line,$match_array))
853
            $borrows = $match_array[1][0];
854
        if (preg_match_all("/suspends:\s+(.*)/",$stats_line,$match_array))
855
            $suspends = $match_array[1][0];
856
        if (preg_match_all("/dropped pkts:\s+(.*)/",$stats_line,$match_array))
857
            $drops = $match_array[1][0];
858
        if (preg_match_all("/measured:\s+(.*)packets/",$stats_line,$match_array)) {
859
            $measured = $match_array[1][0];
860
	    if($dont_return_root_queues == true)
861
		if(stristr($queue_name,"root_") == false)
862
		    array_push($queue_stats, "{$queue_name}|{$speed}|{$measured}|{$borrows}|{$suspends}|{$drops}");
863
        }
864
    }
865
    return $queue_stats;
866
}
867

    
868
/*
869
 * reverse_strrchr($haystack, $needle):  Return everything in $haystack up to the *last* instance of $needle.
870
 *					 Useful for finding paths and stripping file extensions.
871
 */
872
function reverse_strrchr($haystack, $needle)
873
{
874
               return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) +1 ) : false;
875
}
876

    
877
/*
878
 *  backup_config_section($section): returns as an xml file string of
879
 *                                   the configuration section
880
 */
881
function backup_config_section($section) {
882
    global $config;
883
    $new_section = &$config[$section];
884
    /* generate configuration XML */
885
    $xmlconfig = dump_xml_config($new_section, $section);
886
    $xmlconfig = str_replace("<?xml version=\"1.0\"?>", "", $xmlconfig);
887
    return $xmlconfig;
888
}
889

    
890
/*
891
 *  backup_config_ts_scheduler(): returns the traffic shaper scheduler for backup
892
 */
893
function backup_config_ts_scheduler() {
894
    global $config;
895
    $new_section = &$config['syste']['schedulertype'];
896
    /* generate configuration XML */
897
    $xmlconfig = dump_xml_config($new_section, $section);
898
    $xmlconfig = str_replace("<?xml version=\"1.0\"?>", "", $xmlconfig);
899
    return $xmlconfig;
900
}
901

    
902
/*
903
 *  backup_config_section($section): returns as an xml file string of
904
 *                                   the configuration section
905
 */
906
function backup_vip_config_section() {
907
    global $config;
908
    $new_section = &$config['virtualip'];
909
    foreach($new_section['vip'] as $section) {
910
	if($section['mode'] == "proxyarp") {
911
		unset($section);		
912
	}
913
	if($section['advskew'] <> "") {
914
		$section_val = intval($section['advskew']);
915
		$section_val=$section_val+100;
916
		if($section_val > 255)
917
			$section_val = 255;
918
		$section['advskew'] = $section_val;
919
	}
920
	$temp['vip'][] = $section;
921
    }
922
    return $temp;
923
}
924

    
925
/*
926
 *  restore_config_section($section, new_contents): restore a configuration section,
927
 *                                                  and write the configuration out
928
 *                                                  to disk/cf.
929
 */
930
function restore_config_section($section, $new_contents) {
931
    global $config;
932
    conf_mount_rw();
933
    $fout = fopen("{$g['tmp_path']}/tmpxml","w");
934
    fwrite($fout, $new_contents);
935
    fclose($fout);
936
    $section_xml = parse_xml_config($g['tmp_path'] . "/tmpxml", $section);
937
    $config[$section] = &$section_xml;
938
    unlink($g['tmp_path'] . "/tmpxml");
939
    write_config("Restored {$section} of config file (maybe from CARP partner)");
940
    conf_mount_ro();
941
    return;
942
}
943

    
944
/*
945
 * http_post($server, $port, $url, $vars): does an http post to a web server
946
 *                                         posting the vars array.
947
 * written by nf@bigpond.net.au
948
 */
949
function http_post($server, $port, $url, $vars) {
950
    $user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)";
951
    $urlencoded = "";
952
    while (list($key,$value) = each($vars))
953
	$urlencoded.= urlencode($key) . "=" . urlencode($value) . "&";
954
    $urlencoded = substr($urlencoded,0,-1);
955

    
956
    $content_length = strlen($urlencoded);
957

    
958
    $headers = "POST $url HTTP/1.1
959
Accept: */*
960
Accept-Language: en-au
961
Content-Type: application/x-www-form-urlencoded
962
User-Agent: $user_agent
963
Host: $server
964
Connection: Keep-Alive
965
Cache-Control: no-cache
966
Content-Length: $content_length
967

    
968
";
969

    
970
    $fp = fsockopen($server, $port, $errno, $errstr);
971
    if (!$fp) {
972
	return false;
973
    }
974

    
975
    fputs($fp, $headers);
976
    fputs($fp, $urlencoded);
977

    
978
    $ret = "";
979
    while (!feof($fp))
980
	$ret.= fgets($fp, 1024);
981

    
982
    fclose($fp);
983

    
984
    return $ret;
985

    
986
}
987

    
988
/*
989
 *  php_check_syntax($code_tocheck, $errormessage): checks $code_to_check for errors
990
 */
991
if (!function_exists('php_check_syntax')){
992
   function php_check_syntax($code_to_check, &$errormessage){
993
	return false;
994
        $fout = fopen("/tmp/codetocheck.php","w");
995
        $code = $_POST['content'];
996
        $code = str_replace("<?php", "", $code);
997
        $code = str_replace("?>", "", $code);
998
        fwrite($fout, "<?php\n\n");
999
        fwrite($fout, $code_to_check);
1000
        fwrite($fout, "\n\n?>\n");
1001
        fclose($fout);
1002
        $command = "/usr/local/bin/php -l /tmp/codetocheck.php";
1003
        $output = exec_command($command);
1004
        if (stristr($output, "Errors parsing") == false) {
1005
            echo "false\n";
1006
            $errormessage = '';
1007
            return(false);
1008
        } else {
1009
            $errormessage = $output;
1010
            return(true);
1011
        }
1012
    }
1013
}
1014

    
1015
/*
1016
 *  php_check_filename_syntax($filename, $errormessage): checks the file $filename for errors
1017
 */
1018
if (!function_exists('php_check_syntax')){
1019
   function php_check_syntax($code_to_check, &$errormessage){
1020
	return false;
1021
        $command = "/usr/local/bin/php -l " . $code_to_check;
1022
        $output = exec_command($command);
1023
        if (stristr($output, "Errors parsing") == false) {
1024
            echo "false\n";
1025
            $errormessage = '';
1026
            return(false);
1027
        } else {
1028
            $errormessage = $output;
1029
            return(true);
1030
        }
1031
    }
1032
}
1033

    
1034
/*
1035
 * rmdir_recursive($path,$follow_links=false)
1036
 * Recursively remove a directory tree (rm -rf path)
1037
 * This is for directories _only_
1038
 */
1039
function rmdir_recursive($path,$follow_links=false) {
1040
	$to_do = glob($path);
1041
	if(!is_array($to_do)) $to_do = array($to_do);
1042
	foreach($to_do as $workingdir) { // Handle wildcards by foreaching.
1043
		if(file_exists($workingdir)) {
1044
			if(is_dir($workingdir)) {
1045
				$dir = opendir($workingdir);
1046
				while ($entry = readdir($dir)) {
1047
					if (is_file("$workingdir/$entry") || ((!$follow_links) && is_link("$workingdir/$entry")))
1048
						unlink("$workingdir/$entry");
1049
					elseif (is_dir("$workingdir/$entry") && $entry!='.' && $entry!='..')
1050
						rmdir_recursive("$workingdir/$entry");
1051
				}
1052
				closedir($dir);
1053
				rmdir($workingdir);
1054
			} elseif (is_file($workingdir)) {
1055
				unlink($workingdir);
1056
			}
1057
               	}
1058
	}
1059
	return;
1060
}
1061

    
1062
/*
1063
 *     get_memory()
1064
 *     returns an array listing the amount of
1065
 *     memory installed in the hardware
1066
 *     [0]real and [1]available
1067
 */
1068
function get_memory() {
1069
	if(file_exists("/var/log/dmesg.boot")) {
1070
		$mem = `cat /var/log/dmesg.boot | grep memory`;
1071
		if (preg_match_all("/real memory  = .* \((.*) MB/", $mem, $matches))
1072
			$real = $matches[1];
1073
		if (preg_match_all("/avail memory = .* \((.*) MB/", $mem, $matches))
1074
			$avail = $matches[1];
1075
		return array($real[0],$avail[0]);
1076
	}
1077
	return array("64","64");
1078
}
1079

    
1080

    
1081
/*
1082
 *    safe_mkdir($path, $mode = 0755)
1083
 *    create directory if it doesn't already exist and isn't a file!
1084
 */
1085
function safe_mkdir($path, $mode=0755) {
1086
	global $g;
1087

    
1088
	/* cdrom is ro. */
1089
	if($g['platform'] == "cdrom")
1090
		return false;
1091
	
1092
	if (!is_file($path) && !is_dir($path))
1093
		return mkdir($path, $mode);
1094
	else
1095
		return false;
1096
}
1097

    
1098
/*
1099
 * make_dirs($path, $mode = 0755)
1100
 * create directory tree recursively (mkdir -p)
1101
 */
1102
function make_dirs($path, $mode = 0755) {
1103
	/* is dir already created? */
1104
	if(is_dir($path)) return;
1105
	/* create directory in question */
1106
	$to_create = explode("/", $path);
1107
	foreach($to_create as $tc) 
1108
	    if(!is_dir($tc))
1109
		safe_mkdir($path, $mode);
1110
}
1111

    
1112
/*
1113
 * check_firmware_version(): Check whether the current firmware installed is the most recently released.
1114
 */
1115
function check_firmware_version($tocheck = "all", $return_php = true) {
1116
        global $g, $config;
1117
	$xmlrpc_base_url = $g['xmlrpcbaseurl'];
1118
        $xmlrpc_path = $g['xmlrpcpath'];
1119
	$rawparams = array("firmware" => array("version" => trim(file_get_contents('/etc/version'))),
1120
			"kernel"   => array("version" => trim(file_get_contents('/etc/version_kernel'))),
1121
			"base"     => array("version" => trim(file_get_contents('/etc/version_base'))),
1122
			"platform" => trim(file_get_contents('/etc/platform'))
1123
		);
1124
	if($tocheck == "all") {
1125
		$params = $rawparams;
1126
	} else {
1127
		foreach($tocheck as $check) {
1128
			$params['check'] = $rawparams['check'];
1129
			$params['platform'] = $rawparams['platform'];
1130
		}
1131
	}
1132
	if($config['system']['firmware']['branch']) {
1133
		$params['branch'] = $config['system']['firmware']['branch'];
1134
	}
1135
	$xmlparams = php_value_to_xmlrpc($params);
1136
        $msg = new XML_RPC_Message('pfsense.get_firmware_version', array($xmlparams));
1137
        $cli = new XML_RPC_Client($xmlrpc_path, $xmlrpc_base_url);
1138
	//$cli->setDebug(1);
1139
	$resp = $cli->send($msg, 10);
1140
	if(!$resp or $resp->faultCode()) {
1141
		$raw_versions = false;
1142
	} else {
1143
		$raw_versions = XML_RPC_decode($resp->value());
1144
		$raw_versions["current"] = $params;
1145
	}
1146
	return $raw_versions;
1147
}
1148

    
1149
function get_disk_info() {
1150
        exec("df -h | grep -w '/' | awk '{ print $2, $3, $4, $5 }'", $diskout);
1151
        return explode(' ', $diskout[0]);
1152
        // $size, $used, $avail, $cap
1153
}
1154

    
1155
/****f* pfsense-utils/display_top_tabs
1156
 * NAME
1157
 *   display_top_tabs - display tabs with rounded edges
1158
 * INPUTS
1159
 *   $text	- array of tabs
1160
 * RESULT
1161
 *   null
1162
 ******/
1163
    function display_top_tabs($tab_array) {
1164
	    echo "<table cellpadding='0' cellspacing='0'>\n";
1165
	    echo " <tr height='1'>\n";
1166
	    $tabscounter = 0;
1167
	    foreach ($tab_array as $ta) {
1168
		    if($ta[1] == true) {
1169
			    echo "  <td bgcolor='#EEEEEE' onClick=\"document.location='{$ta[2]}'\"><div id='tabactive'></div></td>\n";
1170
		    } else {
1171
			    echo "  <td bgcolor='#777777' onClick=\"document.location='{$ta[2]}'\"><div id='tabdeactive{$tabscounter}'></div></td>\n";
1172
		    }
1173
		    $tabscounter++;
1174
	    }
1175
	    echo "</tr>\n<tr>\n";
1176
	    foreach ($tab_array as $ta) {
1177
		    if($ta[1] == true) {
1178
			    echo "  <td bgcolor='#EEEEEE' onClick=\"document.location='{$ta[2]}'\"><B>&nbsp;&nbsp;&nbsp;{$ta[0]}";
1179
			    echo "&nbsp;&nbsp;&nbsp;";
1180
			    echo "<font size='-12'>&nbsp;</td>\n";
1181
		    } else {
1182
			    echo "  <td bgcolor='#777777' onClick=\"document.location='{$ta[2]}'\"><B>&nbsp;&nbsp;&nbsp;<a href='{$ta[2]}'>";
1183
			    echo "<font color='white'>{$ta[0]}</a>&nbsp;&nbsp;&nbsp;";
1184
			    echo "<font size='-12'>&nbsp;</td>\n";
1185
		    }
1186
	    }
1187
	    echo "</tr>\n<tr height='5px'>\n";
1188
	    foreach ($tab_array as $ta) {
1189
		    if($ta[1] == true) {
1190
			    echo "  <td bgcolor='#EEEEEE' onClick=\"document.location='{$ta[2]}'\"></td>\n";
1191
		    } else {
1192
			    echo "  <td bgcolor='#777777' onClick=\"document.location='{$ta[2]}'\"></td>\n";
1193
		    }
1194
		    $tabscounter++;
1195
	    }
1196
	    echo " </tr>\n";
1197
	    echo "</table>\n";
1198
	    
1199
	    echo "<script type=\"text/javascript\">";
1200
	    echo "NiftyCheck();\n";
1201
	    echo "Rounded(\"div#tabactive\",\"top\",\"#FFF\",\"#EEEEEE\",\"smooth\");\n";
1202
	    for($x=0; $x<$tabscounter; $x++) 
1203
		    echo "Rounded(\"div#tabdeactive{$x}\",\"top\",\"#FFF\",\"#777777\",\"smooth\");\n";
1204
	    echo "</script>";
1205
    }
1206

    
1207

    
1208
/****f* pfsense-utils/display_topbar
1209
 * NAME
1210
 *   display_topbar - top a table off with rounded edges
1211
 * INPUTS
1212
 *   $text	- (optional) Text to include in bar
1213
 * RESULT
1214
 *   null
1215
 ******/
1216
function display_topbar($text = "", $bg_color="#990000", $replace_color="#FFFFFF", $rounding_style="smooth") {	    
1217
	echo "     <table width='100%' cellpadding='0' cellspacing='0'>\n";
1218
	echo "       <tr height='1'>\n";
1219
	echo "         <td width='100%' valign='top' color='{$bg_color}' bgcolor='{$bg_color}'>";
1220
	echo "		<div id='topbar'></div></td>\n";
1221
	echo "       </tr>\n";
1222
	echo "       <tr height='1'>\n";
1223
	if ($text != "")
1224
		echo "         <td height='1' class='listtopic'>{$text}</td>\n";
1225
	else
1226
		echo "         <td height='1' class='listtopic'></td>\n";
1227
	echo "       </tr>\n";
1228
	echo "     </table>";
1229
	echo "<script type=\"text/javascript\">";
1230
	echo "NiftyCheck();\n";
1231
	echo "Rounded(\"div#topbar\",\"top\",\"{$replace_color}\",\"{$bg_color}\",\"{$rounding_style}\");\n";
1232
	echo "</script>";
1233
}
1234

    
1235
/****f* pfsense-utils/generate_random_mac_address
1236
 * NAME
1237
 *   generate_random_mac - generates a random mac address
1238
 * INPUTS
1239
 *   none
1240
 * RESULT
1241
 *   $mac - a random mac address
1242
 ******/
1243
function generate_random_mac_address() {
1244
	$mac = "00:a0:8e";
1245
	for($x=0; $x<3; $x++) 
1246
	    $mac .= ":" . dechex(rand(16, 255));
1247

    
1248
	return $mac;
1249
}
1250

    
1251
/****f* pfsense-utils/strncpy
1252
 * NAME
1253
 *   strncpy - copy strings
1254
 * INPUTS
1255
 *   &$dst, $src, $length
1256
 * RESULT
1257
 *   none
1258
 ******/
1259
function strncpy(&$dst, $src, $length) {
1260
	if (strlen($src) > $length) {
1261
		$dst = substr($src, 0, $length);
1262
	} else {
1263
		$dst = $src;
1264
	}
1265
}
1266

    
1267
/****f* pfsense-utils/reload_interfaces_sync
1268
 * NAME
1269
 *   reload_interfaces - reload all interfaces
1270
 * INPUTS
1271
 *   none
1272
 * RESULT
1273
 *   none
1274
 ******/
1275
function reload_interfaces_sync() {
1276
	global $config, $g;
1277
	
1278
	if(file_exists("{$g['tmp_path']}/config.cache"))
1279
		unlink("{$g['tmp_path']}/config.cache");
1280
	
1281
	/* parse config.xml again */
1282
	$config = parse_config(true);
1283

    
1284
	/* delete all old interface information */
1285
	$iflist = split(" ", str_replace("\n", "", `/sbin/ifconfig -l`));
1286
	foreach ($iflist as $ifent => $ifname) {
1287
		$ifname_real = convert_friendly_interface_to_real_interface_name($ifname);
1288
		mwexec("/sbin/ifconfig {$ifname_real} down");
1289
		mwexec("/sbin/ifconfig {$ifname_real} delete");
1290
	}
1291

    
1292
	/* set up VLAN virtual interfaces */
1293
	interfaces_vlan_configure();
1294

    
1295
	/* set up LAN interface */
1296
	interfaces_lan_configure();
1297

    
1298
	/* set up WAN interface */
1299
	interfaces_wan_configure();
1300

    
1301
	/* set up Optional interfaces */
1302
	interfaces_optional_configure();
1303
        
1304
	/* set up static routes */
1305
	system_routing_configure();
1306
	
1307
	/* enable routing */
1308
	system_routing_enable();
1309
	
1310
	/* setup captive portal if needed */
1311
	captiveportal_configure();
1312
	
1313
	/* bring up carp interfaces */
1314
	interfaces_carp_configure();
1315
	
1316
	/* bring up carp interfaces*/
1317
	interfaces_carp_bring_up_final();	
1318
}
1319

    
1320
/****f* pfsense-utils/reload_all
1321
 * NAME
1322
 *   reload_all - triggers a reload of all settings
1323
 *   * INPUTS
1324
 *   none
1325
 * RESULT
1326
 *   none
1327
 ******/
1328
function reload_all() {
1329
	touch("/tmp/reload_all");
1330
}
1331

    
1332
/****f* pfsense-utils/reload_interfaces
1333
 * NAME
1334
 *   reload_interfaces - triggers a reload of all interfaces
1335
 * INPUTS
1336
 *   none
1337
 * RESULT
1338
 *   none
1339
 ******/
1340
function reload_interfaces() {
1341
	touch("/tmp/reload_interfaces");
1342
}
1343

    
1344
/****f* pfsense-utils/sync_webgui_passwords
1345
 * NAME
1346
 *   sync_webgui_passwords - syncs webgui and ssh passwords
1347
 * INPUTS
1348
 *   none
1349
 * RESULT
1350
 *   none
1351
 ******/
1352
function sync_webgui_passwords() {
1353
	global $config, $g;
1354
	conf_mount_rw();
1355
	$fd = fopen("{$g['varrun_path']}/htpasswd", "w");
1356
	if (!$fd) {
1357
		printf("Error: cannot open htpasswd in system_password_configure().\n");
1358
		return 1;
1359
	}
1360
	/* set admin account */
1361
	$username = $config['system']['username'];
1362
	
1363
	/* set defined user account */
1364
	if($username <> "admin") {
1365
		$username = $config['system']['username'];
1366
		fwrite($fd, $username . ":" . $config['system']['password'] . "\n");
1367
	} else {
1368
		fwrite($fd, $username . ":" . $config['system']['password'] . "\n");	
1369
	}	
1370
	fclose($fd);
1371
	chmod("{$g['varrun_path']}/htpasswd", 0600);	
1372
	$crypted_pw = $config['system']['password'];
1373
	mwexec("/usr/sbin/pwd_mkdb -d /etc -p /etc/master.passwd");
1374
	mwexec("/usr/sbin/pwd_mkdb -p /etc/master.passwd");
1375
	/* sync root */
1376
	$fd = popen("/usr/sbin/pw usermod -n root -H 0", "w");
1377
	fwrite($fd, $crypted_pw);
1378
	pclose($fd);
1379
	mwexec("/usr/sbin/pw usermod -n root -s /bin/sh");
1380
	/* sync admin */
1381
	$fd = popen("/usr/sbin/pw usermod -n admin -H 0", "w");
1382
	fwrite($fd, $crypted_pw);
1383
	pclose($fd);
1384
	mwexec("/usr/sbin/pw usermod -n admin -s /etc/rc.initial");
1385
	mwexec("/usr/sbin/pwd_mkdb -d /etc -p /etc/master.passwd");
1386
	mwexec("/usr/sbin/pwd_mkdb -p /etc/master.passwd");
1387
	conf_mount_ro();
1388
}
1389

    
1390
/****f* pfsense-utils/reload_all_sync
1391
 * NAME
1392
 *   reload_all - reload all settings
1393
 *   * INPUTS
1394
 *   none
1395
 * RESULT
1396
 *   none
1397
 ******/
1398
function reload_all_sync() {
1399
	global $config, $g;
1400
	
1401
	if(file_exists("{$g['tmp_path']}/config.cache"))
1402
		unlink("{$g['tmp_path']}/config.cache");
1403
	
1404
	/* parse config.xml again */
1405
	$config = parse_config(true);
1406

    
1407
	/* set up our timezone */
1408
	system_timezone_configure();
1409

    
1410
	/* set up our hostname */
1411
	system_hostname_configure();
1412

    
1413
	/* make hosts file */
1414
	system_hosts_generate();
1415

    
1416
	/* generate resolv.conf */
1417
	system_resolvconf_generate();
1418

    
1419
	/* delete all old interface information */
1420
	$iflist = split(" ", str_replace("\n", "", `/sbin/ifconfig -l`));
1421
	foreach ($iflist as $ifent => $ifname) {
1422
		$ifname_real = convert_friendly_interface_to_real_interface_name($ifname);
1423
		mwexec("/sbin/ifconfig {$ifname_real} down");
1424
		mwexec("/sbin/ifconfig {$ifname_real} delete");
1425
	}
1426

    
1427
	/* set up VLAN virtual interfaces */
1428
	interfaces_vlan_configure();
1429

    
1430
	/* set up LAN interface */
1431
	interfaces_lan_configure();
1432

    
1433
	/* set up WAN interface */
1434
	interfaces_wan_configure();
1435

    
1436
	/* set up Optional interfaces */
1437
	interfaces_optional_configure();
1438
        
1439
	/* bring up carp interfaces */
1440
	interfaces_carp_configure();
1441
	
1442
	/* set up static routes */
1443
	system_routing_configure();
1444

    
1445
	/* enable routing */
1446
	system_routing_enable();
1447
	
1448
	/* ensure passwords are sync'd */
1449
	system_password_configure();
1450

    
1451
	/* start dnsmasq service */
1452
	services_dnsmasq_configure();
1453

    
1454
	/* start dyndns service */
1455
	services_dyndns_configure();
1456

    
1457
	/* start DHCP service */
1458
	services_dhcpd_configure();
1459

    
1460
	/* start the NTP client */
1461
	system_ntp_configure();
1462

    
1463
	/* start ftp proxy helpers if they are enabled */
1464
	system_start_ftp_helpers();
1465
	
1466
	/* start the captive portal */
1467
	captiveportal_configure();
1468

    
1469
        /* reload the filter */
1470
	filter_configure_sync();
1471

    
1472
	/* bring up carp interfaces*/
1473
	interfaces_carp_bring_up_final();
1474

    
1475
	/* sync pw database */
1476
	conf_mount_rw();
1477
	mwexec("/usr/sbin/pwd_mkdb -d /etc/ /etc/master.passwd");
1478
	conf_mount_ro();
1479

    
1480
	/* restart sshd */
1481
	touch("/tmp/start_sshd");
1482
	
1483
}
1484

    
1485
?>
(14-14/26)