Project

General

Profile

Download (35.3 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.* {$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
	if(is_array($dhcpdcfg))
86
		foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
87
			if($dhcpif == "lan") 
88
				if(!$config['interfaces']['lan']) 	
89
					continue;
90
			if (isset($dhcpifconf['enable']) &&
91
				(($dhcpif == "lan") ||
92
				(isset($config['interfaces'][$dhcpif]['enable']) &&
93
				$config['interfaces'][$dhcpif]['if'] && (!$config['interfaces'][$dhcpif]['bridge']))))
94
				$dhcpdenable = true;
95
			if (isset($dhcpifconf['enable']) &&
96
				(($dhcpif == "wan") || (isset($config['interfaces'][$dhcpif]['enable']) &&
97
				$config['interfaces'][$dhcpif]['if'] && (!$config['interfaces'][$dhcpif]['bridge']))))
98
				$dhcpdenable = true;
99
		}
100

    
101
	if (!$dhcpdenable)
102
		return 0;
103

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

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

    
116

    
117

    
118
	$dhcpdconf = <<<EOD
119
	
120
option domain-name "{$syscfg['domain']}";
121
option ldap-server code 95 = text;
122
option domain-search-list code 119 = text;
123
default-lease-time 7200;
124
max-lease-time 86400;
125
log-facility local7;
126
ddns-update-style none;
127
one-lease-per-client true;
128
deny duplicates;
129
ping-check true;
130

    
131
EOD;
132

    
133
	$dhcpdifs = array();
134

    
135
	/*    loop through and deterimine if we need to setup
136
	 *    failover peer "bleh" entries
137
	 */
138
	$dhcpnum = 0;
139
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
140

    
141
		if(!isset($dhcpifconf['disableauthoritative']))
142
			$dhcpdconf .= "authoritative;\n";
143

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

    
190
EOPP;
191
		$dhcpnum++;
192
		}
193
	}
194

    
195
	$dhcpnum = 0;
196

    
197
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
198

    
199
		$ifcfg = $config['interfaces'][$dhcpif];
200

    
201
		if (!isset($dhcpifconf['enable']) ||
202
			($ifcfg['ipaddr'] == "dhcp") ||
203
			(($dhcpif != "lan") &&
204
			(!isset($ifcfg['enable']) || !$ifcfg['if'] || $ifcfg['bridge'])))
205
			continue;
206

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

    
210
		$subnet = gen_subnet($ifcfg['ipaddr'], $ifcfg['subnet']);
211
		$subnetmask = gen_subnet_mask($ifcfg['subnet']);
212

    
213
		if($is_olsr_enabled == true)
214
			if($dhcpifconf['netmask'])
215
				$subnetmask = gen_subnet_mask($dhcpifconf['netmask']);
216

    
217
		$dnscfg = "";
218

    
219
		if ($dhcpifconf['domain']) {
220
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
221
		}
222
		
223
    if($dhcpifconf['domainsearchlist'] <> "") {
224
			$dnscfg .= "	option domain-search-list \"{$dhcpifconf['domainsearchlist']}\";\n";
225
    }
226

    
227
		if (isset($dhcpifconf['ddnsupdate'])) {
228
			if($dhcpifconf['ddnsdomain'] <> "") {
229
				$dnscfg .= "	ddns-domainname \"{$dhcpifconf['ddnsdomain']}\";\n";
230
			}
231
			$dnscfg .= "	ddns-update-style interim;\n";
232
		}
233

    
234
		if (is_array($dhcpifconf['dnsserver']) && ($dhcpifconf['dnsserver'][0])) {
235
			$dnscfg .= "	option domain-name-servers " . join(",", $dhcpifconf['dnsserver']) . ";";
236
		} else if (isset($config['dnsmasq']['enable'])) {
237
			$dnscfg .= "	option domain-name-servers " . $ifcfg['ipaddr'] . ";";
238
		} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
239
			$dnscfg .= "	option domain-name-servers " . join(",", $syscfg['dnsserver']) . ";";
240
		}
241

    
242
		$dhcpdconf .= "subnet $subnet netmask $subnetmask {\n";
243
		$dhcpdconf .= "	pool {\n";
244

    
245
		/* is failover dns setup? */
246
		if (is_array($dhcpifconf['dnsserver']) && $dhcpifconf['dnsserver'][0] <> "") {
247
			$dhcpdconf .= "		option domain-name-servers {$dhcpifconf['dnsserver'][0]}";
248
			if($dhcpifconf['dnsserver'][1] <> "")
249
				$dhcpdconf .= ",{$dhcpifconf['dnsserver'][1]}";
250
			$dhcpdconf .= ";\n";
251
		}
252

    
253
		if($dhcpifconf['failover_peerip'] <> "")
254
			$dhcpdconf .= "		deny dynamic bootp clients;\n";
255

    
256
		if (isset($dhcpifconf['denyunknown']))
257
		   $dhcpdconf .= "		deny unknown clients;\n";
258

    
259
		if ($dhcpifconf['gateway'])
260
			$routers = $dhcpifconf['gateway'];
261
		else
262
			$routers = $ifcfg['ipaddr'];
