Project

General

Profile

Download (29.6 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/* $Id$ */
3
/*
4
	services.inc
5
	part of m0n0wall (http://m0n0.ch/wall)
6

    
7
	Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
8
	All rights reserved.
9

    
10
	Redistribution and use in source and binary forms, with or without
11
	modification, are permitted provided that the following conditions are met:
12

    
13
	1. Redistributions of source code must retain the above copyright notice,
14
	   this list of conditions and the following disclaimer.
15

    
16
	2. Redistributions in binary form must reproduce the above copyright
17
	   notice, this list of conditions and the following disclaimer in the
18
	   documentation and/or other materials provided with the distribution.
19

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

    
32
/* include all configuration functions */
33
require_once("functions.inc");
34

    
35
function services_dhcpd_configure() {
36
	global $config, $g;
37
	if(isset($config['system']['developerspew'])) {
38
		$mt = microtime();
39
		echo "services_dhcpd_configure($if) being called $mt\n";
40
	}
41

    
42
	/* configure DHCPD chroot */
43
	$fd = fopen("/tmp/dhcpd.sh","w");
44
	$status = `mount | grep "/var/dhcpd/dev"`;
45
	fwrite($fd, "mkdir -p /var/dhcpd/dev\n");
46
	fwrite($fd, "mkdir -p /var/dhcpd\n");
47
	fwrite($fd, "mkdir -p /var/dhcpd/etc\n");
48
	fwrite($fd, "mkdir -p /var/dhcpd/usr/local/sbin\n");
49
	fwrite($fd, "mkdir -p /var/dhcpd/var/db\n");
50
	fwrite($fd, "mkdir -p /var/dhcpd/usr\n");
51
	fwrite($fd, "mkdir -p /var/dhcpd/var/dhcpd\n");
52
	fwrite($fd, "mkdir -p /var/dhcpd/lib\n");
53
	fwrite($fd, "mkdir -p /var/dhcpd/run\n");
54
	fwrite($fd, "chown -R dhcpd:_dhcp /var/dhcpd/*");
55
	fwrite($fd, "cp /lib/libc.so.6 /var/dhcpd/lib/\n");
56
	fwrite($fd, "cp /usr/local/sbin/dhcpd /var/dhcpd\n");
57
	if(!trim($status)) 
58
		fwrite($fd, "mount_devfs devfs /var/dhcpd/dev\n");
59
	fclose($fd);
60
	mwexec("/bin/sh /tmp/dhcpd.sh");
61

    
62
	/* kill any running dhcpd */
63
	mwexec("killall dhcpd");
64

    
65
	$syscfg = $config['system'];
66
	$dhcpdcfg = $config['dhcpd'];
67

    
68
	/* DHCP enabled on any interfaces? */
69
	$dhcpdenable = false;
70
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
71
		if (isset($dhcpifconf['enable']) &&
72
			(($dhcpif == "lan") ||
73
			(isset($config['interfaces'][$dhcpif]['enable']) &&
74
			$config['interfaces'][$dhcpif]['if'] && (!$config['interfaces'][$dhcpif]['bridge']))))
75
			$dhcpdenable = true;
76
	}
77

    
78
	if (!$dhcpdenable)
79
		return 0;
80

    
81
	if ($g['booting'])
82
		echo "Starting DHCP service... ";
83
	else
84
		sleep(1);
85

    
86
	/* write dhcpd.conf */
87
	$fd = fopen("/var/dhcpd/etc/dhcpd.conf", "w");
88
	if (!$fd) {
89
		printf("Error: cannot open dhcpd.conf in services_dhcpd_configure().\n");
90
		return 1;
91
	}
92

    
93
	
94

    
95
	$dhcpdconf = <<<EOD
96
option domain-name "{$syscfg['domain']}";
97
default-lease-time 7200;
98
max-lease-time 86400;
99
authoritative;
100
log-facility local7;
101
ddns-update-style none;
102

    
103
EOD;
104

    
105
	$dhcpdifs = array();
106
	
107
	/*    loop through and deterimine if we need to setup
108
	 *    failover peer "bleh" entries
109
	 */
110
	$dhcpnum = 0;
111
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
112
		if($dhcpifconf['failover_peerip'] <> "") {
113
			/*
114
			 *    yep, failover peer is defined.
115
			 *    does it match up to a defined vip?
116
			 */
117
			$skew = 110;
118
			$a_vip = &$config['virtualip']['vip'];
119
			if(is_array($a_vip)) {
120
				foreach ($a_vip as $vipent) {
121
					$int = guess_interface_from_ip($dhcpifconf['failover_peerip']);
122
					$intip = find_interface_ip($int);
123
					$real_dhcpif = convert_friendly_interface_to_real_interface_name($dhcpif);
124
					if($int == $real_dhcpif) {
125
						/* this is the interface! */
126
						if($vipent['advskew'] == "0")
127
							$skew = 0;
128
					}
129
				}
130
			} else {
131
				log_error("Warning!  DHCP Failover setup and no CARP virtual IP's defined!");
132
			}
133
			if($skew > 10) {
134
				$type = "secondary";
135
				$dhcpdconf_pri  = "mclt 600;\n";
136
				$my_port = "520";
137
				$peer_port = "519";
138
			} else {
139
				$my_port = "519";
140
				$peer_port = "520";
141
				$type = "primary";
142
				$dhcpdconf_pri  = "split 128;\n";
143
				$dhcpdconf_pri .= "  mclt 600;\n";
144
			}
145
			$dhcpdconf .= <<<EOPP
146
failover peer "dhcp{$dhcpnum}" { 
147
  {$type};
148
  address {$intip};
149
  port {$my_port};
150
  peer address {$dhcpifconf['failover_peerip']};
151
  peer port {$peer_port};
152
  max-response-delay 60;
153
  max-unacked-updates 10;
154
  {$dhcpdconf_pri}
155
  load balance max seconds 3;
156
}
157

    
158
EOPP;
159
		$dhcpnum++;
160
		}
161
	}
