Project

General

Profile

Download (57.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
        global $config, $g;
74

    
75
	if(empty($if)) {
76
		log_error("interface_vlan_confgure called with if undefined.");
77
		return;
78
	}
79

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

    
86
        if ($g['booting'] || !(empty($vlanif))) {
87
		/* before destroying, see if CARP is in use
88
		  If an interface containing an active CARP IP is destroyed,
89
		  the CARP interface will hang in INIT and must be destroyed
90
		  itself before it will function again (which causes a panic).
91
		  Trying to configure a CARP interface stuck in INIT will
92
		  cause a panic as well.  -cmb
93
		*/
94
		$carpcount = find_number_of_needed_carp_interfaces();
95
		/* will continue to destroy VLANs where CARP is not in use
96
		  to retain previous behavior and avoid regressions */
97
		if($carpcount < 1)
98
			mwexec("/sbin/ifconfig {$vlanif} destroy");
99
		mwexec("/sbin/ifconfig {$vlanif} create");
100
        } else 
101
		$vlanif = exec("/sbin/ifconfig vlan create");
102
	
103
        mwexec("/sbin/ifconfig {$vlanif} vlan " .
104
                escapeshellarg($tag) . " vlandev " .
105
                escapeshellarg($if));
106

    
107
	interfaces_bring_up($vlanif);
108

    
109
        /* invalidate interface cache */
110
        get_interface_arr(true);
111

    
112
        /*   all vlans need to spoof their parent mac address, too.  see
113
         *   ticket #1514: http://cvstrac.pfsense.com/tktview?tn=1514,33
114
         */
115
        foreach($config['interfaces'] as $interfaces) {
116
                if($interfaces['if'] == $if && $interfaces['spoofmac']) {
117
                        mwexec("/sbin/ifconfig " . escapeshellarg($if) .
118
                                " link " . escapeshellarg($interfaces['spoofmac']));
119
                }
120
        }
121

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

    
125
        return $vlanif;
126
}
127

    
128
function interfaces_bridge_configure() {
129
        global $config;
130

    
131
        $i = 0;
132
        if (is_array($config['bridges']['bridged']) && count($config['bridges']['bridged'])) {
133
                foreach ($config['bridges']['bridged'] as $bridge) {
134
                        if(empty($bridge['bridgeif']))
135
                                $bridge['bridgeif'] = "bridge{$i}";
136
                        /* XXX: Maybe we should report any errors?! */
137
                        interface_bridge_configure($bridge);
138
                        $i++;
139
                }
140
        }
141
}
142

    
143
function interface_bridge_configure(&$bridge) {
144
	global $config, $g;
145

    
146
	if (!is_array($bridge))
147
	        return -1;
148

    
149
	if (empty($bridge['members'])) {
150
		log_error("No members found on {$bridge['bridgeif']}");
151
		return -1;
152
	}
153

    
154
	$members = explode(',', $bridge['members']);
155
	if (!count($members))
156
		return -1;
157
	
158
	$checklist = get_configured_interface_list();
159

    
160
	if ($g['booting'] || !empty($bridge['bridgeif'])) {
161
		mwexec("/sbin/ifconfig {$bridge['bridgeif']} destroy");
162
		mwexec("/sbin/ifconfig {$bridge['bridgeif']} create");
163
		$bridgeif = $bridge['bridgeif'];
164
	} else {
165
		$bridgeif = exec("/sbin/ifconfig bridge create");
166
	}
167

    
168
	/* Calculate smaller mtu and enforce it */
169
	$smallermtu = 0;
170
	foreach ($members as $member) {
171
		$realif = get_real_interface($member);
172
		$mtu = get_interface_mtu($realif);
173
		if ($smallermtu == 0 && !empty($mtu))
174
			$smallermtu = $mtu;
175
		else if (!empty($mtu) && $mtu < $smallermtu)
176
			$smallermtu = $mtu;
177
	}
178
	 
179
	/* Just in case anything is not working well */
180
	if ($smallermtu == 0)
181
		$smallermtu = 1500; 
182

    
183
	/* Add interfaces to bridge */
184
	foreach ($members as $member) {
185
		if (!array_key_exists($member, $checklist))
186
			continue;
187
		$realif = get_real_interface($member);
188
		$realif =  escapeshellarg($realif);
189
		/* make sure the parent interface is up */
190
		mwexec("/sbin/ifconfig {$realif} mtu {$smallermtu}");
191
		if(!$realif) 
192
			log_error("realif not defined in interfaces bridge - up");
193
		interfaces_bring_up($realif);
194
		mwexec("/sbin/ifconfig {$bridgeif} addm {$realif}");	
195
	}
196

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

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

    
297
	if($bridgeif)
298
		interfaces_bring_up($bridgeif);	
299
	else 
300
		log_error("bridgeif not defined -- could not bring interface up");
301

    
302
	return $bridgeif;
303
}
304

    
305
function interfaces_lagg_configure() 
306
{
307
        global $config;
308

    
309
        $i = 0;
310
        if (is_array($config['laggs']['lagg']) && count($config['laggs']['lagg'])) {
311
                foreach ($config['laggs']['lagg'] as $lagg) {
312
                        if(empty($lagg['laggif']))
313
                                $lagg['laggif'] = "lagg{$i}";
314
                        /* XXX: Maybe we should report any errors?! */
315
                        interface_lagg_configure($lagg);
316
                        $i++;
317
                }
318
        }
319
}
320

    
321
function interface_lagg_configure(&$lagg) {
322
        global $config, $g;
323

    
324
        if (!is_array($lagg))
325
		return -1;
326

    
327
	$members = explode(',', $lagg['members']);
328
	if (!count($members))
329
		return -1;
330
	
331
	$checklist = get_interface_list();
332

    
333
	if ($g['booting'] || !(empty($lagg['laggif']))) {
334
                mwexec("/sbin/ifconfig {$lagg['laggif']} destroy");
335
                mwexec("/sbin/ifconfig {$lagg['laggif']} create");
336
                $laggif = $lagg['laggif'];
337
        } else
338
                $laggif = exec("/sbin/ifconfig lagg create");
339

    
340
	/* Calculate smaller mtu and enforce it */
341
        $smallermtu = 0;
342
        foreach ($members as $member) {
343
                $realif = get_real_interface($member);
344
                $mtu = get_interface_mtu($realif);
345
		if ($smallermtu == 0 && !empty($mtu))
346
			$smallermtu = $mtu;
347
                else if (!empty($mtu) && $mtu < $smallermtu)
348
                        $smallermtu = $mtu;
349
        }
350

    
351
	/* Just in case anything is not working well */
352
        if ($smallermtu == 0)
353
                $smallermtu = 1500;
354

    
355
	foreach ($members as $member) {
356
		if (!array_key_exists($member, $checklist))
357
			continue;
358
                $realif = get_real_interface($member);
359
		/* make sure the parent interface is up */
360
		mwexec("/sbin/ifconfig {$realif} mtu {$smallermtu}");
361
		if($realif)
362
			interfaces_bring_up($realif);
363
		else 
364
			log_error("could not bring realif up -- foreach(memebers)");
365
		mwexec("/sbin/ifconfig {laggif} laggport {$realif}");
366
	}
367
	
368
	mwexec("/sbin/ifconfig {$laggif} {$lagg['proto']}");
369

    
370
	interfaces_bring_up($laggif);
371

    
372
	return $laggif;
373
}
374

    
375
function interfaces_gre_configure() {
376
        global $config;
377

    
378
        $i = 0;
379
        if (is_array($config['gres']['gre']) && count($config['gres']['gre'])) {
380
                foreach ($config['gres']['gre'] as $gre) {
381
                        if(empty($gre['greif']))
382
                                $gre['greif'] = "gre{$i}";
383
                        /* XXX: Maybe we should report any errors?! */
384
                        interface_gre_configure($gre);
385
                        $i++;
386
                }
387
        }
388
}
389

    
390
function interface_gre_configure(&$gre) {
391
        global $config, $g;
392

    
393
	if (!is_array($gre))
394
		return -1;
395

    
396
	$realif = get_real_interface($gre['if']);
397
	$realifip = get_interface_ip($gre['if']);
398

    
399
	/* make sure the parent interface is up */
400
	interfaces_bring_up($realif);
401

    
402
	if ($g['booting'] || !(empty($gre['greif']))) {
403
		mwexec("/sbin/ifconfig {$gre['greif']} destroy");
404
		mwexec("/sbin/ifconfig {$gre['greif']} create");
405
		$greif = $gre['greif'];
406
	} else {
407
		$greif = exec("/sbin/ifconfig gre create");
408
	}
409

    
410
	/* Do not change the order here for more see gre(4) NOTES section. */
411
	mwexec("/sbin/ifconfig {$greif} tunnel {$realifip} {$gre['remote-addr']}");
412
	mwexec("/sbin/ifconfig {$greif} {$gre['tunnel-local-addr']} {$gre['tunnel-remote-addr']} netmask " . gen_subnet_mask($gre['tunnel-remote-net']));
413
	if (isset($gre['link0']) && $gre['link0'])
414
		mwexec("/sbin/ifconfig {$greif} link0");
415
	if (isset($gre['link1']) && $gre['link1'])
416
		mwexec("/sbin/ifconfig {$greif} link1");
417
	if (isset($gre['link2']) && $gre['link2'])
418
		mwexec("/sbin/ifconfig {$greif} link2");
419

    
420
	if($greif)
421
		interfaces_bring_up($greif);
422
	else 
423
		log_error("Could not bring greif up -- variable not defined.");
424

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

    
428
	return $greif;
429
}
430

    
431
function interfaces_gif_configure() {
432
        global $config;
433

    
434
        $i = 0;
435
        if (is_array($config['gifs']['gif']) && count($config['gifs']['gif'])) {
436
                foreach ($config['gifs']['gif'] as $gif) {
437
                        if(empty($gif['gifif']))
438
                                $gre['gifif'] = "gif{$i}";
439
                        /* XXX: Maybe we should report any errors?! */
440
                        interface_gif_configure($gif);
441
                        $i++;
442
                }
443
        }
444
}
445

    
446
function interface_gif_configure(&$gif) {
447
        global $config, $g;
448

    
449
        if (!is_array($gif))
450
                return -1;
451

    
452
        $realif = get_real_interface($gif['if']);
453
        $realifip = get_interface_ip($gif['if']);
454

    
455
        /* make sure the parent interface is up */
456
		if($realif)
457
			interfaces_bring_up($realif);
458
		else 
459
			log_error("could not bring realif up -- variable not defined -- interface_gif_configure()");
460

    
461
        if ($g['booting'] || !(empty($gif['gifif']))) {
462
                mwexec("/sbin/ifconfig {$gif['gifif']} destroy");
463
                mwexec("/sbin/ifconfig {$gif['gifif']} create");
464
                $gifif = $gif['gifif'];
465
        } else
466
                $gifif = exec("/sbin/ifconfig gif create");
467

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

    
482
        return $gifif;
483
}
484

    
485
function interfaces_configure() {
486
	global $config, $g;
487

    
488
	/* set up LAGG virtual interfaces */
489
	interfaces_lagg_configure();
490

    
491
	/* set up VLAN virtual interfaces */
492
	interfaces_vlan_configure();
493

    
494
	/* Set up PPP interfaces */
495
	interfaces_ppp_configure();
496

    
497
	$iflist = get_configured_interface_with_descr();
498
	$delayed_list = array();
499
	$bridge_list = array();
500
	
501
	foreach($iflist as $if => $ifname) {
502
		$realif = $config['interfaces'][$if]['if'];
503
		if(is_array($realif['pppoe']) && isset($realif['pppoe']['pppoe-reset-type']))
504
			setup_pppoe_reset_file($if, true);
505
		else 
506
			setup_pppoe_reset_file($if, false);
507
		if (strstr($realif, "bridge")) 
508
			$bridge_list[$if] = $ifname;
509
		else if (strstr($realif, "gre"))
510
			$delayed_list[$if] = $ifname;
511
		else if (strstr($realif, "gif"))
512
			$delayed_list[$if] = $ifname;
513
		else {
514
			if ($g['booting'])
515
				echo "Configuring {$ifname} interface...";
516
        	if($g['debug'])
517
				log_error("Configuring {$ifname}");
518
			interface_configure($if);
519
			if ($g['booting']) 
520
				echo "done.\n";
521
		}
522
	}
523

    
524
	/* set up GRE virtual interfaces */
525
	interfaces_gre_configure();
526

    
527
	/* set up GIF virtual interfaces */
528
	interfaces_gif_configure();
529
	
530
	foreach ($delayed_list as $if => $ifname) {
531
		if ($g['booting'])
532
			echo "Configuring {$ifname} interface...";
533
        if($g['debug'])
534
        	log_error("Configuring {$ifname}");
535

    
536
		interface_configure($if);
537

    
538
		if ($g['booting'])
539
			echo "done.\n";
540
	}
541

    
542
	/* set up BRIDGe virtual interfaces */
543
	interfaces_bridge_configure();
544

    
545
	foreach ($bridge_list as $if => $ifname) {
546
		if ($g['booting'])
547
			echo "Configuring {$ifname} interface...";
548
		if($g['debug'])
549
			log_error("Configuring {$ifname}");
550

    
551
		interface_configure($if);
552

    
553
		if ($g['booting'])
554
			echo "done.\n";
555
	}
556

    
557
	/* bring up carp interfaces */
558
	interfaces_carp_configure();
559

    
560
	/* bring ip IP aliases */
561
	interfaces_ipalias_configure();
562

    
563
	if (!$g['booting']) {
564
		/* reconfigure static routes (kernel may have deleted them) */
565
		system_routing_configure();
566

    
567
		/* reload IPsec tunnels */
568
		vpn_ipsec_configure();
569

    
570
		/* reload dhcpd (interface enabled/disabled status may have changed) */
571
		services_dhcpd_configure();
572

    
573
		/* restart dnsmasq */
574
		services_dnsmasq_configure();
575

    
576
		/* reload captive portal */
577
		captiveportal_configure();
578

    
579
		/* set the reload filter dity flag */
580
		filter_configure();
581
	}
582

    
583
	return 0;
584
}
585

    
586
function interface_reconfigure($interface = "wan") {
587
	interface_bring_down($interface);
588
	sleep(1);
589
	interface_configure($interface);
590
}
591

    
592
function interface_bring_down($interface = "wan", $destroy = false) {
593
	global $config, $g;
594

    
595
	if (!isset($config['interfaces'][$interface]))
596
		return; 
597

    
598
	$ifcfg = $config['interfaces'][$interface];
599

    
600
	$realif = get_real_interface($interface);
601

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

    
604
        /* remove interface up file if it exists */
605
        unlink_if_exists("{$g['tmp_path']}/{$realif}up");
606
        unlink_if_exists("{$g['vardb_path']}/{$interface}ip");
607
        //unlink_if_exists("{$g['varetc_path']}/nameservers.conf");
608

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

    
640
	if ($destroy == true) {
641
		if (preg_match("/^tun|^ppp|^ovpn|^gif|^gre|^lagg|^bridge|^vlan/i", $realif))
642
                	mwexec("/sbin/ifconfig {$realif} destroy");
643
	}
644
	
645
	unlink_if_exists("/tmp/{$realif}_router");
646
	return;
647
}
648

    
649
function interfaces_ppp_configure() {
650
        global $config;
651

    
652
        $i = 0;
653
        if (is_array($config['ppps']['ppp']) && count($config['ppps']['ppp'])) {
654
                foreach ($config['ppps']['ppp'] as $ppp) {
655
                        if(empty($ppp['pppif']))
656
                                $ppp['pppif'] = "ppp{$i}";
657
                        /* XXX: Maybe we should report any errors?! */
658
                        interface_ppp_configure($ppp);
659
                        $i++;
660
                }
661
        }
662
}
663

    
664
function interface_ppp_configure($ifcfg) {
665
	global $config, $g;
666
	
667
	/* Remove  the /dev/ from the device name. */
668
	$dev = substr($ifcfg['port'], 5);
669

    
670
	$realif  = $ifcfg['pppif'];
671
	if ($realif <> "") {
672
		$i = 0;
673
		while ($realif != "ppp{$i}")
674
			$i++;
675
		if(file_exists("/var/run/ppp{$i}.pid")) {
676
			$pid = trim(file_get_contents("/var/run/ppp{$i}.pid"));
677
			mwexec("kill {$pid}");
678
		}
679
	}
680
	
681
	if ($g['booting'] || $realif <> "") {
682
                mwexec("/sbin/ifconfig {$realif} destroy");
683
                mwexec("/sbin/ifconfig {$realif} create");
684
        } else
685
                $realif = exec("/sbin/ifconfig ppp create");
686

    
687

    
688
	$peerfile = "lcp-echo-failure 0\n";
689
	$peerfile .= "lcp-echo-interval 0\n";
690
	$peerfile .= "connect /etc/ppp/peers/ppp{$dev}-connect-chat\n";
691
	//$peerfile .= "disconnect /etc/ppp/peers/ppp{$dev}-disconnect-chat\n";
692
	$peerfile .= "{$ifcfg['port']} {$ifcfg['linespeed']}\n";
693
	$peerfile .= "crtscts\n";
694
	if ($ifcfg['connect-max-attempts'] <> "")
695
		$peerfile .= "connect-max-attempts {$ifcfg['connect-max-attempts']}";
696
	$peerfile .= "local\n";
697
	if ($ifcfg['localip'] <> "") {
698
		$peerfile .= ":{$ifcfg['gateway']}\n";
699
		$peerfile .= "{$ifcfg['localip']}:{$ifcfg['gateway']}";
700
	} else if ($ifcfg['gateway'] <> "") {
701
		$peerfile .= ":{$ifcfg['gateway']}\n";
702
		$peerfile .= "noipdefault\n";
703
	} else 
704
		$peerfile .= "noipdefault\n";
705
	$peerfile .= "ipcp-accept-local\n";
706
	$peerfile .= "novj\n";
707
	$peerfile .= "nobsdcomp\n";
708
	$peerfile .= "novjccomp\n";
709
	$peerfile .= "nopcomp\n";
710
	$peerfile .= "noaccomp\n";
711
	$peerfile .= "noauth\n";
712
	//$peerfile .= "nodetach\n";
713
	$peerfile .= "persist\n";
714
	$peerfile .= "debug\n";
715
	// KD - test
716
	//$peerfile .= "defaultroute\n";
717
	//$peerfile .= "nodetach\n";
718
	// KD - so I know where to look!
719
	$peerfile .= "# created by /etc/inc/interfaces.inc\n";
720

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

    
754
	config_lock();
755
	conf_mount_rw();
756
	safe_mkdir("/etc/ppp/peers", "0755");
757
	file_put_contents("/etc/ppp/peers/ppp_{$dev}", $peerfile);
758
	file_put_contents("/etc/ppp/peers/ppp{$dev}-connect-chat", $chatfile);
759
	chmod("/etc/ppp/peers/ppp{$dev}-connect-chat", 0755);
760
	conf_mount_ro();
761
	config_unlock();
762
	
763
	sleep(1);
764
	mwexec("/usr/sbin/pppd call ppp_{$dev}");
765

    
766
	return $realif;
767
}
768

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

    
856
	if(is_array($viparr))
