Project

General

Profile

Download (32.9 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/* $Id$ */
3
/*
4
	services.inc
5
	part of m0n0wall (http://m0n0.ch/wall)
6

    
7
	Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
8
	All rights reserved.
9

    
10
	Redistribution and use in source and binary forms, with or without
11
	modification, are permitted provided that the following conditions are met:
12

    
13
	1. Redistributions of source code must retain the above copyright notice,
14
	   this list of conditions and the following disclaimer.
15

    
16
	2. Redistributions in binary form must reproduce the above copyright
17
	   notice, this list of conditions and the following disclaimer in the
18
	   documentation and/or other materials provided with the distribution.
19

    
20
	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
21
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
22
	AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
23
	AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
24
	OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29
	POSSIBILITY OF SUCH DAMAGE.
30
*/
31

    
32
/* include all configuration functions */
33
require_once("functions.inc");
34

    
35
function services_dhcpd_configure() {
36
	global $config, $g;
37
	if(isset($config['system']['developerspew'])) {
38
		$mt = microtime();
39
		echo "services_dhcpd_configure($if) being called $mt\n";
40
	}
41

    
42
	/* if OLSRD is enabled, allow WAN to house DHCP. */
43
	if($config['installedpackages']['olsrd'])
44
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd)
45
				if($olsrd['enable'])
46
					$is_olsr_enabled = true;
47

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

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

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

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

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

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

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

    
104

    
105

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

    
115
EOD;
116

    
117
	$dhcpdifs = array();
118

    
119
	/*    loop through and deterimine if we need to setup
120
	 *    failover peer "bleh" entries
121
	 */
122
	$dhcpnum = 0;
123
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
124

    
125
		if(!isset($dhcpifconf['disableauthoritative']))
126
			$dhcpdconf .= "authoritative;\n";
127

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

    
174
EOPP;
175
		$dhcpnum++;
176
		}
177
	}
178

    
179
	$dhcpnum = 0;
180

    
181
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
182

    
183
		$ifcfg = $config['interfaces'][$dhcpif];
184

    
185
		if (!isset($dhcpifconf['enable']) ||
186
			($ifcfg['ipaddr'] == "dhcp") ||
187
			(($dhcpif != "lan") &&
188
			(!isset($ifcfg['enable']) || !$ifcfg['if'] || $ifcfg['bridge'])))
189
			continue;
190

    
191
		if($dhcpif == "lan" && $ifcfg['bridge'])
192
			continue;
193

    
194
		$subnet = gen_subnet($ifcfg['ipaddr'], $ifcfg['subnet']);
195
		$subnetmask = gen_subnet_mask($ifcfg['subnet']);
196

    
197
		if($is_olsr_enabled == true)
198
			if($dhcpifconf['netmask'])
199
				$subnetmask = gen_subnet_mask($dhcpifconf['netmask']);
200

    
201
		$dnscfg = "";
202

    
203
		if ($dhcpifconf['domain']) {
204
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
205
		}
206
		if (isset($dhcpifconf['ddnsupdate'])) {
207
			if($dhcpifconf['ddnsdomain'] <> "") {
208
				$dnscfg .= "	ddns-domainname \"{$dhcpifconf['ddnsdomain']}\";\n";
209
			}
210
			$dnscfg .= "	ddns-update-style interim;\n";
211
		}
212

    
213

    
214
		if (is_array($dhcpifconf['dnsserver']) && ($dhcpifconf['dnsserver'][0])) {
215
			$dnscfg .= "	option domain-name-servers " . join(",", $dhcpifconf['dnsserver']) . ";";
216
		} else if (isset($config['dnsmasq']['enable'])) {
217
			$dnscfg .= "	option domain-name-servers " . $ifcfg['ipaddr'] . ";";
218
		} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
219
			$dnscfg .= "	option domain-name-servers " . join(",", $syscfg['dnsserver']) . ";";
220
		}
221

    
222
		$dhcpdconf .= "subnet $subnet netmask $subnetmask {\n";
223
		$dhcpdconf .= "	pool {\n";
224

    
225
		/* is failover dns setup? */
226
		if (is_array($dhcpifconf['dnsserver']) && $dhcpifconf['dnsserver'][0] <> "") {
227
			$dhcpdconf .= "		option domain-name-servers {$dhcpifconf['dnsserver'][0]}";
228
			if($dhcpifconf['dnsserver'][1] <> "")
229
				$dhcpdconf .= ",{$dhcpifconf['dnsserver'][1]}";
230
			$dhcpdconf .= ";\n";
231
		}
232

    
233
		if($dhcpifconf['failover_peerip'] <> "")
234
			$dhcpdconf .= "		deny dynamic bootp clients;\n";
235

    
236
		if (isset($dhcpifconf['denyunknown']))
237
		   $dhcpdconf .= "		deny unknown clients;\n";
