Project

General

Profile

Download (30.2 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
deny duplicates;
104

    
105
EOD;
106

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

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

    
165
	$dhcpnum = 0;
166

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

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

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

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

    
179
		$dnscfg = "";
180

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

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

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

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

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

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

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

    
226
EOD;
227

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

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

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

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

    
246
EOD;
247

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

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

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

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

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

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

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

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

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

    
283
	return 0;
284
}
285

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

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

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

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

    
312
        return 0;
313
}
314

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
388
	return 0;
389
}
390

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

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

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

    
410
	return 0;
411
}
412

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

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

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

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

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

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

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

    
456
	return 0;
457
}
458

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

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

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

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

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

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

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

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

    
501
EOD;
502

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

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

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

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

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

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

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

    
538
        return 0;
539
}
540

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

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

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

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

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

    
561
		$args = "";
562

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

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

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

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

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

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

    
586
	return 0;
587
}
588

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

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

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

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

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

    
611

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

    
617
EOD;
618

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

    
625
EOD;
626
		}
627
*/
628

    
629

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

    
637

    
638
EOD;
639
		}
640

    
641

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

    
649
EOD;
650

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

    
656
EOD;
657
		}
658
*/
659

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

    
667
EOD;
668
		}
669

    
670

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

    
674
EOD;
675

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

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

    
686
EOD;
687

    
688
		}
689

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

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

    
699
snmpEnableAuthenTraps = 2
700

    
701
EOD;
702

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

    
708
EOD;
709
		    }
710

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

    
717
EOD;
718
		    }
719

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

    
725

    
726
EOD;
727
		    }
728
		}
729

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

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

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

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

    
745
	return 0;
746
}
747

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

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

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

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

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

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

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

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

    
785
			foreach ($paents as $paent) {
786

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

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

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

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

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

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

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

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

    
899
DebugLevel	2
900

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

    
903
IpVersion	4
904

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

    
907
ClearScreen     yes
908

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

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

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

    
933

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

    
939
AllowNoInt	yes
940

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

    
945
#TosValue	16
946

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

    
952
#Willingness    	4
953

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

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

    
963
     MaxConnections  0
964

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

    
969
     Host            127.0.0.1
970
     #Host            10.0.0.5
971

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

    
976
     #Net             192.168.1.0 255.255.255.0     
977
}
978

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

    
984
UseHysteresis	no
985

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

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

    
999

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

    
1006
LinkQualityLevel	2
1007

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

    
1011
LinkQualityWinSize	10
1012

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

    
1016
Pollrate	0.05
1017

    
1018

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

    
1029
TcRedundancy	2
1030

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

    
1040
MprCoverage	3
1041

    
1042
# Example plugin entry with parameters:
1043

    
1044
EODA;
1045

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

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

    
1055
EODB;
1056

    
1057
}
1058

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

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

    
1067
EODC;
1068

    
1069
}
1070

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

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

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

    
1090
EODE;
1091

    
1092
}
1093

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

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

    
1106
    # Ip4Broadcast		255.255.255.255
1107

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

    
1111
    # Ip6AddrType		site-local
1112

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

    
1117
    # Ip6MulticastSite		ff05::11
1118

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

    
1123
    # Ip6MulticastGlobal	ff0e::1
1124

    
1125

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

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

    
1133
    # HELLO validity time
1134
    HelloValidityTime	20.0
1135

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

    
1139
    # TC validity time
1140
    TcValidityTime	30.0
1141

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

    
1145
    # MID validity time
1146
    MidValidityTime	30.0
1147

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

    
1151
    # HNA validity time
1152
    HnaValidityTime 	30.0
1153

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

    
1162
    # Weight 0
1163

    
1164

    
1165
}
1166

    
1167
EOD;
1168

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

    
1184
?>
(18-18/27)