Project

General

Profile

Download (86.6 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
		if (is_array($dhcpifconf['pool'])) {
552
			foreach ($dhcpifconf['pool'] as $poolidx => $poolconf) {
553
				if (is_array($poolconf['numberoptions']) && is_array($poolconf['numberoptions']['item'])) {
554
					foreach ($poolconf['numberoptions']['item'] as $itemidx => $item) {
555
						if (!empty($item['type'])) {
556
							$itemtype = $item['type'];
557
						} else {
558
							$itemtype = "text";
559
						}
560
						$custoptions .= "option custom-{$dhcpif}-{$poolidx}-{$itemidx} code {$item['number']} = {$itemtype};\n";
561
					}
562
				}
563
			}
564
		}
565
	}
566

    
567
	$dhcpdconf = <<<EOD
568

    
569
option domain-name "{$syscfg['domain']}";
570
option ldap-server code 95 = text;
571
option domain-search-list code 119 = text;
572
option arch code 93 = unsigned integer 16; # RFC4578
573
{$custoptions}
574
default-lease-time 7200;
575
max-lease-time 86400;
576
log-facility local7;
577
one-lease-per-client true;
578
deny duplicates;
579
ping-check true;
580
update-conflict-detection false;
581
dhcp-cache-threshold 0;
582

    
583
EOD;
584

    
585
	if (!isset($dhcpifconf['disableauthoritative'])) {
586
		$dhcpdconf .= "authoritative;\n";
587
	}
588

    
589
	if (isset($dhcpifconf['alwaysbroadcast'])) {
590
		$dhcpdconf .= "always-broadcast on\n";
591
	}
592

    
593
	$dhcpdifs = array();
594
	$enable_add_routers = false;
595
	$gateways_arr = return_gateways_array();
596
	/* only add a routers line if the system has any IPv4 gateway at all */
597
	/* a static route has a gateway, manually overriding this field always works */
598
	foreach ($gateways_arr as $gwitem) {
599
		if ($gwitem['ipprotocol'] == "inet") {
600
			$enable_add_routers = true;
601
			break;
602
		}
603
	}
604

    
605
	/*    loop through and determine if we need to setup
606
	 *    failover peer "bleh" entries
607
	 */
608
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
609

    
610
		if (!isset($config['interfaces'][$dhcpif]['enable'])) {
611
			continue;
612
		}
613

    
614
		interfaces_staticarp_configure($dhcpif);
615

    
616
		if (!isset($dhcpifconf['enable'])) {
617
			continue;
618
		}
619

    
620
		if ($dhcpifconf['failover_peerip'] <> "") {
621
			$intip = get_interface_ip($dhcpif);
622
			/*
623
			 *    yep, failover peer is defined.
624
			 *    does it match up to a defined vip?
625
			 */
626
			$skew = 110;
627
			if (is_array($config['virtualip']['vip'])) {
628
				foreach ($config['virtualip']['vip'] as $vipent) {
629
					if ($vipent['interface'] == $dhcpif) {
630
						$carp_nw = gen_subnet($vipent['subnet'], $vipent['subnet_bits']);
631
						if (ip_in_subnet($dhcpifconf['failover_peerip'], "{$carp_nw}/{$vipent['subnet_bits']}")) {
632
							/* this is the interface! */
633
							if (is_numeric($vipent['advskew']) && (intval($vipent['advskew']) < 20)) {
634
								$skew = 0;
635
								break;
636
							}
637
						}
638
					}
639
				}
640
			} else {
641
				log_error(gettext("Warning!  DHCP Failover setup and no CARP virtual IPs defined!"));
642
			}
643
			if ($skew > 10) {
644
				$type = "secondary";
645
				$my_port = "520";
646
				$peer_port = "519";
647
			} else {
648
				$my_port = "519";
649
				$peer_port = "520";
650
				$type = "primary";
651
				$dhcpdconf_pri = "split 128;\n";
652
				$dhcpdconf_pri .= "  mclt 600;\n";
653
			}
654

    
655
			if (is_ipaddrv4($intip)) {
656
				$dhcpdconf .= <<<EOPP
657
failover peer "dhcp_{$dhcpif}" {
658
  {$type};
659
  address {$intip};
660
  port {$my_port};
661
  peer address {$dhcpifconf['failover_peerip']};
662
  peer port {$peer_port};
663
  max-response-delay 10;
664
  max-unacked-updates 10;
665
  {$dhcpdconf_pri}
666
  load balance max seconds 3;
667
}
668
\n
669
EOPP;
670
			}
671
		}
672
	}
673

    
674
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
675

    
676
		$newzone = array();
677
		$ifcfg = $config['interfaces'][$dhcpif];
678

    
679
		if (!isset($dhcpifconf['enable']) || !isset($Iflist[$dhcpif])) {
680
			continue;
681
		}
682
		$ifcfgip = get_interface_ip($dhcpif);
683
		$ifcfgsn = get_interface_subnet($dhcpif);
684
		$subnet = gen_subnet($ifcfgip, $ifcfgsn);
685
		$subnetmask = gen_subnet_mask($ifcfgsn);
686

    
687
		if (!is_ipaddr($subnet)) {
688
			continue;
689
		}
690

    
691
		if ($is_olsr_enabled == true) {
692
			if ($dhcpifconf['netmask']) {
693
				$subnetmask = gen_subnet_mask($dhcpifconf['netmask']);
694
			}
695
		}
696

    
697
		$all_pools = array();
698
		$all_pools[] = $dhcpifconf;
699
		if (is_array($dhcpifconf['pool'])) {
700
			$all_pools = array_merge($all_pools, $dhcpifconf['pool']);
701
		}
702

    
703
		$dnscfg = "";
704

    
705
		if ($dhcpifconf['domain']) {
706
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
707
		}
708

    
709
		if ($dhcpifconf['domainsearchlist'] <> "") {
710
			$dnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpifconf['domainsearchlist'])) . "\";\n";
711
		}
712

    
713
		if (isset($dhcpifconf['ddnsupdate'])) {
714
			$need_ddns_updates = true;
715
			$newzone = array();
716
			if ($dhcpifconf['ddnsdomain'] <> "") {
717
				$newzone['domain-name'] = $dhcpifconf['ddnsdomain'];
718
				$dnscfg .= "	ddns-domainname \"{$dhcpifconf['ddnsdomain']}\";\n";
719
			} else {
720
				$newzone['domain-name'] = $config['system']['domain'];
721
			}
722

    
723
			$revsubnet = array_reverse(explode('.',$subnet));
724

    
725
			/* Take care of full classes first */
726
			switch ($ifcfgsn) {
727
				case 8:
728
					$start_octet = 3;
729
					break;
730
				case 16:
731
					$start_octet = 2;
732
					break;
733
				case 24:
734
					$start_octet = 1;
735
					break;
736
				default:
737
					$start_octet = 0;
738
					/* Add subnet bitmask to first octet */
739
					$revsubnet[0] .= '-' . $ifcfgsn;
740
					break;
741

    
742
			}
743

    
744
			$ptr_domain = '';
745
			for ($octet = 0; $octet <= 3; $octet++) {
746
				if ($octet < $start_octet) {
747
					continue;
748
				}
749
				$ptr_domain .= ((empty($ptr_domain) && $ptr_domain !== "0") ? '' : '.');
750
				$ptr_domain .= $revsubnet[$octet];
751
			}
752
			$ptr_domain .= ".in-addr.arpa";
753
			$newzone['ptr-domain'] = $ptr_domain;
754
			unset($ptr_domain, $revsubnet, $start_octet);
755
		}
756

    
757
		if (is_array($dhcpifconf['dnsserver']) && ($dhcpifconf['dnsserver'][0])) {
758
			$dnscfg .= "	option domain-name-servers " . join(",", $dhcpifconf['dnsserver']) . ";";
759
			if ($newzone['domain-name']) {
760
				$newzone['dns-servers'] = $dhcpifconf['dnsserver'];
761
			}
762
		} else if (isset($config['dnsmasq']['enable'])) {
763
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
764
			if ($newzone['domain-name'] && is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
765
				$newzone['dns-servers'] = $syscfg['dnsserver'];
766
			}
767
		} else if (isset($config['unbound']['enable'])) {
768
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
769
		} else if (!empty($dns_arrv4)) {
770
			$dnscfg .= "	option domain-name-servers " . join(",", $dns_arrv4) . ";";
771
			if ($newzone['domain-name']) {
772
				$newzone['dns-servers'] = $dns_arrv4;
773
			}
774
		}
775

    
776
		/* Create classes - These all contain comma separated lists. Join them into one
777
		   big comma separated string then split them all up. */
778
		$all_mac_strings = array();
779
		if (is_array($dhcpifconf['pool'])) {
780
			foreach ($all_pools as $poolconf) {
781
				$all_mac_strings[] = $poolconf['mac_allow'];
782
				$all_mac_strings[] = $poolconf['mac_deny'];
783
			}
784
		}
785
		$all_mac_strings[] = $dhcpifconf['mac_allow'];
786
		$all_mac_strings[] = $dhcpifconf['mac_deny'];
787
		if (!empty($all_mac_strings)) {
788
			$all_mac_list = array_unique(explode(',', implode(',', $all_mac_strings)));
789
			foreach ($all_mac_list as $mac) {
790
				if (empty($mac)) {
791
					continue;
792
				}
793
				$dhcpdconf .= 'class "' . str_replace(':', '', $mac) . '" {' . "\n";
794
				// Skip the first octet of the MAC address - for media type, typically Ethernet ("01") and match the rest.
795
				$dhcpdconf .= '	match if substring (hardware, 1, ' . (substr_count($mac, ':') + 1) . ') = ' . $mac . ';' . "\n";
796
				$dhcpdconf .= '}' . "\n";
797
			}
798
		}
799

    
800
		$dhcpdconf .= "subnet {$subnet} netmask {$subnetmask} {\n";
801

    
802
		// Setup pool options
803
		foreach ($all_pools as $all_pools_idx => $poolconf) {
804
			if (!(ip_in_subnet($poolconf['range']['from'], "{$subnet}/{$ifcfgsn}") && ip_in_subnet($poolconf['range']['to'], "{$subnet}/{$ifcfgsn}"))) {
805
				// If the user has changed the subnet from the interfaces page and applied,
806
				// but has not updated the DHCP range, then the range to/from of the pool can be outside the subnet.
807
				// This can also happen when implementing the batch of changes when the setup wizard reloads the new settings.
808
				$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);
809
				$do_file_notice = true;
810
				$conf_ipv4_address = $ifcfg['ipaddr'];
811
				$conf_ipv4_subnetmask = $ifcfg['subnet'];
812
				if (is_ipaddrv4($conf_ipv4_address) && is_subnet("{$conf_ipv4_address}/{$conf_ipv4_subnetmask}")) {
813
					$conf_subnet_base = gen_subnet($conf_ipv4_address, $conf_ipv4_subnetmask);
814
					if (ip_in_subnet($poolconf['range']['from'], "{$conf_subnet_base}/{$conf_ipv4_subnetmask}") &&
815
					    ip_in_subnet($poolconf['range']['to'], "{$conf_subnet_base}/{$conf_ipv4_subnetmask}")) {
816
						// Even though the running interface subnet does not match the pool range,
817
						// the interface subnet in the config file contains the pool range.
818
						// We are somewhere part-way through a settings reload, e.g. after running the setup wizard.
819
						// services_dhcpdv4_configure will be called again later when the new interface settings from
820
						// the config are applied and at that time everything will match up.
821
						// Ignore this pool on this interface for now and just log the error to the system log.
822
						log_error($error_msg);
823
						$do_file_notice = false;
824
					}
825
				}
826
				if ($do_file_notice) {
827
					file_notice("DHCP", $error_msg);
828
				}
829
				continue;
830
			}
