Project

General

Profile

Download (30.1 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 "{$g['dhcpd_chroot_path']}/dev"`;
45
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}\n");
46
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/dev\n");
47
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/etc\n");
48
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/usr/local/sbin\n");
49
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/var/db\n");
50
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/usr\n");
51
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/lib\n");
52
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/run\n");
53
	fwrite($fd, "chown -R dhcpd:_dhcp {$g['dhcpd_chroot_path']}/*\n");
54
	fwrite($fd, "cp /lib/libc.so.6 {$g['dhcpd_chroot_path']}/lib/\n");
55
	fwrite($fd, "cp /usr/local/sbin/dhcpd {$g['dhcpd_chroot_path']}/usr/local/sbin/\n");
56
	fwrite($fd, "chmod a+rx {$g['dhcpd_chroot_path']}/usr/local/sbin/dhcpd\n");
57
	if(!trim($status)) 
58
		fwrite($fd, "mount_devfs devfs {$g['dhcpd_chroot_path']}/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("{$g['dhcpd_chroot_path']}/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'] < "20")
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("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
272

    
273
	/* fire up dhcpd in a chroot */
274
	mwexec("/usr/local/sbin/dhcpd -user dhcpd -group _dhcp -chroot {$g['dhcpd_chroot_path']} -cf {$g['dhcpd_chroot_path']}/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['dhcpd_chroot_path']}/var/db/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() {
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
	foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
878
		$fd = fopen("{$g['varetc_path']}/olsr.conf", "w");
879
		$olsr .= <<<EODA
880
#
881
# olsr.org OLSR daemon config file
882
#
883
# Lines starting with a # are discarded
884
#
885
# This file was generated by setup_wireless_olsr() in services.inc
886
#
887

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

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

    
896
DebugLevel	2
897

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

    
900
IpVersion	4
901

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

    
904
ClearScreen     yes
905

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

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

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

    
930

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

    
936
AllowNoInt	yes
937

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

    
942
#TosValue	16
943

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

    
949
#Willingness    	4
950

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

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

    
960
     MaxConnections  0
961

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

    
966
     Host            127.0.0.1
967
     #Host            10.0.0.5
968

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

    
973
     #Net             192.168.1.0 255.255.255.0     
974
}
975

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

    
981
UseHysteresis	no
982

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

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

    
996

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

    
1003
LinkQualityLevel	2
1004

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

    
1008
LinkQualityWinSize	10
1009

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

    
1013
Pollrate	0.05
1014

    
1015

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

    
1026
TcRedundancy	2
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
# Example plugin entry with parameters:
1040

    
1041
EODA;
1042

    
1043
if($olsr['enablehttpinfo']) {
1044
	$olsr .= <<<EODB
1045

    
1046
LoadPlugin "/usr/local/lib/olsrd_httpinfo.so.0.1"
1047
{
1048
    PlParam     "port"   "{$olsrd['port']}"
1049
    PlParam     "Net"    "{$olsrd['allowedhttpinfohost']} {$olsrd['allowedhttpinfosubnet']}"
1050
}
1051

    
1052
EODB;
1053

    
1054
}
1055

    
1056
if($olsr['enabledyngw']) {
1057
	$olsr .= <<<EODC
1058

    
1059
LoadPlugin "/usr/local/lib/olsrd_secure.so.0.4"
1060
{
1061
    PlParam     "Keyfile"   "/usr/local/etc/olsrkey.txt"
1062
}
1063

    
1064
EODC;
1065

    
1066
}
1067

    
1068
if($olsr['enabledyngw']) {
1069
	$olsr .= <<<EODE
1070

    
1071
LoadPlugin "/usr/local/lib/olsrd_dyn_gw.so.0.4"
1072
{
1073
    # how often to look for a inet gw, in seconds
1074
    # defaults to 5 secs, if commented out
1075
    PlParam     "Interval"   "{$olsrd['polling']}"
1076

    
1077
    # if one or more IPv4 addresses are given, do a ping on these in
1078
    # descending order to validate that there is not only an entry in
1079
    # routing table, but also a real internet connection. If any of
1080
    # these addresses could be pinged successfully, the test was
1081
    # succesful, i.e. if the ping on the 1st address was successful,the
1082
    # 2nd won't be pinged
1083
    PlParam     "Ping"       "{$olsrd['ping']}"
1084
    #PlParam     "HNA"   "192.168.81.0 255.255.255.0"
1085
}
1086

    
1087
EODE;
1088

    
1089
}
1090

    
1091
foreach($config['installedpackages']['olsrd']['config'] as $conf) {
1092
	foreach($conf['interface_array'] as $interface) {
1093
		$realinterface = convert_friendly_interface_to_real_interface_name($interface);
1094
$olsr .= <<<EOD
1095
Interface "{$realinterface}" 
1096
{
1097

    
1098
    # IPv4 broadcast address to use. The
1099
    # one usefull example would be 255.255.255.255
1100
    # If not defined the broadcastaddress
1101
    # every card is configured with is used
1102

    
1103
    # Ip4Broadcast		255.255.255.255
1104

    
1105
    # IPv6 address scope to use.
1106
    # Must be 'site-local' or 'global'
1107

    
1108
    # Ip6AddrType		site-local
1109

    
1110
    # IPv6 multicast address to use when
1111
    # using site-local addresses.
1112
    # If not defined, ff05::15 is used
1113

    
1114
    # Ip6MulticastSite		ff05::11
1115

    
1116
    # IPv6 multicast address to use when
1117
    # using global addresses
1118
    # If not defined, ff0e::1 is used
1119

    
1120
    # Ip6MulticastGlobal	ff0e::1
1121

    
1122

    
1123
    # Emission intervals.
1124
    # If not defined, RFC proposed values will
1125
    # be used in most cases.
1126

    
1127
    # Hello interval in seconds(float)
1128
    HelloInterval    2.0
1129

    
1130
    # HELLO validity time
1131
    HelloValidityTime	20.0
1132

    
1133
    # TC interval in seconds(float)
1134
    TcInterval        5.0
1135

    
1136
    # TC validity time
1137
    TcValidityTime	30.0
1138

    
1139
    # MID interval in seconds(float)
1140
    MidInterval	5.0
1141

    
1142
    # MID validity time
1143
    MidValidityTime	30.0
1144

    
1145
    # HNA interval in seconds(float)
1146
    HnaInterval	5.0
1147

    
1148
    # HNA validity time
1149
    HnaValidityTime 	30.0
1150

    
1151
    # When multiple links exist between hosts
1152
    # the weight of interface is used to determine
1153
    # the link to use. Normally the weight is
1154
    # automatically calculated by olsrd based
1155
    # on the characteristics of the interface,
1156
    # but here you can specify a fixed value.
1157
    # Olsrd will choose links with the lowest value.
1158

    
1159
    # Weight 0
1160

    
1161

    
1162
}
1163

    
1164
EOD;
1165

    
1166
	}
1167
	break;
1168
}
1169
		fwrite($fd, $olsr);
1170
		fclose($fd);
1171
	}
1172
	
1173
	if(is_process_running("olsrd"))
1174
		mwexec("killall -HUP olsrd");
1175
	else 
1176
		mwexec_bg("/usr/local/sbin/olsrd -f {$g['varetc_path']}/olsr.conf");
1177
}
1178

    
1179
?>
(18-18/27)