Project

General

Profile

Download (34.7 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 load_balancer_use_sticky() {
36
	global $config, $g;
37
	if (isset ($config['system']['lb_use_sticky']))
38
		touch("/var/etc/use_pf_pool__stickyaddr");
39
	else
40
		unlink_if_exists("/var/etc/use_pf_pool__stickyaddr");
41
}
42

    
43
function services_dhcpd_configure() {
44
	global $config, $g;
45
	if(isset($config['system']['developerspew'])) {
46
		$mt = microtime();
47
		echo "services_dhcpd_configure($if) being called $mt\n";
48
	}
49

    
50
	/* if OLSRD is enabled, allow WAN to house DHCP. */
51
	if($config['installedpackages']['olsrd'])
52
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd)
53
				if($olsrd['enable'])
54
					$is_olsr_enabled = true;
55

    
56
	/* configure DHCPD chroot */
57
	$fd = fopen("/tmp/dhcpd.sh","w");
58
	$status = `mount | grep "{$g['dhcpd_chroot_path']}/dev"`;
59
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}\n");
60
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/dev\n");
61
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/etc\n");
62
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/usr/local/sbin\n");
63
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/var/db\n");
64
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/var/run\n");
65
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/usr\n");
66
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/lib\n");
67
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/run\n");
68
	fwrite($fd, "chown -R dhcpd:_dhcp {$g['dhcpd_chroot_path']}/*\n");
69
	fwrite($fd, "cp /lib/libc.so.* {$g['dhcpd_chroot_path']}/lib/\n");
70
	fwrite($fd, "cp /usr/local/sbin/dhcpd {$g['dhcpd_chroot_path']}/usr/local/sbin/\n");
71
	fwrite($fd, "chmod a+rx {$g['dhcpd_chroot_path']}/usr/local/sbin/dhcpd\n");
72
	if(!trim($status))
73
		fwrite($fd, "mount -t devfs devfs {$g['dhcpd_chroot_path']}/dev\n");
74
	fclose($fd);
75
	mwexec("/bin/sh /tmp/dhcpd.sh");
76

    
77
	/* kill any running dhcpd */
78
	if(is_process_running("dhcpd"))
79
		mwexec("killall dhcpd", true);
80

    
81
	$syscfg = $config['system'];
82
	$dhcpdcfg = $config['dhcpd'];
83

    
84
	/* DHCP enabled on any interfaces? */
85
	$dhcpdenable = false;
86
	if(is_array($dhcpdcfg))
87
		foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
88
			if (isset($dhcpifconf['enable']) &&
89
				(($dhcpif == "lan") ||
90
				(isset($config['interfaces'][$dhcpif]['enable']) &&
91
				$config['interfaces'][$dhcpif]['if'] && (!$config['interfaces'][$dhcpif]['bridge']))))
92
				$dhcpdenable = true;
93
			if (isset($dhcpifconf['enable']) &&
94
				(($dhcpif == "wan") || (isset($config['interfaces'][$dhcpif]['enable']) &&
95
				$config['interfaces'][$dhcpif]['if'] && (!$config['interfaces'][$dhcpif]['bridge']))))
96
				$dhcpdenable = true;
97
		}
98

    
99
	if (!$dhcpdenable)
100
		return 0;
101

    
102
	if ($g['booting'])
103
		echo "Starting DHCP service...";
104
	else
105
		sleep(1);
106

    
107
	/* write dhcpd.conf */
108
	$fd = fopen("{$g['dhcpd_chroot_path']}/etc/dhcpd.conf", "w");
109
	if (!$fd) {
110
		printf("Error: cannot open dhcpd.conf in services_dhcpd_configure().\n");
111
		return 1;
112
	}
113

    
114

    
115

    
116
	$dhcpdconf = <<<EOD
117
option domain-name "{$syscfg['domain']}";
118
default-lease-time 7200;
119
max-lease-time 86400;
120
authoritative;
121
log-facility local7;
122
ddns-update-style none;
123
one-lease-per-client true;
124
deny duplicates;
125

    
126
EOD;
127

    
128
	$dhcpdifs = array();
129

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

    
181
EOPP;
182
		$dhcpnum++;
183
		}
184
	}
185

    
186
	$dhcpnum = 0;
187

    
188
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
189

    
190
		$ifcfg = $config['interfaces'][$dhcpif];
191

    
192
		if (!isset($dhcpifconf['enable']) ||
193
			($ifcfg['ipaddr'] == "dhcp") ||
194
			(($dhcpif != "lan") &&
195
			(!isset($ifcfg['enable']) || !$ifcfg['if'] || $ifcfg['bridge'])))
196
			continue;
197

    
198
		if($dhcpif == "lan" && $ifcfg['bridge'])
199
			log_error("NOTE: DHCP Server on LAN is enabled.");
200

    
201
		$subnet = gen_subnet($ifcfg['ipaddr'], $ifcfg['subnet']);
202
		$subnetmask = gen_subnet_mask($ifcfg['subnet']);
203

    
204
		if($is_olsr_enabled == true)
205
			if($dhcpifconf['netmask'])
206
				$subnetmask = gen_subnet_mask($dhcpifconf['netmask']);
207

    
208
		$dnscfg = "";
209

    
210
		if ($dhcpifconf['domain']) {
211
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
212
		}