831
			$dhcpdconf .= "	pool {\n";
832
			/* is failover dns setup? */
833
			if (is_array($poolconf['dnsserver']) && $poolconf['dnsserver'][0] <> "") {
834
				$dhcpdconf .= "		option domain-name-servers {$poolconf['dnsserver'][0]}";
835
				if ($poolconf['dnsserver'][1] <> "") {
836
					$dhcpdconf .= ",{$poolconf['dnsserver'][1]}";
837
				}
838
				if ($poolconf['dnsserver'][2] <> "") {
839
					$dhcpdconf .= ",{$poolconf['dnsserver'][2]}";
840
				}
841
				if ($poolconf['dnsserver'][3] <> "") {
842
					$dhcpdconf .= ",{$poolconf['dnsserver'][3]}";
843
				}
844
				$dhcpdconf .= ";\n";
845
			}
846

    
847
			/* allow/deny MACs */
848
			$mac_allow_list = array_unique(explode(',', $poolconf['mac_allow']));
849
			foreach ($mac_allow_list as $mac) {
850
				if (empty($mac)) {
851
					continue;
852
				}
853
				$dhcpdconf .= "		allow members of \"" . str_replace(':', '', $mac) . "\";\n";
854
			}
855
			$deny_action = "deny";
856
			if (isset($poolconf['nonak']) && empty($poolconf['failover_peerip'])) {
857
				$deny_action = "ignore";
858
			}
859
			$mac_deny_list = array_unique(explode(',', $poolconf['mac_deny']));
860
			foreach ($mac_deny_list as $mac) {
861
				if (empty($mac)) {
862
					continue;
863
				}
864
				$dhcpdconf .= "		$deny_action members of \"" . str_replace(':', '', $mac) . "\";\n";
865
			}
866

    
867
			if ($poolconf['failover_peerip'] <> "") {
868
				$dhcpdconf .= "		$deny_action dynamic bootp clients;\n";
869
			}
870

    
871
			if (isset($poolconf['denyunknown'])) {
872
				$dhcpdconf .= "		$deny_action unknown-clients;\n";
873
			}
874

    
875
			if ($poolconf['gateway'] && $poolconf['gateway'] != "none" && ($poolconf['gateway'] != $dhcpifconf['gateway'])) {
876
				$dhcpdconf .= "		option routers {$poolconf['gateway']};\n";
877
			}
878

    
879
			if ($dhcpifconf['failover_peerip'] <> "") {
880
				$dhcpdconf .= "		failover peer \"dhcp_{$dhcpif}\";\n";
881
			}
882

    
883
			$pdnscfg = "";
884

    
885
			if ($poolconf['domain'] && ($poolconf['domain'] != $dhcpifconf['domain'])) {
886
				$pdnscfg .= "		option domain-name \"{$poolconf['domain']}\";\n";
887
			}