857
	foreach ($viparr as $vip) {
858
		$vip_password = $vip['password'];
859
		$vip_password = str_replace(" ", "", $vip_password);
860
		if($vip['password'] != "")
861
                	$password = " pass \"" . $vip_password . "\"";
862
		$interface = filter_translate_type_to_real_interface($vip['interface']);
863
		$carpint = "carp" . $carp_instances_counter;
864

    
865
		switch ($vip['mode']) {
866
		case "carp":
867
			/* ensure CARP IP really exists prior to loading up */
868
			$found = false;
869
			$iflist = get_configured_interface_list();
870
			foreach($iflist as $if) {
871
				$ww_subnet_ip = $config['interfaces'][$if]['ipaddr'];
872
				$ww_subnet_bits = $config['interfaces'][$if]['subnet'];
873
				if (ip_in_subnet($vip['subnet'], gen_subnet($ww_subnet_ip, $ww_subnet_bits) . "/" . $ww_subnet_bits))
874
					$found = true;
875
			}
876
			if($found == false) {
877
				file_notice("CARP", "Sorry but we could not find a matching real interface subnet for the virtual IP address {$vip['subnet']}.", "Firewall: Virtual IP", "");
878
				continue;
879
			}
880
			/* ensure the interface containing the VIP really exists
881
			  prevents a panic if the interface is missing or invalid
882
			*/
883
			$realif = convert_friendly_interface_to_real_interface_name($vip['interface']);
884
			$intcount = exec("/sbin/ifconfig | grep $realif | wc -l | awk '{print $1}'");
885
			if($intcount < 1) {
886
				file_notice("CARP", "Interface specified for the virtual IP address {$vip['subnet']} does not exist. Skipping this VIP.", "Firewall: Virtual IP", "");
887
				continue;
888
			}
889
			/* create the carp interface and setup */
890
			$cmdchain->add("create CARP interface", "/sbin/ifconfig {$carpint} create", false);
891

    
892
			/* invalidate interface cache */
893
			get_interface_arr(true);
894
			$broadcast_address = gen_subnet_max($vip['subnet'], $vip['subnet_bits']);
895
			$cmdchain->add("config CARP interface", "/sbin/ifconfig {$carpint} " . $vip['subnet'] . "/" . $vip['subnet_bits'] . " vhid " . $vip['vhid'] . " advskew " . $vip['advskew'] . $password, false);
896
			$cmdchain->add("bring CARP interface UP", "/sbin/ifconfig {$carpint} up", false);
897
			$carp_instances_counter++;
898
			break;
899
		case "carpdev-dhcp":
900
			log_error("Found carpdev interface {$vip['interface']} on top of interface {$interface}");
901
			if(!empty($interface)) {
902
				
903
					$cmdchain->add("bring CARP parent interface UP", "/sbin/ifconfig {$interface} up", false);			
904
					$cmdchain->add("create CARP interface", "/sbin/ifconfig {$carpint} create", false);
905
					$cmdchain->add("bring CARP interface UP", "/sbin/ifconfig {$carpint} up", false);
906
					$cmdchain->add("assign CARP CarpDEV directive", "/sbin/ifconfig {$carpint} carpdev ". $interface . " vhid " . $vip['vhid'] . " advskew " . $vip['advskew'] . $password, false);
907
					$cmdchain->add("bring CARP interface UP", "/sbin/ifconfig {$carpint} up", false);
908

    
909
					/*
910
					 * XXX: BIG HACK but carpdev needs ip services active
911
					 * 	before even starting something as dhclient.
912
					 * 	I do not know if this is a feature or a bug
913
					 * 	but better than track it make it work ;) .
914
					 */
915
					//$fakeiptouse = "10.254.254." . ($carp_instances_counter+1);
916
					//$cmdchain->add("CarpDEV hack", "/sbin/ifconfig {$carpint} inet {$fakeiptouse}", false);
917

    
918
        			/* generate dhclient_wan.conf */
919
        			$fd = fopen("{$g['varetc_path']}/dhclient_{$carpint}.conf", "w");
920
        			if ($fd) {
921

    
922
        				$dhclientconf = "";
923

    
924
        				$dhclientconf .= <<<EOD
925
interface "{$carpint}" {
926
timeout 60;
927
retry 1;
928
select-timeout 0;
929
initial-interval 1;
930
script "/sbin/dhclient-script";
931
}
932

    
933
EOD;
934

    
935
 			        fwrite($fd, $dhclientconf);
936
        			fclose($fd);
937

    
938
        			/* fire up dhclient */
939
					$cmdchain->add("bring CARP dhclient UP", "/sbin/dhclient -c {$g['varetc_path']}/dhclient_{$carpint}.conf {$carpint} >/tmp/{$carpint}_output >/tmp/{$carpint}_error_output", false);
940
				} else {
941
					log_error("Error: cannot open dhclient_{$carpint}.conf in interfaces_carp_configure() for writing.\n");
942
					$cmdchain->add("bring CARP dhclient UP in background", "/sbin/dhclient -b {$carpint}", false);					
943
				}
944

    
945
        		$fout = fopen("/tmp/ifconfig_{$carpint}","w");
946
        		fwrite($fout, "/sbin/dhclient -c {$g['varetc_path']}/dhclient_{$carpint}.conf {$carpint}");
947
        		fclose($fout);
948

    
949
			} else {
950
				log_error("Could not determine CarpDEV parent interface for {$vip['descr']}.");
951
			}
952
			$carp_instances_counter++;
953
			break;
954
		}
955
	}
