Project

General

Profile

Download (84.7 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * services.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2004-2016 Electric Sheep Fencing, LLC
7
 * All rights reserved.
8
 *
9
 * originally part of m0n0wall (http://m0n0.ch/wall)
10
 * Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>.
11
 * All rights reserved.
12
 *
13
 * Redistribution and use in source and binary forms, with or without
14
 * modification, are permitted provided that the following conditions are met:
15
 *
16
 * 1. Redistributions of source code must retain the above copyright notice,
17
 *    this list of conditions and the following disclaimer.
18
 *
19
 * 2. Redistributions in binary form must reproduce the above copyright
20
 *    notice, this list of conditions and the following disclaimer in
21
 *    the documentation and/or other materials provided with the
22
 *    distribution.
23
 *
24
 * 3. All advertising materials mentioning features or use of this software
25
 *    must display the following acknowledgment:
26
 *    "This product includes software developed by the pfSense Project
27
 *    for use in the pfSense® software distribution. (http://www.pfsense.org/).
28
 *
29
 * 4. The names "pfSense" and "pfSense Project" must not be used to
30
 *    endorse or promote products derived from this software without
31
 *    prior written permission. For written permission, please contact
32
 *    coreteam@pfsense.org.
33
 *
34
 * 5. Products derived from this software may not be called "pfSense"
35
 *    nor may "pfSense" appear in their names without prior written
36
 *    permission of the Electric Sheep Fencing, LLC.
37
 *
38
 * 6. Redistributions of any form whatsoever must retain the following
39
 *    acknowledgment:
40
 *
41
 * "This product includes software developed by the pfSense Project
42
 * for use in the pfSense software distribution (http://www.pfsense.org/).
43
 *
44
 * THIS SOFTWARE IS PROVIDED BY THE pfSense PROJECT ``AS IS'' AND ANY
45
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
46
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
47
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE pfSense PROJECT OR
48
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
49
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
50
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
51
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
53
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
54
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
55
 * OF THE POSSIBILITY OF SUCH DAMAGE.
56
 */
57

    
58
define('DYNDNS_PROVIDER_VALUES', 'citynetwork cloudflare cloudflare-v6 custom custom-v6 dnsexit dnsimple dnsmadeeasy dnsomatic dyndns dyndns-custom dyndns-static dyns easydns eurodns freedns freedns-v6 glesys googledomains gratisdns he-net he-net-v6 he-net-tunnelbroker loopia namecheap noip noip-free ods opendns ovh-dynhost route53 selfhost spdyn spdyn-v6 zoneedit');
59
define('DYNDNS_PROVIDER_DESCRIPTIONS', 'City Network,CloudFlare,CloudFlare (v6),Custom,Custom (v6),DNSexit,DNSimple,DNS Made Easy,DNS-O-Matic,DynDNS (dynamic),DynDNS (custom),DynDNS (static),DyNS,easyDNS,Euro Dns,freeDNS,freeDNS (v6),GleSYS,Google Domains,GratisDNS,HE.net,HE.net (v6),HE.net Tunnelbroker,Loopia,Namecheap,No-IP,No-IP (free),ODS.org,OpenDNS,OVH DynHOST,Route 53,SelfHost,SPDYN,SPDYN (v6),ZoneEdit');
60

    
61
/* implement ipv6 route advertising daemon */
62
function services_radvd_configure($blacklist = array()) {
63
	global $config, $g;
64

    
65
	if (isset($config['system']['developerspew'])) {
66
		$mt = microtime();
67
		echo "services_radvd_configure() being called $mt\n";
68
	}
69

    
70
	if (!is_array($config['dhcpdv6'])) {
71
		$config['dhcpdv6'] = array();
72
	}
73

    
74
	$Iflist = get_configured_interface_list();
75
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
76

    
77
	$radvdconf = "# Automatically Generated, do not edit\n";
78

    
79
	/* Process all links which need the router advertise daemon */
80
	$radvdifs = array();
81

    
82
	/* handle manually configured DHCP6 server settings first */
83
	foreach ($config['dhcpdv6'] as $dhcpv6if => $dhcpv6ifconf) {
84
		if (!is_array($config['interfaces'][$dhcpv6if])) {
85
			continue;
86
		}
87
		if (!isset($config['interfaces'][$dhcpv6if]['enable'])) {
88
			continue;
89
		}
90

    
91
		/* Do not put in the config an interface which is down */
92
		if (isset($blacklist[$dhcpv6if])) {
93
			continue;
94
		}
95
		if (!isset($dhcpv6ifconf['ramode'])) {
96
			$dhcpv6ifconf['ramode'] = $dhcpv6ifconf['mode'];
97
		}
98

    
99
		/* are router advertisements enabled? */
100
		if ($dhcpv6ifconf['ramode'] == "disabled") {
101
			continue;
102
		}
103

    
104
		if (!isset($dhcpv6ifconf['rapriority'])) {
105
			$dhcpv6ifconf['rapriority'] = "medium";
106
		}
107

    
108
		$racarpif = false;
109
		/* check if binding to CARP IP */
110
		if (!empty($dhcpv6ifconf['rainterface'])) {
111
			if (strstr($dhcpv6ifconf['rainterface'], "_vip")) {
112
				if (get_carp_interface_status($dhcpv6ifconf['rainterface']) == "MASTER") {
113
					$dhcpv6if = $dhcpv6ifconf['rainterface'];
114
					$racarpif = true;
115
				} else {
116
					continue;
117
				}
118
			}
119
		}
120

    
121
		$realif = get_real_interface($dhcpv6if, "inet6");
122

    
123
		if (isset($radvdifs[$realif])) {
124
			continue;
125
		}
126

    
127
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
128
		if (!is_ipaddrv6($ifcfgipv6)) {
129
			continue;
130
		}
131

    
132
		$ifcfgsnv6 = get_interface_subnetv6($dhcpv6if);
133
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
134
		if (!is_subnetv6($subnetv6 . "/" . $ifcfgsnv6)) {
135
			log_error("radvd: skipping configuration for interface $dhcpv6if because its subnet or prefix length is invalid.");
136
			continue;
137
		}
138
		$radvdifs[$realif] = $realif;
139

    
140
		$radvdconf .= "# Generated for DHCPv6 Server $dhcpv6if\n";
141
		$radvdconf .= "interface {$realif} {\n";
142
		if (strstr($realif, "ovpn")) {
143
			$radvdconf .= "\tUnicastOnly on;\n";
144
		}
145
		$radvdconf .= "\tAdvSendAdvert on;\n";
146

    
147
		if (is_numericint($dhcpv6ifconf['raminrtradvinterval'])) {
148
			$radvdconf .= "\tMinRtrAdvInterval {$dhcpv6ifconf['raminrtradvinterval']};\n";
149
		} else {
150
			$radvdconf .= "\tMinRtrAdvInterval 5;\n";
151
		}
152

    
153
		if (is_numericint($dhcpv6ifconf['ramaxrtradvinterval'])) {
154
			$radvdconf .= "\tMaxRtrAdvInterval {$dhcpv6ifconf['ramaxrtradvinterval']};\n";
155
		} else {
156
			$radvdconf .= "\tMaxRtrAdvInterval 20;\n";
157
		}
158
		if (is_numericint($dhcpv6ifconf['raadvdefaultlifetime'])) {
159
			$radvdconf .= "\tAdvDefaultLifetime {$dhcpv6ifconf['raadvdefaultlifetime']};\n";
160
		}
161

    
162
		$mtu = get_interface_mtu($realif);
163
		if (is_numeric($mtu)) {
164
			$radvdconf .= "\tAdvLinkMTU {$mtu};\n";
165
		} else {
166
			$radvdconf .= "\tAdvLinkMTU 1280;\n";
167
		}
168
		switch ($dhcpv6ifconf['rapriority']) {
169
			case "low":
170
				$radvdconf .= "\tAdvDefaultPreference low;\n";
171
				break;
172
			case "high":
173
				$radvdconf .= "\tAdvDefaultPreference high;\n";
174
				break;
175
			default:
176
				$radvdconf .= "\tAdvDefaultPreference medium;\n";
177
				break;
178
		}
179
		switch ($dhcpv6ifconf['ramode']) {
180
			case "managed":
181
			case "assist":
182
				$radvdconf .= "\tAdvManagedFlag on;\n";
183
				$radvdconf .= "\tAdvOtherConfigFlag on;\n";
184
				break;
185
			case "stateless_dhcp":
186
				$radvdconf .= "\tAdvManagedFlag off;\n";
187
				$radvdconf .= "\tAdvOtherConfigFlag on;\n";
188
				break;
189
		}
190
		$radvdconf .= "\tprefix {$subnetv6}/{$ifcfgsnv6} {\n";
191
		if ($racarpif == true) {
192
			$radvdconf .= "\t\tDeprecatePrefix off;\n";
193
		} else {
194
			$radvdconf .= "\t\tDeprecatePrefix on;\n";
195
		}
196
		switch ($dhcpv6ifconf['ramode']) {
197
			case "managed":
198
				$radvdconf .= "\t\tAdvOnLink on;\n";
199
				$radvdconf .= "\t\tAdvAutonomous off;\n";
200
				$radvdconf .= "\t\tAdvRouterAddr on;\n";
201
				break;
202
			case "router":
203
				$radvdconf .= "\t\tAdvOnLink off;\n";
204
				$radvdconf .= "\t\tAdvAutonomous off;\n";
205
				$radvdconf .= "\t\tAdvRouterAddr on;\n";
206
				break;
207
			case "stateless_dhcp":
208
			case "assist":
209
				$radvdconf .= "\t\tAdvOnLink on;\n";
210
				$radvdconf .= "\t\tAdvAutonomous on;\n";
211
				$radvdconf .= "\t\tAdvRouterAddr on;\n";
212
				break;
213
			case "unmanaged":
214
				$radvdconf .= "\t\tAdvOnLink on;\n";
215
				$radvdconf .= "\t\tAdvAutonomous on;\n";
216
				$radvdconf .= "\t\tAdvRouterAddr on;\n";
217
				break;
218
		}
219

    
220
		if (is_numericint($dhcpv6ifconf['ravalidlifetime'])) {
221
		  $radvdconf .= "\t\tAdvValidLifetime {$dhcpv6ifconf['ravalidlifetime']};\n";
222
		} else {
223
		  $radvdconf .= "\t\tAdvValidLifetime 86400;\n";
224
		}
225

    
226
		if (is_numericint($dhcpv6ifconf['rapreferredlifetime'])) {
227
		  $radvdconf .= "\t\tAdvPreferredLifetime {$dhcpv6ifconf['rapreferredlifetime']};\n";
228
		} else {
229
		  $radvdconf .= "\t\tAdvPreferredLifetime 14400;\n";
230
		}
231

    
232
		$radvdconf .= "\t};\n";
233

    
234
		if (is_array($dhcpv6ifconf['subnets']['item'])) {
235
			foreach ($dhcpv6ifconf['subnets']['item'] as $subnet) {
236
				if (is_subnetv6($subnet)) {
237
					$radvdconf .= "\tprefix {$subnet} {\n";
238
					$radvdconf .= "\t\tDeprecatePrefix on;\n";
239
					switch ($dhcpv6ifconf['ramode']) {
240
						case "managed":
241
							$radvdconf .= "\t\tAdvOnLink on;\n";
242
							$radvdconf .= "\t\tAdvAutonomous off;\n";
243
							$radvdconf .= "\t\tAdvRouterAddr on;\n";
244
							break;
245
						case "router":
246
							$radvdconf .= "\t\tAdvOnLink off;\n";
247
							$radvdconf .= "\t\tAdvAutonomous off;\n";
248
							$radvdconf .= "\t\tAdvRouterAddr on;\n";
249
							break;
250
						case "assist":
251
							$radvdconf .= "\t\tAdvOnLink on;\n";
252
							$radvdconf .= "\t\tAdvAutonomous on;\n";
253
							$radvdconf .= "\t\tAdvRouterAddr on;\n";
254
							break;
255
						case "unmanaged":
256
							$radvdconf .= "\t\tAdvOnLink on;\n";
257
							$radvdconf .= "\t\tAdvAutonomous on;\n";
258
							$radvdconf .= "\t\tAdvRouterAddr on;\n";
259
							break;
260
					}
261
					$radvdconf .= "\t};\n";
262
				}
263
			}
264
		}
265
		$radvdconf .= "\troute ::/0 {\n";
266
		$radvdconf .= "\t\tRemoveRoute on;\n";
267
		$radvdconf .= "\t};\n";
268

    
269
		/* add DNS servers */
270
		$dnslist = array();
271
		if (isset($dhcpv6ifconf['rasamednsasdhcp6']) && is_array($dhcpv6ifconf['dnsserver']) && !empty($dhcpv6ifconf['dnsserver'])) {
272
			foreach ($dhcpv6ifconf['dnsserver'] as $server) {
273
				if (is_ipaddrv6($server)) {
274
					$dnslist[] = $server;
275
				}
276
			}
277
		} elseif (!isset($dhcpv6ifconf['rasamednsasdhcp6']) && isset($dhcpv6ifconf['radnsserver']) && is_array($dhcpv6ifconf['radnsserver'])) {
278
			foreach ($dhcpv6ifconf['radnsserver'] as $server) {
279
				if (is_ipaddrv6($server)) {
280
					$dnslist[] = $server;
281
				}
282
			}
283
		} elseif (isset($config['dnsmasq']['enable']) || isset($config['unbound']['enable'])) {
284
			$dnslist[] = get_interface_ipv6($realif);
285
		} elseif (is_array($config['system']['dnsserver']) && !empty($config['system']['dnsserver'])) {
286
			foreach ($config['system']['dnsserver'] as $server) {
287
				if (is_ipaddrv6($server)) {
288
					$dnslist[] = $server;
289
				}
290
			}
291
		}
292
		if (count($dnslist) > 0) {
293
			$dnsstring = implode(" ", $dnslist);
294
			if ($dnsstring <> "") {
295
				$radvdconf .= "\tRDNSS {$dnsstring} { };\n";
296
			}
297
		}
298
		if (!empty($dhcpv6ifconf['domain'])) {
299
			$radvdconf .= "\tDNSSL {$dhcpv6ifconf['domain']} { };\n";
300
		} elseif (!empty($config['system']['domain'])) {
301
			$radvdconf .= "\tDNSSL {$config['system']['domain']} { };\n";
302
		}
303
		$radvdconf .= "};\n";
304
	}
305

    
306
	/* handle DHCP-PD prefixes and 6RD dynamic interfaces */
307
	foreach ($Iflist as $if => $ifdescr) {
308
		if (!isset($config['interfaces'][$if]['track6-interface']) ||
309
		    !isset($config['interfaces'][$if]['ipaddrv6']) ||
310
		    $config['interfaces'][$if]['ipaddrv6'] != 'track6') {
311
			continue;
312
		}
313
		if (!isset($config['interfaces'][$if]['enable'])) {
314
			continue;
315
		}
316
		if ($config['dhcpdv6'][$if]['ramode'] == "disabled") {
317
			continue;
318
		}
319
		/* Do not put in the config an interface which is down */
320
		if (isset($blacklist[$if])) {
321
			continue;
322
		}
323
		$trackif = $config['interfaces'][$if]['track6-interface'];
324
		if (empty($config['interfaces'][$trackif])) {
325
			continue;
326
		}
327

    
328
		$realif = get_real_interface($if, "inet6");
329

    
330
		/* prevent duplicate entries, manual overrides */
331
		if (isset($radvdifs[$realif])) {
332
			continue;
333
		}
334

    
335
		$ifcfgipv6 = get_interface_ipv6($if);
336
		if (!is_ipaddrv6($ifcfgipv6)) {
337
			$subnetv6 = "::";
338
			$ifcfgsnv6 = "64";
339
		} else {
340
			$ifcfgsnv6 = get_interface_subnetv6($if);
341
			$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
342
		}
343
		$radvdifs[$realif] = $realif;
344

    
345
		$autotype = $config['interfaces'][$trackif]['ipaddrv6'];
346

    
347
		if ($g['debug']) {
348
			log_error("configuring RA on {$if} for type {$autotype} radvd subnet {$subnetv6}/{$ifcfgsnv6}");
349
		}
350

    
351
		$radvdconf .= "# Generated config for {$autotype} delegation from {$trackif} on {$if}\n";
352
		$radvdconf .= "interface {$realif} {\n";
353
		$radvdconf .= "\tAdvSendAdvert on;\n";
354
		if (is_numericint($dhcpv6ifconf['raminrtradvinterval'])) {
355
			$radvdconf .= "\tMinRtrAdvInterval {$dhcpv6ifconf['raminrtradvinterval']};\n";
356
		} else {
357
			$radvdconf .= "\tMinRtrAdvInterval 5;\n";
358
                }
359
		if (is_numericint($dhcpv6ifconf['ramaxrtradvinterval'])) {
360
			$radvdconf .= "\tMaxRtrAdvInterval {$dhcpv6ifconf['ramaxrtradvinterval']};\n";
361
		} else {
362
			$radvdconf .= "\tMaxRtrAdvInterval 10;\n";
363
		}
364
		$mtu = get_interface_mtu($realif);
365
		if (is_numeric($mtu)) {
366
			$radvdconf .= "\tAdvLinkMTU {$mtu};\n";
367
		} else {
368
			$radvdconf .= "\tAdvLinkMTU 1280;\n";
369
		}
370
		$radvdconf .= "\tAdvOtherConfigFlag on;\n";
371
		$radvdconf .= "\tprefix {$subnetv6}/{$ifcfgsnv6} {\n";
372
		$radvdconf .= "\t\tAdvOnLink on;\n";
373
		$radvdconf .= "\t\tAdvAutonomous on;\n";
374
		$radvdconf .= "\t\tAdvRouterAddr on;\n";
375
		$radvdconf .= "\t};\n";
376

    
377
		/* add DNS servers */
378
		$dnslist = array();
379
		if (isset($config['dnsmasq']['enable']) || isset($config['unbound']['enable'])) {
380
			$dnslist[] = $ifcfgipv6;
381
		} elseif (is_array($config['system']['dnsserver']) && !empty($config['system']['dnsserver'])) {
382
			foreach ($config['system']['dnsserver'] as $server) {
383
				if (is_ipaddrv6($server)) {
384
					$dnslist[] = $server;
385
				}
386
			}
387
		}
388
		if (count($dnslist) > 0) {
389
			$dnsstring = implode(" ", $dnslist);
390
			if (!empty($dnsstring)) {
391
				$radvdconf .= "\tRDNSS {$dnsstring} { };\n";
392
			}
393
		}
394
		if (!empty($config['system']['domain'])) {
395
			$radvdconf .= "\tDNSSL {$config['system']['domain']} { };\n";
396
		}
397
		$radvdconf .= "};\n";
398
	}
399

    
400
	/* write radvd.conf */
401
	if (!@file_put_contents("{$g['varetc_path']}/radvd.conf", $radvdconf)) {
402
		log_error(gettext("Error: cannot open radvd.conf in services_radvd_configure()."));
403
		if (platform_booting()) {
404
			printf("Error: cannot open radvd.conf in services_radvd_configure().\n");
405
		}
406
	}
407
	unset($radvdconf);
408

    
409
	if (count($radvdifs) > 0) {
410
		if (isvalidpid("{$g['varrun_path']}/radvd.pid")) {
411
			sigkillbypid("{$g['varrun_path']}/radvd.pid", "HUP");
412
		} else {
413
			mwexec("/usr/local/sbin/radvd -p {$g['varrun_path']}/radvd.pid -C {$g['varetc_path']}/radvd.conf -m syslog");
414
		}
415
	} else {
416
		/* we need to shut down the radvd cleanly, it will send out the prefix
417
		 * information with a lifetime of 0 to notify clients of a (possible) new prefix */
418
		if (isvalidpid("{$g['varrun_path']}/radvd.pid")) {
419
			log_error(gettext("Shutting down Router Advertisment daemon cleanly"));
420
			killbypid("{$g['varrun_path']}/radvd.pid");
421
			@unlink("{$g['varrun_path']}/radvd.pid");
422
		}
423
	}
424
	return 0;
425
}
426

    
427
function services_dhcpd_configure($family = "all", $blacklist = array()) {
428
	global $config, $g;
429

    
430
	/* configure DHCPD chroot once */
431
	$fd = fopen("{$g['tmp_path']}/dhcpd.sh", "w");
432
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}\n");
433
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/dev\n");
434
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/etc\n");
435
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/usr/local/sbin\n");
436
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db\n");
437
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run\n");
438
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/usr\n");
439
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/lib\n");
440
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/run\n");
441
	fwrite($fd, "/usr/sbin/chown -R dhcpd:_dhcp {$g['dhcpd_chroot_path']}/*\n");
442
	fwrite($fd, "/bin/cp -n /lib/libc.so.* {$g['dhcpd_chroot_path']}/lib/\n");
443
	fwrite($fd, "/bin/cp -n /usr/local/sbin/dhcpd {$g['dhcpd_chroot_path']}/usr/local/sbin/\n");
444
	fwrite($fd, "/bin/chmod a+rx {$g['dhcpd_chroot_path']}/usr/local/sbin/dhcpd\n");
445

    
446
	$status = `/sbin/mount | /usr/bin/grep -v grep | /usr/bin/grep "{$g['dhcpd_chroot_path']}/dev"`;
447
	if (!trim($status)) {
448
		fwrite($fd, "/sbin/mount -t devfs devfs {$g['dhcpd_chroot_path']}/dev\n");
449
	}
450
	fclose($fd);
451
	mwexec("/bin/sh {$g['tmp_path']}/dhcpd.sh");
452

    
453
	if ($family == "all" || $family == "inet") {
454
		services_dhcpdv4_configure();
455
	}
456
	if ($family == "all" || $family == "inet6") {
457
		services_dhcpdv6_configure($blacklist);
458
		services_radvd_configure($blacklist);
459
	}
460
}
461

    
462
function services_dhcpdv4_configure() {
463
	global $config, $g;
464
	$need_ddns_updates = false;
465
	$ddns_zones = array();
466

    
467
	if ($g['services_dhcp_server_enable'] == false) {
468
		return;
469
	}
470

    
471
	if (isset($config['system']['developerspew'])) {
472
		$mt = microtime();
473
		echo "services_dhcpdv4_configure($if) being called $mt\n";
474
	}
475

    
476
	/* kill any running dhcpd */
477
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid")) {
478
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid");
479
	}
480

    
481
	/* DHCP enabled on any interfaces? */
482
	if (!is_dhcp_server_enabled()) {
483
		return 0;
484
	}
485

    
486
	/* if OLSRD is enabled, allow WAN to house DHCP. */
487
	if (!function_exists('is_package_installed')) {
488
		require_once('pkg-utils.inc');
489
	}
490
	if (is_package_installed('olsrd') && isset($config['installedpackages']['olsrd'])) {
491
		foreach ($config['installedpackages']['olsrd']['config'] as $olsrd) {
492
			if (isset($olsrd['enable']) && $olsrd['enable'] == "on") {
493
				$is_olsr_enabled = true;
494
				break;
495
			}
496
		}
497
	}
498

    
499
	if (platform_booting()) {
500
		/* restore the leases, if we have them */
501
		if (file_exists("{$g['cf_conf_path']}/dhcpleases.tgz")) {
502
			$dhcprestore = "";
503
			$dhcpreturn = "";
504
			exec("cd /;LANG=C /usr/bin/tar -xzf {$g['cf_conf_path']}/dhcpleases.tgz 2>&1", $dhcprestore, $dhcpreturn);
505
			$dhcprestore = implode(" ", $dhcprestore);
506
			if ($dhcpreturn <> 0) {
507
				log_error(sprintf(gettext('DHCP leases restore failed exited with %1$s, the error is: %2$s%3$s'), $dhcpreturn, $dhcprestore, "\n"));
508
			}
509
		}
510
		/* If this backup is still there on a full install, but we aren't going to use ram disks, remove the archive since this is a transition. */
511
		if (($g['platform'] == $g['product_name']) && !isset($config['system']['use_mfs_tmpvar'])) {
512
			unlink_if_exists("{$g['cf_conf_path']}/dhcpleases.tgz");
513
		}
514
	}
515

    
516
	$syscfg = $config['system'];
517
	if (!is_array($config['dhcpd'])) {
518
		$config['dhcpd'] = array();
519
	}
520
	$dhcpdcfg = $config['dhcpd'];
521
	$Iflist = get_configured_interface_list();
522

    
523
	/* Only consider DNS servers with IPv4 addresses for the IPv4 DHCP server. */
524
	$dns_arrv4 = array();
525
	if (is_array($syscfg['dnsserver'])) {
526
		foreach ($syscfg['dnsserver'] as $dnsserver) {
527
			if (is_ipaddrv4($dnsserver)) {
528
				$dns_arrv4[] = $dnsserver;
529
			}
530
		}
531
	}
532

    
533
	if (platform_booting()) {
534
		echo gettext("Starting DHCP service...");
535
	} else {
536
		sleep(1);
537
	}
538

    
539
	$custoptions = "";
540
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
541
		if (is_array($dhcpifconf['numberoptions']) && is_array($dhcpifconf['numberoptions']['item'])) {
542
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
543
				if (!empty($item['type'])) {
544
					$itemtype = $item['type'];
545
				} else {
546
					$itemtype = "text";
547
				}
548
				$custoptions .= "option custom-{$dhcpif}-{$itemidx} code {$item['number']} = {$itemtype};\n";
549
			}
550
		}
551
	}
552

    
553
	$dhcpdconf = <<<EOD
554

    
555
option domain-name "{$syscfg['domain']}";
556
option ldap-server code 95 = text;
557
option domain-search-list code 119 = text;
558
option arch code 93 = unsigned integer 16; # RFC4578
559
{$custoptions}
560
default-lease-time 7200;
561
max-lease-time 86400;
562
log-facility local7;
563
one-lease-per-client true;
564
deny duplicates;
565
ping-check true;
566
update-conflict-detection false;
567
dhcp-cache-threshold 0;
568

    
569
EOD;
570

    
571
	if (!isset($dhcpifconf['disableauthoritative'])) {
572
		$dhcpdconf .= "authoritative;\n";
573
	}
574

    
575
	if (isset($dhcpifconf['alwaysbroadcast'])) {
576
		$dhcpdconf .= "always-broadcast on\n";
577
	}
578

    
579
	$dhcpdifs = array();
580
	$enable_add_routers = false;
581
	$gateways_arr = return_gateways_array();
582
	/* only add a routers line if the system has any IPv4 gateway at all */
583
	/* a static route has a gateway, manually overriding this field always works */
584
	foreach ($gateways_arr as $gwitem) {
585
		if ($gwitem['ipprotocol'] == "inet") {
586
			$enable_add_routers = true;
587
			break;
588
		}
589
	}
590

    
591
	/*    loop through and determine if we need to setup
592
	 *    failover peer "bleh" entries
593
	 */
594
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
595

    
596
		if (!isset($config['interfaces'][$dhcpif]['enable'])) {
597
			continue;
598
		}
599

    
600
		interfaces_staticarp_configure($dhcpif);
601

    
602
		if (!isset($dhcpifconf['enable'])) {
603
			continue;
604
		}
605

    
606
		if ($dhcpifconf['failover_peerip'] <> "") {
607
			$intip = get_interface_ip($dhcpif);
608
			/*
609
			 *    yep, failover peer is defined.
610
			 *    does it match up to a defined vip?
611
			 */
612
			$skew = 110;
613
			if (is_array($config['virtualip']['vip'])) {
614
				foreach ($config['virtualip']['vip'] as $vipent) {
615
					if ($vipent['interface'] == $dhcpif) {
616
						$carp_nw = gen_subnet($vipent['subnet'], $vipent['subnet_bits']);
617
						if (ip_in_subnet($dhcpifconf['failover_peerip'], "{$carp_nw}/{$vipent['subnet_bits']}")) {
618
							/* this is the interface! */
619
							if (is_numeric($vipent['advskew']) && (intval($vipent['advskew']) < 20)) {
620
								$skew = 0;
621
								break;
622
							}
623
						}
624
					}
625
				}
626
			} else {
627
				log_error(gettext("Warning!  DHCP Failover setup and no CARP virtual IPs defined!"));
628
			}
629
			if ($skew > 10) {
630
				$type = "secondary";
631
				$my_port = "520";
632
				$peer_port = "519";
633
			} else {
634
				$my_port = "519";
635
				$peer_port = "520";
636
				$type = "primary";
637
				$dhcpdconf_pri = "split 128;\n";
638
				$dhcpdconf_pri .= "  mclt 600;\n";
639
			}
640

    
641
			if (is_ipaddrv4($intip)) {
642
				$dhcpdconf .= <<<EOPP
643
failover peer "dhcp_{$dhcpif}" {
644
  {$type};
645
  address {$intip};
646
  port {$my_port};
647
  peer address {$dhcpifconf['failover_peerip']};
648
  peer port {$peer_port};
649
  max-response-delay 10;
650
  max-unacked-updates 10;
651
  {$dhcpdconf_pri}
652
  load balance max seconds 3;
653
}
654
\n
655
EOPP;
656
			}
657
		}
658
	}