238

    
239
		if ($dhcpifconf['gateway'])
240
			$routers = $dhcpifconf['gateway'];
241
		else
242
			$routers = $ifcfg['ipaddr'];
243

    
244
		if($dhcpifconf['failover_peerip'] <> "") {
245
			$dhcpdconf .= "		failover peer \"dhcp{$dhcpnum}\";\n";
246
			$dhcpnum++;
247
		}
248

    
249
		$dhcpdconf .= <<<EOD
250
		range {$dhcpifconf['range']['from']} {$dhcpifconf['range']['to']};
251
	}
252
	option routers {$routers};
253
$dnscfg
254

    
255
EOD;
256

    
257
		if ($dhcpifconf['defaultleasetime'])
258
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
259
		if ($dhcpifconf['maxleasetime'])
260
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
261

    
262
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
263
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
264
			$dhcpdconf .= "	option netbios-node-type 8;\n";
265
		}
266

    
267
		if(isset($dhcpifconf['netboot'])) {
268
			if (($dhcpifconf['next-server'] <> "") && ($dhcpifconf['filename'] <> "")) {
269
				$dhcpdconf .= "	next-server {$dhcpifconf['next-server']};\n";
270
				$dhcpdconf .= "	filename \"{$dhcpifconf['filename']}\";\n";
271
			}
272
		}
273
		$dhcpdconf .= <<<EOD
274
}
275

    
276
EOD;
277

    
278
		/* add static mappings */
279
		if (is_array($dhcpifconf['staticmap'])) {
280

    
281
			$i = 0;
282
			foreach ($dhcpifconf['staticmap'] as $sm) {
283
				$dhcpdconf .= <<<EOD
284
host s_{$dhcpif}_{$i} {
285
	hardware ethernet {$sm['mac']};
286

    
287
EOD;
288
				if ($sm['ipaddr'])
289
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
290

    
291
				$dhcpdconf .= "}\n";
292
				$i++;
293
			}
294
		}
295

    
296
		$dhcpdifs[] = $ifcfg['if'];
297
	}
298

    
299
	fwrite($fd, $dhcpdconf);
300
	fclose($fd);
301

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

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

    
309
	if ($g['booting']) {
310
		print "done.\n";
311
	}
312

    
313
	return 0;
314
}
315

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

    
323
        $ifcfg = $config['interfaces'][$if];
324

    
325
        /* Enable staticarp, if enabled */
326
        if(isset($config['dhcpd'][$if]['staticarp'])) {
327
                mwexec("/sbin/ifconfig " . escapeshellarg($ifcfg['if']) . " staticarp " );
328
                mwexec("/usr/sbin/arp -ad > /dev/null 2>&1 ");
329
                if (is_array($config['dhcpd'][$if]['staticmap'])) {
330

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

    
334
                        }
335

    
336
                }
337
        } else {
338
                mwexec("/sbin/ifconfig " . escapeshellarg($ifcfg['if']) . " -staticarp " );
339
                mwexec("/usr/sbin/arp -da > /dev/null 2>&1 ");
340
        }
341

    
342
        return 0;