213
		if (isset($dhcpifconf['ddnsupdate'])) {
214
			if($dhcpifconf['ddnsdomain'] <> "") {
215
				$dnscfg .= "	ddns-domainname \"{$dhcpifconf['ddnsdomain']}\";\n";
216
			}
217
			$dnscfg .= "	ddns-update-style interim;\n";
218
		}
219

    
220

    
221
		if (is_array($dhcpifconf['dnsserver']) && ($dhcpifconf['dnsserver'][0])) {
222
			$dnscfg .= "	option domain-name-servers " . join(",", $dhcpifconf['dnsserver']) . ";";
223
		} else if (isset($config['dnsmasq']['enable'])) {
224
			$dnscfg .= "	option domain-name-servers " . $ifcfg['ipaddr'] . ";";
225
		} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
226
			$dnscfg .= "	option domain-name-servers " . join(",", $syscfg['dnsserver']) . ";";
227
		}
228

    
229
		$dhcpdconf .= "subnet $subnet netmask $subnetmask {\n";
230
		$dhcpdconf .= "	pool {\n";
231

    
232
		/* is failover dns setup? */
233
		if (is_array($dhcpifconf['dnsserver']) && $dhcpifconf['dnsserver'][0] <> "") {
234
			$dhcpdconf .= "		option domain-name-servers {$dhcpifconf['dnsserver'][0]}";
235
			if($dhcpifconf['dnsserver'][1] <> "")
236
				$dhcpdconf .= ",{$dhcpifconf['dnsserver'][1]}";
237
			$dhcpdconf .= ";\n";
238
		}
239

    
240
		if($dhcpifconf['failover_peerip'] <> "")
241
			$dhcpdconf .= "		deny dynamic bootp clients;\n";
242

    
243
		if (isset($dhcpifconf['denyunknown']))
244
		   $dhcpdconf .= "		deny unknown clients;\n";
245

    
246
		if ($dhcpifconf['gateway'])
247
			$routers = $dhcpifconf['gateway'];
248
		else
249
			$routers = $ifcfg['ipaddr'];
250

    
251
		if($dhcpifconf['failover_peerip'] <> "") {
252
			$dhcpdconf .= "		failover peer \"dhcp{$dhcpnum}\";\n";
253
			$dhcpnum++;
254
		}
255

    
256
		$dhcpdconf .= <<<EOD
257
		range {$dhcpifconf['range']['from']} {$dhcpifconf['range']['to']};
258
	}
259
	option routers {$routers};
260
$dnscfg
261

    
262
EOD;
263

    
264
		if ($dhcpifconf['defaultleasetime'])
265
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
266
		if ($dhcpifconf['maxleasetime'])
267
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
268

    
269
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
270
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
271
			$dhcpdconf .= "	option netbios-node-type 8;\n";
272
		}
273

    
274
		if (is_array($dhcpifconf['ntpserver']) && $dhcpifconf['ntpserver'][0])
275
			$dhcpdconf .= "	option ntp-servers " . join(",", $dhcpifconf['ntpserver']) . ";\n";
276

    
277
		if(isset($dhcpifconf['netboot'])) {
278
			if (($dhcpifconf['next-server'] <> "") && ($dhcpifconf['filename'] <> "")) {
279
				$dhcpdconf .= "	next-server {$dhcpifconf['next-server']};\n";
280
				$dhcpdconf .= "	filename \"{$dhcpifconf['filename']}\";\n";
281
			}
282
		}
283
		$dhcpdconf .= <<<EOD
284
}
285

    
286
EOD;
287

    
288
		/* add static mappings */
289
		if (is_array($dhcpifconf['staticmap'])) {
290

    
291
			$i = 0;
292
			foreach ($dhcpifconf['staticmap'] as $sm) {
293
				$dhcpdconf .= <<<EOD
294
host s_{$dhcpif}_{$i} {
295
	hardware ethernet {$sm['mac']};
296

    
297
EOD;
298
				if ($sm['ipaddr'])
299
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
300

    
301
				$dhcpdconf .= "}\n";
302
				$i++;
303
			}
304
		}
305

    
306
		$dhcpdifs[] = $ifcfg['if'];
307
	}
308

    
309
	fwrite($fd, $dhcpdconf);
310
	fclose($fd);
311

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

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

    
319
	if ($g['booting']) {
320
		print "done.\n";
321
	}
322

    
323
	return 0;