162

    
163
	$dhcpnum = 0;
164

    
165
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
166

    
167
		$ifcfg = $config['interfaces'][$dhcpif];
168

    
169
		if (!isset($dhcpifconf['enable']) ||
170
			(($dhcpif != "lan") &&
171
			(!isset($ifcfg['enable']) || !$ifcfg['if'] || $ifcfg['bridge'])))
172
			continue;
173

    
174
		$subnet = gen_subnet($ifcfg['ipaddr'], $ifcfg['subnet']);
175
		$subnetmask = gen_subnet_mask($ifcfg['subnet']);
176

    
177
		$dnscfg = "";
178

    
179
		if ($dhcpifconf['domain']) {
180
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
181
		}
182

    
183
		if (is_array($dhcpifconf['dnsserver']) && ($dhcpifconf['dnsserver'][0])) {
184
			$dnscfg .= "	option domain-name-servers " . join(",", $dhcpifconf['dnsserver']) . ";";
185
		} else if (isset($config['dnsmasq']['enable'])) {
186
			$dnscfg .= "	option domain-name-servers " . $ifcfg['ipaddr'] . ";";
187
		} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
188
			$dnscfg .= "	option domain-name-servers " . join(",", $syscfg['dnsserver']) . ";";
189
		}
190

    
191
		$dhcpdconf .= "subnet $subnet netmask $subnetmask {\n";
192
		$dhcpdconf .= "	pool {\n";
193

    
194
		/* is failover dns setup? */
195
		if (is_array($dhcpifconf['dnsserver']) && $dhcpifconf['dnsserver'][0] <> "") {
196
			$dhcpdconf .= "		option domain-name-servers {$dhcpifconf['dnsserver'][0]}";
197
			if($dhcpifconf['dnsserver'][1] <> "")
198
				$dhcpdconf .= ",{$dhcpifconf['dnsserver'][1]}";
199
			$dhcpdconf .= ";\n";
200
		}
201
		
202
		if($dhcpifconf['failover_peerip'] <> "") 
203
			$dhcpdconf .= "		deny dynamic bootp clients;\n";
204
		
205
		if (isset($dhcpifconf['denyunknown']))
206
		   $dhcpdconf .= "		deny unknown clients;\n";
207

    
208
		if ($dhcpifconf['gateway'])
209
			$routers = $dhcpifconf['gateway'];
210
		else
211
			$routers = $ifcfg['ipaddr'];
212

    
213
		if($dhcpifconf['failover_peerip'] <> "") {
214
			$dhcpdconf .= "		failover peer \"dhcp{$dhcpnum}\";\n";
215
			$dhcpnum++;
216
		}
217

    
218
		$dhcpdconf .= <<<EOD
219
		range {$dhcpifconf['range']['from']} {$dhcpifconf['range']['to']};
220
	}
221
	option routers {$routers};
222
$dnscfg
223

    
224
EOD;
225

    
226
		if ($dhcpifconf['defaultleasetime'])
227
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
228
		if ($dhcpifconf['maxleasetime'])
229
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
230

    
231
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
232
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
233
			$dhcpdconf .= "	option netbios-node-type 8;\n";
234
		}
235

    
236
		if ($dhcpifconf['next-server'])
237
			$dhcpdconf .= "	next-server {$dhcpifconf['next-server']};\n";
238
		if ($dhcpifconf['filename'])
239
			$dhcpdconf .= "	filename \"{$dhcpifconf['filename']}\";\n";
240

    
241
		$dhcpdconf .= <<<EOD
242
}
243

    
244
EOD;
245

    
246
		/* add static mappings */
247
		if (is_array($dhcpifconf['staticmap'])) {
248

    
249
			$i = 0;
250
			foreach ($dhcpifconf['staticmap'] as $sm) {
251
				$dhcpdconf .= <<<EOD
252
host s_{$dhcpif}_{$i} {
253
	hardware ethernet {$sm['mac']};
254

    
255
EOD;
256
				if ($sm['ipaddr'])
257
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
258

    
259
				$dhcpdconf .= "}\n";
260
				$i++;
261
			}
262
		}
263

    
264
		$dhcpdifs[] = $ifcfg['if'];
265
	}