343
}
344

    
345
function services_dhcrelay_configure() {
346
	global $config, $g;
347
	if(isset($config['system']['developerspew'])) {
348
		$mt = microtime();
349
		echo "services_dhcrelay_configure() being called $mt\n";
350
	}
351

    
352
	/* kill any running dhcrelay */
353
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
354

    
355
	$dhcrelaycfg = $config['dhcrelay'];
356

    
357
	/* DHCPRelay enabled on any interfaces? */
358
	$dhcrelayenable = false;
359
	if(is_array($dhcrelaycfg)) {
360
		foreach ($dhcrelaycfg as $dhcrelayif => $dhcrelayifconf) {
361
			if (isset($dhcrelayifconf['enable']) &&
362
				(($dhcrelayif == "lan") ||
363
				(isset($config['interfaces'][$dhcrelayif]['enable']) &&
364
				$config['interfaces'][$dhcrelayif]['if'] && (!$config['interfaces'][$dhcrelayif]['bridge']))))
365
				$dhcrelayenable = true;
366
		}
367
	}
368

    
369
	if (!$dhcrelayenable)
370
		return 0;
371

    
372
	if ($g['booting'])
373
		echo "Starting DHCP relay service...";
374
	else
375
		sleep(1);
376

    
377
	$dhcrelayifs = array();
378
	foreach ($dhcrelaycfg as $dhcrelayif => $dhcrelayifconf) {
379

    
380
		$ifcfg = $config['interfaces'][$dhcrelayif];
381

    
382
		if (!isset($dhcrelayifconf['enable']) ||
383
			(($dhcrelayif != "lan") &&
384
			(!isset($ifcfg['enable']) || !$ifcfg['if'] || $ifcfg['bridge'])))
385
			continue;
386

    
387
		$dhcrelayifs[] = $ifcfg['if'];
388
	}
389

    
390
	/* In order for the relay to work, it needs to be active on the
391
	   interface in which the destination server sits */
392
	foreach ($config['interfaces'] as $ifname) {
393
		$subnet = $ifname['ipaddr'] . "/" . $ifname['subnet'];
394
		if (ip_in_subnet($dhcrelaycfg['server'],$subnet))
395
			$destif = $ifname['if'];
396
	}
397

    
398
	if (!isset($destif))
399
		$destif = $config['interfaces']['wan']['if'];
400

    
401
	$dhcrelayifs[] = $destif;
402
	$dhcrelayifs = array_unique($dhcrelayifs);
403

    
404
	/* fire up dhcrelay */
405
	$cmd = "/usr/local/sbin/dhcrelay -i " .  join(" -i ", $dhcrelayifs);
406

    
407
	if (isset($dhcrelaycfg['agentoption']))
408
		$cmd .=  " -a -m replace";
409

    
410
	$cmd .= " {$dhcrelaycfg['server']}";
411
	mwexec($cmd);
412

    
413
	if (!$g['booting']) {
414
		/* set the reload filter dity flag */
415
		touch("{$g['tmp_path']}/filter_dirty");
416
	}
417

    
418
	return 0;
419
}
420

    
421
function services_dyndns_reset() {
422
	global $config, $g;
423
	if(isset($config['system']['developerspew'])) {
424
		$mt = microtime();
425
		echo "services_dyndns_reset() being called $mt\n";
426
	}
427

    
428
	if (file_exists("{$g['vardb_path']}/ez-ipupdate.cache")) {
429
		conf_mount_rw();
430
		unlink("{$g['vardb_path']}/ez-ipupdate.cache");
431
		conf_mount_ro();
432
	}
433

    
434
	if (file_exists("{$g['conf_path']}/ez-ipupdate.cache")) {
435
		conf_mount_rw();
436
		unlink("{$g['conf_path']}/ez-ipupdate.cache");
437
		conf_mount_ro();
438
	}
439

    
440
	return 0;
441
}
442

    
443
function services_dyndns_configure() {
444
	global $config, $g;
445
	if(isset($config['system']['developerspew'])) {
446
		$mt = microtime();
447
		echo "services_dyndns_configure() being called $mt\n";
448
	}
449

    
450
	$dyndnscfg = $config['dyndns'];
451
	$wancfg = $config['interfaces']['wan'];
452

    
453
	if (isset($dyndnscfg['enable'])) {
454

    
455
		if ($g['booting']) {
456
			echo "Starting DynDNS client...";
457
			if(isset($config['system']['use_old_dyndns'])) {
458
				echo " [Using ez-ipupdate] ";
459
				services_dyndns_configure_old();
460
				return;
461
			}
462
		} else {
463
			sleep(1);
464
			if(isset($config['system']['use_old_dyndns'])) {
465
				services_dyndns_configure_old();
466
				return;
467
			}
468
		}
469

    
470
		/* load up the dyndns.class */
471
		require_once("dyndns.class");
472

    
473
		log_error("DynDns: Running updatedns()");
474

    
475
		/* determine WAN interface name */
476
		$wanif = get_real_wan_interface();
477
		/* get ip */
478
		$ip = find_interface_ip($wanif);
479

    
480
		$dns = new updatedns($dnsService = $config['dyndns']['type'],
481
							 $dnsHost = $config['dyndns']['host'],
482
							 $dnsUser = $config['dyndns']['username'],
483
							 $dnsPass = $config['dyndns']['password'],
484
							 $dnsWilcard = $config['dyndns']['wildcard'],
485
							 $dnsMX = $config['dyndns']['mx']);
486

    
487
		if ($g['booting'])
488
			echo "done.\n";
489
	}
490

    
491
	return 0;
492
}
493

    
494
function services_dyndns_configure_old() {
495
	global $config, $g;
496
	if(isset($config['system']['developerspew'])) {
497
		$mt = microtime();
498
		echo "services_dyndns_configure_old() being called $mt\n";
499
	}
500

    
501
        /* kill any running ez-ipupdate */
502
        /* ez-ipupdate needs SIGQUIT instead of SIGTERM */
503
        sigkillbypid("{$g['varrun_path']}/ez-ipupdate.pid", "QUIT");
504

    
505
        $dyndnscfg = $config['dyndns'];
506
        $wancfg = $config['interfaces']['wan'];
507

    
508
        if (isset($dyndnscfg['enable'])) {
509

    
510
                if ($g['booting'])
511
                        echo "Starting DynDNS client...";
512
                else
513
                        sleep(1);
514

    
515
                /* determine WAN interface name */
516
                $wanif = get_real_wan_interface();
517

    
518
                /* write ez-ipupdate.conf */
519
                $fd = fopen("{$g['varetc_path']}/ez-ipupdate.conf", "w");
520
                if (!$fd) {
521
                        printf("Error: cannot open ez-ipupdate.conf in services_dyndns_configure().\n");
522
                        return 1;
523
                }
524

    
525
                $ezipupdateconf = <<<EOD
526
service-type={$dyndnscfg['type']}
527
user={$dyndnscfg['username']}:{$dyndnscfg['password']}
528
host={$dyndnscfg['host']}
529
interface={$wanif}
530
max-interval=2073600
531
pid-file={$g['varrun_path']}/ez-ipupdate.pid
532
cache-file={$g['vardb_path']}/ez-ipupdate.cache
533
execute=/etc/rc.dyndns.storecache
534
daemon
535

    
536
EOD;
537

    
538
                /* enable server[:port]? */
539
                if ($dyndnscfg['server']) {
540
                        if ($dyndnscfg['port'])
541
                                $ezipupdateconf .= "server={$dyndnscfg['server']}:{$dyndnscfg['port']}\n";
542
                        else
543
                                $ezipupdateconf .= "server={$dyndnscfg['server']}\n";
544
                }
545

    
546
                /* enable MX? */
547
                if ($dyndnscfg['mx']) {
548
                        $ezipupdateconf .= "mx={$dyndnscfg['mx']}\n";
549
                }
550

    
551
                /* enable wildcards? */
552
                if (isset($dyndnscfg['wildcard'])) {
553
                        $ezipupdateconf .= "wildcard\n";
554
                }
555

    
556
                fwrite($fd, $ezipupdateconf);
557
                fclose($fd);
558

    
559
                /* if we're booting, copy the cache file from /conf */
560
                if ($g['booting']) {
561
                        if (file_exists("{$g['conf_path']}/ez-ipupdate.cache")) {
562
                                copy("{$g['conf_path']}/ez-ipupdate.cache", "{$g['vardb_path']}/ez-ipupdate.cache");
563
                       }
564
                }
565

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

    
569
                if ($g['booting'])
570
                        echo "done\n";
571
        }
572

    
573
        return 0;
574
}
575

    
576
function services_dnsmasq_configure() {
577
	global $config, $g;
578
	$return = 0;
579
	
580
	if(isset($config['system']['developerspew'])) {
581
		$mt = microtime();
582
		echo "services_dnsmasq_configure() being called $mt\n";
583
	}
584

    
585
	/* kill any running dnsmasq */
586
	sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
587

    
588
	if (isset($config['dnsmasq']['enable'])) {
589

    
590
		if ($g['booting'])
591
			echo "Starting DNS forwarder...";
592
		else
593
			sleep(1);
594

    
595
		/* generate hosts file */
596
		if(system_hosts_generate()!=0)
597
			$return = 1;
598

    
599
		$args = "";
600

    
601
		if (isset($config['dnsmasq']['regdhcp'])) {
602

    
603
			$args .= " -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases" .
604
				" -s {$config['system']['domain']}";
605
		}
606

    
607
                if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
608
                        foreach($config['dnsmasq']['domainoverrides'] as $override) {
609
                                $args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
610
                        }
611
                }
612

    
613
		/* run dnsmasq */
614
		mwexec("/usr/local/sbin/dnsmasq {$args}");
615

    
616
		if ($g['booting'])
617
			echo "done.\n";
618
	}
