Project

General

Profile

Download (34.1 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/* $Id$ */
3
/*
4
	services.inc
5
	part of the pfSense project (http://www.pfsense.com)
6

    
7
	originally part of m0n0wall (http://m0n0.ch/wall)
8
	Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
9
	All rights reserved.
10

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

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

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

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

    
33
/*
34
	pfSense_BUILDER_BINARIES:	/usr/bin/killall	/bin/sh	/usr/local/sbin/dhcpd	/usr/local/sbin/igmpproxy
35
	pfSense_BUILDER_BINARIES:	/sbin/ifconfig	/usr/sbin/arp	/sbin/ifconfig	/usr/local/sbin/dnsmasq
36
	pfSense_BUILDER_BINARIES:	/usr/sbin/bsnmpd	/sbin/route	/usr/local/sbin/olsrd
37
	pfSense_BUILDER_BINARIES:	/usr/local/sbin/miniupnpd	
38
	pfSense_MODULE:	utils
39
*/
40

    
41
function services_dhcpd_configure() {
42
	global $config, $g;
43
	
44
	if($g['services_dhcp_server_enable'] == false) 
45
		return;
46

    
47
	if(isset($config['system']['developerspew'])) {
48
		$mt = microtime();
49
		echo "services_dhcpd_configure($if) being called $mt\n";
50
	}
51
	
52
	/* kill any running dhcpd */
53
	if(is_process_running("dhcpd"))
54
		mwexec("killall dhcpd", true);
55

    
56
	/* DHCP enabled on any interfaces? */
57
	if (!is_dhcp_server_enabled())
58
		return 0;
59

    
60
	/* if OLSRD is enabled, allow WAN to house DHCP. */
61
	if($config['installedpackages']['olsrd'])
62
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd)
63
				if($olsrd['enable'])
64
					$is_olsr_enabled = true;
65

    
66
	/* configure DHCPD chroot */
67
	$fd = fopen("{$g['tmp_path']}/dhcpd.sh","w");
68
	$status = `mount | grep "{$g['dhcpd_chroot_path']}/dev"`;
69
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}\n");
70
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/dev\n");
71
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/etc\n");
72
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/usr/local/sbin\n");
73
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/var/db\n");
74
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/var/run\n");	
75
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/usr\n");
76
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/lib\n");
77
	fwrite($fd, "mkdir -p {$g['dhcpd_chroot_path']}/run\n");
78
	fwrite($fd, "chown -R dhcpd:_dhcp {$g['dhcpd_chroot_path']}/*\n");
79
	fwrite($fd, "cp /lib/libc.so.* {$g['dhcpd_chroot_path']}/lib/\n");
80
	fwrite($fd, "cp /usr/local/sbin/dhcpd {$g['dhcpd_chroot_path']}/usr/local/sbin/\n");
81
	fwrite($fd, "chmod a+rx {$g['dhcpd_chroot_path']}/usr/local/sbin/dhcpd\n");
82
	if(!trim($status))
83
		fwrite($fd, "mount -t devfs devfs {$g['dhcpd_chroot_path']}/dev\n");
84
	fclose($fd);
85
	mwexec("/bin/sh {$g['tmp_path']}/dhcpd.sh");
86

    
87
	$syscfg = $config['system'];
88
	$dhcpdcfg = $config['dhcpd'];
89
	$Iflist = get_configured_interface_list();
90
		
91
	if ($g['booting'])
92
		echo "Starting DHCP service...";
93
	else
94
		sleep(1);
95

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

    
103
	$custoptions = "";
104
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {	
105
		if(is_array($dhcpifconf['numberoptions']) && is_array($dhcpifconf['numberoptions']['item'])) {
106
			foreach($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
107
				$custoptions .= "option custom-{$dhcpif}-{$itemidx} code {$item['number']} = text;\n";
108
			}
109
		}
110
	}
111

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

    
126
EOD;
127

    
128
	if(isset($dhcpifconf['alwaysbroadcast'])) 
129
		$dhcpdconf .= "always-broadcast on\n";
130

    
131
	$dhcpdifs = array();
132

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

    
139
		interfaces_staticarp_configure($dhcpif);
140

    
141
		if (!isset($dhcpifconf['enable']))
142
			continue;
143

    
144
		if(!isset($dhcpifconf['disableauthoritative']))
