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']}/usr\n");
65
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/lib\n");
66
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/run\n");
67
	fwrite($fd, "chown -R dhcpd:_dhcp {$g['dhcpd_chroot_path']}/*\n");
68
	fwrite($fd, "cp /lib/libc.so.6 {$g['dhcpd_chroot_path']}/lib/\n");
69
	fwrite($fd, "cp /usr/local/sbin/dhcpd {$g['dhcpd_chroot_path']}/usr/local/sbin/\n");
70
	fwrite($fd, "chmod a+rx {$g['dhcpd_chroot_path']}/usr/local/sbin/dhcpd\n");
71
	if(!trim($status))
72
		fwrite($fd, "mount_devfs devfs {$g['dhcpd_chroot_path']}/dev\n");
73
	fclose($fd);
74
	mwexec("/bin/sh /tmp/dhcpd.sh");
75

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

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

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

    
97
	if (!$dhcpdenable)
98
		return 0;
99

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

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

    
112

    
113

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

    
124
EOD;
125

    
126
	$dhcpdifs = array();
127

    
128
	/*    loop through and deterimine if we need to setup
129
	 *    failover peer "bleh" entries
130
	 */
131
	$dhcpnum = 0;
132
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
133

    
134
		if(!isset($dhcpifconf['disableauthoritative']))
135
			$dhcpdconf .= "authoritative;\n";
136

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

    
183
EOPP;
184
		$dhcpnum++;
185
		}
186
	}
187

    
188
	$dhcpnum = 0;
189

    
190
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
191

    
192
		$ifcfg = $config['interfaces'][$dhcpif];
193

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

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

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

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

    
210
		$dnscfg = "";
211

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

    
222

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

    
231
		$dhcpdconf .= "subnet $subnet netmask $subnetmask {\n";
232
		$dhcpdconf .= "	pool {\n";
233

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

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

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

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

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

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

    
264
EOD;
265

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

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

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

    
279
		if ($dhcpifconf['tftp'] <> "")
280
			$dhcpdconf .= "	option tftp-server-name \"{$dhcpifconf['tftp']}\";\n";
281

    
282
    if ($dhcpifconf['ldap'] <> "")
283
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
284

    
285
		if(isset($dhcpifconf['netboot'])) {
286
			if (($dhcpifconf['next-server'] <> "") && ($dhcpifconf['filename'] <> "")) {
287
				$dhcpdconf .= "	next-server {$dhcpifconf['next-server']};\n";
288
				$dhcpdconf .= "	filename \"{$dhcpifconf['filename']}\";\n";
289
			}
290
			if (($dhcpifconf['rootpathip'] <> "") && ($dhcpifconf['rootpath'] <> "")) {
291
				$dhcpdconf .= "	option root-path \"{$dhcpifconf['rootpathip']}:{$dhcpifconf['rootpath']}\";\n";
292
      }
293
		}
294
		
295
		$dhcpdconf .= <<<EOD
296
}
297

    
298
EOD;
299

    
300
		/* add static mappings */
301
		if (is_array($dhcpifconf['staticmap'])) {
302

    
303
			$i = 0;
304
			foreach ($dhcpifconf['staticmap'] as $sm) {
305
				$dhcpdconf .= <<<EOD
306
host s_{$dhcpif}_{$i} {
307
	hardware ethernet {$sm['mac']};
308

    
309
EOD;
310
				if ($sm['ipaddr'])
311
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
312

    
313
				$dhcpdconf .= "}\n";
314
				$i++;
315
			}
316
		}
317

    
318
		$dhcpdifs[] = $ifcfg['if'];
319
	}
320

    
321
	fwrite($fd, $dhcpdconf);
322
	fclose($fd);
323

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

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

    
331
	if ($g['booting']) {
332
		print "done.\n";
333
	}
334

    
335
	return 0;