619

    
620
	if (!$g['booting']) {
621
		if(services_dhcpd_configure()!=0)
622
			$return = 1;
623
	}
624

    
625
	return $return;
626
}
627

    
628
function services_snmpd_configure() {
629
	global $config, $g;
630
	if(isset($config['system']['developerspew'])) {
631
		$mt = microtime();
632
		echo "services_snmpd_configure() being called $mt\n";
633
	}
634

    
635
	/* kill any running snmpd */
636
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
637
	if(is_process_running("bsnmpd")) 
638
		exec("/usr/bin/killall bsnmpd");
639

    
640
	if (isset($config['snmpd']['enable'])) {
641

    
642
		if ($g['booting'])
643
			echo "Starting SNMP daemon... ";
644

    
645
		/* generate snmpd.conf */
646
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
647
		if (!$fd) {
648
			printf("Error: cannot open snmpd.conf in services_snmpd_configure().\n");
649
			return 1;
650
		}
651

    
652

    
653
		$snmpdconf = <<<EOD
654
location := "{$config['snmpd']['syslocation']}"
655
contact := "{$config['snmpd']['syscontact']}"
656
read := "{$config['snmpd']['rocommunity']}"
657

    
658
EOD;
659

    
660
/* No docs on what write strings do there for disable for now.
661
		if(isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])){
662
		    $snmpdconf .= <<<EOD
663
# write string
664
write := "{$config['snmpd']['rwcommunity']}"
665

    
666
EOD;
667
		}
668
*/
669

    
670

    
671
		if(isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])){
672
		    $snmpdconf .= <<<EOD
673
# SNMP Trap support.
674
traphost := {$config['snmpd']['trapserver']}
675
trapport := {$config['snmpd']['trapserverport']}
676
trap := "{$config['snmpd']['trapstring']}"
677

    
678

    
679
EOD;
680
		}