263

    
264
		if($dhcpifconf['failover_peerip'] <> "") {
265
			$dhcpdconf .= "		failover peer \"dhcp{$dhcpnum}\";\n";
266
			$dhcpnum++;
267
		}
268

    
269
		$dhcpdconf .= <<<EOD
270
		range {$dhcpifconf['range']['from']} {$dhcpifconf['range']['to']};
271
	}
272
	option routers {$routers};
273
$dnscfg
274

    
275
EOD;
276
    
277
    if ($dhcpifconf['defaultleasetime'])
278
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
279
		if ($dhcpifconf['maxleasetime'])
280
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
281

    
282
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
283
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
284
			$dhcpdconf .= "	option netbios-node-type 8;\n";
285
		}
286

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

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

    
293
    if ($dhcpifconf['ldap'] <> "")
294
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
295

    
296
		if(isset($dhcpifconf['netboot'])) {
297
			if (($dhcpifconf['next-server'] <> "") && ($dhcpifconf['filename'] <> "")) {
298
				$dhcpdconf .= "	next-server {$dhcpifconf['next-server']};\n";
299
				$dhcpdconf .= "	filename \"{$dhcpifconf['filename']}\";\n";
300
			}
301
			if ($dhcpifconf['rootpath'] <> "") {
302
				$dhcpdconf .= "	option root-path \"{$dhcpifconf['rootpath']}\";\n";
303
      }
304
		}
305
		
306
		$dhcpdconf .= <<<EOD
307
}
308

    
309
EOD;
310

    
311
		/* add static mappings */
312
		if (is_array($dhcpifconf['staticmap'])) {
313

    
314
			$i = 0;
315
			foreach ($dhcpifconf['staticmap'] as $sm) {
316
				$dhcpdconf .= <<<EOD
317
host s_{$dhcpif}_{$i} {
318
	hardware ethernet {$sm['mac']};
319

    
320
EOD;
321
				if ($sm['ipaddr'])
322
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
323

    
324
				if ($sm['hostname'])
325
					$dhcpdconf .= "	option host-name {$sm['hostname']};\n";
326

    
327
				$dhcpdconf .= "}\n";
328
				$i++;
329
			}
330
		}
331

    
332
		$dhcpdifs[] = $ifcfg['if'];
333
	}
334

    
335
	fwrite($fd, $dhcpdconf);
336
	fclose($fd);
337

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

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

    
345
	if ($g['booting']) {
346
		print "done.\n";
347
	}
348

    
349
	return 0;
350
}
351

    
352
function interfaces_staticarp_configure($if) {
353
	global $config, $g;
354
	if(isset($config['system']['developerspew'])) {
355
		$mt = microtime();
356
		echo "interfaces_staticarp_configure($if) being called $mt\n";
357
	}
358

    
359
        $ifcfg = $config['interfaces'][$if];
360

    
361
        /* Enable staticarp, if enabled */
362
        if(isset($config['dhcpd'][$if]['staticarp'])) {
363
                mwexec("/sbin/ifconfig " . escapeshellarg($ifcfg['if']) . " staticarp " );
364
                mwexec("/usr/sbin/arp -ad > /dev/null 2>&1 ");
365
                if (is_array($config['dhcpd'][$if]['staticmap'])) {
366

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

    
370
                        }
371

    
372
                }
373
        } else {
374
                mwexec("/sbin/ifconfig " . escapeshellarg($ifcfg['if']) . " -staticarp " );
375
                mwexec("/usr/sbin/arp -da > /dev/null 2>&1 ");
376
        }
377

    
378
        return 0;