888

    
889
			if (!empty($poolconf['domainsearchlist']) && ($poolconf['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
890
				$pdnscfg .= "		option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $poolconf['domainsearchlist'])) . "\";\n";
891
			}
892

    
893
			if (isset($poolconf['ddnsupdate'])) {
894
				if (($poolconf['ddnsdomain'] <> "") && ($poolconf['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
895
					$pdnscfg .= "		ddns-domainname \"{$poolconf['ddnsdomain']}\";\n";
896
				}
897
				$pdnscfg .= "		ddns-update-style interim;\n";
898
			}
899

    
900
			$dhcpdconf .= "{$pdnscfg}";
901

    
902
			// default-lease-time
903
			if ($poolconf['defaultleasetime'] && ($poolconf['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
904
				$dhcpdconf .= "		default-lease-time {$poolconf['defaultleasetime']};\n";
905
			}
906

    
907
			// max-lease-time
908
			if ($poolconf['maxleasetime'] && ($poolconf['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
909
				$dhcpdconf .= "		max-lease-time {$poolconf['maxleasetime']};\n";
910
			}
911

    
912
			// ignore bootp
913
			if (isset($poolconf['ignorebootp'])) {
914
				$dhcpdconf .= "		ignore bootp;\n";
915
			}
916

    
917
			// netbios-name*
918
			if (is_array($poolconf['winsserver']) && $poolconf['winsserver'][0] && ($poolconf['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
919
				$dhcpdconf .= "		option netbios-name-servers " . join(",", $poolconf['winsserver']) . ";\n";
920
				$dhcpdconf .= "		option netbios-node-type 8;\n";
921
			}
922

    
923
			// ntp-servers
924
			if (is_array($poolconf['ntpserver']) && $poolconf['ntpserver'][0] && ($poolconf['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
925
				$dhcpdconf .= "		option ntp-servers " . join(",", $poolconf['ntpserver']) . ";\n";
926
			}
927

    
928
			// tftp-server-name
929
			if (!empty($poolconf['tftp']) && ($poolconf['tftp'] != $dhcpifconf['tftp'])) {
930
				$dhcpdconf .= "		option tftp-server-name \"{$poolconf['tftp']}\";\n";
931
			}
932

    
933
			// Handle pool-specific options
934
			$dhcpdconf .= "\n";
935
			// Ignore the first pool, which is the "overall" pool when $all_pools_idx is 0 - those are put outside the pool block later
936
			if ($poolconf['numberoptions']['item'] && ($all_pools_idx > 0)) {
937
				// Use the "real" pool index from the config, excluding the "overall" pool, and based from 0.
938
				// This matches the way $poolidx was used when generating the $custoptions string earlier.
939
				$poolidx = $all_pools_idx - 1;
940
				foreach ($poolconf['numberoptions']['item'] as $itemidx => $item) {
941
					$item_value = base64_decode($item['value']);
942
					if (empty($item['type']) || $item['type'] == "text") {
943
						$dhcpdconf .= "	option custom-{$dhcpif}-{$poolidx}-{$itemidx} \"{$item_value}\";\n";
944
					} else {
945
						$dhcpdconf .= "	option custom-{$dhcpif}-{$poolidx}-{$itemidx} {$item_value};\n";
946
					}
947
				}
948
			}
949

    
950
			// ldap-server
951
			if (!empty($poolconf['ldap']) && ($poolconf['ldap'] != $dhcpifconf['ldap'])) {
952
				$dhcpdconf .= "		option ldap-server \"{$poolconf['ldap']}\";\n";
953
			}
954

    
955
			// net boot information
956
			if (isset($poolconf['netboot'])) {
957
				if (!empty($poolconf['nextserver']) && ($poolconf['nextserver'] != $dhcpifconf['nextserver'])) {
958
					$dhcpdconf .= "		next-server {$poolconf['nextserver']};\n";
959
				}
960
				if (!empty($poolconf['filename']) && ($poolconf['filename'] != $dhcpifconf['filename'])) {
961
					$dhcpdconf .= "		filename \"{$poolconf['filename']}\";\n";
962
				}
963
				if (!empty($poolconf['rootpath']) && ($poolconf['rootpath'] != $dhcpifconf['rootpath'])) {
964
					$dhcpdconf .= "		option root-path \"{$poolconf['rootpath']}\";\n";
965
				}
966
			}
967
			$dhcpdconf .= "		range {$poolconf['range']['from']} {$poolconf['range']['to']};\n";
968
			$dhcpdconf .= "	}\n\n";
969
		}
970
// End of settings inside pools
971

    
972
		if ($dhcpifconf['gateway'] && $dhcpifconf['gateway'] != "none") {
973
			$routers = $dhcpifconf['gateway'];
974
			$add_routers = true;
975
		} elseif ($dhcpifconf['gateway'] == "none") {
976
			$add_routers = false;
977
		} else {
978
			$add_routers = $enable_add_routers;
979
			$routers = $ifcfgip;
980
		}
981
		if ($add_routers) {
982
			$dhcpdconf .= "	option routers {$routers};\n";
983
		}
984

    
985
		$dhcpdconf .= <<<EOD
986
$dnscfg
987

    
988
EOD;
989
		// default-lease-time
990
		if ($dhcpifconf['defaultleasetime']) {
991
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
992
		}
993

    
994
		// max-lease-time
995
		if ($dhcpifconf['maxleasetime']) {
996
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
997
		}
998

    
999
		// netbios-name*
1000
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
1001
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
1002
			$dhcpdconf .= "	option netbios-node-type 8;\n";
1003
		}
1004

    
1005
		// ntp-servers
1006
		if (is_array($dhcpifconf['ntpserver']) && $dhcpifconf['ntpserver'][0]) {
1007
			$dhcpdconf .= "	option ntp-servers " . join(",", $dhcpifconf['ntpserver']) . ";\n";
1008
		}
1009

    
1010
		// tftp-server-name
1011
		if ($dhcpifconf['tftp'] <> "") {
1012
			$dhcpdconf .= "	option tftp-server-name \"{$dhcpifconf['tftp']}\";\n";
1013
		}
1014

    
1015
		// Handle option, number rowhelper values
1016
		$dhcpdconf .= "\n";
1017
		if ($dhcpifconf['numberoptions']['item']) {
1018
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
1019
				$item_value = base64_decode($item['value']);
1020
				if (empty($item['type']) || $item['type'] == "text") {
1021
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} \"{$item_value}\";\n";
1022
				} else {
1023
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} {$item_value};\n";
1024
				}
1025
			}
1026
		}
1027

    
1028
		// ldap-server
1029
		if ($dhcpifconf['ldap'] <> "") {
1030
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
1031
		}
1032

    
1033
		// net boot information
1034
		if (isset($dhcpifconf['netboot'])) {
1035
			if ($dhcpifconf['nextserver'] <> "") {
1036
				$dhcpdconf .= "	next-server {$dhcpifconf['nextserver']};\n";
1037
			}
1038
			if (!empty($dhcpifconf['filename']) && !empty($dhcpifconf['filename32']) && !empty($dhcpifconf['filename64'])) {
1039
				$dhcpdconf .= "	if option arch = 00:06 {\n";
1040
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename32']}\";\n";
1041
				$dhcpdconf .= "	} else if option arch = 00:07 {\n";
1042
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1043
				$dhcpdconf .= "	} else if option arch = 00:09 {\n";
1044
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1045
				$dhcpdconf .= "	} else {\n";
1046
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename']}\";\n";
1047
				$dhcpdconf .= "	}\n\n";
1048
			} elseif (!empty($dhcpifconf['filename'])) {
1049
				$dhcpdconf .= "	filename \"{$dhcpifconf['filename']}\";\n";
1050
			}
1051
			if (!empty($dhcpifconf['rootpath'])) {
1052
				$dhcpdconf .= "	option root-path \"{$dhcpifconf['rootpath']}\";\n";
1053
			}
1054
		}
1055

    
1056
		$dhcpdconf .= <<<EOD
1057
}
1058

    
1059
EOD;
1060

    
1061
		/* add static mappings */
1062
		if (is_array($dhcpifconf['staticmap'])) {
1063

    
1064
			$i = 0;
1065
			foreach ($dhcpifconf['staticmap'] as $sm) {
1066
				$dhcpdconf .= "host s_{$dhcpif}_{$i} {\n";
1067

    
1068
				if ($sm['mac']) {
1069
					$dhcpdconf .= "        hardware ethernet {$sm['mac']};\n";
1070
				}
1071

    
1072
				if ($sm['cid']) {
1073
					$dhcpdconf .= "        option dhcp-client-identifier \"{$sm['cid']}\";\n";
1074
				}
1075

    
1076
				if ($sm['ipaddr']) {
1077
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
1078
				}
1079

    
1080
				if ($sm['hostname']) {
1081
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1082
					$dhhostname = str_replace(".", "_", $dhhostname);
1083
					$dhcpdconf .= "	option host-name \"{$dhhostname}\";\n";
1084
				}
1085
				if ($sm['filename']) {
1086
					$dhcpdconf .= "	filename \"{$sm['filename']}\";\n";
1087
				}
1088

    
1089
				if ($sm['rootpath']) {
1090
					$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1091
				}
1092

    
1093
				if ($sm['gateway'] && ($sm['gateway'] != $dhcpifconf['gateway'])) {
1094
					$dhcpdconf .= "	option routers {$sm['gateway']};\n";
1095
				}
1096

    
1097
				$smdnscfg = "";
1098

    
1099
				if ($sm['domain'] && ($sm['domain'] != $dhcpifconf['domain'])) {
1100
					$smdnscfg .= "	option domain-name \"{$sm['domain']}\";\n";
1101
				}
1102

    
1103
				if (!empty($sm['domainsearchlist']) && ($sm['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
1104
					$smdnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $sm['domainsearchlist'])) . "\";\n";
1105
				}
1106

    
1107
				if (isset($sm['ddnsupdate'])) {
1108
					if (($sm['ddnsdomain'] <> "") && ($sm['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
1109
						$smdnscfg .= "		ddns-domainname \"{$sm['ddnsdomain']}\";\n";
1110
					}
1111
					$smdnscfg .= "		ddns-update-style interim;\n";
1112
				}
1113

    
1114
				if (is_array($sm['dnsserver']) && ($sm['dnsserver'][0]) && ($sm['dnsserver'][0] != $dhcpifconf['dnsserver'][0])) {
1115
					$smdnscfg .= "	option domain-name-servers " . join(",", $sm['dnsserver']) . ";\n";
1116
				}
1117
				$dhcpdconf .= "{$smdnscfg}";
1118

    
1119
				// default-lease-time
1120
				if ($sm['defaultleasetime'] && ($sm['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
1121
					$dhcpdconf .= "	default-lease-time {$sm['defaultleasetime']};\n";
1122
				}
1123

    
1124
				// max-lease-time
1125
				if ($sm['maxleasetime'] && ($sm['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
1126
					$dhcpdconf .= "	max-lease-time {$sm['maxleasetime']};\n";
1127
				}
1128

    
1129
				// netbios-name*
1130
				if (is_array($sm['winsserver']) && $sm['winsserver'][0] && ($sm['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
1131
					$dhcpdconf .= "	option netbios-name-servers " . join(",", $sm['winsserver']) . ";\n";
1132
					$dhcpdconf .= "	option netbios-node-type 8;\n";
1133
				}
1134

    
1135
				// ntp-servers
1136
				if (is_array($sm['ntpserver']) && $sm['ntpserver'][0] && ($sm['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
1137
					$dhcpdconf .= "	option ntp-servers " . join(",", $sm['ntpserver']) . ";\n";
1138
				}
1139

    
1140
				// tftp-server-name
1141
				if (!empty($sm['tftp']) && ($sm['tftp'] != $dhcpifconf['tftp'])) {
1142
					$dhcpdconf .= "	option tftp-server-name \"{$sm['tftp']}\";\n";
1143
				}
1144

    
1145
				$dhcpdconf .= "}\n";
1146
				$i++;
1147
			}
1148
		}
1149

    
1150
		$dhcpdifs[] = get_real_interface($dhcpif);
1151
		if ($newzone['domain-name']) {
1152
			if ($need_ddns_updates) {
1153
				$newzone['dns-servers'] = array($dhcpifconf['ddnsdomainprimary']);
1154
				$newzone['ddnsdomainkeyname'] = $dhcpifconf['ddnsdomainkeyname'];
1155
				$newzone['ddnsdomainkey'] = $dhcpifconf['ddnsdomainkey'];
1156
				$dhcpdconf .= dhcpdkey($dhcpifconf);
1157
			}
1158
			$ddns_zones[] = $newzone;
1159
		}
1160
	}
1161

    
1162
	if ($need_ddns_updates) {
1163
		$dhcpdconf .= "ddns-update-style interim;\n";
1164
		$dhcpdconf .= "update-static-leases on;\n";
1165

    
1166
		$dhcpdconf .= dhcpdzones($ddns_zones);
1167
	}
1168

    
1169
	/* write dhcpd.conf */
1170
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpd.conf", $dhcpdconf)) {
1171
		printf(gettext("Error: cannot open dhcpd.conf in services_dhcpdv4_configure().%s"), "\n");
1172
		unset($dhcpdconf);
1173
		return 1;
1174
	}
1175
	unset($dhcpdconf);
1176

    
1177
	/* create an empty leases database */
1178
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
1179
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
1180
	}
1181

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

    
1186
	/* fire up dhcpd in a chroot */
1187
	if (count($dhcpdifs) > 0) {
1188
		mwexec("/usr/local/sbin/dhcpd -user dhcpd -group _dhcp -chroot {$g['dhcpd_chroot_path']} -cf /etc/dhcpd.conf -pf {$g['varrun_path']}/dhcpd.pid " .
1189
			join(" ", $dhcpdifs));
1190
	}
1191

    
1192
	if (platform_booting()) {
1193
		print "done.\n";
1194
	}
1195

    
1196
	return 0;
1197
}
1198

    
1199
function dhcpdkey($dhcpifconf) {
1200
	$dhcpdconf = "";
1201
	if ($dhcpifconf['ddnsdomainkeyname'] <> "" && $dhcpifconf['ddnsdomainkey'] <> "") {
1202
		$dhcpdconf .= "key {$dhcpifconf['ddnsdomainkeyname']} {\n";
1203
		$dhcpdconf .= "	algorithm hmac-md5;\n";
1204
		$dhcpdconf .= "	secret {$dhcpifconf['ddnsdomainkey']};\n";
1205
		$dhcpdconf .= "}\n";
1206
	}
1207

    
1208
	return $dhcpdconf;
1209
}
1210

    
1211
function dhcpdzones($ddns_zones) {
1212
	$dhcpdconf = "";
1213

    
1214
	if (is_array($ddns_zones)) {
1215
		$added_zones = array();
1216
		foreach ($ddns_zones as $zone) {
1217
			if (!is_array($zone) || empty($zone) || !is_array($zone['dns-servers'])) {
1218
				continue;
1219
			}
1220
			$primary = $zone['dns-servers'][0];
1221
			$secondary = empty($zone['dns-servers'][1]) ? "" : $zone['dns-servers'][1];
1222

    
1223
			// Make sure we aren't using any invalid or IPv6 DNS servers.
1224
			if (!is_ipaddrv4($primary)) {
1225
				if (is_ipaddrv4($secondary)) {
1226
					$primary = $secondary;
1227
					$secondary = "";
1228
				} else {
1229
					continue;
1230
				}
1231
			}
1232

    
1233
			// We don't need to add zones multiple times.
1234
			if ($zone['domain-name'] && !in_array($zone['domain-name'], $added_zones)) {
1235
				$dhcpdconf .= "zone {$zone['domain-name']}. {\n";
1236
				$dhcpdconf .= "	primary {$primary};\n";
1237
				if (is_ipaddrv4($secondary)) {
1238
					$dhcpdconf .= "	secondary {$secondary};\n";
1239
				}
1240
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1241
					$dhcpdconf .= "	key {$zone['ddnsdomainkeyname']};\n";
1242
				}
1243
				$dhcpdconf .= "}\n";
1244
				$added_zones[] = $zone['domain-name'];
1245
			}
1246
			if ($zone['ptr-domain'] && !in_array($zone['ptr-domain'], $added_zones)) {
1247
				$dhcpdconf .= "zone {$zone['ptr-domain']} {\n";
1248
				$dhcpdconf .= "	primary {$primary};\n";
1249
				if (is_ipaddrv4($secondary)) {
1250
					$dhcpdconf .= "	secondary {$secondary};\n";
1251
				}
1252
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1253
					$dhcpdconf .= "	key {$zone['ddnsdomainkeyname']};\n";
1254
				}
1255
				$dhcpdconf .= "}\n";
1256
				$added_zones[] = $zone['ptr-domain'];
1257
			}
1258
		}
1259
	}
1260

    
1261
	return $dhcpdconf;
1262
}
1263

    
1264
function services_dhcpdv6_configure($blacklist = array()) {
1265
	global $config, $g;
1266

    
1267
	if ($g['services_dhcp_server_enable'] == false) {
1268
		return;
1269
	}
1270

    
1271
	if (isset($config['system']['developerspew'])) {
1272
		$mt = microtime();
1273
		echo "services_dhcpd_configure($if) being called $mt\n";
1274
	}
1275

    
1276
	/* kill any running dhcpd */
1277
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid")) {
1278
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid");
1279
	}
1280
	if (isvalidpid("{$g['varrun_path']}/dhcpleases6.pid")) {
1281
		killbypid("{$g['varrun_path']}/dhcpleases6.pid");
1282
	}
1283

    
1284
	/* DHCP enabled on any interfaces? */
1285
	if (!is_dhcpv6_server_enabled()) {
1286
		return 0;
1287
	}
1288

    
1289
	if (platform_booting()) {
1290
		if ($g['platform'] != $g['product_name']) {
1291
			/* restore the leases, if we have them */
1292
			if (file_exists("{$g['cf_conf_path']}/dhcp6leases.tgz")) {
1293
				$dhcprestore = "";
1294
				$dhcpreturn = "";
1295
				exec("cd /;LANG=C /usr/bin/tar -xzf {$g['cf_conf_path']}/dhcp6leases.tgz 2>&1", $dhcprestore, $dhcpreturn);
1296
				$dhcprestore = implode(" ", $dhcprestore);
1297
				if ($dhcpreturn <> 0) {
1298
					log_error(sprintf(gettext('DHCP leases v6 restore failed exited with %1$s, the error is: %2$s'), $dhcpreturn, $dhcprestore));
1299
				}
1300
			}
1301
		}
1302
	}
1303

    
1304
	$syscfg = $config['system'];
1305
	if (!is_array($config['dhcpdv6'])) {
1306
		$config['dhcpdv6'] = array();
1307
	}
1308
	$dhcpdv6cfg = $config['dhcpdv6'];
1309
	$Iflist = get_configured_interface_list();
1310
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
1311

    
1312

    
1313
	if (platform_booting()) {
1314
		echo "Starting DHCPv6 service...";
1315
	} else {
1316
		sleep(1);
1317
	}
1318

    
1319
	$custoptionsv6 = "";
1320
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1321
		if (is_array($dhcpv6ifconf['numberoptions']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1322
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1323
				$custoptionsv6 .= "option custom-{$dhcpv6if}-{$itemv6idx} code {$itemv6['number']} = text;\n";
1324
			}
1325
		}
1326
	}
1327

    
1328
	if (isset($dhcpv6ifconf['netboot']) && !empty($dhcpv6ifconf['bootfile_url'])) {
1329
		$custoptionsv6 .= "option dhcp6.bootfile-url code 59 = string;\n";
1330
	}
1331

    
1332
	$dhcpdv6conf = <<<EOD
1333

    
1334
option domain-name "{$syscfg['domain']}";
1335
option ldap-server code 95 = text;
1336
option domain-search-list code 119 = text;
1337
{$custoptionsv6}
1338
default-lease-time 7200;
1339
max-lease-time 86400;
1340
log-facility local7;
1341
one-lease-per-client true;
1342
deny duplicates;
1343
ping-check true;
1344
update-conflict-detection false;
1345

    
1346
EOD;
1347

    
1348
	if (!isset($dhcpv6ifconf['disableauthoritative'])) {
1349
		$dhcpdv6conf .= "authoritative;\n";
1350
	}
1351

    
1352
	if (isset($dhcpv6ifconf['alwaysbroadcast'])) {
1353
		$dhcpdv6conf .= "always-broadcast on\n";
1354
	}
1355

    
1356
	$dhcpdv6ifs = array();
1357

    
1358
	$dhcpv6num = 0;
1359
	$nsupdate = false;
1360

    
1361
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1362

    
1363
		$ddns_zones = array();
1364

    
1365
		$ifcfgv6 = $config['interfaces'][$dhcpv6if];
1366

    
1367
		if (!isset($dhcpv6ifconf['enable']) || !isset($Iflist[$dhcpv6if]) || !isset($ifcfgv6['enable'])) {
1368
			continue;
1369
		}
1370
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1371
		if (!is_ipaddrv6($ifcfgipv6)) {
1372
			continue;
1373
		}
1374
		$ifcfgsnv6 = get_interface_subnetv6($dhcpv6if);
1375
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1376

    
1377
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
1378
			$trackifname = $config['interfaces'][$ifname]['track6-interface'];
1379
			$trackcfg = $config['interfaces'][$trackifname];
1380
			$pdlen = 64 - $trackcfg['dhcp6-ia-pd-len'];
1381
		}
1382

    
1383
		if ($is_olsr_enabled == true) {
1384
			if ($dhcpv6ifconf['netmask']) {
1385
				$subnetmask = gen_subnet_maskv6($dhcpv6ifconf['netmask']);
1386
			}
1387
		}
1388

    
1389
		$dnscfgv6 = "";
1390

    
1391
		if ($dhcpv6ifconf['domain']) {
1392
			$dnscfgv6 .= "	option domain-name \"{$dhcpv6ifconf['domain']}\";\n";
1393
		}
1394

    
1395
		if ($dhcpv6ifconf['domainsearchlist'] <> "") {
1396
			$dnscfgv6 .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpv6ifconf['domainsearchlist'])) . "\";\n";
1397
		}
1398

    
1399
		if (isset($dhcpv6ifconf['ddnsupdate'])) {
1400
			if ($dhcpv6ifconf['ddnsdomain'] <> "") {
1401
				$dnscfgv6 .= "	ddns-domainname \"{$dhcpv6ifconf['ddnsdomain']}\";\n";
1402
			}
1403
			if (empty($dhcpv6ifconf['ddnsclientupdates'])) {
1404
				$ddnsclientupdates = 'allow';
1405
			} else {
1406
				$ddnsclientupdates = $dhcpv6ifconf['ddnsclientupdates'];
1407
			}
1408
			$dnscfgv6 .= "	{$ddnsclientupdates} client-updates;\n";
1409
			$nsupdate = true;
1410
		} else {
1411
			$dnscfgv6 .= "	do-forward-updates false;\n";
1412
		}
1413

    
1414
		if (is_array($dhcpv6ifconf['dnsserver']) && ($dhcpv6ifconf['dnsserver'][0])) {
1415
			$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dhcpv6ifconf['dnsserver']) . ";";
1416
		} else if (((isset($config['dnsmasq']['enable'])) || isset($config['unbound']['enable'])) && (is_ipaddrv6($ifcfgipv6))) {
1417
			$dnscfgv6 .= "	option dhcp6.name-servers {$ifcfgipv6};";
1418
		} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1419
			$dns_arrv6 = array();
1420
			foreach ($syscfg['dnsserver'] as $dnsserver) {
1421
				if (is_ipaddrv6($dnsserver)) {
1422
					$dns_arrv6[] = $dnsserver;
1423
				}
1424
			}
1425
			if (!empty($dns_arrv6)) {
1426
				$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dns_arrv6) . ";";
1427
			}
1428
		}
1429

    
1430
		if (!is_ipaddrv6($ifcfgipv6)) {
1431
			$ifcfgsnv6 = "64";
1432
			$subnetv6 = gen_subnetv6($dhcpv6ifconf['range']['from'], $ifcfgsnv6);
1433
		}
1434

    
1435
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1436

    
1437
		if (isset($dhcpv6ifconf['ddnsupdate']) &&
1438
		    !empty($dhcpv6ifconf['ddnsdomain'])) {
1439
			$newzone = array();
1440
			$newzone['domain-name'] = $dhcpv6ifconf['ddnsdomain'];
1441
			$newzone['dns-servers'][] = $dhcpv6ifconf['ddnsdomainprimary'];
1442
			$newzone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1443
			$newzone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1444
			$ddns_zones[] = $newzone;
1445
			if (isset($dhcpv6ifconf['ddnsreverse'])) {
1446
				$ptr_zones = get_v6_ptr_zones($subnetv6, $ifcfgsnv6);
1447
				foreach ($ptr_zones as $ptr_zone) {
1448
					$reversezone = array();
1449
					$reversezone['domain-name'] = $ptr_zone;
1450
					$reversezone['dns-servers'][] =
1451
					    $dhcpv6ifconf['ddnsdomainprimary'];
1452
					$ddns_zones[] = $reversezone;
1453
				}
1454
			}
1455
		}
1456

    
1457
		$dhcpdv6conf .= " {\n";
1458

    
1459
		$range_from = $dhcpv6ifconf['range']['from'];
1460
		$range_to = $dhcpv6ifconf['range']['to'];
1461
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
1462
			$range_from = merge_ipv6_delegated_prefix($ifcfgipv6, $range_from, $pdlen);
1463
			$range_to = merge_ipv6_delegated_prefix($ifcfgipv6, $range_to, $pdlen);
1464
		}
1465

    
1466
		$dhcpdv6conf .= <<<EOD
1467
	range6 {$range_from} {$range_to};
1468
$dnscfgv6
1469

    
1470
EOD;
1471

    
1472
		if (is_ipaddrv6($dhcpv6ifconf['prefixrange']['from']) && is_ipaddrv6($dhcpv6ifconf['prefixrange']['to'])) {
1473
			$dhcpdv6conf .= "	prefix6 {$dhcpv6ifconf['prefixrange']['from']} {$dhcpv6ifconf['prefixrange']['to']} /{$dhcpv6ifconf['prefixrange']['prefixlength']};\n";
1474
		}
1475
		if (is_ipaddrv6($dhcpv6ifconf['dns6ip'])) {
1476
			$dns6ip = $dhcpv6ifconf['dns6ip'];
1477
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1478
			    Net_IPv6::isInNetmask($dns6ip, '::', $pdlen)) {
1479
				$dns6ip = merge_ipv6_delegated_prefix($ifcfgipv6, $dns6ip, $pdlen);
1480
			}
1481
			$dhcpdv6conf .= "	option dhcp6.name-servers {$dns6ip};\n";
1482
		}
1483
		// default-lease-time
1484
		if ($dhcpv6ifconf['defaultleasetime']) {
1485
			$dhcpdv6conf .= "	default-lease-time {$dhcpv6ifconf['defaultleasetime']};\n";
1486
		}
1487

    
1488
		// max-lease-time
1489
		if ($dhcpv6ifconf['maxleasetime']) {
1490
			$dhcpdv6conf .= "	max-lease-time {$dhcpv6ifconf['maxleasetime']};\n";
1491
		}
1492

    
1493
		// ntp-servers
1494
		if (is_array($dhcpv6ifconf['ntpserver']) && $dhcpv6ifconf['ntpserver'][0]) {
1495
			$ntpservers = array();
1496
			foreach ($dhcpv6ifconf['ntpserver'] as $ntpserver) {
1497
				if (!is_ipaddrv6($ntpserver)) {
1498
					continue;
1499
				}
1500
				if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1501
				    Net_IPv6::isInNetmask($ntpserver, '::', $pdlen)) {
1502
					$ntpserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ntpserver, $pdlen);
1503
				}
1504
				$ntpservers[] = $ntpserver;
1505
			}