659

    
660
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
661

    
662
		$newzone = array();
663
		$ifcfg = $config['interfaces'][$dhcpif];
664

    
665
		if (!isset($dhcpifconf['enable']) || !isset($Iflist[$dhcpif])) {
666
			continue;
667
		}
668
		$ifcfgip = get_interface_ip($dhcpif);
669
		$ifcfgsn = get_interface_subnet($dhcpif);
670
		$subnet = gen_subnet($ifcfgip, $ifcfgsn);
671
		$subnetmask = gen_subnet_mask($ifcfgsn);
672

    
673
		if (!is_ipaddr($subnet)) {
674
			continue;
675
		}
676

    
677
		if ($is_olsr_enabled == true) {
678
			if ($dhcpifconf['netmask']) {
679
				$subnetmask = gen_subnet_mask($dhcpifconf['netmask']);
680
			}
681
		}
682

    
683
		$all_pools = array();
684
		$all_pools[] = $dhcpifconf;
685
		if (is_array($dhcpifconf['pool'])) {
686
			$all_pools = array_merge($all_pools, $dhcpifconf['pool']);
687
		}
688

    
689
		$dnscfg = "";
690

    
691
		if ($dhcpifconf['domain']) {
692
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
693
		}
694

    
695
		if ($dhcpifconf['domainsearchlist'] <> "") {
696
			$dnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpifconf['domainsearchlist'])) . "\";\n";