379
}
380

    
381
function services_dhcrelay_configure() {
382
	global $config, $g;
383
	if(isset($config['system']['developerspew'])) {
384
		$mt = microtime();
385
		echo "services_dhcrelay_configure() being called $mt\n";
386
	}
387

    
388
	/* kill any running dhcrelay */
389
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
390

    
391
	$dhcrelaycfg = $config['dhcrelay'];
392

    
393
	/* DHCPRelay enabled on any interfaces? */
394
	$dhcrelayenable = false;
395
	if(is_array($dhcrelaycfg)) {
396
		foreach ($dhcrelaycfg as $dhcrelayif => $dhcrelayifconf) {
397
			if (isset($dhcrelayifconf['enable']) &&
398
				(($dhcrelayif == "lan") ||
399
				(isset($config['interfaces'][$dhcrelayif]['enable']) &&
400
				$config['interfaces'][$dhcrelayif]['if'] && (!$config['interfaces'][$dhcrelayif]['bridge']))))
401
				$dhcrelayenable = true;
402
		}
403
	}
404

    
405
	if (!$dhcrelayenable)
406
		return 0;
407

    
408
	if ($g['booting'])
409
		echo "Starting DHCP relay service...";
410
	else
411
		sleep(1);
412

    
413
	$dhcrelayifs = array();
414
	foreach ($dhcrelaycfg as $dhcrelayif => $dhcrelayifconf) {
415

    
416
		$ifcfg = $config['interfaces'][$dhcrelayif];
417

    
418
		if (!isset($dhcrelayifconf['enable']) ||
419
			(($dhcrelayif != "lan") &&
420
			(!isset($ifcfg['enable']) || !$ifcfg['if'] || $ifcfg['bridge'])))
421
			continue;
422

    
423
		$dhcrelayifs[] = $ifcfg['if'];
424
	}
425

    
426
	/* In order for the relay to work, it needs to be active on the
427
	   interface in which the destination server sits */
428
	foreach ($config['interfaces'] as $ifname) {
429
		$subnet = $ifname['ipaddr'] . "/" . $ifname['subnet'];
430
		if (ip_in_subnet($dhcrelaycfg['server'],$subnet))
431
			$destif = $ifname['if'];
432
	}
433

    
434
	if (!isset($destif))
435
		$destif = $config['interfaces']['wan']['if'];
436

    
437
	$dhcrelayifs[] = $destif;
438
	$dhcrelayifs = array_unique($dhcrelayifs);
439

    
440
	/* fire up dhcrelay */
441
	$cmd = "/usr/local/sbin/dhcrelay -i " .  join(" -i ", $dhcrelayifs);
442

    
443
	if (isset($dhcrelaycfg['agentoption']))
444
		$cmd .=  " -a -m replace";
445

    
446
	$cmd .= " {$dhcrelaycfg['server']}";
447
	mwexec($cmd);
448

    
449
	if (!$g['booting']) {
450
		/* set the reload filter dity flag */
451
		touch("{$g['tmp_path']}/filter_dirty");
452
	}
453

    
454
	return 0;
455
}
456

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

    
464
	if (file_exists("{$g['vardb_path']}/ez-ipupdate.cache")) {
465
		conf_mount_rw();
466
		unlink("{$g['vardb_path']}/ez-ipupdate.cache");
467
		conf_mount_ro();
468
	}
469

    
470
	if (file_exists("{$g['conf_path']}/ez-ipupdate.cache")) {
471
		conf_mount_rw();
472
		unlink("{$g['conf_path']}/ez-ipupdate.cache");
473
		conf_mount_ro();
474
	}
475
	
476
	if (file_exists("{$g['conf_path']}/dyndns.cache")) {
477
		conf_mount_rw();
478
		unlink("{$g['conf_path']}/dyndns.cache");
479
		conf_mount_ro();
480
	}
481

    
482
	return 0;