266

    
267
	fwrite($fd, $dhcpdconf);
268
	fclose($fd);
269

    
270
	/* create an empty leases database */
271
	touch("/var/dhcpd/var/db/dhcpd.leases");
272

    
273
	/* fire up dhcpd in a chroot */
274
	mwexec("/usr/local/sbin/dhcpd -user dhcpd -group _dhcp -chroot /var/dhcpd -cf /var/dhcpd/etc/dhcpd.conf " .
275
		join(" ", $dhcpdifs));
276

    
277
	if ($g['booting']) {
278
		print "done.\n";
279
	}
280

    
281
	return 0;
282
}
283

    
284
function interfaces_staticarp_configure($if) {
285
	global $config, $g;
286
	if(isset($config['system']['developerspew'])) {
287
		$mt = microtime();
288
		echo "interfaces_staticarp_configure($if) being called $mt\n";
289
	}
290
        
291
        $ifcfg = $config['interfaces'][$if];
292

    
293
        /* Enable staticarp, if enabled */
294
        if(isset($config['dhcpd'][$if]['staticarp'])) {
295
                mwexec("/sbin/ifconfig " . escapeshellarg($ifcfg['if']) . " staticarp " );
296
                mwexec("/usr/sbin/arp -ad > /dev/null 2>&1 ");
297
                if (is_array($config['dhcpd'][$if]['staticmap'])) {
298

    
299
                        foreach ($config['dhcpd'][$if]['staticmap'] as $arpent) {
300
                                mwexec("/usr/sbin/arp -s " . escapeshellarg($arpent['ipaddr']) . " " . escapeshellarg($arpent['mac']));
301

    
302
                        }
303
                        
304
                }
305
        } else {
306
                mwexec("/sbin/ifconfig " . escapeshellarg($ifcfg['if']) . " -staticarp " );
307
                mwexec("/usr/sbin/arp -ad > /dev/null 2>&1 ");
308
        }
309

    
310
        return 0;
311
}
312

    
313
function services_dhcrelay_configure() {
314
	global $config, $g;
315
	if(isset($config['system']['developerspew'])) {
316
		$mt = microtime();
317
		echo "services_dhcrelay_configure() being called $mt\n";
318
	}
319

    
320
	/* kill any running dhcrelay */
321
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
322

    
323
	$dhcrelaycfg = $config['dhcrelay'];
324

    
325
	/* DHCPRelay enabled on any interfaces? */
326
	$dhcrelayenable = false;
327
	if(is_array($dhcrelaycfg)) {
328
		foreach ($dhcrelaycfg as $dhcrelayif => $dhcrelayifconf) {
329
			if (isset($dhcrelayifconf['enable']) &&
330
				(($dhcrelayif == "lan") ||
331
				(isset($config['interfaces'][$dhcrelayif]['enable']) &&
332
				$config['interfaces'][$dhcrelayif]['if'] && (!$config['interfaces'][$dhcrelayif]['bridge']))))
333
				$dhcrelayenable = true;
334
		}
335
	}
336

    
337
	if (!$dhcrelayenable)
338
		return 0;
339

    
340
	if ($g['booting'])
341
		echo "Starting DHCP relay service... ";
342
	else
343
		sleep(1);
344

    
345
	$dhcrelayifs = array();
346
	foreach ($dhcrelaycfg as $dhcrelayif => $dhcrelayifconf) {
347

    
348
		$ifcfg = $config['interfaces'][$dhcrelayif];
349

    
350
		if (!isset($dhcrelayifconf['enable']) ||
351
			(($dhcrelayif != "lan") &&
352
			(!isset($ifcfg['enable']) || !$ifcfg['if'] || $ifcfg['bridge'])))
353
			continue;
354

    
355
		$dhcrelayifs[] = $ifcfg['if'];
356
	}
357

    
358
	/* In order for the relay to work, it needs to be active on the
359
	   interface in which the destination server sits */
360
	foreach ($config['interfaces'] as $ifname) {
361
		$subnet = $ifname['ipaddr'] . "/" . $ifname['subnet'];
362
		if (ip_in_subnet($dhcrelaycfg['server'],$subnet))
363
			$destif = $ifname['if'];
364
	}
365

    
366
	if (!isset($destif))
367
		$destif = $config['interfaces']['wan']['if'];
368

    
369
	$dhcrelayifs[] = $destif;
370
	$dhcrelayifs = array_unique($dhcrelayifs);
371

    
372
	/* fire up dhcrelay */
373
	$cmd = "/usr/local/sbin/dhcrelay -i " .  join(" -i ", $dhcrelayifs);
374

    
375
	if (isset($dhcrelaycfg['agentoption']))
376
		$cmd .=  " -a -m replace";
377

    
378
	$cmd .= " {$dhcrelaycfg['server']}";
379
	mwexec($cmd);
380

    
381
	if (!$g['booting']) {
382
		/* set the reload filter dity flag */
383
		touch("{$g['tmp_path']}/filter_dirty");
384
	}
385

    
386
	return 0;
387
}
388

    
389
function services_dyndns_reset() {
390
	global $config, $g;
391
	if(isset($config['system']['developerspew'])) {
392
		$mt = microtime();
393
		echo "services_dyndns_reset() being called $mt\n";
394
	}
395

    
396
	if (file_exists("{$g['vardb_path']}/ez-ipupdate.cache")) {
397
		conf_mount_rw();
398
		unlink("{$g['vardb_path']}/ez-ipupdate.cache");
399
		conf_mount_ro();
400
	}
401

    
402
	if (file_exists("{$g['conf_path']}/ez-ipupdate.cache")) {
403
		conf_mount_rw();
404
		unlink("{$g['conf_path']}/ez-ipupdate.cache");
405
		conf_mount_ro();
406
	}
407

    
408
	return 0;
409
}
410

    
411
function services_dyndns_configure() {
412
	global $config, $g;
413
	if(isset($config['system']['developerspew'])) {
414
		$mt = microtime();
415
		echo "services_dyndns_configure() being called $mt\n";
416
	}
417

    
418
	$dyndnscfg = $config['dyndns'];
419
	$wancfg = $config['interfaces']['wan'];
420

    
421
	if (isset($dyndnscfg['enable'])) {
422

    
423
		if ($g['booting']) {
424
			echo "Starting DynDNS client... ";
425
			if(isset($config['system']['use_old_dyndns'])) {
426
				echo " [Using ez-ipupdate] ";
427
				services_dyndns_configure_old();
428
				return;
429
			}	
430
		} else {
431
			sleep(1);
432
			if(isset($config['system']['use_old_dyndns'])) {
433
				services_dyndns_configure_old();
434
				return;
435
			}			
436
		}
437
		
438
		/* load up the dyndns.class */
439
		require_once("dyndns.class");
440

    
441
		log_error("DynDns: Running updatedns()");
442

    
443
		$dns = new updatedns($dnsService = $config['dyndns']['type'],
444
							 $dnsHost = $config['dyndns']['host'],
445
							 $dnsUser = $config['dyndns']['username'],
446
							 $dnsPass = $config['dyndns']['password'],
447
							 $dnsWilcard = $config['dyndns']['wildcard'],
448
							 $dnsMX = $config['dyndns']['mx']);
449

    
450
		if ($g['booting'])
451
			echo "done.\n";
452
	}
453

    
454
	return 0;
455
}
456

    
457
function services_dyndns_configure_old() {
458
	global $config, $g;
459
	if(isset($config['system']['developerspew'])) {
460
		$mt = microtime();
461
		echo "services_dyndns_configure_old() being called $mt\n";
462
	}
463

    
464
        /* kill any running ez-ipupdate */
465
        /* ez-ipupdate needs SIGQUIT instead of SIGTERM */
466
        sigkillbypid("{$g['varrun_path']}/ez-ipupdate.pid", "QUIT");
467

    
468
        $dyndnscfg = $config['dyndns'];
469
        $wancfg = $config['interfaces']['wan'];
470

    
471
        if (isset($dyndnscfg['enable'])) {
472

    
473
                if ($g['booting'])
474
                        echo "Starting DynDNS client... ";
475
                else
476
                        sleep(1);
477

    
478
                /* determine WAN interface name */
479
                $wanif = get_real_wan_interface();
480

    
481
                /* write ez-ipupdate.conf */
482
                $fd = fopen("{$g['varetc_path']}/ez-ipupdate.conf", "w");
483
                if (!$fd) {
484
                        printf("Error: cannot open ez-ipupdate.conf in services_dyndns_configure().\n");
485
                        return 1;
486
                }
487

    
488
                $ezipupdateconf = <<<EOD
489
service-type={$dyndnscfg['type']}
490
user={$dyndnscfg['username']}:{$dyndnscfg['password']}
491
host={$dyndnscfg['host']}
492
interface={$wanif}
493
max-interval=2073600
494
pid-file={$g['varrun_path']}/ez-ipupdate.pid
495
cache-file={$g['vardb_path']}/ez-ipupdate.cache
496
execute=/etc/rc.dyndns.storecache
497
daemon
498

    
499
EOD;
500

    
501
                /* enable server[:port]? */
502
                if ($dyndnscfg['server']) {
503
                        if ($dyndnscfg['port'])
504
                                $ezipupdateconf .= "server={$dyndnscfg['server']}:{$dyndnscfg['port']}\n";
505
                        else
506
                                $ezipupdateconf .= "server={$dyndnscfg['server']}\n";
507
                }
508

    
509
                /* enable MX? */
510
                if ($dyndnscfg['mx']) {
511
                        $ezipupdateconf .= "mx={$dyndnscfg['mx']}\n";
512
                }
513

    
514
                /* enable wildcards? */
515
                if (isset($dyndnscfg['wildcard'])) {
516
                        $ezipupdateconf .= "wildcard\n";
517
                }
518

    
519
                fwrite($fd, $ezipupdateconf);
520
                fclose($fd);
521

    
522
                /* if we're booting, copy the cache file from /conf */
523
                if ($g['booting']) {
524
                        if (file_exists("{$g['conf_path']}/ez-ipupdate.cache")) {
525
                                copy("{$g['conf_path']}/ez-ipupdate.cache", "{$g['vardb_path']}/ez-ipupdate.cache");
526
                       }
527
                }
528

    
529
                /* run ez-ipupdate */
530
                mwexec("/usr/local/bin/ez-ipupdate -c {$g['varetc_path']}/ez-ipupdate.conf");
531

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

    
536
        return 0;
537
}
538

    
539
function services_dnsmasq_configure() {
540
	global $config, $g;
541
	if(isset($config['system']['developerspew'])) {
542
		$mt = microtime();
543
		echo "services_dnsmasq_configure() being called $mt\n";
544
	}
545

    
546
	/* kill any running dnsmasq */
547
	sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
548

    
549
	if (isset($config['dnsmasq']['enable'])) {
550

    
551
		if ($g['booting'])
552
			echo "Starting DNS forwarder... ";
553
		else
554
			sleep(1);
555

    
556
		/* generate hosts file */
557
		system_hosts_generate();
558

    
559
		$args = "";
560

    
561
		if (isset($config['dnsmasq']['regdhcp'])) {
562

    
563
			$args .= " -l {$g['vardb_path']}/dhcpd.leases" .
564
				" -s {$config['system']['domain']}";
565
		}
566

    
567
                if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
568
                        foreach($config['dnsmasq']['domainoverrides'] as $override) {
569
                                $args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
570
                        }
571
                }
572

    
573
		/* run dnsmasq */
574
		mwexec("/usr/local/sbin/dnsmasq {$args}");
575

    
576
		if ($g['booting'])
577
			echo "done.\n";
578
	}
579

    
580
	if (!$g['booting']) {
581
		services_dhcpd_configure();
582
	}
583

    
584
	return 0;
585
}
586

    
587
function services_snmpd_configure() {
588
	global $config, $g;
589
	if(isset($config['system']['developerspew'])) {
590
		$mt = microtime();
591
		echo "services_snmpd_configure() being called $mt\n";
592
	}
593

    
594
	/* kill any running snmpd */
595
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
596

    
597
	if (isset($config['snmpd']['enable'])) {
598

    
599
		if ($g['booting'])
600
			echo "Starting SNMP daemon... ";
601

    
602
		/* generate snmpd.conf */
603
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
604
		if (!$fd) {
605
			printf("Error: cannot open snmpd.conf in services_snmpd_configure().\n");
606
			return 1;
607
		}
608

    
609

    
610
		$snmpdconf = <<<EOD
611
location := "{$config['snmpd']['syslocation']}"
612
contact := "{$config['snmpd']['syscontact']}"
613
read := "{$config['snmpd']['rocommunity']}"
614

    
615
EOD;
616

    
617
/* No docs on what write strings do there for disable for now.
618
		if(isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])){
619
		    $snmpdconf .= <<<EOD
620
# write string
621
write := "{$config['snmpd']['rwcommunity']}"
622

    
623
EOD;
624
		}
625
*/
626

    
627

    
628
		if(isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])){
629
		    $snmpdconf .= <<<EOD
630
# SNMP Trap support.
631
traphost := {$config['snmpd']['trapserver']}
632
trapport := {$config['snmpd']['trapserverport']}
633
trap := "{$config['snmpd']['trapstring']}"
634

    
635

    
636
EOD;
637
		}