1506
			if (count($ntpservers) > 0) {
1507
				$dhcpdv6conf .= "        option dhcp6.sntp-servers " . join(",", $dhcpv6ifconf['ntpserver']) . ";\n";
1508
			}
1509
		}
1510
		// tftp-server-name
1511
		/* Needs ISC DHCPD support
1512
		 if ($dhcpv6ifconf['tftp'] <> "") {
1513
			$dhcpdv6conf .= "	option tftp-server-name \"{$dhcpv6ifconf['tftp']}\";\n";
1514
		 }
1515
		*/
1516

    
1517
		// Handle option, number rowhelper values
1518
		$dhcpdv6conf .= "\n";
1519
		if ($dhcpv6ifconf['numberoptions']['item']) {
1520
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1521
				$itemv6_value = base64_decode($itemv6['value']);
1522
				$dhcpdv6conf .= "	option custom-{$dhcpv6if}-{$itemv6idx} \"{$itemv6_value}\";\n";
1523
			}
1524
		}
1525

    
1526
		// ldap-server
1527
		if ($dhcpv6ifconf['ldap'] <> "") {
1528
			$ldapserver = $dhcpv6ifconf['ldap'];
1529
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1530
			    Net_IPv6::isInNetmask($ldapserver, '::', $pdlen)) {
1531
				$ldapserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ldapserver, $pdlen);
1532
			}
1533
			$dhcpdv6conf .= "	option ldap-server \"{$ldapserver}\";\n";
1534
		}
1535

    
1536
		// net boot information
1537
		if (isset($dhcpv6ifconf['netboot'])) {
1538
			if (!empty($dhcpv6ifconf['bootfile_url'])) {
1539
				$dhcpdv6conf .= "	option dhcp6.bootfile-url \"{$dhcpv6ifconf['bootfile_url']}\";\n";
1540
			}
1541
		}
1542

    
1543
		$dhcpdv6conf .= "}\n";
1544

    
1545
		/* add static mappings */
1546
		/* Needs to use DUID */
