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
	if($interface)
1248
		$pid = `ps awwwux | grep dhclient | grep -v grep | grep {$interface} | awk '{ print \$2 }'`;
1249
	return $pid;
1250
}
1251

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

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

    
1258
	$realif = get_real_interface($interface);
1259

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1388

    
1389
	unmute_kernel_msgs();
1390

    
1391
	return 0;
1392
}
1393

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

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

    
1405
	return 0;
1406
}
1407

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

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

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

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

    
1427
	$wanif = get_real_interface($interface);
1428

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

    
1441
EOD;
1442

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

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

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

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

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

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

    
1472
	return 0;
1473
}
1474

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

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

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

    
1488
	$idle = 0;
1489

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

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

    
1502
EOD;
1503

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

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

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

    
1528
EOD;
1529

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

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

    
1540
EOD;
1541
		}
1542
	}
1543

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

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

    
1565
EOD;
1566

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

    
1571
EOD;
1572
	}
1573

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

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

    
1584
EOD;
1585

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

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

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

    
1604
EOD;
1605

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

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

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

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

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

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

    
1638
	return 0;
1639
}
1640

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

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

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

    
1653
	$idle = 0;
1654

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

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

    
1667
EOD;
1668

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

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

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

    
1684
EOD;
1685

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

    
1692
EOD;
1693

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

    
1698
EOD;
1699
	}
1700

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

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

    
1719
EOD;
1720
	}
1721

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

    
1725
EOD;
1726

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

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

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

    
1745
EOD;
1746

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

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

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

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

    
1773
	$wanif = NULL;
1774

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

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

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

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

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

    
1848
    return $wanif;
1849
}
1850

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

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

    
1861
	return null;
1862
}
1863

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

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

    
1874
	return null;
1875
}
1876

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

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

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

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

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

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

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

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

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

    
1950
function setup_pppoe_reset_file($interface, $status) {
1951
	define("CRON_PPPOE_CMD_FILE", "/conf/pppoe{$interface}restart");
1952
	define("CRON_PPPOE_CMD", "#!/bin/sh\necho '<?php require(\"interfaces.inc\"); interface_reconfigure({$interface}); services_dyndns_reset({$interface}); filter_configure(); ?>' | /usr/local/bin/php -q");
1953
	if($status == true) {
1954
		if(!file_exists(CRON_PPPOE_CMD_FILE)) {
1955
			file_put_contents(CRON_PPPOE_CMD_FILE, CRON_PPPOE_CMD);
1956
			chmod(CRON_PPPOE_CMD_FILE, 0700);
1957
		}	
1958
	} else {
1959
		unlink_if_exists(CRON_PPPOE_CMD_FILE);
1960
	}
1961
}
1962

    
1963
?>
(16-16/39)