145
			$dhcpdconf .= "authoritative;\n";
146

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

    
193
EOPP;
194
		$dhcpnum++;
195
		}
196
	}
197

    
198
	$dhcpnum = 0;
199

    
200
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
201

    
202
		$ifcfg = $config['interfaces'][$dhcpif];
203

    
204
		if (!isset($dhcpifconf['enable']) || !isset($Iflist[$dhcpif]))
205
			continue;
206
		$ifcfgip = get_interface_ip($dhcpif);
207
		$ifcfgsn = get_interface_subnet($dhcpif);
208
		$subnet = gen_subnet($ifcfgip, $ifcfgsn);
209
		$subnetmask = gen_subnet_mask($ifcfgsn);
210

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

    
215
		$dnscfg = "";
216

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

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

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

    
240
		$dhcpdconf .= "subnet $subnet netmask $subnetmask {\n";
241
		$dhcpdconf .= "	pool {\n";
242

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

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

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

    
257
		if ($dhcpifconf['gateway'])
258
			$routers = $dhcpifconf['gateway'];
259
		else
260
			$routers = $ifcfgip;
261

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

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

    
273
EOD;
274
    
275
		// default-lease-time
276
		if ($dhcpifconf['defaultleasetime'])
277
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
278

    
279
		// max-lease-time
280
		if ($dhcpifconf['maxleasetime'])
281
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
282

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

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

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

    
297
		// Handle option, number rowhelper values
298
		$dhcpdconf .= "\n";
299
		if($dhcpifconf['numberoptions']['item']) {
300
			foreach($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
301
				$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} \"{$item['value']}\";\n";
302
			}
303
		}
304

    
305
		// ldap-server
306
		if ($dhcpifconf['ldap'] <> "")
307
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
308

    
309
		// net boot information
310
		if(isset($dhcpifconf['netboot'])) {
311
			if (($dhcpifconf['next-server'] <> "") && ($dhcpifconf['filename'] <> "")) {
312
				$dhcpdconf .= "	next-server {$dhcpifconf['next-server']};\n";
313
				$dhcpdconf .= "	filename \"{$dhcpifconf['filename']}\";\n";
314
			}
315
			if ($dhcpifconf['rootpath'] <> "") {
316
				$dhcpdconf .= "	option root-path \"{$dhcpifconf['rootpath']}\";\n";
317
      		}
318
		}
319
		
320
		$dhcpdconf .= <<<EOD
321
}
322

    
323
EOD;
324

    
325
		/* add static mappings */
326
		if (is_array($dhcpifconf['staticmap'])) {
327

    
328
			$i = 0;
329
			foreach ($dhcpifconf['staticmap'] as $sm) {
330
				$dhcpdconf .= <<<EOD
331
host s_{$dhcpif}_{$i} {
332
	hardware ethernet {$sm['mac']};
333

    
334
EOD;
335
				if ($sm['ipaddr'])
336
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
337

    
338
				if ($sm['hostname']) {
339
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
340
					$dhhostname = str_replace(".", "_", $dhhostname);
341
					$dhcpdconf .= "	option host-name {$dhhostname};\n";
342
				}
343

    
344
				$dhcpdconf .= "}\n";
345
				$i++;
346
			}
347
		}
348

    
349
		$dhcpdifs[] = get_real_interface($dhcpif);
350
	}
351

    
352
	fwrite($fd, $dhcpdconf);
353
	fclose($fd);
354

    
355
	/* create an empty leases database */
356
	touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
357
	touch("{$g['varrun_path']}/dhcpd.pid");
358
	
359

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

    
364
	if ($g['booting']) {
365
		print "done.\n";
366
	}
367

    
368
	return 0;
