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
		/* determine WAN interface name */
446
		$wanif = get_real_wan_interface();
447
		/* get ip */
448
		$ip = find_interface_ip($wanif);
449

    
450
		$dns = new updatedns($dnsService = $config['dyndns']['type'],
451
							 $dnsHost = $config['dyndns']['host'],
452
							 $dnsUser = $config['dyndns']['username'],
453
							 $dnsPass = $config['dyndns']['password'],
454
							 $dnsWilcard = $config['dyndns']['wildcard'],
455
							 $dnsMX = $config['dyndns']['mx']);
456

    
457
		if ($g['booting'])
458
			echo "done.\n";
459
	}
460

    
461
	return 0;
462
}
463

    
464
function services_dyndns_configure_old() {
465
	global $config, $g;
466
	if(isset($config['system']['developerspew'])) {
467
		$mt = microtime();
468
		echo "services_dyndns_configure_old() being called $mt\n";
469
	}
470

    
471
        /* kill any running ez-ipupdate */
472
        /* ez-ipupdate needs SIGQUIT instead of SIGTERM */
473
        sigkillbypid("{$g['varrun_path']}/ez-ipupdate.pid", "QUIT");
474

    
475
        $dyndnscfg = $config['dyndns'];
476
        $wancfg = $config['interfaces']['wan'];
477

    
478
        if (isset($dyndnscfg['enable'])) {
479

    
480
                if ($g['booting'])
481
                        echo "Starting DynDNS client... ";
482
                else
483
                        sleep(1);
484

    
485
                /* determine WAN interface name */
486
                $wanif = get_real_wan_interface();
487

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

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

    
506
EOD;
507

    
508
                /* enable server[:port]? */
509
                if ($dyndnscfg['server']) {
510
                        if ($dyndnscfg['port'])
511
                                $ezipupdateconf .= "server={$dyndnscfg['server']}:{$dyndnscfg['port']}\n";
512
                        else
513
                                $ezipupdateconf .= "server={$dyndnscfg['server']}\n";
514
                }
515

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

    
521
                /* enable wildcards? */
522
                if (isset($dyndnscfg['wildcard'])) {
523
                        $ezipupdateconf .= "wildcard\n";
524
                }
525

    
526
                fwrite($fd, $ezipupdateconf);
527
                fclose($fd);
528

    
529
                /* if we're booting, copy the cache file from /conf */
530
                if ($g['booting']) {
531
                        if (file_exists("{$g['conf_path']}/ez-ipupdate.cache")) {
532
                                copy("{$g['conf_path']}/ez-ipupdate.cache", "{$g['vardb_path']}/ez-ipupdate.cache");
533
                       }
534
                }
535

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

    
539
                if ($g['booting'])
540
                        echo "done\n";
541
        }
542

    
543
        return 0;
544
}
545

    
546
function services_dnsmasq_configure() {
547
	global $config, $g;
548
	if(isset($config['system']['developerspew'])) {
549
		$mt = microtime();
550
		echo "services_dnsmasq_configure() being called $mt\n";
551
	}
552

    
553
	/* kill any running dnsmasq */
554
	sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
555

    
556
	if (isset($config['dnsmasq']['enable'])) {
557

    
558
		if ($g['booting'])
559
			echo "Starting DNS forwarder... ";
560
		else
561
			sleep(1);
562

    
563
		/* generate hosts file */
564
		system_hosts_generate();
565

    
566
		$args = "";
567

    
568
		if (isset($config['dnsmasq']['regdhcp'])) {
569

    
570
			$args .= " -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases" .
571
				" -s {$config['system']['domain']}";
572
		}
573

    
574
                if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
575
                        foreach($config['dnsmasq']['domainoverrides'] as $override) {
576
                                $args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
577
                        }
578
                }
579

    
580
		/* run dnsmasq */
581
		mwexec("/usr/local/sbin/dnsmasq {$args}");
582

    
583
		if ($g['booting'])
584
			echo "done.\n";
585
	}
586

    
587
	if (!$g['booting']) {
588
		services_dhcpd_configure();
589
	}
590

    
591
	return 0;
