Project

General

Profile

Download (54 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/* $Id$ */
3
/*
4
	interfaces.inc
5
	Copyright (C) 2004-2006 Scott Ullrich
6
	All rights reserved.
7

    
8
	function interfaces_wireless_configure is
9
	Copyright (C) 2005 Espen Johansen
10
	All rights reserved.
11

    
12
	originally part of m0n0wall (http://m0n0.ch/wall)
13
	Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
14
	All rights reserved.
15

    
16
	Redistribution and use in source and binary forms, with or without
17
	modification, are permitted provided that the following conditions are met:
18

    
19
	1. Redistributions of source code must retain the above copyright notices,
20
	   this list of conditions and the following disclaimer.
21

    
22
	2. Redistributions in binary form must reproduce the above copyright
23
	   notices, this list of conditions and the following disclaimer in the
24
	   documentation and/or other materials provided with the distribution.
25

    
26
	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
27
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
28
	AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
29
	AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
30
	OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35
	POSSIBILITY OF SUCH DAMAGE.
36
*/
37

    
38
/* include all configuration functions */
39
require_once("functions.inc");
40
require_once("globals.inc");
41

    
42
function interfaces_loopback_configure() {
43
	mwexec("/sbin/ifconfig lo0 127.0.0.1");
44

    
45
	return 0;
46
}
47

    
48
function interfaces_vlan_configure() {
49
	global $config, $g;
50

    
51
	if (is_array($config['vlans']['vlan']) && count($config['vlans']['vlan'])) {
52

    
53
		/* devices with native VLAN support */
54
		$vlan_native_supp = $g['vlan_native_supp'];
55

    
56
		/* devices with long frame support */
57
		$vlan_long_frame = $g['vlan_long_frame'];
58

    
59
		/* sweep through and axe old interfaces */
60
		$vlan_count = get_number_of_vlan_interfaces();
61
		for($x=0; $x<$vlan_count; $x++)
62
			exec("/sbin/ifconfig vlan{$x} down destroy");
63

    
64
		$i = 0;
65

    
66
		foreach ($config['vlans']['vlan'] as $vlan) {
67

    
68
			$cmd = "/sbin/ifconfig vlan{$i} create vlan " .
69
				escapeshellarg($vlan['tag']) . " vlandev " .
70
				escapeshellarg($vlan['if']);
71

    
72
			/* get driver name */
73
			for ($j = 0; $j < strlen($vlan['if']); $j++) {
74
				if ($vlan['if'][$j] >= '0' && $vlan['if'][$j] <= '9')
75
					break;
76
			}
77
			$drvname = substr($vlan['if'], 0, $j);
78

    
79
			if (in_array($drvname, $vlan_native_supp))
80
				$cmd .= " link0";
81
			else if (in_array($drvname, $vlan_long_frame))
82
				$cmd .= " mtu 1500";
83

    
84
			mwexec($cmd);
85

    
86
			/* invalidate interface cache */
87
			get_interface_arr(true);
88

    
89
			/*   all vlans need to spoof their parent mac address, too.  see
90
			 *   ticket #1514: http://cvstrac.pfsense.com/tktview?tn=1514,33 
91
			 */
92
			foreach($config['interfaces'] as $interfaces) {
93
				if($interfaces['if'] == $vlan['if']) {
94
					if($interfaces['spoofmac']) {
95
						mwexec("/sbin/ifconfig " . escapeshellarg($interfaces['if']) .
96
							" link " . escapeshellarg($interfaces['spoofmac']));
97
					}
98
				}
99
			}
100

    
101
			/* make sure the parent interface is up */
102
			mwexec("/sbin/ifconfig " . escapeshellarg($vlan['if']) . " up");
103

    
104
			$i++;
105
		}
106
	}
107

    
108
	/* CARP interfaces can be attached to VLAN's, too. */
109
	interfaces_carp_bring_up_final();
110

    
111
	return 0;
112
}
113

    
114
function interfaces_lan_configure() {
115
	global $config, $g;
116

    
117
	$bridges_total = get_next_available_bridge_interface();
118

    
119
	$lancfg = $config['interfaces']['lan'];
120

    
121
	/* if user has removed ip address, clear it*/
122
	if($lancfg['ipaddr'] == "")
123
		mwexec("/sbin/ifconfig {$lancfg['if']} delete");
124

    
125
	/* wireless configuration? */
126
	if (is_array($lancfg['wireless']))
127
		interfaces_wireless_configure($lancfg['if'], $lancfg['wireless']);
128

    
129
	/* MAC spoofing? */
130
	if ($lancfg['spoofmac']) {
131
		mwexec("/sbin/ifconfig " . escapeshellarg($lancfg['if']) .
132
			" link " . escapeshellarg($lancfg['spoofmac']));
133
	} else {
134
		$mac = get_interface_mac_address($lancfg['if']);
135
		if($mac == "ff:ff:ff:ff:ff:ff") {
136
			/*   this is not a valid mac address.  generate a
137
			 *   temporary mac address so the machine can get online.
138
			 */
139
			echo "Generating new MAC address.";
140
			$random_mac = generate_random_mac_address();
141
			mwexec("/sbin/ifconfig " . escapeshellarg($lancfg['if']) .
142
				" link " . escapeshellarg($random_mac));
143
			$lancfg['spoofmac'] = $random_mac;
144
			write_config();
145
			file_notice("MAC Address altered", "The INVALID MAC address (ff:ff:ff:ff:ff:ff) on interface {$lancfg['if']} has been automatically replaced with {$random_mac}", "Interfaces");
146
		}
147
	}
148

    
149
	/* bridged? */
150

    
151
	if ($lancfg['bridge']) {
152
		/* use open/netBSD style bridge */
153
		mwexec("/sbin/ifconfig bridge{$bridges_total} create");
154

    
155
		/* force all bridged interfaces to use same mtu */
156
		$mtu = get_interface_mtu($config['interfaces'][$lancfg['bridge']]['if']);
157
		mwexec("/sbin/ifconfig {$lancfg['if']} mtu {$mtu}");
158
		mwexec("/sbin/ifconfig {$config['interfaces'][$lancfg['bridge']]['if']} mtu {$mtu}");
159

    
160
		/* assign items to a bridge */
161
		mwexec("/sbin/ifconfig bridge{$bridges_total} addm {$lancfg['if']} addm {$config['interfaces'][$lancfg['bridge']]['if']}");
162

    
163
		if(!is_interface_wireless($lancfg['if']) and
164
		   !is_interface_wireless($config['interfaces'][$lancfg['bridge']]['if']))
165
			mwexec("/sbin/ifconfig bridge{$bridges_total} stp {$config['interfaces'][$lancfg['bridge']]['if']} stp {$lancfg['if']}");
166

    
167
		/* log commands run for debugging in /tmp/ */
168
		$fd = fopen("{$g['tmp_path']}/bridge_config_{$lancfg['if']}", "w");
169
		fwrite($fd, "/sbin/ifconfig {$lancfg['if']} mtu {$mtu}\n");
170
		fwrite($fd, "/sbin/ifconfig {$config['interfaces'][$lancfg['bridge']]['if']} mtu {$mtu}\n");
171
		fwrite($fd, "/sbin/ifconfig bridge{$bridges_total} create\n");
172
		fwrite($fd, "/sbin/ifconfig bridge{$bridges_total} addm {$lancfg['if']} addm {$config['interfaces'][$lancfg['bridge']]['if']}\n");
173
		if(!is_interface_wireless($lancfg['if']) and
174
		   !is_interface_wireless($config['interfaces'][$lancfg['bridge']]['if']))		
175
				fwrite($fd, "/sbin/ifconfig bridge{$bridges_total} stp {$lancfg['if']} stp {$config['interfaces'][$lancfg['bridge']]['if']}\n");
176
		fclose($fd);
177

    
178
		/* bring up interfaces */
179
		mwexec("/sbin/ifconfig bridge{$bridges_total} down");
180
		usleep(100);
181
		mwexec("/sbin/ifconfig {$config['interfaces'][$lancfg['bridge']]['if']} up");
182
		usleep(5);
183
		mwexec("/sbin/ifconfig {$lancfg['if']} up");
184
		usleep(5);
185
		mwexec("/sbin/ifconfig bridge{$bridges_total} up");
186

    
187
		$bridges_total++;
188
		/* update cache */
189
		if ($bridges_total != find_number_of_created_bridges())
190
			find_number_of_created_bridges(true);
191
	}
192

    
193
	/* media */
194
	if ($lancfg['media'] || $lancfg['mediaopt']) {
195
		$cmd = "/sbin/ifconfig " . escapeshellarg($lancfg['if']);
196
		if ($lancfg['media'])
197
			$cmd .= " media " . escapeshellarg($lancfg['media']);
198
		if ($lancfg['mediaopt'])
199
			$cmd .= " mediaopt " . escapeshellarg($lancfg['mediaopt']);
200
		mwexec($cmd);
201
	}
202

    
203
	mwexec("/sbin/ifconfig " . escapeshellarg($lancfg['if']) . " " .
204
		escapeshellarg($lancfg['ipaddr'] . "/" . $lancfg['subnet']));
205

    
206
	if (!$g['booting']) {
207
		/* make new hosts file */
208
		system_hosts_generate();
209

    
210
		/* reconfigure static routes (kernel may have deleted them) */
211
		system_routing_configure();
212

    
213
		/* set the reload filter dity flag */
214
		touch("{$g['tmp_path']}/filter_dirty");
215

    
216
		/* reload IPsec tunnels */
217
		vpn_ipsec_configure();
218

    
219
		/* reload dhcpd (gateway may have changed) */
220
		services_dhcpd_configure();
221

    
222
		/* reload dnsmasq */
223
		services_dnsmasq_configure();
224

    
225
		/* reload captive portal */
226
		captiveportal_configure();
227

    
228
	}
229

    
230
	return 0;
231
}
232

    
233
function interfaces_optional_configure() {
234
	global $config, $g;
235
	global $bridgeconfig;
236

    
237
	for ($i = 1; isset($config['interfaces']['opt' . $i]); $i++) {
238
		interfaces_optional_configure_if($i);
239
	}
240

    
241
	if (!$g['booting']) {
242
		/* reconfigure static routes (kernel may have deleted them) */
243
		system_routing_configure();
244

    
245
		/* reload IPsec tunnels */
246
		vpn_ipsec_configure();
247

    
248
		/* reload dhcpd (interface enabled/disabled/bridged status may have changed) */
249
		services_dhcpd_configure();
250

    
251
		/* restart dnsmasq */
252
		services_dnsmasq_configure();
253

    
254
		/* reload captive portal */
255
		captiveportal_configure();
256

    
257
		/* set the reload filter dity flag */
258
		touch("{$g['tmp_path']}/filter_dirty");
259
	}
260

    
261
	return 0;
262
}
263

    
264
function interfaces_optional_configure_if($opti) {
265
	global $config, $g;
266
	global $bridgeconfig, $debugging;
267

    
268
	$bridges_total = get_next_available_bridge_interface();
269

    
270
	$optcfg = $config['interfaces']['opt' . $opti];
271

    
272
	if ($g['booting']) {
273
		$optdescr = "";
274
		if ($optcfg['descr'])
275
			$optdescr = " ({$optcfg['descr']})";
276
		print "\tOPT{$opti}{$optdescr}... ";
277
	}
278
	
279
	if(file_exists("/tmp/{$optcfg['if']}_router"))
280
		unlink("/tmp/{$optcfg['if']}_router");
281

    
282
	if (isset($optcfg['enable'])) {
283
		if($optcfg['gateway'])
284
			system("echo " . $optcfg['gateway'] . " > /tmp/" . $optcfg['if'] . "_router");
285

    
286
		/* wireless configuration? */
287
		if (is_array($optcfg['wireless']))
288
			interfaces_wireless_configure($optcfg['if'], $optcfg['wireless']);
289

    
290
		/* PPP configuration */
291
		if (isset($optcfg['pointtopoint']))
292
			interfaces_ppp_configure_if($optcfg);
293

    
294
		/* MAC spoofing? */
295
		if ($optcfg['spoofmac']) {
296
			mwexec("/sbin/ifconfig " . escapeshellarg($optcfg['if']) .
297
				" link " . escapeshellarg($optcfg['spoofmac']));
298
		} else {
299
			$mac = get_interface_mac_address($optcfg['if']);
300
			if($mac == "ff:ff:ff:ff:ff:ff") {
301
				/*   this is not a valid mac address.  generate a
302
				 *   temporary mac address so the machine can get online.
303
				 */
304
				echo "Generating new MAC address.";
305
				$random_mac = generate_random_mac_address();
306
				mwexec("/sbin/ifconfig " . escapeshellarg($optcfg['if']) .
307
					" link " . escapeshellarg($random_mac));
308
				$optcfg['spoofmac'] = $random_mac;
309
				write_config();
310
				file_notice("MAC Address altered", "The INVALID MAC address (ff:ff:ff:ff:ff:ff) on interface {$optcfg['if']} has been automatically replaced with {$random_mac}", "Interfaces");
311
			}
312
		}
313

    
314
		/* media */
315
		if ($optcfg['media'] || $optcfg['mediaopt']) {
316
			$cmd = "/sbin/ifconfig " . escapeshellarg($optcfg['if']);
317
			if ($optcfg['media'])
318
				$cmd .= " media " . escapeshellarg($optcfg['media']);
319
			if ($optcfg['mediaopt'])
320
				$cmd .= " mediaopt " . escapeshellarg($optcfg['mediaopt']);
321
			mwexec($cmd);
322
		}
323

    
324
		/* bridged? */
325
		if ($optcfg['bridge']) {
326
			mwexec("/sbin/ifconfig " . escapeshellarg($optcfg['if']) . " delete up");
327
                        /* use open/netBSD style bridge */
328
			mwexec("/sbin/ifconfig bridge{$bridges_total} create");
329

    
330
			/* invalidate interface cache */
331
			get_interface_arr(true);
332

    
333
			/* force all bridged interfaces to use same mtu */
334
			$mtu = get_interface_mtu($config['interfaces'][$optcfg['bridge']]['if']);
335
			mwexec("/sbin/ifconfig {$optcfg['if']} mtu {$mtu}");
336
			mwexec("/sbin/ifconfig {$config['interfaces'][$optcfg['bridge']]['if']} mtu {$mtu}");
337

    
338
			/* assign items to a bridge */
339
                        mwexec("/sbin/ifconfig bridge{$bridges_total} addm {$optcfg['if']} addm {$config['interfaces'][$optcfg['bridge']]['if']}");
340

    
341
			if(!is_interface_wireless($optcfg['if']) and
342
			   !is_interface_wireless($config['interfaces'][$optcfg['bridge']]['if']))
343
				mwexec("/sbin/ifconfig bridge{$bridges_total} stp {$config['interfaces'][$optcfg['bridge']]['if']} stp {$optcfg['if']}");
344

    
345
			/* log commands run for debugging in /tmp/ */
346
			$fd = fopen("{$g['tmp_path']}/bridge_config_{$optcfg['if']}", "w");
347
			fwrite($fd, "/sbin/ifconfig {$optcfg['if']} mtu {$mtu}\n");
348
			fwrite($fd, "/sbin/ifconfig {$config['interfaces'][$optcfg['bridge']]['if']} mtu {$mtu}\n");
349
			fwrite($fd, "/sbin/ifconfig bridge{$bridges_total} create\n");
350
			fwrite($fd, "/sbin/ifconfig bridge{$bridges_total} addm {$optcfg['if']} addm {$config['interfaces'][$optcfg['bridge']]['if']} up\n");
351
			if(!is_interface_wireless($optcfg['if']) and
352
			   !is_interface_wireless($config['interfaces'][$optcfg['bridge']]['if']))
353
					fwrite($fd, "/sbin/ifconfig bridge{$bridges_total} stp {$optcfg['if']} stp {$config['interfaces'][$optcfg['bridge']]['if']}\n");
354
			fclose($fd);
355

    
356
			/* bring up interfaces */
357
			mwexec("/sbin/ifconfig bridge{$bridges_total} down");
358
			usleep(100);
359
			mwexec("/sbin/ifconfig {$config['interfaces'][$optcfg['bridge']]['if']} up");
360
			usleep(5);
361
			mwexec("/sbin/ifconfig {$optcfg['if']} up");
362
			usleep(5);
363
			mwexec("/sbin/ifconfig bridge{$bridges_total} up");
364

    
365
			$bridges_total++;
366
			/* update cache */
367
			if ($bridges_total != find_number_of_created_bridges())
368
				find_number_of_created_bridges(true);
369
		} else {
370
			/* if user has selected DHCP type then act accordingly */
371
			if($optcfg['ipaddr'] == "dhcp") {
372
				interfaces_opt_dhcp_configure("opt{$opti}");
373
			} else {
374
				mwexec("/sbin/ifconfig " . escapeshellarg($optcfg['if']) . " " .
375
				escapeshellarg($optcfg['ipaddr'] . "/" . $optcfg['subnet']));
376
			}
377
		}
378
	} else {
379
		mwexec("/sbin/ifconfig " . escapeshellarg($optcfg['if']) . " delete down");
380
	}
381
	return 0;
382
}
383

    
384
function interfaces_ppp_configure_if($ifcfg) {
385
	global $config;
386
	
387
	if(file_exists("/var/run/ppp0.pid")) {
388
		$pid = file_get_contents("/var/run/ppp0.pid");
389
		mwexec('kill $pid');
390
	}
391
	
392
	mwexec("/sbin/ifconfig ppp0 down destroy");
393

    
394
	$peerfile = "lcp-echo-failure 0\n";
395
	$peerfile .= "lcp-echo-interval 0\n";
396
	$peerfile .= "connect /etc/ppp/peers/ppp0-connect-chat\n";
397
	//$peerfile .= "disconnect /etc/ppp/peers/ppp0-disconnect-chat\n";
398
	$peerfile .= "/dev/{$ifcfg['serialport']}\n";
399
	$peerfile .= "crtscts\n";
400
	$peerfile .= "local\n";
401
	$peerfile .= ":{$ifcfg['gateway']}\n";
402
	$peerfile .= "noipdefault\n";
403
	$peerfile .= "ipcp-accept-local\n";
404
	$peerfile .= "novj\n";
405
	$peerfile .= "nobsdcomp\n";
406
	$peerfile .= "novjccomp\n";
407
	$peerfile .= "nopcomp\n";
408
	$peerfile .= "noaccomp\n";
409
	$peerfile .= "noauth\n";
410
	$peerfile .= "persist\n";
411
	$peerfile .= "debug\n";
412
	// KD - test
413
	//$peerfile .= "defaultroute\n";
414
	//$peerfile .= "nodetach\n";
415
	// KD - so I know where to look!
416
	$peerfile .= "# created by /etc/inc/interfaces.inc\n";
417
	file_put_contents("/etc/ppp/peers/ppp0", $peerfile);
418

    
419
	// Added single quotes to some strings below:
420
	// the \rAT is *always* going to need it
421
	// and the phone number on a GSM connection ends in a # char
422
	// Kevin Dawson, 22 Jan 2008
423
	// Refer Andrew Curtis
424
			
425
	$chatfile = "#!/bin/sh\n";
426
	$chatfile .= "exec chat \\\n";
427
	$chatfile .= "TIMEOUT 5 \\\n";
428
	$chatfile .= "ECHO ON \\\n";
429
	$chatfile .= "ABORT '\\nBUSY\\r' \\\n";
430
	$chatfile .= "ABORT '\\nERROR\\r' \\\n";
431
	$chatfile .= "ABORT '\\nNO ANSWER\\r' \\\n";
432
	$chatfile .= "ABORT '\\nNO CARRIER\\r' \\\n";
433
	$chatfile .= "ABORT '\\nNO DIALTONE\\r' \\\n";
434
	$chatfile .= "ABORT '\\nRINGING\\r\\n\\r\\nRINGING\\r' \\\n";
435
	// KD
436
	$chatfile .= "'' '\\rAT' \\\n";
437
	$chatfile .= "TIMEOUT 12 \\\n";
438
	$chatfile .= "OK ATH \\\n";
439
	$chatfile .= "OK ATE1 \\\n";
440
	$chatfile .= "OK 'AT+CGDCONT=1,\"IP\",\"{$ifcfg['ap']}\"' \\\n";
441
	// KD
442
	$chatfile .= "OK 'ATD{$ifcfg['phone']}' \\\n";
443
	$chatfile .= "TIMEOUT 22 \\\n";
444
	$chatfile .= "CONNECT \"\" \\\n";
445
	$chatfile .= "SAY \"\\nConnected.\"\n";
446
	file_put_contents("/etc/ppp/peers/ppp0-connect-chat", $chatfile);
447
	chmod("/etc/ppp/peers/ppp0-connect-chat", 0755);
448
	mwexec("/sbin/ifconfig ppp0 create");
449
	return 0;
450
}
451

    
452
function interfaces_carp_configure() {
453
	global $g, $config, $debugging;
454
	$balanacing = "";
455
	$pfsyncinterface = "";
456
	$pfsyncenabled = "";
457
	if(isset($config['system']['developerspew'])) {
458
		$mt = microtime();
459
		echo "interfaces_carp_configure() being called $mt\n";
460
	}
461
	$carp_instances_counter = 0;
462
	$total_carp_interfaces_defined = find_number_of_created_carp_interfaces();
463
	/* destroy previous interfaces */
464
	for($x=0; $x<$total_carp_interfaces_defined; $x++)
465
		mwexec("/sbin/ifconfig carp{$x} delete");
466
	if ($g['booting']) {
467
		echo "Configuring CARP interfaces...";
468
		mute_kernel_msgs();
469
	}
470
	/* suck in configuration items */
471
	if($config['installedpackages']['carpsettings']) 
472
		if($config['installedpackages']['carpsettings']['config']) {
473
		foreach($config['installedpackages']['carpsettings']['config'] as $carp) {
474
			$pfsyncenabled = $carp['pfsyncenabled'];
475
			$balanacing = $carp['balancing'];
476
			$pfsyncinterface = $carp['pfsyncinterface'];
477
			$pfsyncpeerip = $carp['pfsyncpeerip'];
478
		}
479
	} else {
480
		unset($pfsyncinterface);
481
		unset($balanacing);
482
		unset($pfsyncenabled);
483
	}
484
	if($balanacing) {
485
		mwexec("/sbin/sysctl net.inet.carp.arpbalance=1");
486
		mwexec("/sbin/sysctl net.inet.carp.preempt=0");
487
	} else {
488
		mwexec("/sbin/sysctl net.inet.carp.preempt=1");
489
	}
490
	$carp_sync_int = convert_friendly_interface_to_real_interface_name($pfsyncinterface);
491
	if($g['booting']) {
492
		/*    install rules to alllow pfsync to sync up during boot
493
		 *    carp interfaces will remain down until the bootup sequence finishes
494
		 */
495
		exec("echo pass quick proto carp all keep state > /tmp/rules.boot");
496
		exec("echo pass quick proto pfsync all >> /tmp/rules.boot");
497
		exec("echo pass out proto { tcp, udp } from any to any port 53 keep state >> /tmp/rules.boot");
498
		exec("/sbin/pfctl -f /tmp/rules.boot");
499
	}
500
	/* setup pfsync interface */
501
	if($carp_sync_int and $pfsyncenabled) {
502
		if($pfsyncpeerip) {
503
			mwexec("/sbin/ifconfig pfsync0 syncdev {$carp_sync_int} syncpeer {$pfsyncpeerip} up");
504
		} else {
505
			mwexec("/sbin/ifconfig pfsync0 syncdev {$carp_sync_int} up");
506
		}
507
	} else {
508
		mwexec("/sbin/ifconfig pfsync0 syncdev lo0 up");
509
	}
510
	$fd = fopen("/tmp/carp.sh", "w");
511
	if($config['virtualip']['vip']) {
512
		$viparr = &$config['virtualip']['vip'];
513
		mwexec("/sbin/sysctl net.inet.carp.allow=1");
514
	} else {
515
		$viparr = array();
516
		mwexec("/sbin/sysctl net.inet.carp.allow=0");
517
	}
518
	foreach ($viparr as $vip) {
519
		if ($vip['mode'] == "carp") {
520
			$vip_password = $vip['password'];
521
			$vip_password = str_replace(" ", "", $vip_password);
522

    
523
			/* ensure CARP IP really exists prior to loading up */
524
			$found = false;
525
			$iflist = array("lan", "wan");
526
			for ($i = 1; isset($config['interfaces']['opt' . $i]); $i++)
527
				$iflist['opt' . $i] = 'opt' . $i;
528
			foreach($iflist as $if) {
529
				/* ignore down or "disabled" interfaces */
530
				if($if <> "lan" and $if <> "wan")
531
					if (!isset($config['interfaces'][$if]['enable'])) 
532
						continue;								
533
				$ww_subnet_ip = $config['interfaces'][$if]['ipaddr'];
534
				$ww_subnet_bits = $config['interfaces'][$if]['subnet'];
535
				if (ip_in_subnet($vip['subnet'], gen_subnet($ww_subnet_ip, $ww_subnet_bits) . "/" . $ww_subnet_bits))
536
					$found = true;
537
			}
538
			if($found == false and $vip['type'] =="carp") {
539
				file_notice("CARP", "Sorry but we could not find a matching real interface subnet for the virtual IP address {$vip['subnet']}.", "Firewall: Virtual IP", "");
540
				continue;
541
			}			
542
			/* create the carp interface and setup */
543
			mwexec("/sbin/ifconfig carp" . $carp_instances_counter . " create");
544

    
545
			/* invalidate interface cache */
546
			get_interface_arr(true);
547
			if($vip['type'] =="carp") 
548
				$broadcast_address = gen_subnet_max($vip['subnet'], $vip['subnet_bits']);
549
			if($vip['password'] != "")
550
				$password = " pass \"" . $vip_password . "\"";
551

    
552
			if($vip['type'] =="carp") {
553
				mwexec("/sbin/ifconfig carp" . $carp_instances_counter . " " . $vip['subnet'] . "/" . $vip['subnet_bits'] . " broadcast " . $broadcast_address . " vhid " . $vip['vhid'] . " advskew 200 " . $password);
554
				mwexec("/sbin/ifconfig carp" . $carp_instances_counter . " up");
555
			}
556

    
557
			if($vip['type'] =="carpdev-dhcp") {
558
				$interface = convert_friendly_interface_to_real_interface_name($vip['interface']);
559
				if($interface) {
560
					exec("ifconfig carp{$carp_instances_counter} carpdev $interface");
561
					mwexec("/sbin/ifconfig carp" . $carp_instances_counter . " vhid " . $vip['vhid'] . " advskew 200 " . $password);	
562
					mwexec("/sbin/ifconfig carp" . $carp_instances_counter . " up");
563
					mwexec_bg("dhclient carp{$carp_instances_counter}");
564
				} else {
565
					log_error("Could not determine CarpDEV parent interface for {$vip['descr']}.");
566
				}
567
			}
568
			
569
			usleep(10);
570
			$carp_instances_counter++;
571
		}
572
	}
573
	fclose($fd);
574
	mwexec("/bin/sh /tmp/carp.sh");
575
	if ($g['booting']) {
576
		unmute_kernel_msgs();
577
		echo "done.\n";
578
	}
579

    
580
	/* update cache */
581
	if ($carp_instances_counter != find_number_of_created_carp_interfaces())
582
		find_number_of_created_carp_interfaces(true);
583
}
584

    
585
function interfaces_carp_bring_up_final() {
586
	global $config, $g, $debugging;
587
	if(isset($config['system']['developerspew'])) {
588
		$mt = microtime();
589
		echo "interfaces_carp_bring_up_final() being called $mt\n";
590
	}
591
	if(!$config['virtualip']['vip'])
592
		return;
593
	$viparr = &$config['virtualip']['vip'];
594
	/* could not locate an array, return */
595
	if(!is_array($viparr))
596
		return;
597
	$havecarp = false;
598
	foreach ($viparr as $vip) {
599
		/* bail if this isn't a carp VIP */
600
		if ($vip['mode'] == "carp")
601
			$havecarp = true;
602
	}		
603
	if($havecarp == false) 
604
		return;		
605
	$carp_instances_counter = 0;
606
	$counter = 0;
607
	if($g['booting'])
608
		echo "Waiting for final CARP interface bringup...";
609
	$supress = intval(`/sbin/sysctl net.inet.carp.suppress_preempt | cut -d" " -f2`);
610
	if($g['booting']) {
611
		while($supress > 0) {
612
			sleep(2);
613
			$supress = intval(`/sbin/sysctl net.inet.carp.suppress_preempt | cut -d" " -f2`);
614
			if($counter > 15)
615
				$supress = 0;
616
			$counter++;
617
			echo ".";
618
		}
619
		echo " done.\n";
620
	}
621
	foreach ($viparr as $vip) {
622
		/* bail if this isn't a carp VIP */
623
		if ($vip['mode'] != "carp")
624
			continue;
625

    
626
		if($debugging)
627
			echo "Upping interface carp{$carp_instances_counter}.\n";
628
		$broadcast_address = gen_subnet_max($vip['subnet'], $vip['subnet_bits']);
629
		if($vip['password'] != "")
630
			$password = " pass " . $vip['password'];
631

    
632
		if($vip['type'] =="carp") {
633
			mwexec("/sbin/ifconfig carp" . $carp_instances_counter . " " . $vip['subnet'] . "/" . $vip['subnet_bits'] . " broadcast " . $broadcast_address . " vhid " . $vip['vhid'] . " advskew " . $vip['advskew'] . $password);
634
			mwexec("/sbin/ifconfig carp" . $carp_instances_counter . " up");
635
		}
636
		
637
		if($vip['type'] =="carpdev-dhcp") {
638
			$interface = convert_friendly_interface_to_real_interface_name($vip['interface']);
639
			if($interface)
640
				exec("ifconfig carp{$carp_instances_counter} carpdev $interface");			
641
			mwexec("/sbin/ifconfig carp" . $carp_instances_counter . " vhid " . $vip['vhid'] . " advskew " . $vip['advskew'] . $password);
642
			mwexec("/sbin/ifconfig carp" . $carp_instances_counter . " up");
643
			mwexec_bg("dhclient carp{$carp_instances_counter}");
644
		}
645

    
646
		usleep(10);
647

    
648
		$carp_instances_counter++;
649
	}
650
	if($g['booting'])
651
		echo " done.\n";
652
}
653

    
654
function interfaces_ipalias_configure() {
655
	global $g, $config, $debugging;
656
	if(isset($config['system']['developerspew'])) {
657
		$mt = microtime();
658
		echo "interfaces_ipalias_configure() being called $mt\n";
659
	}
660
	$viparr = &$config['virtualip']['vip'];
661
	if(is_array($viparr)) {
662
		foreach ($viparr as $vip) {
663
			if ($vip['mode'] == "ipalias") {
664
				$if = $vip['interface'];
665
				mwexec("/sbin/ifconfig " . escapeshellarg($config['interfaces'][$if]['if']) . " " . $vip['subnet'] . "/" . escapeshellarg($vip['subnet_bits']) . " alias"); 
666
			}
667
		}
668
	}
669
}
670

    
671
function interfaces_wireless_configure($if, $wlcfg) {
672
	global $config, $g;
673

    
674
	/*    open up a shell script that will be used to output the commands.
675
	 *    since wireless is changing a lot, these series of commands are fragile
676
     *    and will sometimes need to be verified by a operator by executing the command
677
     *    and returning the output of the command to the developers for inspection.  please
678
     *    do not change this routine from a shell script to individul exec commands.  -sullrich
679
	 */
680

    
681
	conf_mount_rw();
682

    
683
	unlink_if_exists("{$g['tmp_path']}/{$if}_setup.sh");
684

    
685
	$fd_set = fopen("/tmp/{$if}_setup.sh","w");
686
	fwrite($fd_set, "#!/bin/sh\n");
687
	fwrite($fd_set, "# {$g['product_name']} wireless configuration script.\n\n");
688

    
689
	fwrite($fd_set, "# enable shell debugging\n");
690
	fwrite($fd_set, "set -x\n");
691

    
692
	/* set values for /path/program */
693
	$hostapd = "/usr/sbin/hostapd";
694
	$wpa_supplicant = "/usr/sbin/wpa_supplicant";
695
	$ifconfig = "/sbin/ifconfig";
696
	$killall = "/usr/bin/killall";
697

    
698
	/* Set all wireless ifconfig variables (splitt up to get rid of needed checking) */
699

    
700
	/* Set a/b/g standard */
701
	$standard = "mode " . escapeshellarg($wlcfg['standard']);
702

    
703
	/* Set 802.11g protection mode */
704
	$protmode = "protmode " . escapeshellarg($wlcfg['protmode']);
705

    
706
	/* set wireless channel value */
707
	if(isset($wlcfg['channel']))
708
		$channel = "channel " . escapeshellarg($wlcfg['channel']);
709

    
710
	/* set Distance value */
711
	if($wlcfg['distance'])
712
		$distance = escapeshellarg($wlcfg['distance']);
713

    
714
	/* Set ssid */
715
	if($wlcfg['ssid'])
716
		$ssid = "ssid " . escapeshellarg($wlcfg['ssid']);
717

    
718
	/* Set wireless hostap mode */
719
	if ($wlcfg['mode'] == "hostap")
720
		$hostapmode = "mediaopt hostap";
721
	else
722
		$hostapmode = "-mediaopt hostap";
723

    
724
	/* Set wireless adhoc mode */
725
	if ($wlcfg['mode'] == "adhoc")
726
		$adhocmode = "mediaopt adhoc";
727
	else
728
		$adhocmode = "-mediaopt adhoc";
729

    
730
	/* Not neccesary to set BSS mode as this is default if adhoc and/or hostap is NOT set */
731

    
732
	/* handle hide ssid option */
733
	if(isset($wlcfg['hidessid']['enable']))
734
		$hidessid = "hidessid";
735
	else
736
		$hidessid = "-hidessid";
737

    
738
	/* handle pureg (802.11g) only option */
739
	if(isset($wlcfg['pureg']['enable']))
740
		$pureg = "mode 11g pureg";
741
	else
742
		$pureg = "-pureg";
743

    
744
	/* enable apbridge option */
745
	if(isset($wlcfg['apbridge']['enable']))
746
		$apbridge = "apbridge";
747
	else
748
		$apbridge = "-apbridge";
749

    
750
	/* handle turbo option */
751
	if(isset($wlcfg['turbo']['enable']))
752
		$turbo = "mediaopt turbo";
753
	else
754
		$turbo = "-mediaopt turbo";
755

    
756
	/* handle txpower setting */
757
	if($wlcfg['txpower'] <> "")
758
		$txpower = "txpower " . escapeshellarg($wlcfg['txpower']);
759

    
760
	/* handle wme option */
761
	if(isset($wlcfg['wme']['enable']))
762
		$wme = "wme";
763
	else
764
		$wme = "-wme";
765

    
766
	/* set up wep if enabled */
767
    if (isset($wlcfg['wep']['enable']) && is_array($wlcfg['wep']['key'])) {
768
		if($wlcfg['wpa']['auth_algs'] == "1")
769
			$wepset .= "authmode open wepmode on ";
770
		else if($wlcfg['wpa']['auth_algs'] == "2")
771
			$wepset .= "authmode shared wepmode on ";
772
		else if($wlcfg['wpa']['auth_algs'] == "3")
773
			$wepset .= "authmode mixed wepmode on ";
774
		$i = 1;
775
		foreach ($wlcfg['wep']['key'] as $wepkey) {
776
			$wepset .= "wepkey " . escapeshellarg("{$i}:{$wepkey['value']}") . " ";
777
			if (isset($wepkey['txkey']))
778
				$wepset .= "weptxkey {$i} ";
779
			$i++;
780
		}
781
    } else {
782
    	$wepset .= "authmode open wepmode off ";
783
	}
784

    
785
	/* generate wpa_supplicant/hostap config if wpa is enabled */
786

    
787
	switch ($wlcfg['mode']) {
788
		case 'bss':
789
			if (isset($wlcfg['wpa']['enable'])) {
790

    
791
				$wpa .= <<<EOD
792
ctrl_interface={$g['varrun_path']}/wpa_supplicant
793
ctrl_interface_group=0
794
ap_scan=1
795
#fast_reauth=1
796
network={
797
ssid="{$wlcfg['ssid']}"
798
scan_ssid=1
799
priority=5
800
key_mgmt={$wlcfg['wpa']['wpa_key_mgmt']}
801
psk="{$wlcfg['wpa']['passphrase']}"
802
pairwise={$wlcfg['wpa']['wpa_pairwise']}
803
group={$wlcfg['wpa']['wpa_pairwise']}
804
}
805
EOD;
806

    
807
				$fd = fopen("{$g['varetc_path']}/wpa_supplicant_{$if}.conf", "w");
808
				fwrite($fd, "{$wpa}");
809
				fclose($fd);
810

    
811
				fwrite($fd_set, kill_wpasupplicant($if));
812
			}
813
		break;
814

    
815
		case 'hostap':
816
			if (isset($wlcfg['wpa']['enable'])) {
817
				$wpa .= <<<EOD
818
interface={$if}
819
driver=bsd
820
logger_syslog=-1
821
logger_syslog_level=0
822
logger_stdout=-1
823
logger_stdout_level=0
824
dump_file={$g['tmp_path']}/hostapd_{$if}.dump
825
ctrl_interface={$g['varrun_path']}/hostapd
826
ctrl_interface_group=wheel
827
#accept_mac_file={$g['tmp_path']}/hostapd_{$if}.accept
828
#deny_mac_file={$g['tmp_path']}/hostapd_{$if}.deny
829
#macaddr_acl={$wlcfg['wpa']['macaddr_acl']}
830
ssid={$wlcfg['ssid']}
831
debug={$wlcfg['wpa']['debug_mode']}
832
auth_algs={$wlcfg['wpa']['auth_algs']}
833
wpa={$wlcfg['wpa']['wpa_mode']}
834
wpa_key_mgmt={$wlcfg['wpa']['wpa_key_mgmt']}
835
wpa_pairwise={$wlcfg['wpa']['wpa_pairwise']}
836
wpa_group_rekey={$wlcfg['wpa']['wpa_group_rekey']}
837
wpa_gmk_rekey={$wlcfg['wpa']['wpa_gmk_rekey']}
838
wpa_strict_rekey={$wlcfg['wpa']['wpa_strict_rekey']}
839
wpa_passphrase={$wlcfg['wpa']['passphrase']}
840
ieee8021x={$wlcfg['wpa']['ieee8021x']}
841
#Enable the next lines for preauth when roaming. Interface = wired or wireless interface talking to the AP you want to roam from/to
842
#rsn_preauth=1
843
#rsn_preauth_interfaces=eth0
844
EOD;
845

    
846
				$fd = fopen("{$g['varetc_path']}/hostapd_{$if}.conf", "w");
847
				fwrite($fd, "{$wpa}");
848
				fclose($fd);
849

    
850
				fwrite($fd_set, kill_hostapd($if));
851
			}
852
		break;
853

    
854
		case 'adhoc':
855
			fwrite($fd_set, kill_hostapd($if));
856
			fwrite($fd_set, kill_wpasupplicant($if));
857
		break;
858
	}
859

    
860
	/*
861
	 *    all variables are set, lets start up everything
862
     */
863

    
864
	/* set ack timers according to users preference (if he/she has any) */
865
	if($distance) {
866
		fwrite($fd_set, "# Enable ATH distance settings\n");
867
		fwrite($fd_set, "/sbin/athctrl.sh -i {$if} -d {$distance}\n");
868
	}
869

    
870
	$standard_no_turbo = str_replace(" Turbo", "", $standard);
871

    
872
	$settings = <<<EOD
873

    
874
{$ifconfig} {$if} down
875
{$ifconfig} {$if} {$hostapmode}
876
{$ifconfig} {$if} {$standard_no_turbo}
877
{$ifconfig} {$if} {$channel}
878
{$ifconfig} {$if} {$turbo}
879
{$ifconfig} {$if} {$ssid}
880
{$ifconfig} {$if} {$hidessid}
881
{$ifconfig} {$if} {$adhocmode}
882
{$ifconfig} {$if} {$protmode}
883
{$ifconfig} {$if} {$pureg}
884
{$ifconfig} {$if} {$apbridge}
885
{$ifconfig} {$if} {$wme}
886
{$ifconfig} {$if} {$wepset}
887
{$ifconfig} {$if} {$txpower}
888
{$ifconfig} {$if} up
889

    
890
EOD;
891

    
892
	/* write out above <<EOD stuff */
893
	fwrite($fd_set, $settings);
894

    
895
	if (isset($wlcfg['wpa']['enable'])) {
896
		if ($wlcfg['mode'] == "bss")
897
			fwrite($fd_set, "{$wpa_supplicant} -B -i {$if} -c {$g['varetc_path']}/wpa_supplicant_{$if}.conf\n");
898
		if ($wlcfg['mode'] == "hostap")
899
			fwrite($fd_set, "{$hostapd} -B {$g['varetc_path']}/hostapd_{$if}.conf\n");
900
	}
901

    
902
	fclose($fd_set);
903

    
904
	conf_mount_ro();
905

    
906
	/* execute commands now in shell */
907
	mwexec("/bin/sh /tmp/{$if}_setup.sh");
908
	sleep(2);
909
	mwexec("/bin/sh /tmp/{$if}_setup.sh");
910

    
911
	return 0;
912

    
913
}
914

    
915
function kill_hostapd($interface) {
916
	return "/bin/ps awwuxx | grep hostapd | grep $interface | awk '{ print \$2 }' | xargs kill\n";
917
}
918

    
919
function kill_wpasupplicant($interface) {
920
	return "/bin/ps awwuxx | grep wpa_supplicant | grep $interface | awk '{ print \$2 }' | xargs kill\n";
921
}
922

    
923
function find_dhclient_process($interface) {
924
	if(filter_translate_type_to_real_interface($interface) <> "")
925
        	$realinterface = filter_translate_type_to_real_interface($interface);
926
	if($realinterface)
927
		$pid = `ps awwwux | grep dhclient | grep -v grep | grep {$realinterface} | awk '{ print \$2 }'`;
928
	return $pid;
929
}
930

    
931
function interfaces_wan_configure() {
932
	global $config, $g, $bridges_total;
933

    
934
	$wancfg = $config['interfaces']['wan'];
935

    
936
	if(file_exists("/tmp/{$config['interfaces']['wan']['if']}_router")) 
937
		unlink("/tmp/{$config['interfaces']['wan']['if']}_router");
938

    
939
	if(!$g['booting']) {
940
		mute_kernel_msgs();
941

    
942
		/* find dhclient process for wan and kill it */
943
		killbypid(find_dhclient_process("wan"));
944

    
945
		/* remove wanup file if it exists */
946
		unlink_if_exists("{$g['tmp_path']}/wanup");
947

    
948
		/* kill PPPoE client (mpd) */
949
		killbypid("{$g['varrun_path']}/mpd.pid");
950

    
951
		/* wait for processes to die */
952
		sleep(3);
953

    
954
		unlink_if_exists("{$g['varetc_path']}/dhclient_wan.conf");
955
		unlink_if_exists("{$g['varetc_path']}/mpd.conf");
956
		unlink_if_exists("{$g['varetc_path']}/mpd.links");
957
		unlink_if_exists("{$g['vardb_path']}/wanip");
958
		unlink_if_exists("{$g['varetc_path']}/nameservers.conf");
959
	}
960

    
961
	/* remove all addresses first */
962
	while (mwexec("/sbin/ifconfig " . escapeshellarg($wancfg['if']) . " -alias") == 0);
963
	mwexec("/sbin/ifconfig " . escapeshellarg($wancfg['if']) . " down");
964

    
965
	/* wireless configuration? */
966
	if (is_array($wancfg['wireless']))
967
		interfaces_wireless_configure($wancfg['if'], $wancfg['wireless']);
968

    
969
	if ($wancfg['spoofmac']) {
970
		mwexec("/sbin/ifconfig " . escapeshellarg($wancfg['if']) .
971
			" link " . escapeshellarg($wancfg['spoofmac']));
972
	}  else {
973
		$mac = get_interface_mac_address($wancfg['if']);
974
		if($mac == "ff:ff:ff:ff:ff:ff") {
975
			/*   this is not a valid mac address.  generate a
976
			 *   temporary mac address so the machine can get online.
977
			 */
978
			echo "Generating new MAC address.";
979
			$random_mac = generate_random_mac_address();
980
			mwexec("/sbin/ifconfig " . escapeshellarg($wancfg['if']) .
981
				" link " . escapeshellarg($random_mac));
982
			$wancfg['spoofmac'] = $random_mac;
983
			write_config();
984
			file_notice("MAC Address altered", "The INVALID MAC address (ff:ff:ff:ff:ff:ff) on interface {$wancfg['if']} has been automatically replaced with {$random_mac}", "Interfaces");
985
		}
986
	}
987

    
988
	/* media */
989
	if ($wancfg['media'] || $wancfg['mediaopt']) {
990
		$cmd = "/sbin/ifconfig " . escapeshellarg($wancfg['if']);
991
		if ($wancfg['media'])
992
			$cmd .= " media " . escapeshellarg($wancfg['media']);
993
		if ($wancfg['mediaopt'])
994
			$cmd .= " mediaopt " . escapeshellarg($wancfg['mediaopt']);
995
		mwexec($cmd);
996
	}
997

    
998
	switch ($wancfg['ipaddr']) {
999

    
1000
		case 'carpdev-dhcp':
1001
			interfaces_wan_carpdev_dhcp_configure();
1002
			break;
1003
		case 'dhcp':
1004
			interfaces_wan_dhcp_configure();
1005
			break;
1006

    
1007
		case 'pppoe':
1008
			interfaces_wan_pppoe_configure();
1009
			break;
1010

    
1011
		case 'pptp':
1012
			interfaces_wan_pptp_configure();
1013
			break;
1014

    
1015
		case 'bigpond':
1016
			/* just configure DHCP for now; fire up bpalogin when we've got the lease */
1017
			interfaces_wan_dhcp_configure();
1018
			break;
1019

    
1020
		default:
1021
			if (isset($wancfg['ispointtopoint']) && $wancfg['pointtopoint']) {
1022
				mwexec("/sbin/ifconfig " . escapeshellarg($wancfg['if']) . " " .
1023
					escapeshellarg($wancfg['ipaddr'] . "/" . $wancfg['subnet']) .
1024
					" " . escapeshellarg($wancfg['pointtopoint']) . " up");
1025
			} else {
1026
				mwexec("/sbin/ifconfig " . escapeshellarg($wancfg['if']) . " " .
1027
					escapeshellarg($wancfg['ipaddr'] . "/" . $wancfg['subnet']));
1028
			}
1029

    
1030
			if($config['interfaces']['wan']['gateway'])
1031
				system("echo " . $config['interfaces']['wan']['gateway'] . " > /tmp/" . $config['interfaces']['wan']['if'] . "_router");
1032

    
1033
			/* resync pf (done automatically for DHCP/PPPoE/PPTP) */
1034
			filter_configure();
1035
	}
1036

    
1037
	if ($wancfg['bridge']) {
1038
		/* use open/netBSD style bridge */
1039
		mwexec("/sbin/ifconfig bridge{$bridges_total} create");
1040

    
1041
		/* invalidate interface cache */
1042
		get_interface_arr(true);
1043

    
1044
		/* force all bridged interfaces to use same mtu */
1045
		$mtu = get_interface_mtu($config['interfaces'][$wancfg['bridge']]['if']);
1046
		mwexec("/sbin/ifconfig {$wancfg['if']} mtu {$mtu}");
1047
		mwexec("/sbin/ifconfig {$config['interfaces'][$wancfg['bridge']]['if']} mtu {$mtu}");
1048

    
1049
		/* assign items to a bridge */
1050
		mwexec("/sbin/ifconfig bridge{$bridges_total} addm {$wancfg['if']} addm {$config['interfaces'][$wancfg['bridge']]['if']}");
1051

    
1052
		if(!is_interface_wireless($wancfg['if']) and
1053
		   !is_interface_wireless($config['interfaces'][$wancfg['bridge']]['if']))
1054
			mwexec("/sbin/ifconfig bridge{$bridges_total} stp {$config['interfaces'][$wancfg['bridge']]['if']} stp {$wancfg['if']}");
1055

    
1056
		/* log commands run for debugging in /tmp/ */
1057
		$fd = fopen("{$g['tmp_path']}/bridge_config_{$wancfg['if']}", "w");
1058
		fwrite($fd, "/sbin/ifconfig {$wancfg['if']} mtu {$mtu}\n");
1059
		fwrite($fd, "/sbin/ifconfig {$config['interfaces'][$wancfg['bridge']]['if']} mtu {$mtu}\n");
1060
		fwrite($fd, "/sbin/ifconfig bridge{$bridges_total} create\n");
1061
		fwrite($fd, "/sbin/ifconfig bridge{$bridges_total} addm {$wancfg['if']} addm {$config['interfaces'][$wancfg['bridge']]['if']}\n");
1062
		if(!is_interface_wireless($wancfg['if']) and
1063
		   !is_interface_wireless($config['interfaces'][$wancfg['bridge']]['if']))
1064
				fwrite($fd, "/sbin/ifconfig bridge{$bridges_total} stp {$wancfg['if']} stp {$config['interfaces'][$wancfg['bridge']]['if']}\n");
1065
		fclose($fd);
1066

    
1067
		/* bring up interfaces */
1068
		mwexec("/sbin/ifconfig bridge{$bridges_total} down");
1069
		usleep(100);
1070
		mwexec("/sbin/ifconfig {$config['interfaces'][$wancfg['bridge']]['if']} up");
1071
		usleep(5);
1072
		mwexec("/sbin/ifconfig {$wancfg['if']} up");
1073
		usleep(5);
1074
		mwexec("/sbin/ifconfig bridge{$bridges_total} up");
1075

    
1076
		$bridges_total++;
1077
		/* update cache */
1078
		if ($bridges_total != find_number_of_created_bridges())
1079
			find_number_of_created_bridges(true);
1080
	}
1081

    
1082
	if (!$g['booting']) {
1083
		/* reconfigure static routes (kernel may have deleted them) */
1084
		system_routing_configure();
1085

    
1086
		/* set the reload filter dity flag */
1087
		touch("{$g['tmp_path']}/filter_dirty");
1088

    
1089
		/* reload ipsec tunnels */
1090
		vpn_ipsec_configure();
1091

    
1092
		/* restart ez-ipupdate */
1093
		services_dyndns_configure();
1094

    
1095
		/* force DNS update */
1096
		services_dnsupdate_process();
1097

    
1098
		/* restart dnsmasq */
1099
		services_dnsmasq_configure();
1100

    
1101
		/* reload captive portal */
1102
		captiveportal_configure();
1103
	}
1104

    
1105
	mwexec("/sbin/ifconfig {$wancfg['if']} up");
1106

    
1107
	unmute_kernel_msgs();
1108

    
1109
	return 0;
1110
}
1111

    
1112
function interfaces_opt_dhcp_configure($interface) {
1113
	global $config, $g;
1114

    
1115
	$optcfg = $config['interfaces'][$interface];
1116
	$optif = $optcfg['if'];
1117

    
1118
	/* generate dhclient_wan.conf */
1119
	$fd = fopen("{$g['varetc_path']}/dhclient_{$optif}.conf", "w");
1120
	if (!$fd) {
1121
		printf("Error: cannot open dhclient_{$optif}.conf in interfaces_opt_dhcp_configure({$optif}) for writing.\n");
1122
		return 1;
1123
	}
1124

    
1125
	if ($optcfg['dhcphostname']) {
1126
		$dhclientconf_hostname = "send dhcp-client-identifier \"{$optcfg['dhcphostname']}\";\n";
1127
		$dhclientconf_hostname .= "\tsend host-name \"{$optcfg['dhcphostname']}\";\n";
1128
	} else {
1129
		$dhclientconf_hostname = "";
1130
	}
1131

    
1132
 	$dhclientconf = "";
1133

    
1134
	$dhclientconf .= <<<EOD
1135
timeout 60;
1136
retry 1;
1137
select-timeout 0;
1138
initial-interval 1;
1139
interface "{$optif}" {
1140
	script "/sbin/dhclient-script";
1141
	{$dhclientconf_hostname}
1142
}
1143

    
1144
EOD;
1145

    
1146
if(is_ipaddr($optcfg['alias-address'])) {
1147
	$subnetmask = gen_subnet_mask($optcfg['alias-subnet']);
1148
	$dhclientconf .= <<<EOD
1149
alias {
1150
	interface  "{$optif}";
1151
	fixed-address {$optcfg['alias-address']};
1152
	option subnet-mask {$subnetmask};
1153
}
1154

    
1155
EOD;
1156
}
1157
	fwrite($fd, $dhclientconf);
1158
	fclose($fd);
1159

    
1160
        /* bring interface up before starting dhclient */
1161
        mwexec("/sbin/ifconfig {$optif} up");
1162

    
1163
        /* fire up dhclient */
1164
        mwexec("/sbin/dhclient -c {$g['varetc_path']}/dhclient_{$optif}.conf {$optif}");
1165

    
1166
	return 0;
1167
}
1168

    
1169
function interfaces_dhcp_configure($interface) {
1170
	global $config, $g;
1171

    
1172
	if(filter_translate_type_to_real_interface($interface) <> "")
1173
        	$realinterface = filter_translate_type_to_real_interface($interface);
1174

    
1175
	$optcfg = $config['interfaces'][$interface];
1176

    
1177
	/* generate dhclient_$interface.conf */
1178
	$fd = fopen("{$g['varetc_path']}/dhclient_{$interface}.conf", "w");
1179
	if (!$fd) {
1180
		printf("Error: cannot open dhclient_{$interface}.conf in interfaces_dhcp_configure({$$interface}) for writing.\n");
1181
		return 1;
1182
	}
1183

    
1184
	if ($optcfg['dhcphostname']) {
1185
		$dhclientconf_hostname =  "send dhcp-client-identifier \"{$optcfg['dhcphostname']}\";\n";
1186
		$dhclientconf_hostname .= "\tsend host-name \"{$optcfg['dhcphostname']}\";\n";
1187
	} else {
1188
		$dhclientconf_hostname = "";
1189
	}
1190

    
1191
 	$dhclientconf = "";
1192

    
1193
	$dhclientconf .= <<<EOD
1194
timeout 60;
1195
retry 1;
1196
select-timeout 0;
1197
initial-interval 1;
1198
interface "{$realinterface}" {
1199
	{$dhclientconf_hostname}
1200
	script "/sbin/dhclient-script";
1201
}
1202

    
1203
EOD;
1204

    
1205
if(is_ipaddr($optcfg['alias-address'])) {
1206
	$subnetmask = gen_subnet_mask($optcfg['alias-subnet']);
1207
	$dhclientconf .= <<<EOD
1208
alias {
1209
	interface  "{$optif}";
1210
	fixed-address {$optcfg['alias-address']};
1211
	option subnet-mask {$subnetmask};
1212
}
1213

    
1214
EOD;
1215
}
1216

    
1217
	fwrite($fd, $dhclientconf);
1218
	fclose($fd);
1219

    
1220
	$optif = $optcfg['if'];
1221

    
1222
        /* bring wan interface up before starting dhclient */
1223
        mwexec("/sbin/ifconfig {$optif} up");
1224

    
1225
        /* fire up dhclient */
1226
        mwexec("/sbin/dhclient -c {$g['varetc_path']}/dhclient_{$optif}.conf {$optif} >/tmp/{$optif}_output >/tmp/{$optif}_error_output");
1227

    
1228
	$fout = fopen("/tmp/ifconfig_{$optif}","w");
1229
	fwrite($fout, "/sbin/dhclient -c {$g['varetc_path']}/dhclient_{$optif}.conf {$optif}");
1230
	fclose($fout);
1231

    
1232
	return 0;
1233
}
1234

    
1235
function interfaces_wan_carpdev_dhcp_configure() {
1236
	global $config, $g;
1237

    
1238
	$wancfg = $config['interfaces']['wan'];
1239
	/* bring wan interface up before starting dhclient */
1240
	mwexec("/sbin/ifconfig {$wanif} up");
1241

    
1242
	return 0;
1243
}
1244

    
1245
function interfaces_wan_dhcp_configure() {
1246
	global $config, $g;
1247

    
1248
	$wancfg = $config['interfaces']['wan'];
1249

    
1250
	/* generate dhclient_wan.conf */
1251
	$fd = fopen("{$g['varetc_path']}/dhclient_wan.conf", "w");
1252
	if (!$fd) {
1253
		printf("Error: cannot open dhclient_wan.conf in interfaces_wan_dhcp_configure() for writing.\n");
1254
		return 1;
1255
	}
1256

    
1257
	if ($wancfg['dhcphostname']) {
1258
		$dhclientconf_hostname = "send dhcp-client-identifier \"{$wancfg['dhcphostname']}\";\n";
1259
		$dhclientconf_hostname .= "\tsend host-name \"{$wancfg['dhcphostname']}\";\n";
1260
	} else {
1261
		$dhclientconf_hostname = "";
1262
	}
1263

    
1264
 	$dhclientconf = "";
1265

    
1266
	$dhclientconf .= <<<EOD
1267
interface "{$wancfg['if']}" {
1268
timeout 60;
1269
retry 1;
1270
select-timeout 0;
1271
initial-interval 1;
1272
	{$dhclientconf_hostname}
1273
	script "/sbin/dhclient-script";
1274
}
1275

    
1276
EOD;
1277

    
1278
if(is_ipaddr($wancfg['alias-address'])) {
1279
	$subnetmask = gen_subnet_mask($wancfg['alias-subnet']);
1280
	$dhclientconf .= <<<EOD
1281
alias {
1282
	interface  "{$wancfg['if']}";
1283
	fixed-address {$wancfg['alias-address']};
1284
	option subnet-mask {$subnetmask};
1285
}
1286

    
1287
EOD;
1288
}
1289
	fwrite($fd, $dhclientconf);
1290
	fclose($fd);
1291

    
1292
	$wanif = $wancfg['if'];
1293

    
1294
        /* bring wan interface up before starting dhclient */
1295
        mwexec("/sbin/ifconfig {$wanif} up");
1296

    
1297
        /* fire up dhclient */
1298
        mwexec("/sbin/dhclient -c {$g['varetc_path']}/dhclient_wan.conf {$wanif} >/tmp/{$wanif}_output >/tmp/{$wanif}_error_output");
1299

    
1300
	$fout = fopen("/tmp/ifconfig_{$wanif}","w");
1301
	fwrite($fout, "/sbin/dhclient -c {$g['varetc_path']}/dhclient_wan.conf {$wanif}");
1302
	fclose($fout);
1303

    
1304
	return 0;
1305
}
1306

    
1307
function interfaces_wan_dhcp_down() {
1308
	global $config;
1309
	$wancfg = $config['interfaces']['wan'];
1310
	$wanif = $wancfg['if'];
1311
	mwexec("/sbin/ifconfig {$wanif} delete");
1312
	sleep(1);
1313
}
1314

    
1315
function interfaces_dhcp_down($interface) {
1316
	global $config;
1317
	if(filter_translate_type_to_real_interface($interface) <> "")
1318
		$realinterface = filter_translate_type_to_real_interface($interface);
1319
	mwexec("/sbin/ifconfig {$realinterface} down");
1320
	sleep(1);
1321
	$pid = find_dhclient_process($interface);
1322
	if($pid)
1323
		mwexec("kill {$pid}");
1324
}
1325

    
1326
function interfaces_dhcp_up($interface) {
1327
	interfaces_dhcp_configure($interface);
1328
	sleep(1);
1329
}
1330

    
1331
function interfaces_wan_dhcp_up() {
1332
	interfaces_wan_dhcp_configure();
1333
	sleep(1);
1334
}
1335

    
1336
function interfaces_wan_pppoe_configure() {
1337
	global $config, $g;
1338

    
1339
	$wancfg = $config['interfaces']['wan'];
1340
	$pppoecfg = $config['pppoe'];
1341

    
1342
	/* generate mpd.conf */
1343
	$fd = fopen("{$g['varetc_path']}/mpd.conf", "w");
1344
	if (!$fd) {
1345
		printf("Error: cannot open mpd.conf in interfaces_wan_pppoe_configure().\n");
1346
		return 1;
1347
	}
1348

    
1349
	$idle = 0;
1350

    
1351
	if (isset($pppoecfg['ondemand'])) {
1352
		$ondemand = "enable";
1353
		if ($pppoecfg['timeout'])
1354
			$idle = $pppoecfg['timeout'];
1355
	} else {
1356
		$ondemand = "disable";
1357
	}
1358

    
1359
	$mpdconf = <<<EOD
1360
startup:
1361
pppoeclient:
1362
	new -i pppoe0 pppoeclient pppoeclient
1363
	set iface route default
1364
	set iface {$ondemand} on-demand
1365
	set iface idle {$idle}
1366
	set iface up-script /usr/local/sbin/ppp-linkup
1367

    
1368
EOD;
1369

    
1370
	/*    Check for ppp-linkdown Script in /usr/local/sbin
1371
	 *    Create reference in mpd.conf
1372
	 */
1373
	if ( file_exists("/usr/local/sbin/ppp-linkdown") ){
1374
		$mpdconf .= <<<EOD
1375
	set iface down-script /usr/local/sbin/ppp-linkdown
1376

    
1377
EOD;
1378
	}
1379

    
1380
	if (isset($pppoecfg['ondemand'])) {
1381
		if (isset($pppoecfg['local-ip']) && isset($pppoecfg['remote-ip'])) {
1382
			$mpdconf .= <<<EOD
1383
	set iface addrs {$pppoecfg['local-ip']} {$pppoecfg['remote-ip']}
1384

    
1385
EOD;
1386
		} else {
1387
			$mpdconf .= <<<EOD
1388
	set iface addrs 192.0.2.112 192.0.2.113
1389

    
1390
EOD;
1391
		}
1392
	}
1393

    
1394
	$mpdconf .= <<<EOD
1395
	set bundle disable multilink
1396
	set auth authname "{$pppoecfg['username']}"
1397
	set auth password "{$pppoecfg['password']}"
1398
	set link keep-alive 10 60
1399
	set link max-redial 0
1400
	set link no acfcomp protocomp
1401
	set link disable pap chap
1402
	set link accept chap
1403
	set link mtu 1492
1404
	set ipcp yes vjcomp
1405
	set ipcp ranges 0.0.0.0/0 0.0.0.0/0
1406

    
1407

    
1408

    
1409
EOD;
1410

    
1411
	if (isset($config['system']['dnsallowoverride'])) {
1412
		$mpdconf .= <<<EOD
1413
	set ipcp enable req-pri-dns
1414

    
1415
EOD;
1416
	}
1417

    
1418
	if (!isset($config['pppoe']['dnsnosec'])) {
1419
			$mpdconf .= <<<EOD
1420
	set ipcp enable req-sec-dns
1421

    
1422
EOD;
1423
	}
1424
	
1425
	$mpdconf .= <<<EOD
1426
	open
1427

    
1428
EOD;
1429

    
1430
	fwrite($fd, $mpdconf);
1431
	fclose($fd);
1432

    
1433
	/* generate mpd.links */
1434
	$fd = fopen("{$g['varetc_path']}/mpd.links", "w");
1435
	if (!$fd) {
1436
		printf("Error: cannot open mpd.links in interfaces_wan_pppoe_configure().\n");
1437
		return 1;
1438
	}
1439

    
1440
	$mpdconf = <<<EOD
1441
pppoeclient:
1442
	set link type pppoe
1443
	set pppoe iface {$wancfg['if']}
1444
	set pppoe service "{$pppoecfg['provider']}"
1445
	set pppoe enable originate
1446
	set pppoe disable incoming
1447

    
1448
EOD;
1449

    
1450
	fwrite($fd, $mpdconf);
1451
	fclose($fd);
1452

    
1453
	if(file_exists("{$g['varrun_path']}/mpdpppoe.pid") and $g['booting']) {
1454
		/* if we are booting and mpd has already been started then don't start again. */
1455
	} else {
1456
		/* if mpd is active, lets take it down */
1457
		if(file_exists("{$g['varrun_path']}/mpdpppoe.pid")) {
1458
			killbypid("{$g['varrun_path']}/mpdpppoe.pid");
1459
			sleep(3);
1460
		}
1461
		/* fire up mpd */
1462
		mwexec("/usr/local/sbin/mpd4 -b -d {$g['varetc_path']} -p {$g['varrun_path']}/mpdpppoe.pid pppoeclient");
1463
	}
1464

    
1465
        /* sleep until wan is up - or 30 seconds, whichever comes first */
1466
	for ($count = 0; $count < 30; $count++) {
1467
		if(file_exists("{$g['tmp_path']}/wanup")) {
1468
			break;
1469
		}
1470
		sleep(1);
1471
	}
1472

    
1473
	unlink_if_exists("{$g['tmp_path']}/wanup");
1474

    
1475
	return 0;
1476
}
1477

    
1478
function interfaces_wan_pppoe_restart() {
1479
	interfaces_wan_pppoe_down();
1480
	sleep(1);
1481
	interfaces_wan_pppoe_up();
1482
}
1483

    
1484
function interfaces_wan_pppoe_down() {
1485
	global $g;
1486
	sigkillbypid("{$g['varrun_path']}/mpdpppoe.pid", "SIGUSR2");
1487
	sleep(1);
1488
}
1489

    
1490
function interfaces_wan_pppoe_up() {
1491
	global $g;
1492
	sigkillbypid("{$g['varrun_path']}/mpdpppoe.pid", "SIGUSR1");
1493
	sleep(1);
1494
}
1495

    
1496
function interfaces_wan_pptp_configure() {
1497
	global $config, $g;
1498

    
1499
	$wancfg = $config['interfaces']['wan'];
1500
	$pptpcfg = $config['pptp'];
1501

    
1502
	/* generate mpd.conf */
1503
	$fd = fopen("{$g['varetc_path']}/mpd.conf", "w");
1504
	if (!$fd) {
1505
		printf("Error: cannot open mpd.conf in interfaces_wan_pptp_configure().\n");
1506
		return 1;
1507
	}
1508

    
1509
	$idle = 0;
1510

    
1511
	if (isset($pptpcfg['ondemand'])) {
1512
		$ondemand = "enable";
1513
		if ($pptpcfg['timeout'])
1514
			$idle = $pptpcfg['timeout'];
1515
	} else {
1516
		$ondemand = "disable";
1517
	}
1518

    
1519
	$mpdconf = <<<EOD
1520
pptp:
1521
	new -i pptp0 pptp pptp
1522
	set iface route default
1523
	set iface {$ondemand} on-demand
1524
	set iface idle {$idle}
1525
	set iface up-script /usr/local/sbin/ppp-linkup
1526

    
1527
EOD;
1528

    
1529
	/*   Check for ppp-linkdown Script in /usr/local/sbin
1530
	 *   Create reference in mpd.conf
1531
	 */
1532
	if ( file_exists("/usr/local/sbin/ppp-linkdown") ){
1533
		$mpdconf .= <<<EOD
1534
	set iface down-script /usr/local/sbin/ppp-linkdown
1535

    
1536
EOD;
1537
	}
1538

    
1539
	if (isset($pptpcfg['ondemand'])) {
1540
		$mpdconf .= <<<EOD
1541
	set iface addrs 10.0.0.1 10.0.0.2
1542

    
1543
EOD;
1544
	}
1545

    
1546
	$mpdconf .= <<<EOD
1547
	set bundle disable multilink
1548
	set bundle authname "{$pptpcfg['username']}"
1549
	set bundle password "{$pptpcfg['password']}"
1550
	set link keep-alive 10 60
1551
	set link max-redial 0
1552
	set link no acfcomp protocomp
1553
	set link disable pap chap
1554
	set link accept chap
1555
	set ipcp no vjcomp
1556
	set ipcp ranges 0.0.0.0/0 0.0.0.0/0
1557

    
1558
EOD;
1559
	if (isset($config['system']['dnsallowoverride'])) {
1560
		$mpdconf .= <<<EOD
1561
	set ipcp enable req-pri-dns
1562

    
1563
EOD;
1564
	}
1565

    
1566
	$mpdconf .= <<<EOD
1567
	open
1568

    
1569
EOD;
1570

    
1571
	fwrite($fd, $mpdconf);
1572
	fclose($fd);
1573

    
1574
	/* generate mpd.links */
1575
	$fd = fopen("{$g['varetc_path']}/mpd.links", "w");
1576
	if (!$fd) {
1577
		printf("Error: cannot open mpd.links in interfaces_wan_pptp_configure().\n");
1578
		return 1;
1579
	}
1580

    
1581
	$mpdconf = <<<EOD
1582
pptp:
1583
	set link type pptp
1584
	set pptp enable originate outcall
1585
	set pptp disable windowing
1586
	set pptp self {$pptpcfg['local']}
1587
	set pptp peer {$pptpcfg['remote']}
1588

    
1589
EOD;
1590

    
1591
	fwrite($fd, $mpdconf);
1592
	fclose($fd);
1593

    
1594
	/* configure interface */
1595
	mwexec("/sbin/ifconfig " . escapeshellarg($wancfg['if']) . " " .
1596
		escapeshellarg($pptpcfg['local'] . "/" . $pptpcfg['subnet']));
1597

    
1598
	/* fire up mpd */
1599
	mwexec("/usr/local/sbin/mpd -b -d {$g['varetc_path']} -p {$g['varrun_path']}/mpd.pid pptp");
1600

    
1601
	return 0;
1602
}
1603

    
1604
function interfaces_wan_pptp_restart() {
1605
	interfaces_wan_pptp_down();
1606
	sleep(1);
1607
	interfaces_wan_pptp_up();
1608
}
1609

    
1610
function interfaces_wan_pptp_down() {
1611
	global $g;
1612
	sigkillbypid("{$g['varrun_path']}/mpd.pid", "SIGUSR2");
1613
	sleep(1);
1614
}
1615

    
1616
function interfaces_wan_pptp_up() {
1617
	global $g;
1618
	sigkillbypid("{$g['varrun_path']}/mpd.pid", "SIGUSR1");
1619
	sleep(1);
1620
}
1621

    
1622
function interfaces_wan_bigpond_configure($curwanip) {
1623
	global $config, $g;
1624

    
1625
	$bpcfg = $config['bigpond'];
1626

    
1627
	if (!$curwanip) {
1628
		/* IP address not configured yet, exit */
1629
		return 0;
1630
	}
1631

    
1632
	/* kill bpalogin */
1633
	killbyname("bpalogin");
1634

    
1635
	/* wait a moment */
1636
	sleep(1);
1637

    
1638
	/* get the default domain */
1639
	$nfd = @fopen("{$g['varetc_path']}/defaultdomain.conf", "r");
1640
	if ($nfd) {
1641
		$defaultdomain = trim(fgets($nfd));
1642
		fclose($nfd);
1643
	}
1644

    
1645
	/* generate bpalogin.conf */
1646
	$fd = fopen("{$g['varetc_path']}/bpalogin.conf", "w");
1647
	if (!$fd) {
1648
		printf("Error: cannot open bpalogin.conf in interfaces_wan_bigpond_configure().\n");
1649
		return 1;
1650
	}
1651

    
1652
	if (!$bpcfg['authserver'])
1653
		$bpcfg['authserver'] = "dce-server";
1654
	if (!$bpcfg['authdomain'])
1655
		$bpcfg['authdomain'] = $defaultdomain;
1656

    
1657
	$bpconf = <<<EOD
1658
username {$bpcfg['username']}
1659
password {$bpcfg['password']}
1660
authserver {$bpcfg['authserver']}
1661
authdomain {$bpcfg['authdomain']}
1662
localport 5050
1663

    
1664
EOD;
1665

    
1666
	if ($bpcfg['minheartbeatinterval'])
1667
		$bpconf .= "minheartbeatinterval {$bpcfg['minheartbeatinterval']}\n";
1668

    
1669
	fwrite($fd, $bpconf);
1670
	fclose($fd);
1671

    
1672
	/* fire up bpalogin */
1673
	mwexec("/usr/local/sbin/bpalogin -c {$g['varetc_path']}/bpalogin.conf");
1674

    
1675
	return 0;
1676
}
1677

    
1678
function get_real_wan_interface() {
1679
	global $config, $g;
1680

    
1681
	$wancfg = $config['interfaces']['wan'];
1682

    
1683
	$wanif = $wancfg['if'];
1684
	if ($wancfg['ipaddr'] == "pppoe") 
1685
		$wanif = "pppoe0";
1686
	if ($wancfg['ipaddr'] == "pptp") 
1687
		$wanif = "pptp0";
1688

    
1689
	return $wanif;
1690
}
1691

    
1692
function get_current_wan_address($interface = "wan") {
1693
	global $config, $g;
1694

    
1695
	$wancfg = $config['interfaces'][$interface];
1696

    
1697
	$interface = filter_translate_type_to_real_interface($interface);
1698
	$ifinfo = "";
1699
	if(in_array($wancfg['ipaddr'], array('dhcp'))) {
1700
		/* get interface info with netstat */
1701
		exec("/usr/bin/netstat -nWI " . escapeshellarg($interface) . " -f inet", $ifinfo);
1702

    
1703
		if (isset($ifinfo[1])) {
1704
			$aif = preg_split("/\s+/", $ifinfo[1]);
1705
			$curwanip = chop($aif[3]);
1706

    
1707
			if ($curwanip && is_ipaddr($curwanip) && ($curwanip != "0.0.0.0"))
1708
				return $curwanip;
1709
		}
1710

    
1711
		return null;
1712
	} else if (in_array($wancfg['ipaddr'], array('pppoe','pptp','bigpond'))) {
1713
		/* dynamic WAN IP address, find out which one */
1714
		$wanif = get_real_wan_interface();
1715

    
1716
		/* get interface info with netstat */
1717
		exec("/usr/bin/netstat -nWI " . escapeshellarg($wanif) . " -f inet", $ifinfo);
1718

    
1719
		if (isset($ifinfo[1])) {
1720
			$aif = preg_split("/\s+/", $ifinfo[1]);
1721
			$curwanip = chop($aif[3]);
1722

    
1723
			if ($curwanip && is_ipaddr($curwanip) && ($curwanip != "0.0.0.0"))
1724
				return $curwanip;
1725
		}
1726

    
1727
		return null;
1728
	} else {
1729
		/* static WAN IP address */
1730
		return $wancfg['ipaddr'];
1731
	}
1732
}
1733

    
1734
/****f* interfaces/is_altq_capable
1735
 * NAME
1736
 *   is_altq_capable - Test if interface is capable of using ALTQ
1737
 * INPUTS
1738
 *   $int            - string containing interface name
1739
 * RESULT
1740
 *   boolean         - true or false
1741
 ******/
1742

    
1743
function is_altq_capable($int) {
1744
        /* Per:
1745
         * http://www.freebsd.org/cgi/man.cgi?query=altq&manpath=FreeBSD+6.0-current&format=html
1746
         * Only the following drivers have ALTQ support
1747
         */
1748
        $capable = array("an", "ath", "awi", "bfe", "bge", "dc", "de", "ed",
1749
		"em", "fxp", "hme", "lnc", "le", "nve", "re", "rl", "ndis", "sf", "sis", "sk",
1750
		"tun", "vr", "wi", "xl", "vlan", "ste");
1751

    
1752
        $int_family = preg_split("/[0-9]+/", $int);
1753

    
1754
        if (in_array($int_family[0], $capable))
1755
                return true;
1756
        else
1757
                return false;
1758
}
1759

    
1760
function get_number_of_bridged_interfaces() {
1761
	$bridges_total = 0;
1762
	$bridges = split("\n", `/sbin/ifconfig -a | /usr/bin/grep bridge | grep flags`);
1763
	foreach($bridges as $bridge) {
1764
		$match_array = "";
1765
		preg_match_all("/bridge(.*):/",$bridge,$match_array);
1766
		if($match_array[1][0] <> "") {
1767
			if($match_array[1][0] > $bridges_total)
1768
				$bridges_total = $match_array[1][0];
1769
		}
1770
	}
1771
	return "{$bridges_total}";
1772
}
1773

    
1774
function get_number_of_vlan_interfaces() {
1775
        $vlans_total = 0;
1776
        $vlans = split("\n", `/sbin/ifconfig -a | /usr/bin/grep vlan | grep flags`);
1777
        foreach($vlans as $bridge) {
1778
                $match_array = "";
1779
                preg_match_all("/vlan(.*):/",$bridge,$match_array);
1780
                if($match_array[1][0] <> "") {
1781
                        if($match_array[1][0] > $vlans_total)
1782
                                $vlans_total = $match_array[1][0];
1783
                }
1784
        }
1785
        return "{$vlans_total}";
1786
}
1787

    
1788
function get_number_of_ppp_interfaces() {
1789
        $ppps_total = 0;
1790
        $ppps = split("\n", `/sbin/ifconfig -a | /usr/bin/grep ppp | grep flags`);
1791
        foreach($ppps as $bridge) {
1792
                $match_array = "";
1793
                preg_match_all("/ppp(.*):/",$bridge,$match_array);
1794
                if($match_array[1][0] <> "") {
1795
                        if($match_array[1][0] > $ppps_total)
1796
                                $ppps_total = $match_array[1][0];
1797
                }
1798
        }
1799
        return "{$ppps_total}";
1800
}
1801

    
1802
function get_next_available_bridge_interface() {
1803
	$bridges_total = get_number_of_bridged_interfaces();
1804
	$interfaces = `/sbin/ifconfig -l`;
1805
	$x=0;
1806
	for($x=0; $x<$bridges_total; $x++) {
1807
		if(!stristr($interfaces, "bridge{$x}")) {
1808
			return "{$x}";
1809
		}
1810
	}
1811
	return "{$x}";
1812
}
1813

    
1814
function destroy_bridge($bridge_num) {
1815
	mwexec("/sbin/ifconfig bridge{$bridge_num} down");
1816
	sleep(1);
1817
	mwexec("/sbin/ifconfig bridge{$bridge_num} delete");
1818
	sleep(1);
1819
	mwexec("/sbin/ifconfig bridge{$bridge_num} destroy");
1820
	sleep(1);
1821
	return;
1822
}
1823

    
1824
function discover_bridge($interface1, $interface2) {
1825
	if(!$interface1) return;
1826
	if(!$interface2) return;
1827
	$total_bridges = get_number_of_bridged_interfaces();
1828
	$total_bridges++;
1829
	$interfaces = `/sbin/ifconfig -l`;
1830
	$x=0;
1831
	for($x=0; $x<$total_bridges; $x++) {
1832
		$bridge_text = "NA";
1833
		if(!stristr($interfaces, "bridge{$x}"))
1834
			continue;
1835
		$bridge_text = `/sbin/ifconfig bridge{$x} | grep member`;
1836
		if(stristr($bridge_text, $interface1))
1837
			if(stristr($bridge_text, $interface2))
1838
				return $x;
1839
	}
1840
	return "-1";
1841
}
1842

    
1843
function get_wireless_modes($interface)
1844
{
1845
	/* return wireless modes and channels */
1846
	if(is_interface_wireless($interface)) {
1847
		$wi = 1;
1848
		$ifconfig = "/sbin/ifconfig";
1849
		$awk = "/usr/bin/awk";
1850
		$chan_list = "$ifconfig $interface list chan";
1851
		$stack_list = "$awk -F\"Channel \" '{ gsub(/\\*/, \" \"); print \$2 \"\\\n\" \$3 }'";
1852
		$format_list = "$awk '{print \$5 \" \" \$6 \",\" \$1}'";
1853

    
1854
		$interface_channels = "";
1855
		exec("$chan_list | $stack_list | sort -u | $format_list 2>&1", $interface_channels);
1856
		$interface_channel_count = count($interface_channels);
1857

    
1858
		$c = 0;
1859
		while ($c < $interface_channel_count)
1860
		{
1861
			$channel_line = explode(",", $interface_channels["$c"]);
1862
			$wireless_mode = trim($channel_line[0]);
1863
			$wireless_channel = trim($channel_line[1]);
1864
			if(trim($wireless_mode) != "") {
1865
				/* if we only have 11g also set 11b channels */
1866
				if($wireless_mode == "11g") {
1867
					$wireless_modes["11b"] = array();
1868
				}
1869
				$wireless_modes["$wireless_mode"]["$c"] = $wireless_channel;
1870
			}
1871
			$c++;
1872
		}
1873
	}
1874
	return($wireless_modes);
1875
}
1876

    
1877
function get_interface_mac($interface) {
1878

    
1879
        /* build interface list with netstat */
1880
        $linkinfo = "";
1881
        exec("/usr/bin/netstat -I $interface -nW -f link", $linkinfo);
1882
        array_shift($linkinfo);
1883
        $alink = preg_split("/\s+/", $linkinfo[0]);
1884
        $mac = chop($alink[3]);
1885
        return $mac;
1886
}
1887

    
1888
?>
(11-11/29)