681

    
682

    
683
		$snmpdconf .= <<<EOD
684
system := 1     # pfSense
685
%snmpd
686
begemotSnmpdDebugDumpPdus       = 2
687
begemotSnmpdDebugSyslogPri      = 7
688
begemotSnmpdCommunityString.0.1 = $(read)
689

    
690
EOD;
691

    
692
/* No docs on what write strings do there for disable for now.
693
		if(isset($config['snmpd']['rwcommunity']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])){
694
		    $snmpdconf .= <<<EOD
695
begemotSnmpdCommunityString.0.2 = $(write)
696

    
697
EOD;
698
		}
699
*/
700

    
701

    
702
		if(isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])){
703
		    $snmpdconf .= <<<EOD
704
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
705
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
706
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
707

    
708
EOD;
709
		}
710

    
711

    
712
		$snmpdconf .= <<<EOD
713
begemotSnmpdCommunityDisable    = 1
714

    
715
EOD;
716

    
717
		if(isset($config['snmpd']['bindlan'])) {
718
			$bind_to_ip = $config['interfaces']['lan']['ipaddr'];
719
		} else {
720
			$bind_to_ip = "0.0.0.0";
721
		}
722

    
723
		if(is_port( $config['snmpd']['pollport'] )) {
724
		    $snmpdconf .= <<<EOD
725
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
726

    
727
EOD;
728

    
729
		}
730

    
731
		$snmpdconf .= <<<EOD
732
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
733
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
734

    
735
# These are bsnmp macros not php vars.
736
sysContact      = $(contact)
737
sysLocation     = $(location)
738
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
739

    
740
snmpEnableAuthenTraps = 2
741

    
742
EOD;
743

    
744
		if (is_array( $config['snmpd']['modules'] )) {
745
		    if(isset($config['snmpd']['modules']['mibii'])) {
746
			$snmpdconf .= <<<EOD
747
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
748

    
749
EOD;
750
		    }
751

    
752
		    if(isset($config['snmpd']['modules']['netgraph'])) {
753
			$snmpdconf .= <<<EOD
754
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
755
%netgraph
756
begemotNgControlNodeName = "snmpd"
757

    
758
EOD;
759
		    }
760

    
761
		    if(isset($config['snmpd']['modules']['pf'])) {
762
			$snmpdconf .= <<<EOD
763
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
764

    
765
EOD;
766
		    }
767

    
768
		    if(isset($config['snmpd']['modules']['hostres'])) {
769
			$snmpdconf .= <<<EOD
770
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
771

    
772
EOD;
773
		    }
774
		    if(isset($config['snmpd']['modules']['bridge'])) {
775
			$snmpdconf .= <<<EOD
776
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
777
# config must end with blank line
778

    
779

    
780
EOD;
781
		    }
782
		}
783

    
784
		fwrite($fd, $snmpdconf);
785
		fclose($fd);
786

    
787
		if (isset($config['snmpd']['bindlan'])) {
788
			$bindlan = "";
789
		}
790

    
791
		/* run bsnmpd */
792
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
793
			"{$bindlan} -p {$g['varrun_path']}/snmpd.pid");
794

    
795
		if ($g['booting'])
796
			echo "done.\n";
797
	}
798

    
799
	return 0;
800
}
801

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

    
809
	/* kill any running choparp */
810
	killbyname("choparp");
811

    
812
	if (isset($config['virtualip']) && is_array($config['virtualip']['vip'])) {
813
		$paa = array();
814

    
815
		/* group by interface */
816
		foreach ($config['virtualip']['vip'] as $vipent) {
817
			if ($vipent['mode'] === "proxyarp") {
818
				if ($vipent['interface'])
819
					$if = $vipent['interface'];
820
				else
821
					$if = "wan";
822

    
823
				if (!is_array($paa[$if]))
824
					$paa[$if] = array();
825

    
826
				$paa[$if][] = $vipent;
827
			}
828
		}
829

    
830
		if (count($paa))
831
		foreach ($paa as $paif => $paents) {
832
			if ($paif == "wan" && !(is_ipaddr($config['interfaces']['wan']['ipaddr']) ||
833
                                       ($config['interfaces']['wan']['ipaddr'] == "dhcp") ||
834
                                       ($config['interfaces']['wan']['ipaddr'] == "bigpond")))
835
                               continue;
836

    
837
			$args = $config['interfaces'][$paif]['if'] . " auto";
838

    
839
			foreach ($paents as $paent) {
840

    
841
				if (isset($paent['subnet']))
842
					$args .= " " . escapeshellarg("{$paent['subnet']}/{$paent['subnet_bits']}");
843
				else if (isset($paent['range']))
844
					$args .= " " . escapeshellarg($paent['range']['from'] . "-" .
845
						$paent['range']['to']);
846
			}
847

    
848
			mwexec_bg("/usr/local/sbin/choparp " . $args);
849
		}
850
	}