324
}
325

    
326
function interfaces_staticarp_configure($if) {
327
	global $config, $g;
328
	if(isset($config['system']['developerspew'])) {
329
		$mt = microtime();
330
		echo "interfaces_staticarp_configure($if) being called $mt\n";
331
	}
332

    
333
        $ifcfg = $config['interfaces'][$if];
334

    
335
        /* Enable staticarp, if enabled */
336
        if(isset($config['dhcpd'][$if]['staticarp'])) {
337
                mwexec("/sbin/ifconfig " . escapeshellarg($ifcfg['if']) . " staticarp " );
338
                mwexec("/usr/sbin/arp -ad > /dev/null 2>&1 ");
339
                if (is_array($config['dhcpd'][$if]['staticmap'])) {
340

    
341
                        foreach ($config['dhcpd'][$if]['staticmap'] as $arpent) {
342
                                mwexec("/usr/sbin/arp -s " . escapeshellarg($arpent['ipaddr']) . " " . escapeshellarg($arpent['mac']));
343
								log_error("/usr/sbin/arp -s " . escapeshellarg($arpent['ipaddr']) . " " . escapeshellarg($arpent['mac']));
344
                        }
345

    
346
                }
347
        } else {
348
                mwexec("/sbin/ifconfig " . escapeshellarg($ifcfg['if']) . " -staticarp " );
349
                mwexec("/usr/sbin/arp -da > /dev/null 2>&1 ");
350
        }
351

    
352
        return 0;
353
}
354

    
355
function services_dhcrelay_configure() {
356
	global $config, $g;
357
	if(isset($config['system']['developerspew'])) {
358
		$mt = microtime();
359
		echo "services_dhcrelay_configure() being called $mt\n";
360
	}
361

    
362
	/* kill any running dhcrelay */
363
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
364

    
365
	$dhcrelaycfg = $config['dhcrelay'];
366

    
367
	/* DHCPRelay enabled on any interfaces? */
368
	$dhcrelayenable = false;
369
	if(is_array($dhcrelaycfg)) {
370
		foreach ($dhcrelaycfg as $dhcrelayif => $dhcrelayifconf) {
371
			if (isset($dhcrelayifconf['enable']) &&
372
				(($dhcrelayif == "lan") ||
373
				(isset($config['interfaces'][$dhcrelayif]['enable']) &&
374
				$config['interfaces'][$dhcrelayif]['if'] && (!$config['interfaces'][$dhcrelayif]['bridge']))))
375
				$dhcrelayenable = true;
376
		}
377
	}
378

    
379
	if (!$dhcrelayenable)
380
		return 0;
381

    
382
	if ($g['booting'])
383
		echo "Starting DHCP relay service...";
384
	else
385
		sleep(1);
386

    
387
	$dhcrelayifs = array();
388
	foreach ($dhcrelaycfg as $dhcrelayif => $dhcrelayifconf) {
389

    
390
		$ifcfg = $config['interfaces'][$dhcrelayif];
391

    
392
		if (!isset($dhcrelayifconf['enable']) ||
393
			(($dhcrelayif != "lan") &&
394
			(!isset($ifcfg['enable']) || !$ifcfg['if'] || $ifcfg['bridge'])))
395
			continue;
396

    
397
		$dhcrelayifs[] = $ifcfg['if'];
398
	}
399

    
400
	/* In order for the relay to work, it needs to be active on the
401
	   interface in which the destination server sits */
402
	foreach ($config['interfaces'] as $ifname) {
403
		$subnet = $ifname['ipaddr'] . "/" . $ifname['subnet'];
404
		if (ip_in_subnet($dhcrelaycfg['server'],$subnet))
405
			$destif = $ifname['if'];
406
	}
407

    
408
	if (!isset($destif))
409
		$destif = $config['interfaces']['wan']['if'];
410

    
411
	$dhcrelayifs[] = $destif;
412
	$dhcrelayifs = array_unique($dhcrelayifs);
413

    
414
	/* fire up dhcrelay */
415
	$cmd = "/usr/local/sbin/dhcrelay -i " .  join(" -i ", $dhcrelayifs);
416

    
417
	if (isset($dhcrelaycfg['agentoption']))
418
		$cmd .=  " -a -m replace";
419

    
420
	$cmd .= " {$dhcrelaycfg['server']}";
421
	mwexec($cmd);
422

    
423
	if (!$g['booting']) {
424
		/* set the reload filter dity flag */
425
		touch("{$g['tmp_path']}/filter_dirty");
426
	}
427

    
428
	return 0;
429
}
430

    
431
function services_dyndns_reset() {
432
	global $config, $g;
433
	if(isset($config['system']['developerspew'])) {
434
		$mt = microtime();
435
		echo "services_dyndns_reset() being called $mt\n";
436
	}
437

    
438
	if (file_exists("{$g['vardb_path']}/ez-ipupdate.cache")) {
439
		conf_mount_rw();
440
		unlink("{$g['vardb_path']}/ez-ipupdate.cache");
441
		conf_mount_ro();
442
	}
443

    
444
	if (file_exists("{$g['conf_path']}/ez-ipupdate.cache")) {
445
		conf_mount_rw();
446
		unlink("{$g['conf_path']}/ez-ipupdate.cache");
447
		conf_mount_ro();
448
	}
449
	
450
	if (file_exists("{$g['conf_path']}/dyndns.cache")) {
451
		conf_mount_rw();
452
		unlink("{$g['conf_path']}/dyndns.cache");
453
		conf_mount_ro();
454
	}
455

    
456
	return 0;
457
}
458

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

    
466
	$dyndnscfg = $config['dyndns'];
467
	$wancfg = $config['interfaces']['wan'];
468

    
469
	if (isset($dyndnscfg['enable'])) {
470

    
471
		if ($g['booting']) {
472
			echo "Starting DynDNS client...";
473
			if(isset($config['system']['use_old_dyndns'])) {
474
				echo " [Using ez-ipupdate] ";
475
				services_dyndns_configure_old();
476
				return;
477
			}
478
		} else {
479
			sleep(1);
480
			if(isset($config['system']['use_old_dyndns'])) {
481
				services_dyndns_configure_old();
482
				return;
483
			}
484
		}
485

    
486
		/* load up the dyndns.class */
487
		require_once("dyndns.class");
488

    
489
		log_error("DynDns: Running updatedns()");
490

    
491
		/* determine WAN interface name */
492
		$wanif = get_real_wan_interface();
493
		/* get ip */
494
		$ip = find_interface_ip($wanif);
495

    
496
		$dns = new updatedns($dnsService = $config['dyndns']['type'],
497
							 $dnsHost = $config['dyndns']['host'],
498
							 $dnsUser = $config['dyndns']['username'],
499
							 $dnsPass = $config['dyndns']['password'],
500
							 $dnsWilcard = $config['dyndns']['wildcard'],
501
							 $dnsMX = $config['dyndns']['mx']);
502

    
503
		if ($g['booting'])
504
			echo "done.\n";
505
	}
