Project

General

Profile

Download (30.4 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
	/* if OLSRD is enabled, allow WAN to house DHCP. */
43
	if($config['installedpackages']['olsrd'])
44
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd)
45
				if($olsrd['enable'])
46
					$is_olsr_enabled = true;
47

    
48
	/* configure DHCPD chroot */
49
	$fd = fopen("/tmp/dhcpd.sh","w");
50
	$status = `mount | grep "{$g['dhcpd_chroot_path']}/dev"`;
51
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}\n");
52
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/dev\n");
53
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/etc\n");
54
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/usr/local/sbin\n");
55
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/var/db\n");
56
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/usr\n");
57
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/lib\n");
58
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/run\n");
59
	fwrite($fd, "chown -R dhcpd:_dhcp {$g['dhcpd_chroot_path']}/*\n");
60
	fwrite($fd, "cp /lib/libc.so.6 {$g['dhcpd_chroot_path']}/lib/\n");
61
	fwrite($fd, "cp /usr/local/sbin/dhcpd {$g['dhcpd_chroot_path']}/usr/local/sbin/\n");
62
	fwrite($fd, "chmod a+rx {$g['dhcpd_chroot_path']}/usr/local/sbin/dhcpd\n");
63
	if(!trim($status))
64
		fwrite($fd, "mount_devfs devfs {$g['dhcpd_chroot_path']}/dev\n");
65
	fclose($fd);
66
	mwexec("/bin/sh /tmp/dhcpd.sh");
67

    
68
	/* kill any running dhcpd */
69
	mwexec("killall dhcpd");
70

    
71
	$syscfg = $config['system'];
72
	$dhcpdcfg = $config['dhcpd'];
73

    
74
	/* DHCP enabled on any interfaces? */
75
	$dhcpdenable = false;
76
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
77
		if (isset($dhcpifconf['enable']) &&
78
			(($dhcpif == "lan") ||
79
			(isset($config['interfaces'][$dhcpif]['enable']) &&
80
			$config['interfaces'][$dhcpif]['if'] && (!$config['interfaces'][$dhcpif]['bridge']))))
81
			$dhcpdenable = true;
82
		if (isset($dhcpifconf['enable']) &&
83
			(($dhcpif == "wan") || (isset($config['interfaces'][$dhcpif]['enable']) &&
84
			$config['interfaces'][$dhcpif]['if'] && (!$config['interfaces'][$dhcpif]['bridge']))))
85
			$dhcpdenable = true;
86
	}
87

    
88
	if (!$dhcpdenable)
89
		return 0;
90

    
91
	if ($g['booting'])
92
		echo "Starting DHCP service... ";
93
	else
94
		sleep(1);
95

    
96
	/* write dhcpd.conf */
97
	$fd = fopen("{$g['dhcpd_chroot_path']}/etc/dhcpd.conf", "w");
98
	if (!$fd) {
99
		printf("Error: cannot open dhcpd.conf in services_dhcpd_configure().\n");
100
		return 1;
101
	}
102

    
103

    
104

    
105
	$dhcpdconf = <<<EOD
106
option domain-name "{$syscfg['domain']}";
107
default-lease-time 7200;
108
max-lease-time 86400;
109
authoritative;
110
log-facility local7;
111
ddns-update-style none;
112
one-lease-per-client true;
113
deny duplicates;
114

    
115
EOD;
116

    
117
	$dhcpdifs = array();
118

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

    
170
EOPP;
171
		$dhcpnum++;
172
		}
173
	}
174

    
175
	$dhcpnum = 0;
176

    
177
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
178

    
179
		$ifcfg = $config['interfaces'][$dhcpif];
180

    
181
		if (!isset($dhcpifconf['enable']) ||
182
			(($dhcpif != "lan") &&
183
			(!isset($ifcfg['enable']) || !$ifcfg['if'] || $ifcfg['bridge'])))
184
			continue;
185

    
186
		$subnet = gen_subnet($ifcfg['ipaddr'], $ifcfg['subnet']);
187
		$subnetmask = gen_subnet_mask($ifcfg['subnet']);
188

    
189
		if($is_olsr_enabled == true)
190
			if($dhcpifconf['netmask'])
191
				$subnetmask = gen_subnet_mask($dhcpifconf['netmask']);
192

    
193
		$dnscfg = "";
194

    
195
		if ($dhcpifconf['domain']) {
196
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
197
		}
198

    
199
		if (is_array($dhcpifconf['dnsserver']) && ($dhcpifconf['dnsserver'][0])) {
200
			$dnscfg .= "	option domain-name-servers " . join(",", $dhcpifconf['dnsserver']) . ";";
201
		} else if (isset($config['dnsmasq']['enable'])) {
202
			$dnscfg .= "	option domain-name-servers " . $ifcfg['ipaddr'] . ";";
203
		} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
