Project

General

Profile

Download (35.6 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 -t 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['dyndnses']['dyndns'];
493

    
494
	if (is_array($dyndnscfg)) {
495
		foreach ($dyndnscfg as $dyndns) {
496
			if (!isset($dyndns['enable']))
497
				continue;
498
			/* determine interface name */
499
			if ($dyndns['interface'] == "wan")
500
				$if = get_real_wan_interface();
501
			else
502
				$if = convert_friendly_interface_to_real_interface_name($dyndns['interface']);
503

    
504
			if ($g['booting']) {
505
				echo "Starting DynDNS clients...";
506
				if (isset($config['system']['use_old_dyndns'])) {
507
					echo " [Using ez-ipupdate] ";
508
					services_dyndns_configure_old($if);
509
					continue;
510
				}
511
			} else {
512
				sleep(1);
513
				if (isset($config['system']['use_old_dyndns'])) {
514
					services_dyndns_configure_old($if);
515
					continue;
516
				}
517
			}
518

    
519
			/* load up the dyndns.class */
520
			require_once("dyndns.class");
521

    
522
			log_error("DynDns: Running updatedns()");
523

    
524
			
525
			/* get ip */
526
			$ip = find_interface_ip($if);
527

    
528
			$dns = new updatedns($dnsService = $dyndns['type'],
529
							 $dnsHost = $dyndns['host'],
530
							 $dnsUser = $dyndns['username'],
531
							 $dnsPass = $dyndns['password'],
532
							 $dnsWilcard = $dyndns['wildcard'],
533
							 $dnsMX = $dyndns['mx'], $dnsIf = $if);
534

    
535
		}
536

    
537
		if ($g['booting'])
538
			echo "done.\n";
539
	}
540

    
541
	return 0;
542
}
543

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

    
551
        /* kill any running ez-ipupdate */
552
        /* ez-ipupdate needs SIGQUIT instead of SIGTERM */
553
        sigkillbypid("{$g['varrun_path']}/ez-ipupdate_{$if}.pid", "QUIT");
554

    
555
        $dyndnscfg = $config['dyndnses']['dyndns'];
556
        $wancfg = $config['interfaces']['wan'];
557

    
558
                sleep(1);
559

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

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

    
578
EOD;
579

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

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

    
593
                /* enable wildcards? */
594
                if (isset($dyndns['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_{$if}.cache")) {
604
                                copy("{$g['conf_path']}/ez-ipupdate_{$if}.cache", "{$g['vardb_path']}/ez-ipupdate_{$if}.cache");
605
                       }
606
                }
607

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

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

    
614
        return 0;
615
}
616

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

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

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

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

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

    
640
		$args = "";
641

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

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

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

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

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

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

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

    
672
	return $return;
673
}
674

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

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

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

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

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

    
699

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

    
705
EOD;
706

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

    
713
EOD;
714
		}
715
*/
716

    
717

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

    
725

    
726
EOD;
727
		}
728

    
729

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

    
737
EOD;
738

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

    
744
EOD;
745
		}
746
*/
747

    
748

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

    
755
EOD;
756
		}
757

    
758

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

    
762
EOD;
763

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

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

    
774
EOD;
775

    
776
		}
777

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

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

    
787
snmpEnableAuthenTraps = 2
788

    
789
EOD;
790

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

    
796
EOD;
797
		    }
798

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

    
805
EOD;
806
		    }
807

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

    
812
EOD;
813
		    }
814

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

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

    
826

    
827
EOD;
828
		    }
829
		}
830

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

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

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

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

    
846
	return 0;