506

    
507
	return 0;
508
}
509

    
510
function services_dyndns_configure_old() {
511
	global $config, $g;
512
	if(isset($config['system']['developerspew'])) {
513
		$mt = microtime();
514
		echo "services_dyndns_configure_old() being called $mt\n";
515
	}
516

    
517
        /* kill any running ez-ipupdate */
518
        /* ez-ipupdate needs SIGQUIT instead of SIGTERM */
519
        sigkillbypid("{$g['varrun_path']}/ez-ipupdate.pid", "QUIT");
520

    
521
        $dyndnscfg = $config['dyndns'];
522
        $wancfg = $config['interfaces']['wan'];
523

    
524
        if (isset($dyndnscfg['enable'])) {
525

    
526
                if ($g['booting'])
527
                        echo "Starting DynDNS client...";
528
                else
529
                        sleep(1);
530

    
531
                /* determine WAN interface name */
532
                $wanif = get_real_wan_interface();
533

    
534
                /* write ez-ipupdate.conf */
535
                $fd = fopen("{$g['varetc_path']}/ez-ipupdate.conf", "w");
536
                if (!$fd) {
537
                        printf("Error: cannot open ez-ipupdate.conf in services_dyndns_configure().\n");
538
                        return 1;
539
                }
540

    
541
                $ezipupdateconf = <<<EOD
542
service-type={$dyndnscfg['type']}
543
user={$dyndnscfg['username']}:{$dyndnscfg['password']}
544
host={$dyndnscfg['host']}
545
interface={$wanif}
546
max-interval=2073600
547
pid-file={$g['varrun_path']}/ez-ipupdate.pid
548
cache-file={$g['vardb_path']}/ez-ipupdate.cache
549
execute=/etc/rc.dyndns.storecache
550
daemon
551

    
552
EOD;
553

    
554
                /* enable server[:port]? */
555
                if ($dyndnscfg['server']) {
556
                        if ($dyndnscfg['port'])
557
                                $ezipupdateconf .= "server={$dyndnscfg['server']}:{$dyndnscfg['port']}\n";
558
                        else
559
                                $ezipupdateconf .= "server={$dyndnscfg['server']}\n";
560
                }
561

    
562
                /* enable MX? */
563
                if ($dyndnscfg['mx']) {
564
                        $ezipupdateconf .= "mx={$dyndnscfg['mx']}\n";
565
                }
566

    
567
                /* enable wildcards? */
568
                if (isset($dyndnscfg['wildcard'])) {
569
                        $ezipupdateconf .= "wildcard\n";
570
                }
571

    
572
                fwrite($fd, $ezipupdateconf);
573
                fclose($fd);
574

    
575
                /* if we're booting, copy the cache file from /conf */
576
                if ($g['booting']) {
577
                        if (file_exists("{$g['conf_path']}/ez-ipupdate.cache")) {
578
                                copy("{$g['conf_path']}/ez-ipupdate.cache", "{$g['vardb_path']}/ez-ipupdate.cache");
579
                       }
580
                }
581

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

    
585
                if ($g['booting'])
586
                        echo "done\n";
587
        }
588

    
589
        return 0;
590
}
591

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

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

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

    
606
		if ($g['booting'])
607
			echo "Starting DNS forwarder...";
608
		else
609
			sleep(1);
610

    
611
		/* generate hosts file */
612
		if(system_hosts_generate()!=0)
613
			$return = 1;
614

    
615
		$args = "";
616

    
617
		if (isset($config['dnsmasq']['regdhcp'])) {
618

    
619
			$args .= " -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases" .
620
				" -s {$config['system']['domain']}";
621
		}
622

    
623
                if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
624
                        foreach($config['dnsmasq']['domainoverrides'] as $override) {
625
                                $args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
626
                        }
627
                }
628

    
629
		/* suppose that dnsmasq handles our domain and don't send
630
		requests for our local domain to upstream servers */
631
		//if (!empty($config['system']['domain'])) {
632
		//	$args .= sprintf(' --local=/%s/', $config['system']['domain']);
633
		//}
634

    
635
		/* run dnsmasq */
636
		mwexec("/usr/local/sbin/dnsmasq --all-servers {$args}");
637

    
638
		if ($g['booting'])
639
			echo "done.\n";
640
	}
641

    
642
	if (!$g['booting']) {
643
		if(services_dhcpd_configure()!=0)
644
			$return = 1;
645
	}
646

    
647
	return $return;