204
			$dnscfg .= "	option domain-name-servers " . join(",", $syscfg['dnsserver']) . ";";
205
		}
206

    
207
		$dhcpdconf .= "subnet $subnet netmask $subnetmask {\n";
208
		$dhcpdconf .= "	pool {\n";
209

    
210
		/* is failover dns setup? */
211
		if (is_array($dhcpifconf['dnsserver']) && $dhcpifconf['dnsserver'][0] <> "") {
212
			$dhcpdconf .= "		option domain-name-servers {$dhcpifconf['dnsserver'][0]}";
213
			if($dhcpifconf['dnsserver'][1] <> "")
214
				$dhcpdconf .= ",{$dhcpifconf['dnsserver'][1]}";
215
			$dhcpdconf .= ";\n";
216
		}
217

    
218
		if($dhcpifconf['failover_peerip'] <> "")
219
			$dhcpdconf .= "		deny dynamic bootp clients;\n";
220

    
221
		if (isset($dhcpifconf['denyunknown']))
222
		   $dhcpdconf .= "		deny unknown clients;\n";
223

    
224
		if ($dhcpifconf['gateway'])
225
			$routers = $dhcpifconf['gateway'];
226
		else
227
			$routers = $ifcfg['ipaddr'];
228

    
229
		if($dhcpifconf['failover_peerip'] <> "") {
230
			$dhcpdconf .= "		failover peer \"dhcp{$dhcpnum}\";\n";
231
			$dhcpnum++;
232
		}
233

    
234
		$dhcpdconf .= <<<EOD
235
		range {$dhcpifconf['range']['from']} {$dhcpifconf['range']['to']};
236
	}
237
	option routers {$routers};
238
$dnscfg
239

    
240
EOD;
241

    
242
		if ($dhcpifconf['defaultleasetime'])
243
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
244
		if ($dhcpifconf['maxleasetime'])
245
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
246

    
247
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
248
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
249
			$dhcpdconf .= "	option netbios-node-type 8;\n";
250
		}
251

    
252
		if ($dhcpifconf['next-server'])
253
			$dhcpdconf .= "	next-server {$dhcpifconf['next-server']};\n";
254
		if ($dhcpifconf['filename'])
255
			$dhcpdconf .= "	filename \"{$dhcpifconf['filename']}\";\n";
256

    
257
		$dhcpdconf .= <<<EOD
258
}
259

    
260
EOD;
261

    
262
		/* add static mappings */
263
		if (is_array($dhcpifconf['staticmap'])) {
264

    
265
			$i = 0;
266
			foreach ($dhcpifconf['staticmap'] as $sm) {
267
				$dhcpdconf .= <<<EOD
268
host s_{$dhcpif}_{$i} {
269
	hardware ethernet {$sm['mac']};
270

    
271
EOD;
272
				if ($sm['ipaddr'])
273
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
274

    
275
				$dhcpdconf .= "}\n";
276
				$i++;
277
			}
278
		}
279

    
280
		$dhcpdifs[] = $ifcfg['if'];
281
	}
282

    
283
	fwrite($fd, $dhcpdconf);
284
	fclose($fd);
285

    
286
	/* create an empty leases database */
287
	touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
288

    
289
	/* fire up dhcpd in a chroot */
290
	mwexec("/usr/local/sbin/dhcpd -user dhcpd -group _dhcp -chroot {$g['dhcpd_chroot_path']} -cf {$g['dhcpd_chroot_path']}/etc/dhcpd.conf " .
291
		join(" ", $dhcpdifs));
292

    
293
	if ($g['booting']) {
294
		print "done.\n";
295
	}
296

    
297
	return 0;
298
}
299

    
300
function interfaces_staticarp_configure($if) {
301
	global $config, $g;
302
	if(isset($config['system']['developerspew'])) {
303
		$mt = microtime();
304
		echo "interfaces_staticarp_configure($if) being called $mt\n";
305
	}
306

    
307
        $ifcfg = $config['interfaces'][$if];
308

    
309
        /* Enable staticarp, if enabled */
310
        if(isset($config['dhcpd'][$if]['staticarp'])) {
311
                mwexec("/sbin/ifconfig " . escapeshellarg($ifcfg['if']) . " staticarp " );
312
                mwexec("/usr/sbin/arp -ad > /dev/null 2>&1 ");
313
                if (is_array($config['dhcpd'][$if]['staticmap'])) {
314

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

    
318
                        }
319

    
320
                }
321
        } else {
322
                mwexec("/sbin/ifconfig " . escapeshellarg($ifcfg['if']) . " -staticarp " );
323
                mwexec("/usr/sbin/arp -da > /dev/null 2>&1 ");
324
        }