483
}
484

    
485
function services_dyndns_configure() {
486
	global $config, $g;
487
	if(isset($config['system']['developerspew'])) {
488
		$mt = microtime();
489
		echo "services_dyndns_configure() being called $mt\n";
490
	}
491

    
492
	$dyndnscfg = $config['dyndns'];
493
	$wancfg = $config['interfaces']['wan'];
494

    
495
	if (isset($dyndnscfg['enable'])) {
496

    
497
		if ($g['booting']) {
498
			echo "Starting DynDNS client...";
499
			if(isset($config['system']['use_old_dyndns'])) {
500
				echo " [Using ez-ipupdate] ";
501
				services_dyndns_configure_old();
502
				return;
503
			}
504
		} else {
505
			sleep(1);
506
			if(isset($config['system']['use_old_dyndns'])) {
507
				services_dyndns_configure_old();
508
				return;
509
			}
510
		}
511

    
512
		/* load up the dyndns.class */
513
		require_once("dyndns.class");
514

    
515
		log_error("DynDns: Running updatedns()");
516

    
517
		/* determine WAN interface name */
518
		$wanif = get_real_wan_interface();
519
		/* get ip */
520
		$ip = find_interface_ip($wanif);
521

    
522
		$dns = new updatedns($dnsService = $config['dyndns']['type'],
523
							 $dnsHost = $config['dyndns']['host'],
524
							 $dnsUser = $config['dyndns']['username'],
525
							 $dnsPass = $config['dyndns']['password'],
526
							 $dnsWilcard = $config['dyndns']['wildcard'],
527
							 $dnsMX = $config['dyndns']['mx']);
528

    
529
		if ($g['booting'])
530
			echo "done.\n";
531
	}
532

    
533
	return 0;
534
}
535

    
536
function services_dyndns_configure_old() {
537
	global $config, $g;
538
	if(isset($config['system']['developerspew'])) {
539
		$mt = microtime();
540
		echo "services_dyndns_configure_old() being called $mt\n";
541
	}
542

    
543
        /* kill any running ez-ipupdate */
544
        /* ez-ipupdate needs SIGQUIT instead of SIGTERM */
545
        sigkillbypid("{$g['varrun_path']}/ez-ipupdate.pid", "QUIT");
546

    
547
        $dyndnscfg = $config['dyndns'];
548
        $wancfg = $config['interfaces']['wan'];
549

    
550
        if (isset($dyndnscfg['enable'])) {
551

    
552
                if ($g['booting'])
553
                        echo "Starting DynDNS client...";
554
                else
555
                        sleep(1);
556

    
557
                /* determine WAN interface name */
558
                $wanif = get_real_wan_interface();
559

    
560
                /* write ez-ipupdate.conf */
561
                $fd = fopen("{$g['varetc_path']}/ez-ipupdate.conf", "w");
562
                if (!$fd) {
563
                        printf("Error: cannot open ez-ipupdate.conf in services_dyndns_configure().\n");
564
                        return 1;
565
                }
566

    
567
                $ezipupdateconf = <<<EOD
568
service-type={$dyndnscfg['type']}
569
user={$dyndnscfg['username']}:{$dyndnscfg['password']}
570
host={$dyndnscfg['host']}
571
interface={$wanif}
572
max-interval=2073600
573
pid-file={$g['varrun_path']}/ez-ipupdate.pid
574
cache-file={$g['vardb_path']}/ez-ipupdate.cache
575
execute=/etc/rc.dyndns.storecache
576
daemon
577

    
578
EOD;
579

    
580
                /* enable server[:port]? */
581
                if ($dyndnscfg['server']) {
582
                        if ($dyndnscfg['port'])
583
                                $ezipupdateconf .= "server={$dyndnscfg['server']}:{$dyndnscfg['port']}\n";
584
                        else
585
                                $ezipupdateconf .= "server={$dyndnscfg['server']}\n";
586
                }
587

    
588
                /* enable MX? */
589
                if ($dyndnscfg['mx']) {
590
                        $ezipupdateconf .= "mx={$dyndnscfg['mx']}\n";
591
                }
592

    
593
                /* enable wildcards? */
594
                if (isset($dyndnscfg['wildcard'])) {
595
                        $ezipupdateconf .= "wildcard\n";
596
                }
597

    
598
                fwrite($fd, $ezipupdateconf);
599
                fclose($fd);
600

    
601
                /* if we're booting, copy the cache file from /conf */
602
                if ($g['booting']) {
603
                        if (file_exists("{$g['conf_path']}/ez-ipupdate.cache")) {
604
                                copy("{$g['conf_path']}/ez-ipupdate.cache", "{$g['vardb_path']}/ez-ipupdate.cache");
605
                       }
606
                }
607

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

    
611
                if ($g['booting'])
612
                        echo "done\n";
613
        }
614

    
615
        return 0;
616
}
617

    
618
function services_dnsmasq_configure() {
619
	global $config, $g;
620
	$return = 0;
621
	
622
	if(isset($config['system']['developerspew'])) {
623
		$mt = microtime();
624
		echo "services_dnsmasq_configure() being called $mt\n";
625
	}
626

    
627
	/* kill any running dnsmasq */
628
	sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
629

    
630
	if (isset($config['dnsmasq']['enable'])) {
631

    
632
		if ($g['booting'])
633
			echo "Starting DNS forwarder...";
634
		else
635
			sleep(1);
636

    
637
		/* generate hosts file */
638
		if(system_hosts_generate()!=0)
639
			$return = 1;
640

    
641
		$args = "";
642

    
643
		if (isset($config['dnsmasq']['regdhcp'])) {
644

    
645
			$args .= " -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases" .
646
				" -s {$config['system']['domain']}";
647
		}
648

    
649
                if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
650
                        foreach($config['dnsmasq']['domainoverrides'] as $override) {
651
                                $args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
652
                        }
653
                }
654

    
655
		/* suppose that dnsmasq handles our domain and don't send
656
		requests for our local domain to upstream servers */
657
		//if (!empty($config['system']['domain'])) {
658
		//	$args .= sprintf(' --local=/%s/', $config['system']['domain']);
659
		//}
660

    
661
		/* run dnsmasq */
662
		mwexec("/usr/local/sbin/dnsmasq --cache-size=5000 {$args}");
663

    
664
		if ($g['booting'])
665
			echo "done.\n";
666
	}
667

    
668
	if (!$g['booting']) {
669
		if(services_dhcpd_configure()!=0)
670
			$return = 1;
671
	}
672

    
673
	return $return;
674
}
675

    
676
function services_snmpd_configure() {
677
	global $config, $g;
678
	if(isset($config['system']['developerspew'])) {
679
		$mt = microtime();
680
		echo "services_snmpd_configure() being called $mt\n";
681
	}
682

    
683
	/* kill any running snmpd */
684
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
685
	if(is_process_running("bsnmpd")) 
686
		exec("/usr/bin/killall bsnmpd");
687

    
688
	if (isset($config['snmpd']['enable'])) {
689

    
690
		if ($g['booting'])
691
			echo "Starting SNMP daemon... ";
692

    
693
		/* generate snmpd.conf */
694
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
695
		if (!$fd) {
696
			printf("Error: cannot open snmpd.conf in services_snmpd_configure().\n");
697
			return 1;
698
		}
699

    
700

    
701
		$snmpdconf = <<<EOD
702
location := "{$config['snmpd']['syslocation']}"
703
contact := "{$config['snmpd']['syscontact']}"
704
read := "{$config['snmpd']['rocommunity']}"
705

    
706
EOD;
707

    
708
/* No docs on what write strings do there for disable for now.
709
		if(isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])){
710
		    $snmpdconf .= <<<EOD
711
# write string
712
write := "{$config['snmpd']['rwcommunity']}"
713

    
714
EOD;
715
		}
716
*/
717

    
718

    
719
		if(isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])){
720
		    $snmpdconf .= <<<EOD
721
# SNMP Trap support.
722
traphost := {$config['snmpd']['trapserver']}
723
trapport := {$config['snmpd']['trapserverport']}
724
trap := "{$config['snmpd']['trapstring']}"
725

    
726

    
727
EOD;
728
		}