648
}
649

    
650
function services_snmpd_configure() {
651
	global $config, $g;
652
	if(isset($config['system']['developerspew'])) {
653
		$mt = microtime();
654
		echo "services_snmpd_configure() being called $mt\n";
655
	}
656

    
657
	/* kill any running snmpd */
658
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
659
	if(is_process_running("bsnmpd")) 
660
		mwexec("/usr/bin/killall bsnmpd", true);
661

    
662
	if (isset($config['snmpd']['enable'])) {
663

    
664
		if ($g['booting'])
665
			echo "Starting SNMP daemon... ";
666

    
667
		/* generate snmpd.conf */
668
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
669
		if (!$fd) {
670
			printf("Error: cannot open snmpd.conf in services_snmpd_configure().\n");
671
			return 1;
672
		}
673

    
674

    
675
		$snmpdconf = <<<EOD
676
location := "{$config['snmpd']['syslocation']}"
677
contact := "{$config['snmpd']['syscontact']}"
678
read := "{$config['snmpd']['rocommunity']}"
679

    
680
EOD;
681

    
682
/* No docs on what write strings do there for disable for now.
683
		if(isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])){
684
		    $snmpdconf .= <<<EOD
685
# write string
686
write := "{$config['snmpd']['rwcommunity']}"
687

    
688
EOD;
689
		}
690
*/
691

    
692

    
693
		if(isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])){
694
		    $snmpdconf .= <<<EOD
695
# SNMP Trap support.
696
traphost := {$config['snmpd']['trapserver']}
697
trapport := {$config['snmpd']['trapserverport']}
698
trap := "{$config['snmpd']['trapstring']}"
699

    
700

    
701
EOD;
702
		}
703

    
704

    
705
		$snmpdconf .= <<<EOD
706
system := 1     # pfSense
707
%snmpd
708
begemotSnmpdDebugDumpPdus       = 2
709
begemotSnmpdDebugSyslogPri      = 7
710
begemotSnmpdCommunityString.0.1 = $(read)
711

    
712
EOD;
713

    
714
/* No docs on what write strings do there for disable for now.
715
		if(isset($config['snmpd']['rwcommunity']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])){
716
		    $snmpdconf .= <<<EOD
717
begemotSnmpdCommunityString.0.2 = $(write)
718

    
719
EOD;
720
		}
721
*/
722

    
723

    
724
		if(isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])){
725
		    $snmpdconf .= <<<EOD
726
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
727
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
728
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
729

    
730
EOD;
731
		}
732

    
733

    
734
		$snmpdconf .= <<<EOD
735
begemotSnmpdCommunityDisable    = 1
736

    
737
EOD;
738

    
739
		if(isset($config['snmpd']['bindlan'])) {
740
			$bind_to_ip = $config['interfaces']['lan']['ipaddr'];
741
		} else {
742
			$bind_to_ip = "0.0.0.0";
743
		}
744

    
745
		if(is_port( $config['snmpd']['pollport'] )) {
746
		    $snmpdconf .= <<<EOD
747
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
748

    
749
EOD;
750

    
751
		}
752

    
753
		$snmpdconf .= <<<EOD
754
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
755
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
756

    
757
# These are bsnmp macros not php vars.
758
sysContact      = $(contact)
759
sysLocation     = $(location)
760
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
761

    
762
snmpEnableAuthenTraps = 2
763

    
764
EOD;
765

    
766
		if (is_array( $config['snmpd']['modules'] )) {
767
		    if(isset($config['snmpd']['modules']['mibii'])) {
768
			$snmpdconf .= <<<EOD
769
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
770

    
771
EOD;
772
		    }
773

    
774
		    if(isset($config['snmpd']['modules']['netgraph'])) {
775
			$snmpdconf .= <<<EOD
776
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
777
%netgraph
778
begemotNgControlNodeName = "snmpd"
779

    
780
EOD;
781
		    }
782

    
783
		    if(isset($config['snmpd']['modules']['pf'])) {
784
			$snmpdconf .= <<<EOD
785
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
786

    
787
EOD;
788
		    }
789

    
790
		    if(isset($config['snmpd']['modules']['hostres'])) {
791
			$snmpdconf .= <<<EOD
792
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
793

    
794
EOD;
795
		    }
796
		    if(isset($config['snmpd']['modules']['bridge'])) {
797
			$snmpdconf .= <<<EOD
798
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
799
# config must end with blank line
800

    
801

    
802
EOD;
803
		    }
804
		}
805

    
806
		fwrite($fd, $snmpdconf);
807
		fclose($fd);
808

    
809
		if (isset($config['snmpd']['bindlan'])) {
810
			$bindlan = "";
811
		}
812

    
813
		/* run bsnmpd */
814
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
815
			"{$bindlan} -p {$g['varrun_path']}/snmpd.pid");
816

    
817
		if ($g['booting'])
818
			echo "done.\n";
819
	}
820

    
821
	return 0;