369
}
370

    
371
function services_igmpproxy_configure() {
372
        global $config, $g;
373

    
374
        $iflist = get_configured_interface_list();
375

    
376
        /* kill any running igmpproxy */
377
        killbyname("igmpproxy");
378

    
379
	if (!is_array($config['igmpproxy']['igmpentry']))
380
		return 1;
381

    
382
        $igmpconf = <<<EOD
383

    
384
##------------------------------------------------------
385
## Enable Quickleave mode (Sends Leave instantly)
386
##------------------------------------------------------
387
quickleave
388

    
389
EOD;
390

    
391
        foreach ($config['igmpproxy']['igmpentry'] as $igmpcf) {
392
                unset($iflist[$igmpcf['ifname']]);
393
                $realif = get_real_interface($igmpcf['ifname']);
394
                if (empty($igmpcf['threshold']))
395
                        $threshld = 1;
396
                else
397
                        $threshld = $igmpcf['threshold'];
398
                $igmpconf .= "phyint {$realif} {$igmpcf['type']} ratelimit 0 threshold {$threshld}\n";
399

    
400
                if ($igmpcf['address'] <> "") {
401
                        $item = explode(" ", $igmpcf['address']);
402
                        foreach($item as $iww)
403
                                $igmpconf .= "altnet {$iww}\n";
404
                }
405
                $igmpconf .= "\n";
406
        }
407
        foreach ($iflist as $ifn) {
408
                $realif = get_real_interface($ifn);
409
                $igmpconf .= "phyint {$realif} disabled\n";
410
        }
411

    
412
        $igmpfl = fopen($g['tmp_path'] . "/igmpproxy.conf", "w");
413
        if (!$igmpfl) {
414
                log_error("Could not write Igmpproxy configuration file!");
415
                return;
416
        }
417
        fwrite($igmpfl, $igmpconf);
418
        fclose($igmpfl);
419

    
420
        mwexec("/usr/local/sbin/igmpproxy -c " . $g['tmp_path'] . "/igmpproxy.conf");
421
        log_error("Started Igmpproxy service sucsesfully.");
422

    
423
        return 0;
424
}
425

    
426
function interfaces_staticarp_configure($if) {
427
	global $config, $g;
428
	if(isset($config['system']['developerspew'])) {
429
		$mt = microtime();
430
		echo "interfaces_staticarp_configure($if) being called $mt\n";
431
	}
432

    
433
        $ifcfg = $config['interfaces'][$if];
434

    
435
        /* Enable staticarp, if enabled */
436
        if(isset($config['dhcpd'][$if]['staticarp'])) {
437
                mwexec("/sbin/ifconfig " . escapeshellarg($ifcfg['if']) . " staticarp " );
438
                mwexec("/usr/sbin/arp -d -i " . escapeshellarg($ifcfg['if']) . " -a > /dev/null 2>&1 ");
439
                if (is_array($config['dhcpd'][$if]['staticmap'])) {
440

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

    
444
                        }
445

    
446
                }
447
        } else {
448
                mwexec("/sbin/ifconfig " . escapeshellarg($ifcfg['if']) . " -staticarp " );
449
                mwexec("/usr/sbin/arp -d -i " . escapeshellarg($ifcfg['if']) . " -a > /dev/null 2>&1 ");
450
        }
451

    
452
        return 0;
453
}
454

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

    
462
	/* kill any running dhcrelay */
463
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
464

    
465
	$dhcrelaycfg = $config['dhcrelay'];
466

    
467
	/* DHCPRelay enabled on any interfaces? */
468
	$dhcrelayenable = false;
469
	if(is_array($dhcrelaycfg)) {
470
		foreach ($dhcrelaycfg as $dhcrelayif => $dhcrelayifconf) {
471
			if (isset($dhcrelayifconf['enable']) &&
472
				(($dhcrelayif == "lan") ||
473
				(isset($config['interfaces'][$dhcrelayif]['enable']) &&
474
				$config['interfaces'][$dhcrelayif]['if'] && (!link_interface_to_bridge($dhcrelayif)))))
475
				$dhcrelayenable = true;
476
		}
477
	}
478

    
479
	if (!$dhcrelayenable)
480
		return 0;
481

    
482
	if ($g['booting'])
483
		echo "Starting DHCP relay service...";
484
	else
485
		sleep(1);
486

    
487
	$dhcrelayifs = array();
488
	foreach ($dhcrelaycfg as $dhcrelayif => $dhcrelayifconf) {
489

    
490
		$ifcfg = $config['interfaces'][$dhcrelayif];
491

    
492
		if (!isset($dhcrelayifconf['enable']) ||
493
			(($dhcrelayif != "lan") &&
494
			(!isset($ifcfg['enable']) || !$ifcfg['if'] || 
495
			link_interface_to_bridge($dhcrelayif))))
496
			continue;
497

    
498
		$dhcrelayifs[] = get_real_interface($dhcrelayif);
499
	}
