Project

General

Profile

Download (57.9 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
	/* configure interface groups */
564
	interfaces_group_setup();
565

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

    
570
		/* reload IPsec tunnels */
571
		vpn_ipsec_configure();
572

    
573
		/* reload dhcpd (interface enabled/disabled status may have changed) */
574
		services_dhcpd_configure();
575

    
576
		/* restart dnsmasq */
577
		services_dnsmasq_configure();
578

    
579
		/* reload captive portal */
580
		captiveportal_configure();
581

    
582
		/* set the reload filter dity flag */
583
		filter_configure();
584
	}
585

    
586
	return 0;
587
}
588

    
589
function interface_reconfigure($interface = "wan") {
590
	interface_bring_down($interface);
591
	sleep(1);
592
	interface_configure($interface);
593
}
594

    
595
function interface_bring_down($interface = "wan", $destroy = false) {
596
	global $config, $g;
597

    
598
	if (!isset($config['interfaces'][$interface]))
599
		return; 
600

    
601
	$ifcfg = $config['interfaces'][$interface];
602

    
603
	$realif = get_real_interface($interface);
604

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

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

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

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

    
652
function interfaces_ppp_configure() {
653
        global $config;
654

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

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

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

    
690

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

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

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

    
769
	return $realif;
770
}
771

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

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

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

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

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

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

    
925
        				$dhclientconf = "";
926

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

    
936
EOD;
937

    
938
 			        fwrite($fd, $dhclientconf);
939
        			fclose($fd);
940

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

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

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

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

    
965
	if ($g['booting']) {
966
		unmute_kernel_msgs();
967
		echo "done.\n";
968
	}
969

    
970
	/* update cache */
971
	if ($carp_instances_counter != find_number_of_created_carp_interfaces())
972
		find_number_of_created_carp_interfaces(true);
973

    
974
}
975

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

    
993
function interface_wireless_configure($if, $wlcfg) {
994
	global $config, $g;
995

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

    
1003
	conf_mount_rw();
1004

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

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

    
1011
	fwrite($fd_set, "# enable shell debugging\n");
1012
	fwrite($fd_set, "set -x\n");
1013

    
1014
	/* set values for /path/program */
1015
	$hostapd = "/usr/sbin/hostapd";
1016
	$wpa_supplicant = "/usr/sbin/wpa_supplicant";
1017
	$ifconfig = "/sbin/ifconfig";
1018
	$killall = "/usr/bin/killall";
1019

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

    
1022
	/* Set a/b/g standard */
1023
	$standard = "mode " . escapeshellarg($wlcfg['standard']);
1024

    
1025
	/* Set 802.11g protection mode */
1026
	$protmode = "protmode " . escapeshellarg($wlcfg['protmode']);
1027

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

    
1035
	/* set Distance value */
1036
	if($wlcfg['distance'])
1037
		$distance = escapeshellarg($wlcfg['distance']);
1038

    
1039
	/* Set ssid */
1040
	if($wlcfg['ssid'])
1041
		$ssid = "ssid " . escapeshellarg($wlcfg['ssid']);
1042

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

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

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

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

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

    
1069
	/* enable apbridge option */
1070
	if(isset($wlcfg['apbridge']['enable']))
1071
		$apbridge = "apbridge";
1072
	else
1073
		$apbridge = "-apbridge";
1074

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

    
1081
	/* handle txpower setting */
1082
	if($wlcfg['txpower'] <> "")
1083
		$txpower = "txpower " . escapeshellarg($wlcfg['txpower']);
1084

    
1085
	/* handle wme option */
1086
	if(isset($wlcfg['wme']['enable']))
1087
		$wme = "wme";
1088
	else
1089
		$wme = "-wme";
1090

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

    
1110
	/* generate wpa_supplicant/hostap config if wpa is enabled */
1111

    
1112
	switch ($wlcfg['mode']) {
1113
		case 'bss':
1114
			if (isset($wlcfg['wpa']['enable'])) {
1115

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

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

    
1136
				fwrite($fd_set, kill_wpasupplicant($if));
1137
			}
1138
		break;
1139

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

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

    
1175
				fwrite($fd_set, kill_hostapd($if));
1176
			}
1177
		break;
1178

    
1179
		case 'adhoc':
1180
			fwrite($fd_set, kill_hostapd($if));
1181
			fwrite($fd_set, kill_wpasupplicant($if));
1182
		break;
1183
	}