1547
		if (is_array($dhcpv6ifconf['staticmap'])) {
1548
			$i = 0;
1549
			foreach ($dhcpv6ifconf['staticmap'] as $sm) {
1550
				$dhcpdv6conf .= <<<EOD
1551
host s_{$dhcpv6if}_{$i} {
1552
	host-identifier option dhcp6.client-id {$sm['duid']};
1553

    
1554
EOD;
1555
				if ($sm['ipaddrv6']) {
1556
					$ipaddrv6 = $sm['ipaddrv6'];
1557
					if ($ifcfgv6['ipaddrv6'] == 'track6') {
1558
						$ipaddrv6 = merge_ipv6_delegated_prefix($ifcfgipv6, $ipaddrv6, $pdlen);
1559
					}
1560
					$dhcpdv6conf .= "	fixed-address6 {$ipaddrv6};\n";
1561
				}
1562

    
1563
				if ($sm['hostname']) {
1564
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1565
					$dhhostname = str_replace(".", "_", $dhhostname);
1566
					$dhcpdv6conf .= "	option host-name {$dhhostname};\n";
1567
				}
1568
				if ($sm['filename']) {
1569
					$dhcpdv6conf .= "	filename \"{$sm['filename']}\";\n";
1570
				}
1571

    
1572
				if ($sm['rootpath']) {
1573
					$dhcpdv6conf .= "	option root-path \"{$sm['rootpath']}\";\n";
1574
				}
1575

    
1576
				$dhcpdv6conf .= "}\n";
1577
				$i++;
1578
			}
1579
		}
1580

    
1581
		if ($dhcpv6ifconf['ddnsdomain']) {
1582
			$dhcpdv6conf .= dhcpdkey($dhcpv6ifconf);
1583
			$dhcpdv6conf .= dhcpdzones($ddns_zones);
1584
		}
1585

    
1586
		if ($config['dhcpdv6'][$dhcpv6if]['ramode'] <> "unmanaged" && isset($config['interfaces'][$dhcpv6if]['enable'])) {
1587
			if (preg_match("/poes/si", $dhcpv6if)) {
1588
				/* magic here */
1589
				$dhcpdv6ifs = array_merge($dhcpdv6ifs, get_pppoes_child_interfaces($dhcpv6if));
1590
			} else {
1591
				$realif = get_real_interface($dhcpv6if, "inet6");
1592
				if (stristr("$realif", "bridge")) {
1593
					$mac = get_interface_mac($realif);
1594
					$v6address = generate_ipv6_from_mac($mac);
1595
					/* Create link local address for bridges */
1596
					mwexec("/sbin/ifconfig {$realif} inet6 {$v6address}");
1597
				}
1598
				$realif = escapeshellcmd($realif);
1599
				$dhcpdv6ifs[] = $realif;
1600
			}
1601
		}
1602
	}
1603

    
1604
	if ($nsupdate) {
1605
		$dhcpdv6conf .= "ddns-update-style interim;\n";
1606
	} else {
1607
		$dhcpdv6conf .= "ddns-update-style none;\n";
1608
	}
1609

    
1610
	/* write dhcpdv6.conf */
1611
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf", $dhcpdv6conf)) {
1612
		log_error("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1613
		if (platform_booting()) {
1614
			printf("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1615
		}
1616
		unset($dhcpdv6conf);
1617
		return 1;
1618
	}
1619
	unset($dhcpdv6conf);
1620

    
1621
	/* create an empty leases v6 database */
1622
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases")) {
1623
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1624
	}
1625

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

    
1630
	/* fire up dhcpd in a chroot */
1631
	if (count($dhcpdv6ifs) > 0) {
1632
		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 " .
1633
			join(" ", $dhcpdv6ifs));
1634
		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");
1635
	}
1636
	if (platform_booting()) {
1637
		print gettext("done.") . "\n";
1638
	}
1639

    
1640
	return 0;