500

    
501
	/* In order for the relay to work, it needs to be active on the
502
	   interface in which the destination server sits */
503
	$iflist = get_configured_interface_list();
504
	foreach ($iflist as $ifname) {
505
		$subnet = get_interface_ip($ifname) . "/" . get_interface_subnet($ifname);
506
		if (ip_in_subnet($dhcrelaycfg['server'],$subnet)) {
507
			$destif = get_real_interface($ifname);
508
			break;
509
		}
510
	}
511
	if (!isset($destif)) {
512
		if (is_array($config['staticroutes']['route'])) {
513
			foreach ($config['staticroutes']['route'] as $rtent) {
514
				if (ip_in_subnet($dhcrelaycfg['server'], $rtent['network'])) {
515
					$a_gateways = return_gateways_array(true);
516
					$destif = $a_gateways[$rtent['gateway']]['interface'];
517
					break;
518
				}
519
			}
520
		}
521
	}
522

    
523
	if (!isset($destif)) {
524
		if (is_array($config['gateways']['gateway_item'])) {
525
			foreach ($config['gateways']['gateway_item'] as $gateway) {
526
				if (isset($gateway['defaultgw'])) {
527
					$a_gateways = return_gateways_array(true);
528
                                        $destif = $a_gateways[$rtent['gateway']]['interface'];
529
					break;
530
				}		
531
			}
532
		} else
533
			$destif = get_real_interface("wan");
534
	}
535

    
536
	$dhcrelayifs[] = $destif;
537
	$dhcrelayifs = array_unique($dhcrelayifs);
538

    
539
	/* fire up dhcrelay */
540
	$cmd = "/usr/local/sbin/dhcrelay -i " .  join(" -i ", $dhcrelayifs);
541

    
542
	if (isset($dhcrelaycfg['agentoption']))
543
		$cmd .=  " -a -m replace";
544

    
545
	$cmd .= " {$dhcrelaycfg['server']}";
546
	mwexec($cmd);
547

    
548
	return 0;
549
}
550

    
551
function services_dyndns_configure_client($conf) {
552

    
553
	if (!isset($conf['enable']))
554
		continue;
555

    
556
	/* load up the dyndns.class */
557
	require_once("dyndns.class");
558

    
559
	log_error("DynDns: Running updatedns()");
560

    
561
	$dns = new updatedns($dnsService = $conf['type'],
562
		$dnsHost = $conf['host'],
563
		$dnsUser = $conf['username'],
564
		$dnsPass = $conf['password'],
565
		$dnsWilcard = $conf['wildcard'],
566
		$dnsMX = $conf['mx'], 
567
		$dnsIf = "{$conf['interface']}");
568

    
569
}
570

    
571
function services_dyndns_configure($int = "") {
572
	global $config, $g;
573
	if(isset($config['system']['developerspew'])) {
574
		$mt = microtime();
575
		echo "services_dyndns_configure() being called $mt\n";
576
	}
577

    
578
	$dyndnscfg = $config['dyndnses']['dyndns'];
579

    
580
	if (is_array($dyndnscfg)) {
581
		if ($g['booting']) 
582
			echo "Starting DynDNS clients...";
583

    
584
		foreach ($dyndnscfg as $dyndns) {
585
			if (!empty($int) && $int != $dyndns['interface'])
586
				continue;
587

    
588
			services_dyndns_configure_client($dyndns);
589

    
590
			sleep(1);
591

    
592
			if (!empty($int))
593
				break;
594
		}
595

    
596
		if ($g['booting'])
597
			echo "done.\n";
598
	}
599

    
600
	return 0;
601
}
602

    
603
function services_dnsmasq_configure() {
604
	global $config, $g;
605
	$return = 0;
606
	
607
	if(isset($config['system']['developerspew'])) {
608
		$mt = microtime();
609
		echo "services_dnsmasq_configure() being called $mt\n";
610
	}
611

    
612
	/* kill any running dnsmasq */
613
	sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
614

    
615
	if (isset($config['dnsmasq']['enable'])) {
616

    
617
		if ($g['booting'])
618
			echo "Starting DNS forwarder...";
619
		else
620
			sleep(1);
621

    
622
		/* generate hosts file */
623
		if(system_hosts_generate()!=0)
624
			$return = 1;
625

    
626
		$args = "";
627

    
628
		if (isset($config['dnsmasq']['regdhcp'])) {
629
			$args .= " --dhcp-hostsfile={$g['varetc_path']}/hosts ";
630
		}
631
		
632
		/* Setup forwarded domains */
633
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
634
			foreach($config['dnsmasq']['domainoverrides'] as $override) {
635
			        $args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
636
			}
637
		}
638

    
639
		/* Allow DNS Rebind for forwarded domains */
640
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
641
			if(!isset($config['system']['webgui']['nodnsrebindcheck'])) {
642
				foreach($config['dnsmasq']['domainoverrides'] as $override) {
643
					$args .= ' --rebind-domain-ok=/' . $override['domain'] . '/ ';
644
				}
645
			}
646
		}