336
}
337

    
338
function interfaces_staticarp_configure($if) {
339
	global $config, $g;
340
	if(isset($config['system']['developerspew'])) {
341
		$mt = microtime();
342
		echo "interfaces_staticarp_configure($if) being called $mt\n";
343
	}
344

    
345
        $ifcfg = $config['interfaces'][$if];
346

    
347
        /* Enable staticarp, if enabled */
348
        if(isset($config['dhcpd'][$if]['staticarp'])) {
349
                mwexec("/sbin/ifconfig " . escapeshellarg($ifcfg['if']) . " staticarp " );
350
                mwexec("/usr/sbin/arp -ad > /dev/null 2>&1 ");
351
                if (is_array($config['dhcpd'][$if]['staticmap'])) {
352

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

    
356
                        }
357

    
358
                }
359
        } else {
360
                mwexec("/sbin/ifconfig " . escapeshellarg($ifcfg['if']) . " -staticarp " );
361
                mwexec("/usr/sbin/arp -da > /dev/null 2>&1 ");
362
        }
363

    
364
        return 0;
365
}
366

    
367
function services_dhcrelay_configure() {
368
	global $config, $g;
369
	if(isset($config['system']['developerspew'])) {
370
		$mt = microtime();
371
		echo "services_dhcrelay_configure() being called $mt\n";
372
	}
373

    
374
	/* kill any running dhcrelay */
375
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
376

    
377
	$dhcrelaycfg = $config['dhcrelay'];
378

    
379
	/* DHCPRelay enabled on any interfaces? */
380
	$dhcrelayenable = false;
381
	if(is_array($dhcrelaycfg)) {
382
		foreach ($dhcrelaycfg as $dhcrelayif => $dhcrelayifconf) {
383
			if (isset($dhcrelayifconf['enable']) &&
384
				(($dhcrelayif == "lan") ||
385
				(isset($config['interfaces'][$dhcrelayif]['enable']) &&
386
				$config['interfaces'][$dhcrelayif]['if'] && (!$config['interfaces'][$dhcrelayif]['bridge']))))
387
				$dhcrelayenable = true;
388
		}
389
	}
390

    
391
	if (!$dhcrelayenable)
392
		return 0;
393

    
394
	if ($g['booting'])
395
		echo "Starting DHCP relay service...";
396
	else
397
		sleep(1);
398

    
399
	$dhcrelayifs = array();
400
	foreach ($dhcrelaycfg as $dhcrelayif => $dhcrelayifconf) {
401

    
402
		$ifcfg = $config['interfaces'][$dhcrelayif];
403

    
404
		if (!isset($dhcrelayifconf['enable']) ||
405
			(($dhcrelayif != "lan") &&
406
			(!isset($ifcfg['enable']) || !$ifcfg['if'] || $ifcfg['bridge'])))
407
			continue;
408

    
409
		$dhcrelayifs[] = $ifcfg['if'];
410
	}
411

    
412
	/* In order for the relay to work, it needs to be active on the
413
	   interface in which the destination server sits */
414
	foreach ($config['interfaces'] as $ifname) {
415
		$subnet = $ifname['ipaddr'] . "/" . $ifname['subnet'];
416
		if (ip_in_subnet($dhcrelaycfg['server'],$subnet))
417
			$destif = $ifname['if'];
418
	}
419

    
420
	if (!isset($destif))
421
		$destif = $config['interfaces']['wan']['if'];
422

    
423
	$dhcrelayifs[] = $destif;
424
	$dhcrelayifs = array_unique($dhcrelayifs);
425

    
426
	/* fire up dhcrelay */
427
	$cmd = "/usr/local/sbin/dhcrelay -i " .  join(" -i ", $dhcrelayifs);
428

    
429
	if (isset($dhcrelaycfg['agentoption']))
430
		$cmd .=  " -a -m replace";
431

    
432
	$cmd .= " {$dhcrelaycfg['server']}";
433
	mwexec($cmd);
434

    
435
	if (!$g['booting']) {
436
		/* set the reload filter dity flag */
437
		touch("{$g['tmp_path']}/filter_dirty");
438
	}
439

    
440
	return 0;
441
}
442

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

    
450
	if (file_exists("{$g['vardb_path']}/ez-ipupdate.cache")) {
451
		conf_mount_rw();
452
		unlink("{$g['vardb_path']}/ez-ipupdate.cache");
453
		conf_mount_ro();
454
	}
