Project

General

Profile

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

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

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

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

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

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

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

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

    
43
function interfaces_bring_up($interface) {
44
	if(!$interface) {
45
		log_error("bring_interface_up was called but no variable defined.");
46
		log_error( "Backtrace: " . var_dump(debug_backtrace()) );
47
		return;
48
	}
49
	mwexec("/sbin/ifconfig " . escapeshellarg($interface) . " up");
50
}
51

    
52
function interfaces_loopback_configure() {
53
	mwexec("/sbin/ifconfig lo0 127.0.0.1");
54
	interfaces_bring_up("lo0");
55
	return 0;
56
}
57

    
58
function interfaces_vlan_configure() {
59
	global $config;
60
	$i = 0;
61
	if (is_array($config['vlans']['vlan']) && count($config['vlans']['vlan'])) {
62
		foreach ($config['vlans']['vlan'] as $vlan) {
63
			if(empty($vlan['vlanif']))
64
				$vlan['vlanif'] = "vlan{$i}";
65
			/* XXX: Maybe we should report any errors?! */
66
			interface_vlan_configure($vlan['if'], $vlan['tag'], $vlan['vlanif']);
67
			$i++;
68
		}
69
	}
70
}
71

    
72
function interface_vlan_configure($if, $tag, $vlanif = "") {
73
		if(!$if) {
74
			log_error("interface_vlan_confgure called with if defined.");
75
			return;
76
		}
77
		if(!$vlanif) {
78
			log_error("interface_vlan_confgure called with vlanif defined.");
79
			return;
80
		}
81

    
82
        global $config, $g;
83

    
84
        /* make sure the parent interface is up */
85
		interfaces_bring_up($if);
86
		/* Since we are going to add vlan(4) try to enable all that hardware supports. */
87
		mwexec("/sbin/ifconfig {$if} vlanhwtag");
88
		mwexec("/sbin/ifconfig {$if} vlanmtu");
89

    
90
        if ($g['booting'] || !(empty($vlanif))) {
91
		mwexec("/sbin/ifconfig {$vlanif} destroy");
92
		mwexec("/sbin/ifconfig {$vlanif} create");
93
        } else 
94
		$vlanif = exec("/sbin/ifconfig vlan create");
95
	
96
        mwexec("/sbin/ifconfig {$vlanif} vlan " .
97
                escapeshellarg($tag) . " vlandev " .
98
                escapeshellarg($if));
99

    
100
		interfaces_bring_up($vlanif);
101

    
102
        /* invalidate interface cache */
103
        get_interface_arr(true);
104

    
105
        /*   all vlans need to spoof their parent mac address, too.  see
106
         *   ticket #1514: http://cvstrac.pfsense.com/tktview?tn=1514,33
107
         */
108
        foreach($config['interfaces'] as $interfaces) {
109
                if($interfaces['if'] == $if && $interfaces['spoofmac']) {
110
                        mwexec("/sbin/ifconfig " . escapeshellarg($if) .
111
                                " link " . escapeshellarg($interfaces['spoofmac']));
112
                }
113
        }
114

    
115
        /* XXX: ermal -- for now leave it here at the moment it does not hurt. */
116
		interfaces_bring_up($if);
117

    
118
        return $vlanif;
119
}
120

    
121
function interfaces_bridge_configure() {
122
        global $config;
123

    
124
        $i = 0;
125
        if (is_array($config['bridges']['bridged']) && count($config['bridges']['bridged'])) {
126
                foreach ($config['bridges']['bridged'] as $bridge) {
127
                        if(empty($bridge['bridgeif']))
128
                                $bridge['bridgeif'] = "bridge{$i}";
129
                        /* XXX: Maybe we should report any errors?! */
130
                        interface_bridge_configure($bridge);
131
                        $i++;
132
                }
133
        }
134
}
135

    
136
function interface_bridge_configure(&$bridge) {
137
	global $config, $g;
138

    
139
	if (!is_array($bridge))
140
	        return -1;
141

    
142
	if (empty($bridge['members'])) {
143
		log_error("No members found on {$bridge['bridgeif']}");
144
		return -1;
145
	}
146

    
147
	$members = explode(',', $bridge['members']);
148
	if (!count($members))
149
		return -1;
150
	
151
	$checklist = get_configured_interface_list();
152

    
153
	if ($g['booting'] || !empty($bridge['bridgeif'])) {
154
		mwexec("/sbin/ifconfig {$bridge['bridgeif']} destroy");
155
		mwexec("/sbin/ifconfig {$bridge['bridgeif']} create");
156
		$bridgeif = $bridge['bridgeif'];
157
	} else {
158
		$bridgeif = exec("/sbin/ifconfig bridge create");
159
	}
160

    
161
	/* Calculate smaller mtu and enforce it */
162
	$smallermtu = 0;
163
	foreach ($members as $member) {
164
		$realif = get_real_interface($member);
165
		$mtu = get_interface_mtu($realif);
166
		if ($smallermtu == 0 && !empty($mtu))
167
			$smallermtu = $mtu;
168
		else if (!empty($mtu) && $mtu < $smallermtu)
169
			$smallermtu = $mtu;
170
	}
171
	 
172
	/* Just in case anything is not working well */
173
	if ($smallermtu == 0)
174
		$smallermtu = 1500; 
175

    
176
	/* Add interfaces to bridge */
177
	foreach ($members as $member) {
178
		if (!array_key_exists($member, $checklist))
179
			continue;
180
		$realif = get_real_interface($member);
181
		$realif =  escapeshellarg($realif);
182
		/* make sure the parent interface is up */
183
		mwexec("/sbin/ifconfig {$realif} mtu {$smallermtu}");
184
		if(!$realif) 
185
			log_error("realif not defined in interfaces bridge - up");
186
		interfaces_bring_up($realif);
187
		mwexec("/sbin/ifconfig {$bridgeif} addm {$realif}");	
188
	}
189

    
190
	if (isset($bridge['enablestp'])) {
191
		/* Choose spanning tree proto */
192
		mwexec("/sbin/ifconfig {$bridgeif} proto {$bridge['proto']}");	
193
		
194
		if (!empty($bridge['stp'])) {
195
			$stpifs = explode(',', $bridge['stp']);
196
			foreach ($stpifs as $stpif) {
197
				$realif = get_real_interface($stpif);
198
				mwexec("/sbin/ifconfig {$bridgeif} stp {$realif}");
199
			}
200
		}
201
		if (!empty($bridge['maxage']))
202
			mwexec("/sbin/ifconfig {$bridgeif} maxage {$bridge['maxage']}");
203
		if (!empty($brige['fwdelay']))
204
			mwexec("/sbin/ifconfig {$bridgeif} fwddelay {$bridge['fwdelay']}");
205
		if (!empty($brige['hellotime']))
206
                        mwexec("/sbin/ifconfig {$bridgeif} hellotime {$bridge['hellotime']}");
207
		if (!empty($brige['priority']))
208
                        mwexec("/sbin/ifconfig {$bridgeif} priority {$bridge['priority']}");
209
		if (!empty($brige['holdcount']))
210
                        mwexec("/sbin/ifconfig {$bridgeif} holdcnt {$bridge['holdcnt']}");
211
		if (!empty($bridge['ifpriority'])) {
212
			$pconfig = explode(",", $bridge['ifpriority']);
213
			$ifpriority = array();
214
			foreach ($pconfig as $cfg) {
215
				$embcfg = explode(":", $cfg);
216
				foreach ($embcfg as $key => $value)
217
					$ifpriority[$key] = $value;
218
			}
219
			foreach ($ifpriority as $key => $value) {
220
				$realif = get_real_interface($key);
221
				mwexec("/sbin/ifconfig ${bridgeif} ifpriority {$realif} {$value}"); 
222
			}
223
		}
224
		if (!empty($bridge['ifpathcost'])) {
225
			$pconfig = explode(",", $bridges['ifpathcost']);
226
			$ifpathcost = array();
227
			foreach ($pconfig as $cfg) {
228
				$embcfg = explode(":", $cfg);
229
				foreach ($embcfg as $key => $value)
230
					$ifpathcost[$key] = $value;
231
			}
232
			foreach ($ifpathcost as $key => $value) {
233
                        	$realif = get_real_interface($key);
234
                        	mwexec("/sbin/ifconfig ${bridgeif} ifpathcost {$realif} {$value}");
235
                	}
236
		}
237
	}
238

    
239
	if ($bridge['maxaddr'] <> "")
240
		mwexec("/sbin/ifconfig {$bridgeif} maxaddr {$bridge['maxaddr']}");
241
        if ($bridge['timeout'] <> "")
242
                mwexec("/sbin/ifconfig {$bridgeif} timeout {$bridge['timeout']}");
243
        if ($bridge['span'] <> "") {
244
		$realif = get_real_interface($bridge['span']);
245
                mwexec("/sbin/ifconfig {$bridgeif} span {$realif}");
246
	}
247
	if (!empty($bridge['edge'])) {
248
        	$edgeifs = explode(',', $bridge['edge']);
249
        	foreach ($edgeifs as $edgeif) {
250
			$realif = get_real_interface($edgeif);
251
                	mwexec("/sbin/ifconfig {$bridgeif} edge {$realif}");
252
        	}
253
	}
254
	if (!empty($bridge['autoedge'])) {
255
        	$edgeifs = explode(',', $bridge['autoedge']);
256
        	foreach ($edgeifs as $edgeif) {
257
                	$realif = get_real_interface($edgeif);
258
                	mwexec("/sbin/ifconfig {$bridgeif} -autoedge {$realif}");
259
        	}
260
	}
261
	if (!empty($bridge['ptp'])) {
262
        	$ptpifs = explode(',', $bridge['ptp']);
263
        	foreach ($ptpifs as $ptpif) {
264
                	$realif = get_real_interface($ptpif);
265
                	mwexec("/sbin/ifconfig {$bridgeif} ptp {$realif}");
266
        	}
267
	}
268
	if (!empty($bridge['autoptp'])) {
269
        	$ptpifs = explode(',', $bridge['autoptp']);
270
        	foreach ($ptpifs as $ptpif) {
271
                	$realif = get_real_interface($ptpif);
272
                	mwexec("/sbin/ifconfig {$bridgeif} -autoptp {$realif}");
273
        	}
274
	}
275
	if (!empty($bridge['static'])) {
276
        	$stickyifs = explode(',', $bridge['static']);
277
        	foreach ($stickyifs as $stickyif) {
278
                	$realif = get_real_interface($stickyif);
279
                	mwexec("/sbin/ifconfig {$bridgeif} sticky {$realif}");
280
        	}
281
	}
282
	if (!empty($bridge['private'])) {
283
        	$privateifs = explode(',', $bridge['private']);
284
        	foreach ($privateifs as $privateif) {
285
                	$realif = get_real_interface($privateif);
286
               	 	mwexec("/sbin/ifconfig {$bridgeif} private {$realif}");
287
        	}
288
	}
289

    
290
	if($bridgeif)
291
		interfaces_bring_up($bridgeif);	
292
	else 
293
		log_error("bridgeif not defined -- could not bring interface up");
294

    
295
	return $bridgeif;
296
}
297

    
298
function interfaces_lagg_configure() 
299
{
300
        global $config;
301

    
302
        $i = 0;
303
        if (is_array($config['laggs']['lagg']) && count($config['laggs']['lagg'])) {
304
                foreach ($config['laggs']['lagg'] as $lagg) {
305
                        if(empty($lagg['laggif']))
306
                                $lagg['laggif'] = "lagg{$i}";
307
                        /* XXX: Maybe we should report any errors?! */
308
                        interface_lagg_configure($lagg);
309
                        $i++;
310
                }
311
        }
312
}
313

    
314
function interface_lagg_configure(&$lagg) {
315
        global $config, $g;
316

    
317
        if (!is_array($lagg))
318
		return -1;
319

    
320
	$members = explode(',', $lagg['members']);
321
	if (!count($members))
322
		return -1;
323
	
324
	$checklist = get_interface_list();
325

    
326
	if ($g['booting'] || !(empty($lagg['laggif']))) {
327
                mwexec("/sbin/ifconfig {$lagg['laggif']} destroy");
328
                mwexec("/sbin/ifconfig {$lagg['laggif']} create");
329
                $laggif = $lagg['laggif'];
330
        } else
331
                $laggif = exec("/sbin/ifconfig lagg create");
332

    
333
	mwexec("/sbin/ifconfig {$laggif} {$lagg['proto']}");
334

    
335
	/* Calculate smaller mtu and enforce it */
336
        $smallermtu = 0;
337
        foreach ($members as $member) {
338
                $realif = get_real_interface($member);
339
                $mtu = get_interface_mtu($realif);
340
		if ($smallermtu == 0 && !empty($mtu))
341
			$smallermtu = $mtu;
342
                else if (!empty($mtu) && $mtu < $smallermtu)
343
                        $smallermtu = $mtu;
344
        }
345

    
346
	/* Just in case anything is not working well */
347
        if ($smallermtu == 0)
348
                $smallermtu = 1500;
349

    
350
	foreach ($members as $member) {
351
		if (!array_key_exists($member, $checklist))
352
			continue;
353
		$realif =  escapeshellarg($member);
354
		/* make sure the parent interface is up */
355
		mwexec("/sbin/ifconfig {$realif} mtu {$smallermtu}");
356
		if($realif)
357
			interfaces_bring_up($realif);
358
		else 
359
			log_error("could not bring realif up -- foreach(memebers)");
360
		mwexec("/sbin/ifconfig {laggif} laggport {$realif}");
361
	}
362
	
363
	interfaces_bring_up($laggif);
364

    
365
	return $laggif;
366
}
367

    
368
function interfaces_gre_configure() {
369
        global $config;
370

    
371
        $i = 0;
372
        if (is_array($config['gres']['gre']) && count($config['gres']['gre'])) {
373
                foreach ($config['gres']['gre'] as $gre) {
374
                        if(empty($gre['greif']))
375
                                $gre['greif'] = "gre{$i}";
376
                        /* XXX: Maybe we should report any errors?! */
377
                        interface_gre_configure($gre);
378
                        $i++;
379
                }
380
        }
381
}
382

    
383
function interface_gre_configure(&$gre) {
384
        global $config, $g;
385

    
386
	if (!is_array($gre))
387
		return -1;
388

    
389
	$realif = get_real_interface($gre['if']);
390
	$realifip = get_interface_ip($gre['if']);
391

    
392
	/* make sure the parent interface is up */
393
	interfaces_bring_up($realif);
394

    
395
	if ($g['booting'] || !(empty($gre['greif']))) {
396
		mwexec("/sbin/ifconfig {$gre['greif']} destroy");
397
		mwexec("/sbin/ifconfig {$gre['greif']} create");
398
		$greif = $gre['greif'];
399
	} else {
400
		$greif = exec("/sbin/ifconfig gre create");
401
	}
402

    
403
	/* Do not change the order here for more see gre(4) NOTES section. */
404
	mwexec("/sbin/ifconfig {$greif} tunnel {$realifip} {$gre['remote-addr']}");
405
	mwexec("/sbin/ifconfig {$greif} {$gre['tunnel-local-addr']} {$gre['tunnel-remote-addr']} netmask " . gen_subnet_mask($gre['tunnel-remote-net']));
406
	if (isset($gre['link0']) && $gre['link0'])
407
		mwexec("/sbin/ifconfig {$greif} link0");
408
	if (isset($gre['link1']) && $gre['link1'])
409
		mwexec("/sbin/ifconfig {$greif} link1");
410
	if (isset($gre['link2']) && $gre['link2'])
411
		mwexec("/sbin/ifconfig {$greif} link2");
412

    
413
	if($greif)
414
		interfaces_bring_up($greif);
415
	else 
416
		log_error("Could not bring greif up -- variable not defined.");
417

    
418
	mwexec("/sbin/route add {$gre['remote-addr']}/{$gre['tunnel-remote-net']} {$realifip}");
419
	file_put_contents("/tmp/{$greif}_router", $gre['tunnel-remote-addr']);
420

    
421
	return $greif;
422
}
423

    
424
function interfaces_gif_configure() {
425
        global $config;
426

    
427
        $i = 0;
428
        if (is_array($config['gifs']['gif']) && count($config['gifs']['gif'])) {
429
                foreach ($config['gifs']['gif'] as $gif) {
430
                        if(empty($gif['gifif']))
431
                                $gre['gifif'] = "gif{$i}";
432
                        /* XXX: Maybe we should report any errors?! */
433
                        interface_gif_configure($gif);
434
                        $i++;
435
                }
436
        }
437
}
438

    
439
function interface_gif_configure(&$gif) {
440
        global $config, $g;
441

    
442
        if (!is_array($gif))
443
                return -1;
444

    
445
        $realif = get_real_interface($gif['if']);
446
        $realifip = get_interface_ip($gif['if']);
447

    
448
        /* make sure the parent interface is up */
449
		if($realif)
450
			interfaces_bring_up($realif);
451
		else 
452
			log_error("could not bring realif up -- variable not defined -- interface_gif_configure()");
453

    
454
        if ($g['booting'] || !(empty($gif['gifif']))) {
455
                mwexec("/sbin/ifconfig {$gif['gifif']} destroy");
456
                mwexec("/sbin/ifconfig {$gif['gifif']} create");
457
                $gifif = $gif['gifif'];
458
        } else
459
                $gifif = exec("/sbin/ifconfig gif create");
460

    
461
        /* Do not change the order here for more see gif(4) NOTES section. */
462
        mwexec("/sbin/ifconfig {$gifif} tunnel {$realifip} {$gif['remote-addr']}");
463
        mwexec("/sbin/ifconfig {$gifif} {$gif['tunnel-local-addr']} {$gif['tunnel-remote-addr']} netmask " . gen_subnet_mask($gif['tunnel-remote-net']));
464
        if (isset($gif['link0']) && $gif['link0'])
465
                mwexec("/sbin/ifconfig {$gifif} link0");
466
        if (isset($gif['link1']) && $gif['link1'])
467
                mwexec("/sbin/ifconfig {$gifif} link1");
468
		if($gifif)
469
			interfaces_bring_up($gifif);
470
		else
471
		 	log_error("could not bring gifif up -- variable not defined");
472
        mwexec("/sbin/route add {$gif['remote-addr']}/{$gif['tunnel-remote-net']} {$realifip}");
473
		file_put_contents("/tmp/{$gifif}_router", $gif['tunnel-remote-addr']);
474

    
475
        return $gifif;
476
}
477

    
478
function interfaces_configure() {
479
	global $config, $g;
480

    
481
	/* set up VLAN virtual interfaces */
482
	interfaces_vlan_configure();
483

    
484
	/* set up LAGG virtual interfaces */
485
	interfaces_lagg_configure();
486

    
487
	/* Set up PPP interfaces */
488
	interfaces_ppp_configure();
489

    
490
	$iflist = get_configured_interface_with_descr();
491
	$delayed_list = array();
492
	$bridge_list = array();
493
	
494
	foreach($iflist as $if => $ifname) {
495
		$realif = $config['interfaces'][$if]['if'];
496
		if(isset($realif['pppoe_reset'])) 
497
			setup_pppoe_reset_file($if, true);
498
		else 
499
			setup_pppoe_reset_file($if, false);
500
		if (strstr($realif, "bridge")) 
501
			$bridge_list[$if] = $ifname;
502
		else if (strstr($realif, "gre"))
503
			$delayed_list[$if] = $ifname;
504
		else if (strstr($realif, "gif"))
505
			$delayed_list[$if] = $ifname;
506
		else {
507
			if ($g['booting'])
508
				echo "Configuring {$ifname} interface...";
509
        	if($g['debug'])
510
				log_error("Configuring {$ifname}");
511
			interface_configure($if);
512
			if ($g['booting']) 
513
				echo "done.\n";
514
		}
515
	}
516

    
517
	/* set up GRE virtual interfaces */
518
	interfaces_gre_configure();
519

    
520
	/* set up GIF virtual interfaces */
521
	interfaces_gif_configure();
522
	
523
	foreach ($delayed_list as $if => $ifname) {
524
		if ($g['booting'])
525
			echo "Configuring {$ifname} interface...";
526
        if($g['debug'])
527
        	log_error("Configuring {$ifname}");
528

    
529
		interface_configure($if);
530

    
531
		if ($g['booting'])
532
			echo "done.\n";
533
	}
534

    
535
	/* set up BRIDGe virtual interfaces */
536
	interfaces_bridge_configure();
537

    
538
	foreach ($bridge_list as $if => $ifname) {
539
		if ($g['booting'])
540
			echo "Configuring {$ifname} interface...";
541
		if($g['debug'])
542
			log_error("Configuring {$ifname}");
543

    
544
		interface_configure($if);
545

    
546
		if ($g['booting'])
547
			echo "done.\n";
548
	}
549

    
550
	/* bring up carp interfaces */
551
	interfaces_carp_configure();
552

    
553
	/* bring ip IP aliases */
554
	interfaces_ipalias_configure();
555

    
556
	if (!$g['booting']) {
557
		/* reconfigure static routes (kernel may have deleted them) */
558
		system_routing_configure();
559

    
560
		/* reload IPsec tunnels */
561
		vpn_ipsec_configure();
562

    
563
		/* reload dhcpd (interface enabled/disabled status may have changed) */
564
		services_dhcpd_configure();
565

    
566
		/* restart dnsmasq */
567
		services_dnsmasq_configure();
568

    
569
		/* reload captive portal */
570
		captiveportal_configure();
571

    
572
		/* set the reload filter dity flag */
573
		filter_configure();
574
	}
575

    
576
	return 0;
577
}
578

    
579
function interface_reconfigure($interface = "wan") {
580
	interface_bring_down($interface);
581
	sleep(1);
582
	interface_configure($interface);
583
}
584

    
585
function interface_bring_down($interface = "wan") {
586
	global $config, $g;
587

    
588
	$ifcfg = $config['interfaces'][$interface];
589

    
590
	$realif = get_real_interface($interface);
591

    
592
	mwexec("/usr/sbin/arp -d -i {$realif} -a");
593

    
594
        /* remove interface up file if it exists */
595
        unlink_if_exists("{$g['tmp_path']}/{$interface}up");
596
        unlink_if_exists("{$g['vardb_path']}/{$interface}ip");
597
        unlink_if_exists("{$g['varetc_path']}/nameservers.conf");
598

    
599
	switch ($ifcfg['ipaddr']) {
600
	case "pppoe":
601
		killbypid("{$g['varrun_path']}/pppoe_{$interface}.pid");
602
        	sleep(2);
603
                unlink_if_exists("{$g['varetc_path']}/mpd_{$interface}.conf");
604
                unlink_if_exists("{$g['varetc_path']}/mpd_{$interface}.links");
605
		break;
606
	case "pptp":
607
		killbypid("{$g['varrun_path']}/pptp_{$interface}.pid");
608
        	sleep(2);
609
                unlink_if_exists("{$g['varetc_path']}/mpd_{$interface}.conf");
610
                unlink_if_exists("{$g['varetc_path']}/mpd_{$interface}.links");
611
		break;
612
	case "carpdev-dhcp":
613
		/* 
614
		 * NB: When carpdev gets enabled it would be better to be handled as all
615
		 *	other interfaces! 
616
		 */
617
	case "dhcp":
618
        	$pid = find_dhclient_process($interface);
619
        	if($pid)
620
                	mwexec("kill {$pid}");
621
               	sleep(1);
622
                unlink_if_exists("{$g['varetc_path']}/dhclient_{$interface}.conf");
623
               	mwexec("/sbin/ifconfig {$realinterface} delete down");
624
		break;
625
	default:
626
		mwexec("/sbin/ifconfig " . escapeshellarg($realif) . " delete down");
627
		break;
628
	}
629

    
630
	if (preg_match("/^tun|^ppp|^ovpn|^gif|^gre|^lagg|^bridge|^vlan/i", $realif))
631
                mwexec("/sbin/ifconfig {$realif} destroy");
632
	
633
	unlink_if_exists("/tmp/{$realif}_router");
634
	return;
635
}
636

    
637
function interfaces_ppp_configure() {
638
        global $config;
639

    
640
        $i = 0;
641
        if (is_array($config['ppps']['ppp']) && count($config['ppps']['ppp'])) {
642
                foreach ($config['ppps']['ppp'] as $ppp) {
643
                        if(empty($ppp['pppif']))
644
                                $ppp['pppif'] = "ppp{$i}";
645
                        /* XXX: Maybe we should report any errors?! */
646
                        interface_ppp_configure($ppp);
647
                        $i++;
648
                }
649
        }
650
}
651

    
652
function interface_ppp_configure($ifcfg) {
653
	global $config, $g;
654
	
655
	/* Remove  the /dev/ from the device name. */
656
	$dev = substr($ifcfg['port'], 5);
657

    
658
	$realif  = $ifcfg['pppif'];
659
	if ($realif <> "") {
660
		$i = 0;
661
		while ($realif != "ppp{$i}")
662
			$i++;
663
		if(file_exists("/var/run/ppp{$i}.pid")) {
664
			$pid = trim(file_get_contents("/var/run/ppp{$i}.pid"));
665
			mwexec("kill {$pid}");
666
		}
667
	}
668
	
669
	if ($g['booting'] || $realif <> "") {
670
                mwexec("/sbin/ifconfig {$realif} destroy");
671
                mwexec("/sbin/ifconfig {$realif} create");
672
        } else
673
                $realif = exec("/sbin/ifconfig ppp create");
674

    
675

    
676
	$peerfile = "lcp-echo-failure 0\n";
677
	$peerfile .= "lcp-echo-interval 0\n";
678
	$peerfile .= "connect /etc/ppp/peers/ppp{$dev}-connect-chat\n";
679
	//$peerfile .= "disconnect /etc/ppp/peers/ppp{$dev}-disconnect-chat\n";
680
	$peerfile .= "{$ifcfg['port']} {$ifcfg['linespeed']}\n";
681
	$peerfile .= "crtscts\n";
682
	if ($ifcfg['connect-max-attempts'] <> "")
683
		$peerfile .= "connect-max-attempts {$ifcfg['connect-max-attempts']}";
684
	$peerfile .= "local\n";
685
	if ($ifcfg['localip'] <> "") {
686
		$peerfile .= ":{$ifcfg['gateway']}\n";
687
		$peerfile .= "{$ifcfg['localip']}:{$ifcfg['gateway']}";
688
	} else if ($ifcfg['gateway'] <> "") {
689
		$peerfile .= ":{$ifcfg['gateway']}\n";
690
		$peerfile .= "noipdefault\n";
691
	} else 
692
		$peerfile .= "noipdefault\n";
693
	$peerfile .= "ipcp-accept-local\n";
694
	$peerfile .= "novj\n";
695
	$peerfile .= "nobsdcomp\n";
696
	$peerfile .= "novjccomp\n";
697
	$peerfile .= "nopcomp\n";
698
	$peerfile .= "noaccomp\n";
699
	$peerfile .= "noauth\n";
700
	//$peerfile .= "nodetach\n";
701
	$peerfile .= "persist\n";
702
	$peerfile .= "debug\n";
703
	// KD - test
704
	//$peerfile .= "defaultroute\n";
705
	//$peerfile .= "nodetach\n";
706
	// KD - so I know where to look!
707
	$peerfile .= "# created by /etc/inc/interfaces.inc\n";
708

    
709
	// Added single quotes to some strings below:
710
	// the \rAT is *always* going to need it
711
	// and the phone number on a GSM connection ends in a # char
712
	// Kevin Dawson, 22 Jan 2008
713
	// Refer Andrew Curtis
714
			
715
	$chatfile = "#!/bin/sh\n";
716
	$chatfile .= "exec chat \\\n";
717
	$chatfile .= "TIMEOUT 5 \\\n";
718
	$chatfile .= "ECHO ON \\\n";
719
	$chatfile .= "ABORT '\\nBUSY\\r' \\\n";
720
	$chatfile .= "ABORT '\\nERROR\\r' \\\n";
721
	$chatfile .= "ABORT '\\nNO ANSWER\\r' \\\n";
722
	$chatfile .= "ABORT '\\nNO CARRIER\\r' \\\n";
723
	$chatfile .= "ABORT '\\nNO DIALTONE\\r' \\\n";
724
	$chatfile .= "ABORT '\\nRINGING\\r\\n\\r\\nRINGING\\r' \\\n";
725
	// KD
726
	$chatfile .= "'' '\\rAT' \\\n";
727
	$chatfile .= "TIMEOUT 12 \\\n";
728
	$chatfile .= "OK ATH \\\n";
729
	$chatfile .= "OK ATE1 \\\n";
730
	$chatfile .= "OK 'AT+CGDCONT=1,\"IP\",\"{$ifcfg['ap']}\"' \\\n";
731
	// KD
732
	$chatfile .= "OK 'ATD{$ifcfg['phone']}' \\\n";
733
	$chatfile .= "TIMEOUT 22 \\\n";
734
	if ($ifcfg['username'] <> "") {
735
		$chatfile .= "CONNECT \"\" TIMEOUT 10 \\\n";
736
		$chatfile .= "ogin:-\\r-ogin: {$ifcfg['username']}\\\n";
737
		$chatfile .= " TIMEOUT 5 sword: {$ifcfg['password']} \\\n";
738
	} else
739
		$chatfile .= "CONNECT \"\" \\\n";
740
	$chatfile .= "SAY \"\\nConnected.\"\n";
741

    
742
	config_lock();
743
	conf_mount_rw();
744
	safe_mkdir("/etc/ppp/peers", "0755");
745
	file_put_contents("/etc/ppp/peers/ppp_{$dev}", $peerfile);
746
	file_put_contents("/etc/ppp/peers/ppp{$dev}-connect-chat", $chatfile);
747
	chmod("/etc/ppp/peers/ppp{$dev}-connect-chat", 0755);
748
	conf_mount_ro();
749
	config_unlock();
750
	
751
	sleep(1);
752
	mwexec("/usr/sbin/pppd call ppp_{$dev}");
753

    
754
	return $realif;
755
}
756

    
757
function interfaces_carp_configure() {
758
	global $g, $config;
759
	$balanacing = "";
760
	$pfsyncinterface = "";
761
	$pfsyncenabled = "";
762
	if(isset($config['system']['developerspew'])) {
763
		$mt = microtime();
764
		echo "interfaces_carp_configure() being called $mt\n";
765
	}
766
	// Prepare CmdCHAIN that will be used to execute commands.
767
	$cmdchain = new CmdCHAIN();	
768
	$carp_instances_counter = 0;
769
	$total_carp_interfaces_defined = find_number_of_created_carp_interfaces();
770
	/* destroy previous interfaces */
771
	for($x=0; $x<$total_carp_interfaces_defined; $x++) 
772
		$cmdchain->add("Delete CARP interface", "/sbin/ifconfig carp{$x} delete", false);
773
	if ($g['booting']) {
774
		echo "Configuring CARP interfaces...";
775
		mute_kernel_msgs();
776
	}
777
	/* suck in configuration items */
778
	if($config['installedpackages']['carpsettings']) 
779
		if($config['installedpackages']['carpsettings']['config']) {
780
		foreach($config['installedpackages']['carpsettings']['config'] as $carp) {
781
			$pfsyncenabled = $carp['pfsyncenabled'];
782
			$balanacing = $carp['balancing'];
783
			$pfsyncinterface = $carp['pfsyncinterface'];
784
			$pfsyncpeerip = $carp['pfsyncpeerip'];
785
		}
786
	} else {
787
		unset($pfsyncinterface);
788
		unset($balanacing);
789
		unset($pfsyncenabled);
790
	}
791
	$cmdchain->add("Allow CARP", "/sbin/sysctl net.inet.carp.allow=1", true);			
792
	if($balanacing) {
793
		$cmdchain->add("Enable CARP ARP-balancing", "/sbin/sysctl net.inet.carp.arpbalance=1", true);
794
		$cmdchain->add("Disallow CARP preemption", "/sbin/sysctl net.inet.carp.preempt=0", true);
795
	} else {
796
		$cmdchain->add("Enable CARP preemption", "/sbin/sysctl net.inet.carp.preempt=1", true);		
797
	}
798
	$cmdchain->add("Enable CARP logging", "/sbin/sysctl net.inet.carp.log=2", true);
799
	$carp_sync_int = convert_friendly_interface_to_real_interface_name($pfsyncinterface);
800
	if($g['booting']) {
801
		/*    install rules to alllow pfsync to sync up during boot
802
		 *    carp interfaces will remain down until the bootup sequence finishes
803
		 */
804
		exec("echo pass quick proto carp all keep state > /tmp/rules.boot");
805
		exec("echo pass quick proto pfsync all >> /tmp/rules.boot");
806
		exec("echo pass out quick from any to any keep state >> /tmp/rules.boot");
807
		exec("/sbin/pfctl -f /tmp/rules.boot");
808
	}
809
	/* setup pfsync interface */
810
	if($carp_sync_int and $pfsyncenabled) {
811
		if($pfsyncpeerip) {
812
			$cmdchain->add("Bring up pfsync0 syncpeer", "/sbin/ifconfig pfsync0 syncdev {$carp_sync_int} syncpeer {$pfsyncpeerip} up", false);						
813
		} else {
814
			$cmdchain->add("Bring up pfsync0 syncdev", "/sbin/ifconfig pfsync0 syncdev {$carp_sync_int} up", false);			
815
		}
816
	} else {
817
		$cmdchain->add("Bring up pfsync0", "/sbin/ifconfig pfsync0 syncdev lo0 up", false);						
818
	}
819
	//$fd = fopen("/tmp/carp.sh", "w");
820
	$viparr = &$config['virtualip']['vip'];
821
	if($config['virtualip']['vip']) {
822
		$cmdchain->add("Allow CARP.", "/sbin/sysctl net.inet.carp.allow=1", true);				
823
	} else {
824
		$viparr = array();
825
		$cmdchain->add("Disallow CARP.", "/sbin/sysctl net.inet.carp.allow=0", true);		
826
	}
827
	if(!$viparr and $config['interfaces']['wan']['ipaddr'] == "carpdev-dhcp") {
828
		/* no vips exist but we need to bring up carpdev... */
829
		$viparr_temp = array();
830
		$viparr_temp['advskew'] = "200";
831
		$viparr_temp['vhid'] = "1";
832
		$viparr_temp['mode'] = "carpdev-dhcp";
833
		$viparr_temp['password'] = $config['system']['hostname'] . "pfS";
834
		$viparr = $viparr_temp;
835
	}
836
	
837
	if($g['debug'])
838
		$cmdchain->setdebug(); // optional for verbose logging
839
	$cmdchain->execute();
840
	
841
	// Reset CmdCHAIN
842
	$cmdchain->clear();
843

    
844
	if(is_array($viparr))
845
	foreach ($viparr as $vip) {
846
		$vip_password = $vip['password'];
847
		$vip_password = str_replace(" ", "", $vip_password);
848
		if($vip['password'] != "")
849
                	$password = " pass \"" . $vip_password . "\"";
850
		$interface = filter_translate_type_to_real_interface($vip['interface']);
851
		$carpint = "carp" . $carp_instances_counter;
852

    
853
		switch ($vip['mode']) {
854
		case "carp":
855
			/* ensure CARP IP really exists prior to loading up */
856
			$found = false;
857
			$iflist = get_configured_interface_list();
858
			foreach($iflist as $if) {
859
				$ww_subnet_ip = $config['interfaces'][$if]['ipaddr'];
860
				$ww_subnet_bits = $config['interfaces'][$if]['subnet'];
861
				if (ip_in_subnet($vip['subnet'], gen_subnet($ww_subnet_ip, $ww_subnet_bits) . "/" . $ww_subnet_bits))
862
					$found = true;
863
			}
864
			if($found == false) {
865
				file_notice("CARP", "Sorry but we could not find a matching real interface subnet for the virtual IP address {$vip['subnet']}.", "Firewall: Virtual IP", "");
866
				continue;
867
			}			
868
			/* create the carp interface and setup */
869
			$cmdchain->add("create CARP interface", "/sbin/ifconfig {$carpint} create", false);
870

    
871
			/* invalidate interface cache */
872
			get_interface_arr(true);
873
			$broadcast_address = gen_subnet_max($vip['subnet'], $vip['subnet_bits']);
874
			$cmdchain->add("config CARP interface", "/sbin/ifconfig {$carpint} " . $vip['subnet'] . "/" . $vip['subnet_bits'] . " broadcast " . $broadcast_address . " vhid " . $vip['vhid'] . " advskew " . $vip['advskew'] . $password, false);
875
			$cmdchain->add("bring CARP interface UP", "/sbin/ifconfig {$carpint} up", false);
876
			$carp_instances_counter++;
877
			break;
878
		case "carpdev-dhcp":
879
			log_error("Found carpdev interface {$vip['interface']} on top of interface {$interface}");
880
			if(!empty($interface)) {
881
				
882
					$cmdchain->add("bring CARP parent interface UP", "/sbin/ifconfig {$interface} up", false);			
883
					$cmdchain->add("create CARP interface", "/sbin/ifconfig {$carpint} create", false);
884
					$cmdchain->add("bring CARP interface UP", "/sbin/ifconfig {$carpint} up", false);
885
					$cmdchain->add("assign CARP CarpDEV directive", "/sbin/ifconfig {$carpint} carpdev ". $interface . " vhid " . $vip['vhid'] . " advskew " . $vip['advskew'] . $password, false);
886
					$cmdchain->add("bring CARP interface UP", "/sbin/ifconfig {$carpint} up", false);
887

    
888
					/*
889
					 * XXX: BIG HACK but carpdev needs ip services active
890
					 * 	before even starting something as dhclient.
891
					 * 	I do not know if this is a feature or a bug
892
					 * 	but better than track it make it work ;) .
893
					 */
894
					//$fakeiptouse = "10.254.254." . ($carp_instances_counter+1);
895
					//$cmdchain->add("CarpDEV hack", "/sbin/ifconfig {$carpint} inet {$fakeiptouse}", false);
896

    
897
        			/* generate dhclient_wan.conf */
898
        			$fd = fopen("{$g['varetc_path']}/dhclient_{$carpint}.conf", "w");
899
        			if ($fd) {
900

    
901
        				$dhclientconf = "";
902

    
903
        				$dhclientconf .= <<<EOD
904
interface "{$carpint}" {
905
timeout 60;
906
retry 1;
907
select-timeout 0;
908
initial-interval 1;
909
script "/sbin/dhclient-script";
910
}
911

    
912
EOD;
913

    
914
 			        fwrite($fd, $dhclientconf);
915
        			fclose($fd);
916

    
917
        			/* fire up dhclient */
918
					$cmdchain->add("bring CARP dhclient UP", "/sbin/dhclient -c {$g['varetc_path']}/dhclient_{$carpint}.conf {$carpint} >/tmp/{$carpint}_output >/tmp/{$carpint}_error_output", false);
919
				} else {
920
					log_error("Error: cannot open dhclient_{$carpint}.conf in interfaces_carp_configure() for writing.\n");
921
					$cmdchain->add("bring CARP dhclient UP in background", "/sbin/dhclient -b {$carpint}", false);					
922
				}
923

    
924
        		$fout = fopen("/tmp/ifconfig_{$carpint}","w");
925
        		fwrite($fout, "/sbin/dhclient -c {$g['varetc_path']}/dhclient_{$carpint}.conf {$carpint}");
926
        		fclose($fout);
927

    
928
			} else {
929
				log_error("Could not determine CarpDEV parent interface for {$vip['descr']}.");
930
			}
931
			$carp_instances_counter++;
932
			break;
933
		}
934
	}
935

    
936
	if($g['debug'])
937
		$cmdchain->setdebug(); // optional for verbose logging
938
	// Execute built up command chain.
939
	$cmdchain->execute();	
940

    
941
	if ($g['booting']) {
942
		unmute_kernel_msgs();
943
		echo "done.\n";
944
	}
945

    
946
	/* update cache */
947
	if ($carp_instances_counter != find_number_of_created_carp_interfaces())
948
		find_number_of_created_carp_interfaces(true);
949

    
950
}
951

    
952
function interfaces_ipalias_configure() {
953
	global $g, $config;
954
	if(isset($config['system']['developerspew'])) {
955
		$mt = microtime();
956
		echo "interfaces_ipalias_configure() being called $mt\n";
957
	}
958
	$viparr = &$config['virtualip']['vip'];
959
	if(is_array($viparr)) {
960
		foreach ($viparr as $vip) {
961
			if ($vip['mode'] == "ipalias") {
962
				$if = get_real_interface($vip['interface']);
963
				mwexec("/sbin/ifconfig " . escapeshellarg($if) . " " . $vip['subnet'] . "/" . escapeshellarg($vip['subnet_bits']) . " alias"); 
964
			}
965
		}
966
	}
967
}
968

    
969
function interface_wireless_configure($if, $wlcfg) {
970
	global $config, $g;
971

    
972
	/*    open up a shell script that will be used to output the commands.
973
	 *    since wireless is changing a lot, these series of commands are fragile
974
     *    and will sometimes need to be verified by a operator by executing the command
975
     *    and returning the output of the command to the developers for inspection.  please
976
     *    do not change this routine from a shell script to individul exec commands.  -sullrich
977
	 */
978

    
979
	conf_mount_rw();
980

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

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

    
987
	fwrite($fd_set, "# enable shell debugging\n");
988
	fwrite($fd_set, "set -x\n");
989

    
990
	/* set values for /path/program */
991
	$hostapd = "/usr/sbin/hostapd";
992
	$wpa_supplicant = "/usr/sbin/wpa_supplicant";
993
	$ifconfig = "/sbin/ifconfig";
994
	$killall = "/usr/bin/killall";
995

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

    
998
	/* Set a/b/g standard */
999
	$standard = "mode " . escapeshellarg($wlcfg['standard']);
1000

    
1001
	/* Set 802.11g protection mode */
1002
	$protmode = "protmode " . escapeshellarg($wlcfg['protmode']);
1003

    
1004
	/* set wireless channel value */
1005
	if(isset($wlcfg['channel']))
1006
		if($wlcfg['channel'] == "0")
1007
			$channel = "channel any";
1008
		else
1009
			$channel = "channel " . escapeshellarg($wlcfg['channel']);
1010

    
1011
	/* set Distance value */
1012
	if($wlcfg['distance'])
1013
		$distance = escapeshellarg($wlcfg['distance']);
1014

    
1015
	/* Set ssid */
1016
	if($wlcfg['ssid'])
1017
		$ssid = "ssid " . escapeshellarg($wlcfg['ssid']);
1018

    
1019
	/* Set wireless hostap mode */
1020
	if ($wlcfg['mode'] == "hostap")
1021
		$hostapmode = "mediaopt hostap";
1022
	else
1023
		$hostapmode = "-mediaopt hostap";
1024

    
1025
	/* Set wireless adhoc mode */
1026
	if ($wlcfg['mode'] == "adhoc")
1027
		$adhocmode = "mediaopt adhoc";
1028
	else
1029
		$adhocmode = "-mediaopt adhoc";
1030

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

    
1033
	/* handle hide ssid option */
1034
	if(isset($wlcfg['hidessid']['enable']))
1035
		$hidessid = "hidessid";
1036
	else
1037
		$hidessid = "-hidessid";
1038

    
1039
	/* handle pureg (802.11g) only option */
1040
	if(isset($wlcfg['pureg']['enable']))
1041
		$pureg = "mode 11g pureg";
1042
	else
1043
		$pureg = "-pureg";
1044

    
1045
	/* enable apbridge option */
1046
	if(isset($wlcfg['apbridge']['enable']))
1047
		$apbridge = "apbridge";
1048
	else
1049
		$apbridge = "-apbridge";
1050

    
1051
	/* handle turbo option */
1052
	if(isset($wlcfg['turbo']['enable']))
1053
		$turbo = "mediaopt turbo";
1054
	else
1055
		$turbo = "-mediaopt turbo";
1056

    
1057
	/* handle txpower setting */
1058
	if($wlcfg['txpower'] <> "")
1059
		$txpower = "txpower " . escapeshellarg($wlcfg['txpower']);
1060

    
1061
	/* handle wme option */
1062
	if(isset($wlcfg['wme']['enable']))
1063
		$wme = "wme";
1064
	else
1065
		$wme = "-wme";
1066

    
1067
	/* set up wep if enabled */
1068
    if (isset($wlcfg['wep']['enable']) && is_array($wlcfg['wep']['key'])) {
1069
		if($wlcfg['wpa']['auth_algs'] == "1")
1070
			$wepset .= "authmode open wepmode on ";
1071
		else if($wlcfg['wpa']['auth_algs'] == "2")
1072
			$wepset .= "authmode shared wepmode on ";
1073
		else if($wlcfg['wpa']['auth_algs'] == "3")
1074
			$wepset .= "authmode mixed wepmode on ";
1075
		$i = 1;
1076
		foreach ($wlcfg['wep']['key'] as $wepkey) {
1077
			$wepset .= "wepkey " . escapeshellarg("{$i}:{$wepkey['value']}") . " ";
1078
			if (isset($wepkey['txkey']))
1079
				$wepset .= "weptxkey {$i} ";
1080
			$i++;
1081
		}
1082
    } else {
1083
    	$wepset .= "authmode open wepmode off ";
1084
	}
1085

    
1086
	/* generate wpa_supplicant/hostap config if wpa is enabled */
1087

    
1088
	switch ($wlcfg['mode']) {
1089
		case 'bss':
1090
			if (isset($wlcfg['wpa']['enable'])) {
1091

    
1092
				$wpa .= <<<EOD
1093
ctrl_interface={$g['varrun_path']}/wpa_supplicant
1094
ctrl_interface_group=0
1095
ap_scan=1
1096
#fast_reauth=1
1097
network={
1098
ssid="{$wlcfg['ssid']}"
1099
scan_ssid=1
1100
priority=5
1101
key_mgmt={$wlcfg['wpa']['wpa_key_mgmt']}
1102
psk="{$wlcfg['wpa']['passphrase']}"
1103
pairwise={$wlcfg['wpa']['wpa_pairwise']}
1104
group={$wlcfg['wpa']['wpa_pairwise']}
1105
}
1106
EOD;
1107

    
1108
				$fd = fopen("{$g['varetc_path']}/wpa_supplicant_{$if}.conf", "w");
1109
				fwrite($fd, "{$wpa}");
1110
				fclose($fd);
1111

    
1112
				fwrite($fd_set, kill_wpasupplicant($if));
1113
			}
1114
		break;
1115

    
1116
		case 'hostap':
1117
			if (isset($wlcfg['wpa']['enable'])) {
1118
				$wpa .= <<<EOD
1119
interface={$if}
1120
driver=bsd
1121
logger_syslog=-1
1122
logger_syslog_level=0
1123
logger_stdout=-1
1124
logger_stdout_level=0
1125
dump_file={$g['tmp_path']}/hostapd_{$if}.dump
1126
ctrl_interface={$g['varrun_path']}/hostapd
1127
ctrl_interface_group=wheel
1128
#accept_mac_file={$g['tmp_path']}/hostapd_{$if}.accept
1129
#deny_mac_file={$g['tmp_path']}/hostapd_{$if}.deny
1130
#macaddr_acl={$wlcfg['wpa']['macaddr_acl']}
1131
ssid={$wlcfg['ssid']}
1132
debug={$wlcfg['wpa']['debug_mode']}
1133
auth_algs={$wlcfg['wpa']['auth_algs']}
1134
wpa={$wlcfg['wpa']['wpa_mode']}
1135
wpa_key_mgmt={$wlcfg['wpa']['wpa_key_mgmt']}
1136
wpa_pairwise={$wlcfg['wpa']['wpa_pairwise']}
1137
wpa_group_rekey={$wlcfg['wpa']['wpa_group_rekey']}
1138
wpa_gmk_rekey={$wlcfg['wpa']['wpa_gmk_rekey']}
1139
wpa_strict_rekey={$wlcfg['wpa']['wpa_strict_rekey']}
1140
wpa_passphrase={$wlcfg['wpa']['passphrase']}
1141
ieee8021x={$wlcfg['wpa']['ieee8021x']}
1142
#Enable the next lines for preauth when roaming. Interface = wired or wireless interface talking to the AP you want to roam from/to
1143
#rsn_preauth=1
1144
#rsn_preauth_interfaces=eth0
1145
EOD;
1146

    
1147
				$fd = fopen("{$g['varetc_path']}/hostapd_{$if}.conf", "w");
1148
				fwrite($fd, "{$wpa}");
1149
				fclose($fd);
1150

    
1151
				fwrite($fd_set, kill_hostapd($if));
1152
			}
1153
		break;
1154

    
1155
		case 'adhoc':
1156
			fwrite($fd_set, kill_hostapd($if));
1157
			fwrite($fd_set, kill_wpasupplicant($if));
1158
		break;
1159
	}
1160

    
1161
	/*
1162
	 *    all variables are set, lets start up everything
1163
     */
1164

    
1165
	/* set ack timers according to users preference (if he/she has any) */
1166
	if($distance) {
1167
		fwrite($fd_set, "# Enable ATH distance settings\n");
1168
		fwrite($fd_set, "/sbin/athctrl.sh -i {$if} -d {$distance}\n");
1169
	}
1170

    
1171
	$standard_no_turbo = str_replace(" Turbo", "", $standard);
1172

    
1173
	$settings = <<<EOD
1174

    
1175
{$ifconfig} {$if} down
1176
{$ifconfig} {$if} {$standard_no_turbo}
1177
{$ifconfig} {$if} {$channel}
1178
{$ifconfig} {$if} {$turbo}
1179
{$ifconfig} {$if} {$ssid}
1180
{$ifconfig} {$if} {$hidessid}
1181
{$ifconfig} {$if} {$adhocmode}
1182
{$ifconfig} {$if} {$protmode}
1183
{$ifconfig} {$if} {$pureg}
1184
{$ifconfig} {$if} {$apbridge}
1185
{$ifconfig} {$if} {$wme}
1186
{$ifconfig} {$if} {$wepset}
1187
{$ifconfig} {$if} {$txpower}
1188
{$ifconfig} {$if} {$hostapmode}
1189
{$ifconfig} {$if} up
1190

    
1191
EOD;
1192

    
1193
	/* write out above <<EOD stuff */
1194
	fwrite($fd_set, $settings);
1195

    
1196
	if (isset($wlcfg['wpa']['enable'])) {
1197
		if ($wlcfg['mode'] == "bss")
1198
			fwrite($fd_set, "{$wpa_supplicant} -B -i {$if} -c {$g['varetc_path']}/wpa_supplicant_{$if}.conf\n");
1199
		if ($wlcfg['mode'] == "hostap")
1200
			fwrite($fd_set, "{$hostapd} -B {$g['varetc_path']}/hostapd_{$if}.conf\n");
1201
	}
1202

    
1203
	fclose($fd_set);
1204

    
1205
	conf_mount_ro();
1206

    
1207
	/* execute commands now in shell */
1208
	mwexec("/bin/sh /tmp/{$if}_setup.sh");
1209
	sleep(2);
1210
	// XXX: ermal - This seems like not needed!? 
1211
	//mwexec("/bin/sh /tmp/{$if}_setup.sh");
1212

    
1213
	return 0;
1214

    
1215
}
1216

    
1217
function kill_hostapd($interface) {
1218
	return "/bin/ps awwuxx | grep hostapd | grep $interface | awk '{ print \$2 }' | xargs kill\n";
1219
}
1220

    
1221
function kill_wpasupplicant($interface) {
1222
	return "/bin/ps awwuxx | grep wpa_supplicant | grep $interface | awk '{ print \$2 }' | xargs kill\n";
1223
}
1224

    
1225
function find_dhclient_process($interface) {
1226
	$realinterface = get_real_interface($interface);
1227
	if($realinterface)
1228
		$pid = `ps awwwux | grep dhclient | grep -v grep | grep {$realinterface} | awk '{ print \$2 }'`;
1229
	return $pid;
1230
}
1231

    
1232
function interface_configure($interface = "wan") {
1233
	global $config, $g;
1234
	global $interface_sn_arr_cache, $interface_ip_arr_cache;
1235

    
1236
	$wancfg = $config['interfaces'][$interface];
1237

    
1238
	$realif = get_real_interface($interface);
1239

    
1240
	if(!$g['booting']) {
1241
		/* remove all addresses first */
1242
		while (mwexec("/sbin/ifconfig " . escapeshellarg($realif) . " -alias", true) == 0);
1243
		interface_bring_down($interface);
1244
		mwexec("/sbin/ifconfig " . escapeshellarg($wancfg['if']) . " down");
1245
	}
1246
	/* wireless configuration? */
1247
	if (is_array($wancfg['wireless']))
1248
		interface_wireless_configure($realif, $wancfg['wireless']);
1249

    
1250
	if ($wancfg['spoofmac']) {
1251
		mwexec("/sbin/ifconfig " . escapeshellarg($wancfg['if']) .
1252
			" link " . escapeshellarg($wancfg['spoofmac']));
1253
	}  else {
1254
		$mac = get_interface_mac_address($wancfg['if']);
1255
		if($mac == "ff:ff:ff:ff:ff:ff") {
1256
			/*   this is not a valid mac address.  generate a
1257
			 *   temporary mac address so the machine can get online.
1258
			 */
1259
			echo "Generating new MAC address.";
1260
			$random_mac = generate_random_mac_address();
1261
			mwexec("/sbin/ifconfig " . escapeshellarg($wancfg['if']) .
1262
				" link " . escapeshellarg($random_mac));
1263
			$wancfg['spoofmac'] = $random_mac;
1264
			write_config();
1265
			file_notice("MAC Address altered", "The INVALID MAC address (ff:ff:ff:ff:ff:ff) on interface {$realif} has been automatically replaced with {$random_mac}", "Interfaces");
1266
		}
1267
	}
1268

    
1269
	/* media */
1270
	if ($wancfg['media'] || $wancfg['mediaopt']) {
1271
		$cmd = "/sbin/ifconfig " . escapeshellarg($wancfg['if']);
1272
		if ($wancfg['media'])
1273
			$cmd .= " media " . escapeshellarg($wancfg['media']);
1274
		if ($wancfg['mediaopt'])
1275
			$cmd .= " mediaopt " . escapeshellarg($wancfg['mediaopt']);
1276
		mwexec($cmd);
1277
	}
1278

    
1279
	/* invalidate interface/ip/sn cache */
1280
	get_interface_arr(true);
1281
	unset($interface_ip_arr_cache[$realif]);
1282
	unset($interface_sn_arr_cache[$realif]);
1283

    
1284
	switch ($wancfg['ipaddr']) {
1285

    
1286
		case 'carpdev-dhcp':
1287
			interface_carpdev_dhcp_configure($interface);
1288
			break;
1289
		case 'dhcp':
1290
			interface_dhcp_configure($interface);
1291
			break;
1292

    
1293
		case 'pppoe':
1294
			interface_pppoe_configure($interface);
1295
			break;
1296

    
1297
		case 'pptp':
1298
			interface_pptp_configure($interface);
1299
			break;
1300

    
1301
		default:
1302
			if ($wancfg['ipaddr'] <> "" && $wancfg['subnet'] <> "") {
1303
				if (isset($wancfg['ispointtopoint']) && $wancfg['pointtopoint']) {
1304
					mwexec("/sbin/ifconfig " . escapeshellarg($realif) . " " .
1305
						escapeshellarg($wancfg['ipaddr'] . "/" . $wancfg['subnet']) .
1306
						" " . escapeshellarg($wancfg['pointtopoint']) . " up");
1307
				} else {
1308
					if($wancfg['ipaddr'] && $wancfg['subnet'])
1309
						mwexec("/sbin/ifconfig " . escapeshellarg($realif) .
1310
							" " . escapeshellarg($wancfg['ipaddr'] . "/" . 
1311
							$wancfg['subnet']));
1312
				}
1313
			}
1314

    
1315
			if (is_ipaddr($wancfg['gateway']))
1316
				file_put_contents("/tmp/{$realif}_router", $wancfg['gateway']);
1317
	}
1318
	if($wancfg['if'])
1319
		interfaces_bring_up($wancfg['if']);
1320
	else 
1321
		log_error("Could not bring wancfg['if'] up -- variable not defined in interface_configure()");
1322
	
1323
	if (!$g['booting']) {
1324
		if (link_interface_to_gre($interface)) {
1325
			foreach ($config['gres']['gre'] as $gre)
1326
				if ($gre['if'] == $interface)
1327
					interface_gre_configure($gre);
1328
		}
1329
		if (link_interface_to_gif($interface)) {
1330
                	foreach ($config['gifs']['gif'] as $gif)
1331
				if ($gif['if'] == $interface)
1332
                        		interface_gre_configure($gif);
1333
        	}
1334
		if (link_interface_to_bridge($interface)) {
1335
			foreach ($config['bridges']['bridged'] as $bridge)
1336
				if (stristr($bridge['members'], "{$interface}"))
1337
					interface_bridge_configure($bridge);
1338
		}
1339

    
1340
		/* XXX: Shouldn't the caller do this?! */
1341
		/* XXX */
1342
		if ($interface = "lan")
1343
			/* make new hosts file */
1344
                	system_hosts_generate();
1345

    
1346
		/* reconfigure static routes (kernel may have deleted them) */
1347
		system_routing_configure();
1348

    
1349
		/* set the reload filter dity flag */
1350
		filter_configure();
1351

    
1352
		/* reload ipsec tunnels */
1353
		vpn_ipsec_configure();
1354

    
1355
		/* update dyndns */
1356
		services_dyndns_configure();
1357

    
1358
		/* force DNS update */
1359
		services_dnsupdate_process();
1360

    
1361
		/* restart dnsmasq */
1362
		services_dnsmasq_configure();
1363

    
1364
		/* reload captive portal */
1365
		captiveportal_configure();
1366
	}
1367

    
1368

    
1369
	unmute_kernel_msgs();
1370

    
1371
	return 0;
1372
}
1373

    
1374
function interface_carpdev_dhcp_configure($interface = "wan") {
1375
	global $config, $g;
1376

    
1377
	$wancfg = $config['interfaces'][$interface];
1378
	$wanif = $wancfg['if'];
1379
	/* bring wan interface up before starting dhclient */
1380
	if($wanif)
1381
		interfaces_bring_up($wanif);
1382
	else 
1383
		log_error("Could not bring wanif up in terface_carpdev_dhcp_configure()");
1384

    
1385
	return 0;
1386
}
1387

    
1388
function interface_dhcp_configure($interface = "wan") {
1389
	global $config, $g;
1390

    
1391
	$wancfg = $config['interfaces'][$interface];
1392

    
1393
	/* generate dhclient_wan.conf */
1394
	$fd = fopen("{$g['varetc_path']}/dhclient_{$interface}.conf", "w");
1395
	if (!$fd) {
1396
		printf("Error: cannot open dhclient_{$interface}.conf in interfaces_wan_dhcp_configure() for writing.\n");
1397
		return 1;
1398
	}
1399

    
1400
	if ($wancfg['dhcphostname']) {
1401
		$dhclientconf_hostname = "send dhcp-client-identifier \"{$wancfg['dhcphostname']}\";\n";
1402
		$dhclientconf_hostname .= "\tsend host-name \"{$wancfg['dhcphostname']}\";\n";
1403
	} else {
1404
		$dhclientconf_hostname = "";
1405
	}
1406

    
1407
	$wanif = get_real_interface($interface);
1408

    
1409
 	$dhclientconf = "";
1410
	
1411
	$dhclientconf .= <<<EOD
1412
interface "{$wanif}" {
1413
timeout 60;
1414
retry 1;
1415
select-timeout 0;
1416
initial-interval 1;
1417
	{$dhclientconf_hostname}
1418
	script "/sbin/dhclient-script";
1419
}
1420

    
1421
EOD;
1422

    
1423
if(is_ipaddr($wancfg['alias-address'])) {
1424
	$subnetmask = gen_subnet_mask($wancfg['alias-subnet']);
1425
	$dhclientconf .= <<<EOD
1426
alias {
1427
	interface  "{$wanif}";
1428
	fixed-address {$wancfg['alias-address']};
1429
	option subnet-mask {$subnetmask};
1430
}
1431

    
1432
EOD;
1433
}
1434
	fwrite($fd, $dhclientconf);
1435
	fclose($fd);
1436

    
1437
	$relwanif = $wancfg['if'];
1438

    
1439
	/* bring wan interface up before starting dhclient */
1440
	if($realwanif)
1441
		interfaces_bring_up($realwanif);
1442
	else 
1443
		log_error("Could not bring realwanif up in interface_dhcp_configure()");
1444

    
1445
	/* fire up dhclient */
1446
	mwexec("/sbin/dhclient -c {$g['varetc_path']}/dhclient_{$interface}.conf {$wanif} >/tmp/{$wanif}_output >/tmp/{$wanif}_error_output");
1447

    
1448
	$fout = fopen("/tmp/ifconfig_{$wanif}","w");
1449
	fwrite($fout, "/sbin/dhclient -c {$g['varetc_path']}/dhclient_{$interface}.conf {$wanif}");
1450
	fclose($fout);
1451

    
1452
	return 0;
1453
}
1454

    
1455
function interface_pppoe_configure($interface = "wan") 
1456
{
1457
	global $config, $g;
1458

    
1459
	$wancfg = $config['interfaces'][$interface];
1460

    
1461
	/* generate mpd.conf */
1462
	$fd = fopen("{$g['varetc_path']}/mpd_{$interface}.conf", "w");
1463
	if (!$fd) {
1464
		printf("Error: cannot open mpd_{$interface}.conf in interface_pppoe_configure().\n");
1465
		return 1;
1466
	}
1467

    
1468
	$idle = 0;
1469

    
1470
	if (isset($wancfg['ondemand'])) {
1471
		$ondemand = "enable";
1472
		if ($wancfg['timeout'])
1473
			$idle = $wancfg['timeout'];
1474
	} else {
1475
		$ondemand = "disable";
1476
	}
1477

    
1478
	$mpdconf = <<<EOD
1479
startup:
1480
pppoeclient:
1481

    
1482
EOD;
1483

    
1484
	if ($interface == "wan")
1485
		$realif = "pppoe0";
1486
	else {
1487
		// Here code assumes only that strings of form "opt#" will be passed.
1488
		$realif = "pppoe" . substr($interface, 3); 
1489
	}
1490
	
1491
	$mpdconf .= <<<EOD
1492
	new -i {$realif} pppoeclient pppoeclient
1493

    
1494
EOD;
1495
	if ($interface == "wan")
1496
		$mpdconf .= <<<EOD
1497
	set iface route default
1498

    
1499
EOD;
1500
	
1501
	$mpdconf .= <<<EOD
1502
	set iface {$ondemand} on-demand
1503
	set iface idle {$idle}
1504
	set iface enable tcpmssfix
1505
	set iface up-script /usr/local/sbin/ppp-linkup
1506
	set iface down-script /usr/local/sbin/ppp-linkdown
1507

    
1508
EOD;
1509

    
1510
	if (isset($wancfg['ondemand'])) {
1511
		if (isset($wancfg['local-ip']) && isset($wancfg['remote-ip'])) {
1512
			$mpdconf .= <<<EOD
1513
	set iface addrs {$wancfg['local-ip']} {$wancfg['remote-ip']}
1514

    
1515
EOD;
1516
		} else {
1517
			$mpdconf .= <<<EOD
1518
	set iface addrs 192.0.2.112 192.0.2.113
1519

    
1520
EOD;
1521
		}
1522
	}
1523

    
1524
	$mpdconf .= <<<EOD
1525
	set bundle disable multilink
1526
	set auth authname "{$wancfg['pppoe_username']}"
1527
	set auth password "{$wancfg['pppoe_password']}"
1528
	set link keep-alive 10 60
1529
	set link max-redial 0
1530
	set link no acfcomp protocomp
1531
	set link disable pap chap
1532
	set link accept chap
1533
	
1534
EOD;
1535
	if (empty($wancfg['mtu']))
1536
		$mpdmtu = "1492";
1537
	else 
1538
		$mpdmtu = "{$wancfg['mtu']}";
1539

    
1540
	$mpdconf .= <<<EOD
1541
	set link mtu {$mpdmtu}
1542
	set ipcp yes vjcomp
1543
	set ipcp ranges 0.0.0.0/0 0.0.0.0/0
1544

    
1545
EOD;
1546

    
1547
	if (isset($config['system']['dnsallowoverride'])) {
1548
		$mpdconf .= <<<EOD
1549
	set ipcp enable req-pri-dns
1550

    
1551
EOD;
1552
	}
1553

    
1554
	if (!isset($wancfg['dnsnosec']) && isset($config['system']['dnsallowoverride'])) {
1555
			$mpdconf .= <<<EOD
1556
	set ipcp enable req-sec-dns
1557

    
1558
EOD;
1559
	}
1560
	
1561
	$mpdconf .= <<<EOD
1562
	open
1563

    
1564
EOD;
1565

    
1566
	fwrite($fd, $mpdconf);
1567
	fclose($fd);
1568

    
1569
	/* generate mpd.links */
1570
	$fd = fopen("{$g['varetc_path']}/mpd_{$interface}.links", "w");
1571
	if (!$fd) {
1572
		printf("Error: cannot open mpd_{$interface}.links in interface_pppoe_configure().\n");
1573
		return 1;
1574
	}
1575

    
1576
	$mpdconf = <<<EOD
1577
pppoeclient:
1578
	set link type pppoe
1579
	set pppoe iface {$wancfg['if']}
1580
	set pppoe service "{$wancfg['provider']}"
1581
	set pppoe enable originate
1582
	set pppoe disable incoming
1583

    
1584
EOD;
1585

    
1586
	fwrite($fd, $mpdconf);
1587
	fclose($fd);
1588

    
1589
	if(file_exists("{$g['varrun_path']}/pppoe_{$interface}.pid") and $g['booting']) {
1590
		/* if we are booting and mpd has already been started then don't start again. */
1591
	} else {
1592
		/* if mpd is active, lets take it down */
1593
		if(file_exists("{$g['varrun_path']}/pppoe_{$interface}.pid")) {
1594
			killbypid("{$g['varrun_path']}/pppoe_{$interface}.pid");
1595
			sleep(3);
1596
		}
1597

    
1598
		/* Bring the parent interface up */
1599
		if($wancfg['if'])
1600
			interfaces_bring_up($wancfg['if']);
1601
		else 
1602
			log_error("Could not bring wancfg['if'] up in interface_pppoe_configure()");
1603

    
1604
		/* fire up mpd */
1605
		mwexec("/usr/local/sbin/mpd4 -b -d {$g['varetc_path']} -f mpd_{$interface}.conf -l mpd_{$interface}.links -p {$g['varrun_path']}/pppoe_{$interface}.pid pppoeclient");
1606
	}
1607

    
1608
	/* sleep until wan is up - or 30 seconds, whichever comes first */
1609
	for ($count = 0; $count < 30; $count++) {
1610
		if(file_exists("{$g['tmp_path']}/{$interface}up")) {
1611
			break;
1612
		}
1613
		sleep(1);
1614
	}
1615

    
1616
	unlink_if_exists("{$g['tmp_path']}/{$interface}up");
1617

    
1618
	return 0;
1619
}
1620

    
1621
function interface_pptp_configure($interface) {
1622
	global $config, $g;
1623

    
1624
	$wancfg = $config['interfaces'][$interface];
1625

    
1626
	/* generate mpd.conf */
1627
	$fd = fopen("{$g['varetc_path']}/mpd_{$interface}.conf", "w");
1628
	if (!$fd) {
1629
		printf("Error: cannot open mpd_{$interface}.conf in interface_pptp_configure().\n");
1630
		return 1;
1631
	}
1632

    
1633
	$idle = 0;
1634

    
1635
	if (isset($wancfg['ondemand'])) {
1636
		$ondemand = "enable";
1637
		if ($wancfg['timeout'])
1638
			$idle = $wancfg['timeout'];
1639
	} else {
1640
		$ondemand = "disable";
1641
	}
1642

    
1643
	$mpdconf = <<<EOD
1644
startup:
1645
pptp:
1646

    
1647
EOD;
1648

    
1649
        if ($interface == "wan")
1650
                $realif = "pptp0";
1651
        else {
1652
                // Here code assumes only that strings of form "opt#" will be passed.
1653
                $realif = "pptp" . substr($interface, 3);
1654
	}
1655

    
1656
        $mpdconf .= <<<EOD
1657
        new -i {$realif} pptp pptp 
1658

    
1659
EOD;
1660
        if ($interface == "wan")
1661
                $mpdconf .= <<<EOD
1662
        set iface route default
1663

    
1664
EOD;
1665

    
1666
        $mpdconf .= <<<EOD
1667
	set iface {$ondemand} on-demand
1668
	set iface idle {$idle}
1669
	set iface up-script /usr/local/sbin/ppp-linkup
1670
	set iface down-script /usr/local/sbin/ppp-linkdown
1671

    
1672
EOD;
1673

    
1674
	if (isset($wanfg['ondemand'])) {
1675
		$mpdconf .= <<<EOD
1676
	set iface addrs 10.0.0.1 10.0.0.2
1677

    
1678
EOD;
1679
	}
1680

    
1681
	$mpdconf .= <<<EOD
1682
	set bundle disable multilink
1683
	set bundle authname "{$wancfg['pptp_username']}"
1684
	set bundle password "{$wancfg['pptp_password']}"
1685
	set bundle no noretry
1686
	set link keep-alive 10 60
1687
	set link max-redial 0
1688
	set link no acfcomp protocomp
1689
	set link disable pap chap
1690
	set link accept chap
1691
	set ipcp no vjcomp
1692
	set ipcp ranges 0.0.0.0/0 0.0.0.0/0
1693

    
1694
EOD;
1695
	if (isset($config['system']['dnsallowoverride'])) {
1696
		$mpdconf .= <<<EOD
1697
	set ipcp enable req-pri-dns
1698

    
1699
EOD;
1700
	}
1701

    
1702
	$mpdconf .= <<<EOD
1703
	open
1704

    
1705
EOD;
1706

    
1707
	fwrite($fd, $mpdconf);
1708
	fclose($fd);
1709

    
1710
	/* generate mpd.links */
1711
	$fd = fopen("{$g['varetc_path']}/mpd_{$interface}.links", "w");
1712
	if (!$fd) {
1713
		printf("Error: cannot open mpd_{$interface}.links in interface_pptp_configure().\n");
1714
		return 1;
1715
	}
1716

    
1717
	$mpdconf = <<<EOD
1718
pptp:
1719
	set link type pptp
1720
	set pptp enable originate outcall
1721
	set pptp disable windowing
1722
	set pptp self {$wancfg['local']}
1723
	set pptp peer {$wancfg['remote']}
1724

    
1725
EOD;
1726

    
1727
	fwrite($fd, $mpdconf);
1728
	fclose($fd);
1729

    
1730
	/* configure interface */
1731
	if($wancfg['if'])
1732
		mwexec("/sbin/ifconfig " . escapeshellarg($wancfg['if']) . " " .
1733
			escapeshellarg($wancfg['local'] . "/" . $wancfg['subnet']) . " up");
1734
	else 
1735
		log_error("Could not bring interface wancfg['if'] up in interface_pptp_configure()");
1736
	/* fire up mpd */
1737
	mwexec("/usr/local/sbin/mpd4 -b -d {$g['varetc_path']} -f mpd_{$interface}.conf -l mpd_{$interface}.links -p {$g['varrun_path']}/pptp_{$interface}.pid pptp");
1738

    
1739
	return 0;
1740
}
1741
 