638

    
639

    
640
		$snmpdconf .= <<<EOD
641
system := 1     # pfSense
642
%snmpd
643
begemotSnmpdDebugDumpPdus       = 2
644
begemotSnmpdDebugSyslogPri      = 7
645
begemotSnmpdCommunityString.0.1 = $(read)
646

    
647
EOD;
648

    
649
/* No docs on what write strings do there for disable for now.
650
		if(isset($config['snmpd']['rwcommunity']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])){
651
		    $snmpdconf .= <<<EOD
652
begemotSnmpdCommunityString.0.2 = $(write)
653

    
654
EOD;
655
		}
656
*/
657

    
658
		
659
		if(isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])){
660
		    $snmpdconf .= <<<EOD
661
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
662
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
663
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
664

    
665
EOD;
666
		}
667

    
668

    
669
		$snmpdconf .= <<<EOD
670
begemotSnmpdCommunityDisable    = 1
671

    
672
EOD;
673

    
674
		if(isset($config['snmpd']['bindlan'])) {
675
			$bind_to_ip = $config['interfaces']['lan']['ipaddr'];
676
		} else {
677
			$bind_to_ip = "0.0.0.0";
678
		}
679

    
680
		if(is_port( $config['snmpd']['pollport'] )) {
681
		    $snmpdconf .= <<<EOD
682
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
683

    
684
EOD;
685

    
686
		}