325

    
326
        return 0;
327
}
328

    
329
function services_dhcrelay_configure() {
330
	global $config, $g;
331
	if(isset($config['system']['developerspew'])) {
332
		$mt = microtime();
333
		echo "services_dhcrelay_configure() being called $mt\n";
334
	}
335

    
336
	/* kill any running dhcrelay */
337
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
338

    
339
	$dhcrelaycfg = $config['dhcrelay'];
340

    
341
	/* DHCPRelay enabled on any interfaces? */
342
	$dhcrelayenable = false;
343
	if(is_array($dhcrelaycfg)) {
344
		foreach ($dhcrelaycfg as $dhcrelayif => $dhcrelayifconf) {
345
			if (isset($dhcrelayifconf['enable']) &&
346
				(($dhcrelayif == "lan") ||
347
				(isset($config['interfaces'][$dhcrelayif]['enable']) &&
348
				$config['interfaces'][$dhcrelayif]['if'] && (!$config['interfaces'][$dhcrelayif]['bridge']))))
349
				$dhcrelayenable = true;
350
		}
351
	}
352

    
353
	if (!$dhcrelayenable)
354
		return 0;
355

    
356
	if ($g['booting'])
357
		echo "Starting DHCP relay service... ";
358
	else
359
		sleep(1);
360

    
361
	$dhcrelayifs = array();
362
	foreach ($dhcrelaycfg as $dhcrelayif => $dhcrelayifconf) {
363

    
364
		$ifcfg = $config['interfaces'][$dhcrelayif];
365

    
366
		if (!isset($dhcrelayifconf['enable']) ||
367
			(($dhcrelayif != "lan") &&
368
			(!isset($ifcfg['enable']) || !$ifcfg['if'] || $ifcfg['bridge'])))
369
			continue;
370

    
371
		$dhcrelayifs[] = $ifcfg['if'];
372
	}
373

    
374
	/* In order for the relay to work, it needs to be active on the
375
	   interface in which the destination server sits */
376
	foreach ($config['interfaces'] as $ifname) {
377
		$subnet = $ifname['ipaddr'] . "/" . $ifname['subnet'];
378
		if (ip_in_subnet($dhcrelaycfg['server'],$subnet))
379
			$destif = $ifname['if'];
380
	}
381

    
382
	if (!isset($destif))
383
		$destif = $config['interfaces']['wan']['if'];
384

    
385
	$dhcrelayifs[] = $destif;
386
	$dhcrelayifs = array_unique($dhcrelayifs);
387

    
388
	/* fire up dhcrelay */
389
	$cmd = "/usr/local/sbin/dhcrelay -i " .  join(" -i ", $dhcrelayifs);
390

    
391
	if (isset($dhcrelaycfg['agentoption']))
392
		$cmd .=  " -a -m replace";
393

    
394
	$cmd .= " {$dhcrelaycfg['server']}";
395
	mwexec($cmd);
396

    
397
	if (!$g['booting']) {
398
		/* set the reload filter dity flag */
399
		touch("{$g['tmp_path']}/filter_dirty");
400
	}
401

    
402
	return 0;
403
}
404

    
405
function services_dyndns_reset() {
406
	global $config, $g;
407
	if(isset($config['system']['developerspew'])) {
408
		$mt = microtime();
409
		echo "services_dyndns_reset() being called $mt\n";
410
	}
411

    
412
	if (file_exists("{$g['vardb_path']}/ez-ipupdate.cache")) {
413
		conf_mount_rw();
414
		unlink("{$g['vardb_path']}/ez-ipupdate.cache");
415
		conf_mount_ro();
416
	}
417

    
418
	if (file_exists("{$g['conf_path']}/ez-ipupdate.cache")) {
419
		conf_mount_rw();
420
		unlink("{$g['conf_path']}/ez-ipupdate.cache");
421
		conf_mount_ro();
422
	}
423

    
424
	return 0;
425
}
426

    
427
function services_dyndns_configure() {
428
	global $config, $g;
429
	if(isset($config['system']['developerspew'])) {
430
		$mt = microtime();
431
		echo "services_dyndns_configure() being called $mt\n";
432
	}
433

    
434
	$dyndnscfg = $config['dyndns'];
435
	$wancfg = $config['interfaces']['wan'];
436

    
437
	if (isset($dyndnscfg['enable'])) {
438

    
439
		if ($g['booting']) {
440
			echo "Starting DynDNS client... ";
441
			if(isset($config['system']['use_old_dyndns'])) {
442
				echo " [Using ez-ipupdate] ";
443
				services_dyndns_configure_old();
444
				return;
445
			}
446
		} else {
447
			sleep(1);
448
			if(isset($config['system']['use_old_dyndns'])) {
449
				services_dyndns_configure_old();
450
				return;
451
			}
452
		}
453

    
454
		/* load up the dyndns.class */
455
		require_once("dyndns.class");
456

    
457
		log_error("DynDns: Running updatedns()");
458

    
459
		/* determine WAN interface name */
460
		$wanif = get_real_wan_interface();
461
		/* get ip */
462
		$ip = find_interface_ip($wanif);
463

    
464
		$dns = new updatedns($dnsService = $config['dyndns']['type'],
465
							 $dnsHost = $config['dyndns']['host'],
466
							 $dnsUser = $config['dyndns']['username'],
467
							 $dnsPass = $config['dyndns']['password'],
468
							 $dnsWilcard = $config['dyndns']['wildcard'],
469
							 $dnsMX = $config['dyndns']['mx']);
470

    
471
		if ($g['booting'])
472
			echo "done.\n";
473
	}
474

    
475
	return 0;
476
}
477

    
478
function services_dyndns_configure_old() {
479
	global $config, $g;
480
	if(isset($config['system']['developerspew'])) {
481
		$mt = microtime();
482
		echo "services_dyndns_configure_old() being called $mt\n";
483
	}
484

    
485
        /* kill any running ez-ipupdate */
486
        /* ez-ipupdate needs SIGQUIT instead of SIGTERM */
487
        sigkillbypid("{$g['varrun_path']}/ez-ipupdate.pid", "QUIT");
488

    
489
        $dyndnscfg = $config['dyndns'];
490
        $wancfg = $config['interfaces']['wan'];
491

    
492
        if (isset($dyndnscfg['enable'])) {
493

    
494
                if ($g['booting'])
495
                        echo "Starting DynDNS client... ";
496
                else
497
                        sleep(1);
498

    
499
                /* determine WAN interface name */
500
                $wanif = get_real_wan_interface();
501

    
502
                /* write ez-ipupdate.conf */
503
                $fd = fopen("{$g['varetc_path']}/ez-ipupdate.conf", "w");
504
                if (!$fd) {
505
                        printf("Error: cannot open ez-ipupdate.conf in services_dyndns_configure().\n");
506
                        return 1;
507
                }
508

    
509
                $ezipupdateconf = <<<EOD
510
service-type={$dyndnscfg['type']}
511
user={$dyndnscfg['username']}:{$dyndnscfg['password']}
512
host={$dyndnscfg['host']}
513
interface={$wanif}
514
max-interval=2073600
515
pid-file={$g['varrun_path']}/ez-ipupdate.pid
516
cache-file={$g['vardb_path']}/ez-ipupdate.cache
517
execute=/etc/rc.dyndns.storecache
518
daemon
519

    
520
EOD;
521

    
522
                /* enable server[:port]? */
523
                if ($dyndnscfg['server']) {
524
                        if ($dyndnscfg['port'])
525
                                $ezipupdateconf .= "server={$dyndnscfg['server']}:{$dyndnscfg['port']}\n";
526
                        else
527
                                $ezipupdateconf .= "server={$dyndnscfg['server']}\n";
528
                }
529

    
530
                /* enable MX? */
531
                if ($dyndnscfg['mx']) {
532
                        $ezipupdateconf .= "mx={$dyndnscfg['mx']}\n";
533
                }
534

    
535
                /* enable wildcards? */
536
                if (isset($dyndnscfg['wildcard'])) {
537
                        $ezipupdateconf .= "wildcard\n";
538
                }
539

    
540
                fwrite($fd, $ezipupdateconf);
541
                fclose($fd);
542

    
543
                /* if we're booting, copy the cache file from /conf */
544
                if ($g['booting']) {
545
                        if (file_exists("{$g['conf_path']}/ez-ipupdate.cache")) {
546
                                copy("{$g['conf_path']}/ez-ipupdate.cache", "{$g['vardb_path']}/ez-ipupdate.cache");
547
                       }
548
                }
549

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

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

    
557
        return 0;
558
}
559

    
560
function services_dnsmasq_configure() {
561
	global $config, $g;
562
	if(isset($config['system']['developerspew'])) {
563
		$mt = microtime();
564
		echo "services_dnsmasq_configure() being called $mt\n";
565
	}
566

    
567
	/* kill any running dnsmasq */
568
	sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
569

    
570
	if (isset($config['dnsmasq']['enable'])) {
571

    
572
		if ($g['booting'])
573
			echo "Starting DNS forwarder... ";
574
		else
575
			sleep(1);
576

    
577
		/* generate hosts file */
578
		system_hosts_generate();
579

    
580
		$args = "";
581

    
582
		if (isset($config['dnsmasq']['regdhcp'])) {
583

    
584
			$args .= " -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases" .
585
				" -s {$config['system']['domain']}";
586
		}
587

    
588
                if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
589
                        foreach($config['dnsmasq']['domainoverrides'] as $override) {
590
                                $args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
591
                        }
592
                }
593

    
594
		/* run dnsmasq */
595
		mwexec("/usr/local/sbin/dnsmasq {$args}");
596

    
597
		if ($g['booting'])
598
			echo "done.\n";
599
	}
600

    
601
	if (!$g['booting']) {
602
		services_dhcpd_configure();
603
	}
604

    
605
	return 0;
606
}
607

    
608
function services_snmpd_configure() {
609
	global $config, $g;
610
	if(isset($config['system']['developerspew'])) {
611
		$mt = microtime();
612
		echo "services_snmpd_configure() being called $mt\n";
613
	}
614

    
615
	/* kill any running snmpd */
616
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
617

    
618
	if (isset($config['snmpd']['enable'])) {
619

    
620
		if ($g['booting'])
621
			echo "Starting SNMP daemon... ";
622

    
623
		/* generate snmpd.conf */
624
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
625
		if (!$fd) {
626
			printf("Error: cannot open snmpd.conf in services_snmpd_configure().\n");
627
			return 1;
628
		}
629

    
630

    
631
		$snmpdconf = <<<EOD
632
location := "{$config['snmpd']['syslocation']}"
633
contact := "{$config['snmpd']['syscontact']}"
634
read := "{$config['snmpd']['rocommunity']}"
635

    
636
EOD;
637

    
638
/* No docs on what write strings do there for disable for now.
639
		if(isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])){
640
		    $snmpdconf .= <<<EOD
641
# write string
642
write := "{$config['snmpd']['rwcommunity']}"
643

    
644
EOD;
645
		}
646
*/
647

    
648

    
649
		if(isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])){
650
		    $snmpdconf .= <<<EOD
651
# SNMP Trap support.
652
traphost := {$config['snmpd']['trapserver']}
653
trapport := {$config['snmpd']['trapserverport']}
654
trap := "{$config['snmpd']['trapstring']}"
655

    
656

    
657
EOD;
658
		}