1184

    
1185
	/*
1186
	 *    all variables are set, lets start up everything
1187
     */
1188

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

    
1195
	$standard_no_turbo = str_replace(" Turbo", "", $standard);
1196

    
1197
	$settings = <<<EOD
1198

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

    
1215
EOD;
1216

    
1217
	/* write out above <<EOD stuff */
1218
	fwrite($fd_set, $settings);
1219

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

    
1227
	fclose($fd_set);
1228

    
1229
	conf_mount_ro();
1230

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

    
1237
	return 0;
1238

    
1239
}
1240

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

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

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

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

    
1259
	$wancfg = $config['interfaces'][$interface];
1260

    
1261
	$realif = get_real_interface($interface);
1262

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

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

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

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

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

    
1307
	switch ($wancfg['ipaddr']) {
1308

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

    
1316
		case 'pppoe':
1317
			interface_pppoe_configure($interface);
1318
			break;
1319

    
1320
		case 'pptp':
1321
			interface_pptp_configure($interface);
1322
			break;
1323

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

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

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

    
1369
		/* reconfigure static routes (kernel may have deleted them) */
1370
		system_routing_configure();
1371

    
1372
		/* set the reload filter dity flag */
1373
		filter_configure();
1374

    
1375
		/* reload ipsec tunnels */
1376
		vpn_ipsec_configure();
1377

    
1378
		/* update dyndns */
1379
		services_dyndns_configure();
1380

    
1381
		/* force DNS update */
1382
		services_dnsupdate_process();
1383

    
1384
		/* restart dnsmasq */
1385
		services_dnsmasq_configure();
1386

    
1387
		/* reload captive portal */
1388
		captiveportal_configure();
1389
	}
1390

    
1391

    
1392
	unmute_kernel_msgs();
1393

    
1394
	return 0;
1395
}
1396

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

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

    
1408
	return 0;
1409
}
1410

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

    
1414
	$wancfg = $config['interfaces'][$interface];
1415

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

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

    
1430
	$wanif = get_real_interface($interface);
1431

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

    
1444
EOD;
1445

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

    
1455
EOD;
1456
}
1457
	fwrite($fd, $dhclientconf);
1458
	fclose($fd);
1459

    
1460
	$relwanif = $wancfg['if'];
1461

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

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

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

    
1475
	return 0;
1476
}
1477

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

    
1482
	$wancfg = $config['interfaces'][$interface];
1483

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

    
1491
	$idle = 0;
1492

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

    
1501
	$mpdconf = <<<EOD
1502
startup:
1503
pppoeclient:
1504

    
1505
EOD;
1506

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

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

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

    
1531
EOD;
1532

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

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

    
1543
EOD;
1544
		}
1545
	}
1546

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

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

    
1568
EOD;
1569

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

    
1574
EOD;
1575
	}
1576

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

    
1581
EOD;
1582
	}
1583
	
1584
	$mpdconf .= <<<EOD
1585
	open
1586

    
1587
EOD;
1588

    
1589
	fwrite($fd, $mpdconf);
1590
	fclose($fd);
1591

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

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

    
1607
EOD;
1608

    
1609
	fwrite($fd, $mpdconf);
1610
	fclose($fd);
1611

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

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

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

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

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

    
1641
	return 0;
1642
}
1643

    
1644
function interface_pptp_configure($interface) {
1645
	global $config, $g;
1646

    
1647
	$wancfg = $config['interfaces'][$interface];
1648

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

    
1656
	$idle = 0;
1657

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

    
1666
	$mpdconf = <<<EOD
1667
startup:
1668
pptp:
1669

    
1670
EOD;
1671

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

    
1679
        $mpdconf .= <<<EOD
1680
        new -i {$realif} pptp pptp 
1681

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

    
1687
EOD;
1688

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

    
1695
EOD;
1696

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

    
1701
EOD;
1702
	}