697
		}
698

    
699
		if (isset($dhcpifconf['ddnsupdate'])) {
700
			$need_ddns_updates = true;
701
			$newzone = array();
702
			if ($dhcpifconf['ddnsdomain'] <> "") {
703
				$newzone['domain-name'] = $dhcpifconf['ddnsdomain'];
704
				$dnscfg .= "	ddns-domainname \"{$dhcpifconf['ddnsdomain']}\";\n";
705
			} else {
706
				$newzone['domain-name'] = $config['system']['domain'];
707
			}
708

    
709
			$revsubnet = array_reverse(explode('.',$subnet));
710

    
711
			/* Take care of full classes first */
712
			switch ($ifcfgsn) {
713
				case 8:
714
					$start_octet = 3;
715
					break;
716
				case 16:
717
					$start_octet = 2;
718
					break;
719
				case 24:
720
					$start_octet = 1;
721
					break;
722
				default:
723
					$start_octet = 0;
724
					/* Add subnet bitmask to first octet */
725
					$revsubnet[0] .= '-' . $ifcfgsn;
726
					break;
727

    
728
			}
729

    
730
			$ptr_domain = '';
731
			for ($octet = 0; $octet <= 3; $octet++) {
732
				if ($octet < $start_octet) {
733
					continue;
734
				}
735
				$ptr_domain .= ((empty($ptr_domain) && $ptr_domain !== "0") ? '' : '.');
736
				$ptr_domain .= $revsubnet[$octet];
737
			}
738
			$ptr_domain .= ".in-addr.arpa";
739
			$newzone['ptr-domain'] = $ptr_domain;
740
			unset($ptr_domain, $revsubnet, $start_octet);
741
		}
742

    
743
		if (is_array($dhcpifconf['dnsserver']) && ($dhcpifconf['dnsserver'][0])) {
744
			$dnscfg .= "	option domain-name-servers " . join(",", $dhcpifconf['dnsserver']) . ";";
745
			if ($newzone['domain-name']) {
746
				$newzone['dns-servers'] = $dhcpifconf['dnsserver'];
747
			}
748
		} else if (isset($config['dnsmasq']['enable'])) {
749
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
750
			if ($newzone['domain-name'] && is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
751
				$newzone['dns-servers'] = $syscfg['dnsserver'];
752
			}
753
		} else if (isset($config['unbound']['enable'])) {
754
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
755
		} else if (!empty($dns_arrv4)) {
756
			$dnscfg .= "	option domain-name-servers " . join(",", $dns_arrv4) . ";";
757
			if ($newzone['domain-name']) {
758
				$newzone['dns-servers'] = $dns_arrv4;
759
			}
760
		}
761

    
762
		/* Create classes - These all contain comma separated lists. Join them into one
763
		   big comma separated string then split them all up. */
764
		$all_mac_strings = array();
765
		if (is_array($dhcpifconf['pool'])) {
766
			foreach ($all_pools as $poolconf) {
767
				$all_mac_strings[] = $poolconf['mac_allow'];
768
				$all_mac_strings[] = $poolconf['mac_deny'];
769
			}
770
		}
771
		$all_mac_strings[] = $dhcpifconf['mac_allow'];
772
		$all_mac_strings[] = $dhcpifconf['mac_deny'];
773
		if (!empty($all_mac_strings)) {
774
			$all_mac_list = array_unique(explode(',', implode(',', $all_mac_strings)));
775
			foreach ($all_mac_list as $mac) {
776
				if (empty($mac)) {
777
					continue;
778
				}
779
				$dhcpdconf .= 'class "' . str_replace(':', '', $mac) . '" {' . "\n";
780
				// Skip the first octet of the MAC address - for media type, typically Ethernet ("01") and match the rest.
781
				$dhcpdconf .= '	match if substring (hardware, 1, ' . (substr_count($mac, ':') + 1) . ') = ' . $mac . ';' . "\n";
782
				$dhcpdconf .= '}' . "\n";
783
			}
784
		}
785

    
786
		$dhcpdconf .= "subnet {$subnet} netmask {$subnetmask} {\n";
787

    
788
		// Setup pool options