647

    
648
		if(!isset($config['system']['webgui']['nodnsrebindcheck']))
649
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
650

    
651
		/* run dnsmasq */
652
		mwexec("/usr/local/sbin/dnsmasq --local-ttl 1 --all-servers {$dns_rebind} --dns-forward-max=5000 --cache-size=10000 {$args}");
653

    
654
		if ($g['booting'])
655
			echo "done.\n";
656
	}
657

    
658
	if (!$g['booting']) {
659
		if(services_dhcpd_configure()!=0)
660
			$return = 1;
661
	}
662

    
663
	return $return;
664
}
665

    
666
function services_snmpd_configure() {
667
	global $config, $g;
668
	if(isset($config['system']['developerspew'])) {
669
		$mt = microtime();
670
		echo "services_snmpd_configure() being called $mt\n";
671
	}
672

    
673
	/* kill any running snmpd */
674
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
675
	if(is_process_running("bsnmpd")) 
676
		mwexec("/usr/bin/killall bsnmpd", true);
677

    
678
	if (isset($config['snmpd']['enable'])) {
679

    
680
		if ($g['booting'])
681
			echo "Starting SNMP daemon... ";
682

    
683
		/* generate snmpd.conf */
684
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
685
		if (!$fd) {
686
			printf("Error: cannot open snmpd.conf in services_snmpd_configure().\n");
687
			return 1;
688
		}
689

    
690

    
691
		$snmpdconf = <<<EOD
692
location := "{$config['snmpd']['syslocation']}"
693
contact := "{$config['snmpd']['syscontact']}"
694
read := "{$config['snmpd']['rocommunity']}"
695

    
696
EOD;
697

    
698
/* No docs on what write strings do there for disable for now.
699
		if(isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])){
700
		    $snmpdconf .= <<<EOD
701
# write string
702
write := "{$config['snmpd']['rwcommunity']}"
703

    
704
EOD;
705
		}
706
*/
707

    
708

    
709
		if(isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])){
710
		    $snmpdconf .= <<<EOD
711
# SNMP Trap support.
712
traphost := {$config['snmpd']['trapserver']}
713
trapport := {$config['snmpd']['trapserverport']}
714
trap := "{$config['snmpd']['trapstring']}"
715

    
716

    
717
EOD;
718
		}
719

    
720

    
721
		$snmpdconf .= <<<EOD
722
system := 1     # pfSense
723
%snmpd
724
begemotSnmpdDebugDumpPdus       = 2
725
begemotSnmpdDebugSyslogPri      = 7
726
begemotSnmpdCommunityString.0.1 = $(read)
727

    
728
EOD;
729

    
730
/* No docs on what write strings do there for disable for now.
731
		if(isset($config['snmpd']['rwcommunity']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])){
732
		    $snmpdconf .= <<<EOD
733
begemotSnmpdCommunityString.0.2 = $(write)
734

    
735
EOD;
736
		}
737
*/
738

    
739

    
740
		if(isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])){
741
		    $snmpdconf .= <<<EOD
742
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
743
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
744
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
745

    
746
EOD;
747
		}
748

    
749

    
750
		$snmpdconf .= <<<EOD
751
begemotSnmpdCommunityDisable    = 1
752

    
753
EOD;
754

    
755
		if(isset($config['snmpd']['bindlan'])) {
756
			$bind_to_ip = get_interface_ip("lan");
757
		} else {
758
			$bind_to_ip = "0.0.0.0";
759
		}