592
}
593

    
594
function services_snmpd_configure() {
595
	global $config, $g;
596
	if(isset($config['system']['developerspew'])) {
597
		$mt = microtime();
598
		echo "services_snmpd_configure() being called $mt\n";
599
	}
600

    
601
	/* kill any running snmpd */
602
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
603

    
604
	if (isset($config['snmpd']['enable'])) {
605

    
606
		if ($g['booting'])
607
			echo "Starting SNMP daemon... ";
608

    
609
		/* generate snmpd.conf */
610
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
611
		if (!$fd) {
612
			printf("Error: cannot open snmpd.conf in services_snmpd_configure().\n");
613
			return 1;
614
		}
615

    
616

    
617
		$snmpdconf = <<<EOD
618
location := "{$config['snmpd']['syslocation']}"
619
contact := "{$config['snmpd']['syscontact']}"
620
read := "{$config['snmpd']['rocommunity']}"
621

    
622
EOD;
623

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

    
630
EOD;
631
		}
632
*/
633

    
634

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

    
642

    
643
EOD;
644
		}
645

    
646

    
647
		$snmpdconf .= <<<EOD
648
system := 1     # pfSense
649
%snmpd
650
begemotSnmpdDebugDumpPdus       = 2
651
begemotSnmpdDebugSyslogPri      = 7
652
begemotSnmpdCommunityString.0.1 = $(read)
653

    
654
EOD;
655

    
656
/* No docs on what write strings do there for disable for now.
657
		if(isset($config['snmpd']['rwcommunity']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])){
658
		    $snmpdconf .= <<<EOD
659
begemotSnmpdCommunityString.0.2 = $(write)
660

    
661
EOD;
662
		}
663
*/
664

    
665
		
666
		if(isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])){
667
		    $snmpdconf .= <<<EOD
668
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
669
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
670
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
671

    
672
EOD;
673
		}
674

    
675

    
676
		$snmpdconf .= <<<EOD
677
begemotSnmpdCommunityDisable    = 1
678

    
679
EOD;
680

    
681
		if(isset($config['snmpd']['bindlan'])) {
682
			$bind_to_ip = $config['interfaces']['lan']['ipaddr'];
683
		} else {
684
			$bind_to_ip = "0.0.0.0";
685
		}
686

    
687
		if(is_port( $config['snmpd']['pollport'] )) {
688
		    $snmpdconf .= <<<EOD
689
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
690

    
691
EOD;
692

    
693
		}
694

    
695
		$snmpdconf .= <<<EOD
696
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
697
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
698

    
699
# These are bsnmp macros not php vars.
700
sysContact      = $(contact)
701
sysLocation     = $(location)
702
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
703

    
704
snmpEnableAuthenTraps = 2
705

    
706
EOD;
707

    
708
		if (is_array( $config['snmpd']['modules'] )) {
709
		    if(isset($config['snmpd']['modules']['mibii'])) {
710
			$snmpdconf .= <<<EOD
711
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
712

    
713
EOD;
714
		    }
715

    
716
		    if(isset($config['snmpd']['modules']['netgraph'])) {
717
			$snmpdconf .= <<<EOD
718
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
719
%netgraph
720
begemotNgControlNodeName = "snmpd"
721

    
722
EOD;
723
		    }
724

    
725
		    if(isset($config['snmpd']['modules']['pf'])) {
726
			$snmpdconf .= <<<EOD
727
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
728
# config must end with blank line
729

    
730

    
731
EOD;
732
		    }
733
		}
734

    
735
		fwrite($fd, $snmpdconf);
736
		fclose($fd);
737

    
738
		if (isset($config['snmpd']['bindlan'])) {
739
			$bindlan = "";
740
		}
741

    
742
		/* run bsnmpd */
743
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
744
			"{$bindlan} -p {$g['varrun_path']}/snmpd.pid");
745

    
746
		if ($g['booting'])
747
			echo "done.\n";
748
	}
749

    
750
	return 0;