956

    
957
	if($g['debug'])
958
		$cmdchain->setdebug(); // optional for verbose logging
959
	// Execute built up command chain.
960
	$cmdchain->execute();	
961

    
962
	if ($g['booting']) {
963
		unmute_kernel_msgs();
964
		echo "done.\n";
965
	}
966

    
967
	/* update cache */
968
	if ($carp_instances_counter != find_number_of_created_carp_interfaces())
969
		find_number_of_created_carp_interfaces(true);
970

    
971
}
972

    
973
function interfaces_ipalias_configure() {
974
	global $g, $config;
975
	if(isset($config['system']['developerspew'])) {
976
		$mt = microtime();
977
		echo "interfaces_ipalias_configure() being called $mt\n";
978
	}
979
	$viparr = &$config['virtualip']['vip'];
980
	if(is_array($viparr)) {
981
		foreach ($viparr as $vip) {
982
			if ($vip['mode'] == "ipalias") {
983
				$if = get_real_interface($vip['interface']);
984
				mwexec("/sbin/ifconfig " . escapeshellarg($if) . " " . $vip['subnet'] . "/" . escapeshellarg($vip['subnet_bits']) . " alias"); 
985
			}
986
		}
987
	}
988
}
989

    
990
function interface_wireless_configure($if, $wlcfg) {
991
	global $config, $g;
992

    
993
	/*    open up a shell script that will be used to output the commands.
994
	 *    since wireless is changing a lot, these series of commands are fragile
995
     *    and will sometimes need to be verified by a operator by executing the command
996
     *    and returning the output of the command to the developers for inspection.  please
997
     *    do not change this routine from a shell script to individul exec commands.  -sullrich
998
	 */
999

    
1000
	conf_mount_rw();
1001

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

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

    
1008
	fwrite($fd_set, "# enable shell debugging\n");
1009
	fwrite($fd_set, "set -x\n");
1010

    
1011
	/* set values for /path/program */
1012
	$hostapd = "/usr/sbin/hostapd";
1013
	$wpa_supplicant = "/usr/sbin/wpa_supplicant";
1014
	$ifconfig = "/sbin/ifconfig";
1015
	$killall = "/usr/bin/killall";
1016

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

    
1019
	/* Set a/b/g standard */
1020
	$standard = "mode " . escapeshellarg($wlcfg['standard']);
1021

    
1022
	/* Set 802.11g protection mode */
1023
	$protmode = "protmode " . escapeshellarg($wlcfg['protmode']);
1024

    
1025
	/* set wireless channel value */
1026
	if(isset($wlcfg['channel']))
1027
		if($wlcfg['channel'] == "0")
1028
			$channel = "channel any";
1029
		else
1030
			$channel = "channel " . escapeshellarg($wlcfg['channel']);
1031

    
1032
	/* set Distance value */
1033
	if($wlcfg['distance'])
1034
		$distance = escapeshellarg($wlcfg['distance']);
1035

    
1036
	/* Set ssid */
1037
	if($wlcfg['ssid'])
1038
		$ssid = "ssid " . escapeshellarg($wlcfg['ssid']);
1039

    
1040
	/* Set wireless hostap mode */
1041
	if ($wlcfg['mode'] == "hostap")
1042
		$hostapmode = "mediaopt hostap";
1043
	else
1044
		$hostapmode = "-mediaopt hostap";
1045

    
1046
	/* Set wireless adhoc mode */
1047
	if ($wlcfg['mode'] == "adhoc")
1048
		$adhocmode = "mediaopt adhoc";
1049
	else
1050
		$adhocmode = "-mediaopt adhoc";
1051

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

    
1054
	/* handle hide ssid option */
1055
	if(isset($wlcfg['hidessid']['enable']))
1056
		$hidessid = "hidessid";
1057
	else
1058
		$hidessid = "-hidessid";
1059

    
1060
	/* handle pureg (802.11g) only option */
1061
	if(isset($wlcfg['pureg']['enable']))
1062
		$pureg = "mode 11g pureg";
1063
	else
1064
		$pureg = "-pureg";
1065

    
1066
	/* enable apbridge option */
1067
	if(isset($wlcfg['apbridge']['enable']))
1068
		$apbridge = "apbridge";
1069
	else
1070
		$apbridge = "-apbridge";
1071

    
1072
	/* handle turbo option */
1073
	if(isset($wlcfg['turbo']['enable']))
1074
		$turbo = "mediaopt turbo";
1075
	else
1076
		$turbo = "-mediaopt turbo";
1077

    
1078
	/* handle txpower setting */
1079
	if($wlcfg['txpower'] <> "")
1080
		$txpower = "txpower " . escapeshellarg($wlcfg['txpower']);
1081

    
1082
	/* handle wme option */
1083
	if(isset($wlcfg['wme']['enable']))
1084
		$wme = "wme";
1085
	else
1086
		$wme = "-wme";
1087

    
1088
	/* set up wep if enabled */
1089
    if (isset($wlcfg['wep']['enable']) && is_array($wlcfg['wep']['key'])) {
1090
		if($wlcfg['wpa']['auth_algs'] == "1")
1091
			$wepset .= "authmode open wepmode on ";
1092
		else if($wlcfg['wpa']['auth_algs'] == "2")
1093
			$wepset .= "authmode shared wepmode on ";
1094
		else if($wlcfg['wpa']['auth_algs'] == "3")
1095
			$wepset .= "authmode mixed wepmode on ";
1096
		$i = 1;
1097
		foreach ($wlcfg['wep']['key'] as $wepkey) {
1098
			$wepset .= "wepkey " . escapeshellarg("{$i}:{$wepkey['value']}") . " ";
1099
			if (isset($wepkey['txkey']))
1100
				$wepset .= "weptxkey {$i} ";
1101
			$i++;
1102
		}
1103
    } else {
1104
    	$wepset .= "authmode open wepmode off ";
1105
	}
1106

    
1107
	/* generate wpa_supplicant/hostap config if wpa is enabled */
1108

    
1109
	switch ($wlcfg['mode']) {
1110
		case 'bss':
1111
			if (isset($wlcfg['wpa']['enable'])) {
1112

    
1113
				$wpa .= <<<EOD
1114
ctrl_interface={$g['varrun_path']}/wpa_supplicant
1115
ctrl_interface_group=0
1116
ap_scan=1
1117
#fast_reauth=1
1118
network={
1119
ssid="{$wlcfg['ssid']}"
1120
scan_ssid=1
1121
priority=5
1122
key_mgmt={$wlcfg['wpa']['wpa_key_mgmt']}
1123
psk="{$wlcfg['wpa']['passphrase']}"
1124
pairwise={$wlcfg['wpa']['wpa_pairwise']}
1125
group={$wlcfg['wpa']['wpa_pairwise']}
1126
}
1127
EOD;
1128

    
1129
				$fd = fopen("{$g['varetc_path']}/wpa_supplicant_{$if}.conf", "w");
1130
				fwrite($fd, "{$wpa}");
1131
				fclose($fd);
1132

    
1133
				fwrite($fd_set, kill_wpasupplicant($if));
1134
			}
1135
		break;
1136

    
1137
		case 'hostap':
1138
			if (isset($wlcfg['wpa']['enable'])) {
1139
				$wpa .= <<<EOD
1140
interface={$if}
1141
driver=bsd
1142
logger_syslog=-1
1143
logger_syslog_level=0
1144
logger_stdout=-1
1145
logger_stdout_level=0
1146
dump_file={$g['tmp_path']}/hostapd_{$if}.dump
1147
ctrl_interface={$g['varrun_path']}/hostapd
1148
ctrl_interface_group=wheel
1149
#accept_mac_file={$g['tmp_path']}/hostapd_{$if}.accept
1150
#deny_mac_file={$g['tmp_path']}/hostapd_{$if}.deny
1151
#macaddr_acl={$wlcfg['wpa']['macaddr_acl']}
1152
ssid={$wlcfg['ssid']}
1153
debug={$wlcfg['wpa']['debug_mode']}
1154
auth_algs={$wlcfg['wpa']['auth_algs']}
1155
wpa={$wlcfg['wpa']['wpa_mode']}
1156
wpa_key_mgmt={$wlcfg['wpa']['wpa_key_mgmt']}
1157
wpa_pairwise={$wlcfg['wpa']['wpa_pairwise']}
1158
wpa_group_rekey={$wlcfg['wpa']['wpa_group_rekey']}
1159
wpa_gmk_rekey={$wlcfg['wpa']['wpa_gmk_rekey']}
1160
wpa_strict_rekey={$wlcfg['wpa']['wpa_strict_rekey']}
1161
wpa_passphrase={$wlcfg['wpa']['passphrase']}
1162
ieee8021x={$wlcfg['wpa']['ieee8021x']}
1163
#Enable the next lines for preauth when roaming. Interface = wired or wireless interface talking to the AP you want to roam from/to
1164
#rsn_preauth=1
1165
#rsn_preauth_interfaces=eth0
1166
EOD;
1167

    
1168
				$fd = fopen("{$g['varetc_path']}/hostapd_{$if}.conf", "w");
1169
				fwrite($fd, "{$wpa}");
1170
				fclose($fd);
1171

    
1172
				fwrite($fd_set, kill_hostapd($if));
1173
			}
1174
		break;
1175

    
1176
		case 'adhoc':
1177
			fwrite($fd_set, kill_hostapd($if));
1178
			fwrite($fd_set, kill_wpasupplicant($if));
1179
		break;
1180
	}
1181

    
1182
	/*
1183
	 *    all variables are set, lets start up everything
1184
     */
1185

    
1186
	/* set ack timers according to users preference (if he/she has any) */
1187
	if($distance) {
1188
		fwrite($fd_set, "# Enable ATH distance settings\n");
1189
		fwrite($fd_set, "/sbin/athctrl.sh -i {$if} -d {$distance}\n");
1190
	}
1191

    
1192
	$standard_no_turbo = str_replace(" Turbo", "", $standard);
1193

    
1194
	$settings = <<<EOD
1195

    
1196
{$ifconfig} {$if} down
1197
{$ifconfig} {$if} {$standard_no_turbo}
1198
{$ifconfig} {$if} {$channel}
1199
{$ifconfig} {$if} {$turbo}
1200
{$ifconfig} {$if} {$ssid}
1201
{$ifconfig} {$if} {$hidessid}
1202
{$ifconfig} {$if} {$adhocmode}
1203
{$ifconfig} {$if} {$protmode}
1204
{$ifconfig} {$if} {$pureg}
1205
{$ifconfig} {$if} {$apbridge}
1206
{$ifconfig} {$if} {$wme}
1207
{$ifconfig} {$if} {$wepset}
1208
{$ifconfig} {$if} {$txpower}
1209
{$ifconfig} {$if} {$hostapmode}
1210
{$ifconfig} {$if} up
1211

    
1212
EOD;
1213

    
1214
	/* write out above <<EOD stuff */
1215
	fwrite($fd_set, $settings);
1216

    
1217
	if (isset($wlcfg['wpa']['enable'])) {
1218
		if ($wlcfg['mode'] == "bss")
1219
			fwrite($fd_set, "{$wpa_supplicant} -B -i {$if} -c {$g['varetc_path']}/wpa_supplicant_{$if}.conf\n");
1220
		if ($wlcfg['mode'] == "hostap")
1221
			fwrite($fd_set, "{$hostapd} -B {$g['varetc_path']}/hostapd_{$if}.conf\n");
1222
	}
1223

    
1224
	fclose($fd_set);
1225

    
1226
	conf_mount_ro();
1227

    
1228
	/* execute commands now in shell */
1229
	mwexec("/bin/sh /tmp/{$if}_setup.sh");
1230
	sleep(2);
1231
	// XXX: ermal - This seems like not needed!? 
1232
	//mwexec("/bin/sh /tmp/{$if}_setup.sh");
1233

    
1234
	return 0;
1235

    
1236
}
1237

    
1238
function kill_hostapd($interface) {
1239
	return "/bin/ps awwuxx | grep hostapd | grep $interface | awk '{ print \$2 }' | xargs kill\n";
1240
}
1241

    
1242
function kill_wpasupplicant($interface) {
1243
	return "/bin/ps awwuxx | grep wpa_supplicant | grep $interface | awk '{ print \$2 }' | xargs kill\n";
1244
}
1245

    
1246
function find_dhclient_process($interface) {
1247
	$realinterface = get_real_interface($interface);
1248
	if($realinterface)
1249
		$pid = `ps awwwux | grep dhclient | grep -v grep | grep {$realinterface} | awk '{ print \$2 }'`;
1250
	return $pid;
1251
}
1252

    
1253
function interface_configure($interface = "wan") {
1254
	global $config, $g;
1255
	global $interface_sn_arr_cache, $interface_ip_arr_cache;
1256

    
1257
	$wancfg = $config['interfaces'][$interface];
1258

    
1259
	$realif = get_real_interface($interface);
1260

    
1261
	if (!$g['booting']) {
1262
		/* remove all IPv4 addresses */
1263
		while (mwexec("/sbin/ifconfig " . escapeshellarg($realif) . " -alias", true) == 0);
1264
			interface_bring_down($interface);
1265
	}
1266

    
1267
	/* wireless configuration? */
1268
	if (is_array($wancfg['wireless']))
1269
		interface_wireless_configure($realif, $wancfg['wireless']);
1270

    
1271
	if ($wancfg['spoofmac']) {
1272
		mwexec("/sbin/ifconfig " . escapeshellarg($wancfg['if']) .
1273
			" link " . escapeshellarg($wancfg['spoofmac']));
1274
	}  else {
1275
		$mac = get_interface_mac_address($wancfg['if']);
1276
		if($mac == "ff:ff:ff:ff:ff:ff") {
1277
			/*   this is not a valid mac address.  generate a
1278
			 *   temporary mac address so the machine can get online.
1279
			 */
1280
			echo "Generating new MAC address.";
1281
			$random_mac = generate_random_mac_address();
1282
			mwexec("/sbin/ifconfig " . escapeshellarg($wancfg['if']) .
1283
				" link " . escapeshellarg($random_mac));
1284
			$wancfg['spoofmac'] = $random_mac;
1285
			write_config();
1286
			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");
1287
		}
1288
	}
1289

    
1290
	/* media */
1291
	if ($wancfg['media'] || $wancfg['mediaopt']) {
1292
		$cmd = "/sbin/ifconfig " . escapeshellarg($wancfg['if']);
1293
		if ($wancfg['media'])
1294
			$cmd .= " media " . escapeshellarg($wancfg['media']);
1295
		if ($wancfg['mediaopt'])
1296
			$cmd .= " mediaopt " . escapeshellarg($wancfg['mediaopt']);
1297
		mwexec($cmd);
1298
	}
1299

    
1300
	/* invalidate interface/ip/sn cache */
1301
	get_interface_arr(true);
1302
	unset($interface_ip_arr_cache[$realif]);
1303
	unset($interface_sn_arr_cache[$realif]);
1304

    
1305
	switch ($wancfg['ipaddr']) {
1306

    
1307
		case 'carpdev-dhcp':
1308
			interface_carpdev_dhcp_configure($interface);
1309
			break;
1310
		case 'dhcp':
1311
			interface_dhcp_configure($interface);
1312
			break;
1313

    
1314
		case 'pppoe':
1315
			interface_pppoe_configure($interface);
1316
			break;
1317

    
1318
		case 'pptp':
1319
			interface_pptp_configure($interface);
1320
			break;
1321

    
1322
		default:
1323
			if ($wancfg['ipaddr'] <> "" && $wancfg['subnet'] <> "") {
1324
				if (isset($wancfg['ispointtopoint']) && $wancfg['pointtopoint']) {
1325
					mwexec("/sbin/ifconfig " . escapeshellarg($realif) . " " .
1326
						escapeshellarg($wancfg['ipaddr'] . "/" . $wancfg['subnet']) .
1327
						" " . escapeshellarg($wancfg['pointtopoint']) . " up");
1328
				} else {
1329
					if($wancfg['ipaddr'] && $wancfg['subnet'])
1330
						mwexec("/sbin/ifconfig " . escapeshellarg($realif) .
1331
							" " . escapeshellarg($wancfg['ipaddr'] . "/" . 
1332
							$wancfg['subnet']));
1333
				}
1334
			}
1335

    
1336
			if (is_ipaddr($wancfg['gateway']))
1337
				file_put_contents("/tmp/{$realif}_router", $wancfg['gateway']);
1338
	}
1339
	if($wancfg['if'])
1340
		interfaces_bring_up($wancfg['if']);
1341
	else 
1342
		log_error("Could not bring wancfg['if'] up -- variable not defined in interface_configure()");
1343
	
1344
	if (!$g['booting']) {
1345
		if (link_interface_to_gre($interface)) {
1346
			foreach ($config['gres']['gre'] as $gre)
1347
				if ($gre['if'] == $interface)
1348
					interface_gre_configure($gre);
1349
		}
1350
		if (link_interface_to_gif($interface)) {
1351
                	foreach ($config['gifs']['gif'] as $gif)
1352
				if ($gif['if'] == $interface)
1353
                        		interface_gre_configure($gif);
1354
        	}
1355
		if (link_interface_to_bridge($interface)) {
1356
			foreach ($config['bridges']['bridged'] as $bridge)
1357
				if (stristr($bridge['members'], "{$interface}"))
1358
					interface_bridge_configure($bridge);
1359
		}
1360

    
1361
		/* XXX: Shouldn't the caller do this?! */
1362
		/* XXX */
1363
		if ($interface = "lan")
1364
			/* make new hosts file */
1365
                	system_hosts_generate();
1366

    
1367
		/* reconfigure static routes (kernel may have deleted them) */
1368
		system_routing_configure();
1369

    
1370
		/* set the reload filter dity flag */
1371
		filter_configure();
1372

    
1373
		/* reload ipsec tunnels */
1374
		vpn_ipsec_configure();
1375

    
1376
		/* update dyndns */
1377
		services_dyndns_configure();
1378

    
1379
		/* force DNS update */
1380
		services_dnsupdate_process();
1381

    
1382
		/* restart dnsmasq */
1383
		services_dnsmasq_configure();
1384

    
1385
		/* reload captive portal */
1386
		captiveportal_configure();
1387
	}
1388

    
1389

    
1390
	unmute_kernel_msgs();
1391

    
1392
	return 0;
1393
}
1394

    
1395
function interface_carpdev_dhcp_configure($interface = "wan") {
1396
	global $config, $g;
1397

    
1398
	$wancfg = $config['interfaces'][$interface];
1399
	$wanif = $wancfg['if'];
1400
	/* bring wan interface up before starting dhclient */
1401
	if($wanif)
1402
		interfaces_bring_up($wanif);
1403
	else 
1404
		log_error("Could not bring wanif up in terface_carpdev_dhcp_configure()");
1405

    
1406
	return 0;
1407
}
1408

    
1409
function interface_dhcp_configure($interface = "wan") {
1410
	global $config, $g;
1411

    
1412
	$wancfg = $config['interfaces'][$interface];
1413

    
1414
	/* generate dhclient_wan.conf */
1415
	$fd = fopen("{$g['varetc_path']}/dhclient_{$interface}.conf", "w");
1416
	if (!$fd) {
1417
		printf("Error: cannot open dhclient_{$interface}.conf in interfaces_wan_dhcp_configure() for writing.\n");
1418
		return 1;
1419
	}
1420

    
1421
	if ($wancfg['dhcphostname']) {
1422
		$dhclientconf_hostname = "send dhcp-client-identifier \"{$wancfg['dhcphostname']}\";\n";
1423
		$dhclientconf_hostname .= "\tsend host-name \"{$wancfg['dhcphostname']}\";\n";
1424
	} else {
1425
		$dhclientconf_hostname = "";
1426
	}
1427

    
1428
	$wanif = get_real_interface($interface);
1429

    
1430
 	$dhclientconf = "";
1431
	
1432
	$dhclientconf .= <<<EOD
1433
interface "{$wanif}" {
1434
timeout 60;
1435
retry 1;
1436
select-timeout 0;
1437
initial-interval 1;
1438
	{$dhclientconf_hostname}
1439
	script "/sbin/dhclient-script";
1440
}
1441

    
1442
EOD;
1443

    
1444
if(is_ipaddr($wancfg['alias-address'])) {
1445
	$subnetmask = gen_subnet_mask($wancfg['alias-subnet']);
1446
	$dhclientconf .= <<<EOD
1447
alias {
1448
	interface  "{$wanif}";
1449
	fixed-address {$wancfg['alias-address']};
1450
	option subnet-mask {$subnetmask};
1451
}
1452

    
1453
EOD;
1454
}
1455
	fwrite($fd, $dhclientconf);
1456
	fclose($fd);
1457

    
1458
	$relwanif = $wancfg['if'];
1459

    
1460
	/* bring wan interface up before starting dhclient */
1461
	if($realwanif)
1462
		interfaces_bring_up($realwanif);
1463
	else 
1464
		log_error("Could not bring realwanif up in interface_dhcp_configure()");
1465

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

    
1469
	$fout = fopen("/tmp/ifconfig_{$wanif}","w");
1470
	fwrite($fout, "/sbin/dhclient -c {$g['varetc_path']}/dhclient_{$interface}.conf {$wanif}");
1471
	fclose($fout);
1472

    
1473
	return 0;
1474
}
1475

    
1476
function interface_pppoe_configure($interface = "wan") 
1477
{
1478
	global $config, $g;
1479

    
1480
	$wancfg = $config['interfaces'][$interface];
1481

    
1482
	/* generate mpd.conf */
1483
	$fd = fopen("{$g['varetc_path']}/mpd_{$interface}.conf", "w");
1484
	if (!$fd) {
1485
		printf("Error: cannot open mpd_{$interface}.conf in interface_pppoe_configure().\n");
1486
		return 1;
1487
	}
1488

    
1489
	$idle = 0;
1490

    
1491
	if (isset($wancfg['ondemand'])) {
1492
		$ondemand = "enable";
1493
		if ($wancfg['timeout'])
1494
			$idle = $wancfg['timeout'];
1495
	} else {
1496
		$ondemand = "disable";
1497
	}
1498

    
1499
	$mpdconf = <<<EOD
1500
startup:
1501
pppoeclient:
1502

    
1503
EOD;
1504

    
1505
	if ($interface == "wan")
1506
		$realif = "pppoe0";
1507
	else {
1508
		// Here code assumes only that strings of form "opt#" will be passed.
1509
		$realif = "pppoe" . substr($interface, 3); 
1510
	}
1511
	
1512
	$mpdconf .= <<<EOD
1513
	new -i {$realif} pppoeclient pppoeclient
1514

    
1515
EOD;
1516
	if ($interface == "wan")
1517
		$mpdconf .= <<<EOD
1518
	set iface route default
1519

    
1520
EOD;
1521
	
1522
	$mpdconf .= <<<EOD
1523
	set iface {$ondemand} on-demand
1524
	set iface idle {$idle}
1525
	set iface enable tcpmssfix
1526
	set iface up-script /usr/local/sbin/ppp-linkup
1527
	set iface down-script /usr/local/sbin/ppp-linkdown
1528

    
1529
EOD;
1530

    
1531
	if (isset($wancfg['ondemand'])) {
1532
		if (isset($wancfg['local-ip']) && isset($wancfg['remote-ip'])) {
1533
			$mpdconf .= <<<EOD
1534
	set iface addrs {$wancfg['local-ip']} {$wancfg['remote-ip']}
1535

    
1536
EOD;
1537
		} else {
1538
			$mpdconf .= <<<EOD
1539
	set iface addrs 192.0.2.112 192.0.2.113
1540

    
1541
EOD;
1542
		}
1543
	}
1544

    
1545
	$mpdconf .= <<<EOD
1546
	set bundle disable multilink
1547
	set auth authname "{$wancfg['pppoe_username']}"
1548
	set auth password "{$wancfg['pppoe_password']}"
1549
	set link keep-alive 10 60
1550
	set link max-redial 0
1551
	set link no acfcomp protocomp
1552
	set link disable pap chap
1553
	set link accept chap
1554
	
1555
EOD;
1556
	if (empty($wancfg['mtu']))
1557
		$mpdmtu = "1492";
1558
	else 
1559
		$mpdmtu = "{$wancfg['mtu']}";
1560

    
1561
	$mpdconf .= <<<EOD
1562
	set link mtu {$mpdmtu}
1563
	set ipcp yes vjcomp
1564
	set ipcp ranges 0.0.0.0/0 0.0.0.0/0
1565

    
1566
EOD;
1567

    
1568
	if (isset($config['system']['dnsallowoverride'])) {
1569
		$mpdconf .= <<<EOD
1570
	set ipcp enable req-pri-dns
1571

    
1572
EOD;
1573
	}
1574

    
1575
	if (!isset($wancfg['dnsnosec']) && isset($config['system']['dnsallowoverride'])) {
1576
			$mpdconf .= <<<EOD
1577
	set ipcp enable req-sec-dns
1578

    
1579
EOD;
1580
	}
1581
	
1582
	$mpdconf .= <<<EOD
1583
	open
1584

    
1585
EOD;
1586

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

    
1590
	/* generate mpd.links */
1591
	$fd = fopen("{$g['varetc_path']}/mpd_{$interface}.links", "w");
1592
	if (!$fd) {
1593
		printf("Error: cannot open mpd_{$interface}.links in interface_pppoe_configure().\n");
1594
		return 1;
1595
	}
1596

    
1597
	$mpdconf = <<<EOD
1598
pppoeclient:
1599
	set link type pppoe
1600
	set pppoe iface {$wancfg['if']}
1601
	set pppoe service "{$wancfg['provider']}"
1602
	set pppoe enable originate
1603
	set pppoe disable incoming
1604

    
1605
EOD;
1606

    
1607
	fwrite($fd, $mpdconf);
1608
	fclose($fd);
1609

    
1610
	if(file_exists("{$g['varrun_path']}/pppoe_{$interface}.pid") and $g['booting']) {
1611
		/* if we are booting and mpd has already been started then don't start again. */
1612
	} else {
1613
		/* if mpd is active, lets take it down */
1614
		if(file_exists("{$g['varrun_path']}/pppoe_{$interface}.pid")) {
1615
			killbypid("{$g['varrun_path']}/pppoe_{$interface}.pid");
1616
			sleep(3);
1617
		}
1618

    
1619
		/* Bring the parent interface up */
1620
		if($wancfg['if'])
1621
			interfaces_bring_up($wancfg['if']);
1622
		else 
1623
			log_error("Could not bring wancfg['if'] up in interface_pppoe_configure()");
1624

    
1625
		/* fire up mpd */
1626
		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");
1627
	}
1628

    
1629
	/* sleep until wan is up - or 30 seconds, whichever comes first */
1630
	for ($count = 0; $count < 30; $count++) {
1631
		if(file_exists("{$g['tmp_path']}/{$realif}up")) {
1632
			break;
1633
		}
1634
		sleep(1);
1635
	}
1636

    
1637
	unlink_if_exists("{$g['tmp_path']}/{$realif}up");
1638

    
1639
	return 0;
1640
}
1641

    
1642
function interface_pptp_configure($interface) {
1643
	global $config, $g;
1644

    
1645
	$wancfg = $config['interfaces'][$interface];
1646

    
1647
	/* generate mpd.conf */
1648
	$fd = fopen("{$g['varetc_path']}/mpd_{$interface}.conf", "w");
1649
	if (!$fd) {
1650
		printf("Error: cannot open mpd_{$interface}.conf in interface_pptp_configure().\n");
1651
		return 1;
1652
	}
1653

    
1654
	$idle = 0;
1655

    
1656
	if (isset($wancfg['ondemand'])) {
1657
		$ondemand = "enable";
1658
		if ($wancfg['timeout'])
1659
			$idle = $wancfg['timeout'];
1660
	} else {
1661
		$ondemand = "disable";
1662
	}
1663

    
1664
	$mpdconf = <<<EOD
1665
startup:
1666
pptp:
1667

    
1668
EOD;
1669

    
1670
        if ($interface == "wan")
1671
                $realif = "pptp0";
1672
        else {
1673
                // Here code assumes only that strings of form "opt#" will be passed.
1674
                $realif = "pptp" . substr($interface, 3);
1675
	}
1676

    
1677
        $mpdconf .= <<<EOD
1678
        new -i {$realif} pptp pptp 
1679

    
1680
EOD;
1681
        if ($interface == "wan")
1682
                $mpdconf .= <<<EOD
1683
        set iface route default
1684

    
1685
EOD;
1686

    
1687
        $mpdconf .= <<<EOD
1688
	set iface {$ondemand} on-demand
1689
	set iface idle {$idle}
1690
	set iface up-script /usr/local/sbin/ppp-linkup
1691
	set iface down-script /usr/local/sbin/ppp-linkdown
1692

    
1693
EOD;
1694

    
1695
	if (isset($wanfg['ondemand'])) {
1696
		$mpdconf .= <<<EOD
1697
	set iface addrs 10.0.0.1 10.0.0.2
1698

    
1699
EOD;
1700
	}
1701

    
1702
	$mpdconf .= <<<EOD
1703
	set bundle disable multilink
1704
	set auth authname "{$wancfg['pptp_username']}"
1705
	set auth password "{$wancfg['pptp_password']}"
1706
	set bundle no noretry
1707
	set link keep-alive 10 60
1708
	set link max-redial 0
1709
	set link no acfcomp protocomp
1710
	set link disable pap chap
1711
	set link accept chap
1712
	set ipcp no vjcomp
1713
	set ipcp ranges 0.0.0.0/0 0.0.0.0/0
1714

    
1715
EOD;
1716
	if (isset($config['system']['dnsallowoverride'])) {
1717
		$mpdconf .= <<<EOD
1718
	set ipcp enable req-pri-dns
1719

    
1720
EOD;
1721
	}
1722

    
1723
	$mpdconf .= <<<EOD
1724
	open
1725

    
1726
EOD;
1727

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

    
1731
	/* generate mpd.links */
1732
	$fd = fopen("{$g['varetc_path']}/mpd_{$interface}.links", "w");
1733
	if (!$fd) {
1734
		printf("Error: cannot open mpd_{$interface}.links in interface_pptp_configure().\n");
1735
		return 1;
1736
	}
1737

    
1738
	$mpdconf = <<<EOD
1739
pptp:
1740
	set link type pptp
1741
	set pptp enable originate outcall
1742
	set pptp disable windowing
1743
	set pptp self {$wancfg['local']}
1744
	set pptp peer {$wancfg['remote']}
1745

    
1746
EOD;
1747

    
1748
	fwrite($fd, $mpdconf);
1749
	fclose($fd);
1750

    
1751
	/* configure interface */
1752
	if($wancfg['if'])
1753
		mwexec("/sbin/ifconfig " . escapeshellarg($wancfg['if']) . " " .
1754
			escapeshellarg($wancfg['local'] . "/" . $wancfg['subnet']) . " up");
1755
	else 
1756
		log_error("Could not bring interface wancfg['if'] up in interface_pptp_configure()");
1757
	/* fire up mpd */
1758
	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");
1759

    
1760
	return 0;
1761
}
1762
 