1641
}
1642

    
1643
function services_igmpproxy_configure() {
1644
	global $config, $g;
1645

    
1646
	/* kill any running igmpproxy */
1647
	killbyname("igmpproxy");
1648

    
1649
	if (!is_array($config['igmpproxy']['igmpentry']) || (count($config['igmpproxy']['igmpentry']) == 0)) {
1650
		return 1;
1651
	}
1652

    
1653
	$iflist = get_configured_interface_list();
1654

    
1655
	$igmpconf = <<<EOD
1656

    
1657
##------------------------------------------------------
1658
## Enable Quickleave mode (Sends Leave instantly)
1659
##------------------------------------------------------
1660
quickleave
1661

    
1662
EOD;
1663

    
1664
	foreach ($config['igmpproxy']['igmpentry'] as $igmpcf) {
1665
		unset($iflist[$igmpcf['ifname']]);
1666
		$realif = get_real_interface($igmpcf['ifname']);
1667
		if (empty($igmpcf['threshold'])) {
1668
			$threshld = 1;
1669
		} else {
1670
			$threshld = $igmpcf['threshold'];
1671
		}
1672
		$igmpconf .= "phyint {$realif} {$igmpcf['type']} ratelimit 0 threshold {$threshld}\n";
1673

    
1674
		if ($igmpcf['address'] <> "") {
1675
			$item = explode(" ", $igmpcf['address']);
1676
			foreach ($item as $iww) {
1677
				$igmpconf .= "altnet {$iww}\n";
1678
			}
1679
		}
1680
		$igmpconf .= "\n";
1681
	}
1682
	foreach ($iflist as $ifn) {
1683
		$realif = get_real_interface($ifn);
1684
		$igmpconf .= "phyint {$realif} disabled\n";
1685
	}
1686
	$igmpconf .= "\n";
1687

    
1688
	$igmpfl = fopen($g['tmp_path'] . "/igmpproxy.conf", "w");
1689
	if (!$igmpfl) {
1690
		log_error(gettext("Could not write Igmpproxy configuration file!"));
1691
		return;
1692
	}
1693
	fwrite($igmpfl, $igmpconf);
1694
	fclose($igmpfl);
1695
	unset($igmpconf);
1696

    
1697
	if (isset($config['syslog']['igmpxverbose'])) {
1698
		mwexec_bg("/usr/local/sbin/igmpproxy -v {$g['tmp_path']}/igmpproxy.conf");
1699
	} else {
1700
		mwexec_bg("/usr/local/sbin/igmpproxy {$g['tmp_path']}/igmpproxy.conf");
1701
	}
1702

    
1703
	log_error(gettext("Started IGMP proxy service."));
1704

    
1705
	return 0;
1706
}
1707

    
1708
function services_dhcrelay_configure() {
1709
	global $config, $g;
1710

    
1711
	if (isset($config['system']['developerspew'])) {
1712
		$mt = microtime();
1713
		echo "services_dhcrelay_configure() being called $mt\n";
1714
	}
1715

    
1716
	/* kill any running dhcrelay */
1717
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
1718

    
1719
	$dhcrelaycfg =& $config['dhcrelay'];
1720

    
1721
	/* DHCPRelay enabled on any interfaces? */
1722
	if (!isset($dhcrelaycfg['enable'])) {
1723
		return 0;
1724
	}
1725

    
1726
	if (platform_booting()) {
1727
		echo gettext("Starting DHCP relay service...");
1728
	} else {
1729
		sleep(1);
1730
	}
1731

    
1732
	$iflist = get_configured_interface_list();
1733

    
1734
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1735
	foreach ($dhcifaces as $dhcrelayif) {
1736
		if (!isset($iflist[$dhcrelayif]) ||
1737
		    link_interface_to_bridge($dhcrelayif)) {
1738
			continue;
1739
		}
1740

    
1741
		if (is_ipaddr(get_interface_ip($dhcrelayif))) {
1742
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1743
		}
1744
	}
1745

    
1746
	/*
1747
	 * In order for the relay to work, it needs to be active
1748
	 * on the interface in which the destination server sits.
1749
	 */
1750
	$srvips = explode(",", $dhcrelaycfg['server']);
1751
	if (!is_array($srvips)) {
1752
		log_error(gettext("No destination IP has been configured!"));
1753
		return;
1754
	}
1755

    
1756
	foreach ($srvips as $srcidx => $srvip) {
1757
		unset($destif);
1758
		foreach ($iflist as $ifname) {
1759
			$subnet = get_interface_ip($ifname);
1760
			if (!is_ipaddr($subnet)) {
1761
				continue;
1762
			}
1763
			$subnet .= "/" . get_interface_subnet($ifname);
1764
			if (ip_in_subnet($srvip, $subnet)) {
1765
				$destif = get_real_interface($ifname);
1766
				break;
1767
			}
1768
		}
1769
		if (!isset($destif)) {
1770
			foreach (get_staticroutes() as $rtent) {
1771
				if (ip_in_subnet($srvip, $rtent['network'])) {
1772
					$a_gateways = return_gateways_array(true);
1773
					$destif = $a_gateways[$rtent['gateway']]['interface'];
1774
					break;
1775
				}
1776
			}
1777
		}
1778

    
1779
		if (!isset($destif)) {
1780
			/* Create a array from the existing route table */
1781
			exec("/usr/bin/netstat -rnWf inet", $route_str);
1782
			array_shift($route_str);
1783
			array_shift($route_str);
1784
			array_shift($route_str);
1785
			array_shift($route_str);
1786
			$route_arr = array();
1787
			foreach ($route_str as $routeline) {
1788
				$items = preg_split("/[ ]+/i", $routeline);
1789
				if (is_subnetv4($items[0])) {
1790
					$subnet = $items[0];
1791
				} elseif (is_ipaddrv4($items[0])) {
1792
					$subnet = "{$items[0]}/32";
1793
				} else {
1794
					// Not a subnet or IP address, skip to the next line.
1795
					continue;
1796
				}
1797
				if (ip_in_subnet($srvip, $subnet)) {
1798
					$destif = trim($items[6]);
1799
					break;
1800
				}
1801
			}
1802
		}
1803

    
1804
		if (!isset($destif)) {
1805
			if (is_array($config['gateways']['gateway_item'])) {
1806
				foreach ($config['gateways']['gateway_item'] as $gateway) {
1807
					if (isset($gateway['defaultgw'])) {
1808
						$destif = get_real_interface($gateway['interface']);
1809
						break;
1810
					}
1811
				}
1812
			} else {
1813
				$destif = get_real_interface("wan");
1814
			}
1815
		}
1816

    
1817
		if (!empty($destif)) {
1818
			$dhcrelayifs[] = $destif;
1819
		}
1820
	}
1821
	$dhcrelayifs = array_unique($dhcrelayifs);
1822

    
1823
	/* fire up dhcrelay */
1824
	if (empty($dhcrelayifs)) {
1825
		log_error(gettext("No suitable interface found for running dhcrelay!"));
1826
		return; /* XXX */
1827
	}
1828

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

    
1831
	if (isset($dhcrelaycfg['agentoption'])) {
1832
		$cmd .= " -a -m replace";
1833
	}
1834

    
1835
	$cmd .= " " . implode(" ", $srvips);
1836
	mwexec($cmd);
1837
	unset($cmd);
1838

    
1839
	return 0;
1840
}
1841

    
1842
function services_dhcrelay6_configure() {
1843
	global $config, $g;
1844

    
1845
	if (isset($config['system']['developerspew'])) {
1846
		$mt = microtime();
1847
		echo "services_dhcrelay6_configure() being called $mt\n";
1848
	}
1849

    
1850
	/* kill any running dhcrelay */
1851
	killbypid("{$g['varrun_path']}/dhcrelay6.pid");
1852

    
1853
	$dhcrelaycfg =& $config['dhcrelay6'];
1854

    
1855
	/* DHCPv6 Relay enabled on any interfaces? */
1856
	if (!isset($dhcrelaycfg['enable'])) {
1857
		return 0;
1858
	}
1859

    
1860
	if (platform_booting()) {
1861
		echo gettext("Starting DHCPv6 relay service...");
1862
	} else {
1863
		sleep(1);
1864
	}
1865

    
1866
	$iflist = get_configured_interface_list();
1867

    
1868
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1869
	foreach ($dhcifaces as $dhcrelayif) {
1870
		if (!isset($iflist[$dhcrelayif]) ||
1871
		    link_interface_to_bridge($dhcrelayif)) {
1872
			continue;
1873
		}
1874

    
1875
		if (is_ipaddrv6(get_interface_ipv6($dhcrelayif))) {
1876
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1877
		}
1878
	}
1879
	$dhcrelayifs = array_unique($dhcrelayifs);
1880

    
1881
	/*
1882
	 * In order for the relay to work, it needs to be active
1883
	 * on the interface in which the destination server sits.
1884
	 */
1885
	$srvips = explode(",", $dhcrelaycfg['server']);
1886
	$srvifaces = array();
1887
	foreach ($srvips as $srcidx => $srvip) {
1888
		unset($destif);
1889
		foreach ($iflist as $ifname) {
1890
			$subnet = get_interface_ipv6($ifname);
1891
			if (!is_ipaddrv6($subnet)) {
1892
				continue;
1893
			}
1894
			$subnet .= "/" . get_interface_subnetv6($ifname);
1895
			if (ip_in_subnet($srvip, $subnet)) {
1896
				$destif = get_real_interface($ifname);
1897
				break;
1898
			}
1899
		}
1900
		if (!isset($destif)) {
1901
			if (is_array($config['staticroutes']['route'])) {
1902
				foreach ($config['staticroutes']['route'] as $rtent) {
1903
					if (ip_in_subnet($srvip, $rtent['network'])) {
1904
						$a_gateways = return_gateways_array(true);
1905
						$destif = $a_gateways[$rtent['gateway']]['interface'];
1906
						break;
1907
					}
1908
				}
1909
			}
1910
		}
1911

    
1912
		if (!isset($destif)) {
1913
			/* Create a array from the existing route table */
1914
			exec("/usr/bin/netstat -rnWf inet6", $route_str);
1915
			array_shift($route_str);
1916
			array_shift($route_str);
1917
			array_shift($route_str);
1918
			array_shift($route_str);
1919
			$route_arr = array();
1920
			foreach ($route_str as $routeline) {
1921
				$items = preg_split("/[ ]+/i", $routeline);
1922
				if (ip_in_subnet($srvip, $items[0])) {
1923
					$destif = trim($items[6]);
1924
					break;
1925
				}
1926
			}
1927
		}
1928

    
1929
		if (!isset($destif)) {
1930
			if (is_array($config['gateways']['gateway_item'])) {
1931
				foreach ($config['gateways']['gateway_item'] as $gateway) {
1932
					if (isset($gateway['defaultgw'])) {
1933
						$destif = get_real_interface($gateway['interface']);
1934
						break;
1935
					}
1936
				}
1937
			} else {
1938
				$destif = get_real_interface("wan");
1939
			}
1940
		}
1941

    
1942
		if (!empty($destif)) {
1943
			$srvifaces[] = "{$srvip}%{$destif}";
1944
		}
1945
	}
1946

    
1947
	/* fire up dhcrelay */
1948
	if (empty($dhcrelayifs) || empty($srvifaces)) {
1949
		log_error(gettext("No suitable interface found for running dhcrelay -6!"));
1950
		return; /* XXX */
1951
	}
1952

    
1953
	$cmd = "/usr/local/sbin/dhcrelay -6 -pf \"{$g['varrun_path']}/dhcrelay6.pid\"";
1954
	foreach ($dhcrelayifs as $dhcrelayif) {
1955
		$cmd .= " -l {$dhcrelayif}";
1956
	}
1957
	foreach ($srvifaces as $srviface) {
1958
		$cmd .= " -u \"{$srviface}\"";
1959
	}
1960
	mwexec($cmd);
1961
	unset($cmd);
1962

    
1963
	return 0;
1964
}
1965

    
1966
function services_dyndns_configure_client($conf) {
1967

    
1968
	if (!isset($conf['enable'])) {
1969
		return;
1970
	}
1971

    
1972
	/* load up the dyndns.class */
1973
	require_once("dyndns.class");
1974

    
1975
	$dns = new updatedns($dnsService = $conf['type'],
1976
		$dnsHost = $conf['host'],
1977
		$dnsDomain = $conf['domainname'],
1978
		$dnsUser = $conf['username'],
1979
		$dnsPass = $conf['password'],
1980
		$dnsWildcard = $conf['wildcard'],
1981
		$dnsMX = $conf['mx'],
1982
		$dnsIf = "{$conf['interface']}",
1983
		$dnsBackMX = NULL,
1984
		$dnsServer = NULL,
1985
		$dnsPort = NULL,
1986
		$dnsUpdateURL = "{$conf['updateurl']}",
1987
		$forceUpdate = $conf['force'],
1988
		$dnsZoneID = $conf['zoneid'],
1989
		$dnsTTL = $conf['ttl'],
1990
		$dnsResultMatch = "{$conf['resultmatch']}",
1991
		$dnsRequestIf = "{$conf['requestif']}",
1992
		$dnsID = "{$conf['id']}",
1993
		$dnsVerboseLog = $conf['verboselog'],
1994
		$curlIpresolveV4 = $conf['curl_ipresolve_v4'],
1995
		$curlSslVerifypeer = $conf['curl_ssl_verifypeer']);
1996
}
1997

    
1998
function services_dyndns_configure($int = "") {
1999
	global $config, $g;
2000
	if (isset($config['system']['developerspew'])) {
2001
		$mt = microtime();
2002
		echo "services_dyndns_configure() being called $mt\n";
2003
	}
2004

    
2005
	$dyndnscfg = $config['dyndnses']['dyndns'];
2006
	$gwgroups = return_gateway_groups_array();
2007
	if (is_array($dyndnscfg)) {
2008
		if (platform_booting()) {
2009
			echo gettext("Starting DynDNS clients...");
2010
		}
2011

    
2012
		foreach ($dyndnscfg as $dyndns) {
2013
			/*
2014
			 * If it's using a gateway group, check if interface is
2015
			 * the active gateway for that group
2016
			 */
2017
			$group_int = '';
2018
			if (is_array($gwgroups[$dyndns['interface']])) {
2019
				if (!empty($gwgroups[$dyndns['interface']][0]['vip'])) {
2020
					$group_int = $gwgroups[$dyndns['interface']][0]['vip'];
2021
				} else {
2022
					$group_int = $gwgroups[$dyndns['interface']][0]['int'];
2023
				}
2024
			}
2025
			if ((empty($int)) || ($int == $dyndns['interface']) || ($int == $group_int)) {
2026
				$dyndns['verboselog'] = isset($dyndns['verboselog']);
2027
				$dyndns['curl_ipresolve_v4'] = isset($dyndns['curl_ipresolve_v4']);
2028
				$dyndns['curl_ssl_verifypeer'] = isset($dyndns['curl_ssl_verifypeer']);
2029
				services_dyndns_configure_client($dyndns);
2030
				sleep(1);
2031
			}
2032
		}
2033

    
2034
		if (platform_booting()) {
2035
			echo gettext("done.") . "\n";
2036
		}
2037
	}
2038

    
2039
	return 0;
2040
}
2041

    
2042
function dyndnsCheckIP($int) {
2043
	global $config;
2044
	$ip_address = get_interface_ip($int);
2045
	if (is_private_ip($ip_address)) {
2046
		$gateways_status = return_gateways_status(true);
2047
		// If the gateway for this interface is down, then the external check cannot work.
2048
		// Avoid the long wait for the external check to timeout.
2049
		if (stristr($gateways_status[$config['interfaces'][$int]['gateway']]['status'], "down")) {
2050
			return "down";
2051
		}
2052
		$hosttocheck = "http://checkip.dyndns.org";
2053
		$ip_ch = curl_init($hosttocheck);
2054
		curl_setopt($ip_ch, CURLOPT_RETURNTRANSFER, 1);
2055
		curl_setopt($ip_ch, CURLOPT_SSL_VERIFYPEER, FALSE);
2056
		curl_setopt($ip_ch, CURLOPT_INTERFACE, 'host!' . $ip_address);
2057
		curl_setopt($ip_ch, CURLOPT_CONNECTTIMEOUT, '30');
2058
		curl_setopt($ip_ch, CURLOPT_TIMEOUT, 120);
2059
		curl_setopt($ip_ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
2060
		$ip_result_page = curl_exec($ip_ch);
2061
		curl_close($ip_ch);
2062
		$ip_result_decoded = urldecode($ip_result_page);
2063
		preg_match('=Current IP Address: (.*)</body>=siU', $ip_result_decoded, $matches);
2064
		$ip_address = trim($matches[1]);
2065
	}
2066
	return $ip_address;
2067
}
2068

    
2069
function services_dnsmasq_configure($restart_dhcp = true) {
2070
	global $config, $g;
2071
	$return = 0;
2072

    
2073
	// hard coded args: will be removed to avoid duplication if specified in custom_options
2074
	$standard_args = array(
2075
		"dns-forward-max" => "--dns-forward-max=5000",
2076
		"cache-size" => "--cache-size=10000",
2077
		"local-ttl" => "--local-ttl=1"
2078
	);
2079

    
2080

    
2081
	if (isset($config['system']['developerspew'])) {
2082
		$mt = microtime();
2083
		echo "services_dnsmasq_configure() being called $mt\n";
2084
	}
2085

    
2086
	/* kill any running dnsmasq */
2087
	if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) {
2088
		sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
2089
	}
2090

    
2091
	if (isset($config['dnsmasq']['enable'])) {
2092

    
2093
		if (platform_booting()) {
2094
			echo gettext("Starting DNS forwarder...");
2095
		} else {
2096
			sleep(1);
2097
		}
2098

    
2099
		/* generate hosts file */
2100
		if (system_hosts_generate() != 0) {
2101
			$return = 1;
2102
		}
2103

    
2104
		$args = "";
2105

    
2106
		if (isset($config['dnsmasq']['regdhcp'])) {
2107
			$args .= " --dhcp-hostsfile={$g['varetc_path']}/hosts ";
2108
		}
2109

    
2110
		/* Setup listen port, if non-default */
2111
		if (is_port($config['dnsmasq']['port'])) {
2112
			$args .= " --port={$config['dnsmasq']['port']} ";
2113
		}
2114

    
2115
		$listen_addresses = "";
2116
		if (isset($config['dnsmasq']['interface'])) {
2117
			$interfaces = explode(",", $config['dnsmasq']['interface']);
2118
			foreach ($interfaces as $interface) {
2119
				$if = get_real_interface($interface);
2120
				if (does_interface_exist($if)) {
2121
					$laddr = get_interface_ip($interface);
2122
					if (is_ipaddrv4($laddr)) {
2123
						$listen_addresses .= " --listen-address={$laddr} ";
2124
					}
2125
					$laddr6 = get_interface_ipv6($interface);
2126
					if (is_ipaddrv6($laddr6) && !isset($config['dnsmasq']['strictbind'])) {
2127
						/*
2128
						 * XXX: Since dnsmasq does not support link-local address
2129
						 * with scope specified. These checks are being done.
2130
						 */
2131
						if (is_linklocal($laddr6) && strstr($laddr6, "%")) {
2132
							$tmpaddrll6 = explode("%", $laddr6);
2133
							$listen_addresses .= " --listen-address={$tmpaddrll6[0]} ";
2134
						} else {
2135
							$listen_addresses .= " --listen-address={$laddr6} ";
2136
						}
2137
					}
2138
				}
2139
			}
2140
			if (!empty($listen_addresses)) {
2141
				$args .= " {$listen_addresses} ";
2142
				if (isset($config['dnsmasq']['strictbind'])) {
2143
					$args .= " --bind-interfaces ";
2144
				}
2145
			}
2146
		}
2147

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

    
2155
			// Build an array of domain overrides to help in checking for matches.
2156
			$override_a = array();
2157
			if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2158
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2159
					$override_a[$override['domain']] = "y";
2160
				}
2161
			}
2162

    
2163
			// Build an array of the private reverse lookup domain names
2164
			$reverse_domain_a = array("10.in-addr.arpa", "168.192.in-addr.arpa");