789
		foreach ($all_pools as $poolconf) {
790
			if (!(ip_in_subnet($poolconf['range']['from'], "{$subnet}/{$ifcfgsn}") && ip_in_subnet($poolconf['range']['to'], "{$subnet}/{$ifcfgsn}"))) {
791
				// If the user has changed the subnet from the interfaces page and applied,
792
				// but has not updated the DHCP range, then the range to/from of the pool can be outside the subnet.
793
				// This can also happen when implementing the batch of changes when the setup wizard reloads the new settings.
794
				$error_msg = sprintf(gettext("Invalid DHCP pool %s - %s for %s subnet %s/%s detected. Please correct the settings in Services, DHCP Server"), $poolconf['range']['from'], $poolconf['range']['to'], convert_real_interface_to_friendly_descr($dhcpif), $subnet, $ifcfgsn);
795
				$do_file_notice = true;
796
				$conf_ipv4_address = $ifcfg['ipaddr'];
797
				$conf_ipv4_subnetmask = $ifcfg['subnet'];
798
				if (is_ipaddrv4($conf_ipv4_address) && is_subnet("{$conf_ipv4_address}/{$conf_ipv4_subnetmask}")) {
799
					$conf_subnet_base = gen_subnet($conf_ipv4_address, $conf_ipv4_subnetmask);
800
					if (ip_in_subnet($poolconf['range']['from'], "{$conf_subnet_base}/{$conf_ipv4_subnetmask}") &&
801
					    ip_in_subnet($poolconf['range']['to'], "{$conf_subnet_base}/{$conf_ipv4_subnetmask}")) {
802
						// Even though the running interface subnet does not match the pool range,
803
						// the interface subnet in the config file contains the pool range.
804
						// We are somewhere part-way through a settings reload, e.g. after running the setup wizard.
805
						// services_dhcpdv4_configure will be called again later when the new interface settings from
806
						// the config are applied and at that time everything will match up.
807
						// Ignore this pool on this interface for now and just log the error to the system log.
808
						log_error($error_msg);
809
						$do_file_notice = false;
810
					}
811
				}
812
				if ($do_file_notice) {
813
					file_notice("DHCP", $error_msg);
814
				}
815
				continue;
816
			}
817
			$dhcpdconf .= "	pool {\n";
818
			/* is failover dns setup? */
819
			if (is_array($poolconf['dnsserver']) && $poolconf['dnsserver'][0] <> "") {
820
				$dhcpdconf .= "		option domain-name-servers {$poolconf['dnsserver'][0]}";
821
				if ($poolconf['dnsserver'][1] <> "") {
822
					$dhcpdconf .= ",{$poolconf['dnsserver'][1]}";
823
				}
824
				if ($poolconf['dnsserver'][2] <> "") {
825
					$dhcpdconf .= ",{$poolconf['dnsserver'][2]}";
826
				}
827
				if ($poolconf['dnsserver'][3] <> "") {
828
					$dhcpdconf .= ",{$poolconf['dnsserver'][3]}";
829
				}
830
				$dhcpdconf .= ";\n";
831
			}
832

    
833
			/* allow/deny MACs */
834
			$mac_allow_list = array_unique(explode(',', $poolconf['mac_allow']));
835
			foreach ($mac_allow_list as $mac) {
836
				if (empty($mac)) {
837
					continue;
838
				}
839
				$dhcpdconf .= "		allow members of \"" . str_replace(':', '', $mac) . "\";\n";
840
			}
841
			$deny_action = "deny";
842
			if (isset($poolconf['nonak']) && empty($poolconf['failover_peerip'])) {
843
				$deny_action = "ignore";
844
			}
845
			$mac_deny_list = array_unique(explode(',', $poolconf['mac_deny']));
846
			foreach ($mac_deny_list as $mac) {
847
				if (empty($mac)) {
848
					continue;
849
				}
850
				$dhcpdconf .= "		$deny_action members of \"" . str_replace(':', '', $mac) . "\";\n";
851
			}
852

    
853
			if ($poolconf['failover_peerip'] <> "") {
854
				$dhcpdconf .= "		$deny_action dynamic bootp clients;\n";
855
			}
856

    
857
			if (isset($poolconf['denyunknown'])) {
858
				$dhcpdconf .= "		$deny_action unknown-clients;\n";
859
			}
860

    
861
			if ($poolconf['gateway'] && $poolconf['gateway'] != "none" && ($poolconf['gateway'] != $dhcpifconf['gateway'])) {
862
				$dhcpdconf .= "		option routers {$poolconf['gateway']};\n";
863
			}
864

    
865
			if ($dhcpifconf['failover_peerip'] <> "") {
866
				$dhcpdconf .= "		failover peer \"dhcp_{$dhcpif}\";\n";
867
			}
868

    
869
			$pdnscfg = "";
870

    
871
			if ($poolconf['domain'] && ($poolconf['domain'] != $dhcpifconf['domain'])) {
872
				$pdnscfg .= "		option domain-name \"{$poolconf['domain']}\";\n";
873
			}
874

    
875
			if (!empty($poolconf['domainsearchlist']) && ($poolconf['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
876
				$pdnscfg .= "		option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $poolconf['domainsearchlist'])) . "\";\n";
877
			}
878

    
879
			if (isset($poolconf['ddnsupdate'])) {
880
				if (($poolconf['ddnsdomain'] <> "") && ($poolconf['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
881
					$pdnscfg .= "		ddns-domainname \"{$poolconf['ddnsdomain']}\";\n";
882
				}
883
				$pdnscfg .= "		ddns-update-style interim;\n";
884
			}
885

    
886
			if (is_array($poolconf['dnsserver']) && ($poolconf['dnsserver'][0]) && ($poolconf['dnsserver'][0] != $dhcpifconf['dnsserver'][0])) {
887
				$pdnscfg .= "		option domain-name-servers " . join(",", $poolconf['dnsserver']) . ";\n";
888
			}
889
			$dhcpdconf .= "{$pdnscfg}";
890

    
891
			// default-lease-time
892
			if ($poolconf['defaultleasetime'] && ($poolconf['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
893
				$dhcpdconf .= "		default-lease-time {$poolconf['defaultleasetime']};\n";
894
			}
895

    
896
			// max-lease-time
897
			if ($poolconf['maxleasetime'] && ($poolconf['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
898
				$dhcpdconf .= "		max-lease-time {$poolconf['maxleasetime']};\n";
899
			}
900

    
901
			// ignore bootp
902
			if (isset($poolconf['ignorebootp'])) {
903
				$dhcpdconf .= "		ignore bootp;\n";
904
			}
905

    
906
			// netbios-name*
907
			if (is_array($poolconf['winsserver']) && $poolconf['winsserver'][0] && ($poolconf['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
908
				$dhcpdconf .= "		option netbios-name-servers " . join(",", $poolconf['winsserver']) . ";\n";
909
				$dhcpdconf .= "		option netbios-node-type 8;\n";
910
			}
911

    
912
			// ntp-servers
913
			if (is_array($poolconf['ntpserver']) && $poolconf['ntpserver'][0] && ($poolconf['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
914
				$dhcpdconf .= "		option ntp-servers " . join(",", $poolconf['ntpserver']) . ";\n";
915
			}
916

    
917
			// tftp-server-name
918
			if (!empty($poolconf['tftp']) && ($poolconf['tftp'] != $dhcpifconf['tftp'])) {
919
				$dhcpdconf .= "		option tftp-server-name \"{$poolconf['tftp']}\";\n";
920
			}
921

    
922
			// ldap-server
923
			if (!empty($poolconf['ldap']) && ($poolconf['ldap'] != $dhcpifconf['ldap'])) {
924
				$dhcpdconf .= "		option ldap-server \"{$poolconf['ldap']}\";\n";
925
			}
926

    
927
			// net boot information
928
			if (isset($poolconf['netboot'])) {
929
				if (!empty($poolconf['nextserver']) && ($poolconf['nextserver'] != $dhcpifconf['nextserver'])) {
930
					$dhcpdconf .= "		next-server {$poolconf['nextserver']};\n";
931
				}
932
				if (!empty($poolconf['filename']) && ($poolconf['filename'] != $dhcpifconf['filename'])) {
933
					$dhcpdconf .= "		filename \"{$poolconf['filename']}\";\n";
934
				}
935
				if (!empty($poolconf['rootpath']) && ($poolconf['rootpath'] != $dhcpifconf['rootpath'])) {
936
					$dhcpdconf .= "		option root-path \"{$poolconf['rootpath']}\";\n";
937
				}
938
			}
939
			$dhcpdconf .= "		range {$poolconf['range']['from']} {$poolconf['range']['to']};\n";
940
			$dhcpdconf .= "	}\n\n";
941
		}
942
// End of settings inside pools
943

    
944
		if ($dhcpifconf['gateway'] && $dhcpifconf['gateway'] != "none") {
945
			$routers = $dhcpifconf['gateway'];
946
			$add_routers = true;
947
		} elseif ($dhcpifconf['gateway'] == "none") {
948
			$add_routers = false;
949
		} else {
950
			$add_routers = $enable_add_routers;
951
			$routers = $ifcfgip;
952
		}
953
		if ($add_routers) {
954
			$dhcpdconf .= "	option routers {$routers};\n";
955
		}
956

    
957
		$dhcpdconf .= <<<EOD
958
$dnscfg
959

    
960
EOD;
961
		// default-lease-time
962
		if ($dhcpifconf['defaultleasetime']) {
963
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
964
		}
965

    
966
		// max-lease-time
967
		if ($dhcpifconf['maxleasetime']) {
968
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
969
		}
970

    
971
		// netbios-name*
972
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
973
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
974
			$dhcpdconf .= "	option netbios-node-type 8;\n";
975
		}
976

    
977
		// ntp-servers
978
		if (is_array($dhcpifconf['ntpserver']) && $dhcpifconf['ntpserver'][0]) {
979
			$dhcpdconf .= "	option ntp-servers " . join(",", $dhcpifconf['ntpserver']) . ";\n";
980
		}
981

    
982
		// tftp-server-name
983
		if ($dhcpifconf['tftp'] <> "") {
984
			$dhcpdconf .= "	option tftp-server-name \"{$dhcpifconf['tftp']}\";\n";
985
		}
986

    
987
		// Handle option, number rowhelper values
988
		$dhcpdconf .= "\n";
989
		if ($dhcpifconf['numberoptions']['item']) {
990
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
991
				$item_value = base64_decode($item['value']);
992
				if (empty($item['type']) || $item['type'] == "text") {
993
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} \"{$item_value}\";\n";
994
				} else {
995
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} {$item_value};\n";
996
				}
997
			}
998
		}
999

    
1000
		// ldap-server
1001
		if ($dhcpifconf['ldap'] <> "") {
1002
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
1003
		}
1004

    
1005
		// net boot information
1006
		if (isset($dhcpifconf['netboot'])) {
1007
			if ($dhcpifconf['nextserver'] <> "") {
1008
				$dhcpdconf .= "	next-server {$dhcpifconf['nextserver']};\n";
1009
			}
1010
			if (!empty($dhcpifconf['filename']) && !empty($dhcpifconf['filename32']) && !empty($dhcpifconf['filename64'])) {
1011
				$dhcpdconf .= "	if option arch = 00:06 {\n";
1012
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename32']}\";\n";
1013
				$dhcpdconf .= "	} else if option arch = 00:07 {\n";
1014
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1015
				$dhcpdconf .= "	} else if option arch = 00:09 {\n";
1016
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1017
				$dhcpdconf .= "	} else {\n";
1018
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename']}\";\n";
1019
				$dhcpdconf .= "	}\n\n";
1020
			} elseif (!empty($dhcpifconf['filename'])) {
1021
				$dhcpdconf .= "	filename \"{$dhcpifconf['filename']}\";\n";
1022
			}
1023
			if (!empty($dhcpifconf['rootpath'])) {
1024
				$dhcpdconf .= "	option root-path \"{$dhcpifconf['rootpath']}\";\n";
1025
			}
1026
		}
1027

    
1028
		$dhcpdconf .= <<<EOD
1029
}
1030

    
1031
EOD;
1032

    
1033
		/* add static mappings */
1034
		if (is_array($dhcpifconf['staticmap'])) {
1035

    
1036
			$i = 0;
1037
			foreach ($dhcpifconf['staticmap'] as $sm) {
1038
				$dhcpdconf .= "host s_{$dhcpif}_{$i} {\n";
1039

    
1040
				if ($sm['mac']) {
1041
					$dhcpdconf .= "        hardware ethernet {$sm['mac']};\n";
1042
				}
1043

    
1044
				if ($sm['cid']) {
1045
					$dhcpdconf .= "        option dhcp-client-identifier \"{$sm['cid']}\";\n";
1046
				}
1047

    
1048
				if ($sm['ipaddr']) {
1049
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
1050
				}
1051

    
1052
				if ($sm['hostname']) {
1053
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1054
					$dhhostname = str_replace(".", "_", $dhhostname);
1055
					$dhcpdconf .= "	option host-name \"{$dhhostname}\";\n";
1056
				}
1057
				if ($sm['filename']) {
1058
					$dhcpdconf .= "	filename \"{$sm['filename']}\";\n";
1059
				}
1060

    
1061
				if ($sm['rootpath']) {
1062
					$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1063
				}
1064

    
1065
				if ($sm['gateway'] && ($sm['gateway'] != $dhcpifconf['gateway'])) {
1066
					$dhcpdconf .= "	option routers {$sm['gateway']};\n";
1067
				}
1068

    
1069
				$smdnscfg = "";
1070

    
1071
				if ($sm['domain'] && ($sm['domain'] != $dhcpifconf['domain'])) {
1072
					$smdnscfg .= "	option domain-name \"{$sm['domain']}\";\n";
1073
				}
1074

    
1075
				if (!empty($sm['domainsearchlist']) && ($sm['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
1076
					$smdnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $sm['domainsearchlist'])) . "\";\n";
1077
				}
1078

    
1079
				if (isset($sm['ddnsupdate'])) {
1080
					if (($sm['ddnsdomain'] <> "") && ($sm['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
1081
						$pdnscfg .= "		ddns-domainname \"{$sm['ddnsdomain']}\";\n";
1082
					}
1083
					$pdnscfg .= "		ddns-update-style interim;\n";
1084
				}
1085

    
1086
				if (is_array($sm['dnsserver']) && ($sm['dnsserver'][0]) && ($sm['dnsserver'][0] != $dhcpifconf['dnsserver'][0])) {
1087
					$smdnscfg .= "	option domain-name-servers " . join(",", $sm['dnsserver']) . ";\n";
1088
				}
1089
				$dhcpdconf .= "{$smdnscfg}";
1090

    
1091
				// default-lease-time
1092
				if ($sm['defaultleasetime'] && ($sm['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
1093
					$dhcpdconf .= "	default-lease-time {$sm['defaultleasetime']};\n";
1094
				}
1095

    
1096
				// max-lease-time
1097
				if ($sm['maxleasetime'] && ($sm['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
1098
					$dhcpdconf .= "	max-lease-time {$sm['maxleasetime']};\n";
1099
				}
1100

    
1101
				// netbios-name*
1102
				if (is_array($sm['winsserver']) && $sm['winsserver'][0] && ($sm['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
1103
					$dhcpdconf .= "	option netbios-name-servers " . join(",", $sm['winsserver']) . ";\n";
1104
					$dhcpdconf .= "	option netbios-node-type 8;\n";
1105
				}
1106

    
1107
				// ntp-servers
1108
				if (is_array($sm['ntpserver']) && $sm['ntpserver'][0] && ($sm['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
1109
					$dhcpdconf .= "	option ntp-servers " . join(",", $sm['ntpserver']) . ";\n";
1110
				}
1111

    
1112
				// tftp-server-name
1113
				if (!empty($sm['tftp']) && ($sm['tftp'] != $dhcpifconf['tftp'])) {
1114
					$dhcpdconf .= "	option tftp-server-name \"{$sm['tftp']}\";\n";
1115
				}
1116

    
1117
				$dhcpdconf .= "}\n";
1118
				$i++;
1119
			}
1120
		}
1121

    
1122
		$dhcpdifs[] = get_real_interface($dhcpif);
1123
		if ($newzone['domain-name']) {
1124
			if ($need_ddns_updates) {
1125
				$newzone['dns-servers'] = array($dhcpifconf['ddnsdomainprimary']);
1126
				$newzone['ddnsdomainkeyname'] = $dhcpifconf['ddnsdomainkeyname'];
1127
				$newzone['ddnsdomainkey'] = $dhcpifconf['ddnsdomainkey'];
1128
				$dhcpdconf .= dhcpdkey($dhcpifconf);
1129
			}
1130
			$ddns_zones[] = $newzone;
1131
		}
1132
	}
1133

    
1134
	if ($need_ddns_updates) {
1135
		$dhcpdconf .= "ddns-update-style interim;\n";
1136
		$dhcpdconf .= "update-static-leases on;\n";
1137

    
1138
		$dhcpdconf .= dhcpdzones($ddns_zones);
1139
	}
1140

    
1141
	/* write dhcpd.conf */
1142
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpd.conf", $dhcpdconf)) {
1143
		printf(gettext("Error: cannot open dhcpd.conf in services_dhcpdv4_configure().%s"), "\n");
1144
		unset($dhcpdconf);
1145
		return 1;
1146
	}
1147
	unset($dhcpdconf);
1148

    
1149
	/* create an empty leases database */
1150
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
1151
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
1152
	}
1153

    
1154
	/* make sure there isn't a stale dhcpd.pid file, which can make dhcpd fail to start.   */
1155
	/* if we get here, dhcpd has been killed and is not started yet                        */
1156
	unlink_if_exists("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid");
1157

    
1158
	/* fire up dhcpd in a chroot */
1159
	if (count($dhcpdifs) > 0) {
1160
		mwexec("/usr/local/sbin/dhcpd -user dhcpd -group _dhcp -chroot {$g['dhcpd_chroot_path']} -cf /etc/dhcpd.conf -pf {$g['varrun_path']}/dhcpd.pid " .
1161
			join(" ", $dhcpdifs));
1162
	}
1163

    
1164
	if (platform_booting()) {
1165
		print "done.\n";
1166
	}
1167

    
1168
	return 0;
1169
}
1170

    
1171
function dhcpdkey($dhcpifconf) {
1172
	$dhcpdconf = "";
1173
	if ($dhcpifconf['ddnsdomainkeyname'] <> "" && $dhcpifconf['ddnsdomainkey'] <> "") {
1174
		$dhcpdconf .= "key {$dhcpifconf['ddnsdomainkeyname']} {\n";
1175
		$dhcpdconf .= "	algorithm hmac-md5;\n";
1176
		$dhcpdconf .= "	secret {$dhcpifconf['ddnsdomainkey']};\n";
1177
		$dhcpdconf .= "}\n";
1178
	}
1179

    
1180
	return $dhcpdconf;
1181
}
1182

    
1183
function dhcpdzones($ddns_zones) {
1184
	$dhcpdconf = "";
1185

    
1186
	if (is_array($ddns_zones)) {
1187
		$added_zones = array();
1188
		foreach ($ddns_zones as $zone) {
1189
			if (!is_array($zone) || empty($zone) || !is_array($zone['dns-servers'])) {
1190
				continue;
1191
			}
1192
			$primary = $zone['dns-servers'][0];
1193
			$secondary = empty($zone['dns-servers'][1]) ? "" : $zone['dns-servers'][1];
1194

    
1195
			// Make sure we aren't using any invalid or IPv6 DNS servers.
1196
			if (!is_ipaddrv4($primary)) {
1197
				if (is_ipaddrv4($secondary)) {
1198
					$primary = $secondary;
1199
					$secondary = "";
1200
				} else {
1201
					continue;
1202
				}
1203
			}
1204

    
1205
			// We don't need to add zones multiple times.
1206
			if ($zone['domain-name'] && !in_array($zone['domain-name'], $added_zones)) {
1207
				$dhcpdconf .= "zone {$zone['domain-name']}. {\n";
1208
				$dhcpdconf .= "	primary {$primary};\n";
1209
				if (is_ipaddrv4($secondary)) {
1210
					$dhcpdconf .= "	secondary {$secondary};\n";
1211
				}
1212
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1213
					$dhcpdconf .= "	key {$zone['ddnsdomainkeyname']};\n";
1214
				}
1215
				$dhcpdconf .= "}\n";
1216
				$added_zones[] = $zone['domain-name'];
1217
			}
1218
			if ($zone['ptr-domain'] && !in_array($zone['ptr-domain'], $added_zones)) {
1219
				$dhcpdconf .= "zone {$zone['ptr-domain']} {\n";
1220
				$dhcpdconf .= "	primary {$primary};\n";
1221
				if (is_ipaddrv4($secondary)) {
1222
					$dhcpdconf .= "	secondary {$secondary};\n";
1223
				}
1224
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1225
					$dhcpdconf .= "	key {$zone['ddnsdomainkeyname']};\n";
1226
				}
1227
				$dhcpdconf .= "}\n";
1228
				$added_zones[] = $zone['ptr-domain'];
1229
			}
1230
		}
1231
	}
1232

    
1233
	return $dhcpdconf;
1234
}
1235

    
1236
function services_dhcpdv6_configure($blacklist = array()) {
1237
	global $config, $g;
1238

    
1239
	if ($g['services_dhcp_server_enable'] == false) {
1240
		return;
1241
	}
1242

    
1243
	if (isset($config['system']['developerspew'])) {
1244
		$mt = microtime();
1245
		echo "services_dhcpd_configure($if) being called $mt\n";
1246
	}
1247

    
1248
	/* kill any running dhcpd */
1249
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid")) {
1250
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid");
1251
	}
1252
	if (isvalidpid("{$g['varrun_path']}/dhcpleases6.pid")) {
1253
		killbypid("{$g['varrun_path']}/dhcpleases6.pid");
1254
	}
1255

    
1256
	/* DHCP enabled on any interfaces? */
1257
	if (!is_dhcpv6_server_enabled()) {
1258
		return 0;
1259
	}
1260

    
1261
	if (platform_booting()) {
1262
		if ($g['platform'] != $g['product_name']) {
1263
			/* restore the leases, if we have them */
1264
			if (file_exists("{$g['cf_conf_path']}/dhcp6leases.tgz")) {
1265
				$dhcprestore = "";
1266
				$dhcpreturn = "";
1267
				exec("cd /;LANG=C /usr/bin/tar -xzf {$g['cf_conf_path']}/dhcp6leases.tgz 2>&1", $dhcprestore, $dhcpreturn);
1268
				$dhcprestore = implode(" ", $dhcprestore);
1269
				if ($dhcpreturn <> 0) {
1270
					log_error(sprintf(gettext('DHCP leases v6 restore failed exited with %1$s, the error is: %2$s'), $dhcpreturn, $dhcprestore));
1271
				}
1272
			}
1273
		}
1274
	}
1275

    
1276
	$syscfg = $config['system'];
1277
	if (!is_array($config['dhcpdv6'])) {
1278
		$config['dhcpdv6'] = array();
1279
	}
1280
	$dhcpdv6cfg = $config['dhcpdv6'];
1281
	$Iflist = get_configured_interface_list();
1282
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
1283

    
1284

    
1285
	if (platform_booting()) {
1286
		echo "Starting DHCPv6 service...";
1287
	} else {
1288
		sleep(1);
1289
	}
1290

    
1291
	$custoptionsv6 = "";
1292
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1293
		if (is_array($dhcpv6ifconf['numberoptions']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1294
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1295
				$custoptionsv6 .= "option custom-{$dhcpv6if}-{$itemv6idx} code {$itemv6['number']} = text;\n";
1296
			}
1297
		}
1298
	}
1299

    
1300
	if (isset($dhcpv6ifconf['netboot']) && !empty($dhcpv6ifconf['bootfile_url'])) {
1301
		$custoptionsv6 .= "option dhcp6.bootfile-url code 59 = string;\n";
1302
	}
1303

    
1304
	$dhcpdv6conf = <<<EOD
1305

    
1306
option domain-name "{$syscfg['domain']}";
1307
option ldap-server code 95 = text;
1308
option domain-search-list code 119 = text;
1309
{$custoptionsv6}
1310
default-lease-time 7200;
1311
max-lease-time 86400;
1312
log-facility local7;
1313
one-lease-per-client true;
1314
deny duplicates;
1315
ping-check true;
1316
update-conflict-detection false;
1317

    
1318
EOD;
1319

    
1320
	if (!isset($dhcpv6ifconf['disableauthoritative'])) {
1321
		$dhcpdv6conf .= "authoritative;\n";
1322
	}
1323

    
1324
	if (isset($dhcpv6ifconf['alwaysbroadcast'])) {
1325
		$dhcpdv6conf .= "always-broadcast on\n";
1326
	}
1327

    
1328
	$dhcpdv6ifs = array();
1329

    
1330
	$dhcpv6num = 0;
1331
	$nsupdate = false;
1332

    
1333
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1334

    
1335
		$ddns_zones = array();
1336

    
1337
		$ifcfgv6 = $config['interfaces'][$dhcpv6if];
1338

    
1339
		if (!isset($dhcpv6ifconf['enable']) || !isset($Iflist[$dhcpv6if]) || !isset($ifcfgv6['enable'])) {
1340
			continue;
1341
		}
1342
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1343
		if (!is_ipaddrv6($ifcfgipv6)) {
1344
			continue;
1345
		}
1346
		$ifcfgsnv6 = get_interface_subnetv6($dhcpv6if);
1347
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1348

    
1349
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
1350
			$trackifname = $config['interfaces'][$ifname]['track6-interface'];
1351
			$trackcfg = $config['interfaces'][$trackifname];
1352
			$pdlen = 64 - $trackcfg['dhcp6-ia-pd-len'];
1353
		}
1354

    
1355
		if ($is_olsr_enabled == true) {
1356
			if ($dhcpv6ifconf['netmask']) {
1357
				$subnetmask = gen_subnet_maskv6($dhcpv6ifconf['netmask']);
1358
			}
1359
		}
1360

    
1361
		$dnscfgv6 = "";
1362

    
1363
		if ($dhcpv6ifconf['domain']) {
1364
			$dnscfgv6 .= "	option domain-name \"{$dhcpv6ifconf['domain']}\";\n";
1365
		}
1366

    
1367
		if ($dhcpv6ifconf['domainsearchlist'] <> "") {
1368
			$dnscfgv6 .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpv6ifconf['domainsearchlist'])) . "\";\n";
1369
		}
1370

    
1371
		if (isset($dhcpv6ifconf['ddnsupdate'])) {
1372
			if ($dhcpv6ifconf['ddnsdomain'] <> "") {
1373
				$dnscfgv6 .= "	ddns-domainname \"{$dhcpv6ifconf['ddnsdomain']}\";\n";
1374
			}
1375
			if (empty($dhcpv6ifconf['ddnsclientupdates'])) {
1376
				$ddnsclientupdates = 'allow';
1377
			} else {
1378
				$ddnsclientupdates = $dhcpv6ifconf['ddnsclientupdates'];
1379
			}
1380
			$dnscfgv6 .= "	{$ddnsclientupdates} client-updates;\n";
1381
			$nsupdate = true;
1382
		} else {
1383
			$dnscfgv6 .= "	do-forward-updates false;\n";
1384
		}
1385

    
1386
		if (is_array($dhcpv6ifconf['dnsserver']) && ($dhcpv6ifconf['dnsserver'][0])) {
1387
			$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dhcpv6ifconf['dnsserver']) . ";";
1388
		} else if (((isset($config['dnsmasq']['enable'])) || isset($config['unbound']['enable'])) && (is_ipaddrv6($ifcfgipv6))) {
1389
			$dnscfgv6 .= "	option dhcp6.name-servers {$ifcfgipv6};";
1390
		} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1391
			$dns_arrv6 = array();
1392
			foreach ($syscfg['dnsserver'] as $dnsserver) {
1393
				if (is_ipaddrv6($dnsserver)) {
1394
					$dns_arrv6[] = $dnsserver;
1395
				}
1396
			}
1397
			if (!empty($dns_arrv6)) {
1398
				$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dns_arrv6) . ";";
1399
			}
1400
		}
1401

    
1402
		if (!is_ipaddrv6($ifcfgipv6)) {
1403
			$ifcfgsnv6 = "64";
1404
			$subnetv6 = gen_subnetv6($dhcpv6ifconf['range']['from'], $ifcfgsnv6);
1405
		}
1406

    
1407
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1408

    
1409
		if (isset($dhcpv6ifconf['ddnsupdate']) &&
1410
		    !empty($dhcpv6ifconf['ddnsdomain'])) {
1411
			$newzone = array();
1412
			$newzone['domain-name'] = $dhcpv6ifconf['ddnsdomain'];
1413
			$newzone['dns-servers'][] = $dhcpv6ifconf['ddnsdomainprimary'];
1414
			$newzone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1415
			$newzone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1416
			$ddns_zones[] = $newzone;
1417
			if (isset($dhcpv6ifconf['ddnsreverse'])) {
1418
				$ptr_zones = get_v6_ptr_zones($subnetv6, $ifcfgsnv6);
1419
				foreach ($ptr_zones as $ptr_zone) {
1420
					$reversezone = array();
1421
					$reversezone['domain-name'] = $ptr_zone;
1422
					$reversezone['dns-servers'][] =
1423
					    $dhcpv6ifconf['ddnsdomainprimary'];
1424
					$ddns_zones[] = $reversezone;
1425
				}
1426
			}
1427
		}
1428

    
1429
		$dhcpdv6conf .= " {\n";
1430

    
1431
		$range_from = $dhcpv6ifconf['range']['from'];
1432
		$range_to = $dhcpv6ifconf['range']['to'];
1433
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
1434
			$range_from = merge_ipv6_delegated_prefix($ifcfgipv6, $range_from, $pdlen);
1435
			$range_to = merge_ipv6_delegated_prefix($ifcfgipv6, $range_to, $pdlen);
1436
		}
1437

    
1438
		$dhcpdv6conf .= <<<EOD
1439
	range6 {$range_from} {$range_to};
1440
$dnscfgv6
1441

    
1442
EOD;
1443

    
1444
		if (is_ipaddrv6($dhcpv6ifconf['prefixrange']['from']) && is_ipaddrv6($dhcpv6ifconf['prefixrange']['to'])) {
1445
			$dhcpdv6conf .= "	prefix6 {$dhcpv6ifconf['prefixrange']['from']} {$dhcpv6ifconf['prefixrange']['to']} /{$dhcpv6ifconf['prefixrange']['prefixlength']};\n";
1446
		}
1447
		if (is_ipaddrv6($dhcpv6ifconf['dns6ip'])) {
1448
			$dns6ip = $dhcpv6ifconf['dns6ip'];
1449
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1450
			    Net_IPv6::isInNetmask($dns6ip, '::', $pdlen)) {
1451
				$dns6ip = merge_ipv6_delegated_prefix($ifcfgipv6, $dns6ip, $pdlen);
1452
			}
1453
			$dhcpdv6conf .= "	option dhcp6.name-servers {$dns6ip};\n";
1454
		}
1455
		// default-lease-time
1456
		if ($dhcpv6ifconf['defaultleasetime']) {
1457
			$dhcpdv6conf .= "	default-lease-time {$dhcpv6ifconf['defaultleasetime']};\n";
1458
		}
1459

    
1460
		// max-lease-time
1461
		if ($dhcpv6ifconf['maxleasetime']) {
1462
			$dhcpdv6conf .= "	max-lease-time {$dhcpv6ifconf['maxleasetime']};\n";
1463
		}
1464

    
1465
		// ntp-servers
1466
		if (is_array($dhcpv6ifconf['ntpserver']) && $dhcpv6ifconf['ntpserver'][0]) {
1467
			$ntpservers = array();
1468
			foreach ($dhcpv6ifconf['ntpserver'] as $ntpserver) {
1469
				if (!is_ipaddrv6($ntpserver)) {
1470
					continue;
1471
				}
1472
				if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1473
				    Net_IPv6::isInNetmask($ntpserver, '::', $pdlen)) {
1474
					$ntpserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ntpserver, $pdlen);
1475
				}
1476
				$ntpservers[] = $ntpserver;
1477
			}
1478
			if (count($ntpservers) > 0) {
1479
				$dhcpdv6conf .= "        option dhcp6.sntp-servers " . join(",", $dhcpv6ifconf['ntpserver']) . ";\n";
1480
			}
1481
		}