659

    
660

    
661
		$snmpdconf .= <<<EOD
662
system := 1     # pfSense
663
%snmpd
664
begemotSnmpdDebugDumpPdus       = 2
665
begemotSnmpdDebugSyslogPri      = 7
666
begemotSnmpdCommunityString.0.1 = $(read)
667

    
668
EOD;
669

    
670
/* No docs on what write strings do there for disable for now.
671
		if(isset($config['snmpd']['rwcommunity']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])){
672
		    $snmpdconf .= <<<EOD
673
begemotSnmpdCommunityString.0.2 = $(write)
674

    
675
EOD;
676
		}
677
*/
678

    
679

    
680
		if(isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])){
681
		    $snmpdconf .= <<<EOD
682
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
683
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
684
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
685

    
686
EOD;
687
		}
688

    
689

    
690
		$snmpdconf .= <<<EOD
691
begemotSnmpdCommunityDisable    = 1
692

    
693
EOD;
694

    
695
		if(isset($config['snmpd']['bindlan'])) {
696
			$bind_to_ip = $config['interfaces']['lan']['ipaddr'];
697
		} else {
698
			$bind_to_ip = "0.0.0.0";
699
		}
700

    
701
		if(is_port( $config['snmpd']['pollport'] )) {
702
		    $snmpdconf .= <<<EOD
703
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
704

    
705
EOD;
706

    
707
		}