455

    
456
	if (file_exists("{$g['conf_path']}/ez-ipupdate.cache")) {
457
		conf_mount_rw();
458
		unlink("{$g['conf_path']}/ez-ipupdate.cache");
459
		conf_mount_ro();
460
	}
461

    
462
	return 0;
463
}
464

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

    
472
	$dyndnscfg = $config['dyndns'];
473
	$wancfg = $config['interfaces']['wan'];
474

    
475
	if (isset($dyndnscfg['enable'])) {
476

    
477
		if ($g['booting']) {
478
			echo "Starting DynDNS client...";
479
			if(isset($config['system']['use_old_dyndns'])) {
480
				echo " [Using ez-ipupdate] ";
481
				services_dyndns_configure_old();
482
				return;
483
			}
484
		} else {
485
			sleep(1);
486
			if(isset($config['system']['use_old_dyndns'])) {
487
				services_dyndns_configure_old();
488
				return;
489
			}
490
		}
491

    
492
		/* load up the dyndns.class */
493
		require_once("dyndns.class");
494

    
495
		log_error("DynDns: Running updatedns()");
496

    
497
		/* determine WAN interface name */
498
		$wanif = get_real_wan_interface();
499
		/* get ip */
500
		$ip = find_interface_ip($wanif);
501

    
502
		$dns = new updatedns($dnsService = $config['dyndns']['type'],
503
							 $dnsHost = $config['dyndns']['host'],
504
							 $dnsUser = $config['dyndns']['username'],
505
							 $dnsPass = $config['dyndns']['password'],
506
							 $dnsWilcard = $config['dyndns']['wildcard'],
507
							 $dnsMX = $config['dyndns']['mx']);
508

    
509
		if ($g['booting'])
510
			echo "done.\n";
511
	}
512

    
513
	return 0;