1482
		// tftp-server-name
1483
		/* Needs ISC DHCPD support
1484
		 if ($dhcpv6ifconf['tftp'] <> "") {
1485
			$dhcpdv6conf .= "	option tftp-server-name \"{$dhcpv6ifconf['tftp']}\";\n";
1486
		 }
1487
		*/
1488

    
1489
		// Handle option, number rowhelper values
1490
		$dhcpdv6conf .= "\n";
1491
		if ($dhcpv6ifconf['numberoptions']['item']) {
1492
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1493
				$itemv6_value = base64_decode($itemv6['value']);
1494
				$dhcpdv6conf .= "	option custom-{$dhcpv6if}-{$itemv6idx} \"{$itemv6_value}\";\n";
1495
			}
1496
		}
1497

    
1498
		// ldap-server
1499
		if ($dhcpv6ifconf['ldap'] <> "") {
1500
			$ldapserver = $dhcpv6ifconf['ldap'];
1501
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1502
			    Net_IPv6::isInNetmask($ldapserver, '::', $pdlen)) {
1503
				$ldapserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ldapserver, $pdlen);
1504
			}
1505
			$dhcpdv6conf .= "	option ldap-server \"{$ldapserver}\";\n";
1506
		}
1507

    
1508
		// net boot information
1509
		if (isset($dhcpv6ifconf['netboot'])) {
1510
			if (!empty($dhcpv6ifconf['bootfile_url'])) {
1511
				$dhcpdv6conf .= "	option dhcp6.bootfile-url \"{$dhcpv6ifconf['bootfile_url']}\";\n";
1512
			}
1513
		}
1514

    
1515
		$dhcpdv6conf .= "}\n";
1516

    
1517
		/* add static mappings */
1518
		/* Needs to use DUID */
1519
		if (is_array($dhcpv6ifconf['staticmap'])) {
1520
			$i = 0;
1521
			foreach ($dhcpv6ifconf['staticmap'] as $sm) {
1522
				$dhcpdv6conf .= <<<EOD
1523
host s_{$dhcpv6if}_{$i} {
1524
	host-identifier option dhcp6.client-id {$sm['duid']};
1525

    
1526
EOD;
1527
				if ($sm['ipaddrv6']) {
1528
					$ipaddrv6 = $sm['ipaddrv6'];
1529
					if ($ifcfgv6['ipaddrv6'] == 'track6') {
1530
						$ipaddrv6 = merge_ipv6_delegated_prefix($ifcfgipv6, $ipaddrv6, $pdlen);
1531
					}
1532
					$dhcpdv6conf .= "	fixed-address6 {$ipaddrv6};\n";
1533
				}
1534

    
1535
				if ($sm['hostname']) {
1536
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1537
					$dhhostname = str_replace(".", "_", $dhhostname);
1538
					$dhcpdv6conf .= "	option host-name {$dhhostname};\n";
1539
				}
1540
				if ($sm['filename']) {
1541
					$dhcpdv6conf .= "	filename \"{$sm['filename']}\";\n";
1542
				}
1543

    
1544
				if ($sm['rootpath']) {
1545
					$dhcpdv6conf .= "	option root-path \"{$sm['rootpath']}\";\n";
1546
				}
1547

    
1548
				$dhcpdv6conf .= "}\n";
1549
				$i++;
1550
			}
1551
		}
1552

    
1553
		if ($dhcpv6ifconf['ddnsdomain']) {
1554
			$dhcpdv6conf .= dhcpdkey($dhcpv6ifconf);
1555
			$dhcpdv6conf .= dhcpdzones($ddns_zones);
1556
		}
1557

    
1558
		if ($config['dhcpdv6'][$dhcpv6if]['ramode'] <> "unmanaged" && isset($config['interfaces'][$dhcpv6if]['enable'])) {
1559
			if (preg_match("/poes/si", $dhcpv6if)) {
1560
				/* magic here */
1561
				$dhcpdv6ifs = array_merge($dhcpdv6ifs, get_pppoes_child_interfaces($dhcpv6if));
1562
			} else {
1563
				$realif = get_real_interface($dhcpv6if, "inet6");
1564
				if (stristr("$realif", "bridge")) {
1565
					$mac = get_interface_mac($realif);
1566
					$v6address = generate_ipv6_from_mac($mac);
1567
					/* Create link local address for bridges */
1568
					mwexec("/sbin/ifconfig {$realif} inet6 {$v6address}");
1569
				}
1570
				$realif = escapeshellcmd($realif);
1571
				$dhcpdv6ifs[] = $realif;
1572
			}
1573
		}
1574
	}
1575

    
1576
	if ($nsupdate) {
1577
		$dhcpdv6conf .= "ddns-update-style interim;\n";
1578
	} else {
1579
		$dhcpdv6conf .= "ddns-update-style none;\n";
1580
	}
1581

    
1582
	/* write dhcpdv6.conf */
1583
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf", $dhcpdv6conf)) {
1584
		log_error("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1585
		if (platform_booting()) {
1586
			printf("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1587
		}
1588
		unset($dhcpdv6conf);
1589
		return 1;
1590
	}
1591
	unset($dhcpdv6conf);
1592

    
1593
	/* create an empty leases v6 database */
1594
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases")) {
1595
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1596
	}
1597

    
1598
	/* make sure there isn't a stale dhcpdv6.pid file, which may make dhcpdv6 fail to start.  */
1599
	/* if we get here, dhcpdv6 has been killed and is not started yet                         */
1600
	unlink_if_exists("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid");
1601

    
1602
	/* fire up dhcpd in a chroot */