1763
/* XXX: stub for code that references the old functions(mostly packages) */
1764
function get_real_wan_interface($interface = "wan") {
1765
	return get_real_interface($interface);
1766
}
1767
function get_current_wan_address($interface = "wan") {
1768
	return get_interface_ip($interface);
1769
}
1770

    
1771
function get_real_interface($interface = "wan") {
1772
    global $config;
1773

    
1774
	$wanif = NULL;
1775

    
1776
	switch ($interface) {
1777
	case "l2tp":
1778
		$wanif = "l2tp";
1779
		break;
1780
	case "pptp":
1781
		$wanif = "pptp";
1782
		break;
1783
	case "pppoe":
1784
		$wanif = "pppoe";
1785
		break;
1786
	case "openvpn":
1787
		$wanif = "openvpn";
1788
		break;
1789
	case "enc0":
1790
		$wanif = "enc0";
1791
		break;
1792
	/* XXX: dial in support?!
1793
	case "ppp":
1794
		$wanif = "ppp";
1795
		break;
1796
	*/
1797
	default:
1798
		$iflist = get_configured_interface_with_descr(false, true);
1799

    
1800
		foreach ($iflist as $if => $ifdesc) {
1801
			if ($interface == $if || $interface == $ifdesc) {
1802

    
1803
			$cfg = $config['interfaces'][$if];
1804

    
1805
			if (empty($cfg['ipaddr'])) {
1806
				$wanif = $cfg['if'];
1807
				break;
1808
			}
1809

    
1810
			switch ($cfg['ipaddr']) {
1811
			case "carpdev-dhcp":
1812
				$viparr = &$config['virtualip']['vip'];
1813
				$counter = 0;
1814
				if(is_array($viparr))
1815
				foreach ($viparr as $vip) {
1816
					if ($vip['mode'] == "carpdev-dhcp") {
1817
						if($vip['interface'] == $if) {
1818
							$wanif =  "carp{$counter}";
1819
							break;
1820
						}
1821
						$counter++;
1822
					} else if ($vip['mode'] = "carp") 
1823
						$counter++;
1824
				}
1825
				break;
1826
			case "pppoe": 
1827
				if ($if == "wan")
1828
					$wanif = "pppoe0";
1829
				else
1830
					$wanif = "pppoe" . substr($if,3);
1831
				break;
1832
			case "pptp": 
1833
				if ($if == "wan")
1834
					$wanif = "pptp0";
1835
				else
1836
					$wanif = "pptp" . substr($if, 3);
1837
				break;
1838
			default:
1839
				$wanif = $cfg['if'];
1840
				break;
1841
			}
1842
			
1843
			break;
1844
			}
1845
		}
1846
		break;
1847
	}
1848

    
1849
    return $wanif;
1850
}
1851

    
1852
function get_interface_ip($interface = "wan") {
1853
	$realif = get_real_interface($interface);
1854
	/* Do we really come here for these interfaces ?! */
1855
	if (in_array($realif, array("pptp", "pppoe", "l2tp", "openvpn", "enc0" /* , "ppp" */)))
1856
			return "";
1857

    
1858
	$curip = find_interface_ip($realif);
1859
	if ($curip && is_ipaddr($curip) && ($curip != "0.0.0.0"))
1860
		return $curip;
1861

    
1862
	return null;
1863
}
1864

    
1865
function get_interface_subnet($interface = "wan") {
1866
	$realif = get_real_interface($interface);
1867
	/* Do we really come here for these interfaces ?! */
1868
	if (in_array($realif, array("pptp", "pppoe", "openvpn", "enc0" /* , "ppp" */)))
1869
		return "";
1870

    
1871
	$cursn = find_interface_subnet($realif);
1872
	if (!empty($cursn))
1873
		return $cursn;
1874

    
1875
	return null;
1876
}
1877

    
1878
/****f* interfaces/is_altq_capable
1879
 * NAME
1880
 *   is_altq_capable - Test if interface is capable of using ALTQ
1881
 * INPUTS
1882
 *   $int            - string containing interface name
1883
 * RESULT
1884
 *   boolean         - true or false
1885
 ******/