514
}
515

    
516
function services_dyndns_configure_old() {
517
	global $config, $g;
518
	if(isset($config['system']['developerspew'])) {
519
		$mt = microtime();
520
		echo "services_dyndns_configure_old() being called $mt\n";
521
	}
522

    
523
        /* kill any running ez-ipupdate */
524
        /* ez-ipupdate needs SIGQUIT instead of SIGTERM */
525
        sigkillbypid("{$g['varrun_path']}/ez-ipupdate.pid", "QUIT");
526

    
527
        $dyndnscfg = $config['dyndns'];
528
        $wancfg = $config['interfaces']['wan'];
529

    
530
        if (isset($dyndnscfg['enable'])) {
531

    
532
                if ($g['booting'])
533
                        echo "Starting DynDNS client...";
534
                else
535
                        sleep(1);
536

    
537
                /* determine WAN interface name */
538
                $wanif = get_real_wan_interface();
539

    
540
                /* write ez-ipupdate.conf */
541
                $fd = fopen("{$g['varetc_path']}/ez-ipupdate.conf", "w");
542
                if (!$fd) {
543
                        printf("Error: cannot open ez-ipupdate.conf in services_dyndns_configure().\n");
544
                        return 1;
545
                }
546

    
547
                $ezipupdateconf = <<<EOD
548
service-type={$dyndnscfg['type']}
549
user={$dyndnscfg['username']}:{$dyndnscfg['password']}
550
host={$dyndnscfg['host']}
551
interface={$wanif}
552
max-interval=2073600
553
pid-file={$g['varrun_path']}/ez-ipupdate.pid
554
cache-file={$g['vardb_path']}/ez-ipupdate.cache
555
execute=/etc/rc.dyndns.storecache
556
daemon
557

    
558
EOD;
559

    
560
                /* enable server[:port]? */
561
                if ($dyndnscfg['server']) {
562
                        if ($dyndnscfg['port'])
563
                                $ezipupdateconf .= "server={$dyndnscfg['server']}:{$dyndnscfg['port']}\n";
564
                        else
565
                                $ezipupdateconf .= "server={$dyndnscfg['server']}\n";
566
                }
567

    
568
                /* enable MX? */
569
                if ($dyndnscfg['mx']) {
570
                        $ezipupdateconf .= "mx={$dyndnscfg['mx']}\n";
571
                }
572

    
573
                /* enable wildcards? */
574
                if (isset($dyndnscfg['wildcard'])) {
575
                        $ezipupdateconf .= "wildcard\n";
576
                }
577

    
578
                fwrite($fd, $ezipupdateconf);
579
                fclose($fd);
580

    
581
                /* if we're booting, copy the cache file from /conf */
582
                if ($g['booting']) {
583
                        if (file_exists("{$g['conf_path']}/ez-ipupdate.cache")) {
584
                                copy("{$g['conf_path']}/ez-ipupdate.cache", "{$g['vardb_path']}/ez-ipupdate.cache");
585
                       }
586
                }
587

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

    
591
                if ($g['booting'])
592
                        echo "done\n";
593
        }
594

    
595
        return 0;
596
}
597

    
598
function services_dnsmasq_configure() {
599
	global $config, $g;
600
	$return = 0;
601
	
602
	if(isset($config['system']['developerspew'])) {
603
		$mt = microtime();
604
		echo "services_dnsmasq_configure() being called $mt\n";
605
	}
606

    
607
	/* kill any running dnsmasq */
608
	sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
609

    
610
	if (isset($config['dnsmasq']['enable'])) {
611

    
612
		if ($g['booting'])
613
			echo "Starting DNS forwarder...";
614
		else
615
			sleep(1);
616

    
617
		/* generate hosts file */
618
		if(system_hosts_generate()!=0)
619
			$return = 1;
620

    
621
		$args = "";
622

    
623
		if (isset($config['dnsmasq']['regdhcp'])) {
624

    
625
			$args .= " -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases" .
626
				" -s {$config['system']['domain']}";
627
		}
628

    
629
                if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
630
                        foreach($config['dnsmasq']['domainoverrides'] as $override) {
631
                                $args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
632
                        }
633
                }
634

    
635
		/* suppose that dnsmasq handles our domain and don't send
636
		requests for our local domain to upstream servers */
637
		//if (!empty($config['system']['domain'])) {
638
		//	$args .= sprintf(' --local=/%s/', $config['system']['domain']);
639
		//}
640

    
641
		/* run dnsmasq */
642
		mwexec("/usr/local/sbin/dnsmasq {$args}");
643

    
644
		if ($g['booting'])
645
			echo "done.\n";
646
	}
647

    
648
	if (!$g['booting']) {
649
		if(services_dhcpd_configure()!=0)
650
			$return = 1;
651
	}
652

    
653
	return $return;
654
}
655

    
656
function services_snmpd_configure() {
657
	global $config, $g;
658
	if(isset($config['system']['developerspew'])) {
659
		$mt = microtime();
660
		echo "services_snmpd_configure() being called $mt\n";
661
	}
662

    
663
	/* kill any running snmpd */
664
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
665
	if(is_process_running("bsnmpd")) 
666
		exec("/usr/bin/killall bsnmpd");
667

    
668
	if (isset($config['snmpd']['enable'])) {
669

    
670
		if ($g['booting'])
671
			echo "Starting SNMP daemon... ";
672

    
673
		/* generate snmpd.conf */
674
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
675
		if (!$fd) {
676
			printf("Error: cannot open snmpd.conf in services_snmpd_configure().\n");
677
			return 1;
678
		}
679

    
680

    
681
		$snmpdconf = <<<EOD
682
location := "{$config['snmpd']['syslocation']}"
683
contact := "{$config['snmpd']['syscontact']}"
684
read := "{$config['snmpd']['rocommunity']}"
685

    
686
EOD;
687

    
688
/* No docs on what write strings do there for disable for now.
689
		if(isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])){
690
		    $snmpdconf .= <<<EOD
691
# write string
692
write := "{$config['snmpd']['rwcommunity']}"
693

    
694
EOD;
695
		}
696
*/
697

    
698

    
699
		if(isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])){
700
		    $snmpdconf .= <<<EOD
701
# SNMP Trap support.
702
traphost := {$config['snmpd']['trapserver']}
703
trapport := {$config['snmpd']['trapserverport']}
704
trap := "{$config['snmpd']['trapstring']}"
705

    
706

    
707
EOD;
708
		}