1603
	if (count($dhcpdv6ifs) > 0) {
1604
		mwexec("/usr/local/sbin/dhcpd -6 -user dhcpd -group _dhcp -chroot {$g['dhcpd_chroot_path']} -cf /etc/dhcpdv6.conf -pf {$g['varrun_path']}/dhcpdv6.pid " .
1605
			join(" ", $dhcpdv6ifs));
1606
		mwexec("/usr/local/sbin/dhcpleases6 -c \"/usr/local/bin/php-cgi -f /usr/local/sbin/prefixes.php|/bin/sh\" -l {$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1607
	}
1608
	if (platform_booting()) {
1609
		print gettext("done.") . "\n";
1610
	}
1611

    
1612
	return 0;
1613
}
1614

    
1615
function services_igmpproxy_configure() {
1616
	global $config, $g;
1617

    
1618
	/* kill any running igmpproxy */
1619
	killbyname("igmpproxy");
1620

    
1621
	if (!is_array($config['igmpproxy']['igmpentry']) || (count($config['igmpproxy']['igmpentry']) == 0)) {
1622
		return 1;
1623
	}
1624

    
1625
	$iflist = get_configured_interface_list();
1626

    
1627
	$igmpconf = <<<EOD
1628

    
1629
##------------------------------------------------------
1630
## Enable Quickleave mode (Sends Leave instantly)
1631
##------------------------------------------------------
1632
quickleave
1633

    
1634
EOD;
1635

    
1636
	foreach ($config['igmpproxy']['igmpentry'] as $igmpcf) {
1637
		unset($iflist[$igmpcf['ifname']]);
1638
		$realif = get_real_interface($igmpcf['ifname']);
1639
		if (empty($igmpcf['threshold'])) {
1640
			$threshld = 1;
1641
		} else {
1642
			$threshld = $igmpcf['threshold'];
1643
		}
1644
		$igmpconf .= "phyint {$realif} {$igmpcf['type']} ratelimit 0 threshold {$threshld}\n";
1645

    
1646
		if ($igmpcf['address'] <> "") {
1647
			$item = explode(" ", $igmpcf['address']);
1648
			foreach ($item as $iww) {
1649
				$igmpconf .= "altnet {$iww}\n";
1650
			}
1651
		}
1652
		$igmpconf .= "\n";
1653
	}
1654
	foreach ($iflist as $ifn) {
1655
		$realif = get_real_interface($ifn);
1656
		$igmpconf .= "phyint {$realif} disabled\n";
1657
	}
1658
	$igmpconf .= "\n";
1659

    
1660
	$igmpfl = fopen($g['tmp_path'] . "/igmpproxy.conf", "w");
1661
	if (!$igmpfl) {
1662
		log_error(gettext("Could not write Igmpproxy configuration file!"));
1663
		return;
1664
	}
1665
	fwrite($igmpfl, $igmpconf);
1666
	fclose($igmpfl);
1667
	unset($igmpconf);
1668

    
1669
	if (isset($config['syslog']['igmpxverbose'])) {
1670
		mwexec_bg("/usr/local/sbin/igmpproxy -v {$g['tmp_path']}/igmpproxy.conf");
1671
	} else {
1672
		mwexec_bg("/usr/local/sbin/igmpproxy {$g['tmp_path']}/igmpproxy.conf");
1673
	}
1674

    
1675
	log_error(gettext("Started IGMP proxy service."));
1676

    
1677
	return 0;
1678
}
1679

    
1680
function services_dhcrelay_configure() {
1681
	global $config, $g;
1682

    
1683
	if (isset($config['system']['developerspew'])) {
1684
		$mt = microtime();
1685
		echo "services_dhcrelay_configure() being called $mt\n";
1686
	}
1687

    
1688
	/* kill any running dhcrelay */
1689
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
1690

    
1691
	$dhcrelaycfg =& $config['dhcrelay'];
1692

    
1693
	/* DHCPRelay enabled on any interfaces? */
1694
	if (!isset($dhcrelaycfg['enable'])) {
1695
		return 0;
1696
	}
1697

    
1698
	if (platform_booting()) {
1699
		echo gettext("Starting DHCP relay service...");
1700
	} else {
1701
		sleep(1);
1702
	}
1703

    
1704
	$iflist = get_configured_interface_list();
1705

    
1706
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1707
	foreach ($dhcifaces as $dhcrelayif) {
1708
		if (!isset($iflist[$dhcrelayif]) ||
1709
		    link_interface_to_bridge($dhcrelayif)) {
1710
			continue;
1711
		}
1712

    
1713
		if (is_ipaddr(get_interface_ip($dhcrelayif))) {
1714
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1715
		}
1716
	}
1717

    
1718
	/*
1719
	 * In order for the relay to work, it needs to be active
1720
	 * on the interface in which the destination server sits.
1721
	 */
1722
	$srvips = explode(",", $dhcrelaycfg['server']);
1723
	if (!is_array($srvips)) {
1724
		log_error(gettext("No destination IP has been configured!"));
1725
		return;
1726
	}
1727

    
1728
	foreach ($srvips as $srcidx => $srvip) {
1729
		unset($destif);
1730
		foreach ($iflist as $ifname) {
1731
			$subnet = get_interface_ip($ifname);
1732
			if (!is_ipaddr($subnet)) {
1733
				continue;
1734
			}
1735
			$subnet .= "/" . get_interface_subnet($ifname);
1736
			if (ip_in_subnet($srvip, $subnet)) {
1737
				$destif = get_real_interface($ifname);
1738
				break;
1739
			}
1740
		}
1741
		if (!isset($destif)) {
1742
			foreach (get_staticroutes() as $rtent) {
1743
				if (ip_in_subnet($srvip, $rtent['network'])) {
1744
					$a_gateways = return_gateways_array(true);
1745
					$destif = $a_gateways[$rtent['gateway']]['interface'];
1746
					break;
1747
				}
1748
			}
1749
		}
1750

    
1751
		if (!isset($destif)) {
1752
			/* Create a array from the existing route table */
1753
			exec("/usr/bin/netstat -rnWf inet", $route_str);
1754
			array_shift($route_str);
1755
			array_shift($route_str);
1756
			array_shift($route_str);
1757
			array_shift($route_str);
1758
			$route_arr = array();
1759
			foreach ($route_str as $routeline) {
1760
				$items = preg_split("/[ ]+/i", $routeline);
1761
				if (is_subnetv4($items[0])) {
1762
					$subnet = $items[0];
1763
				} elseif (is_ipaddrv4($items[0])) {
1764
					$subnet = "{$items[0]}/32";
1765
				} else {
1766
					// Not a subnet or IP address, skip to the next line.
1767
					continue;
1768
				}
1769
				if (ip_in_subnet($srvip, $subnet)) {
1770
					$destif = trim($items[6]);
1771
					break;
1772
				}
1773
			}
1774
		}
1775

    
1776
		if (!isset($destif)) {
1777
			if (is_array($config['gateways']['gateway_item'])) {
1778
				foreach ($config['gateways']['gateway_item'] as $gateway) {
1779
					if (isset($gateway['defaultgw'])) {
1780
						$destif = get_real_interface($gateway['interface']);
1781
						break;
1782
					}
1783
				}
1784
			} else {
1785
				$destif = get_real_interface("wan");
1786
			}
1787
		}
1788

    
1789
		if (!empty($destif)) {
1790
			$dhcrelayifs[] = $destif;
1791
		}
1792
	}
1793
	$dhcrelayifs = array_unique($dhcrelayifs);
1794

    
1795
	/* fire up dhcrelay */
1796
	if (empty($dhcrelayifs)) {
1797
		log_error(gettext("No suitable interface found for running dhcrelay!"));
1798
		return; /* XXX */
1799
	}
1800

    
1801
	$cmd = "/usr/local/sbin/dhcrelay -i " . implode(" -i ", $dhcrelayifs);
1802

    
1803
	if (isset($dhcrelaycfg['agentoption'])) {
1804
		$cmd .= " -a -m replace";
1805
	}
1806

    
1807
	$cmd .= " " . implode(" ", $srvips);
1808
	mwexec($cmd);
1809
	unset($cmd);
1810

    
1811
	return 0;
1812
}
1813

    
1814
function services_dhcrelay6_configure() {
1815
	global $config, $g;
1816

    
1817
	if (isset($config['system']['developerspew'])) {
1818
		$mt = microtime();
1819
		echo "services_dhcrelay6_configure() being called $mt\n";
1820
	}
1821

    
1822
	/* kill any running dhcrelay */
1823
	killbypid("{$g['varrun_path']}/dhcrelay6.pid");
1824

    
1825
	$dhcrelaycfg =& $config['dhcrelay6'];
1826

    
1827
	/* DHCPv6 Relay enabled on any interfaces? */
1828
	if (!isset($dhcrelaycfg['enable'])) {
1829
		return 0;
1830
	}
1831

    
1832
	if (platform_booting()) {
1833
		echo gettext("Starting DHCPv6 relay service...");
1834
	} else {
1835
		sleep(1);
1836
	}
1837

    
1838
	$iflist = get_configured_interface_list();
1839

    
1840
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1841
	foreach ($dhcifaces as $dhcrelayif) {
1842
		if (!isset($iflist[$dhcrelayif]) ||
1843
		    link_interface_to_bridge($dhcrelayif)) {
1844
			continue;
1845
		}
1846

    
1847
		if (is_ipaddrv6(get_interface_ipv6($dhcrelayif))) {
1848
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1849
		}
1850
	}
1851
	$dhcrelayifs = array_unique($dhcrelayifs);
1852

    
1853
	/*
1854
	 * In order for the relay to work, it needs to be active
1855
	 * on the interface in which the destination server sits.
1856
	 */
1857
	$srvips = explode(",", $dhcrelaycfg['server']);
1858
	$srvifaces = array();
1859
	foreach ($srvips as $srcidx => $srvip) {
1860
		unset($destif);
1861
		foreach ($iflist as $ifname) {
1862
			$subnet = get_interface_ipv6($ifname);
1863
			if (!is_ipaddrv6($subnet)) {
1864
				continue;
1865
			}
1866
			$subnet .= "/" . get_interface_subnetv6($ifname);
1867
			if (ip_in_subnet($srvip, $subnet)) {
1868
				$destif = get_real_interface($ifname);
1869
				break;
1870
			}
1871
		}
1872
		if (!isset($destif)) {
1873
			if (is_array($config['staticroutes']['route'])) {
1874
				foreach ($config['staticroutes']['route'] as $rtent) {
1875
					if (ip_in_subnet($srvip, $rtent['network'])) {
1876
						$a_gateways = return_gateways_array(true);
1877
						$destif = $a_gateways[$rtent['gateway']]['interface'];
1878
						break;
1879
					}
1880
				}
1881
			}
1882
		}
1883

    
1884
		if (!isset($destif)) {
1885
			/* Create a array from the existing route table */
1886
			exec("/usr/bin/netstat -rnWf inet6", $route_str);
1887
			array_shift($route_str);
1888
			array_shift($route_str);
1889
			array_shift($route_str);
1890
			array_shift($route_str);
1891
			$route_arr = array();
1892
			foreach ($route_str as $routeline) {
1893
				$items = preg_split("/[ ]+/i", $routeline);
1894
				if (ip_in_subnet($srvip, $items[0])) {
1895
					$destif = trim($items[6]);
1896
					break;
1897
				}
1898
			}
1899
		}
1900

    
1901
		if (!isset($destif)) {
1902
			if (is_array($config['gateways']['gateway_item'])) {
1903
				foreach ($config['gateways']['gateway_item'] as $gateway) {
1904
					if (isset($gateway['defaultgw'])) {
1905
						$destif = get_real_interface($gateway['interface']);
1906
						break;
1907
					}
1908
				}
1909
			} else {
1910
				$destif = get_real_interface("wan");
1911
			}
1912
		}
1913

    
1914
		if (!empty($destif)) {
1915
			$srvifaces[] = "{$srvip}%{$destif}";
1916
		}
1917
	}
1918

    
1919
	/* fire up dhcrelay */
1920
	if (empty($dhcrelayifs) || empty($srvifaces)) {
1921
		log_error(gettext("No suitable interface found for running dhcrelay -6!"));
1922
		return; /* XXX */
1923
	}
1924

    
1925
	$cmd = "/usr/local/sbin/dhcrelay -6 -pf \"{$g['varrun_path']}/dhcrelay6.pid\"";
1926
	foreach ($dhcrelayifs as $dhcrelayif) {
1927
		$cmd .= " -l {$dhcrelayif}";
1928
	}
1929
	foreach ($srvifaces as $srviface) {
1930
		$cmd .= " -u \"{$srviface}\"";
1931
	}
1932
	mwexec($cmd);
1933
	unset($cmd);
1934

    
1935
	return 0;
1936
}
1937

    
1938
function services_dyndns_configure_client($conf) {
1939

    
1940
	if (!isset($conf['enable'])) {
1941
		return;
1942
	}
1943

    
1944
	/* load up the dyndns.class */
1945
	require_once("dyndns.class");
1946

    
1947
	$dns = new updatedns($dnsService = $conf['type'],
1948
		$dnsHost = $conf['host'],
1949
		$dnsDomain = $conf['domainname'],
1950
		$dnsUser = $conf['username'],
1951
		$dnsPass = $conf['password'],
1952
		$dnsWildcard = $conf['wildcard'],
1953
		$dnsMX = $conf['mx'],
1954
		$dnsIf = "{$conf['interface']}",
1955
		$dnsBackMX = NULL,
1956
		$dnsServer = NULL,
1957
		$dnsPort = NULL,
1958
		$dnsUpdateURL = "{$conf['updateurl']}",
1959
		$forceUpdate = $conf['force'],
1960
		$dnsZoneID = $conf['zoneid'],
1961
		$dnsTTL = $conf['ttl'],
1962
		$dnsResultMatch = "{$conf['resultmatch']}",
1963
		$dnsRequestIf = "{$conf['requestif']}",
1964
		$dnsID = "{$conf['id']}",
1965
		$dnsVerboseLog = $conf['verboselog'],
1966
		$curlIpresolveV4 = $conf['curl_ipresolve_v4'],
1967
		$curlSslVerifypeer = $conf['curl_ssl_verifypeer']);
1968
}
1969

    
1970
function services_dyndns_configure($int = "") {
1971
	global $config, $g;
1972
	if (isset($config['system']['developerspew'])) {
1973
		$mt = microtime();
1974
		echo "services_dyndns_configure() being called $mt\n";
1975
	}
1976

    
1977
	$dyndnscfg = $config['dyndnses']['dyndns'];
1978
	$gwgroups = return_gateway_groups_array();
1979
	if (is_array($dyndnscfg)) {
1980
		if (platform_booting()) {
1981
			echo gettext("Starting DynDNS clients...");
1982
		}
1983

    
1984
		foreach ($dyndnscfg as $dyndns) {
1985
			if ((empty($int)) || ($int == $dyndns['interface']) || (is_array($gwgroups[$dyndns['interface']]))) {
1986
				$dyndns['verboselog'] = isset($dyndns['verboselog']);
1987
				$dyndns['curl_ipresolve_v4'] = isset($dyndns['curl_ipresolve_v4']);
1988
				$dyndns['curl_ssl_verifypeer'] = isset($dyndns['curl_ssl_verifypeer']);
1989
				services_dyndns_configure_client($dyndns);
1990
				sleep(1);
1991
			}
1992
		}
1993

    
1994
		if (platform_booting()) {
1995
			echo gettext("done.") . "\n";
1996
		}
1997
	}
1998

    
1999
	return 0;
2000
}
2001

    
2002
function dyndnsCheckIP($int) {
2003
	global $config;
2004
	$ip_address = get_interface_ip($int);
2005
	if (is_private_ip($ip_address)) {
2006
		$gateways_status = return_gateways_status(true);
2007
		// If the gateway for this interface is down, then the external check cannot work.
2008
		// Avoid the long wait for the external check to timeout.
2009
		if (stristr($gateways_status[$config['interfaces'][$int]['gateway']]['status'], "down")) {
2010
			return "down";
2011
		}
2012
		$hosttocheck = "http://checkip.dyndns.org";
2013
		$ip_ch = curl_init($hosttocheck);
2014
		curl_setopt($ip_ch, CURLOPT_RETURNTRANSFER, 1);
2015
		curl_setopt($ip_ch, CURLOPT_SSL_VERIFYPEER, FALSE);
2016
		curl_setopt($ip_ch, CURLOPT_INTERFACE, 'host!' . $ip_address);
2017
		curl_setopt($ip_ch, CURLOPT_CONNECTTIMEOUT, '30');
2018
		curl_setopt($ip_ch, CURLOPT_TIMEOUT, 120);
2019
		curl_setopt($ip_ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
2020
		$ip_result_page = curl_exec($ip_ch);
2021
		curl_close($ip_ch);
2022
		$ip_result_decoded = urldecode($ip_result_page);
2023
		preg_match('=Current IP Address: (.*)</body>=siU', $ip_result_decoded, $matches);
2024
		$ip_address = trim($matches[1]);
2025
	}
2026
	return $ip_address;
2027
}
2028

    
2029
function services_dnsmasq_configure($restart_dhcp = true) {
2030
	global $config, $g;
2031
	$return = 0;
2032

    
2033
	// hard coded args: will be removed to avoid duplication if specified in custom_options
2034
	$standard_args = array(
2035
		"dns-forward-max" => "--dns-forward-max=5000",
2036
		"cache-size" => "--cache-size=10000",
2037
		"local-ttl" => "--local-ttl=1"
2038
	);
2039

    
2040

    
2041
	if (isset($config['system']['developerspew'])) {
2042
		$mt = microtime();
2043
		echo "services_dnsmasq_configure() being called $mt\n";
2044
	}
2045

    
2046
	/* kill any running dnsmasq */
2047
	if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) {
2048
		sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
2049
	}
2050

    
2051
	if (isset($config['dnsmasq']['enable'])) {
2052

    
2053
		if (platform_booting()) {
2054
			echo gettext("Starting DNS forwarder...");
2055
		} else {
2056
			sleep(1);
2057
		}
2058

    
2059
		/* generate hosts file */
2060
		if (system_hosts_generate() != 0) {
2061
			$return = 1;
2062
		}
2063

    
2064
		$args = "";
2065

    
2066
		if (isset($config['dnsmasq']['regdhcp'])) {
2067
			$args .= " --dhcp-hostsfile={$g['varetc_path']}/hosts ";
2068
		}
2069

    
2070
		/* Setup listen port, if non-default */
2071
		if (is_port($config['dnsmasq']['port'])) {
2072
			$args .= " --port={$config['dnsmasq']['port']} ";
2073
		}
2074

    
2075
		$listen_addresses = "";
2076
		if (isset($config['dnsmasq']['interface'])) {
2077
			$interfaces = explode(",", $config['dnsmasq']['interface']);
2078
			foreach ($interfaces as $interface) {
2079
				$if = get_real_interface($interface);
2080
				if (does_interface_exist($if)) {
2081
					$laddr = get_interface_ip($interface);
2082
					if (is_ipaddrv4($laddr)) {
2083
						$listen_addresses .= " --listen-address={$laddr} ";
2084
					}
2085
					$laddr6 = get_interface_ipv6($interface);
2086
					if (is_ipaddrv6($laddr6) && !isset($config['dnsmasq']['strictbind'])) {
2087
						/*
2088
						 * XXX: Since dnsmasq does not support link-local address
2089
						 * with scope specified. These checks are being done.
2090
						 */
2091
						if (is_linklocal($laddr6) && strstr($laddr6, "%")) {
2092
							$tmpaddrll6 = explode("%", $laddr6);
2093
							$listen_addresses .= " --listen-address={$tmpaddrll6[0]} ";
2094
						} else {
2095
							$listen_addresses .= " --listen-address={$laddr6} ";
2096
						}
2097
					}
2098
				}
2099
			}
2100
			if (!empty($listen_addresses)) {
2101
				$args .= " {$listen_addresses} ";
2102
				if (isset($config['dnsmasq']['strictbind'])) {
2103
					$args .= " --bind-interfaces ";
2104
				}
2105
			}
2106
		}
2107

    
2108
		/* If selected, then first forward reverse lookups for private IPv4 addresses to nowhere. */
2109
		/* Only make entries for reverse domains that do not have a matching domain override. */
2110
		if (isset($config['dnsmasq']['no_private_reverse'])) {
2111
			/* Note: Carrier Grade NAT (CGN) addresses 100.64.0.0/10 are intentionally not here. */
2112
			/* End-users should not be aware of CGN addresses, so reverse lookups for these should not happen. */
2113
			/* Just the pfSense WAN might get a CGN address from an ISP. */
2114

    
2115
			// Build an array of domain overrides to help in checking for matches.
2116
			$override_a = array();
2117
			if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2118
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2119
					$override_a[$override['domain']] = "y";
2120
				}
2121
			}
2122

    
2123
			// Build an array of the private reverse lookup domain names
2124
			$reverse_domain_a = array("10.in-addr.arpa", "168.192.in-addr.arpa");
2125
			// Unfortunately the 172.16.0.0/12 range does not map nicely to the in-addr.arpa scheme.
2126
			for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) {
2127
				$reverse_domain_a[] = "$subnet_num.172.in-addr.arpa";
2128
			}