760

    
761
		if(is_port( $config['snmpd']['pollport'] )) {
762
		    $snmpdconf .= <<<EOD
763
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
764

    
765
EOD;
766

    
767
		}
768

    
769
		$snmpdconf .= <<<EOD
770
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
771
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
772

    
773
# These are bsnmp macros not php vars.
774
sysContact      = $(contact)
775
sysLocation     = $(location)
776
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
777

    
778
snmpEnableAuthenTraps = 2
779

    
780
EOD;
781

    
782
		if (is_array( $config['snmpd']['modules'] )) {
783
		    if(isset($config['snmpd']['modules']['mibii'])) {
784
			$snmpdconf .= <<<EOD
785
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
786

    
787
EOD;
788
		    }
789

    
790
		    if(isset($config['snmpd']['modules']['netgraph'])) {
791
			$snmpdconf .= <<<EOD
792
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
793
%netgraph
794
begemotNgControlNodeName = "snmpd"
795

    
796
EOD;
797
		    }
798

    
799
		    if(isset($config['snmpd']['modules']['pf'])) {
800
			$snmpdconf .= <<<EOD
801
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
802

    
803
EOD;
804
		    }
805

    
806
		    if(isset($config['snmpd']['modules']['hostres'])) {
807
			$snmpdconf .= <<<EOD
808
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
809

    
810
EOD;
811
		    }
812
		    if(isset($config['snmpd']['modules']['bridge'])) {
813
			$snmpdconf .= <<<EOD
814
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
815
# config must end with blank line
816

    
817

    
818
EOD;
819
		    }
820
		}
821

    
822
		fwrite($fd, $snmpdconf);
823
		fclose($fd);
824

    
825
		if (isset($config['snmpd']['bindlan'])) {
826
			$bindlan = "";
827
		}
828

    
829
		/* run bsnmpd */
830
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
831
			"{$bindlan} -p {$g['varrun_path']}/snmpd.pid");
832

    
833
		if ($g['booting'])
834
			echo "done.\n";
835
	}
836

    
837
	return 0;
838
}
839

    
840
function services_dnsupdate_process($int = "") {
841
	global $config, $g;
842
	if(isset($config['system']['developerspew'])) {
843
		$mt = microtime();
844
		echo "services_dnsupdate_process() being called $mt\n";
845
	}
846

    
847
	/* Dynamic DNS updating active? */
848
	if (is_array($config['dnsupdates']['dnsupdate'])) {
849
		foreach ($config['dnsupdates']['dnsupdate'] as $i => $dnsupdate) {
850
			if (!isset($dnsupdate['enable']))
851
				continue;
852
			if (!empty($int) && $int != $dnsupdate['interface'])
853
				continue;
854

    
855
			/* determine interface name */
856
			$if = get_real_interface($dnsupdate['interface']);
857
			$wanip = get_interface_ip($dnsupdate['interface']);
858
			if ($wanip) {
859

    
860
				$keyname = $dnsupdate['keyname'];
861
				/* trailing dot */
862
				if (substr($keyname, -1) != ".")
863
					$keyname .= ".";
864

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

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

    
879
EOD;
880
				fwrite($fd, $privkey);
881
				fclose($fd);
882

    
883
				/* write public key file */
884
				if ($dnsupdate['keytype'] == "zone") {
885
					$flags = 257;
886
					$proto = 3;
887
				} else if ($dnsupdate['keytype'] == "host") {
888
					$flags = 513;
889
					$proto = 3;
890
				} else if ($dnsupdate['keytype'] == "user") {
891
					$flags = 0;
892
					$proto = 2;
893
				}
894

    
895
				$fd = fopen("{$g['varetc_path']}/K{$i}{$keyname}+157+00000.key", "w");
896
				fwrite($fd, "{$keyname} IN KEY {$flags} {$proto} 157 {$dnsupdate['keydata']}\n");
897
				fclose($fd);
898

    
899
				/* generate update instructions */
900
				$upinst = "";
901
				if (!empty($dnsupdate['server']))
902
					$upinst .= "server {$dnsupdate['server']}\n";
903
				$upinst .= "update delete {$dnsupdate['host']} A\n";
904
				$upinst .= "update add {$dnsupdate['host']} {$dnsupdate['ttl']} A {$wanip}\n";
905
				$upinst .= "\n";	/* mind that trailing newline! */
906

    
907
				$fd = fopen("{$g['varetc_path']}/nsupdatecmds{$i}", "w");
908
				fwrite($fd, $upinst);
909
				fclose($fd);
910

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

    
922
	return 0;
923
}
924

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

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

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

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

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

    
969
DebugLevel	2
970

    
971
# IP version to use (4 or 6)
972

    
973
IpVersion	4
974

    
975
# Clear the screen each time the internal state changes
976

    
977
ClearScreen     yes
978

    
979
{$enableannounce}
980

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

    
986
AllowNoInt	yes
987

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

    
992
#TosValue	16
993

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

    
999
#Willingness    	4
1000

    
1001
# Allow processes like the GUI front-end
1002
# to connect to the daemon.
1003

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

    
1010
     MaxConnections  0
1011

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

    
1016
     Host            127.0.0.1
1017
     #Host            10.0.0.5
1018

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

    
1023
     #Net             192.168.1.0 255.255.255.0
1024
}
1025

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

    
1031
UseHysteresis	no
1032

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

    
1042
#HystScaling	0.50
1043
#HystThrHigh	0.80
1044
#HystThrLow	0.30
1045

    
1046

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

    
1053
LinkQualityLevel	{$olsrd['enablelqe']}
1054

    
1055
# Link quality window size
1056
# Defaults to 10
1057

    
1058
LinkQualityWinSize	10
1059

    
1060
# Polling rate in seconds(float).
1061
# Default value 0.05 sec
1062

    
1063
Pollrate	0.05
1064

    
1065

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

    
1076
TcRedundancy	2
1077

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

    
1087
MprCoverage	3
1088

    
1089
# Example plugin entry with parameters:
1090

    
1091
EODA;
1092

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

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

    
1102
EODB;
1103

    
1104
}
1105

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

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

    
1114
EODC;
1115

    
1116
}
1117

    
1118
if($olsrd['enabledyngw'] == "on") {
1119

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

    
1123
	$olsr .= <<<EODE
1124

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

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

    
1141
EODE;
1142

    
1143
}
1144

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

    
1153
    # Hello interval in seconds(float)