687

    
688
		$snmpdconf .= <<<EOD
689
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
690
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
691

    
692
# These are bsnmp macros not php vars.
693
sysContact      = $(contact)
694
sysLocation     = $(location)
695
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
696

    
697
snmpEnableAuthenTraps = 2
698

    
699
EOD;
700

    
701
		if (is_array( $config['snmpd']['modules'] )) {
702
		    if(isset($config['snmpd']['modules']['mibii'])) {
703
			$snmpdconf .= <<<EOD
704
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
705

    
706
EOD;
707
		    }
708

    
709
		    if(isset($config['snmpd']['modules']['netgraph'])) {
710
			$snmpdconf .= <<<EOD
711
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
712
%netgraph
713
begemotNgControlNodeName = "snmpd"
714

    
715
EOD;
716
		    }
717

    
718
		    if(isset($config['snmpd']['modules']['pf'])) {
719
			$snmpdconf .= <<<EOD
720
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
721
# config must end with blank line
722

    
723

    
724
EOD;
725
		    }
726
		}
727

    
728
		fwrite($fd, $snmpdconf);
729
		fclose($fd);
730

    
731
		if (isset($config['snmpd']['bindlan'])) {
732
			$bindlan = "";
733
		}
734

    
735
		/* run bsnmpd */