822
}
823

    
824
function services_proxyarp_configure() {
825
	global $config, $g;
826
	if(isset($config['system']['developerspew'])) {
827
		$mt = microtime();
828
		echo "services_proxyarp_configure() being called $mt\n";
829
	}
830

    
831
	/* kill any running choparp */
832
	killbyname("choparp");
833

    
834
	if (isset($config['virtualip']) && is_array($config['virtualip']['vip'])) {
835
		$paa = array();
836

    
837
		/* group by interface */
838
		foreach ($config['virtualip']['vip'] as $vipent) {
839
			if ($vipent['mode'] === "proxyarp") {
840
				if ($vipent['interface'])
841
					$if = $vipent['interface'];
842
				else
843
					$if = "wan";
844

    
845
				if (!is_array($paa[$if]))
846
					$paa[$if] = array();
847

    
848
				$paa[$if][] = $vipent;
849
			}
850
		}
851

    
852
		if (count($paa))
853
		foreach ($paa as $paif => $paents) {
854
			if ($paif == "wan" && !(is_ipaddr($config['interfaces']['wan']['ipaddr']) ||
855
                                       ($config['interfaces']['wan']['ipaddr'] == "dhcp") ||
856
                                       ($config['interfaces']['wan']['ipaddr'] == "bigpond")))
857
                               continue;
858

    
859
			$args = $config['interfaces'][$paif]['if'] . " auto";
860

    
861
			foreach ($paents as $paent) {
862

    
863
				if (isset($paent['subnet']))
864
					$args .= " " . escapeshellarg("{$paent['subnet']}/{$paent['subnet_bits']}");
865
				else if (isset($paent['range']))
866
					$args .= " " . escapeshellarg($paent['range']['from'] . "-" .
867
						$paent['range']['to']);
868
			}
869

    
870
			mwexec_bg("/usr/local/sbin/choparp " . $args);
871
		}
872
	}
873
}
874

    
875
function services_dnsupdate_process() {
876
	global $config, $g;
877
	if(isset($config['system']['developerspew'])) {
878
		$mt = microtime();
879
		echo "services_dnsupdate_process() being called $mt\n";
880
	}
881

    
882
	/* Dynamic DNS updating active? */
883
	if (isset($config['dnsupdate']['enable'])) {
884

    
885
		$wanip = get_current_wan_address();
886
		if ($wanip) {
887

    
888
			$keyname = $config['dnsupdate']['keyname'];
889
			/* trailing dot */
890
			if (substr($keyname, -1) != ".")
891
				$keyname .= ".";
892

    
893
			$hostname = $config['dnsupdate']['host'];
894
			/* trailing dot */
895
			if (substr($hostname, -1) != ".")
896
				$hostname .= ".";
897

    
898
			/* write private key file
899
			   this is dumb - public and private keys are the same for HMAC-MD5,
900
			   but nsupdate insists on having both */
901
			$fd = fopen("{$g['varetc_path']}/K{$keyname}+157+00000.private", "w");
902
			$privkey .= <<<EOD
903
Private-key-format: v1.2
904
Algorithm: 157 (HMAC)
905
Key: {$config['dnsupdate']['keydata']}
906

    
907
EOD;
908
			fwrite($fd, $privkey);
909
			fclose($fd);
910

    
911
			/* write public key file */
912
			if ($config['dnsupdate']['keytype'] == "zone") {
913
				$flags = 257;
914
				$proto = 3;
915
			} else if ($config['dnsupdate']['keytype'] == "host") {
916
				$flags = 513;
917
				$proto = 3;
918
			} else if ($config['dnsupdate']['keytype'] == "user") {
919
				$flags = 0;
920
				$proto = 2;
921
			}
922

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

    
927
			/* generate update instructions */
928
			$upinst = "";
929
			if ($config['dnsupdate']['server'])
930
				$upinst .=  "server {$config['dnsupdate']['server']}\n";
931
			$upinst .= "update delete {$config['dnsupdate']['host']} A\n";
932
			$upinst .= "update add {$config['dnsupdate']['host']} {$config['dnsupdate']['ttl']} A {$wanip}\n";
933
			$upinst .= "\n";	/* mind that trailing newline! */
934

    
935
			$fd = fopen("{$g['varetc_path']}/nsupdatecmds", "w");
936
			fwrite($fd, $upinst);
937
			fclose($fd);
938

    
939
			/* invoke nsupdate */
940
			$cmd = "/usr/bin/nsupdate -k {$g['varetc_path']}/K{$keyname}+157+00000.key";
941
			if (isset($config['dnsupdate']['usetcp']))
942
				$cmd .= " -v";
943
			$cmd .= " {$g['varetc_path']}/nsupdatecmds";
944

    
945
			mwexec_bg($cmd);
946
		}
947
	}
948

    
949
	return 0;
950
}
951

    
952
function setup_wireless_olsr() {
953
	global $config, $g;
954
	if(!$config['installedpackages']['olsrd'] || !$config['installedpackages'])
955
		return;
956
	if(isset($config['system']['developerspew'])) {
957
		$mt = microtime();
958
		echo "setup_wireless_olsr($interface) being called $mt\n";
959
	}
960
	conf_mount_rw();
961
	foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
962
		$olsr_enable = $olsrd['enable'];
963
		if($olsr_enable <> "on")
964
			return;
965
		$fd = fopen("{$g['varetc_path']}/olsr.conf", "w");
966

    
967
		if($olsrd['announcedynamicroute'] or $olsrd['enableannounce'] == "on") {
968
			$enableannounce .= "\nHna4\n";
969
			$enableannounce .= "{\n";
970
		if($olsrd['announcedynamicroute'])
971
			$enableannounce .= "\t{$olsrd['announcedynamicroute']}\n";
972
		if($olsrd['enableannounce'] == "on")
973
			$enableannounce .= "0.0.0.0 0.0.0.0";
974
			$enableannounce .= "\n}\n";
975
		} else {
976
			$enableannounce = "";
977
		}
978

    
979
		$olsr .= <<<EODA
980
#
981
# olsr.org OLSR daemon config file
982
#
983
# Lines starting with a # are discarded
984
#
985
# This file was generated by setup_wireless_olsr() in services.inc
986
#
987

    
988
# This file is an example of a typical
989
# configuration for a mostly static
990
# network(regarding mobility) using
991
# the LQ extention
992

    
993
# Debug level(0-9)
994
# If set to 0 the daemon runs in the background
995

    
996
DebugLevel	2
997

    
998
# IP version to use (4 or 6)
999

    
1000
IpVersion	4
1001

    
1002
# Clear the screen each time the internal state changes
1003

    
1004
ClearScreen     yes
1005

    
1006
{$enableannounce}
1007

    
1008
# Should olsrd keep on running even if there are
1009
# no interfaces available? This is a good idea
1010
# for a PCMCIA/USB hotswap environment.
1011
# "yes" OR "no"
1012

    
1013
AllowNoInt	yes
1014

    
1015
# TOS(type of service) value for
1016
# the IP header of control traffic.
1017
# If not set it will default to 16
1018

    
1019
#TosValue	16
1020

    
1021
# The fixed willingness to use(0-7)
1022
# If not set willingness will be calculated
1023
# dynamically based on battery/power status
1024
# if such information is available
1025

    
1026
#Willingness    	4
1027

    
1028
# Allow processes like the GUI front-end
1029
# to connect to the daemon.
1030

    
1031
IpcConnect
1032
{
1033
     # Determines how many simultaneously
1034
     # IPC connections that will be allowed
1035
     # Setting this to 0 disables IPC
1036

    
1037
     MaxConnections  0
1038

    
1039
     # By default only 127.0.0.1 is allowed
1040
     # to connect. Here allowed hosts can
1041
     # be added
1042

    
1043
     Host            127.0.0.1
1044
     #Host            10.0.0.5
1045

    
1046
     # You can also specify entire net-ranges
1047
     # that are allowed to connect. Multiple
1048
     # entries are allowed
1049

    
1050
     #Net             192.168.1.0 255.255.255.0
1051
}
1052

    
1053
# Wether to use hysteresis or not
1054
# Hysteresis adds more robustness to the
1055
# link sensing but delays neighbor registration.
1056
# Used by default. 'yes' or 'no'
1057

    
1058
UseHysteresis	no
1059

    
1060
# Hysteresis parameters
1061
# Do not alter these unless you know
1062
# what you are doing!
1063
# Set to auto by default. Allowed
1064
# values are floating point values
1065
# in the interval 0,1
1066
# THR_LOW must always be lower than
1067
# THR_HIGH.
1068

    
1069
#HystScaling	0.50
1070
#HystThrHigh	0.80
1071
#HystThrLow	0.30
1072

    
1073

    
1074
# Link quality level
1075
# 0 = do not use link quality
1076
# 1 = use link quality for MPR selection
1077
# 2 = use link quality for MPR selection and routing
1078
# Defaults to 0
1079

    
1080
LinkQualityLevel	{$olsrd['enablelqe']}
1081

    
1082
# Link quality window size
1083
# Defaults to 10
1084

    
1085
LinkQualityWinSize	10
1086

    
1087
# Polling rate in seconds(float).
1088
# Default value 0.05 sec
1089

    
1090
Pollrate	0.05
1091

    
1092

    
1093
# TC redundancy
1094
# Specifies how much neighbor info should
1095
# be sent in TC messages
1096
# Possible values are:
1097
# 0 - only send MPR selectors
1098
# 1 - send MPR selectors and MPRs
1099
# 2 - send all neighbors
1100
#
1101
# defaults to 0
1102

    
1103
TcRedundancy	2
1104

    
1105
#
1106
# MPR coverage
1107
# Specifies how many MPRs a node should
1108
# try select to reach every 2 hop neighbor
1109
#
1110
# Can be set to any integer >0
1111
#
1112
# defaults to 1
1113

    
1114
MprCoverage	3
1115

    
1116
# Example plugin entry with parameters:
1117

    
1118
EODA;
1119

    
1120
if($olsrd['enablehttpinfo'] == "on") {
1121
	$olsr .= <<<EODB
1122

    
1123
LoadPlugin "/usr/local/lib/olsrd_httpinfo.so.0.1"
1124
{
1125
    PlParam     "port"   "{$olsrd['port']}"
1126
    PlParam     "Net"    "{$olsrd['allowedhttpinfohost']} {$olsrd['allowedhttpinfosubnet']}"
1127
}
1128

    
1129
EODB;
1130

    
1131
}
1132

    
1133
if($olsrd['enabledsecure'] == "on") {
1134
	$olsr .= <<<EODC
1135

    
1136
LoadPlugin "/usr/local/lib/olsrd_secure.so.0.5"
1137
{
1138
    PlParam     "Keyfile"   "/usr/local/etc/olsrkey.txt"
1139
}
1140

    
1141
EODC;
1142

    
1143
}
1144

    
1145
if($olsrd['enabledyngw'] == "on") {
1146

    
1147
	/* unset default route, olsr auto negotiates */
1148
	mwexec("/sbin/route delete default");
1149

    
1150
	$olsr .= <<<EODE
1151

    
1152
LoadPlugin "/usr/local/lib/olsrd_dyn_gw.so.0.4"
1153
{
1154
    # how often to look for a inet gw, in seconds
1155
    # defaults to 5 secs, if commented out
1156
    PlParam     "Interval"   "{$olsrd['polling']}"
1157

    
1158
    # if one or more IPv4 addresses are given, do a ping on these in
1159
    # descending order to validate that there is not only an entry in
1160
    # routing table, but also a real internet connection. If any of
1161
    # these addresses could be pinged successfully, the test was
1162
    # succesful, i.e. if the ping on the 1st address was successful,the
1163
    # 2nd won't be pinged
1164
    PlParam     "Ping"       "{$olsrd['ping']}"
1165
    #PlParam     "HNA"   "192.168.81.0 255.255.255.0"
1166
}
1167

    
1168
EODE;
1169

    
1170
}
1171

    
1172
foreach($config['installedpackages']['olsrd']['config'] as $conf) {
1173
	$interfaces = explode(',', $conf['iface_array']);
1174
	foreach($interfaces as $interface) {
1175
		$realinterface = convert_friendly_interface_to_real_interface_name($interface);
1176
$olsr .= <<<EODAD
1177
Interface "{$realinterface}"
1178
{
1179

    
1180
    # Hello interval in seconds(float)
1181
    HelloInterval    2.0
1182

    
1183
    # HELLO validity time
1184
    HelloValidityTime	20.0
1185

    
1186
    # TC interval in seconds(float)
1187
    TcInterval        5.0
1188

    
1189
    # TC validity time
1190
    TcValidityTime	30.0
1191

    
1192
    # MID interval in seconds(float)
1193
    MidInterval	5.0
1194

    
1195
    # MID validity time
1196
    MidValidityTime	30.0
1197

    
1198
    # HNA interval in seconds(float)
1199
    HnaInterval	5.0
1200

    
1201
    # HNA validity time
1202
    HnaValidityTime 	30.0
1203

    
1204
    # When multiple links exist between hosts
1205
    # the weight of interface is used to determine
1206
    # the link to use. Normally the weight is
1207
    # automatically calculated by olsrd based
1208
    # on the characteristics of the interface,
1209
    # but here you can specify a fixed value.
1210
    # Olsrd will choose links with the lowest value.
1211

    
1212
    # Weight 0
1213

    
1214

    
1215
}
1216

    
1217
EODAD;
1218

    
1219
	}
1220
	break;
1221
}
1222
		fwrite($fd, $olsr);
1223
		fclose($fd);
1224
	}