2129

    
2130
			// Set the --server parameter to nowhere for each reverse domain name that was not specifically specified in a domain override.
2131
			foreach ($reverse_domain_a as $reverse_domain) {
2132
				if (!isset($override_a[$reverse_domain])) {
2133
					$args .= " --server=/$reverse_domain/ ";
2134
				}
2135
			}
2136
			unset($override_a);
2137
			unset($reverse_domain_a);
2138
		}
2139

    
2140
		/* Setup forwarded domains */
2141
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2142
			foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2143
				if ($override['ip'] == "!") {
2144
					$override[ip] = "";
2145
				}
2146
				$args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
2147
			}
2148
		}
2149

    
2150
		/* Allow DNS Rebind for forwarded domains */
2151
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2152
			if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2153
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2154
					$args .= ' --rebind-domain-ok=/' . $override['domain'] . '/ ';
2155
				}
2156
			}
2157
		}
2158

    
2159
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2160
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2161
		}
2162

    
2163
		if (isset($config['dnsmasq']['strict_order'])) {
2164
			$args .= " --strict-order ";
2165
		}
2166

    
2167
		if (isset($config['dnsmasq']['domain_needed'])) {
2168
			$args .= " --domain-needed ";
2169
		}
2170

    
2171
		if ($config['dnsmasq']['custom_options']) {
2172
			foreach (preg_split('/\s+/', $config['dnsmasq']['custom_options']) as $c) {
2173
				$args .= " " . escapeshellarg("--{$c}");
2174
				$p = explode('=', $c);
2175
				if (array_key_exists($p[0], $standard_args)) {
2176
					unset($standard_args[$p[0]]);
2177
				}
2178
			}
2179
		}
2180
		$args .= ' ' . implode(' ', array_values($standard_args));
2181

    
2182
		/* run dnsmasq */
2183
		$cmd = "/usr/local/sbin/dnsmasq --all-servers {$dns_rebind} {$args}";
2184
		//log_error("dnsmasq command: {$cmd}");
2185
		mwexec_bg($cmd);
2186
		unset($args);
2187

    
2188
		system_dhcpleases_configure();
2189

    
2190
		if (platform_booting()) {
2191
			echo gettext("done.") . "\n";
2192
		}
2193
	}
2194

    
2195
	if (!platform_booting() && $restart_dhcp) {
2196
		if (services_dhcpd_configure() != 0) {
2197
			$return = 1;
2198
		}
2199
	}
2200

    
2201
	return $return;
2202
}
2203

    
2204
function services_unbound_configure($restart_dhcp = true) {
2205
	global $config, $g;
2206
	$return = 0;
2207

    
2208
	if (isset($config['system']['developerspew'])) {
2209
		$mt = microtime();
2210
		echo "services_unbound_configure() being called $mt\n";
2211
	}
2212

    
2213
	// kill any running Unbound instance
2214
	if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2215
		sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
2216
	}
2217

    
2218
	if (isset($config['unbound']['enable'])) {
2219
		if (platform_booting()) {
2220
			echo gettext("Starting DNS Resolver...");
2221
		} else {
2222
			sleep(1);
2223
		}
2224

    
2225
		/* generate hosts file */
2226
		if (system_hosts_generate() != 0) {
2227
			$return = 1;
2228
		}
2229

    
2230
		require_once('/etc/inc/unbound.inc');
2231
		sync_unbound_service();
2232
		if (platform_booting()) {
2233
			echo gettext("done.") . "\n";
2234
		}
2235

    
2236
		system_dhcpleases_configure();
2237
	}
2238

    
2239
	if (!platform_booting() && $restart_dhcp) {
2240
		if (services_dhcpd_configure() != 0) {
2241
			$return = 1;
2242
		}
2243
	}
2244

    
2245
	return $return;
2246
}
2247

    
2248
function services_snmpd_configure() {
2249
	global $config, $g;
2250
	if (isset($config['system']['developerspew'])) {
2251
		$mt = microtime();
2252
		echo "services_snmpd_configure() being called $mt\n";
2253
	}
2254

    
2255
	/* kill any running snmpd */
2256
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
2257
	sleep(2);
2258
	if (is_process_running("bsnmpd")) {
2259
		mwexec("/usr/bin/killall bsnmpd", true);
2260
	}
2261

    
2262
	if (isset($config['snmpd']['enable'])) {
2263

    
2264
		if (platform_booting()) {
2265
			echo gettext("Starting SNMP daemon... ");
2266
		}
2267

    
2268
		/* generate snmpd.conf */
2269
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
2270
		if (!$fd) {
2271
			printf(gettext("Error: cannot open snmpd.conf in services_snmpd_configure().%s"), "\n");
2272
			return 1;
2273
		}
2274

    
2275

    
2276
		$snmpdconf = <<<EOD
2277
location := "{$config['snmpd']['syslocation']}"
2278
contact := "{$config['snmpd']['syscontact']}"
2279
read := "{$config['snmpd']['rocommunity']}"
2280

    
2281
EOD;
2282

    
2283
/* No docs on what write strings do there so disable for now.
2284
		if (isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])) {
2285
			$snmpdconf .= <<<EOD
2286
# write string
2287
write := "{$config['snmpd']['rwcommunity']}"
2288

    
2289
EOD;
2290
		}
2291
*/
2292

    
2293

    
2294
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2295
			$snmpdconf .= <<<EOD
2296
# SNMP Trap support.
2297
traphost := {$config['snmpd']['trapserver']}
2298
trapport := {$config['snmpd']['trapserverport']}
2299
trap := "{$config['snmpd']['trapstring']}"
2300

    
2301

    
2302
EOD;
2303
		}
2304

    
2305
		$platform = trim(file_get_contents('/etc/platform'));
2306
		if (($platform == "pfSense") && ($g['product_name'] != "pfSense")) {
2307
			$platform = $g['product_name'];
2308
		}
2309
		$sysDescr = "{$g['product_name']} " . php_uname("n") .
2310
			" {$g['product_version']} {$platform} " . php_uname("s") .
2311
			" " . php_uname("r") . " " . php_uname("m");
2312

    
2313
		$snmpdconf .= <<<EOD
2314
system := 1     # pfSense
2315
%snmpd
2316
sysDescr			= "{$sysDescr}"
2317
begemotSnmpdDebugDumpPdus       = 2
2318
begemotSnmpdDebugSyslogPri      = 7
2319
begemotSnmpdCommunityString.0.1 = $(read)
2320

    
2321
EOD;
2322

    
2323
/* No docs on what write strings do there so disable for now.
2324
		if (isset($config['snmpd']['rwcommunity']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])) {
2325
			$snmpdconf .= <<<EOD
2326
begemotSnmpdCommunityString.0.2 = $(write)
2327

    
2328
EOD;
2329
		}
2330
*/
2331

    
2332

    
2333
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2334
			$snmpdconf .= <<<EOD
2335
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
2336
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
2337
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
2338

    
2339
EOD;
2340
		}
2341

    
2342

    
2343
		$snmpdconf .= <<<EOD
2344
begemotSnmpdCommunityDisable    = 1
2345

    
2346
EOD;
2347

    
2348
		$bind_to_ip = "0.0.0.0";
2349
		if (isset($config['snmpd']['bindip'])) {
2350
			if (is_ipaddr($config['snmpd']['bindip'])) {
2351
				$bind_to_ip = $config['snmpd']['bindip'];
2352
			} else {
2353
				$if = get_real_interface($config['snmpd']['bindip']);
2354
				if (does_interface_exist($if)) {
2355
					$bind_to_ip = get_interface_ip($config['snmpd']['bindip']);
2356
				}
2357
			}
2358
		}
2359

    
2360
		if (is_port($config['snmpd']['pollport'])) {
2361
			$snmpdconf .= <<<EOD
2362
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
2363

    
2364
EOD;
2365

    
2366
		}
2367

    
2368
		$snmpdconf .= <<<EOD