847
}
848

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

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

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

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

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

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

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

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

    
886
			foreach ($paents as $paent) {
887

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

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

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

    
907
	/* Dynamic DNS updating active? */
908
	if (is_array($config['dnsupdates']['dnsupdate'])) {
909
		foreach ($config['dnsupdates']['dnsupdate'] as $i => $dnsupdate) {
910
		if (!isset($dyndns['enable']))
911
				continue;
912
			/* determine interface name */
913
			if ($dyndns['interface'] == "wan")
914
				$if = get_real_wan_interface();
915
			else
916
				$if = convert_friendly_interface_to_real_interface_name($dyndns['interface']);
917

    
918
			$wanip = get_current_wan_address($if);
919
			if ($wanip) {
920

    
921
				$keyname = $dnsupdate['keyname'];
922
				/* trailing dot */
923
				if (substr($keyname, -1) != ".")
924
					$keyname .= ".";
925

    
926
				$hostname = $dnsupdate['host'];
927
				/* trailing dot */
928
				if (substr($hostname, -1) != ".")
929
					$hostname .= ".";
930

    
931
				/* write private key file
932
				   this is dumb - public and private keys are the same for HMAC-MD5,
933
				   but nsupdate insists on having both */
934
				$fd = fopen("{$g['varetc_path']}/K{$i}{$keyname}+157+00000.private", "w");
935
				$privkey .= <<<EOD
936
Private-key-format: v1.2
937
Algorithm: 157 (HMAC)
938
Key: {$dnsupdate['keydata']}
939

    
940
EOD;
941
				fwrite($fd, $privkey);
942
				fclose($fd);
943

    
944
				/* write public key file */
945
				if ($dnsupdate['keytype'] == "zone") {
946
					$flags = 257;
947
					$proto = 3;
948
				} else if ($dnsupdate['keytype'] == "host") {
949
					$flags = 513;
950
					$proto = 3;
951
				} else if ($dnsupdate['keytype'] == "user") {
952
					$flags = 0;
953
					$proto = 2;
954
				}
955

    
956
				$fd = fopen("{$g['varetc_path']}/K{$keyname}+157+00000.key", "w");
957
				fwrite($fd, "{$keyname} IN KEY {$flags} {$proto} 157 {$dnsupdate['keydata']}\n");
958
				fclose($fd);
959

    
960
				/* generate update instructions */
961
				$upinst = "";
962
				if (!empty($dnsupdate['server']))
963
					$upinst .= "server {$dnsupdate['server']}\n";
964
				$upinst .= "update delete {$dnsupdate['host']} A\n";
965
				$upinst .= "update add {$dnsupdate['host']} {$dnsupdate['ttl']} A {$wanip}\n";
966
				$upinst .= "\n";	/* mind that trailing newline! */
967

    
968
				$fd = fopen("{$g['varetc_path']}/nsupdatecmds{$i}", "w");
969
				fwrite($fd, $upinst);
970
				fclose($fd);
971

    
972
				/* invoke nsupdate */
973
				$cmd = "/usr/sbin/nsupdate -k {$g['varetc_path']}/K{$i}{$keyname}+157+00000.key";
974
				if (isset($dnsupdate['usetcp']))
975
					$cmd .= " -v";
976
				$cmd .= " {$g['varetc_path']}/nsupdatecmds{$i}";
977
	
978
				mwexec_bg($cmd);
979
			}
980
		}
981
	}
982

    
983
	return 0;
984
}
985

    
986
function setup_wireless_olsr() {
987
	global $config, $g;
988
	if(!$config['installedpackages']['olsrd'] || !$config['installedpackages'])
989
		return;
990
	if(isset($config['system']['developerspew'])) {
991
		$mt = microtime();
992
		echo "setup_wireless_olsr($interface) being called $mt\n";
993
	}
994
	conf_mount_rw();
995
	foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
996
		$olsr_enable = $olsrd['enable'];
997
		if($olsr_enable <> "on")
998
			return;
999
		$fd = fopen("{$g['varetc_path']}/olsr.conf", "w");
1000

    
1001
		if($olsrd['announcedynamicroute'] or $olsrd['enableannounce'] == "on") {
1002
			$enableannounce .= "\nHna4\n";
1003
			$enableannounce .= "{\n";
1004
		if($olsrd['announcedynamicroute'])
1005
			$enableannounce .= "\t{$olsrd['announcedynamicroute']}\n";
1006
		if($olsrd['enableannounce'] == "on")
1007
			$enableannounce .= "0.0.0.0 0.0.0.0";
1008
			$enableannounce .= "\n}\n";
1009
		} else {
1010
			$enableannounce = "";
1011
		}
1012

    
1013
		$olsr .= <<<EODA
1014
#
1015
# olsr.org OLSR daemon config file
1016
#
1017
# Lines starting with a # are discarded
1018
#
1019
# This file was generated by setup_wireless_olsr() in services.inc
1020
#
1021

    
1022
# This file is an example of a typical
1023
# configuration for a mostly static
1024
# network(regarding mobility) using
1025
# the LQ extention
1026

    
1027
# Debug level(0-9)
1028
# If set to 0 the daemon runs in the background
1029

    
1030
DebugLevel	2
1031

    
1032
# IP version to use (4 or 6)
1033

    
1034
IpVersion	4
1035

    
1036
# Clear the screen each time the internal state changes
1037

    
1038
ClearScreen     yes
1039

    
1040
{$enableannounce}
1041

    
1042
# Should olsrd keep on running even if there are
1043
# no interfaces available? This is a good idea
1044
# for a PCMCIA/USB hotswap environment.
1045
# "yes" OR "no"
1046

    
1047
AllowNoInt	yes
1048

    
1049
# TOS(type of service) value for
1050
# the IP header of control traffic.
1051
# If not set it will default to 16
1052

    
1053
#TosValue	16
1054

    
1055
# The fixed willingness to use(0-7)
1056
# If not set willingness will be calculated
1057
# dynamically based on battery/power status
1058
# if such information is available
1059

    
1060
#Willingness    	4
1061

    
1062
# Allow processes like the GUI front-end
1063
# to connect to the daemon.
1064

    
1065
IpcConnect
1066
{
1067
     # Determines how many simultaneously
1068
     # IPC connections that will be allowed
1069
     # Setting this to 0 disables IPC
1070

    
1071
     MaxConnections  0
1072

    
1073
     # By default only 127.0.0.1 is allowed
1074
     # to connect. Here allowed hosts can
1075
     # be added
1076

    
1077
     Host            127.0.0.1
1078
     #Host            10.0.0.5
1079

    
1080
     # You can also specify entire net-ranges
1081
     # that are allowed to connect. Multiple
1082
     # entries are allowed
1083

    
1084
     #Net             192.168.1.0 255.255.255.0
1085
}
1086

    
1087
# Wether to use hysteresis or not
1088
# Hysteresis adds more robustness to the
1089
# link sensing but delays neighbor registration.
1090
# Used by default. 'yes' or 'no'
1091

    
1092
UseHysteresis	no
1093

    
1094
# Hysteresis parameters
1095
# Do not alter these unless you know
1096
# what you are doing!
1097
# Set to auto by default. Allowed
1098
# values are floating point values
1099
# in the interval 0,1
1100
# THR_LOW must always be lower than
1101
# THR_HIGH.
1102

    
1103
#HystScaling	0.50
1104
#HystThrHigh	0.80
1105
#HystThrLow	0.30
1106

    
1107

    
1108
# Link quality level
1109
# 0 = do not use link quality
1110
# 1 = use link quality for MPR selection
1111
# 2 = use link quality for MPR selection and routing
1112
# Defaults to 0
1113

    
1114
LinkQualityLevel	{$olsrd['enablelqe']}
1115

    
1116
# Link quality window size
1117
# Defaults to 10
1118

    
1119
LinkQualityWinSize	10
1120

    
1121
# Polling rate in seconds(float).
1122
# Default value 0.05 sec
1123

    
1124
Pollrate	0.05
1125

    
1126

    
1127
# TC redundancy
1128
# Specifies how much neighbor info should
1129
# be sent in TC messages
1130
# Possible values are:
1131
# 0 - only send MPR selectors
1132
# 1 - send MPR selectors and MPRs
1133
# 2 - send all neighbors
1134
#
1135
# defaults to 0
1136

    
1137
TcRedundancy	2
1138

    
1139
#
1140
# MPR coverage
1141
# Specifies how many MPRs a node should
1142
# try select to reach every 2 hop neighbor
1143
#
1144
# Can be set to any integer >0
1145
#
1146
# defaults to 1
1147

    
1148
MprCoverage	3
1149

    
1150
# Example plugin entry with parameters:
1151

    
1152
EODA;
1153

    
1154
if($olsrd['enablehttpinfo'] == "on") {
1155
	$olsr .= <<<EODB
1156

    
1157
LoadPlugin "/usr/local/lib/olsrd_httpinfo.so.0.1"
1158
{
1159
    PlParam     "port"   "{$olsrd['port']}"
1160
    PlParam     "Net"    "{$olsrd['allowedhttpinfohost']} {$olsrd['allowedhttpinfosubnet']}"
1161
}
1162

    
1163
EODB;
1164

    
1165
}
1166

    
1167
if($olsrd['enabledsecure'] == "on") {
1168
	$olsr .= <<<EODC
1169

    
1170
LoadPlugin "/usr/local/lib/olsrd_secure.so.0.5"
1171
{
1172
    PlParam     "Keyfile"   "/usr/local/etc/olsrkey.txt"
1173
}
1174

    
1175
EODC;
1176

    
1177
}
1178

    
1179
if($olsrd['enabledyngw'] == "on") {
1180

    
1181
	/* unset default route, olsr auto negotiates */
1182
	mwexec("/sbin/route delete default");
1183

    
1184
	$olsr .= <<<EODE
1185

    
1186
LoadPlugin "/usr/local/lib/olsrd_dyn_gw.so.0.4"
1187
{
1188
    # how often to look for a inet gw, in seconds
1189
    # defaults to 5 secs, if commented out
1190
    PlParam     "Interval"   "{$olsrd['polling']}"
1191

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

    
1202
EODE;
1203

    
1204
}
1205

    
1206
foreach($config['installedpackages']['olsrd']['config'] as $conf) {
1207
	$interfaces = explode(',', $conf['iface_array']);
1208
	foreach($interfaces as $interface) {
1209
		$realinterface = convert_friendly_interface_to_real_interface_name($interface);
1210
$olsr .= <<<EODAD
1211
Interface "{$realinterface}"
1212
{
1213

    
1214
    # Hello interval in seconds(float)
1215
    HelloInterval    2.0
1216

    
1217
    # HELLO validity time
1218
    HelloValidityTime	20.0
1219

    
1220
    # TC interval in seconds(float)
1221
    TcInterval        5.0
1222

    
1223
    # TC validity time
1224
    TcValidityTime	30.0
1225

    
1226
    # MID interval in seconds(float)
1227
    MidInterval	5.0
1228

    
1229
    # MID validity time
1230
    MidValidityTime	30.0
1231

    
1232
    # HNA interval in seconds(float)
1233
    HnaInterval	5.0
1234

    
1235
    # HNA validity time
1236
    HnaValidityTime 	30.0
1237

    
1238
    # When multiple links exist between hosts
1239
    # the weight of interface is used to determine
1240
    # the link to use. Normally the weight is
1241
    # automatically calculated by olsrd based
1242
    # on the characteristics of the interface,
1243
    # but here you can specify a fixed value.
1244
    # Olsrd will choose links with the lowest value.
1245

    
1246
    # Weight 0
1247

    
1248

    
1249
}
1250

    
1251
EODAD;
1252

    
1253
	}
1254
	break;
1255
}
1256
		fwrite($fd, $olsr);
1257
		fclose($fd);
1258
	}
1259

    
1260
	if(is_process_running("olsrd"))
1261
		mwexec("/usr/bin/killall olsrd");
1262

    
1263
	sleep(2);
1264

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

    
1267
	conf_mount_ro();
1268
}
1269

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

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

    
1317
function upnp_action ($action) {
1318
	switch($action) {
1319
		case "start":
1320
			if(file_exists('/var/etc/miniupnpd.conf'))
1321
				mwexec_bg('/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf');
1322
			break;
1323
		case "stop":
1324
			while((int)exec("pgrep miniupnpd | wc -l") > 0)
1325
				mwexec('killall miniupnpd 2>/dev/null');
1326
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
1327
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
1328
			break;
1329
		case "restart":
1330
			upnp_action('stop');
1331
			upnp_action('start');
1332
			break;
1333
	}
1334
}
1335

    
1336
function upnp_start() {
1337
	global $config, $g;
1338
	if($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
1339
		if($g['booting']) {
1340
			echo "Starting UPnP service... ";
1341
			include('/usr/local/pkg/miniupnpd.inc');
1342
			sync_package_miniupnpd();
1343
			echo "done.\n";
1344
		}
1345
		else {
1346
			upnp_action('start');
1347
		}
1348
	}
1349
}
1350

    
1351
?>
(21-21/31)