729

    
730

    
731
		$snmpdconf .= <<<EOD
732
system := 1     # pfSense
733
%snmpd
734
begemotSnmpdDebugDumpPdus       = 2
735
begemotSnmpdDebugSyslogPri      = 7
736
begemotSnmpdCommunityString.0.1 = $(read)
737

    
738
EOD;
739

    
740
/* No docs on what write strings do there for disable for now.
741
		if(isset($config['snmpd']['rwcommunity']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])){
742
		    $snmpdconf .= <<<EOD
743
begemotSnmpdCommunityString.0.2 = $(write)
744

    
745
EOD;
746
		}
747
*/
748

    
749

    
750
		if(isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])){
751
		    $snmpdconf .= <<<EOD
752
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
753
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
754
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
755

    
756
EOD;
757
		}
758

    
759

    
760
		$snmpdconf .= <<<EOD
761
begemotSnmpdCommunityDisable    = 1
762

    
763
EOD;
764

    
765
		if(isset($config['snmpd']['bindlan'])) {
766
			$bind_to_ip = $config['interfaces']['lan']['ipaddr'];
767
		} else {
768
			$bind_to_ip = "0.0.0.0";
769
		}
770

    
771
		if(is_port( $config['snmpd']['pollport'] )) {
772
		    $snmpdconf .= <<<EOD
773
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
774

    
775
EOD;
776

    
777
		}
778

    
779
		$snmpdconf .= <<<EOD
780
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
781
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
782

    
783
# These are bsnmp macros not php vars.
784
sysContact      = $(contact)
785
sysLocation     = $(location)
786
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
787

    
788
snmpEnableAuthenTraps = 2
789

    
790
EOD;
791

    
792
		if (is_array( $config['snmpd']['modules'] )) {
793
		    if(isset($config['snmpd']['modules']['mibii'])) {
794
			$snmpdconf .= <<<EOD
795
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
796

    
797
EOD;
798
		    }
799

    
800
		    if(isset($config['snmpd']['modules']['netgraph'])) {
801
			$snmpdconf .= <<<EOD
802
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
803
%netgraph
804
begemotNgControlNodeName = "snmpd"
805

    
806
EOD;
807
		    }
808

    
809
		    if(isset($config['snmpd']['modules']['pf'])) {
810
			$snmpdconf .= <<<EOD
811
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
812

    
813
EOD;
814
		    }
815

    
816
		    if(isset($config['snmpd']['modules']['hostres'])) {
817
			$snmpdconf .= <<<EOD
818
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
819

    
820
EOD;
821
		    }
822
		    if(isset($config['snmpd']['modules']['bridge'])) {
823
			$snmpdconf .= <<<EOD
824
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
825
# config must end with blank line
826

    
827

    
828
EOD;
829
		    }
830
		}
831

    
832
		fwrite($fd, $snmpdconf);
833
		fclose($fd);
834

    
835
		if (isset($config['snmpd']['bindlan'])) {
836
			$bindlan = "";
837
		}
838

    
839
		/* run bsnmpd */
840
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
841
			"{$bindlan} -p {$g['varrun_path']}/snmpd.pid");
842

    
843
		if ($g['booting'])
844
			echo "done.\n";
845
	}
846

    
847
	return 0;