2369
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
2370
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
2371

    
2372
# These are bsnmp macros not php vars.
2373
sysContact      = $(contact)
2374
sysLocation     = $(location)
2375
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
2376

    
2377
snmpEnableAuthenTraps = 2
2378

    
2379
EOD;
2380

    
2381
		if (is_array($config['snmpd']['modules'])) {
2382
			if (isset($config['snmpd']['modules']['mibii'])) {
2383
			$snmpdconf .= <<<EOD
2384
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
2385

    
2386
EOD;
2387
			}
2388

    
2389
			if (isset($config['snmpd']['modules']['netgraph'])) {
2390
				$snmpdconf .= <<<EOD
2391
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
2392
%netgraph
2393
begemotNgControlNodeName = "snmpd"
2394

    
2395
EOD;
2396
			}
2397

    
2398
			if (isset($config['snmpd']['modules']['pf'])) {
2399
				$snmpdconf .= <<<EOD
2400
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
2401

    
2402
EOD;
2403
			}
2404

    
2405
			if (isset($config['snmpd']['modules']['hostres'])) {
2406
				$snmpdconf .= <<<EOD
2407
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
2408

    
2409
EOD;
2410
			}
2411

    
2412
			if (isset($config['snmpd']['modules']['bridge'])) {
2413
				$snmpdconf .= <<<EOD
2414
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
2415
# config must end with blank line
2416

    
2417
EOD;
2418
			}
2419
			if (isset($config['snmpd']['modules']['ucd'])) {
2420
				$snmpdconf .= <<<EOD
2421
begemotSnmpdModulePath."ucd"     = "/usr/local/lib/snmp_ucd.so"
2422

    
2423
EOD;
2424
			}
2425
			if (isset($config['snmpd']['modules']['regex'])) {
2426
				$snmpdconf .= <<<EOD
2427
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"
2428

    
2429
EOD;
2430
			}
2431
		}
2432

    
2433
		fwrite($fd, $snmpdconf);
2434
		fclose($fd);
2435
		unset($snmpdconf);
2436

    
2437
		/* run bsnmpd */
2438
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
2439
			" -p {$g['varrun_path']}/snmpd.pid");
2440

    
2441
		if (platform_booting()) {
2442
			echo gettext("done.") . "\n";
2443
		}
2444
	}
2445

    
2446
	return 0;
2447
}
2448

    
2449
function services_dnsupdate_process($int = "", $updatehost = "", $forced = false) {
2450
	global $config, $g;
2451
	if (isset($config['system']['developerspew'])) {
2452
		$mt = microtime();
2453
		echo "services_dnsupdate_process() being called $mt\n";
2454
	}
2455

    
2456
	/* Dynamic DNS updating active? */
2457
	if (is_array($config['dnsupdates']['dnsupdate'])) {
2458
		$notify_text = "";
2459
		$gwgroups = return_gateway_groups_array();
2460
		foreach ($config['dnsupdates']['dnsupdate'] as $i => $dnsupdate) {
2461
			if (!isset($dnsupdate['enable'])) {
2462
				continue;
2463
			}
2464
			if (!empty($int) && ($int != $dnsupdate['interface']) && (!is_array($gwgroups[$dnsupdate['interface']]))) {
2465
				continue;
2466
			}
2467
			if (!empty($updatehost) && ($updatehost != $dnsupdate['host'])) {
2468
				continue;
2469
			}
2470

    
2471
			/* determine interface name */
2472
			$if = get_failover_interface($dnsupdate['interface']);
2473

    
2474
			if (isset($dnsupdate['usepublicip'])) {
2475
				$wanip = dyndnsCheckIP($if);
2476
			} else {
2477
				$wanip = get_interface_ip($if);
2478
			}
2479

    
2480
			$wanipv6 = get_interface_ipv6($if);
2481
			$cacheFile = "{$g['conf_path']}/dyndns_{$dnsupdate['interface']}_rfc2136_" . escapeshellarg($dnsupdate['host']) . "_{$dnsupdate['server']}.cache";
2482
			$currentTime = time();
2483

    
2484
			if ($wanip || $wanipv6) {
2485
				$keyname = $dnsupdate['keyname'];
2486
				/* trailing dot */
2487
				if (substr($keyname, -1) != ".") {
2488
					$keyname .= ".";
2489
				}
2490

    
2491
				$hostname = $dnsupdate['host'];
2492
				/* trailing dot */
2493
				if (substr($hostname, -1) != ".") {
2494
					$hostname .= ".";
2495
				}
2496

    
2497
				/* write private key file
2498
				   this is dumb - public and private keys are the same for HMAC-MD5,
2499
				   but nsupdate insists on having both */
2500
				$fd = fopen("{$g['varetc_path']}/K{$i}{$keyname}+157+00000.private", "w");
2501
				$privkey = <<<EOD
2502
Private-key-format: v1.2
2503
Algorithm: 157 (HMAC)
2504
Key: {$dnsupdate['keydata']}
2505

    
2506
EOD;
2507
				fwrite($fd, $privkey);
2508
				fclose($fd);
2509

    
2510
				/* write public key file */
2511
				if ($dnsupdate['keytype'] == "zone") {
2512
					$flags = 257;
2513
					$proto = 3;
2514
				} else if ($dnsupdate['keytype'] == "host") {
2515
					$flags = 513;
2516
					$proto = 3;
2517
				} else if ($dnsupdate['keytype'] == "user") {
2518
					$flags = 0;
2519
					$proto = 2;
2520
				}
2521

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

    
2526
				/* generate update instructions */
2527
				$upinst = "";
2528
				if (!empty($dnsupdate['server'])) {
2529
					$upinst .= "server {$dnsupdate['server']}\n";
2530
				}
2531

    
2532
				if (file_exists($cacheFile)) {
2533
					list($cachedipv4, $cacheTimev4) = explode("|", file_get_contents($cacheFile));
2534
				}
2535
				if (file_exists("{$cacheFile}.ipv6")) {
2536
					list($cachedipv6, $cacheTimev6) = explode("|", file_get_contents("{$cacheFile}.ipv6"));
2537
				}
2538

    
2539
				// 25 Days
2540
				$maxCacheAgeSecs = 25 * 24 * 60 * 60;
2541
				$need_update = false;
2542

    
2543
				conf_mount_rw();
2544
				/* Update IPv4 if we have it. */
2545
				if (is_ipaddrv4($wanip) && $dnsupdate['recordtype'] != "AAAA") {
2546
					if (($wanip != $cachedipv4) || (($currentTime - $cacheTimev4) > $maxCacheAgeSecs) || $forced) {
2547
						$upinst .= "update delete {$dnsupdate['host']}. A\n";
2548
						$upinst .= "update add {$dnsupdate['host']}. {$dnsupdate['ttl']} A {$wanip}\n";
2549
						$notify_text .= sprintf(gettext('DynDNS updated IP Address (A) for %1$s on %2$s (%3$s) to %4$s'), $dnsupdate['host'], convert_real_interface_to_friendly_descr($if), $if, $wanip) . "\n";
2550
						@file_put_contents($cacheFile, "{$wanip}|{$currentTime}");
2551
						log_error(sprintf(gettext('phpDynDNS: updating cache file %1$s: %2$s'), $cacheFile, $wanip));
2552
						$need_update = true;
2553
					} else {
2554
						log_error(sprintf(gettext("phpDynDNS: Not updating %s A record because the IP address has not changed."), $dnsupdate['host']));
2555
					}
2556
				} else {
2557
					@unlink($cacheFile);
2558
				}
2559

    
2560
				/* Update IPv6 if we have it. */
2561
				if (is_ipaddrv6($wanipv6) && $dnsupdate['recordtype'] != "A") {
2562
					if (($wanipv6 != $cachedipv6) || (($currentTime - $cacheTimev6) > $maxCacheAgeSecs) || $forced) {
2563
						$upinst .= "update delete {$dnsupdate['host']}. AAAA\n";
2564
						$upinst .= "update add {$dnsupdate['host']}. {$dnsupdate['ttl']} AAAA {$wanipv6}\n";
2565
						$notify_text .= sprintf(gettext('DynDNS updated IPv6 Address (AAAA) for %1$s on %2$s (%3$s) to %4$s'), $dnsupdate['host'], convert_real_interface_to_friendly_descr($if), $if, $wanipv6) . "\n";
2566
						@file_put_contents("{$cacheFile}.ipv6", "{$wanipv6}|{$currentTime}");
2567
						log_error(sprintf(gettext('phpDynDNS: updating cache file %1$s.ipv6: %2$s'), $cacheFile, $wanipv6));
2568
						$need_update = true;
2569
					} else {
2570
						log_error(sprintf(gettext("phpDynDNS: Not updating %s AAAA record because the IPv6 address has not changed."), $dnsupdate['host']));
2571
					}
2572
				} else {
2573
					@unlink("{$cacheFile}.ipv6");
2574
				}
2575
				conf_mount_ro();
2576

    
2577
				$upinst .= "\n";	/* mind that trailing newline! */
2578

    
2579
				if ($need_update) {
2580
					@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}", $upinst);
2581
					unset($upinst);
2582
					/* invoke nsupdate */
2583
					$cmd = "/usr/local/bin/nsupdate -k {$g['varetc_path']}/K{$i}{$keyname}+157+00000.key";
2584
					if (isset($dnsupdate['usetcp'])) {
2585
						$cmd .= " -v";
2586
					}
2587
					$cmd .= " {$g['varetc_path']}/nsupdatecmds{$i}";
2588
					mwexec_bg($cmd);
2589
					unset($cmd);
2590
				}
2591
			}
2592
		}
2593
		if (!empty($notify_text)) {
2594
			notify_all_remote($notify_text);
2595
		}
2596
	}
2597

    
2598
	return 0;
2599
}
2600

    
2601
/* configure cron service */
2602
function configure_cron() {
2603
	global $g, $config;
2604

    
2605
	conf_mount_rw();
2606
	/* preserve existing crontab entries */
2607
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2608

    
2609
	for ($i = 0; $i < count($crontab_contents); $i++) {
2610
		$cron_item =& $crontab_contents[$i];
2611
		if (strpos($cron_item, "# pfSense specific crontab entries") !== false) {
2612
			array_splice($crontab_contents, $i - 1);
2613
			break;
2614
		}
2615
	}
2616
	$crontab_contents = implode("\n", $crontab_contents) . "\n";
2617

    
2618

    
2619
	if (is_array($config['cron']['item'])) {
2620
		$crontab_contents .= "#\n";
2621
		$crontab_contents .= "# pfSense specific crontab entries\n";
2622
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
2623
		$crontab_contents .= "#\n";
2624

    
2625
		if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) {
2626
			$http_proxy = $config['system']['proxyurl'];
2627
			if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) {
2628
				$http_proxy .= ':' . $config['system']['proxyport'];
2629
			}
2630
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
2631
		}
2632

    
2633
		foreach ($config['cron']['item'] as $item) {
2634
			$crontab_contents .= "\n{$item['minute']}\t";
2635
			$crontab_contents .= "{$item['hour']}\t";
2636
			$crontab_contents .= "{$item['mday']}\t";
2637
			$crontab_contents .= "{$item['month']}\t";
2638
			$crontab_contents .= "{$item['wday']}\t";
2639
			$crontab_contents .= "{$item['who']}\t";
2640
			$crontab_contents .= "{$item['command']}";
2641
		}
2642

    
2643
		$crontab_contents .= "\n#\n";
2644
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
2645
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
2646
		$crontab_contents .= "#\n\n";
2647
	}
2648

    
2649
	/* please maintain the newline at the end of file */
2650
	file_put_contents("/etc/crontab", $crontab_contents);
2651
	unset($crontab_contents);
2652

    
2653
	/* make sure that cron is running and start it if it got killed somehow */
2654
	if (!is_process_running("cron")) {
2655
		exec("cd /tmp && /usr/sbin/cron -s 2>/dev/null");
2656
	} else {
2657
	/* do a HUP kill to force sync changes */
2658
		sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP");
2659
	}
2660

    
2661
	conf_mount_ro();
2662
}
2663

    
2664
function upnp_action ($action) {
2665
	global $g, $config;
2666
	switch ($action) {
2667
		case "start":
2668
			if (file_exists('/var/etc/miniupnpd.conf')) {
2669
				@unlink("{$g['varrun_path']}/miniupnpd.pid");
2670
				mwexec_bg("/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf -P {$g['varrun_path']}/miniupnpd.pid");
2671
			}
2672
			break;
2673
		case "stop":
2674
			killbypid("{$g['varrun_path']}/miniupnpd.pid");
2675
			while ((int)exec("/bin/pgrep -a miniupnpd | wc -l") > 0) {
2676
				mwexec('/usr/bin/killall miniupnpd 2>/dev/null', true);
2677
			}
2678
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
2679
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
2680
			break;
2681
		case "restart":
2682
			upnp_action('stop');
2683
			upnp_action('start');
2684
			break;
2685
	}
2686
}
2687

    
2688
function upnp_start() {
2689
	global $config;
2690

    
2691
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
2692
		return;
2693
	}
2694

    
2695
	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
2696
		echo gettext("Starting UPnP service... ");
2697
		require_once('/usr/local/pkg/miniupnpd.inc');
2698
		sync_package_miniupnpd();
2699
		echo "done.\n";
2700
	}
2701
}
2702

    
2703
function install_cron_job($command, $active = false, $minute = "0", $hour = "*", $monthday = "*", $month = "*", $weekday = "*", $who = "root") {
2704
	global $config, $g;
2705

    
2706
	$is_installed = false;
2707
	$cron_changed = true;
2708

    
2709
	if (!is_array($config['cron'])) {
2710
		$config['cron'] = array();
2711
	}
2712
	if (!is_array($config['cron']['item'])) {
2713
		$config['cron']['item'] = array();
2714
	}
2715

    
2716
	$x = 0;
2717
	foreach ($config['cron']['item'] as $item) {
2718
		if (strstr($item['command'], $command)) {
2719
			$is_installed = true;
2720
			break;
2721
		}
2722
		$x++;
2723
	}
2724

    
2725
	if ($active) {
2726
		$cron_item = array();
2727
		$cron_item['minute'] = $minute;
2728
		$cron_item['hour'] = $hour;
2729
		$cron_item['mday'] = $monthday;
2730
		$cron_item['month'] = $month;
2731
		$cron_item['wday'] = $weekday;
2732
		$cron_item['who'] = $who;
2733
		$cron_item['command'] = $command;
2734
		if (!$is_installed) {
2735
			$config['cron']['item'][] = $cron_item;
2736
			write_config(sprintf(gettext("Installed cron job for %s"), $command));
2737
		} else {
2738
			if ($config['cron']['item'][$x] == $cron_item) {
2739
				$cron_changed = false;
2740
				log_error(sprintf(gettext("Checked cron job for %s, no change needed"), $command));
2741
			} else {
2742
				$config['cron']['item'][$x] = $cron_item;
2743
				write_config(sprintf(gettext("Updated cron job for %s"), $command));
2744
			}
2745
		}
2746
	} else {
2747
		if ($is_installed == true) {
2748
			unset($config['cron']['item'][$x]);
2749
			write_config(sprintf(gettext("Removed cron job for %s"), $command));
2750
		}
2751
	}
2752

    
2753
	if ($cron_changed) {
2754
		configure_cron();
2755
	}
2756
}
2757

    
2758
?>
(49-49/65)