1742
/* XXX: stub for code that references the old functions(mostly packages) */
1743
function get_real_wan_interface($interface = "wan") {
1744
	return get_real_interface($interface);
1745
}
1746
function get_current_wan_address($interface = "wan") {
1747
	return get_interface_ip($interface);
1748
}
1749

    
1750
function get_real_interface($interface = "wan") {
1751
    global $config;
1752

    
1753
	$wanif = $interface;
1754

    
1755
	switch ($interface) {
1756
	case "pptp":
1757
		$wanif = "pptp";
1758
		break;
1759
	case "pppoe":
1760
		$wanif = "pppoe";
1761
		break;
1762
	case "openvpn":
1763
		$wanif = "openvpn";
1764
		break;
1765
	case "enc0":
1766
		$wanif = "enc0";
1767
		break;
1768
	/* XXX: dial in support?!
1769
	case "ppp":
1770
		$wanif = "ppp";
1771
		break;
1772
	*/
1773
	default:
1774
		$iflist = get_configured_interface_with_descr(false, true);
1775

    
1776
		foreach ($iflist as $if => $ifdesc) {
1777
			if ($interface == $if || $interface == $ifdesc) {
1778

    
1779
			$cfg = $config['interfaces'][$if];
1780

    
1781
			switch ($cfg['ipaddr']) {
1782
			case "carpdev-dhcp":
1783
				$viparr = &$config['virtualip']['vip'];
1784
				$counter = 0;
1785
				if(is_array($viparr))
1786
				foreach ($viparr as $vip) {
1787
					if ($vip['mode'] == "carpdev-dhcp") {
1788
						if($vip['interface'] == $if) {
1789
							$wanif =  "carp{$counter}";
1790
							break;
1791
						}
1792
						$counter++;
1793
					} else if ($vip['mode'] = "carp") 
1794
						$counter++;
1795
				}
1796
				break;
1797
			case "pppoe": 
1798
				if ($if == "wan")
1799
					$wanif = "pppoe0";
1800
				else
1801
					$wanif = "pppoe" . substr($if,3);
1802
				break;
1803
			case "pptp": 
1804
				if ($if == "wan")
1805
					$wanif = "pptp0";
1806
				else
1807
					$wanif = "pptp" . substr($if, 3);
1808
				break;
1809
			default:
1810
				$wanif = $cfg['if'];
1811
				break;
1812
			}
1813
			
1814
			break;
1815
			}
1816
		}
1817
		break;
1818
	}
1819

    
1820
    return $wanif;
1821
}
1822

    
1823
function get_interface_ip($interface = "wan") {
1824
	$realif = get_real_interface($interface);
1825
	/* Do we really come here for these interfaces ?! */
1826
	if (in_array($realif, array("pptp", "pppoe", "openvpn", "enc0" /* , "ppp" */)))
1827
			return "";
1828

    
1829
	$curip = find_interface_ip($realif);
1830
	if ($curip && is_ipaddr($curip) && ($curip != "0.0.0.0"))
1831
		return $curip;
1832

    
1833
	return null;
1834
}
1835

    
1836
function get_interface_subnet($interface = "wan") {
1837
	$realif = get_real_interface($interface);
1838
	/* Do we really come here for these interfaces ?! */
1839
	if (in_array($realif, array("pptp", "pppoe", "openvpn", "enc0" /* , "ppp" */)))
1840
		return "";
1841

    
1842
	$cursn = find_interface_subnet($realif);
1843
	if (!empty($cursn))
1844
		return $cursn;
1845

    
1846
	return null;
1847
}
1848

    
1849
/****f* interfaces/is_altq_capable
1850
 * NAME
1851
 *   is_altq_capable - Test if interface is capable of using ALTQ
1852
 * INPUTS
1853
 *   $int            - string containing interface name
1854
 * RESULT
1855
 *   boolean         - true or false
1856
 ******/