1154
    HelloInterval    2.0
1155

    
1156
    # HELLO validity time
1157
    HelloValidityTime	20.0
1158

    
1159
    # TC interval in seconds(float)
1160
    TcInterval        5.0
1161

    
1162
    # TC validity time
1163
    TcValidityTime	30.0
1164

    
1165
    # MID interval in seconds(float)
1166
    MidInterval	5.0
1167

    
1168
    # MID validity time
1169
    MidValidityTime	30.0
1170

    
1171
    # HNA interval in seconds(float)
1172
    HnaInterval	5.0
1173

    
1174
    # HNA validity time
1175
    HnaValidityTime 	30.0
1176

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

    
1185
    # Weight 0
1186

    
1187

    
1188
}
1189

    
1190
EODAD;
1191

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

    
1199
	if(is_process_running("olsrd"))
1200
		mwexec("/usr/bin/killall olsrd", true);
1201

    
1202
	sleep(2);
1203

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

    
1206
	conf_mount_ro();
1207
}
1208

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

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

    
1255
function upnp_action ($action) {
1256
	switch($action) {
1257
		case "start":
1258
			if(file_exists('/var/etc/miniupnpd.conf'))
1259
				mwexec_bg('/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf');
1260
			break;
1261
		case "stop":
1262
			while((int)exec("pgrep miniupnpd | wc -l") > 0)
1263
				mwexec('killall miniupnpd 2>/dev/null', true);
1264
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
1265
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
1266
			break;
1267
		case "restart":
1268
			upnp_action('stop');
1269
			upnp_action('start');
1270
			break;
1271
	}
1272
}
1273

    
1274
function upnp_start() {
1275
	global $config, $g;
1276

    
1277
	if(!isset($config['installedpackages']['miniupnpd']['config']))
1278
		return;
1279

    
1280
	if($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
1281
		if($g['booting']) {
1282
			echo "Starting UPnP service... ";
1283
			require_once('/usr/local/pkg/miniupnpd.inc');
1284
			sync_package_miniupnpd();
1285
			echo "done.\n";
1286
		}
1287
		else {
1288
			upnp_action('start');
1289
		}
1290
	}
1291
}
1292

    
1293
?>
(36-36/51)