851
}
852

    
853
function services_dnsupdate_process() {
854
	global $config, $g;
855
	if(isset($config['system']['developerspew'])) {
856
		$mt = microtime();
857
		echo "services_dnsupdate_process() being called $mt\n";
858
	}
859

    
860
	/* Dynamic DNS updating active? */
861
	if (isset($config['dnsupdate']['enable'])) {
862

    
863
		$wanip = get_current_wan_address();
864
		if ($wanip) {
865

    
866
			$keyname = $config['dnsupdate']['keyname'];
867
			/* trailing dot */
868
			if (substr($keyname, -1) != ".")
869
				$keyname .= ".";
870

    
871
			$hostname = $config['dnsupdate']['host'];
872
			/* trailing dot */
873
			if (substr($hostname, -1) != ".")
874
				$hostname .= ".";
875

    
876
			/* write private key file
877
			   this is dumb - public and private keys are the same for HMAC-MD5,
878
			   but nsupdate insists on having both */
879
			$fd = fopen("{$g['varetc_path']}/K{$keyname}+157+00000.private", "w");
880
			$privkey .= <<<EOD
881
Private-key-format: v1.2
882
Algorithm: 157 (HMAC)
883
Key: {$config['dnsupdate']['keydata']}
884

    
885
EOD;
886
			fwrite($fd, $privkey);
887
			fclose($fd);
888

    
889
			/* write public key file */
890
			if ($config['dnsupdate']['keytype'] == "zone") {
891
				$flags = 257;
892
				$proto = 3;
893
			} else if ($config['dnsupdate']['keytype'] == "host") {
894
				$flags = 513;
895
				$proto = 3;
896
			} else if ($config['dnsupdate']['keytype'] == "user") {
897
				$flags = 0;
898
				$proto = 2;
899
			}
900

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

    
905
			/* generate update instructions */
906
			$upinst =  "update delete {$config['dnsupdate']['host']} A\n";
907
			$upinst .= "update add {$config['dnsupdate']['host']} {$config['dnsupdate']['ttl']} A {$wanip}\n";
908
			$upinst .= "\n";	/* mind that trailing newline! */
909

    
910
			$fd = fopen("{$g['varetc_path']}/nsupdatecmds", "w");
911
			fwrite($fd, $upinst);
912
			fclose($fd);
913

    
914
			/* invoke nsupdate */
915
			$cmd = "/usr/sbin/nsupdate -k {$g['varetc_path']}/K{$keyname}+157+00000.key";
916
			if (isset($config['dnsupdate']['usetcp']))
917
				$cmd .= " -v";
918
			$cmd .= " {$g['varetc_path']}/nsupdatecmds";
919

    
920
			mwexec_bg($cmd);
921
		}
922
	}
923

    
924
	return 0;
925
}
926

    
927
function setup_wireless_olsr() {
928
	global $config, $g;
929
	if(!$config['installedpackages']['olsrd'] || !$config['installedpackages'])
930
		return;
931
	if(isset($config['system']['developerspew'])) {
932
		$mt = microtime();
933
		echo "setup_wireless_olsr($interface) being called $mt\n";
934
	}
935
	conf_mount_rw();
936
	foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
937
		$olsr_enable = $olsrd['enable'];
938
		if($olsr_enable <> "on")
939
			return;
940
		$fd = fopen("{$g['varetc_path']}/olsr.conf", "w");
941

    
942
		if($olsrd['announcedynamicroute'] or $olsrd['enableannounce'] == "on") {
943
			$enableannounce .= "\nHna4\n";
944
			$enableannounce .= "{\n";
945
		if($olsrd['announcedynamicroute'])
946
			$enableannounce .= "\t{$olsrd['announcedynamicroute']}\n";
947
		if($olsrd['enableannounce'] == "on")
948
			$enableannounce .= "0.0.0.0 0.0.0.0";
949
			$enableannounce .= "\n}\n";
950
		} else {
951
			$enableannounce = "";
952
		}
953

    
954
		$olsr .= <<<EODA
955
#
956
# olsr.org OLSR daemon config file
957
#
958
# Lines starting with a # are discarded
959
#
960
# This file was generated by setup_wireless_olsr() in services.inc
961
#
962

    
963
# This file is an example of a typical
964
# configuration for a mostly static
965
# network(regarding mobility) using
966
# the LQ extention
967

    
968
# Debug level(0-9)
969
# If set to 0 the daemon runs in the background
970

    
971
DebugLevel	2
972

    
973
# IP version to use (4 or 6)
974

    
975
IpVersion	4
976

    
977
# Clear the screen each time the internal state changes
978

    
979
ClearScreen     yes
980

    
981
{$enableannounce}
982

    
983
# Should olsrd keep on running even if there are
984
# no interfaces available? This is a good idea
985
# for a PCMCIA/USB hotswap environment.
986
# "yes" OR "no"
987

    
988
AllowNoInt	yes
989

    
990
# TOS(type of service) value for
991
# the IP header of control traffic.
992
# If not set it will default to 16
993

    
994
#TosValue	16
995

    
996
# The fixed willingness to use(0-7)
997
# If not set willingness will be calculated
998
# dynamically based on battery/power status
999
# if such information is available
1000

    
1001
#Willingness    	4
1002

    
1003
# Allow processes like the GUI front-end
1004
# to connect to the daemon.
1005

    
1006
IpcConnect
1007
{
1008
     # Determines how many simultaneously
1009
     # IPC connections that will be allowed
1010
     # Setting this to 0 disables IPC
1011

    
1012
     MaxConnections  0
1013

    
1014
     # By default only 127.0.0.1 is allowed
1015
     # to connect. Here allowed hosts can
1016
     # be added
1017

    
1018
     Host            127.0.0.1
1019
     #Host            10.0.0.5
1020

    
1021
     # You can also specify entire net-ranges
1022
     # that are allowed to connect. Multiple
1023
     # entries are allowed
1024

    
1025
     #Net             192.168.1.0 255.255.255.0
1026
}
1027

    
1028
# Wether to use hysteresis or not
1029
# Hysteresis adds more robustness to the
1030
# link sensing but delays neighbor registration.
1031
# Used by default. 'yes' or 'no'
1032

    
1033
UseHysteresis	no
1034

    
1035
# Hysteresis parameters
1036
# Do not alter these unless you know
1037
# what you are doing!
1038
# Set to auto by default. Allowed
1039
# values are floating point values
1040
# in the interval 0,1
1041
# THR_LOW must always be lower than
1042
# THR_HIGH.
1043

    
1044
#HystScaling	0.50
1045
#HystThrHigh	0.80
1046
#HystThrLow	0.30
1047

    
1048

    
1049
# Link quality level
1050
# 0 = do not use link quality
1051
# 1 = use link quality for MPR selection
1052
# 2 = use link quality for MPR selection and routing
1053
# Defaults to 0
1054

    
1055
LinkQualityLevel	{$olsrd['enablelqe']}
1056

    
1057
# Link quality window size
1058
# Defaults to 10
1059

    
1060
LinkQualityWinSize	10
1061

    
1062
# Polling rate in seconds(float).
1063
# Default value 0.05 sec
1064

    
1065
Pollrate	0.05
1066

    
1067

    
1068
# TC redundancy
1069
# Specifies how much neighbor info should
1070
# be sent in TC messages
1071
# Possible values are:
1072
# 0 - only send MPR selectors
1073
# 1 - send MPR selectors and MPRs
1074
# 2 - send all neighbors
1075
#
1076
# defaults to 0
1077

    
1078
TcRedundancy	2
1079

    
1080
#
1081
# MPR coverage
1082
# Specifies how many MPRs a node should
1083
# try select to reach every 2 hop neighbor
1084
#
1085
# Can be set to any integer >0
1086
#
1087
# defaults to 1
1088

    
1089
MprCoverage	3
1090

    
1091
# Example plugin entry with parameters:
1092

    
1093
EODA;
1094

    
1095
if($olsrd['enablehttpinfo'] == "on") {
1096
	$olsr .= <<<EODB
1097

    
1098
LoadPlugin "/usr/local/lib/olsrd_httpinfo.so.0.1"
1099
{
1100
    PlParam     "port"   "{$olsrd['port']}"
1101
    PlParam     "Net"    "{$olsrd['allowedhttpinfohost']} {$olsrd['allowedhttpinfosubnet']}"
1102
}
1103

    
1104
EODB;
1105

    
1106
}
1107

    
1108
if($olsrd['enabledsecure'] == "on") {
1109
	$olsr .= <<<EODC
1110

    
1111
LoadPlugin "/usr/local/lib/olsrd_secure.so.0.5"
1112
{
1113
    PlParam     "Keyfile"   "/usr/local/etc/olsrkey.txt"
1114
}
1115

    
1116
EODC;
1117

    
1118
}
1119

    
1120
if($olsrd['enabledyngw'] == "on") {
1121

    
1122
	/* unset default route, olsr auto negotiates */
1123
	mwexec("/sbin/route delete default");
1124

    
1125
	$olsr .= <<<EODE
1126

    
1127
LoadPlugin "/usr/local/lib/olsrd_dyn_gw.so.0.4"
1128
{
1129
    # how often to look for a inet gw, in seconds
1130
    # defaults to 5 secs, if commented out
1131
    PlParam     "Interval"   "{$olsrd['polling']}"
1132

    
1133
    # if one or more IPv4 addresses are given, do a ping on these in
1134
    # descending order to validate that there is not only an entry in
1135
    # routing table, but also a real internet connection. If any of
1136
    # these addresses could be pinged successfully, the test was
1137
    # succesful, i.e. if the ping on the 1st address was successful,the
1138
    # 2nd won't be pinged
1139
    PlParam     "Ping"       "{$olsrd['ping']}"
1140
    #PlParam     "HNA"   "192.168.81.0 255.255.255.0"
1141
}
1142

    
1143
EODE;
1144

    
1145
}
1146

    
1147
foreach($config['installedpackages']['olsrd']['config'] as $conf) {
1148
	$interfaces = explode(',', $conf['iface_array']);
1149
	foreach($interfaces as $interface) {
1150
		$realinterface = convert_friendly_interface_to_real_interface_name($interface);
1151
$olsr .= <<<EODAD
1152
Interface "{$realinterface}"
1153
{
1154

    
1155
    # Hello interval in seconds(float)
1156
    HelloInterval    2.0
1157

    
1158
    # HELLO validity time
1159
    HelloValidityTime	20.0
1160

    
1161
    # TC interval in seconds(float)
1162
    TcInterval        5.0
1163

    
1164
    # TC validity time
1165
    TcValidityTime	30.0
1166

    
1167
    # MID interval in seconds(float)
1168
    MidInterval	5.0
1169

    
1170
    # MID validity time
1171
    MidValidityTime	30.0
1172

    
1173
    # HNA interval in seconds(float)
1174
    HnaInterval	5.0
1175

    
1176
    # HNA validity time
1177
    HnaValidityTime 	30.0
1178

    
1179
    # When multiple links exist between hosts
1180
    # the weight of interface is used to determine
1181
    # the link to use. Normally the weight is
1182
    # automatically calculated by olsrd based
1183
    # on the characteristics of the interface,
1184
    # but here you can specify a fixed value.
1185
    # Olsrd will choose links with the lowest value.
1186

    
1187
    # Weight 0
1188

    
1189

    
1190
}
1191

    
1192
EODAD;
1193

    
1194
	}
1195
	break;
1196
}
1197
		fwrite($fd, $olsr);
1198
		fclose($fd);
1199
	}