1857

    
1858
function is_altq_capable($int) {
1859
        /* Per:
1860
         * http://www.freebsd.org/cgi/man.cgi?query=altq&manpath=FreeBSD+6.0-current&format=html
1861
         * Only the following drivers have ALTQ support
1862
         */
1863
        $capable = array("an", "ath", "awi", "bfe", "bge", "dc", "de", "ed",
1864
			"em", "fxp", "hme", "le", "nve", "re", "rl", "ndis", "sf", "sis", "sk",
1865
			"tun", "vr", "wi", "xl", "vlan", "ste", "aue", "bce", "ep", "gem", "ipw", 
1866
			"iwi", "msk", "mxge", "my", "nfe", "npe", "ral", "rum", "stge", "udav", 
1867
			"ural", "pppoe", "pptp", "ng", "ppp");
1868

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

    
1871
        if (in_array($int_family[0], $capable))
1872
                return true;
1873
        else
1874
                return false;
1875
}
1876

    
1877
function get_wireless_modes($interface) {
1878
	/* return wireless modes and channels */
1879
	$wireless_modes = array();
1880

    
1881
	if(is_interface_wireless($interface)) {
1882
		$wi = 1;
1883
		$ifconfig = "/sbin/ifconfig";
1884
		$awk = "/usr/bin/awk";
1885
		$chan_list = "$ifconfig $interface list chan";
1886
		$stack_list = "$awk -F\"Channel \" '{ gsub(/\\*/, \" \"); print \$2 \"\\\n\" \$3 }'";
1887
		$format_list = "$awk '{print \$5 \" \" \$6 \",\" \$1}'";
1888

    
1889
		$interface_channels = "";
1890
		exec("$chan_list | $stack_list | sort -u | $format_list 2>&1", $interface_channels);
1891
		$interface_channel_count = count($interface_channels);
1892

    
1893
		$c = 0;
1894
		while ($c < $interface_channel_count)
1895
		{
1896
			$channel_line = explode(",", $interface_channels["$c"]);
1897
			$wireless_mode = trim($channel_line[0]);
1898
			$wireless_channel = trim($channel_line[1]);
1899
			if(trim($wireless_mode) != "") {
1900
				/* if we only have 11g also set 11b channels */
1901
				if($wireless_mode == "11g") {
1902
					$wireless_modes["11b"] = array();
1903
				}
1904
				$wireless_modes["$wireless_mode"]["$c"] = $wireless_channel;
1905
			}
1906
			$c++;
1907
		}
1908
	}
1909
	return($wireless_modes);
1910
}
1911

    
1912
function get_interface_mac($interface) {
1913
	/* build interface list with netstat */
1914
	$linkinfo = "";
1915
	exec("/usr/bin/netstat -I $interface -nW -f link", $linkinfo);
1916
	array_shift($linkinfo);
1917
	$alink = preg_split("/\s+/", $linkinfo[0]);
1918
	$mac = chop($alink[3]);
1919
	return $mac;
1920
}
1921

    
1922
function setup_pppoe_reset_file($interface, $status) {
1923
	define("CRON_PPPOE_CMD_FILE", "/conf/pppoe{$interface}restart");
1924
	define("CRON_PPPOE_CMD", "#!/bin/sh\necho '<?php require(\"interfaces.inc\"); interface_reconfigure(\"$interface\"); services_dyndns_reset(\"$interface\"); filter_configure_sync(); ?>' | /usr/local/bin/php -q");
1925
	if($status == true) {
1926
		if(!file_exists(CRON_PPPOE_CMD_FILE)) {
1927
			file_put_contents(CRON_PPPOE_CMD_FILE, CRON_PPPOE_CMD);
1928
			chmod(CRON_PPPOE_CMD_FILE, 0700);
1929
		}	
1930
	} else {
1931
		unlink_if_exists(CRON_PPPOE_CMD_FILE);
1932
	}
1933
}
1934

    
1935
?>
(15-15/37)