709

    
710

    
711
		$snmpdconf .= <<<EOD
712
system := 1     # pfSense
713
%snmpd
714
begemotSnmpdDebugDumpPdus       = 2
715
begemotSnmpdDebugSyslogPri      = 7
716
begemotSnmpdCommunityString.0.1 = $(read)
717

    
718
EOD;
719

    
720
/* No docs on what write strings do there for disable for now.
721
		if(isset($config['snmpd']['rwcommunity']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])){
722
		    $snmpdconf .= <<<EOD
723
begemotSnmpdCommunityString.0.2 = $(write)
724

    
725
EOD;
726
		}
727
*/
728

    
729

    
730
		if(isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])){
731
		    $snmpdconf .= <<<EOD
732
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
733
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
734
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
735

    
736
EOD;
737
		}
738

    
739

    
740
		$snmpdconf .= <<<EOD
741
begemotSnmpdCommunityDisable    = 1
742

    
743
EOD;
744

    
745
		if(isset($config['snmpd']['bindlan'])) {
746
			$bind_to_ip = $config['interfaces']['lan']['ipaddr'];
747
		} else {
748
			$bind_to_ip = "0.0.0.0";
749
		}
750

    
751
		if(is_port( $config['snmpd']['pollport'] )) {
752
		    $snmpdconf .= <<<EOD
753
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
754

    
755
EOD;
756

    
757
		}
758

    
759
		$snmpdconf .= <<<EOD
760
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
761
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
762

    
763
# These are bsnmp macros not php vars.
764
sysContact      = $(contact)
765
sysLocation     = $(location)
766
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
767

    
768
snmpEnableAuthenTraps = 2
769

    
770
EOD;
771

    
772
		if (is_array( $config['snmpd']['modules'] )) {
773
		    if(isset($config['snmpd']['modules']['mibii'])) {
774
			$snmpdconf .= <<<EOD
775
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
776

    
777
EOD;
778
		    }
779

    
780
		    if(isset($config['snmpd']['modules']['netgraph'])) {
781
			$snmpdconf .= <<<EOD
782
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
783
%netgraph
784
begemotNgControlNodeName = "snmpd"
785

    
786
EOD;
787
		    }
788

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

    
793
EOD;
794
		    }
795

    
796
		    if(isset($config['snmpd']['modules']['hostres'])) {
797
			$snmpdconf .= <<<EOD
798
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
799

    
800
EOD;
801
		    }
802
		    if(isset($config['snmpd']['modules']['bridge'])) {
803
			$snmpdconf .= <<<EOD
804
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
805
# config must end with blank line
806

    
807

    
808
EOD;
809
		    }
810
		}
811

    
812
		fwrite($fd, $snmpdconf);
813
		fclose($fd);
814

    
815
		if (isset($config['snmpd']['bindlan'])) {
816
			$bindlan = "";
817
		}
818

    
819
		/* run bsnmpd */
820
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
821
			"{$bindlan} -p {$g['varrun_path']}/snmpd.pid");
822

    
823
		if ($g['booting'])
824
			echo "done.\n";
825
	}
826

    
827
	return 0;