708

    
709
		$snmpdconf .= <<<EOD
710
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
711
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
712

    
713
# These are bsnmp macros not php vars.
714
sysContact      = $(contact)
715
sysLocation     = $(location)
716
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
717

    
718
snmpEnableAuthenTraps = 2
719

    
720
EOD;
721

    
722
		if (is_array( $config['snmpd']['modules'] )) {
723
		    if(isset($config['snmpd']['modules']['mibii'])) {
724
			$snmpdconf .= <<<EOD
725
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
726

    
727
EOD;
728
		    }
729

    
730
		    if(isset($config['snmpd']['modules']['netgraph'])) {
731
			$snmpdconf .= <<<EOD
732
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
733
%netgraph
734
begemotNgControlNodeName = "snmpd"
735

    
736
EOD;
737
		    }
738

    
739
		    if(isset($config['snmpd']['modules']['pf'])) {
740
			$snmpdconf .= <<<EOD
741
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
742
# config must end with blank line
743

    
744

    
745
EOD;
746
		    }
747
		}
748

    
749
		fwrite($fd, $snmpdconf);
750
		fclose($fd);
751

    
752
		if (isset($config['snmpd']['bindlan'])) {
753
			$bindlan = "";
754
		}
755

    
756
		/* run bsnmpd */
