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
one-lease-per-client true;
103

    
104
EOD;
105

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

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

    
164
	$dhcpnum = 0;
165

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

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

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

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

    
178
		$dnscfg = "";
179

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

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

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

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

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

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

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

    
225
EOD;
226

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

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

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

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

    
245
EOD;
246

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

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

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

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

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

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

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

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

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

    
282
	return 0;
283
}
284

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

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

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

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

    
311
        return 0;
312
}
313

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
387
	return 0;
388
}
389

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

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

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

    
409
	return 0;
410
}
411

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

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

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

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

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

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

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

    
455
	return 0;
456
}
457

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

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

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

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

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

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

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

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

    
500
EOD;
501

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

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

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

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

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

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

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

    
537
        return 0;
538
}
539

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

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

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

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

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

    
560
		$args = "";
561

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

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

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

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

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

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

    
585
	return 0;
586
}
587

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

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

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

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

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

    
610

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

    
616
EOD;
617

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

    
624
EOD;
625
		}
626
*/
627

    
628

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

    
636

    
637
EOD;
638
		}
639

    
640

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

    
648
EOD;
649

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

    
655
EOD;
656
		}
657
*/
658

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

    
666
EOD;
667
		}
668

    
669

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

    
673
EOD;
674

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

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

    
685
EOD;
686

    
687
		}
688

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

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

    
698
snmpEnableAuthenTraps = 2
699

    
700
EOD;
701

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

    
707
EOD;
708
		    }
709

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

    
716
EOD;
717
		    }
718

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

    
724

    
725
EOD;
726
		    }
727
		}
728

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

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

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

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

    
744
	return 0;
745
}
746

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

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

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

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

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

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

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

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

    
784
			foreach ($paents as $paent) {
785

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

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

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

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

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

    
872
function setup_wireless_olsr() {
873
	global $config, $g;
874
	if(isset($config['system']['developerspew'])) {
875
		$mt = microtime();
876
		echo "setup_wireless_olsr($interface) being called $mt\n";
877
	}
878
	conf_mount_rw();
879
	foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
880
		$fd = fopen("{$g['varetc_path']}/olsr.conf", "w");
881
		$olsr .= <<<EODA
882
#
883
# olsr.org OLSR daemon config file
884
#
885
# Lines starting with a # are discarded
886
#
887
# This file was generated by setup_wireless_olsr() in services.inc
888
#
889

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

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

    
898
DebugLevel	2
899

    
900
# IP version to use (4 or 6)
901

    
902
IpVersion	4
903

    
904
# Clear the screen each time the internal state changes
905

    
906
ClearScreen     yes
907

    
908
# HNA IPv4 routes
909
# syntax: netaddr netmask
910
# Example Internet gateway:
911
# 0.0.0.0 0.0.0.0
912

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

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

    
932

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

    
938
AllowNoInt	yes
939

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

    
944
#TosValue	16
945

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

    
951
#Willingness    	4
952

    
953
# Allow processes like the GUI front-end
954
# to connect to the daemon.
955

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

    
962
     MaxConnections  0
963

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

    
968
     Host            127.0.0.1
969
     #Host            10.0.0.5
970

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

    
975
     #Net             192.168.1.0 255.255.255.0     
976
}
977

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

    
983
UseHysteresis	no
984

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

    
994
#HystScaling	0.50
995
#HystThrHigh	0.80
996
#HystThrLow	0.30
997

    
998

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

    
1005
LinkQualityLevel	2
1006

    
1007
# Link quality window size
1008
# Defaults to 10
1009

    
1010
LinkQualityWinSize	10
1011

    
1012
# Polling rate in seconds(float). 
1013
# Default value 0.05 sec
1014

    
1015
Pollrate	0.05
1016

    
1017

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

    
1028
TcRedundancy	2
1029

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

    
1039
MprCoverage	3
1040

    
1041
# Example plugin entry with parameters:
1042

    
1043
EODA;
1044

    
1045
if($olsr['enablehttpinfo']) {
1046
	$olsr .= <<<EODB
1047

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

    
1054
EODB;
1055

    
1056
}
1057

    
1058
if($olsr['enabledyngw']) {
1059
	$olsr .= <<<EODC
1060

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

    
1066
EODC;
1067

    
1068
}
1069

    
1070
if($olsr['enabledyngw']) {
1071
	$olsr .= <<<EODE
1072

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

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

    
1089
EODE;
1090

    
1091
}
1092

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

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

    
1105
    # Ip4Broadcast		255.255.255.255
1106

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

    
1110
    # Ip6AddrType		site-local
1111

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

    
1116
    # Ip6MulticastSite		ff05::11
1117

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

    
1122
    # Ip6MulticastGlobal	ff0e::1
1123

    
1124

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

    
1129
    # Hello interval in seconds(float)
1130
    HelloInterval    2.0
1131

    
1132
    # HELLO validity time
1133
    HelloValidityTime	20.0
1134

    
1135
    # TC interval in seconds(float)
1136
    TcInterval        5.0
1137

    
1138
    # TC validity time
1139
    TcValidityTime	30.0
1140

    
1141
    # MID interval in seconds(float)
1142
    MidInterval	5.0
1143

    
1144
    # MID validity time
1145
    MidValidityTime	30.0
1146

    
1147
    # HNA interval in seconds(float)
1148
    HnaInterval	5.0
1149

    
1150
    # HNA validity time
1151
    HnaValidityTime 	30.0
1152

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

    
1161
    # Weight 0
1162

    
1163

    
1164
}
1165

    
1166
EOD;
1167

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

    
1183
?>
(18-18/27)