848
}
849

    
850
function services_proxyarp_configure() {
851
	global $config, $g;
852
	if(isset($config['system']['developerspew'])) {
853
		$mt = microtime();
854
		echo "services_proxyarp_configure() being called $mt\n";
855
	}
856

    
857
	/* kill any running choparp */
858
	killbyname("choparp");
859

    
860
	if (isset($config['virtualip']) && is_array($config['virtualip']['vip'])) {
861
		$paa = array();
862

    
863
		/* group by interface */
864
		foreach ($config['virtualip']['vip'] as $vipent) {
865
			if ($vipent['mode'] === "proxyarp") {
866
				if ($vipent['interface'])
867
					$if = $vipent['interface'];
868
				else
869
					$if = "wan";
870

    
871
				if (!is_array($paa[$if]))
872
					$paa[$if] = array();
873

    
874
				$paa[$if][] = $vipent;
875
			}
876
		}
877

    
878
		if (count($paa))
879
		foreach ($paa as $paif => $paents) {
880
			if ($paif == "wan" && !(is_ipaddr($config['interfaces']['wan']['ipaddr']) ||
881
                                       ($config['interfaces']['wan']['ipaddr'] == "dhcp") ||
882
                                       ($config['interfaces']['wan']['ipaddr'] == "bigpond")))
883
                               continue;
884

    
885
			$args = $config['interfaces'][$paif]['if'] . " auto";
886

    
887
			foreach ($paents as $paent) {
888

    
889
				if (isset($paent['subnet']))
890
					$args .= " " . escapeshellarg("{$paent['subnet']}/{$paent['subnet_bits']}");
891
				else if (isset($paent['range']))
892
					$args .= " " . escapeshellarg($paent['range']['from'] . "-" .
893
						$paent['range']['to']);
894
			}
895

    
896
			mwexec_bg("/usr/local/sbin/choparp " . $args);
897
		}
898
	}
899
}
900

    
901
function services_dnsupdate_process() {
902
	global $config, $g;
903
	if(isset($config['system']['developerspew'])) {
904
		$mt = microtime();
905
		echo "services_dnsupdate_process() being called $mt\n";
906
	}
907

    
908
	/* Dynamic DNS updating active? */
909
	if (isset($config['dnsupdate']['enable'])) {
910

    
911
		$wanip = get_current_wan_address();
912
		if ($wanip) {
913

    
914
			$keyname = $config['dnsupdate']['keyname'];
915
			/* trailing dot */
916
			if (substr($keyname, -1) != ".")
917
				$keyname .= ".";
918

    
919
			$hostname = $config['dnsupdate']['host'];
920
			/* trailing dot */
921
			if (substr($hostname, -1) != ".")
922
				$hostname .= ".";
923

    
924
			/* write private key file
925
			   this is dumb - public and private keys are the same for HMAC-MD5,
926
			   but nsupdate insists on having both */
927
			$fd = fopen("{$g['varetc_path']}/K{$keyname}+157+00000.private", "w");
928
			$privkey .= <<<EOD
929
Private-key-format: v1.2
930
Algorithm: 157 (HMAC)
931
Key: {$config['dnsupdate']['keydata']}
932

    
933
EOD;
934
			fwrite($fd, $privkey);
935
			fclose($fd);
936

    
937
			/* write public key file */
938
			if ($config['dnsupdate']['keytype'] == "zone") {
939
				$flags = 257;
940
				$proto = 3;
941
			} else if ($config['dnsupdate']['keytype'] == "host") {
942
				$flags = 513;
943
				$proto = 3;
944
			} else if ($config['dnsupdate']['keytype'] == "user") {
945
				$flags = 0;
946
				$proto = 2;
947
			}
948

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

    
953
			/* generate update instructions */
954
			$upinst = "";
955
			if (!empty($config['dnsupdate']['server']))
956
				$upinst .= "server {$config['dnsupdate']['server']}\n";
957
			$upinst .= "update delete {$config['dnsupdate']['host']} A\n";
958
			$upinst .= "update add {$config['dnsupdate']['host']} {$config['dnsupdate']['ttl']} A {$wanip}\n";
959
			$upinst .= "\n";	/* mind that trailing newline! */
960

    
961
			$fd = fopen("{$g['varetc_path']}/nsupdatecmds", "w");
962
			fwrite($fd, $upinst);
963
			fclose($fd);
964

    
965
			/* invoke nsupdate */
966
			$cmd = "/usr/sbin/nsupdate -k {$g['varetc_path']}/K{$keyname}+157+00000.key";
967
			if (isset($config['dnsupdate']['usetcp']))
968
				$cmd .= " -v";
969
			$cmd .= " {$g['varetc_path']}/nsupdatecmds";
970

    
971
			mwexec_bg($cmd);
972
		}
973
	}
974

    
975
	return 0;
976
}
977

    
978
function setup_wireless_olsr() {
979
	global $config, $g;
980
	if(!$config['installedpackages']['olsrd'] || !$config['installedpackages'])
981
		return;
982
	if(isset($config['system']['developerspew'])) {
983
		$mt = microtime();
984
		echo "setup_wireless_olsr($interface) being called $mt\n";
985
	}
986
	conf_mount_rw();
987
	foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
988
		$olsr_enable = $olsrd['enable'];
989
		if($olsr_enable <> "on")
990
			return;
991
		$fd = fopen("{$g['varetc_path']}/olsr.conf", "w");
992

    
993
		if($olsrd['announcedynamicroute'] or $olsrd['enableannounce'] == "on") {
994
			$enableannounce .= "\nHna4\n";
995
			$enableannounce .= "{\n";
996
		if($olsrd['announcedynamicroute'])
997
			$enableannounce .= "\t{$olsrd['announcedynamicroute']}\n";
998
		if($olsrd['enableannounce'] == "on")
999
			$enableannounce .= "0.0.0.0 0.0.0.0";
1000
			$enableannounce .= "\n}\n";
1001
		} else {
1002
			$enableannounce = "";
1003
		}
1004

    
1005
		$olsr .= <<<EODA
1006
#
1007
# olsr.org OLSR daemon config file
1008
#
1009
# Lines starting with a # are discarded
1010
#
1011
# This file was generated by setup_wireless_olsr() in services.inc
1012
#
1013

    
1014
# This file is an example of a typical
1015
# configuration for a mostly static
1016
# network(regarding mobility) using
1017
# the LQ extention
1018

    
1019
# Debug level(0-9)
1020
# If set to 0 the daemon runs in the background
1021

    
1022
DebugLevel	2
1023

    
1024
# IP version to use (4 or 6)
1025

    
1026
IpVersion	4
1027

    
1028
# Clear the screen each time the internal state changes
1029

    
1030
ClearScreen     yes
1031

    
1032
{$enableannounce}
1033

    
1034
# Should olsrd keep on running even if there are
1035
# no interfaces available? This is a good idea
1036
# for a PCMCIA/USB hotswap environment.
1037
# "yes" OR "no"
1038

    
1039
AllowNoInt	yes
1040

    
1041
# TOS(type of service) value for
1042
# the IP header of control traffic.
1043
# If not set it will default to 16
1044

    
1045
#TosValue	16
1046

    
1047
# The fixed willingness to use(0-7)
1048
# If not set willingness will be calculated
1049
# dynamically based on battery/power status
1050
# if such information is available
1051

    
1052
#Willingness    	4
1053

    
1054
# Allow processes like the GUI front-end
1055
# to connect to the daemon.
1056

    
1057
IpcConnect
1058
{
1059
     # Determines how many simultaneously
1060
     # IPC connections that will be allowed
1061
     # Setting this to 0 disables IPC
1062

    
1063
     MaxConnections  0
1064

    
1065
     # By default only 127.0.0.1 is allowed
1066
     # to connect. Here allowed hosts can
1067
     # be added
1068

    
1069
     Host            127.0.0.1
1070
     #Host            10.0.0.5
1071

    
1072
     # You can also specify entire net-ranges
1073
     # that are allowed to connect. Multiple
1074
     # entries are allowed
1075

    
1076
     #Net             192.168.1.0 255.255.255.0
1077
}
1078

    
1079
# Wether to use hysteresis or not
1080
# Hysteresis adds more robustness to the
1081
# link sensing but delays neighbor registration.
1082
# Used by default. 'yes' or 'no'
1083

    
1084
UseHysteresis	no
1085

    
1086
# Hysteresis parameters
1087
# Do not alter these unless you know
1088
# what you are doing!
1089
# Set to auto by default. Allowed
1090
# values are floating point values
1091
# in the interval 0,1
1092
# THR_LOW must always be lower than
1093
# THR_HIGH.
1094

    
1095
#HystScaling	0.50
1096
#HystThrHigh	0.80
1097
#HystThrLow	0.30
1098

    
1099

    
1100
# Link quality level
1101
# 0 = do not use link quality
1102
# 1 = use link quality for MPR selection
1103
# 2 = use link quality for MPR selection and routing
1104
# Defaults to 0
1105

    
1106
LinkQualityLevel	{$olsrd['enablelqe']}
1107

    
1108
# Link quality window size
1109
# Defaults to 10
1110

    
1111
LinkQualityWinSize	10
1112

    
1113
# Polling rate in seconds(float).
1114
# Default value 0.05 sec
1115

    
1116
Pollrate	0.05
1117

    
1118

    
1119
# TC redundancy
1120
# Specifies how much neighbor info should
1121
# be sent in TC messages
1122
# Possible values are:
1123
# 0 - only send MPR selectors
1124
# 1 - send MPR selectors and MPRs
1125
# 2 - send all neighbors
1126
#
1127
# defaults to 0
1128

    
1129
TcRedundancy	2
1130

    
1131
#
1132
# MPR coverage
1133
# Specifies how many MPRs a node should
1134
# try select to reach every 2 hop neighbor
1135
#
1136
# Can be set to any integer >0
1137
#
1138
# defaults to 1
1139

    
1140
MprCoverage	3
1141

    
1142
# Example plugin entry with parameters:
1143

    
1144
EODA;
1145

    
1146
if($olsrd['enablehttpinfo'] == "on") {
1147
	$olsr .= <<<EODB
1148

    
1149
LoadPlugin "/usr/local/lib/olsrd_httpinfo.so.0.1"
1150
{
1151
    PlParam     "port"   "{$olsrd['port']}"
1152
    PlParam     "Net"    "{$olsrd['allowedhttpinfohost']} {$olsrd['allowedhttpinfosubnet']}"
1153
}
1154

    
1155
EODB;
1156

    
1157
}
1158

    
1159
if($olsrd['enabledsecure'] == "on") {
1160
	$olsr .= <<<EODC
1161

    
1162
LoadPlugin "/usr/local/lib/olsrd_secure.so.0.5"
1163
{
1164
    PlParam     "Keyfile"   "/usr/local/etc/olsrkey.txt"
1165
}
1166

    
1167
EODC;
1168

    
1169
}
1170

    
1171
if($olsrd['enabledyngw'] == "on") {
1172

    
1173
	/* unset default route, olsr auto negotiates */
1174
	mwexec("/sbin/route delete default");
1175

    
1176
	$olsr .= <<<EODE
1177

    
1178
LoadPlugin "/usr/local/lib/olsrd_dyn_gw.so.0.4"
1179
{
1180
    # how often to look for a inet gw, in seconds
1181
    # defaults to 5 secs, if commented out
1182
    PlParam     "Interval"   "{$olsrd['polling']}"
1183

    
1184
    # if one or more IPv4 addresses are given, do a ping on these in
1185
    # descending order to validate that there is not only an entry in
1186
    # routing table, but also a real internet connection. If any of
1187
    # these addresses could be pinged successfully, the test was
1188
    # succesful, i.e. if the ping on the 1st address was successful,the
1189
    # 2nd won't be pinged
1190
    PlParam     "Ping"       "{$olsrd['ping']}"
1191
    #PlParam     "HNA"   "192.168.81.0 255.255.255.0"
1192
}
1193

    
1194
EODE;
1195

    
1196
}
1197

    
1198
foreach($config['installedpackages']['olsrd']['config'] as $conf) {
1199
	$interfaces = explode(',', $conf['iface_array']);
1200
	foreach($interfaces as $interface) {
1201
		$realinterface = convert_friendly_interface_to_real_interface_name($interface);
1202
$olsr .= <<<EODAD
1203
Interface "{$realinterface}"
1204
{
1205

    
1206
    # Hello interval in seconds(float)
1207
    HelloInterval    2.0
1208

    
1209
    # HELLO validity time
1210
    HelloValidityTime	20.0
1211

    
1212
    # TC interval in seconds(float)
1213
    TcInterval        5.0
1214

    
1215
    # TC validity time
1216
    TcValidityTime	30.0
1217

    
1218
    # MID interval in seconds(float)
1219
    MidInterval	5.0
1220

    
1221
    # MID validity time
1222
    MidValidityTime	30.0
1223

    
1224
    # HNA interval in seconds(float)
1225
    HnaInterval	5.0
1226

    
1227
    # HNA validity time
1228
    HnaValidityTime 	30.0
1229

    
1230
    # When multiple links exist between hosts
1231
    # the weight of interface is used to determine
1232
    # the link to use. Normally the weight is
1233
    # automatically calculated by olsrd based
1234
    # on the characteristics of the interface,
1235
    # but here you can specify a fixed value.
1236
    # Olsrd will choose links with the lowest value.
1237

    
1238
    # Weight 0
1239

    
1240

    
1241
}
1242

    
1243
EODAD;
1244

    
1245
	}
1246
	break;
1247
}
1248
		fwrite($fd, $olsr);
1249
		fclose($fd);
1250
	}