751
}
752

    
753
function services_proxyarp_configure() {
754
	global $config, $g;
755
	if(isset($config['system']['developerspew'])) {
756
		$mt = microtime();
757
		echo "services_proxyarp_configure() being called $mt\n";
758
	}
759

    
760
	/* kill any running choparp */
761
	killbyname("choparp");
762

    
763
	if (isset($config['virtualip']) && is_array($config['virtualip']['vip'])) {
764
		$paa = array();
765

    
766
		/* group by interface */
767
		foreach ($config['virtualip']['vip'] as $vipent) {
768
			if ($vipent['mode'] === "proxyarp") {
769
				if ($vipent['interface'])
770
					$if = $vipent['interface'];
771
				else
772
					$if = "wan";
773

    
774
				if (!is_array($paa[$if]))
775
					$paa[$if] = array();
776

    
777
				$paa[$if][] = $vipent;
778
			}
779
		}
780

    
781
		if (count($paa))
782
		foreach ($paa as $paif => $paents) {
783
			if ($paif == "wan" && !(is_ipaddr($config['interfaces']['wan']['ipaddr']) ||
784
                                       ($config['interfaces']['wan']['ipaddr'] == "dhcp") ||
785
                                       ($config['interfaces']['wan']['ipaddr'] == "bigpond")))
786
                               continue;
787

    
788
			$args = $config['interfaces'][$paif]['if'] . " auto";
789

    
790
			foreach ($paents as $paent) {
791

    
792
				if (isset($paent['subnet']))
793
					$args .= " " . escapeshellarg("{$paent['subnet']}/{$paent['subnet_bits']}");
794
				else if (isset($paent['range']))
795
					$args .= " " . escapeshellarg($paent['range']['from'] . "-" .
796
						$paent['range']['to']);
797
			}
798

    
799
			mwexec_bg("/usr/local/sbin/choparp " . $args);
800
		}
801
	}
802
}
803

    
804
function services_dnsupdate_process() {
805
	global $config, $g;
806
	if(isset($config['system']['developerspew'])) {
807
		$mt = microtime();
808
		echo "services_dnsupdate_process() being called $mt\n";
809
	}
810

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

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

    
878
function setup_wireless_olsr() {
879
	global $config, $g;
880
	if(!$config['installedpackages']['olsrd'] || !$config['installedpackages'])
881
		return;	
882
	if(isset($config['system']['developerspew'])) {
883
		$mt = microtime();
884
		echo "setup_wireless_olsr($interface) being called $mt\n";
885
	}
886
	conf_mount_rw();
887
	foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
888
		$olsr_enable = $olsrd['enable'];
889
		if($olsr_enable <> "on")
890
			return;		
891
		$fd = fopen("{$g['varetc_path']}/olsr.conf", "w");
892
		$olsr .= <<<EODA
893
#
894
# olsr.org OLSR daemon config file
895
#
896
# Lines starting with a # are discarded
897
#
898
# This file was generated by setup_wireless_olsr() in services.inc
899
#
900

    
901
# This file is an example of a typical
902
# configuration for a mostly static
903
# network(regarding mobility) using
904
# the LQ extention
905

    
906
# Debug level(0-9)
907
# If set to 0 the daemon runs in the background
908

    
909
DebugLevel	2
910

    
911
# IP version to use (4 or 6)
912

    
913
IpVersion	4
914

    
915
# Clear the screen each time the internal state changes
916

    
917
ClearScreen     yes
918

    
919
Hna4
920
{
921
    0.0.0.0 0.0.0.0
922
}
923

    
924
# Should olsrd keep on running even if there are
925
# no interfaces available? This is a good idea
926
# for a PCMCIA/USB hotswap environment.
927
# "yes" OR "no"
928

    
929
AllowNoInt	yes
930

    
931
# TOS(type of service) value for
932
# the IP header of control traffic.
933
# If not set it will default to 16
934

    
935
#TosValue	16
936

    
937
# The fixed willingness to use(0-7)
938
# If not set willingness will be calculated
939
# dynamically based on battery/power status
940
# if such information is available
941

    
942
#Willingness    	4
943

    
944
# Allow processes like the GUI front-end
945
# to connect to the daemon.
946

    
947
IpcConnect
948
{
949
     # Determines how many simultaneously
950
     # IPC connections that will be allowed
951
     # Setting this to 0 disables IPC
952

    
953
     MaxConnections  0
954

    
955
     # By default only 127.0.0.1 is allowed
956
     # to connect. Here allowed hosts can
957
     # be added
958

    
959
     Host            127.0.0.1
960
     #Host            10.0.0.5
961

    
962
     # You can also specify entire net-ranges 
963
     # that are allowed to connect. Multiple
964
     # entries are allowed
965

    
966
     #Net             192.168.1.0 255.255.255.0     
967
}
968

    
969
# Wether to use hysteresis or not
970
# Hysteresis adds more robustness to the
971
# link sensing but delays neighbor registration.
972
# Used by default. 'yes' or 'no'
973

    
974
UseHysteresis	no
975

    
976
# Hysteresis parameters
977
# Do not alter these unless you know 
978
# what you are doing!
979
# Set to auto by default. Allowed
980
# values are floating point values
981
# in the interval 0,1
982
# THR_LOW must always be lower than
983
# THR_HIGH.
984

    
985
#HystScaling	0.50
986
#HystThrHigh	0.80
987
#HystThrLow	0.30
988

    
989

    
990
# Link quality level
991
# 0 = do not use link quality
992
# 1 = use link quality for MPR selection
993
# 2 = use link quality for MPR selection and routing
994
# Defaults to 0
995

    
996
LinkQualityLevel	{$olsrd['enablelqe']}
997

    
998
# Link quality window size
999
# Defaults to 10
1000

    
1001
LinkQualityWinSize	10
1002

    
1003
# Polling rate in seconds(float). 
1004
# Default value 0.05 sec
1005

    
1006
Pollrate	0.05
1007

    
1008

    
1009
# TC redundancy
1010
# Specifies how much neighbor info should
1011
# be sent in TC messages
1012
# Possible values are:
1013
# 0 - only send MPR selectors
1014
# 1 - send MPR selectors and MPRs
1015
# 2 - send all neighbors
1016
#
1017
# defaults to 0
1018

    
1019
TcRedundancy	2
1020

    
1021
#
1022
# MPR coverage
1023
# Specifies how many MPRs a node should
1024
# try select to reach every 2 hop neighbor
1025
#
1026
# Can be set to any integer >0
1027
#
1028
# defaults to 1
1029

    
1030
MprCoverage	3
1031

    
1032
# Example plugin entry with parameters:
1033

    
1034
EODA;
1035

    
1036
if($olsrd['enablehttpinfo'] == "on") {
1037
	$olsr .= <<<EODB
1038

    
1039
LoadPlugin "/usr/local/lib/olsrd_httpinfo.so.0.1"
1040
{
1041
    PlParam     "port"   "{$olsrd['port']}"
1042
    PlParam     "Net"    "{$olsrd['allowedhttpinfohost']} {$olsrd['allowedhttpinfosubnet']}"
1043
}
1044

    
1045
EODB;
1046

    
1047
}
1048

    
1049
if($olsrd['enabledyngw'] == "on") {
1050
	$olsr .= <<<EODC
1051

    
1052
LoadPlugin "/usr/local/lib/olsrd_secure.so.0.5"
1053
{
1054
    PlParam     "Keyfile"   "/usr/local/etc/olsrkey.txt"
1055
}
1056

    
1057
EODC;
1058

    
1059
}
1060

    
1061
if($olsrd['enabledyngw'] == "on") {
1062

    
1063
	/* unset default route, olsr auto negotiates */
1064
	mwexec("/sbin/route delete default");
1065
	
1066
	$olsr .= <<<EODE
1067

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

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

    
1084
EODE;
1085

    
1086
}
1087

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

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

    
1100
    # Ip4Broadcast		255.255.255.255
1101

    
1102
    # IPv6 address scope to use.
1103
    # Must be 'site-local' or 'global'
1104

    
1105
    # Ip6AddrType		site-local
1106

    
1107
    # IPv6 multicast address to use when
1108
    # using site-local addresses.
1109
    # If not defined, ff05::15 is used
1110

    
1111
    # Ip6MulticastSite		ff05::11
1112

    
1113
    # IPv6 multicast address to use when
1114
    # using global addresses
1115
    # If not defined, ff0e::1 is used
1116

    
1117
    # Ip6MulticastGlobal	ff0e::1
1118

    
1119

    
1120
    # Emission intervals.
1121
    # If not defined, RFC proposed values will
1122
    # be used in most cases.
1123

    
1124
    # Hello interval in seconds(float)
1125
    HelloInterval    2.0
1126

    
1127
    # HELLO validity time
1128
    HelloValidityTime	20.0
1129

    
1130
    # TC interval in seconds(float)
1131
    TcInterval        5.0
1132

    
1133
    # TC validity time
1134
    TcValidityTime	30.0
1135

    
1136
    # MID interval in seconds(float)
1137
    MidInterval	5.0
1138

    
1139
    # MID validity time
1140
    MidValidityTime	30.0
1141

    
1142
    # HNA interval in seconds(float)
1143
    HnaInterval	5.0
1144

    
1145
    # HNA validity time
1146
    HnaValidityTime 	30.0
1147

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

    
1156
    # Weight 0
1157

    
1158

    
1159
}
1160

    
1161
EOD;
1162

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

    
1178
?>
(18-18/27)