736
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
737
			"{$bindlan} -p {$g['varrun_path']}/snmpd.pid");
738

    
739
		if ($g['booting'])
740
			echo "done.\n";
741
	}
742

    
743
	return 0;
744
}
745

    
746
function services_proxyarp_configure() {
747
	global $config, $g;
748
	if(isset($config['system']['developerspew'])) {
749
		$mt = microtime();
750
		echo "services_proxyarp_configure() being called $mt\n";
751
	}
752

    
753
	/* kill any running choparp */
754
	killbyname("choparp");
755

    
756
	if (isset($config['virtualip']) && is_array($config['virtualip']['vip'])) {
757
		$paa = array();
758

    
759
		/* group by interface */
760
		foreach ($config['virtualip']['vip'] as $vipent) {
761
			if ($vipent['mode'] === "proxyarp") {
762
				if ($vipent['interface'])
763
					$if = $vipent['interface'];
764
				else
765
					$if = "wan";
766

    
767
				if (!is_array($paa[$if]))
768
					$paa[$if] = array();
769

    
770
				$paa[$if][] = $vipent;
771
			}
772
		}
773

    
774
		if (count($paa))
775
		foreach ($paa as $paif => $paents) {
776
			if ($paif == "wan" && !(is_ipaddr($config['interfaces']['wan']['ipaddr']) ||
777
                                       ($config['interfaces']['wan']['ipaddr'] == "dhcp") ||
778
                                       ($config['interfaces']['wan']['ipaddr'] == "bigpond")))
779
                               continue;
780

    
781
			$args = $config['interfaces'][$paif]['if'] . " auto";
782

    
783
			foreach ($paents as $paent) {
784

    
785
				if (isset($paent['subnet']))
786
					$args .= " " . escapeshellarg("{$paent['subnet']}/{$paent['subnet_bits']}");
787
				else if (isset($paent['range']))
788
					$args .= " " . escapeshellarg($paent['range']['from'] . "-" .
789
						$paent['range']['to']);
790
			}
791

    
792
			mwexec_bg("/usr/local/sbin/choparp " . $args);
793
		}
794
	}
795
}
796

    
797
function services_dnsupdate_process() {
798
	global $config, $g;
799
	if(isset($config['system']['developerspew'])) {
800
		$mt = microtime();
801
		echo "services_dnsupdate_process() being called $mt\n";
802
	}
803

    
804
	/* Dynamic DNS updating active? */
805
	if (isset($config['dnsupdate']['enable'])) {
806
		
807
		$wanip = get_current_wan_address();
808
		if ($wanip) {
809
			
810
			$keyname = $config['dnsupdate']['keyname'];
811
			/* trailing dot */
812
			if (substr($keyname, -1) != ".")
813
				$keyname .= ".";
814
			
815
			$hostname = $config['dnsupdate']['host'];
816
			/* trailing dot */
817
			if (substr($hostname, -1) != ".")
818
				$hostname .= ".";
819
			
820
			/* write private key file
821
			   this is dumb - public and private keys are the same for HMAC-MD5,
822
			   but nsupdate insists on having both */
823
			$fd = fopen("{$g['varetc_path']}/K{$keyname}+157+00000.private", "w");
824
			$privkey .= <<<EOD
825
Private-key-format: v1.2
826
Algorithm: 157 (HMAC)
827
Key: {$config['dnsupdate']['keydata']}
828

    
829
EOD;
830
			fwrite($fd, $privkey);
831
			fclose($fd);
832
			
833
			/* write public key file */
834
			if ($config['dnsupdate']['keytype'] == "zone") {
835
				$flags = 257;
836
				$proto = 3;
837
			} else if ($config['dnsupdate']['keytype'] == "host") {
838
				$flags = 513;
839
				$proto = 3;
840
			} else if ($config['dnsupdate']['keytype'] == "user") {
841
				$flags = 0;
842
				$proto = 2;
843
			}
844
			
845
			$fd = fopen("{$g['varetc_path']}/K{$keyname}+157+00000.key", "w");
846
			fwrite($fd, "{$keyname} IN KEY {$flags} {$proto} 157 {$config['dnsupdate']['keydata']}\n");
847
			fclose($fd);
848
			
849
			/* generate update instructions */
850
			$upinst =  "update delete {$config['dnsupdate']['host']} A\n";
851
			$upinst .= "update add {$config['dnsupdate']['host']} {$config['dnsupdate']['ttl']} A {$wanip}\n";
852
			$upinst .= "\n";	/* mind that trailing newline! */
853
			
854
			$fd = fopen("{$g['varetc_path']}/nsupdatecmds", "w");
855
			fwrite($fd, $upinst);
856
			fclose($fd);
857
			
858
			/* invoke nsupdate */
859
			$cmd = "/usr/sbin/nsupdate -k {$g['varetc_path']}/K{$keyname}+157+00000.key";
860
			if (isset($config['dnsupdate']['usetcp']))
861
				$cmd .= " -v";
862
			$cmd .= " {$g['varetc_path']}/nsupdatecmds";
863
			
864
			mwexec_bg($cmd);
865
		}
866
	}
867
	
868
	return 0;
869
}
870

    
871
function setup_wireless_olsr($interface) {
872
	global $config, $g;
873
	if(isset($config['system']['developerspew'])) {
874
		$mt = microtime();
875
		echo "setup_wireless_olsr($interface) being called $mt\n";
876
	}
877
	$fd = fopen("{$g['varetc_path']}/{$interface}_olsr.conf", "w");
878
	$olsr .= <<<EOD
879
#
880
# olsr.org OLSR daemon config file
881
#
882
# Lines starting with a # are discarded
883
#
884
# This file was shipped with olsrd 0.X.X
885
#
886

    
887
# This file is an example of a typical
888
# configuration for a mostly static
889
# network(regarding mobility) using
890
# the LQ extention
891

    
892
# Debug level(0-9)
893
# If set to 0 the daemon runs in the background
894

    
895
DebugLevel	2
896

    
897
# IP version to use (4 or 6)
898

    
899
IpVersion	4
900

    
901
# Clear the screen each time the internal state changes
902

    
903
ClearScreen     yes
904

    
905
# HNA IPv4 routes
906
# syntax: netaddr netmask
907
# Example Internet gateway:
908
# 0.0.0.0 0.0.0.0
909

    
910
Hna4
911
{
912
#   Internet gateway:
913
#   0.0.0.0      0.0.0.0
914
#   more entries can be added:
915
#   192.168.1.0  255.255.255.0
916
}
917

    
918
# HNA IPv6 routes
919
# syntax: netaddr prefix
920
# Example Internet gateway:
921
Hna6
922
{
923
#   Internet gateway:
924
#   ::              0
925
#   more entries can be added:
926
#   fec0:2200:106:: 48
927
}
928

    
929

    
930
# Should olsrd keep on running even if there are
931
# no interfaces available? This is a good idea
932
# for a PCMCIA/USB hotswap environment.
933
# "yes" OR "no"
934

    
935
AllowNoInt	yes
936

    
937
# TOS(type of service) value for
938
# the IP header of control traffic.
939
# If not set it will default to 16
940

    
941
#TosValue	16
942

    
943
# The fixed willingness to use(0-7)
944
# If not set willingness will be calculated
945
# dynamically based on battery/power status
946
# if such information is available
947

    
948
#Willingness    	4
949

    
950
# Allow processes like the GUI front-end
951
# to connect to the daemon.
952

    
953
IpcConnect
954
{
955
     # Determines how many simultaneously
956
     # IPC connections that will be allowed
957
     # Setting this to 0 disables IPC
958

    
959
     MaxConnections  0
960

    
961
     # By default only 127.0.0.1 is allowed
962
     # to connect. Here allowed hosts can
963
     # be added
964

    
965
     Host            127.0.0.1
966
     #Host            10.0.0.5
967

    
968
     # You can also specify entire net-ranges 
969
     # that are allowed to connect. Multiple
970
     # entries are allowed
971

    
972
     #Net             192.168.1.0 255.255.255.0     
973
}
974

    
975
# Wether to use hysteresis or not
976
# Hysteresis adds more robustness to the
977
# link sensing but delays neighbor registration.
978
# Used by default. 'yes' or 'no'
979

    
980
UseHysteresis	no
981

    
982
# Hysteresis parameters
983
# Do not alter these unless you know 
984
# what you are doing!
985
# Set to auto by default. Allowed
986
# values are floating point values
987
# in the interval 0,1
988
# THR_LOW must always be lower than
989
# THR_HIGH.
990

    
991
#HystScaling	0.50
992
#HystThrHigh	0.80
993
#HystThrLow	0.30
994

    
995

    
996
# Link quality level
997
# 0 = do not use link quality
998
# 1 = use link quality for MPR selection
999
# 2 = use link quality for MPR selection and routing
1000
# Defaults to 0
1001

    
1002
LinkQualityLevel	2
1003

    
1004
# Link quality window size
1005
# Defaults to 10
1006

    
1007
LinkQualityWinSize	10
1008

    
1009
# Polling rate in seconds(float). 
1010
# Default value 0.05 sec
1011

    
1012
Pollrate	0.05
1013

    
1014

    
1015
# TC redundancy
1016
# Specifies how much neighbor info should
1017
# be sent in TC messages
1018
# Possible values are:
1019
# 0 - only send MPR selectors
1020
# 1 - send MPR selectors and MPRs
1021
# 2 - send all neighbors
1022
#
1023
# defaults to 0
1024

    
1025
TcRedundancy	2
1026

    
1027

    
1028
#
1029
# MPR coverage
1030
# Specifies how many MPRs a node should
1031
# try select to reach every 2 hop neighbor
1032
#
1033
# Can be set to any integer >0
1034
#
1035
# defaults to 1
1036

    
1037
MprCoverage	3
1038

    
1039

    
1040
# Olsrd plugins to load
1041
# This must be the absolute path to the file
1042
# or the loader will use the following scheme:
1043
# - Try the paths in the LD_LIBRARY_PATH 
1044
#   environment variable.
1045
# - The list of libraries cached in /etc/ld.so.cache
1046
# - /lib, followed by /usr/lib
1047

    
1048
# Example plugin entry with parameters:
1049

    
1050
#LoadPlugin "olsrd_dyn_gw.so.0.3"
1051
#{
1052
    # Here parameters are set to be sent to the
1053
    # plugin. Theese are on the form "key" "value".
1054
    # Parameters ofcause, differs from plugin to plugin.
1055
    # Consult the documentation of your plugin for details.
1056

    
1057
    # Example: dyn_gw params
1058

    
1059
    # how often to check for Internet connectivity
1060
    # defaults to 5 secs
1061
#   PlParam     "Interval"   "40"
1062
    
1063
    # if one or more IPv4 addresses are given, do a ping on these in
1064
    # descending order to validate that there is not only an entry in
1065
    # routing table, but also a real internet connection. If any of
1066
    # these addresses could be pinged successfully, the test was
1067
    # succesful, i.e. if the ping on the 1st address was successful,the
1068
    # 2nd won't be pinged
1069
#   PlParam     "Ping"       "141.1.1.1"
1070
#   PlParam     "Ping"       "194.25.2.129"
1071
#}
1072

    
1073

    
1074

    
1075
# Interfaces and their rules
1076
# Omitted options will be set to the
1077
# default values. Multiple interfaces
1078
# can be specified in the same block
1079
# and multiple blocks can be set.
1080

    
1081
# !!CHANGE THE INTERFACE LABEL(s) TO MATCH YOUR INTERFACE(s)!!
1082
# (eg. wlan0 or eth1):
1083

    
1084
Interface "{$interface}" 
1085
{
1086

    
1087
    # IPv4 broadcast address to use. The
1088
    # one usefull example would be 255.255.255.255
1089
    # If not defined the broadcastaddress
1090
    # every card is configured with is used
1091

    
1092
    # Ip4Broadcast		255.255.255.255
1093

    
1094
    # IPv6 address scope to use.
1095
    # Must be 'site-local' or 'global'
1096

    
1097
    # Ip6AddrType		site-local
1098

    
1099
    # IPv6 multicast address to use when
1100
    # using site-local addresses.
1101
    # If not defined, ff05::15 is used
1102

    
1103
    # Ip6MulticastSite		ff05::11
1104

    
1105
    # IPv6 multicast address to use when
1106
    # using global addresses
1107
    # If not defined, ff0e::1 is used
1108

    
1109
    # Ip6MulticastGlobal	ff0e::1
1110

    
1111

    
1112
    # Emission intervals.
1113
    # If not defined, RFC proposed values will
1114
    # be used in most cases.
1115

    
1116
    # Hello interval in seconds(float)
1117
    HelloInterval    2.0
1118

    
1119
    # HELLO validity time
1120
    HelloValidityTime	20.0
1121

    
1122
    # TC interval in seconds(float)
1123
    TcInterval        5.0
1124

    
1125
    # TC validity time
1126
    TcValidityTime	30.0
1127

    
1128
    # MID interval in seconds(float)
1129
    MidInterval	5.0
1130

    
1131
    # MID validity time
1132
    MidValidityTime	30.0
1133

    
1134
    # HNA interval in seconds(float)
1135
    HnaInterval	5.0
1136

    
1137
    # HNA validity time
1138
    HnaValidityTime 	30.0
1139

    
1140
    # When multiple links exist between hosts
1141
    # the weight of interface is used to determine
1142
    # the link to use. Normally the weight is
1143
    # automatically calculated by olsrd based
1144
    # on the characteristics of the interface,
1145
    # but here you can specify a fixed value.
1146
    # Olsrd will choose links with the lowest value.
1147

    
1148
    # Weight 0
1149

    
1150

    
1151
}
1152
EOD;
1153
	fwrite($fd, $olsr);
1154
	fclose($fd);
1155
	mwexec_bg("/usr/local/sbin/olsrd -f {$g['varetc_path']}/{$interface}_olsr.conf");
1156
}
1157

    
1158
?>
(18-18/27)