1251

    
1252
	if(is_process_running("olsrd"))
1253
		mwexec("/usr/bin/killall olsrd");
1254

    
1255
	sleep(2);
1256

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

    
1259
	conf_mount_ro();
1260
}
1261

    
1262
/* configure cron service */
1263
function configure_cron() {
1264
	global $g, $config;
1265
	conf_mount_rw();
1266
	/* preserve existing crontab entries */
1267
	$crontab_contents = file_get_contents("/etc/crontab");
1268
	$crontab_contents_a = split("\n", $crontab_contents);
1269
	
1270
	for ($i = 0; $i < count($crontab_contents_a); $i++) {
1271
		$item =& $crontab_contents_a[$i];
1272
		if (strpos($item, "# pfSense specific crontab entries") !== false) {
1273
			array_splice($crontab_contents_a, $i - 1);
1274
			break;
1275
		}
1276
	}
1277
	$crontab_contents = implode("\n", $crontab_contents_a) . "\n";
1278
	
1279
	
1280
	if (is_array($config['cron']['item'])) {
1281
		$crontab_contents .= "#\n";
1282
		$crontab_contents .= "# pfSense specific crontab entries\n";
1283
		$crontab_contents .= "# Created: " . date("F j, Y, g:i a") . "\n";
1284
		$crontab_contents .= "#\n";
1285

    
1286
		foreach ($config['cron']['item'] as $item) {
1287
			$crontab_contents .= "\n{$item['minute']}\t";
1288
			$crontab_contents .= "{$item['hour']}\t";
1289
			$crontab_contents .= "{$item['mday']}\t";
1290
			$crontab_contents .= "{$item['month']}\t";
1291
			$crontab_contents .= "{$item['wday']}\t";
1292
			$crontab_contents .= "{$item['who']}\t";
1293
			$crontab_contents .= "{$item['command']}";
1294
		}
1295
    
1296
		$crontab_contents .= "\n#\n";
1297
		$crontab_contents .= "# If possible do not add items to this file manually.\n";
1298
		$crontab_contents .= "# If you do so, this file must be terminated with a blank line (e.g. new line)\n";
1299
		$crontab_contents .= "#\n\n";
1300
	}
1301
	
1302
	/* please maintain the newline at the end of file */
1303
	file_put_contents("/etc/crontab", $crontab_contents);
1304
	
1305
	if (!$g['booting'])
1306
		conf_mount_ro();
1307
}
1308

    
1309
function upnp_action ($action) {
1310
	switch($action) {
1311
		case "start":
1312
			if(file_exists('/var/etc/miniupnpd.conf'))
1313
				mwexec_bg('/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf');
1314
			break;
1315
		case "stop":
1316
			while((int)exec("pgrep miniupnpd | wc -l") > 0)
1317
				mwexec('killall miniupnpd 2>/dev/null');
1318
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
1319
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
1320
			break;
1321
		case "restart":
1322
			upnp_action('stop');
1323
			upnp_action('start');
1324
			break;
1325
	}
1326
}
1327

    
1328
function upnp_start() {
1329
	global $config, $g;
1330
	if($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
1331
		if($g['booting']) {
1332
			echo "Starting UPnP service... ";
1333
			include('/usr/local/pkg/miniupnpd.inc');
1334
			sync_package_miniupnpd();
1335
			echo "done.\n";
1336
		}
1337
		else {
1338
			upnp_action('start');
1339
		}
1340
	}
1341
}
1342

    
1343
?>
(19-19/29)