1200

    
1201
	if(is_process_running("olsrd"))
1202
		mwexec("/usr/bin/killall olsrd");
1203

    
1204
	sleep(2);
1205

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

    
1208
	conf_mount_ro();
1209
}
1210

    
1211
/* configure cron service */
1212
function configure_cron() {
1213
	global $g, $config;
1214
	if (!$g['booting'])
1215
		conf_mount_rw();
1216
	/* preserve existing crontab entries */
1217
	$crontab_contents = file_get_contents("/etc/crontab");
1218
	$crontab_contents_a = split("\n", $crontab_contents);
1219
	
1220
	for ($i = 0; $i < count($crontab_contents_a); $i++) {
1221
		$item =& $crontab_contents_a[$i];
1222
		if (strpos($item, "# pfSense specific crontab entries") !== false) {
1223
			array_splice($crontab_contents_a, $i - 1);
1224
			break;
1225
		}
1226
	}
1227
	$crontab_contents = implode("\n", $crontab_contents_a) . "\n";
1228
	
1229
	
1230
	if (is_array($config['cron']['item'])) {
1231
		$crontab_contents .= "#\n";
1232
		$crontab_contents .= "# pfSense specific crontab entries\n";
1233
		$crontab_contents .= "# Created: " . date("F j, Y, g:i a") . "\n";
1234
		$crontab_contents .= "#\n";
1235

    
1236
		foreach ($config['cron']['item'] as $item) {
1237
			$crontab_contents .= "\n{$item['minute']}\t";
1238
			$crontab_contents .= "{$item['hour']}\t";
1239
			$crontab_contents .= "{$item['mday']}\t";
1240
			$crontab_contents .= "{$item['month']}\t";
1241
			$crontab_contents .= "{$item['wday']}\t";
1242
			$crontab_contents .= "{$item['who']}\t";
1243
			$crontab_contents .= "{$item['command']}";
1244
		}
1245
    
1246
		$crontab_contents .= "\n#\n";
1247
		$crontab_contents .= "# If possible do not add items to this file manually.\n";
1248
		$crontab_contents .= "# If you do so, this file must be terminated with a blank line (e.g. new line)\n";
1249
		$crontab_contents .= "#\n\n";
1250
	}
1251
	
1252
	/* please maintain the newline at the end of file */
1253
	file_put_contents("/etc/crontab", $crontab_contents);
1254
	
1255
	if (!$g['booting'])
1256
		conf_mount_ro();
1257
}
1258

    
1259
?>
(19-19/29)