1225

    
1226
	if(is_process_running("olsrd"))
1227
		mwexec("/usr/bin/killall olsrd", true);
1228

    
1229
	sleep(2);
1230

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

    
1233
	conf_mount_ro();
1234
}
1235

    
1236
/* configure cron service */
1237
function configure_cron() {
1238
	global $g, $config;
1239
	conf_mount_rw();
1240
	/* preserve existing crontab entries */
1241
	$crontab_contents = file_get_contents("/etc/crontab");
1242
	$crontab_contents_a = split("\n", $crontab_contents);
1243
	
1244
	for ($i = 0; $i < count($crontab_contents_a); $i++) {
1245
		$item =& $crontab_contents_a[$i];
1246
		if (strpos($item, "# pfSense specific crontab entries") !== false) {
1247
			array_splice($crontab_contents_a, $i - 1);
1248
			break;
1249
		}
1250
	}
1251
	$crontab_contents = implode("\n", $crontab_contents_a) . "\n";
1252
	
1253
	
1254
	if (is_array($config['cron']['item'])) {
1255
		$crontab_contents .= "#\n";
1256
		$crontab_contents .= "# pfSense specific crontab entries\n";
1257
		$crontab_contents .= "# Created: " . date("F j, Y, g:i a") . "\n";
1258
		$crontab_contents .= "#\n";
1259

    
1260
		foreach ($config['cron']['item'] as $item) {
1261
			$crontab_contents .= "\n{$item['minute']}\t";
1262
			$crontab_contents .= "{$item['hour']}\t";
1263
			$crontab_contents .= "{$item['mday']}\t";
1264
			$crontab_contents .= "{$item['month']}\t";
1265
			$crontab_contents .= "{$item['wday']}\t";
1266
			$crontab_contents .= "{$item['who']}\t";
1267
			$crontab_contents .= "{$item['command']}";
1268
		}
1269
    
1270
		$crontab_contents .= "\n#\n";
1271
		$crontab_contents .= "# If possible do not add items to this file manually.\n";
1272
		$crontab_contents .= "# If you do so, this file must be terminated with a blank line (e.g. new line)\n";
1273
		$crontab_contents .= "#\n\n";
1274
	}
1275
	
1276
	/* please maintain the newline at the end of file */
1277
	file_put_contents("/etc/crontab", $crontab_contents);
1278
	
1279
	if (!$g['booting'])
1280
		conf_mount_ro();
1281
}
1282

    
1283
function upnp_action ($action) {
1284
	switch($action) {
1285
		case "start":
1286
			if(file_exists('/var/etc/miniupnpd.conf'))
1287
				mwexec_bg('/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf');
1288
			break;
1289
		case "stop":
1290
			while((int)exec("pgrep miniupnpd | wc -l") > 0)
1291
				mwexec('killall miniupnpd 2>/dev/null', true);
1292
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
1293
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
1294
			break;
1295
		case "restart":
1296
			upnp_action('stop');
1297
			upnp_action('start');
1298
			break;
1299
	}
1300
}
1301

    
1302
function upnp_start() {
1303
	global $config, $g;
1304
	if($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
1305
		if($g['booting']) {
1306
			echo "Starting UPnP service...";
1307
			include('/usr/local/pkg/miniupnpd.inc');
1308
			sync_package_miniupnpd();
1309
			echo "done.\n";
1310
		}
1311
		else {
1312
			upnp_action('start');
1313
		}
1314
	}
1315
}
1316

    
1317
?>
(18-18/27)