757
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
758
			"{$bindlan} -p {$g['varrun_path']}/snmpd.pid");
759

    
760
		if ($g['booting'])
761
			echo "done.\n";
762
	}
763

    
764
	return 0;
765
}
766

    
767
function services_proxyarp_configure() {
768
	global $config, $g;
769
	if(isset($config['system']['developerspew'])) {
770
		$mt = microtime();
771
		echo "services_proxyarp_configure() being called $mt\n";
772
	}
773

    
774
	/* kill any running choparp */
775
	killbyname("choparp");
776

    
777
	if (isset($config['virtualip']) && is_array($config['virtualip']['vip'])) {
778
		$paa = array();
779

    
780
		/* group by interface */
781
		foreach ($config['virtualip']['vip'] as $vipent) {
782
			if ($vipent['mode'] === "proxyarp") {
783
				if ($vipent['interface'])
784
					$if = $vipent['interface'];
785
				else
786
					$if = "wan";
787

    
788
				if (!is_array($paa[$if]))
789
					$paa[$if] = array();
790

    
791
				$paa[$if][] = $vipent;
792
			}
793
		}
794

    
795
		if (count($paa))
796
		foreach ($paa as $paif => $paents) {
797
			if ($paif == "wan" && !(is_ipaddr($config['interfaces']['wan']['ipaddr']) ||
798
                                       ($config['interfaces']['wan']['ipaddr'] == "dhcp") ||
799
                                       ($config['interfaces']['wan']['ipaddr'] == "bigpond")))
800
                               continue;
801

    
802
			$args = $config['interfaces'][$paif]['if'] . " auto";
803

    
804
			foreach ($paents as $paent) {
805

    
806
				if (isset($paent['subnet']))
807
					$args .= " " . escapeshellarg("{$paent['subnet']}/{$paent['subnet_bits']}");
808
				else if (isset($paent['range']))
809
					$args .= " " . escapeshellarg($paent['range']['from'] . "-" .
810
						$paent['range']['to']);
811
			}
812

    
813
			mwexec_bg("/usr/local/sbin/choparp " . $args);
814
		}
815
	}
816
}
817

    
818
function services_dnsupdate_process() {
819
	global $config, $g;
820
	if(isset($config['system']['developerspew'])) {
821
		$mt = microtime();
822
		echo "services_dnsupdate_process() being called $mt\n";
823
	}
824

    
825
	/* Dynamic DNS updating active? */
826
	if (isset($config['dnsupdate']['enable'])) {
827

    
828
		$wanip = get_current_wan_address();
829
		if ($wanip) {
830

    
831
			$keyname = $config['dnsupdate']['keyname'];
832
			/* trailing dot */
833
			if (substr($keyname, -1) != ".")
834
				$keyname .= ".";
835

    
836
			$hostname = $config['dnsupdate']['host'];
837
			/* trailing dot */
838
			if (substr($hostname, -1) != ".")
839
				$hostname .= ".";
840

    
841
			/* write private key file
842
			   this is dumb - public and private keys are the same for HMAC-MD5,
843
			   but nsupdate insists on having both */
844
			$fd = fopen("{$g['varetc_path']}/K{$keyname}+157+00000.private", "w");
845
			$privkey .= <<<EOD
846
Private-key-format: v1.2
847
Algorithm: 157 (HMAC)
848
Key: {$config['dnsupdate']['keydata']}
849

    
850
EOD;
851
			fwrite($fd, $privkey);
852
			fclose($fd);
853

    
854
			/* write public key file */
855
			if ($config['dnsupdate']['keytype'] == "zone") {
856
				$flags = 257;
857
				$proto = 3;
858
			} else if ($config['dnsupdate']['keytype'] == "host") {
859
				$flags = 513;
860
				$proto = 3;
861
			} else if ($config['dnsupdate']['keytype'] == "user") {
862
				$flags = 0;
863
				$proto = 2;
864
			}
865

    
866
			$fd = fopen("{$g['varetc_path']}/K{$keyname}+157+00000.key", "w");
867
			fwrite($fd, "{$keyname} IN KEY {$flags} {$proto} 157 {$config['dnsupdate']['keydata']}\n");
868
			fclose($fd);
869

    
870
			/* generate update instructions */
871
			$upinst =  "update delete {$config['dnsupdate']['host']} A\n";
872
			$upinst .= "update add {$config['dnsupdate']['host']} {$config['dnsupdate']['ttl']} A {$wanip}\n";
873
			$upinst .= "\n";	/* mind that trailing newline! */
874

    
875
			$fd = fopen("{$g['varetc_path']}/nsupdatecmds", "w");
876
			fwrite($fd, $upinst);
877
			fclose($fd);
878

    
879
			/* invoke nsupdate */
880
			$cmd = "/usr/sbin/nsupdate -k {$g['varetc_path']}/K{$keyname}+157+00000.key";
881
			if (isset($config['dnsupdate']['usetcp']))
882
				$cmd .= " -v";
883
			$cmd .= " {$g['varetc_path']}/nsupdatecmds";
884

    
885
			mwexec_bg($cmd);
886
		}
887
	}
888

    
889
	return 0;
890
}
891

    
892
function setup_wireless_olsr() {
893
	global $config, $g;
894
	if(!$config['installedpackages']['olsrd'] || !$config['installedpackages'])
895
		return;
896
	if(isset($config['system']['developerspew'])) {
897
		$mt = microtime();
898
		echo "setup_wireless_olsr($interface) being called $mt\n";
899
	}
900
	conf_mount_rw();
901
	foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
902
		$olsr_enable = $olsrd['enable'];
903
		if($olsr_enable <> "on")
904
			return;
905
		$fd = fopen("{$g['varetc_path']}/olsr.conf", "w");
906

    
907
		if($olsrd['announcedynamicroute'] or $olsrd['enableannounce'] == "on") {
908
			$enableannounce .= "\nHna4\n";
909
			$enableannounce .= "{\n";
910
		if($olsrd['announcedynamicroute'])
911
			$enableannounce .= "\t{$olsrd['announcedynamicroute']}\n";
912
		if($olsrd['enableannounce'] == "on")
913
			$enableannounce .= "0.0.0.0 0.0.0.0";
914
			$enableannounce .= "\n}\n";
915
		} else {
916
			$enableannounce = "";
917
		}
918

    
919
		$olsr .= <<<EODA
920
#
921
# olsr.org OLSR daemon config file
922
#
923
# Lines starting with a # are discarded
924
#
925
# This file was generated by setup_wireless_olsr() in services.inc
926
#
927

    
928
# This file is an example of a typical
929
# configuration for a mostly static
930
# network(regarding mobility) using
931
# the LQ extention
932

    
933
# Debug level(0-9)
934
# If set to 0 the daemon runs in the background
935

    
936
DebugLevel	2
937

    
938
# IP version to use (4 or 6)
939

    
940
IpVersion	4
941

    
942
# Clear the screen each time the internal state changes
943

    
944
ClearScreen     yes
945

    
946
{$enableannounce}
947

    
948
# Should olsrd keep on running even if there are
949
# no interfaces available? This is a good idea
950
# for a PCMCIA/USB hotswap environment.
951
# "yes" OR "no"
952

    
953
AllowNoInt	yes
954

    
955
# TOS(type of service) value for
956
# the IP header of control traffic.
957
# If not set it will default to 16
958

    
959
#TosValue	16
960

    
961
# The fixed willingness to use(0-7)
962
# If not set willingness will be calculated
963
# dynamically based on battery/power status
964
# if such information is available
965

    
966
#Willingness    	4
967

    
968
# Allow processes like the GUI front-end
969
# to connect to the daemon.
970

    
971
IpcConnect
972
{
973
     # Determines how many simultaneously
974
     # IPC connections that will be allowed
975
     # Setting this to 0 disables IPC
976

    
977
     MaxConnections  0
978

    
979
     # By default only 127.0.0.1 is allowed
980
     # to connect. Here allowed hosts can
981
     # be added
982

    
983
     Host            127.0.0.1
984
     #Host            10.0.0.5
985

    
986
     # You can also specify entire net-ranges
987
     # that are allowed to connect. Multiple
988
     # entries are allowed
989

    
990
     #Net             192.168.1.0 255.255.255.0
991
}
992

    
993
# Wether to use hysteresis or not
994
# Hysteresis adds more robustness to the
995
# link sensing but delays neighbor registration.
996
# Used by default. 'yes' or 'no'
997

    
998
UseHysteresis	no
999

    
1000
# Hysteresis parameters
1001
# Do not alter these unless you know
1002
# what you are doing!
1003
# Set to auto by default. Allowed
1004
# values are floating point values
1005
# in the interval 0,1
1006
# THR_LOW must always be lower than
1007
# THR_HIGH.
1008

    
1009
#HystScaling	0.50
1010
#HystThrHigh	0.80
1011
#HystThrLow	0.30
1012

    
1013

    
1014
# Link quality level
1015
# 0 = do not use link quality
1016
# 1 = use link quality for MPR selection
1017
# 2 = use link quality for MPR selection and routing
1018
# Defaults to 0
1019

    
1020
LinkQualityLevel	{$olsrd['enablelqe']}
1021

    
1022
# Link quality window size
1023
# Defaults to 10
1024

    
1025
LinkQualityWinSize	10
1026

    
1027
# Polling rate in seconds(float).
1028
# Default value 0.05 sec
1029

    
1030
Pollrate	0.05
1031

    
1032

    
1033
# TC redundancy
1034
# Specifies how much neighbor info should
1035
# be sent in TC messages
1036
# Possible values are:
1037
# 0 - only send MPR selectors
1038
# 1 - send MPR selectors and MPRs
1039
# 2 - send all neighbors
1040
#
1041
# defaults to 0
1042

    
1043
TcRedundancy	2
1044

    
1045
#
1046
# MPR coverage
1047
# Specifies how many MPRs a node should
1048
# try select to reach every 2 hop neighbor
1049
#
1050
# Can be set to any integer >0
1051
#
1052
# defaults to 1
1053

    
1054
MprCoverage	3
1055

    
1056
# Example plugin entry with parameters:
1057

    
1058
EODA;
1059

    
1060
if($olsrd['enablehttpinfo'] == "on") {
1061
	$olsr .= <<<EODB
1062

    
1063
LoadPlugin "/usr/local/lib/olsrd_httpinfo.so.0.1"
1064
{
1065
    PlParam     "port"   "{$olsrd['port']}"
1066
    PlParam     "Net"    "{$olsrd['allowedhttpinfohost']} {$olsrd['allowedhttpinfosubnet']}"
1067
}
1068

    
1069
EODB;
1070

    
1071
}
1072

    
1073
if($olsrd['enabledsecure'] == "on") {
1074
	$olsr .= <<<EODC
1075

    
1076
LoadPlugin "/usr/local/lib/olsrd_secure.so.0.5"
1077
{
1078
    PlParam     "Keyfile"   "/usr/local/etc/olsrkey.txt"
1079
}
1080

    
1081
EODC;
1082

    
1083
}
1084

    
1085
if($olsrd['enabledyngw'] == "on") {
1086

    
1087
	/* unset default route, olsr auto negotiates */
1088
	mwexec("/sbin/route delete default");
1089

    
1090
	$olsr .= <<<EODE
1091

    
1092
LoadPlugin "/usr/local/lib/olsrd_dyn_gw.so.0.4"
1093
{
1094
    # how often to look for a inet gw, in seconds
1095
    # defaults to 5 secs, if commented out
1096
    PlParam     "Interval"   "{$olsrd['polling']}"
1097

    
1098
    # if one or more IPv4 addresses are given, do a ping on these in
1099
    # descending order to validate that there is not only an entry in
1100
    # routing table, but also a real internet connection. If any of
1101
    # these addresses could be pinged successfully, the test was
1102
    # succesful, i.e. if the ping on the 1st address was successful,the
1103
    # 2nd won't be pinged
1104
    PlParam     "Ping"       "{$olsrd['ping']}"
1105
    #PlParam     "HNA"   "192.168.81.0 255.255.255.0"
1106
}
1107

    
1108
EODE;
1109

    
1110
}
1111

    
1112
foreach($config['installedpackages']['olsrd']['config'] as $conf) {
1113
	$interfaces = explode(',', $conf['iface_array']);
1114
	foreach($interfaces as $interface) {
1115
		$realinterface = convert_friendly_interface_to_real_interface_name($interface);
1116
$olsr .= <<<EODAD
1117
Interface "{$realinterface}"
1118
{
1119

    
1120
    # Hello interval in seconds(float)
1121
    HelloInterval    2.0
1122

    
1123
    # HELLO validity time
1124
    HelloValidityTime	20.0
1125

    
1126
    # TC interval in seconds(float)
1127
    TcInterval        5.0
1128

    
1129
    # TC validity time
1130
    TcValidityTime	30.0
1131

    
1132
    # MID interval in seconds(float)
1133
    MidInterval	5.0
1134

    
1135
    # MID validity time
1136
    MidValidityTime	30.0
1137

    
1138
    # HNA interval in seconds(float)
1139
    HnaInterval	5.0
1140

    
1141
    # HNA validity time
1142
    HnaValidityTime 	30.0
1143

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

    
1152
    # Weight 0
1153

    
1154

    
1155
}
1156

    
1157
EODAD;
1158

    
1159
	}
1160
	break;
1161
}
1162
		fwrite($fd, $olsr);
1163
		fclose($fd);
1164
	}
1165

    
1166
	if(is_process_running("olsrd"))
1167
		mwexec("/usr/bin/killall olsrd");
1168

    
1169
	sleep(2);
1170

    
1171
	mwexec_bg("/usr/local/sbin/olsrd -f {$g['varetc_path']}/olsr.conf");
1172

    
1173
	conf_mount_ro();
1174
}
1175

    
1176
?>
(18-18/27)