1703

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

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

    
1722
EOD;
1723
	}
1724

    
1725
	$mpdconf .= <<<EOD
1726
	open
1727

    
1728
EOD;
1729

    
1730
	fwrite($fd, $mpdconf);
1731
	fclose($fd);
1732

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

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

    
1748
EOD;
1749

    
1750
	fwrite($fd, $mpdconf);
1751
	fclose($fd);
1752

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

    
1762
	return 0;
1763
}
1764

    
1765
function interfaces_group_setup() {
1766
	global $config;
1767

    
1768
	if (!is_array($config['ifgroups']['ifgroupentry']))
1769
		return;
1770

    
1771
	foreach ($config['ifgroups']['ifgroupentry'] as $grouppar)
1772
		interface_group_setup($groupar);
1773

    
1774
	return;
1775
}
1776

    
1777
function interface_group_setup($groupname /* The parameter is an array */) {
1778
	global $config;
1779

    
1780
	if (!is_array($groupname))
1781
		return;
1782
	$members = explode(" ", $groupname['members']);
1783
	foreach($members as $ifs) {
1784
		$realif = get_real_interface($ifs);
1785
		if ($realif)
1786
			mwexec("/sbin/ifconfig {$realif} group {$groupname['ifname']}");
1787
	}
1788

    
1789
	return;
1790
}
1791
 
1792
/* XXX: stub for code that references the old functions(mostly packages) */
1793
function get_real_wan_interface($interface = "wan") {
1794
	return get_real_interface($interface);
1795
}
1796
function get_current_wan_address($interface = "wan") {
1797
	return get_interface_ip($interface);
1798
}
1799

    
1800
function get_real_interface($interface = "wan") {
1801
    global $config;
1802

    
1803
	$wanif = NULL;
1804

    
1805
	switch ($interface) {
1806
	case "l2tp":
1807
		$wanif = "l2tp";
1808
		break;
1809
	case "pptp":
1810
		$wanif = "pptp";
1811
		break;
1812
	case "pppoe":
1813
		$wanif = "pppoe";
1814
		break;
1815
	case "openvpn":
1816
		$wanif = "openvpn";
1817
		break;
1818
	case "enc0":
1819
		$wanif = "enc0";
1820
		break;
1821
	/* XXX: dial in support?!
1822
	case "ppp":
1823
		$wanif = "ppp";
1824
		break;
1825
	*/
1826
	default:
1827
		$iflist = get_configured_interface_with_descr(false, true);
1828

    
1829
		foreach ($iflist as $if => $ifdesc) {
1830
			if ($interface == $if || $interface == $ifdesc) {
1831

    
1832
			$cfg = $config['interfaces'][$if];
1833

    
1834
			if (empty($cfg['ipaddr'])) {
1835
				$wanif = $cfg['if'];
1836
				break;
1837
			}
1838

    
1839
			switch ($cfg['ipaddr']) {
1840
			case "carpdev-dhcp":
1841
				$viparr = &$config['virtualip']['vip'];
1842
				$counter = 0;
1843
				if(is_array($viparr))
1844
				foreach ($viparr as $vip) {
1845
					if ($vip['mode'] == "carpdev-dhcp") {
1846
						if($vip['interface'] == $if) {
1847
							$wanif =  "carp{$counter}";
1848
							break;
1849
						}
1850
						$counter++;
1851
					} else if ($vip['mode'] = "carp") 
1852
						$counter++;
1853
				}
1854
				break;
1855
			case "pppoe": 
1856
				if ($if == "wan")
1857
					$wanif = "pppoe0";
1858
				else
1859
					$wanif = "pppoe" . substr($if,3);
1860
				break;
1861
			case "pptp": 
1862
				if ($if == "wan")
1863
					$wanif = "pptp0";
1864
				else
1865
					$wanif = "pptp" . substr($if, 3);
1866
				break;
1867
			default:
1868
				$wanif = $cfg['if'];
1869
				break;
1870
			}
1871
			
1872
			break;
1873
			}
1874
		}
1875
		break;
1876
	}
1877

    
1878
    return $wanif;
1879
}
1880

    
1881
function get_interface_ip($interface = "wan") {
1882
	$realif = get_real_interface($interface);
1883
	/* Do we really come here for these interfaces ?! */
1884
	if (in_array($realif, array("pptp", "pppoe", "l2tp", "openvpn", "enc0" /* , "ppp" */)))
1885
			return "";
1886

    
1887
	$curip = find_interface_ip($realif);
1888
	if ($curip && is_ipaddr($curip) && ($curip != "0.0.0.0"))
1889
		return $curip;
1890

    
1891
	return null;
1892
}
1893

    
1894
function get_interface_subnet($interface = "wan") {
1895
	$realif = get_real_interface($interface);
1896
	/* Do we really come here for these interfaces ?! */
1897
	if (in_array($realif, array("pptp", "pppoe", "openvpn", "enc0" /* , "ppp" */)))
1898
		return "";
1899

    
1900
	$cursn = find_interface_subnet($realif);
1901
	if (!empty($cursn))
1902
		return $cursn;
1903

    
1904
	return null;
1905
}
1906

    
1907
/****f* interfaces/is_altq_capable
1908
 * NAME
1909
 *   is_altq_capable - Test if interface is capable of using ALTQ
1910
 * INPUTS
1911
 *   $int            - string containing interface name
1912
 * RESULT
1913
 *   boolean         - true or false
1914
 ******/