2165
			// Unfortunately the 172.16.0.0/12 range does not map nicely to the in-addr.arpa scheme.
2166
			for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) {
2167
				$reverse_domain_a[] = "$subnet_num.172.in-addr.arpa";
2168
			}
2169

    
2170
			// Set the --server parameter to nowhere for each reverse domain name that was not specifically specified in a domain override.
2171
			foreach ($reverse_domain_a as $reverse_domain) {
2172
				if (!isset($override_a[$reverse_domain])) {
2173
					$args .= " --server=/$reverse_domain/ ";
2174
				}
2175
			}
2176
			unset($override_a);
2177
			unset($reverse_domain_a);
2178
		}
2179

    
2180
		/* Setup forwarded domains */
2181
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2182
			foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2183
				if ($override['ip'] == "!") {
2184
					$override[ip] = "";
2185
				}
2186
				$args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
2187
			}
2188
		}
2189

    
2190
		/* Allow DNS Rebind for forwarded domains */
2191
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2192
			if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2193
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2194
					$args .= ' --rebind-domain-ok=/' . $override['domain'] . '/ ';
2195
				}
2196
			}
2197
		}
2198

    
2199
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2200
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2201
		}
2202

    
2203
		if (isset($config['dnsmasq']['strict_order'])) {
2204
			$args .= " --strict-order ";
2205
		}
2206

    
2207
		if (isset($config['dnsmasq']['domain_needed'])) {
2208
			$args .= " --domain-needed ";
2209
		}
2210

    
2211
		if ($config['dnsmasq']['custom_options']) {
2212
			foreach (preg_split('/\s+/', $config['dnsmasq']['custom_options']) as $c) {
2213
				$args .= " " . escapeshellarg("--{$c}");
2214
				$p = explode('=', $c);
2215
				if (array_key_exists($p[0], $standard_args)) {
2216
					unset($standard_args[$p[0]]);
2217
				}
2218
			}
2219
		}
2220
		$args .= ' ' . implode(' ', array_values($standard_args));
2221

    
2222
		/* run dnsmasq. Use "-C /dev/null" since we use command line args only (Issue #6730) */
2223
		$cmd = "/usr/local/sbin/dnsmasq --all-servers -C /dev/null {$dns_rebind} {$args}";
2224
		//log_error("dnsmasq command: {$cmd}");
2225
		mwexec_bg($cmd);
2226
		unset($args);
2227

    
2228
		system_dhcpleases_configure();
2229

    
2230
		if (platform_booting()) {
2231
			echo gettext("done.") . "\n";
2232
		}
2233
	}
2234

    
2235
	if (!platform_booting() && $restart_dhcp) {
2236
		if (services_dhcpd_configure() != 0) {
2237
			$return = 1;
2238
		}
2239
	}
2240

    
2241
	return $return;
2242
}
2243

    
2244
function services_unbound_configure($restart_dhcp = true) {
2245
	global $config, $g;
2246
	$return = 0;
2247

    
2248
	if (isset($config['system']['developerspew'])) {
2249
		$mt = microtime();
2250
		echo "services_unbound_configure() being called $mt\n";
2251
	}
2252

    
2253
	// kill any running Unbound instance
2254
	if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2255
		sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
2256
	}
2257

    
2258
	if (isset($config['unbound']['enable'])) {
2259
		if (platform_booting()) {
2260
			echo gettext("Starting DNS Resolver...");
2261
		} else {
2262
			sleep(1);
2263
		}
2264

    
2265
		/* generate hosts file */
2266
		if (system_hosts_generate() != 0) {
2267
			$return = 1;
2268
		}
2269

    
2270
		require_once('/etc/inc/unbound.inc');
2271
		sync_unbound_service();
2272
		if (platform_booting()) {
2273
			echo gettext("done.") . "\n";
2274
		}
2275

    
2276
		system_dhcpleases_configure();
2277
	}
2278

    
2279
	if (!platform_booting() && $restart_dhcp) {
2280
		if (services_dhcpd_configure() != 0) {
2281
			$return = 1;
2282
		}
2283
	}
2284

    
2285
	return $return;
2286
}
2287

    
2288
function services_snmpd_configure() {
2289
	global $config, $g;
2290
	if (isset($config['system']['developerspew'])) {
2291
		$mt = microtime();
2292
		echo "services_snmpd_configure() being called $mt\n";
2293
	}
2294

    
2295
	/* kill any running snmpd */
2296
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
2297
	sleep(2);
2298
	if (is_process_running("bsnmpd")) {
2299
		mwexec("/usr/bin/killall bsnmpd", true);
2300
	}
2301

    
2302
	if (isset($config['snmpd']['enable'])) {
2303

    
2304
		if (platform_booting()) {
2305
			echo gettext("Starting SNMP daemon... ");
2306
		}
2307

    
2308
		/* generate snmpd.conf */
2309
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
2310
		if (!$fd) {
2311
			printf(gettext("Error: cannot open snmpd.conf in services_snmpd_configure().%s"), "\n");
2312
			return 1;
2313
		}
2314

    
2315

    
2316
		$snmpdconf = <<<EOD
2317
location := "{$config['snmpd']['syslocation']}"
2318
contact := "{$config['snmpd']['syscontact']}"
2319
read := "{$config['snmpd']['rocommunity']}"
2320

    
2321
EOD;
2322

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

    
2329
EOD;
2330
		}
2331
*/
2332

    
2333

    
2334
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2335
			$snmpdconf .= <<<EOD
2336
# SNMP Trap support.
2337
traphost := {$config['snmpd']['trapserver']}
2338
trapport := {$config['snmpd']['trapserverport']}
2339
trap := "{$config['snmpd']['trapstring']}"
2340

    
2341

    
2342
EOD;
2343
		}
2344

    
2345
		$platform = trim(file_get_contents('/etc/platform'));
2346
		if (($platform == "pfSense") && ($g['product_name'] != "pfSense")) {
2347
			$platform = $g['product_name'];
2348
		}
2349
		$sysDescr = "{$g['product_name']} " . php_uname("n") .
2350
			" {$g['product_version']} {$platform} " . php_uname("s") .
2351
			" " . php_uname("r") . " " . php_uname("m");
2352

    
2353
		$snmpdconf .= <<<EOD
2354
system := 1     # pfSense
2355
%snmpd
2356
sysDescr			= "{$sysDescr}"
2357
begemotSnmpdDebugDumpPdus       = 2
2358
begemotSnmpdDebugSyslogPri      = 7
2359
begemotSnmpdCommunityString.0.1 = $(read)
2360

    
2361
EOD;
2362

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

    
2368
EOD;
2369
		}
2370
*/
2371

    
2372

    
2373
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2374
			$snmpdconf .= <<<EOD
2375
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
2376
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
2377
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
2378

    
2379
EOD;
2380
		}
2381

    
2382

    
2383
		$snmpdconf .= <<<EOD
2384
begemotSnmpdCommunityDisable    = 1
2385

    
2386
EOD;
2387

    
2388
		$bind_to_ip = "0.0.0.0";
2389
		if (isset($config['snmpd']['bindip'])) {
2390
			if (is_ipaddr($config['snmpd']['bindip'])) {
2391
				$bind_to_ip = $config['snmpd']['bindip'];
2392
			} else {
2393
				$if = get_real_interface($config['snmpd']['bindip']);
2394
				if (does_interface_exist($if)) {
2395
					$bind_to_ip = get_interface_ip($config['snmpd']['bindip']);
2396
				}
2397
			}
2398
		}
2399

    
2400
		if (is_port($config['snmpd']['pollport'])) {
2401
			$snmpdconf .= <<<EOD
2402
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
2403

    
2404
EOD;
2405

    
2406
		}
2407

    
2408
		$snmpdconf .= <<<EOD
2409
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
2410
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
2411

    
2412
# These are bsnmp macros not php vars.
2413
sysContact      = $(contact)
2414
sysLocation     = $(location)
2415
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
2416

    
2417
snmpEnableAuthenTraps = 2
2418

    
2419
EOD;
2420

    
2421
		if (is_array($config['snmpd']['modules'])) {
2422
			if (isset($config['snmpd']['modules']['mibii'])) {
2423
			$snmpdconf .= <<<EOD
2424
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
2425

    
2426
EOD;
2427
			}
2428

    
2429
			if (isset($config['snmpd']['modules']['netgraph'])) {
2430
				$snmpdconf .= <<<EOD
2431
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
2432
%netgraph
2433
begemotNgControlNodeName = "snmpd"
2434

    
2435
EOD;
2436
			}
2437

    
2438
			if (isset($config['snmpd']['modules']['pf'])) {
2439
				$snmpdconf .= <<<EOD
2440
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
2441

    
2442
EOD;
2443
			}
2444

    
2445
			if (isset($config['snmpd']['modules']['hostres'])) {
2446
				$snmpdconf .= <<<EOD
2447
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
2448

    
2449
EOD;
2450
			}
2451

    
2452
			if (isset($config['snmpd']['modules']['bridge'])) {
2453
				$snmpdconf .= <<<EOD
2454
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
2455
# config must end with blank line
2456

    
2457
EOD;
2458
			}
2459
			if (isset($config['snmpd']['modules']['ucd'])) {
2460
				$snmpdconf .= <<<EOD
2461
begemotSnmpdModulePath."ucd"     = "/usr/local/lib/snmp_ucd.so"
2462

    
2463
EOD;
2464
			}
2465
			if (isset($config['snmpd']['modules']['regex'])) {
2466
				$snmpdconf .= <<<EOD
2467
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"
2468

    
2469
EOD;
2470
			}
2471
		}
2472

    
2473
		fwrite($fd, $snmpdconf);
2474
		fclose($fd);
2475
		unset($snmpdconf);
2476

    
2477
		/* run bsnmpd */
2478
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
2479
			" -p {$g['varrun_path']}/snmpd.pid");
2480

    
2481
		if (platform_booting()) {
2482
			echo gettext("done.") . "\n";
2483
		}
2484
	}
2485

    
2486
	return 0;