828
}
829

    
830
function services_proxyarp_configure() {
831
	global $config, $g;
832
	if(isset($config['system']['developerspew'])) {
833
		$mt = microtime();
834
		echo "services_proxyarp_configure() being called $mt\n";
835
	}
836

    
837
	/* kill any running choparp */
838
	killbyname("choparp");
839

    
840
	if (isset($config['virtualip']) && is_array($config['virtualip']['vip'])) {
841
		$paa = array();
842

    
843
		/* group by interface */
844
		foreach ($config['virtualip']['vip'] as $vipent) {
845
			if ($vipent['mode'] === "proxyarp") {
846
				if ($vipent['interface'])
847
					$if = $vipent['interface'];
848
				else
849
					$if = "wan";
850

    
851
				if (!is_array($paa[$if]))
852
					$paa[$if] = array();
853

    
854
				$paa[$if][] = $vipent;
855
			}
856
		}
857

    
858
		if (count($paa))
859
		foreach ($paa as $paif => $paents) {
860
			if ($paif == "wan" && !(is_ipaddr($config['interfaces']['wan']['ipaddr']) ||
861
                                       ($config['interfaces']['wan']['ipaddr'] == "dhcp") ||
862
                                       ($config['interfaces']['wan']['ipaddr'] == "bigpond")))
863
                               continue;
864

    
865
			$args = $config['interfaces'][$paif]['if'] . " auto";
866

    
867
			foreach ($paents as $paent) {
868

    
869
				if (isset($paent['subnet']))
870
					$args .= " " . escapeshellarg("{$paent['subnet']}/{$paent['subnet_bits']}");
871
				else if (isset($paent['range']))
872
					$args .= " " . escapeshellarg($paent['range']['from'] . "-" .
873
						$paent['range']['to']);
874
			}
875

    
876
			mwexec_bg("/usr/local/sbin/choparp " . $args);
877
		}
878
	}
879
}
880

    
881
function services_dnsupdate_process() {
882
	global $config, $g;
883
	if(isset($config['system']['developerspew'])) {
884
		$mt = microtime();
885
		echo "services_dnsupdate_process() being called $mt\n";
886
	}
887

    
888
	/* Dynamic DNS updating active? */
889
	if (isset($config['dnsupdate']['enable'])) {
890

    
891
		$wanip = get_current_wan_address();
892
		if ($wanip) {
893

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

    
899
			$hostname = $config['dnsupdate']['host'];
900
			/* trailing dot */
901
			if (substr($hostname, -1) != ".")
902
				$hostname .= ".";
903

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

    
913
EOD;
914
			fwrite($fd, $privkey);
915
			fclose($fd);
916

    
917
			/* write public key file */
918
			if ($config['dnsupdate']['keytype'] == "zone") {
919
				$flags = 257;
920
				$proto = 3;
921
			} else if ($config['dnsupdate']['keytype'] == "host") {
922
				$flags = 513;
923
				$proto = 3;
924
			} else if ($config['dnsupdate']['keytype'] == "user") {
925
				$flags = 0;
926
				$proto = 2;
927
			}
928

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

    
933
			/* generate update instructions */
934
			$upinst =  "update delete {$config['dnsupdate']['host']} A\n";
935
			$upinst .= "update add {$config['dnsupdate']['host']} {$config['dnsupdate']['ttl']} A {$wanip}\n";
936
			$upinst .= "\n";	/* mind that trailing newline! */
937

    
938
			$fd = fopen("{$g['varetc_path']}/nsupdatecmds", "w");
939
			fwrite($fd, $upinst);
940
			fclose($fd);
941

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

    
948
			mwexec_bg($cmd);
949
		}
950
	}
951

    
952
	return 0;
953
}
954

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

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

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

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

    
996
# Debug level(0-9)
997
# If set to 0 the daemon runs in the background
998

    
999
DebugLevel	2
1000

    
1001
# IP version to use (4 or 6)
1002

    
1003
IpVersion	4
1004

    
1005
# Clear the screen each time the internal state changes
1006

    
1007
ClearScreen     yes
1008

    
1009
{$enableannounce}
1010

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

    
1016
AllowNoInt	yes
1017

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

    
1022
#TosValue	16
1023

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

    
1029
#Willingness    	4
1030

    
1031
# Allow processes like the GUI front-end
1032
# to connect to the daemon.
1033

    
1034
IpcConnect
1035
{
1036
     # Determines how many simultaneously
1037
     # IPC connections that will be allowed
1038
     # Setting this to 0 disables IPC
1039

    
1040
     MaxConnections  0
1041

    
1042
     # By default only 127.0.0.1 is allowed
1043
     # to connect. Here allowed hosts can
1044
     # be added
1045

    
1046
     Host            127.0.0.1
1047
     #Host            10.0.0.5
1048

    
1049
     # You can also specify entire net-ranges
1050
     # that are allowed to connect. Multiple
1051
     # entries are allowed
1052

    
1053
     #Net             192.168.1.0 255.255.255.0
1054
}
1055

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

    
1061
UseHysteresis	no
1062

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

    
1072
#HystScaling	0.50
1073
#HystThrHigh	0.80
1074
#HystThrLow	0.30
1075

    
1076

    
1077
# Link quality level
1078
# 0 = do not use link quality
1079
# 1 = use link quality for MPR selection
1080
# 2 = use link quality for MPR selection and routing
1081
# Defaults to 0
1082

    
1083
LinkQualityLevel	{$olsrd['enablelqe']}
1084

    
1085
# Link quality window size
1086
# Defaults to 10
1087

    
1088
LinkQualityWinSize	10
1089

    
1090
# Polling rate in seconds(float).
1091
# Default value 0.05 sec
1092

    
1093
Pollrate	0.05
1094

    
1095

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

    
1106
TcRedundancy	2
1107

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

    
1117
MprCoverage	3
1118

    
1119
# Example plugin entry with parameters:
1120

    
1121
EODA;
1122

    
1123
if($olsrd['enablehttpinfo'] == "on") {
1124
	$olsr .= <<<EODB
1125

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

    
1132
EODB;
1133

    
1134
}
1135

    
1136
if($olsrd['enabledsecure'] == "on") {
1137
	$olsr .= <<<EODC
1138

    
1139
LoadPlugin "/usr/local/lib/olsrd_secure.so.0.5"
1140
{
1141
    PlParam     "Keyfile"   "/usr/local/etc/olsrkey.txt"
1142
}
1143

    
1144
EODC;
1145

    
1146
}
1147

    
1148
if($olsrd['enabledyngw'] == "on") {
1149

    
1150
	/* unset default route, olsr auto negotiates */
1151
	mwexec("/sbin/route delete default");
1152

    
1153
	$olsr .= <<<EODE
1154

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

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

    
1171
EODE;
1172

    
1173
}
1174

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

    
1183
    # Hello interval in seconds(float)
1184
    HelloInterval    2.0
1185

    
1186
    # HELLO validity time
1187
    HelloValidityTime	20.0
1188

    
1189
    # TC interval in seconds(float)
1190
    TcInterval        5.0
1191

    
1192
    # TC validity time
1193
    TcValidityTime	30.0
1194

    
1195
    # MID interval in seconds(float)
1196
    MidInterval	5.0
1197

    
1198
    # MID validity time
1199
    MidValidityTime	30.0
1200

    
1201
    # HNA interval in seconds(float)
1202
    HnaInterval	5.0
1203

    
1204
    # HNA validity time
1205
    HnaValidityTime 	30.0
1206

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

    
1215
    # Weight 0
1216

    
1217

    
1218
}
1219

    
1220
EODAD;
1221

    
1222
	}
1223
	break;
1224
}
1225
		fwrite($fd, $olsr);
1226
		fclose($fd);
1227
	}
1228

    
1229
	if(is_process_running("olsrd"))
1230
		mwexec("/usr/bin/killall olsrd");
1231

    
1232
	sleep(2);
1233

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

    
1236
	conf_mount_ro();
1237
}
1238

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

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

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

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

    
1320
?>
(19-19/29)