1915

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

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

    
1929
        if (in_array($int_family[0], $capable))
1930
                return true;
1931
        else
1932
                return false;
1933
}
1934

    
1935
function get_wireless_modes($interface) {
1936
	/* return wireless modes and channels */
1937
	$wireless_modes = array();
1938

    
1939
	if(is_interface_wireless($interface)) {
1940
		$wi = 1;
1941
		$ifconfig = "/sbin/ifconfig";
1942
		$awk = "/usr/bin/awk";
1943
		$chan_list = "$ifconfig $interface list chan";
1944
		$stack_list = "$awk -F\"Channel \" '{ gsub(/\\*/, \" \"); print \$2 \"\\\n\" \$3 }'";
1945
		$format_list = "$awk '{print \$5 \" \" \$6 \",\" \$1}'";
1946

    
1947
		$interface_channels = "";
1948
		exec("$chan_list | $stack_list | sort -u | $format_list 2>&1", $interface_channels);
1949
		$interface_channel_count = count($interface_channels);
1950

    
1951
		$c = 0;
1952
		while ($c < $interface_channel_count)
1953
		{
1954
			$channel_line = explode(",", $interface_channels["$c"]);
1955
			$wireless_mode = trim($channel_line[0]);
1956
			$wireless_channel = trim($channel_line[1]);
1957
			if(trim($wireless_mode) != "") {
1958
				/* if we only have 11g also set 11b channels */
1959
				if($wireless_mode == "11g") {
1960
					$wireless_modes["11b"] = array();
1961
				}
1962
				$wireless_modes["$wireless_mode"]["$c"] = $wireless_channel;
1963
			}
1964
			$c++;
1965
		}
1966
	}
1967
	return($wireless_modes);
1968
}
1969

    
1970
function get_interface_mac($interface) {
1971
	/* build interface list with netstat */
1972
	$linkinfo = "";
1973
	exec("/usr/bin/netstat -I $interface -nW -f link", $linkinfo);
1974
	array_shift($linkinfo);
1975
	$alink = preg_split("/\s+/", $linkinfo[0]);
1976
	$mac = chop($alink[3]);
1977
	return $mac;
1978
}
1979

    
1980
function setup_pppoe_reset_file($interface, $status) {
1981
	define("CRON_PPPOE_CMD_FILE", "/conf/pppoe{$interface}restart");
1982
	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");
1983
	if($status == true) {
1984
		if(!file_exists(CRON_PPPOE_CMD_FILE)) {
1985
			file_put_contents(CRON_PPPOE_CMD_FILE, CRON_PPPOE_CMD);
1986
			chmod(CRON_PPPOE_CMD_FILE, 0700);
1987
		}	
1988
	} else {
1989
		unlink_if_exists(CRON_PPPOE_CMD_FILE);
1990
	}
1991
}
1992

    
1993
?>
(16-16/40)