2487
}
2488

    
2489
function services_dnsupdate_process($int = "", $updatehost = "", $forced = false) {
2490
	global $config, $g;
2491
	if (isset($config['system']['developerspew'])) {
2492
		$mt = microtime();
2493
		echo "services_dnsupdate_process() being called $mt\n";
2494
	}
2495

    
2496
	/* Dynamic DNS updating active? */
2497
	if (is_array($config['dnsupdates']['dnsupdate'])) {
2498
		$notify_text = "";
2499
		$gwgroups = return_gateway_groups_array();
2500
		foreach ($config['dnsupdates']['dnsupdate'] as $i => $dnsupdate) {
2501
			if (!isset($dnsupdate['enable'])) {
2502
				continue;
2503
			}
2504
			/*
2505
			 * If it's using a gateway group, check if interface is
2506
			 * the active gateway for that group
2507
			 */
2508
			$group_int = '';
2509
			if (is_array($gwgroups[$dnsupdate['interface']])) {
2510
				if (!empty($gwgroups[$dnsupdate['interface']][0]['vip'])) {
2511
					$group_int = $gwgroups[$dnsupdate['interface']][0]['vip'];
2512
				} else {
2513
					$group_int = $gwgroups[$dnsupdate['interface']][0]['int'];
2514
				}
2515
			}
2516
			if (!empty($int) && ($int != $dnsupdate['interface']) && ($int != $group_int)) {
2517
				continue;
2518
			}
2519
			if (!empty($updatehost) && ($updatehost != $dnsupdate['host'])) {
2520
				continue;
2521
			}
2522

    
2523
			/* determine interface name */
2524
			$if = get_failover_interface($dnsupdate['interface']);
2525

    
2526
			if (isset($dnsupdate['usepublicip'])) {
2527
				$wanip = dyndnsCheckIP($if);
2528
			} else {
2529
				$wanip = get_interface_ip($if);
2530
			}
2531

    
2532
			$wanipv6 = get_interface_ipv6($if);
2533
			$cacheFile = "{$g['conf_path']}/dyndns_{$dnsupdate['interface']}_rfc2136_" . escapeshellarg($dnsupdate['host']) . "_{$dnsupdate['server']}.cache";
2534
			$currentTime = time();
2535

    
2536
			if ($wanip || $wanipv6) {
2537
				$keyname = $dnsupdate['keyname'];
2538
				/* trailing dot */
2539
				if (substr($keyname, -1) != ".") {
2540
					$keyname .= ".";
2541
				}
2542

    
2543
				$hostname = $dnsupdate['host'];
2544
				/* trailing dot */
2545
				if (substr($hostname, -1) != ".") {
2546
					$hostname .= ".";
2547
				}
2548

    
2549
				/* write private key file
2550
				   this is dumb - public and private keys are the same for HMAC-MD5,
2551
				   but nsupdate insists on having both */
2552
				$fd = fopen("{$g['varetc_path']}/K{$i}{$keyname}+157+00000.private", "w");
2553
				$privkey = <<<EOD
2554
Private-key-format: v1.2
2555
Algorithm: 157 (HMAC)
2556
Key: {$dnsupdate['keydata']}
2557

    
2558
EOD;
2559
				fwrite($fd, $privkey);
2560
				fclose($fd);
2561

    
2562
				/* write public key file */
2563
				if ($dnsupdate['keytype'] == "zone") {
2564
					$flags = 257;
2565
					$proto = 3;
2566
				} else if ($dnsupdate['keytype'] == "host") {
2567
					$flags = 513;
2568
					$proto = 3;
2569
				} else if ($dnsupdate['keytype'] == "user") {
2570
					$flags = 0;
2571
					$proto = 2;
2572
				}
2573

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

    
2578
				/* generate update instructions */
2579
				$upinst = "";
2580
				if (!empty($dnsupdate['server'])) {
2581
					$upinst .= "server {$dnsupdate['server']}\n";
2582
				}
2583

    
2584
				if (file_exists($cacheFile)) {
2585
					list($cachedipv4, $cacheTimev4) = explode("|", file_get_contents($cacheFile));
2586
				}
2587
				if (file_exists("{$cacheFile}.ipv6")) {
2588
					list($cachedipv6, $cacheTimev6) = explode("|", file_get_contents("{$cacheFile}.ipv6"));
2589
				}
2590

    
2591
				// 25 Days
2592
				$maxCacheAgeSecs = 25 * 24 * 60 * 60;
2593
				$need_update = false;
2594

    
2595
				conf_mount_rw();
2596
				/* Update IPv4 if we have it. */
2597
				if (is_ipaddrv4($wanip) && $dnsupdate['recordtype'] != "AAAA") {
2598
					if (($wanip != $cachedipv4) || (($currentTime - $cacheTimev4) > $maxCacheAgeSecs) || $forced) {
2599
						$upinst .= "update delete {$dnsupdate['host']}. A\n";
2600
						$upinst .= "update add {$dnsupdate['host']}. {$dnsupdate['ttl']} A {$wanip}\n";
2601
						$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";
2602
						@file_put_contents($cacheFile, "{$wanip}|{$currentTime}");
2603
						log_error(sprintf(gettext('phpDynDNS: updating cache file %1$s: %2$s'), $cacheFile, $wanip));
2604
						$need_update = true;
2605
					} else {
2606
						log_error(sprintf(gettext("phpDynDNS: Not updating %s A record because the IP address has not changed."), $dnsupdate['host']));
2607
					}
2608
				} else {
2609
					@unlink($cacheFile);
2610
				}
2611

    
2612
				/* Update IPv6 if we have it. */
2613
				if (is_ipaddrv6($wanipv6) && $dnsupdate['recordtype'] != "A") {
2614
					if (($wanipv6 != $cachedipv6) || (($currentTime - $cacheTimev6) > $maxCacheAgeSecs) || $forced) {
2615
						$upinst .= "update delete {$dnsupdate['host']}. AAAA\n";
2616
						$upinst .= "update add {$dnsupdate['host']}. {$dnsupdate['ttl']} AAAA {$wanipv6}\n";
2617
						$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";
2618
						@file_put_contents("{$cacheFile}.ipv6", "{$wanipv6}|{$currentTime}");
2619
						log_error(sprintf(gettext('phpDynDNS: updating cache file %1$s.ipv6: %2$s'), $cacheFile, $wanipv6));
2620
						$need_update = true;
2621
					} else {
2622
						log_error(sprintf(gettext("phpDynDNS: Not updating %s AAAA record because the IPv6 address has not changed."), $dnsupdate['host']));
2623
					}
2624
				} else {
2625
					@unlink("{$cacheFile}.ipv6");
2626
				}
2627
				conf_mount_ro();
2628

    
2629
				$upinst .= "\n";	/* mind that trailing newline! */
2630

    
2631
				if ($need_update) {
2632
					@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}", $upinst);
2633
					unset($upinst);
2634
					/* invoke nsupdate */
2635
					$cmd = "/usr/local/bin/nsupdate -k {$g['varetc_path']}/K{$i}{$keyname}+157+00000.key";
2636
					if (isset($dnsupdate['usetcp'])) {
2637
						$cmd .= " -v";
2638
					}
2639
					$cmd .= " {$g['varetc_path']}/nsupdatecmds{$i}";
2640
					mwexec_bg($cmd);
2641
					unset($cmd);
2642
				}
2643
			}
2644
		}
2645
		if (!empty($notify_text)) {
2646
			notify_all_remote($notify_text);
2647
		}
2648
	}
2649

    
2650
	return 0;
2651
}
2652

    
2653
/* configure cron service */
2654
function configure_cron() {
2655
	global $g, $config;
2656

    
2657
	conf_mount_rw();
2658
	/* preserve existing crontab entries */
2659
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2660

    
2661
	for ($i = 0; $i < count($crontab_contents); $i++) {
2662
		$cron_item =& $crontab_contents[$i];
2663
		if (strpos($cron_item, "# pfSense specific crontab entries") !== false) {
2664
			array_splice($crontab_contents, $i - 1);
2665
			break;
2666
		}
2667
	}
2668
	$crontab_contents = implode("\n", $crontab_contents) . "\n";
2669

    
2670

    
2671
	if (is_array($config['cron']['item'])) {
2672
		$crontab_contents .= "#\n";
2673
		$crontab_contents .= "# pfSense specific crontab entries\n";
2674
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
2675
		$crontab_contents .= "#\n";
2676

    
2677
		if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) {
2678
			$http_proxy = $config['system']['proxyurl'];
2679
			if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) {
2680
				$http_proxy .= ':' . $config['system']['proxyport'];
2681
			}
2682
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
2683
		}
2684

    
2685
		foreach ($config['cron']['item'] as $item) {
2686
			$crontab_contents .= "\n{$item['minute']}\t";
2687
			$crontab_contents .= "{$item['hour']}\t";
2688
			$crontab_contents .= "{$item['mday']}\t";
2689
			$crontab_contents .= "{$item['month']}\t";
2690
			$crontab_contents .= "{$item['wday']}\t";
2691
			$crontab_contents .= "{$item['who']}\t";
2692
			$crontab_contents .= "{$item['command']}";
2693
		}
2694

    
2695
		$crontab_contents .= "\n#\n";
2696
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
2697
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
2698
		$crontab_contents .= "#\n\n";
2699
	}
2700

    
2701
	/* please maintain the newline at the end of file */
2702
	file_put_contents("/etc/crontab", $crontab_contents);
2703
	unset($crontab_contents);
2704

    
2705
	/* make sure that cron is running and start it if it got killed somehow */
2706
	if (!is_process_running("cron")) {
2707
		exec("cd /tmp && /usr/sbin/cron -s 2>/dev/null");
2708
	} else {
2709
	/* do a HUP kill to force sync changes */
2710
		sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP");
2711
	}
2712

    
2713
	conf_mount_ro();
2714
}
2715

    
2716
function upnp_action ($action) {
2717
	global $g, $config;
2718
	switch ($action) {
2719
		case "start":
2720
			if (file_exists('/var/etc/miniupnpd.conf')) {
2721
				@unlink("{$g['varrun_path']}/miniupnpd.pid");
2722
				mwexec_bg("/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf -P {$g['varrun_path']}/miniupnpd.pid");
2723
			}
2724
			break;
2725
		case "stop":
2726
			killbypid("{$g['varrun_path']}/miniupnpd.pid");
2727
			while ((int)exec("/bin/pgrep -a miniupnpd | wc -l") > 0) {
2728
				mwexec('/usr/bin/killall miniupnpd 2>/dev/null', true);
2729
			}
2730
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
2731
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
2732
			break;
2733
		case "restart":
2734
			upnp_action('stop');
2735
			upnp_action('start');
2736
			break;
2737
	}
2738
}
2739

    
2740
function upnp_start() {
2741
	global $config;
2742

    
2743
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
2744
		return;
2745
	}
2746

    
2747
	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
2748
		echo gettext("Starting UPnP service... ");
2749
		require_once('/usr/local/pkg/miniupnpd.inc');
2750
		sync_package_miniupnpd();
2751
		echo "done.\n";
2752
	}
2753
}
2754

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

    
2758
	$is_installed = false;
2759
	$cron_changed = true;
2760

    
2761
	if (!is_array($config['cron'])) {
2762
		$config['cron'] = array();
2763
	}
2764
	if (!is_array($config['cron']['item'])) {
2765
		$config['cron']['item'] = array();
2766
	}
2767

    
2768
	$x = 0;
2769
	foreach ($config['cron']['item'] as $item) {
2770
		if (strstr($item['command'], $command)) {
2771
			$is_installed = true;
2772
			break;
2773
		}
2774
		$x++;
2775
	}
2776

    
2777
	if ($active) {
2778
		$cron_item = array();
2779
		$cron_item['minute'] = $minute;
2780
		$cron_item['hour'] = $hour;
2781
		$cron_item['mday'] = $monthday;
2782
		$cron_item['month'] = $month;
2783
		$cron_item['wday'] = $weekday;
2784
		$cron_item['who'] = $who;
2785
		$cron_item['command'] = $command;
2786
		if (!$is_installed) {
2787
			$config['cron']['item'][] = $cron_item;
2788
			write_config(sprintf(gettext("Installed cron job for %s"), $command));
2789
		} else {
2790
			if ($config['cron']['item'][$x] == $cron_item) {
2791
				$cron_changed = false;
2792
				log_error(sprintf(gettext("Checked cron job for %s, no change needed"), $command));
2793
			} else {
2794
				$config['cron']['item'][$x] = $cron_item;
2795
				write_config(sprintf(gettext("Updated cron job for %s"), $command));
2796
			}
2797
		}
2798
	} else {
2799
		if ($is_installed == true) {
2800
			unset($config['cron']['item'][$x]);
2801
			write_config(sprintf(gettext("Removed cron job for %s"), $command));
2802
		}
2803
	}
2804

    
2805
	if ($cron_changed) {
2806
		configure_cron();
2807
	}
2808
}
2809

    
2810
?>
(49-49/65)