1886

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

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

    
1900
        if (in_array($int_family[0], $capable))
1901
                return true;
1902
        else
1903
                return false;
1904
}
1905

    
1906
function get_wireless_modes($interface) {
1907
	/* return wireless modes and channels */
1908
	$wireless_modes = array();
1909

    
1910
	if(is_interface_wireless($interface)) {
1911
		$wi = 1;
1912
		$ifconfig = "/sbin/ifconfig";
1913
		$awk = "/usr/bin/awk";
1914
		$chan_list = "$ifconfig $interface list chan";
1915
		$stack_list = "$awk -F\"Channel \" '{ gsub(/\\*/, \" \"); print \$2 \"\\\n\" \$3 }'";
1916
		$format_list = "$awk '{print \$5 \" \" \$6 \",\" \$1}'";
1917

    
1918
		$interface_channels = "";
1919
		exec("$chan_list | $stack_list | sort -u | $format_list 2>&1", $interface_channels);
1920
		$interface_channel_count = count($interface_channels);
1921

    
1922
		$c = 0;
1923
		while ($c < $interface_channel_count)
1924
		{
1925
			$channel_line = explode(",", $interface_channels["$c"]);
1926
			$wireless_mode = trim($channel_line[0]);
1927
			$wireless_channel = trim($channel_line[1]);
1928
			if(trim($wireless_mode) != "") {
1929
				/* if we only have 11g also set 11b channels */
1930
				if($wireless_mode == "11g") {
1931
					$wireless_modes["11b"] = array();
1932
				}
1933
				$wireless_modes["$wireless_mode"]["$c"] = $wireless_channel;
1934
			}
1935
			$c++;
1936
		}
1937
	}
1938
	return($wireless_modes);
1939
}
1940

    
1941
function get_interface_mac($interface) {
1942
	/* build interface list with netstat */
1943
	$linkinfo = "";
1944
	exec("/usr/bin/netstat -I $interface -nW -f link", $linkinfo);
1945
	array_shift($linkinfo);
1946
	$alink = preg_split("/\s+/", $linkinfo[0]);
1947
	$mac = chop($alink[3]);
1948
	return $mac;
1949
}
1950

    
1951
function setup_pppoe_reset_file($interface, $status) {
1952
	define("CRON_PPPOE_CMD_FILE", "/conf/pppoe{$interface}restart");
1953
	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");
1954
	if($status == true) {
1955
		if(!file_exists(CRON_PPPOE_CMD_FILE)) {
1956
			file_put_contents(CRON_PPPOE_CMD_FILE, CRON_PPPOE_CMD);
1957
			chmod(CRON_PPPOE_CMD_FILE, 0700);
1958
		}	
1959
	} else {
1960
		unlink_if_exists(CRON_PPPOE_CMD_FILE);
1961
	}
1962
}
1963

    
1964
?>
(16-16/39)