Project

General

Profile

Download (110 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * services.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2004-2013 BSD Perimeter
7
 * Copyright (c) 2013-2016 Electric Sheep Fencing
8
 * Copyright (c) 2014-2022 Rubicon Communications, LLC (Netgate)
9
 * All rights reserved.
10
 *
11
 * originally part of m0n0wall (http://m0n0.ch/wall)
12
 * Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>.
13
 * All rights reserved.
14
 *
15
 * Licensed under the Apache License, Version 2.0 (the "License");
16
 * you may not use this file except in compliance with the License.
17
 * You may obtain a copy of the License at
18
 *
19
 * http://www.apache.org/licenses/LICENSE-2.0
20
 *
21
 * Unless required by applicable law or agreed to in writing, software
22
 * distributed under the License is distributed on an "AS IS" BASIS,
23
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24
 * See the License for the specific language governing permissions and
25
 * limitations under the License.
26
 */
27

    
28

    
29
define('DYNDNS_PROVIDER_VALUES', 'all-inkl azure azurev6 citynetwork cloudflare cloudflare-v6 cloudns custom custom-v6 desec desec-v6 digitalocean digitalocean-v6 dnsexit dnsimple dnsimple-v6 dnsmadeeasy dnsomatic domeneshop domeneshop-v6 dreamhost dreamhost-v6 duiadns duiadns-v6 dyfi dyndns dyndns-custom dyndns-static dyns dynv6 dynv6-v6 easydns easydns-v6 eurodns freedns freedns-v6 freedns2 freedns2-v6 glesys gandi-livedns gandi-livedns-v6 godaddy godaddy-v6 googledomains gratisdns he-net he-net-v6 he-net-tunnelbroker hover linode linode-v6 loopia mythicbeasts mythicbeasts-v6 name.com name.com-v6 namecheap nicru nicru-v6 noip noip-v6 noip-free noip-free-v6 onecom onecom-v6 ods opendns ovh-dynhost route53 route53-v6 selfhost spdyn spdyn-v6 strato yandex yandex-v6 zoneedit');
30
define('DYNDNS_PROVIDER_DESCRIPTIONS', 'All-Inkl.com,Azure DNS,Azure DNS (v6),City Network,Cloudflare,Cloudflare (v6),ClouDNS,Custom,Custom (v6),deSEC,deSEC (v6),DigitalOcean,DigitalOcean (v6),DNSexit,DNSimple,DNSimple (v6),DNS Made Easy,DNS-O-Matic,Domeneshop,Domeneshop (v6),DreamHost,Dreamhost (v6),DuiaDns.net,DuiaDns.net (v6),DY.fi,DynDNS (dynamic),DynDNS (custom),DynDNS (static),DyNS,Dynv6,Dynv6 (v6),easyDNS,easyDNS (v6),Euro Dns,freeDNS,freeDNS (v6),freeDNS API Version 2, freeDNS API Version 2 (v6),GleSYS,Gandi Live DNS,Gandi Live DNS (v6),GoDaddy,GoDaddy (v6),Google Domains,GratisDNS,HE.net,HE.net (v6),HE.net Tunnelbroker,Hover,Linode,Linode (v6),Loopia,Mythic Beasts,Mythic Beasts (v6),Name.com,Name.com (v6),Namecheap,NIC.RU,NIC.RU (v6),No-IP,No-IP (v6),No-IP (free),No-IP (free-v6),One.com,One.com (v6),ODS.org,OpenDNS,OVH DynHOST,Route 53,Route 53 (v6),SelfHost,SPDYN,SPDYN (v6),Strato,Yandex,Yandex (v6),ZoneEdit');
31

    
32
/* implement ipv6 route advertising daemon */
33
function services_radvd_configure($blacklist = array()) {
34
	global $config, $g;
35

    
36
	if (isset($config['system']['developerspew'])) {
37
		$mt = microtime();
38
		echo "services_radvd_configure() being called $mt\n";
39
	}
40

    
41
	if (!is_array($config['dhcpdv6'])) {
42
		$config['dhcpdv6'] = array();
43
	}
44

    
45
	$Iflist = get_configured_interface_list();
46
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
47

    
48
	$radvdconf = "# Automatically Generated, do not edit\n";
49

    
50
	/* Process all links which need the router advertise daemon */
51
	$radvdifs = array();
52

    
53
	/* handle manually configured DHCP6 server settings first */
54
	foreach ($config['dhcpdv6'] as $dhcpv6if => $dhcpv6ifconf) {
55
		if (!is_array($config['interfaces'][$dhcpv6if])) {
56
			continue;
57
		}
58
		if (!isset($config['interfaces'][$dhcpv6if]['enable'])) {
59
			continue;
60
		}
61

    
62
		/* Do not put in the config an interface which is down */
63
		if (isset($blacklist[$dhcpv6if])) {
64
			continue;
65
		}
66
		if (!isset($dhcpv6ifconf['ramode'])) {
67
			$dhcpv6ifconf['ramode'] = $dhcpv6ifconf['mode'];
68
		}
69

    
70
		/* are router advertisements enabled? */
71
		if ($dhcpv6ifconf['ramode'] == "disabled") {
72
			continue;
73
		}
74

    
75
		if (!isset($dhcpv6ifconf['rapriority'])) {
76
			$dhcpv6ifconf['rapriority'] = "medium";
77
		}
78

    
79
		$racarpif = false;
80
		$rasrcaddr = "";
81
		/* check if binding to CARP IP */
82
		if (!empty($dhcpv6ifconf['rainterface']) && strstr($dhcpv6ifconf['rainterface'], "_vip")) {
83
			if (get_carp_interface_status($dhcpv6ifconf['rainterface']) == "MASTER") {
84
				if (is_linklocal(get_configured_vip_ipv6($dhcpv6ifconf['rainterface']))) {
85
					$rasrcaddr = get_configured_vip_ipv6($dhcpv6ifconf['rainterface']);
86
				} else {
87
					$dhcpv6if = $dhcpv6ifconf['rainterface'];
88
					$racarpif = true;
89
				}
90
			} else {
91
				continue;
92
			}
93
		}
94

    
95
		$realif = get_real_interface($dhcpv6if, "inet6");
96

    
97
		if (isset($radvdifs[$realif])) {
98
			continue;
99
		}
100

    
101
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
102
		if (!is_ipaddrv6($ifcfgipv6)) {
103
			continue;
104
		}
105

    
106
		$ifcfgsnv6 = get_interface_subnetv6($dhcpv6if);
107
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
108
		if (!is_subnetv6($subnetv6 . "/" . $ifcfgsnv6)) {
109
			log_error("radvd: skipping configuration for interface $dhcpv6if because its subnet or prefix length is invalid.");
110
			continue;
111
		}
112
		$radvdifs[$realif] = $realif;
113

    
114
		$radvdconf .= "# Generated for DHCPv6 Server $dhcpv6if\n";
115
		$radvdconf .= "interface {$realif} {\n";
116
		if (strstr($realif, "ovpn")) {
117
			$radvdconf .= "\tUnicastOnly on;\n";
118
		}
119
		$radvdconf .= "\tAdvSendAdvert on;\n";
120

    
121
		if ($rasrcaddr) {
122
			$radvdconf .= "\tAdvRASrcAddress {\n";
123
			$radvdconf .= "\t\t{$rasrcaddr};\n";
124
			$radvdconf .= "\t};\n";
125
		}
126

    
127
		if (is_numericint($dhcpv6ifconf['raminrtradvinterval'])) {
128
			$radvdconf .= "\tMinRtrAdvInterval {$dhcpv6ifconf['raminrtradvinterval']};\n";
129
		} else {
130
			$radvdconf .= "\tMinRtrAdvInterval 200;\n";
131
		}
132

    
133
		if (is_numericint($dhcpv6ifconf['ramaxrtradvinterval'])) {
134
			$ramaxrtradvinterval = $dhcpv6ifconf['ramaxrtradvinterval'];
135
		} else {
136
			$ramaxrtradvinterval = 600;
137
		}
138
		$radvdconf .= "\tMaxRtrAdvInterval {$ramaxrtradvinterval};\n";
139
		if (is_numericint($dhcpv6ifconf['raadvdefaultlifetime'])) {
140
			$raadvdefaultlifetime = $dhcpv6ifconf['raadvdefaultlifetime'];
141
		} else {
142
			$raadvdefaultlifetime = $ramaxrtradvinterval * 3;
143
		}
144
		$radvdconf .= "\tAdvDefaultLifetime {$raadvdefaultlifetime};\n";
145

    
146
		$mtu = get_interface_mtu($realif);
147
		if (is_numeric($mtu)) {
148
			$radvdconf .= "\tAdvLinkMTU {$mtu};\n";
149
		} else {
150
			$radvdconf .= "\tAdvLinkMTU 1280;\n";
151
		}
152
		switch ($dhcpv6ifconf['rapriority']) {
153
			case "low":
154
				$radvdconf .= "\tAdvDefaultPreference low;\n";
155
				break;
156
			case "high":
157
				$radvdconf .= "\tAdvDefaultPreference high;\n";
158
				break;
159
			default:
160
				$radvdconf .= "\tAdvDefaultPreference medium;\n";
161
				break;
162
		}
163
		switch ($dhcpv6ifconf['ramode']) {
164
			case "managed":
165
			case "assist":
166
				$radvdconf .= "\tAdvManagedFlag on;\n";
167
				$radvdconf .= "\tAdvOtherConfigFlag on;\n";
168
				break;
169
			case "stateless_dhcp":
170
				$radvdconf .= "\tAdvManagedFlag off;\n";
171
				$radvdconf .= "\tAdvOtherConfigFlag on;\n";
172
				break;
173
		}
174
		$radvdconf .= "\tprefix {$subnetv6}/{$ifcfgsnv6} {\n";
175
		if ($racarpif == true || $rasrcaddr) {
176
			$radvdconf .= "\t\tDeprecatePrefix off;\n";
177
		} else {
178
			$radvdconf .= "\t\tDeprecatePrefix on;\n";
179
		}
180
		switch ($dhcpv6ifconf['ramode']) {
181
			case "managed":
182
				$radvdconf .= "\t\tAdvOnLink on;\n";
183
				$radvdconf .= "\t\tAdvAutonomous off;\n";
184
				break;
185
			case "router":
186
				$radvdconf .= "\t\tAdvOnLink off;\n";
187
				$radvdconf .= "\t\tAdvAutonomous off;\n";
188
				break;
189
			case "stateless_dhcp":
190
			case "assist":
191
				$radvdconf .= "\t\tAdvOnLink on;\n";
192
				$radvdconf .= "\t\tAdvAutonomous on;\n";
193
				break;
194
			case "unmanaged":
195
				$radvdconf .= "\t\tAdvOnLink on;\n";
196
				$radvdconf .= "\t\tAdvAutonomous on;\n";
197
				break;
198
		}
199

    
200
		if (is_numericint($dhcpv6ifconf['ravalidlifetime'])) {
201
		  $radvdconf .= "\t\tAdvValidLifetime {$dhcpv6ifconf['ravalidlifetime']};\n";
202
		} else {
203
		  $radvdconf .= "\t\tAdvValidLifetime 86400;\n";
204
		}
205

    
206
		if (is_numericint($dhcpv6ifconf['rapreferredlifetime'])) {
207
		  $radvdconf .= "\t\tAdvPreferredLifetime {$dhcpv6ifconf['rapreferredlifetime']};\n";
208
		} else {
209
		  $radvdconf .= "\t\tAdvPreferredLifetime 14400;\n";
210
		}
211

    
212
		$radvdconf .= "\t};\n";
213

    
214
		if (is_array($dhcpv6ifconf['subnets']['item'])) {
215
			foreach ($dhcpv6ifconf['subnets']['item'] as $subnet) {
216
				if (is_subnetv6($subnet)) {
217
					$radvdconf .= "\tprefix {$subnet} {\n";
218
					$radvdconf .= "\t\tDeprecatePrefix on;\n";
219
					switch ($dhcpv6ifconf['ramode']) {
220
						case "managed":
221
							$radvdconf .= "\t\tAdvOnLink on;\n";
222
							$radvdconf .= "\t\tAdvAutonomous off;\n";
223
							break;
224
						case "router":
225
							$radvdconf .= "\t\tAdvOnLink off;\n";
226
							$radvdconf .= "\t\tAdvAutonomous off;\n";
227
							break;
228
						case "assist":
229
							$radvdconf .= "\t\tAdvOnLink on;\n";
230
							$radvdconf .= "\t\tAdvAutonomous on;\n";
231
							break;
232
						case "unmanaged":
233
							$radvdconf .= "\t\tAdvOnLink on;\n";
234
							$radvdconf .= "\t\tAdvAutonomous on;\n";
235
							break;
236
					}
237
					$radvdconf .= "\t};\n";
238
				}
239
			}
240
		}
241
		$radvdconf .= "\troute ::/0 {\n";
242
		switch ($dhcpv6ifconf['rapriority']) {
243
			case "low":
244
				$radvdconf .= "\t\tAdvRoutePreference low;\n";
245
				break;
246
			case "high":
247
				$radvdconf .= "\t\tAdvRoutePreference high;\n";
248
				break;
249
			default:
250
				$radvdconf .= "\t\tAdvRoutePreference medium;\n";
251
				break;
252
		}
253

    
254
		if ($rasrcaddr) {
255
			$radvdconf .= "\t\tRemoveRoute off;\n";
256
		}
257
		else {
258
			$radvdconf .= "\t\tRemoveRoute on;\n";
259
		}
260
		$radvdconf .= "\t};\n";
261

    
262
		/* add DNS servers */
263
		if ($dhcpv6ifconf['radvd-dns'] != 'disabled') {
264
			$dnslist = array();
265
			if (isset($dhcpv6ifconf['rasamednsasdhcp6']) && is_array($dhcpv6ifconf['dnsserver']) && !empty($dhcpv6ifconf['dnsserver'])) {
266
				foreach ($dhcpv6ifconf['dnsserver'] as $server) {
267
					if (is_ipaddrv6($server)) {
268
						$dnslist[] = $server;
269
					}
270
				}
271
			} elseif (!isset($dhcpv6ifconf['rasamednsasdhcp6']) && isset($dhcpv6ifconf['radnsserver']) && is_array($dhcpv6ifconf['radnsserver'])) {
272
				foreach ($dhcpv6ifconf['radnsserver'] as $server) {
273
					if (is_ipaddrv6($server)) {
274
						$dnslist[] = $server;
275
					}
276
				}
277
			} elseif (isset($config['dnsmasq']['enable']) || isset($config['unbound']['enable'])) {
278
				$dnslist[] = get_interface_ipv6($realif);
279
			} elseif (is_array($config['system']['dnsserver']) && !empty($config['system']['dnsserver'])) {
280
				foreach ($config['system']['dnsserver'] as $server) {
281
					if (is_ipaddrv6($server)) {
282
						$dnslist[] = $server;
283
					}
284
				}
285
			}
286
			$raadvdnsslifetime = $ramaxrtradvinterval * 3;
287
			if (count($dnslist) > 0) {
288
				$dnsstring = implode(" ", $dnslist);
289
				if ($dnsstring <> "") {
290
					/* 
291
					 * The value of Lifetime SHOULD by default be at least
292
					 * 3 * MaxRtrAdvInterval, where MaxRtrAdvInterval is the
293
					 * maximum RA interval as defined in [RFC4861].
294
					 * see https://redmine.pfsense.org/issues/11105 
295
					 */
296
					$radvdconf .= "\tRDNSS {$dnsstring} {\n";
297
					$radvdconf .= "\t\tAdvRDNSSLifetime {$raadvdnsslifetime};\n";
298
					$radvdconf .= "\t};\n";
299
				}
300
			}
301

    
302
			$searchlist = array();
303
			$domainsearchlist = explode(';', $dhcpv6ifconf['radomainsearchlist']);
304
			foreach ($domainsearchlist as $sd) {
305
				$sd = trim($sd);
306
				if (is_hostname($sd)) {
307
					$searchlist[] = $sd;
308
				}
309
			}
310
			if (count($searchlist) > 0) {
311
				$searchliststring = trim(implode(" ", $searchlist));
312
			} else {
313
				$searchliststring = "";
314
			}
315
			if (!empty($dhcpv6ifconf['domain'])) {
316
				/* 
317
				 * Lifetime SHOULD by default be at least 3 * MaxRtrAdvInterval
318
				 * see https://redmine.pfsense.org/issues/12173 
319
				 */
320
				$radvdconf .= "\tDNSSL {$dhcpv6ifconf['domain']} {$searchliststring} {\n";
321
				$radvdconf .= "\t\tAdvDNSSLLifetime {$raadvdnsslifetime};\n";
322
				$radvdconf .= "\t};\n";
323
			} elseif (!empty($config['system']['domain'])) {
324
				$radvdconf .= "\tDNSSL {$config['system']['domain']} {$searchliststring} {\n";
325
				$radvdconf .= "\t\tAdvDNSSLLifetime {$raadvdnsslifetime};\n";
326
				$radvdconf .= "\t};\n";
327
			}
328
		}
329
		$radvdconf .= "};\n";
330
	}
331

    
332
	/* handle DHCP-PD prefixes and 6RD dynamic interfaces */
333
	foreach ($Iflist as $if => $ifdescr) {
334
		if (!isset($config['interfaces'][$if]['track6-interface']) ||
335
		    !isset($config['interfaces'][$if]['ipaddrv6']) ||
336
		    $config['interfaces'][$if]['ipaddrv6'] != 'track6') {
337
			continue;
338
		}
339
		if (!isset($config['interfaces'][$if]['enable'])) {
340
			continue;
341
		}
342
		if ($config['dhcpdv6'][$if]['ramode'] == "disabled") {
343
			continue;
344
		}
345
		/* Do not put in the config an interface which is down */
346
		if (isset($blacklist[$if])) {
347
			continue;
348
		}
349
		$trackif = $config['interfaces'][$if]['track6-interface'];
350
		if (empty($config['interfaces'][$trackif])) {
351
			continue;
352
		}
353

    
354
		$realif = get_real_interface($if, "inet6");
355

    
356
		/* prevent duplicate entries, manual overrides */
357
		if (isset($radvdifs[$realif])) {
358
			continue;
359
		}
360

    
361
		$ifcfgipv6 = get_interface_ipv6($if);
362
		if (!is_ipaddrv6($ifcfgipv6)) {
363
			$subnetv6 = "::";
364
			$ifcfgsnv6 = "64";
365
		} else {
366
			$ifcfgsnv6 = get_interface_subnetv6($if);
367
			$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
368
		}
369
		$radvdifs[$realif] = $realif;
370

    
371
		$autotype = $config['interfaces'][$trackif]['ipaddrv6'];
372

    
373
		if ($g['debug']) {
374
			log_error("configuring RA on {$if} for type {$autotype} radvd subnet {$subnetv6}/{$ifcfgsnv6}");
375
		}
376

    
377
		$radvdconf .= "# Generated config for {$autotype} delegation from {$trackif} on {$if}\n";
378
		$radvdconf .= "interface {$realif} {\n";
379
		$radvdconf .= "\tAdvSendAdvert on;\n";
380
		if (is_numericint($dhcpv6ifconf['raminrtradvinterval'])) {
381
			$radvdconf .= "\tMinRtrAdvInterval {$dhcpv6ifconf['raminrtradvinterval']};\n";
382
		} else {
383
			$radvdconf .= "\tMinRtrAdvInterval 200;\n";
384
                }
385
		if (is_numericint($dhcpv6ifconf['ramaxrtradvinterval'])) {
386
			$radvdconf .= "\tMaxRtrAdvInterval {$dhcpv6ifconf['ramaxrtradvinterval']};\n";
387
			$raadvdnsslifetime = $dhcpv6ifconf['ramaxrtradvinterval'] * 3;
388
		} else {
389
			$radvdconf .= "\tMaxRtrAdvInterval 600;\n";
390
			$raadvdnsslifetime = 1800;
391
		}
392
		$mtu = get_interface_mtu($realif);
393
		if (is_numeric($mtu)) {
394
			$radvdconf .= "\tAdvLinkMTU {$mtu};\n";
395
		} else {
396
			$radvdconf .= "\tAdvLinkMTU 1280;\n";
397
		}
398
		$radvdconf .= "\tAdvOtherConfigFlag on;\n";
399
		$radvdconf .= "\tprefix {$subnetv6}/{$ifcfgsnv6} {\n";
400
		$radvdconf .= "\t\tAdvOnLink on;\n";
401
		$radvdconf .= "\t\tAdvAutonomous on;\n";
402
		$radvdconf .= "\t};\n";
403

    
404
		/* add DNS servers */
405
		if ($dhcpv6ifconf['radvd-dns'] != 'disabled') {
406
			$dnslist = array();
407
			if (isset($config['dnsmasq']['enable']) || isset($config['unbound']['enable'])) {
408
				$dnslist[] = $ifcfgipv6;
409
			} elseif (is_array($config['system']['dnsserver']) && !empty($config['system']['dnsserver'])) {
410
				foreach ($config['system']['dnsserver'] as $server) {
411
					if (is_ipaddrv6($server)) {
412
						$dnslist[] = $server;
413
					}
414
				}
415
			}
416
			if (count($dnslist) > 0) {
417
				$dnsstring = implode(" ", $dnslist);
418
				if (!empty($dnsstring)) {
419
					$radvdconf .= "\tRDNSS {$dnsstring} { };\n";
420
				}
421
			}
422
			if (!empty($config['system']['domain'])) {
423
				$radvdconf .= "\tDNSSL {$config['system']['domain']} {\n";
424
				$radvdconf .= "\t\tAdvDNSSLLifetime {$raadvdnsslifetime};\n";
425
				$radvdconf .= "\t};\n";
426
			}
427
		}
428
		$radvdconf .= "};\n";
429
	}
430

    
431
	/* write radvd.conf */
432
	if (!@file_put_contents("{$g['varetc_path']}/radvd.conf", $radvdconf)) {
433
		log_error(gettext("Error: cannot open radvd.conf in services_radvd_configure()."));
434
		if (platform_booting()) {
435
			printf("Error: cannot open radvd.conf in services_radvd_configure().\n");
436
		}
437
	}
438
	unset($radvdconf);
439

    
440
	if (count($radvdifs) > 0) {
441
		if (isvalidpid("{$g['varrun_path']}/radvd.pid")) {
442
			sigkillbypid("{$g['varrun_path']}/radvd.pid", "HUP");
443
		} else {
444
			mwexec("/usr/local/sbin/radvd -p {$g['varrun_path']}/radvd.pid -C {$g['varetc_path']}/radvd.conf -m syslog");
445
		}
446
	} else {
447
		/* we need to shut down the radvd cleanly, it will send out the prefix
448
		 * information with a lifetime of 0 to notify clients of a (possible) new prefix */
449
		if (isvalidpid("{$g['varrun_path']}/radvd.pid")) {
450
			log_error(gettext("Shutting down Router Advertisment daemon cleanly"));
451
			killbypid("{$g['varrun_path']}/radvd.pid");
452
			@unlink("{$g['varrun_path']}/radvd.pid");
453
		}
454
	}
455
	return 0;
456
}
457

    
458
function services_dhcpd_configure($family = "all", $blacklist = array()) {
459
	global $config, $g;
460

    
461
	$dhcpdconfigurelck = lock("dhcpdconfigure", LOCK_EX);
462

    
463
	/* configure DHCPD chroot once */
464
	$fd = fopen("{$g['tmp_path']}/dhcpd.sh", "w");
465
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}\n");
466
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/dev\n");
467
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/etc\n");
468
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/usr/local/sbin\n");
469
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db\n");
470
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run\n");
471
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/usr\n");
472
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/lib\n");
473
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/run\n");
474
	fwrite($fd, "/usr/sbin/chown -R dhcpd:_dhcp {$g['dhcpd_chroot_path']}/*\n");
475
	fwrite($fd, "/bin/cp -n /lib/libc.so.* {$g['dhcpd_chroot_path']}/lib/\n");
476
	fwrite($fd, "/bin/cp -n /usr/local/sbin/dhcpd {$g['dhcpd_chroot_path']}/usr/local/sbin/\n");
477
	fwrite($fd, "/bin/chmod a+rx {$g['dhcpd_chroot_path']}/usr/local/sbin/dhcpd\n");
478

    
479
	$status = `/sbin/mount | /usr/bin/grep -v grep | /usr/bin/grep "{$g['dhcpd_chroot_path']}/dev"`;
480
	if (!trim($status)) {
481
		fwrite($fd, "/sbin/mount -t devfs devfs {$g['dhcpd_chroot_path']}/dev\n");
482
	}
483
	fclose($fd);
484
	mwexec("/bin/sh {$g['tmp_path']}/dhcpd.sh");
485

    
486
	if ($family == "all" || $family == "inet") {
487
		services_dhcpdv4_configure();
488
	}
489
	if ($family == "all" || $family == "inet6") {
490
		services_dhcpdv6_configure($blacklist);
491
		services_radvd_configure($blacklist);
492
	}
493

    
494
	unlock($dhcpdconfigurelck);
495
}
496

    
497
function services_dhcpdv4_configure() {
498
	global $config, $g;
499
	$need_ddns_updates = false;
500
	$ddns_zones = array();
501

    
502
	if ($g['services_dhcp_server_enable'] == false) {
503
		return;
504
	}
505

    
506
	if (isset($config['system']['developerspew'])) {
507
		$mt = microtime();
508
		echo "services_dhcpdv4_configure($if) being called $mt\n";
509
	}
510

    
511
	/* kill any running dhcpd */
512
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid")) {
513
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid");
514
	}
515

    
516
	/* DHCP enabled on any interfaces? */
517
	if (!is_dhcp_server_enabled()) {
518
		return 0;
519
	}
520

    
521
	$syscfg = $config['system'];
522
	if (!is_array($config['dhcpd'])) {
523
		$config['dhcpd'] = array();
524
	}
525
	$dhcpdcfg = $config['dhcpd'];
526
	$Iflist = get_configured_interface_list();
527

    
528
	/* Only consider DNS servers with IPv4 addresses for the IPv4 DHCP server. */
529
	$dns_arrv4 = array();
530
	if (is_array($syscfg['dnsserver'])) {
531
		foreach ($syscfg['dnsserver'] as $dnsserver) {
532
			if (is_ipaddrv4($dnsserver)) {
533
				$dns_arrv4[] = $dnsserver;
534
			}
535
		}
536
	}
537

    
538
	if (platform_booting()) {
539
		echo gettext("Starting DHCP service...");
540
	} else {
541
		sleep(1);
542
	}
543

    
544
	$custoptions = "";
545
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
546
		$idx = 0;
547
		$httpclient = false;
548
		if (is_array($dhcpifconf['numberoptions']) && is_array($dhcpifconf['numberoptions']['item'])) {
549
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
550
				if (!empty($item['type'])) {
551
					$itemtype = $item['type'];
552
				} else {
553
					$itemtype = "text";
554
				}
555
				$custoptions .= "option custom-{$dhcpif}-{$itemidx} code {$item['number']} = {$itemtype};\n";
556
				if (($item['type'] == "text") &&
557
				    ($item['number'] == 60) &&
558
				    (base64_decode($item['value']) == "HTTPClient")) {
559
					$httpclient = true;
560
				} 
561
				$idx++;
562
			}
563
		}
564
		if (!empty($dhcpifconf['uefihttpboot']) && !$httpclient) {
565
			$custoptions .= "option custom-{$dhcpif}-{$idx} code 60 = text;\n";
566
		}
567
		if (is_array($dhcpifconf['pool'])) {
568
			foreach ($dhcpifconf['pool'] as $poolidx => $poolconf) {
569
				$idx = 0;
570
				$httpclient = false;
571
				if (is_array($poolconf['numberoptions']) && is_array($poolconf['numberoptions']['item'])) {
572
					foreach ($poolconf['numberoptions']['item'] as $itemidx => $item) {
573
						if (!empty($item['type'])) {
574
							$itemtype = $item['type'];
575
						} else {
576
							$itemtype = "text";
577
						}
578
						$custoptions .= "option custom-{$dhcpif}-{$poolidx}-{$itemidx} code {$item['number']} = {$itemtype};\n";
579
						if (($item['type'] == "text") &&
580
						    ($item['number'] == 60) &&
581
						    (base64_decode($item['value']) == "HTTPClient")) {
582
							$httpclient = true;
583
						} 
584
						$idx++;
585
					}
586
				}
587
				if (!empty($poolconf['uefihttpboot']) && !$httpclient) {
588
					$custoptions .= "option custom-{$dhcpif}-{$poolidx}-{$idx} code 60 = text;\n";
589
				}
590
			}
591
		}
592
		if (is_array($dhcpifconf['staticmap'])) {
593
			$i = 0;
594
			foreach ($dhcpifconf['staticmap'] as $sm) {
595
				$idx = 0;
596
				$httpclient = false;
597
				if (is_array($sm['numberoptions']) && is_array($sm['numberoptions']['item'])) {
598
					foreach ($sm['numberoptions']['item'] as $itemidx => $item) {
599
						if (!empty($item['type'])) {
600
							$itemtype = $item['type'];
601
						} else {
602
							$itemtype = "text";
603
						}
604
						$custoptions .= "option custom-s_{$dhcpif}_{$i}-{$itemidx} code {$item['number']} = {$itemtype};\n";
605
					}
606
					if (($item['type'] == "text") &&
607
					    ($item['number'] == 60) &&
608
					    (base64_decode($item['value']) == "HTTPClient")) {
609
						$httpclient = true;
610
					} 
611
					$idx++;
612
				}
613
				if (!empty($sm['uefihttpboot']) && !$httpclient) {
614
					$custoptions .= "option custom-s_{$dhcpif}_{$i}-{$idx} code 60 = text;\n";
615
				}
616
				$i++;
617
			}
618
		}
619
	}
620

    
621
	$dhcpdconf = <<<EOD
622

    
623
option domain-name "{$syscfg['domain']}";
624
option ldap-server code 95 = text;
625
option domain-search-list code 119 = text;
626
option arch code 93 = unsigned integer 16; # RFC4578
627
{$custoptions}
628
default-lease-time 7200;
629
max-lease-time 86400;
630
log-facility local7;
631
one-lease-per-client true;
632
deny duplicates;
633
update-conflict-detection false;
634

    
635
EOD;
636

    
637
	/* take these settings from the first DHCP configured interface,
638
	 * see https://redmine.pfsense.org/issues/10270 
639
	 * TODO: Global Settings tab, see https://redmine.pfsense.org/issues/5080 */
640
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
641
		if (!isset($dhcpifconf['disableauthoritative'])) {
642
			$dhcpdconf .= "authoritative;\n";
643
		}
644

    
645
		if (isset($dhcpifconf['alwaysbroadcast'])) {
646
			$dhcpdconf .= "always-broadcast on\n";
647
		}
648

    
649
		// OMAPI Settings
650
		if (isset($dhcpifconf['omapi_port']) && is_numeric($dhcpifconf['omapi_port'])) {
651
			$dhcpdconf .= <<<EOD
652

    
653
key omapi_key {
654
  algorithm {$dhcpifconf['omapi_key_algorithm']};
655
  secret "{$dhcpifconf['omapi_key']}";
656
};
657
omapi-port {$dhcpifconf['omapi_port']};
658
omapi-key omapi_key;
659

    
660
EOD;
661

    
662
		}
663
		break;
664
	}
665

    
666
	$dhcpdifs = array();
667
	$enable_add_routers = false;
668
	$gateways_arr = return_gateways_array();
669
	/* only add a routers line if the system has any IPv4 gateway at all */
670
	/* a static route has a gateway, manually overriding this field always works */
671
	foreach ($gateways_arr as $gwitem) {
672
		if ($gwitem['ipprotocol'] == "inet") {
673
			$enable_add_routers = true;
674
			break;
675
		}
676
	}
677

    
678
	/*    loop through and determine if we need to setup
679
	 *    failover peer "bleh" entries
680
	 */
681
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
682

    
683
		if (!isset($config['interfaces'][$dhcpif]['enable'])) {
684
			continue;
685
		}
686

    
687
		interfaces_staticarp_configure($dhcpif);
688

    
689
		if (!isset($dhcpifconf['enable'])) {
690
			continue;
691
		}
692

    
693
		if ($dhcpifconf['failover_peerip'] <> "") {
694
			$intip = get_interface_ip($dhcpif);
695
			/*
696
			 *    yep, failover peer is defined.
697
			 *    does it match up to a defined vip?
698
			 */
699
			$skew = 110;
700
			if (is_array($config['virtualip']['vip'])) {
701
				foreach ($config['virtualip']['vip'] as $vipent) {
702
					if ($vipent['mode'] != 'carp') {
703
						continue;
704
					}
705
					if ($vipent['interface'] == $dhcpif) {
706
						$carp_nw = gen_subnet($config['interfaces'][$dhcpif]['ipaddr'],
707
						    $config['interfaces'][$dhcpif]['subnet']);
708
						$carp_nw .= "/{$config['interfaces'][$dhcpif]['subnet']}";
709
						if (ip_in_subnet($dhcpifconf['failover_peerip'], $carp_nw)) {
710
							/* this is the interface! */
711
							if (is_numeric($vipent['advskew']) && (intval($vipent['advskew']) < 20)) {
712
								$skew = 0;
713
								break;
714
							}
715
						}
716
					}
717
				}
718
			} else {
719
				log_error(gettext("Warning!  DHCP Failover setup and no CARP virtual IPs defined!"));
720
			}
721
			if ($skew > 10) {
722
				$type = "secondary";
723
				$my_port = "520";
724
				$peer_port = "519";
725
				$dhcpdconf_pri = '';
726
			} else {
727
				$my_port = "519";
728
				$peer_port = "520";
729
				$type = "primary";
730
				$dhcpdconf_pri = "split 128;\n";
731
				$dhcpdconf_pri .= "  mclt 600;\n";
732
			}
733

    
734
			if (is_ipaddrv4($intip)) {
735
				$dhcpdconf .= <<<EOPP
736
failover peer "dhcp_{$dhcpif}" {
737
  {$type};
738
  address {$intip};
739
  port {$my_port};
740
  peer address {$dhcpifconf['failover_peerip']};
741
  peer port {$peer_port};
742
  max-response-delay 10;
743
  max-unacked-updates 10;
744
  {$dhcpdconf_pri}
745
  load balance max seconds 3;
746
}
747
\n
748
EOPP;
749
			}
750
		}
751
	}
752

    
753
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
754

    
755
		$newzone = array();
756
		$ifcfg = $config['interfaces'][$dhcpif];
757

    
758
		if (!isset($dhcpifconf['enable']) || !isset($Iflist[$dhcpif])) {
759
			continue;
760
		}
761
		$ifcfgip = get_interface_ip($dhcpif);
762
		$ifcfgsn = get_interface_subnet($dhcpif);
763
		$subnet = gen_subnet($ifcfgip, $ifcfgsn);
764
		$subnetmask = gen_subnet_mask($ifcfgsn);
765

    
766
		if (!is_ipaddr($subnet)) {
767
			continue;
768
		}
769

    
770
		$all_pools = array();
771
		$all_pools[] = $dhcpifconf;
772
		if (is_array($dhcpifconf['pool'])) {
773
			$all_pools = array_merge($all_pools, $dhcpifconf['pool']);
774
		}
775

    
776
		$dnscfg = "";
777

    
778
		if ($dhcpifconf['domain']) {
779
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
780
		}
781

    
782
		if ($dhcpifconf['domainsearchlist'] <> "") {
783
			$dnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpifconf['domainsearchlist'])) . "\";\n";
784
		}
785

    
786
		if (isset($dhcpifconf['ddnsupdate'])) {
787
			$need_ddns_updates = true;
788
			$newzone = array();
789
			if ($dhcpifconf['ddnsdomain'] <> "") {
790
				$newzone['domain-name'] = $dhcpifconf['ddnsdomain'];
791
				$dnscfg .= "	ddns-domainname \"{$dhcpifconf['ddnsdomain']}\";\n";
792
			} else {
793
				$newzone['domain-name'] = $config['system']['domain'];
794
			}
795

    
796
			if (empty($dhcpifconf['ddnsclientupdates'])) {
797
				$ddnsclientupdates = 'allow';
798
			} else {
799
				$ddnsclientupdates = $dhcpifconf['ddnsclientupdates'];
800
			}
801

    
802
			$dnscfg .= "	{$ddnsclientupdates} client-updates;\n";
803

    
804
			$revsubnet = array_reverse(explode('.',$subnet));
805

    
806
			$subnet_mask_bits = 32 - $ifcfgsn;
807
			$start_octet = $subnet_mask_bits >> 3;
808
			$octet_mask_bits = $subnet_mask_bits & ($subnet_mask_bits % 8);
809
			if ($octet_mask_bits) {
810
			    $octet_mask = (1 << $octet_mask_bits) - 1;
811
			    $octet_start = $revsubnet[$start_octet] & ~$octet_mask;
812
			    $revsubnet[$start_octet] = $octet_start . "-" . ($octet_start + $octet_mask);
813
			}
814

    
815
			$ptr_domain = '';
816
			for ($octet = 0; $octet <= 3; $octet++) {
817
				if ($octet < $start_octet) {
818
					continue;
819
				}
820
				$ptr_domain .= ((empty($ptr_domain) && $ptr_domain !== "0") ? '' : '.');
821
				$ptr_domain .= $revsubnet[$octet];
822
			}
823
			$ptr_domain .= ".in-addr.arpa";
824
			$newzone['ptr-domain'] = $ptr_domain;
825
			unset($ptr_domain, $revsubnet, $start_octet);
826
		}
827

    
828
		if (is_array($dhcpifconf['dnsserver']) && ($dhcpifconf['dnsserver'][0])) {
829
			$dnscfg .= "	option domain-name-servers " . join(",", $dhcpifconf['dnsserver']) . ";";
830
			if ($newzone['domain-name']) {
831
				$newzone['dns-servers'] = $dhcpifconf['dnsserver'];
832
			}
833
		} else if (isset($config['dnsmasq']['enable'])) {
834
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
835
			if ($newzone['domain-name'] && is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
836
				$newzone['dns-servers'] = $syscfg['dnsserver'];
837
			}
838
		} else if (isset($config['unbound']['enable'])) {
839
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
840
		} else if (!empty($dns_arrv4)) {
841
			$dnscfg .= "	option domain-name-servers " . join(",", $dns_arrv4) . ";";
842
			if ($newzone['domain-name']) {
843
				$newzone['dns-servers'] = $dns_arrv4;
844
			}
845
		}
846

    
847
		/* Create classes - These all contain comma separated lists. Join them into one
848
		   big comma separated string then split them all up. */
849
		$all_mac_strings = array();
850
		if (is_array($dhcpifconf['pool'])) {
851
			foreach ($all_pools as $poolconf) {
852
				$all_mac_strings[] = $poolconf['mac_allow'];
853
				$all_mac_strings[] = $poolconf['mac_deny'];
854
			}
855
		}
856
		$all_mac_strings[] = $dhcpifconf['mac_allow'];
857
		$all_mac_strings[] = $dhcpifconf['mac_deny'];
858
		if (!empty($all_mac_strings)) {
859
			$all_mac_list = array_unique(explode(',', implode(',', $all_mac_strings)));
860
			foreach ($all_mac_list as $mac) {
861
				if (empty($mac)) {
862
					continue;
863
				}
864
				$dhcpdconf .= 'class "' . str_replace(':', '', $mac) . '" {' . "\n";
865
				// Skip the first octet of the MAC address - for media type, typically Ethernet ("01") and match the rest.
866
				$dhcpdconf .= '	match if substring (hardware, 1, ' . (substr_count($mac, ':') + 1) . ') = ' . $mac . ';' . "\n";
867
				$dhcpdconf .= '}' . "\n";
868
			}
869
		}
870

    
871
		// instantiate class before pool definition
872
		$dhcpdconf .= "class \"s_{$dhcpif}\" {\n	match pick-first-value (option dhcp-client-identifier, hardware);\n}\n";
873

    
874
		$dhcpdconf .= "subnet {$subnet} netmask {$subnetmask} {\n";
875

    
876
		// Setup pool options
877
		foreach ($all_pools as $all_pools_idx => $poolconf) {
878
			if (!(ip_in_subnet($poolconf['range']['from'], "{$subnet}/{$ifcfgsn}") && ip_in_subnet($poolconf['range']['to'], "{$subnet}/{$ifcfgsn}"))) {
879
				// If the user has changed the subnet from the interfaces page and applied,
880
				// but has not updated the DHCP range, then the range to/from of the pool can be outside the subnet.
881
				// This can also happen when implementing the batch of changes when the setup wizard reloads the new settings.
882
				$error_msg = sprintf(gettext('Invalid DHCP pool %1$s - %2$s for %3$s subnet %4$s/%5$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);
883
				$do_file_notice = true;
884
				$conf_ipv4_address = $ifcfg['ipaddr'];
885
				$conf_ipv4_subnetmask = $ifcfg['subnet'];
886
				if (is_ipaddrv4($conf_ipv4_address) && is_subnet("{$conf_ipv4_address}/{$conf_ipv4_subnetmask}")) {
887
					$conf_subnet_base = gen_subnet($conf_ipv4_address, $conf_ipv4_subnetmask);
888
					if (ip_in_subnet($poolconf['range']['from'], "{$conf_subnet_base}/{$conf_ipv4_subnetmask}") &&
889
					    ip_in_subnet($poolconf['range']['to'], "{$conf_subnet_base}/{$conf_ipv4_subnetmask}")) {
890
						// Even though the running interface subnet does not match the pool range,
891
						// the interface subnet in the config file contains the pool range.
892
						// We are somewhere part-way through a settings reload, e.g. after running the setup wizard.
893
						// services_dhcpdv4_configure will be called again later when the new interface settings from
894
						// the config are applied and at that time everything will match up.
895
						// Ignore this pool on this interface for now and just log the error to the system log.
896
						log_error($error_msg);
897
						$do_file_notice = false;
898
					}
899
				}
900
				if ($do_file_notice) {
901
					file_notice("DHCP", $error_msg);
902
				}
903
				continue;
904
			}
905
			$dhcpdconf .= "	pool {\n";
906
			/* is failover dns setup? */
907
			if (is_array($poolconf['dnsserver']) && $poolconf['dnsserver'][0] <> "") {
908
				$dhcpdconf .= "		option domain-name-servers {$poolconf['dnsserver'][0]}";
909
				if ($poolconf['dnsserver'][1] <> "") {
910
					$dhcpdconf .= ",{$poolconf['dnsserver'][1]}";
911
				}
912
				if ($poolconf['dnsserver'][2] <> "") {
913
					$dhcpdconf .= ",{$poolconf['dnsserver'][2]}";
914
				}
915
				if ($poolconf['dnsserver'][3] <> "") {
916
					$dhcpdconf .= ",{$poolconf['dnsserver'][3]}";
917
				}
918
				$dhcpdconf .= ";\n";
919
			}
920

    
921
			/* allow/deny MACs */
922
			$mac_allow_list = array_unique(explode(',', $poolconf['mac_allow']));
923
			foreach ($mac_allow_list as $mac) {
924
				if (empty($mac)) {
925
					continue;
926
				}
927
				$dhcpdconf .= "		allow members of \"" . str_replace(':', '', $mac) . "\";\n";
928
			}
929
			$deny_action = "deny";
930
			if (isset($poolconf['nonak']) && empty($poolconf['failover_peerip'])) {
931
				$deny_action = "ignore";
932
			}
933
			$mac_deny_list = array_unique(explode(',', $poolconf['mac_deny']));
934
			foreach ($mac_deny_list as $mac) {
935
				if (empty($mac)) {
936
					continue;
937
				}
938
				$dhcpdconf .= "		$deny_action members of \"" . str_replace(':', '', $mac) . "\";\n";
939
			}
940

    
941
			if ($poolconf['failover_peerip'] <> "") {
942
				$dhcpdconf .= "		$deny_action dynamic bootp clients;\n";
943
			}
944

    
945
			// set pool MAC limitations
946
			if (isset($poolconf['denyunknown'])) {
947
				if ($poolconf['denyunknown'] == "class") {
948
					$dhcpdconf .= "		allow members of \"s_{$dhcpif}\";\n";
949
					$dhcpdconf .= "		$deny_action unknown-clients;\n";
950
				} else if ($poolconf['denyunknown'] == "disabled") {
951
					// add nothing to $dhcpdconf; condition added to prevent next condition applying if ever engine changes such that: isset("disabled") == true
952
				} else {	// "catch-all" covering "enabled" value post-PR#4066, and covering non-upgraded boolean option (i.e. literal value "enabled")
953
					$dhcpdconf .= "		$deny_action unknown-clients;\n";
954
				}
955
			}
956

    
957
			if ($poolconf['gateway'] && $poolconf['gateway'] != "none" && ($poolconf['gateway'] != $dhcpifconf['gateway'])) {
958
				$dhcpdconf .= "		option routers {$poolconf['gateway']};\n";
959
			}
960

    
961
			if ($dhcpifconf['failover_peerip'] <> "") {
962
				$dhcpdconf .= "		failover peer \"dhcp_{$dhcpif}\";\n";
963
			}
964

    
965
			$pdnscfg = "";
966

    
967
			if ($poolconf['domain'] && ($poolconf['domain'] != $dhcpifconf['domain'])) {
968
				$pdnscfg .= "		option domain-name \"{$poolconf['domain']}\";\n";
969
			}
970

    
971
			if (!empty($poolconf['domainsearchlist']) && ($poolconf['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
972
				$pdnscfg .= "		option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $poolconf['domainsearchlist'])) . "\";\n";
973
			}
974

    
975
			if (isset($poolconf['ddnsupdate'])) {
976
				if (($poolconf['ddnsdomain'] <> "") && ($poolconf['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
977
					$pdnscfg .= "		ddns-domainname \"{$poolconf['ddnsdomain']}\";\n";
978
				}
979
				$pdnscfg .= "		ddns-update-style interim;\n";
980
			}
981

    
982
			$dhcpdconf .= "{$pdnscfg}";
983

    
984
			// default-lease-time
985
			if ($poolconf['defaultleasetime'] && ($poolconf['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
986
				$dhcpdconf .= "		default-lease-time {$poolconf['defaultleasetime']};\n";
987
			}
988

    
989
			// max-lease-time
990
			if ($poolconf['maxleasetime'] && ($poolconf['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
991
				$dhcpdconf .= "		max-lease-time {$poolconf['maxleasetime']};\n";
992
			}
993

    
994
			// ignore bootp
995
			if (isset($poolconf['ignorebootp'])) {
996
				$dhcpdconf .= "		ignore bootp;\n";
997
			}
998

    
999
			// ignore-client-uids
1000
			if (isset($poolconf['ignoreclientuids'])) {
1001
				$dhcpdconf .= "		ignore-client-uids true;\n";
1002
			}
1003

    
1004
			// netbios-name*
1005
			if (is_array($poolconf['winsserver']) && $poolconf['winsserver'][0] && ($poolconf['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
1006
				$dhcpdconf .= "		option netbios-name-servers " . join(",", $poolconf['winsserver']) . ";\n";
1007
				$dhcpdconf .= "		option netbios-node-type 8;\n";
1008
			}
1009

    
1010
			// ntp-servers
1011
			if (is_array($poolconf['ntpserver']) && $poolconf['ntpserver'][0] && ($poolconf['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
1012
				$dhcpdconf .= "		option ntp-servers " . join(",", $poolconf['ntpserver']) . ";\n";
1013
			}
1014

    
1015
			// tftp-server-name
1016
			if (!empty($poolconf['tftp']) && ($poolconf['tftp'] != $dhcpifconf['tftp'])) {
1017
				$dhcpdconf .= "		option tftp-server-name \"{$poolconf['tftp']}\";\n";
1018
			}
1019

    
1020
			// Handle pool-specific options
1021
			$dhcpdconf .= "\n";
1022
			// Ignore the first pool, which is the "overall" pool when $all_pools_idx is 0 - those are put outside the pool block later
1023
			$idx = 0;
1024
			$httpclient = false;
1025
			if (isset($poolconf['numberoptions']['item']) && is_array($poolconf['numberoptions']['item']) && ($all_pools_idx > 0)) {
1026
				// Use the "real" pool index from the config, excluding the "overall" pool, and based from 0.
1027
				// This matches the way $poolidx was used when generating the $custoptions string earlier.
1028
				$poolidx = $all_pools_idx - 1;
1029
				foreach ($poolconf['numberoptions']['item'] as $itemidx => $item) {
1030
					$item_value = base64_decode($item['value']);
1031
					if (empty($item['type']) || $item['type'] == "text") {
1032
						$dhcpdconf .= "		option custom-{$dhcpif}-{$poolidx}-{$itemidx} \"{$item_value}\";\n";
1033
					} else {
1034
						$dhcpdconf .= "		option custom-{$dhcpif}-{$poolidx}-{$itemidx} {$item_value};\n";
1035
					}
1036
					if (($item['type'] == "text") &&
1037
					    ($item['number'] == 60) &&
1038
					    (base64_decode($item['value']) == "HTTPClient")) {
1039
						$httpclient = true;
1040
					} 
1041
					$idx++;
1042
				}
1043
			}
1044
			if (!empty($poolconf['uefihttpboot']) && !$httpclient &&
1045
			    (!isset($dhcpifconf['uefihttpboot']) ||
1046
			    ($poolconf['uefihttpboot'] != $dhcpifconf['uefihttpboot']))) {
1047
				$dhcpdconf .= "		option custom-{$dhcpif}-{$poolidx}-{$idx} \"HTTPClient\";\n";
1048
			}
1049

    
1050
			// ldap-server
1051
			if (!empty($poolconf['ldap']) && ($poolconf['ldap'] != $dhcpifconf['ldap'])) {
1052
				$dhcpdconf .= "		option ldap-server \"{$poolconf['ldap']}\";\n";
1053
			}
1054

    
1055
			// net boot information
1056
			if (isset($poolconf['netboot'])) {
1057
				if (!empty($poolconf['nextserver']) && ($poolconf['nextserver'] != $dhcpifconf['nextserver'])) {
1058
					$dhcpdconf .= "		next-server {$poolconf['nextserver']};\n";
1059
				}
1060

    
1061
				$pxe_files = array();
1062
				if (!empty($poolconf['filename']) &&
1063
				    (!isset($dhcpifconf['filename']) ||
1064
				    ($poolconf['filename'] != $dhcpifconf['filename']))) {
1065
					$filename = $poolconf['filename'];
1066
				}
1067
				if (!empty($poolconf['uefihttpboot']) &&
1068
				    (!isset($dhcpifconf['uefihttpboot']) ||
1069
				    ($poolconf['uefihttpboot'] != $dhcpifconf['uefihttpboot']))) {
1070
					$pxe_files[] = array('HTTPClient', $poolconf['uefihttpboot']);
1071
				}
1072
				if (!empty($poolconf['filename32']) &&
1073
				    (!isset($dhcpifconf['filename32']) ||
1074
				    ($poolconf['filename32'] != $dhcpifconf['filename32']))) {
1075
					$pxe_files[] = array('00:06', $poolconf['filename32']);
1076
				}
1077
				if (!empty($poolconf['filename64']) &&
1078
				    (!isset($dhcpifconf['filename64']) ||
1079
				    ($poolconf['filename64'] != $dhcpifconf['filename64']))) {
1080
					$pxe_files[] = array('00:07', $poolconf['filename64']);
1081
					$pxe_files[] = array('00:09', $poolconf['filename64']);
1082
				}
1083
				if (!empty($poolconf['filename32arm']) &&
1084
				    (!isset($dhcpifconf['filename32arm']) ||
1085
				    ($poolconf['filename32arm'] != $dhcpifconf['filename32arm']))) {
1086
					$pxe_files[] = array('00:0a', $poolconf['filename32arm']);
1087
				}
1088
				if (!empty($poolconf['filename64arm']) &&
1089
				    (!isset($dhcpifconf['filename64arm']) ||
1090
				    ($poolconf['filename64arm'] != $dhcpifconf['filename64arm']))) {
1091
					$pxe_files[] = array('00:0b', $poolconf['filename64arm']);
1092
				}
1093

    
1094
				$pxeif = false;
1095
				if (is_array($pxe_files) && !empty($pxe_files)) {
1096
					foreach ($pxe_files as $pxe) {
1097
						if ($pxe[0] == 'HTTPClient') {
1098
							$expr = "substring (option vendor-class-identifier, 0, 10) = \"HTTPClient\" {\n";
1099
						} else {
1100
							$expr = "option arch = {$pxe[0]} {\n";
1101
						}
1102
						if (!$pxeif) {
1103
							$dhcpdconf .= "		if " . $expr;
1104
							$pxeif = true;
1105
						} else {
1106
							$dhcpdconf .= " else if " . $expr;
1107
						}
1108
						$dhcpdconf .= "			filename \"{$pxe[1]}\";\n";
1109
						$dhcpdconf .= "		}";
1110
					}
1111
					if ($filename) {
1112
						$dhcpdconf .= " else {\n";
1113
						$dhcpdconf .= "			filename \"{$filename}\";\n";
1114
						$dhcpdconf .= "		}";
1115
					}
1116
					$dhcpdconf .= "\n\n";
1117
				} elseif (!empty($filename)) {
1118
					$dhcpdconf .= "		filename \"{$filename}\";\n";
1119
				}
1120
				unset($filename);
1121

    
1122
				if (!empty($poolconf['rootpath']) && ($poolconf['rootpath'] != $dhcpifconf['rootpath'])) {
1123
					$dhcpdconf .= "		option root-path \"{$poolconf['rootpath']}\";\n";
1124
				}
1125
			}
1126
			$dhcpdconf .= "		range {$poolconf['range']['from']} {$poolconf['range']['to']};\n";
1127
			$dhcpdconf .= "	}\n\n";
1128
		}
1129
// End of settings inside pools
1130

    
1131
		if ($dhcpifconf['gateway'] && $dhcpifconf['gateway'] != "none") {
1132
			$routers = $dhcpifconf['gateway'];
1133
			$add_routers = true;
1134
		} elseif ($dhcpifconf['gateway'] == "none") {
1135
			$add_routers = false;
1136
		} else {
1137
			$add_routers = $enable_add_routers;
1138
			$routers = $ifcfgip;
1139
		}
1140
		if ($add_routers) {
1141
			$dhcpdconf .= "	option routers {$routers};\n";
1142
		}
1143

    
1144
		$dhcpdconf .= <<<EOD
1145
$dnscfg
1146

    
1147
EOD;
1148
		// default-lease-time
1149
		if ($dhcpifconf['defaultleasetime']) {
1150
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
1151
		}
1152

    
1153
		// max-lease-time
1154
		if ($dhcpifconf['maxleasetime']) {
1155
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
1156
		}
1157

    
1158
		if (!isset($dhcpifconf['disablepingcheck'])) {
1159
			$dhcpdconf .= "	ping-check true;\n";
1160
		} else {
1161
			$dhcpdconf .= "	ping-check false;\n";
1162
		}
1163

    
1164
		// netbios-name*
1165
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
1166
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
1167
			$dhcpdconf .= "	option netbios-node-type 8;\n";
1168
		}
1169

    
1170
		// ntp-servers
1171
		if (is_array($dhcpifconf['ntpserver']) && $dhcpifconf['ntpserver'][0]) {
1172
			$dhcpdconf .= "	option ntp-servers " . join(",", $dhcpifconf['ntpserver']) . ";\n";
1173
		}
1174

    
1175
		// tftp-server-name
1176
		if ($dhcpifconf['tftp'] <> "") {
1177
			$dhcpdconf .= "	option tftp-server-name \"{$dhcpifconf['tftp']}\";\n";
1178
		}
1179

    
1180
		// Handle option, number rowhelper values
1181
		$dhcpdconf .= "\n";
1182
		$idx = 0;
1183
		$httpclient = false;
1184
		if (isset($dhcpifconf['numberoptions']['item']) && is_array($dhcpifconf['numberoptions']['item'])) {
1185
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
1186
				$item_value = base64_decode($item['value']);
1187
				if (empty($item['type']) || $item['type'] == "text") {
1188
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} \"{$item_value}\";\n";
1189
				} else {
1190
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} {$item_value};\n";
1191
				}
1192
				if (($item['type'] == "text") &&
1193
				    ($item['number'] == 60) &&
1194
				    (base64_decode($item['value']) == "HTTPClient")) {
1195
					$httpclient = true;
1196
				} 
1197
				$idx++;
1198
			}
1199
		}
1200
		if (!empty($dhcpifconf['uefihttpboot']) && !$httpclient) {
1201
			$dhcpdconf .= "	option custom-{$dhcpif}-{$idx} \"HTTPClient\";\n";
1202
		}
1203

    
1204
		// ldap-server
1205
		if ($dhcpifconf['ldap'] <> "") {
1206
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
1207
		}
1208

    
1209
		// net boot information
1210
		if (isset($dhcpifconf['netboot'])) {
1211
			if ($dhcpifconf['nextserver'] <> "") {
1212
				$dhcpdconf .= "	next-server {$dhcpifconf['nextserver']};\n";
1213
			}
1214

    
1215
			$pxe_files = array();
1216
			if (!empty($dhcpifconf['filename'])) {
1217
				$filename = $dhcpifconf['filename'];
1218
			}
1219
			if (!empty($dhcpifconf['uefihttpboot'])) {
1220
				$pxe_files[] = array('HTTPClient', $dhcpifconf['uefihttpboot']);
1221
			}
1222
			if (!empty($dhcpifconf['filename32'])) {
1223
				$pxe_files[] = array('00:06', $dhcpifconf['filename32']);
1224
			}
1225
			if (!empty($dhcpifconf['filename64'])) {
1226
				$pxe_files[] = array('00:07', $dhcpifconf['filename64']);
1227
				$pxe_files[] = array('00:09', $dhcpifconf['filename64']);
1228
			}
1229
			if (!empty($dhcpifconf['filename32arm'])) {
1230
				$pxe_files[] = array('00:0a', $dhcpifconf['filename32arm']);
1231
			}
1232
			if (!empty($dhcpifconf['filename64arm'])) {
1233
				$pxe_files[] = array('00:0b', $dhcpifconf['filename64arm']);
1234
			}
1235

    
1236
			$pxeif = false;
1237
			if (is_array($pxe_files) && !empty($pxe_files)) {
1238
				foreach ($pxe_files as $pxe) {
1239
					if ($pxe[0] == 'HTTPClient') {
1240
						$expr = "substring (option vendor-class-identifier, 0, 10) = \"HTTPClient\" {\n";
1241
					} else {
1242
						$expr = "option arch = {$pxe[0]} {\n";
1243
					}
1244
					if (!$pxeif) {
1245
						$dhcpdconf .= "	if " . $expr; 
1246
						$pxeif = true;
1247
					} else {
1248
						$dhcpdconf .= " else if " . $expr; 
1249
					}
1250
					$dhcpdconf .= "		filename \"{$pxe[1]}\";\n";
1251
					$dhcpdconf .= "	}";
1252
				}
1253
				if ($filename) {
1254
					$dhcpdconf .= " else {\n";
1255
					$dhcpdconf .= "		filename \"{$filename}\";\n";
1256
					$dhcpdconf .= "	}";
1257
				}
1258
				$dhcpdconf .= "\n\n";
1259
			} elseif (!empty($filename)) {
1260
				$dhcpdconf .= "		filename \"{$filename}\";\n";
1261
			}
1262
			if (!empty($dhcpifconf['rootpath'])) {
1263
				$dhcpdconf .= "	option root-path \"{$dhcpifconf['rootpath']}\";\n";
1264
			}
1265
		}
1266

    
1267
		$dhcpdconf .= <<<EOD
1268
}
1269

    
1270
EOD;
1271

    
1272
		/* add static mappings */
1273
		if (is_array($dhcpifconf['staticmap'])) {
1274

    
1275
			$i = 0;
1276
			$sm_newzone[] = array();
1277
			$need_sm_ddns_updates = false;
1278
			foreach ($dhcpifconf['staticmap'] as $sm) {
1279
				$cid = '';
1280
				$dhcpdconf .= "host s_{$dhcpif}_{$i} {\n";
1281

    
1282
				if ($sm['mac']) {
1283
					$dhcpdconf .= "	hardware ethernet {$sm['mac']};\n";
1284
				}
1285

    
1286
				if ($sm['cid']) {
1287
					$cid = str_replace('"', '\"', $sm['cid']);
1288
					$dhcpdconf .= "	option dhcp-client-identifier \"{$cid}\";\n";
1289
				}
1290

    
1291
				if ($sm['ipaddr']) {
1292
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
1293
				}
1294

    
1295
				if ($sm['hostname']) {
1296
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1297
					$dhhostname = str_replace(".", "_", $dhhostname);
1298
					$dhcpdconf .= "	option host-name \"{$dhhostname}\";\n";
1299
					if ((isset($dhcpifconf['ddnsupdate']) || isset($sm['ddnsupdate'])) && (isset($dhcpifconf['ddnsforcehostname']) || isset($sm['ddnsforcehostname']))) {
1300
						$dhcpdconf .= "	ddns-hostname \"{$dhhostname}\";\n";
1301
					}
1302
				}
1303
				if ($sm['filename']) {
1304
					$dhcpdconf .= "	filename \"{$sm['filename']}\";\n";
1305
				}
1306

    
1307
				if ($sm['rootpath']) {
1308
					$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1309
				}
1310

    
1311
				if ($sm['gateway'] && ($sm['gateway'] != $dhcpifconf['gateway'])) {
1312
					$dhcpdconf .= "	option routers {$sm['gateway']};\n";
1313
				}
1314

    
1315
				$smdnscfg = "";
1316

    
1317
				if ($sm['domain'] && ($sm['domain'] != $dhcpifconf['domain'])) {
1318
					$smdnscfg .= "	option domain-name \"{$sm['domain']}\";\n";
1319
				}
1320

    
1321
				if (!empty($sm['domainsearchlist']) && ($sm['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
1322
					$smdnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $sm['domainsearchlist'])) . "\";\n";
1323
				}
1324

    
1325
				if (isset($sm['ddnsupdate'])) {
1326
					if (($sm['ddnsdomain'] <> "") && ($sm['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
1327
						$smdnscfg .= "	ddns-domainname \"{$sm['ddnsdomain']}\";\n";
1328
				 		$need_sm_ddns_updates = true;	
1329
					}
1330
					$smdnscfg .= "	ddns-update-style interim;\n";
1331
				}
1332

    
1333
				if (is_array($sm['dnsserver']) && ($sm['dnsserver'][0]) && ($sm['dnsserver'][0] != $dhcpifconf['dnsserver'][0])) {
1334
					$smdnscfg .= "	option domain-name-servers " . join(",", $sm['dnsserver']) . ";\n";
1335
				}
1336
				$dhcpdconf .= "{$smdnscfg}";
1337

    
1338
				// default-lease-time
1339
				if ($sm['defaultleasetime'] && ($sm['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
1340
					$dhcpdconf .= "	default-lease-time {$sm['defaultleasetime']};\n";
1341
				}
1342

    
1343
				// max-lease-time
1344
				if ($sm['maxleasetime'] && ($sm['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
1345
					$dhcpdconf .= "	max-lease-time {$sm['maxleasetime']};\n";
1346
				}
1347

    
1348
				// netbios-name*
1349
				if (is_array($sm['winsserver']) && $sm['winsserver'][0] && ($sm['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
1350
					$dhcpdconf .= "	option netbios-name-servers " . join(",", $sm['winsserver']) . ";\n";
1351
					$dhcpdconf .= "	option netbios-node-type 8;\n";
1352
				}
1353

    
1354
				// ntp-servers
1355
				if (is_array($sm['ntpserver']) && $sm['ntpserver'][0] && ($sm['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
1356
					$dhcpdconf .= "	option ntp-servers " . join(",", $sm['ntpserver']) . ";\n";
1357
				}
1358

    
1359
				// tftp-server-name
1360
				if (!empty($sm['tftp']) && ($sm['tftp'] != $dhcpifconf['tftp'])) {
1361
					$dhcpdconf .= "	option tftp-server-name \"{$sm['tftp']}\";\n";
1362
				}
1363

    
1364
				// Handle option, number rowhelper values
1365
				$dhcpdconf .= "\n";
1366
				$idx = 0;
1367
				$httpclient = false;
1368
				if (isset($sm['numberoptions']['item']) && is_array($sm['numberoptions']['item'])) {
1369
					foreach ($sm['numberoptions']['item'] as $itemidx => $item) {
1370
						$item_value = base64_decode($item['value']);
1371
						if (empty($item['type']) || $item['type'] == "text") {
1372
							$dhcpdconf .= "	option custom-s_{$dhcpif}_{$i}-{$itemidx} \"{$item_value}\";\n";
1373
						} else {
1374
							$dhcpdconf .= "	option custom-s_{$dhcpif}_{$i}-{$itemidx} {$item_value};\n";
1375
						}
1376
					}
1377
					if (($item['type'] == "text") &&
1378
					    ($item['number'] == 60) &&
1379
					    (base64_decode($item['value']) == "HTTPClient")) {
1380
						$httpclient = true;
1381
					} 
1382
					$idx++;
1383
				}
1384
				if (!empty($poolconf['uefihttpboot']) && !$httpclient) {
1385
					$dhcpdconf .= "	option custom-s_{$dhcpif}_{$i}-{$idx} \"HTTPClient\";\n";
1386
				}
1387

    
1388
				// ldap-server
1389
				if (!empty($sm['ldap']) && ($sm['ldap'] != $dhcpifconf['ldap'])) {
1390
					$dhcpdconf .= "	option ldap-server \"{$sm['ldap']}\";\n";
1391
				}
1392

    
1393
				// net boot information
1394
				if (isset($sm['netboot'])) {
1395
					if ($sm['nextserver'] <> "") {
1396
						$dhcpdconf .= "	next-server {$sm['nextserver']};\n";
1397
					}
1398

    
1399
					$pxe_files = array();
1400
					if (!empty($sm['filename'])) {
1401
						$filename = $sm['filename'];
1402
					}
1403
					if (!empty($sm['uefihttpboot'])) {
1404
						$pxe_files[] = array('HTTPClient', $sm['uefihttpboot']);
1405
					}
1406
					if (!empty($sm['filename32'])) {
1407
						$pxe_files[] = array('00:06', $sm['filename32']);
1408
					}
1409
					if (!empty($sm['filename64'])) {
1410
						$pxe_files[] = array('00:07', $sm['filename64']);
1411
						$pxe_files[] = array('00:09', $sm['filename64']);
1412
					}
1413
					if (!empty($sm['filename32arm'])) {
1414
						$pxe_files[] = array('00:0a', $sm['filename32arm']);
1415
					}
1416
					if (!empty($sm['filename64arm'])) {
1417
						$pxe_files[] = array('00:0b', $sm['filename64arm']);
1418
					}
1419

    
1420
					$pxeif = false;
1421
					if (is_array($pxe_files) && !empty($pxe_files)) {
1422
						foreach ($pxe_files as $pxe) {
1423
							if ($pxe[0] == 'HTTPClient') {
1424
								$expr = "substring (option vendor-class-identifier, 0, 10) = \"HTTPClient\" {\n";
1425
							} else {
1426
								$expr = "option arch = {$pxe[0]} {\n";
1427
							}
1428
							if (!$pxeif) {
1429
								$dhcpdconf .= "	if " . $expr; 
1430
								$pxeif = true;
1431
							} else {
1432
								$dhcpdconf .= " else if " . $expr; 
1433
							}
1434
							$dhcpdconf .= "		filename \"{$pxe[1]}\";\n";
1435
							$dhcpdconf .= "	}";
1436
						}
1437
						if ($filename) {
1438
							$dhcpdconf .= " else {\n";
1439
							$dhcpdconf .= "		filename \"{$filename}\";\n";
1440
							$dhcpdconf .= "	}";
1441
						}
1442
						$dhcpdconf .= "\n\n";
1443
					} elseif (!empty($filename)) {
1444
						$dhcpdconf .= "		filename \"{$filename}\";\n";
1445
					}
1446
					if (!empty($dhcpifconf['rootpath'])) {
1447
						$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1448
					}
1449
				}
1450

    
1451
				$dhcpdconf .= "}\n";
1452

    
1453
				// add zone DDNS key/server to $ddns_zone[] if required
1454
				if ($need_sm_ddns_updates) {
1455
					$ddnsduplicate = false;
1456
					foreach ($ddns_zones as $ddnszone) {
1457
						if ($ddnszone['domain-name'] == $sm['ddnsdomain']) {
1458
							$ddnsduplicate = true;
1459
						}
1460
					}
1461
					if (!$ddnsduplicate) {
1462
						$sm_newzone['dns-servers'] = array($sm['ddnsdomainprimary'], $sm['ddnsdomainsecondary']);
1463
						$sm_newzone['domain-name'] = $sm['ddnsdomain'];
1464
						$sm_newzone['ddnsdomainkeyname'] = $sm['ddnsdomainkeyname'];
1465
						$sm_newzone['ddnsdomainkeyalgorithm'] = $sm['ddnsdomainkeyalgorithm'];
1466
						$sm_newzone['ddnsdomainkey'] = $sm['ddnsdomainkey'];
1467
						$dhcpdconf .= dhcpdkey($sm_newzone);
1468
						$ddns_zones[] = $sm_newzone;
1469
						$need_ddns_updates = true;
1470
					}
1471
				}
1472

    
1473
				// subclass for DHCP limiting
1474
				if (!empty($sm['mac'])) {
1475
					// assuming ALL addresses are ethernet hardware type ("1:" prefix)
1476
					$dhcpdconf .= "subclass \"s_{$dhcpif}\" 1:{$sm['mac']};\n";
1477
				}
1478
				if (!empty($cid)) {
1479
					$dhcpdconf .= "subclass \"s_{$dhcpif}\" \"{$cid}\";\n";
1480
				}
1481

    
1482

    
1483
				$i++;
1484
			}
1485
		}
1486

    
1487
		$dhcpdifs[] = get_real_interface($dhcpif);
1488
		if ($newzone['domain-name']) {
1489
			if ($need_ddns_updates) {
1490
				$newzone['dns-servers'] = array($dhcpifconf['ddnsdomainprimary'], $dhcpifconf['ddnsdomainsecondary']);
1491
				$newzone['ddnsdomainkeyname'] = $dhcpifconf['ddnsdomainkeyname'];
1492
				$newzone['ddnsdomainkeyalgorithm'] = $dhcpifconf['ddnsdomainkeyalgorithm'];
1493
				$newzone['ddnsdomainkey'] = $dhcpifconf['ddnsdomainkey'];
1494
				$dhcpdconf .= dhcpdkey($dhcpifconf);
1495
			}
1496
			$ddns_zones[] = $newzone;
1497
		}
1498
	}
1499

    
1500
	if ($need_ddns_updates) {
1501
		$dhcpdconf .= "ddns-update-style interim;\n";
1502
		$dhcpdconf .= "update-static-leases on;\n";
1503

    
1504
		$dhcpdconf .= dhcpdzones($ddns_zones);
1505
	}
1506

    
1507
	/* write dhcpd.conf */
1508
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpd.conf", $dhcpdconf)) {
1509
		printf(gettext("Error: cannot open dhcpd.conf in services_dhcpdv4_configure().%s"), "\n");
1510
		unset($dhcpdconf);
1511
		return 1;
1512
	}
1513
	unset($dhcpdconf);
1514

    
1515
	/* create an empty leases database */
1516
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
1517
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
1518
	}
1519

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

    
1524
	/* fire up dhcpd in a chroot */
1525
	if (count($dhcpdifs) > 0) {
1526
		mwexec("/usr/local/sbin/dhcpd -user dhcpd -group _dhcp -chroot {$g['dhcpd_chroot_path']} -cf /etc/dhcpd.conf -pf {$g['varrun_path']}/dhcpd.pid " .
1527
			join(" ", $dhcpdifs));
1528
	}
1529

    
1530
	if (platform_booting()) {
1531
		print "done.\n";
1532
	}
1533

    
1534
	return 0;
1535
}
1536

    
1537
function dhcpdkey($dhcpifconf) {
1538
	$dhcpdconf = "";
1539
	if (!empty($dhcpifconf['ddnsdomainkeyname']) && !empty($dhcpifconf['ddnsdomainkey'])) {
1540
		$algorithm = empty($dhcpifconf['ddnsdomainkeyalgorithm']) ? 'hmac-md5' : $dhcpifconf['ddnsdomainkeyalgorithm'];
1541
		$dhcpdconf .= "key \"{$dhcpifconf['ddnsdomainkeyname']}\" {\n";
1542
		$dhcpdconf .= "	algorithm {$algorithm};\n";
1543
		$dhcpdconf .= "	secret {$dhcpifconf['ddnsdomainkey']};\n";
1544
		$dhcpdconf .= "}\n";
1545
	}
1546

    
1547
	return $dhcpdconf;
1548
}
1549

    
1550
function dhcpdzones($ddns_zones) {
1551
	$dhcpdconf = "";
1552

    
1553
	if (is_array($ddns_zones)) {
1554
		$added_zones = array();
1555
		foreach ($ddns_zones as $zone) {
1556
			if (!is_array($zone) || empty($zone) || !is_array($zone['dns-servers'])) {
1557
				continue;
1558
			}
1559
			$primary = $zone['dns-servers'][0];
1560
			$secondary = empty($zone['dns-servers'][1]) ? "" : $zone['dns-servers'][1];
1561

    
1562
			// Make sure we aren't using any invalid servers.
1563
			if (!is_ipaddr($primary)) {
1564
				if (is_ipaddr($secondary)) {
1565
					$primary = $secondary;
1566
					$secondary = "";
1567
				} else {
1568
					continue;
1569
				}
1570
			}
1571

    
1572
			// We don't need to add zones multiple times.
1573
			if ($zone['domain-name'] && !in_array($zone['domain-name'], $added_zones)) {
1574
				$dhcpdconf .= "zone {$zone['domain-name']}. {\n";
1575
				if (is_ipaddrv4($primary)) {
1576
					$dhcpdconf .= "	primary {$primary};\n";
1577
				} else {
1578
					$dhcpdconf .= "	primary6 {$primary};\n";
1579
				}
1580
				if (is_ipaddrv4($secondary)) {
1581
					$dhcpdconf .= "	secondary {$secondary};\n";
1582
				} elseif (is_ipaddrv6($secondary)) {
1583
					$dhcpdconf .= "	secondary6 {$secondary};\n";
1584
				}
1585
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1586
					$dhcpdconf .= "	key \"{$zone['ddnsdomainkeyname']}\";\n";
1587
				}
1588
				$dhcpdconf .= "}\n";
1589
				$added_zones[] = $zone['domain-name'];
1590
			}
1591
			if ($zone['ptr-domain'] && !in_array($zone['ptr-domain'], $added_zones)) {
1592
				$dhcpdconf .= "zone {$zone['ptr-domain']}. {\n";
1593
				if (is_ipaddrv4($primary)) {
1594
					$dhcpdconf .= "	primary {$primary};\n";
1595
				} else {
1596
					$dhcpdconf .= "	primary6 {$primary};\n";
1597
				}
1598
				if (is_ipaddrv4($secondary)) {
1599
					$dhcpdconf .= "	secondary {$secondary};\n";
1600
				} elseif (is_ipaddrv6($secondary)) {
1601
					$dhcpdconf .= "	secondary6 {$secondary};\n";
1602
				}
1603
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1604
					$dhcpdconf .= "	key \"{$zone['ddnsdomainkeyname']}\";\n";
1605
				}
1606
				$dhcpdconf .= "}\n";
1607
				$added_zones[] = $zone['ptr-domain'];
1608
			}
1609
		}
1610
	}
1611

    
1612
	return $dhcpdconf;
1613
}
1614

    
1615
function services_dhcpdv6_configure($blacklist = array()) {
1616
	global $config, $g;
1617

    
1618
	if ($g['services_dhcp_server_enable'] == false) {
1619
		return;
1620
	}
1621

    
1622
	if (isset($config['system']['developerspew'])) {
1623
		$mt = microtime();
1624
		echo "services_dhcpd_configure($if) being called $mt\n";
1625
	}
1626

    
1627
	/* kill any running dhcpd */
1628
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid")) {
1629
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid");
1630
	}
1631
	if (isvalidpid("{$g['varrun_path']}/dhcpleases6.pid")) {
1632
		killbypid("{$g['varrun_path']}/dhcpleases6.pid");
1633
	}
1634

    
1635
	/* DHCP enabled on any interfaces? */
1636
	if (!is_dhcpv6_server_enabled()) {
1637
		return 0;
1638
	}
1639

    
1640
	$syscfg = $config['system'];
1641
	if (!is_array($config['dhcpdv6'])) {
1642
		$config['dhcpdv6'] = array();
1643
	}
1644
	$dhcpdv6cfg = $config['dhcpdv6'];
1645
	$Iflist = get_configured_interface_list();
1646
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
1647

    
1648

    
1649
	if (platform_booting()) {
1650
		echo "Starting DHCPv6 service...";
1651
	} else {
1652
		sleep(1);
1653
	}
1654

    
1655
	$custoptionsv6 = "";
1656
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1657
		if (is_array($dhcpv6ifconf['numberoptions']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1658
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1659
				$custoptionsv6 .= "option custom-{$dhcpv6if}-{$itemv6idx} code {$itemv6['number']} = text;\n";
1660
			}
1661
		}
1662
	}
1663

    
1664
	if (isset($dhcpv6ifconf['netboot']) && !empty($dhcpv6ifconf['bootfile_url'])) {
1665
		$custoptionsv6 .= "option dhcp6.bootfile-url code 59 = string;\n";
1666
	}
1667

    
1668
	$dhcpdv6conf = <<<EOD
1669

    
1670
option domain-name "{$syscfg['domain']}";
1671
option ldap-server code 95 = text;
1672
option domain-search-list code 119 = text;
1673
{$custoptionsv6}
1674
default-lease-time 7200;
1675
max-lease-time 86400;
1676
log-facility local7;
1677
one-lease-per-client true;
1678
deny duplicates;
1679
ping-check true;
1680
update-conflict-detection false;
1681

    
1682
EOD;
1683

    
1684
	if (!isset($dhcpv6ifconf['disableauthoritative'])) {
1685
		$dhcpdv6conf .= "authoritative;\n";
1686
	}
1687

    
1688
	if (isset($dhcpv6ifconf['alwaysbroadcast'])) {
1689
		$dhcpdv6conf .= "always-broadcast on\n";
1690
	}
1691

    
1692
	$dhcpdv6ifs = array();
1693

    
1694
	$dhcpv6num = 0;
1695
	$nsupdate = false;
1696

    
1697
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1698

    
1699
		$ddns_zones = array();
1700

    
1701
		$ifcfgv6 = $config['interfaces'][$dhcpv6if];
1702

    
1703
		if (!isset($dhcpv6ifconf['enable']) || !isset($Iflist[$dhcpv6if]) ||
1704
		    (!isset($ifcfgv6['enable']) && !preg_match("/poes/", $dhcpv6if))) {
1705
			continue;
1706
		}
1707
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1708
		if (!is_ipaddrv6($ifcfgipv6) && !preg_match("/poes/", $dhcpv6if)) {
1709
			continue;
1710
		}
1711
		$ifcfgsnv6 = get_interface_subnetv6($dhcpv6if);
1712
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1713
		// We might have some prefix-delegation on WAN (e.g. /48),
1714
		// but then it is split and given out to individual interfaces
1715
		// (LAN, OPT1, OPT2...) as multiple /64 subnets. So the size
1716
		// of each subnet here is always /64.
1717
		$pdlen = 64;
1718

    
1719
		if (is_ipaddrv6($ifcfgipv6)) {
1720
			$subnet_start = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1721
			$subnet_end = gen_subnetv6_max($ifcfgipv6, $ifcfgsnv6);
1722
			if ((!is_inrange_v6($dhcpv6ifconf['range']['from'], $subnet_start, $subnet_end)) ||
1723
			    (!is_inrange_v6($dhcpv6ifconf['range']['to'], $subnet_start, $subnet_end))) {
1724
				log_error(gettext("The specified range lies outside of the current subnet. Skipping DHCP6 entry."));
1725
				continue;
1726
			}
1727
		}
1728

    
1729
		$dnscfgv6 = "";
1730

    
1731
		if ($dhcpv6ifconf['domain']) {
1732
			$dnscfgv6 .= "	option domain-name \"{$dhcpv6ifconf['domain']}\";\n";
1733
		}
1734

    
1735
		if ($dhcpv6ifconf['domainsearchlist'] <> "") {
1736
			$dnscfgv6 .= "	option dhcp6.domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpv6ifconf['domainsearchlist'])) . "\";\n";
1737
		}
1738

    
1739
		if (isset($dhcpv6ifconf['ddnsupdate'])) {
1740
			if ($dhcpv6ifconf['ddnsdomain'] <> "") {
1741
				$dnscfgv6 .= "	ddns-domainname \"{$dhcpv6ifconf['ddnsdomain']}\";\n";
1742
			}
1743
			if (empty($dhcpv6ifconf['ddnsclientupdates'])) {
1744
				$ddnsclientupdates = 'allow';
1745
			} else {
1746
				$ddnsclientupdates = $dhcpv6ifconf['ddnsclientupdates'];
1747
			}
1748
			$dnscfgv6 .= "	{$ddnsclientupdates} client-updates;\n";
1749
			$nsupdate = true;
1750
		} else {
1751
			$dnscfgv6 .= "	do-forward-updates false;\n";
1752
		}
1753

    
1754
		if ($dhcpv6ifconf['dhcp6c-dns'] != 'disabled') {
1755
			if (is_array($dhcpv6ifconf['dnsserver']) && ($dhcpv6ifconf['dnsserver'][0])) {
1756
				$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dhcpv6ifconf['dnsserver']) . ";\n";
1757
			} else if (((isset($config['dnsmasq']['enable'])) || isset($config['unbound']['enable'])) && (is_ipaddrv6($ifcfgipv6))) {
1758
				$dnscfgv6 .= "	option dhcp6.name-servers {$ifcfgipv6};\n";
1759
			} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1760
				$dns_arrv6 = array();
1761
				foreach ($syscfg['dnsserver'] as $dnsserver) {
1762
					if (is_ipaddrv6($dnsserver)) {
1763
						if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1764
						    Net_IPv6::isInNetmask($dnsserver, '::', $pdlen)) {
1765
							$dnsserver = merge_ipv6_delegated_prefix($ifcfgipv6, $dnsserver, $pdlen);
1766
						}
1767
						$dns_arrv6[] = $dnsserver;
1768
					}
1769
				}
1770
				if (!empty($dns_arrv6)) {
1771
					$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dns_arrv6) . ";\n";
1772
				}
1773
			}
1774
		} else {
1775
			$dnscfgv6 .= "	#option dhcp6.name-servers --;\n";
1776
		}
1777

    
1778
		if (!is_ipaddrv6($ifcfgipv6)) {
1779
			$ifcfgsnv6 = "64";
1780
			$subnetv6 = gen_subnetv6($dhcpv6ifconf['range']['from'], $ifcfgsnv6);
1781
		}
1782

    
1783
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1784

    
1785
		if (isset($dhcpv6ifconf['ddnsupdate']) &&
1786
		    !empty($dhcpv6ifconf['ddnsdomain'])) {
1787
			$newzone = array();
1788
			$newzone['domain-name'] = $dhcpv6ifconf['ddnsdomain'];
1789
			$newzone['dns-servers'] = array($dhcpv6ifconf['ddnsdomainprimary'], $dhcpv6ifconf['ddnsdomainsecondary']);
1790
			$newzone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1791
			$newzone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1792
			$ddns_zones[] = $newzone;
1793
			if (isset($dhcpv6ifconf['ddnsreverse'])) {
1794
				$ptr_zones = get_v6_ptr_zones($subnetv6, $ifcfgsnv6);
1795
				foreach ($ptr_zones as $ptr_zone) {
1796
					$reversezone = array();
1797
					$reversezone['ptr-domain'] = $ptr_zone;
1798
					$reversezone['dns-servers'] = array($dhcpv6ifconf['ddnsdomainprimary'], $dhcpv6ifconf['ddnsdomainsecondary']);
1799
					$reversezone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1800
					$reversezone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1801
					$ddns_zones[] = $reversezone;
1802
				}
1803
			}
1804
		}
1805

    
1806
		$dhcpdv6conf .= " {\n";
1807

    
1808
		$range_from = $dhcpv6ifconf['range']['from'];
1809
		$range_to = $dhcpv6ifconf['range']['to'];
1810
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
1811
			$range_from = merge_ipv6_delegated_prefix($ifcfgipv6, $range_from, $pdlen);
1812
			$range_to = merge_ipv6_delegated_prefix($ifcfgipv6, $range_to, $pdlen);
1813
		}
1814

    
1815
		if (!empty($dhcpv6ifconf['range']['from']) && !empty($dhcpv6ifconf['range']['to'])) {
1816
			$dhcpdv6conf .= "	range6 {$range_from} {$range_to};\n";
1817
		}
1818

    
1819
		$dhcpdv6conf .= $dnscfgv6;
1820

    
1821
		if (is_ipaddrv6($dhcpv6ifconf['prefixrange']['from']) && is_ipaddrv6($dhcpv6ifconf['prefixrange']['to'])) {
1822
			$dhcpdv6conf .= "	prefix6 {$dhcpv6ifconf['prefixrange']['from']} {$dhcpv6ifconf['prefixrange']['to']} /{$dhcpv6ifconf['prefixrange']['prefixlength']};\n";
1823
		}
1824
		if (is_ipaddrv6($dhcpv6ifconf['dns6ip'])) {
1825
			$dns6ip = $dhcpv6ifconf['dns6ip'];
1826
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1827
			    Net_IPv6::isInNetmask($dns6ip, '::', $pdlen)) {
1828
				$dns6ip = merge_ipv6_delegated_prefix($ifcfgipv6, $dns6ip, $pdlen);
1829
			}
1830
			$dhcpdv6conf .= "	option dhcp6.name-servers {$dns6ip};\n";
1831
		}
1832
		// default-lease-time
1833
		if ($dhcpv6ifconf['defaultleasetime']) {
1834
			$dhcpdv6conf .= "	default-lease-time {$dhcpv6ifconf['defaultleasetime']};\n";
1835
		}
1836

    
1837
		// max-lease-time
1838
		if ($dhcpv6ifconf['maxleasetime']) {
1839
			$dhcpdv6conf .= "	max-lease-time {$dhcpv6ifconf['maxleasetime']};\n";
1840
		}
1841

    
1842
		// ntp-servers
1843
		if (is_array($dhcpv6ifconf['ntpserver']) && $dhcpv6ifconf['ntpserver'][0]) {
1844
			$ntpservers = array();
1845
			foreach ($dhcpv6ifconf['ntpserver'] as $ntpserver) {
1846
				if (!is_ipaddrv6($ntpserver)) {
1847
					continue;
1848
				}
1849
				if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1850
				    Net_IPv6::isInNetmask($ntpserver, '::', $pdlen)) {
1851
					$ntpserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ntpserver, $pdlen);
1852
				}
1853
				$ntpservers[] = $ntpserver;
1854
			}
1855
			if (count($ntpservers) > 0) {
1856
				$dhcpdv6conf .= "        option dhcp6.sntp-servers " . join(",", $dhcpv6ifconf['ntpserver']) . ";\n";
1857
			}
1858
		}
1859
		// tftp-server-name
1860
		/* Needs ISC DHCPD support
1861
		 if ($dhcpv6ifconf['tftp'] <> "") {
1862
			$dhcpdv6conf .= "	option tftp-server-name \"{$dhcpv6ifconf['tftp']}\";\n";
1863
		 }
1864
		*/
1865

    
1866
		// Handle option, number rowhelper values
1867
		$dhcpdv6conf .= "\n";
1868
		if (isset($dhcpv6ifconf['numberoptions']['item']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1869
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1870
				$itemv6_value = base64_decode($itemv6['value']);
1871
				$dhcpdv6conf .= "	option custom-{$dhcpv6if}-{$itemv6idx} \"{$itemv6_value}\";\n";
1872
			}
1873
		}
1874

    
1875
		// ldap-server
1876
		if ($dhcpv6ifconf['ldap'] <> "") {
1877
			$ldapserver = $dhcpv6ifconf['ldap'];
1878
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1879
			    Net_IPv6::isInNetmask($ldapserver, '::', $pdlen)) {
1880
				$ldapserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ldapserver, $pdlen);
1881
			}
1882
			$dhcpdv6conf .= "	option ldap-server \"{$ldapserver}\";\n";
1883
		}
1884

    
1885
		// net boot information
1886
		if (isset($dhcpv6ifconf['netboot'])) {
1887
			if (!empty($dhcpv6ifconf['bootfile_url'])) {
1888
				$dhcpdv6conf .= "	option dhcp6.bootfile-url \"{$dhcpv6ifconf['bootfile_url']}\";\n";
1889
			}
1890
		}
1891

    
1892
		$dhcpdv6conf .= "}\n";
1893

    
1894
		/* add static mappings */
1895
		/* Needs to use DUID */
1896
		if (is_array($dhcpv6ifconf['staticmap'])) {
1897
			$i = 0;
1898
			foreach ($dhcpv6ifconf['staticmap'] as $sm) {
1899
				$dhcpdv6conf .= <<<EOD
1900
host s_{$dhcpv6if}_{$i} {
1901
	host-identifier option dhcp6.client-id {$sm['duid']};
1902

    
1903
EOD;
1904
				if ($sm['ipaddrv6']) {
1905
					$ipaddrv6 = $sm['ipaddrv6'];
1906
					if ($ifcfgv6['ipaddrv6'] == 'track6') {
1907
						$ipaddrv6 = merge_ipv6_delegated_prefix($ifcfgipv6, $ipaddrv6, $pdlen);
1908
					}
1909
					$dhcpdv6conf .= "	fixed-address6 {$ipaddrv6};\n";
1910
				}
1911

    
1912
				if ($sm['hostname']) {
1913
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1914
					$dhhostname = str_replace(".", "_", $dhhostname);
1915
					$dhcpdv6conf .= "	option host-name {$dhhostname};\n";
1916
					if (isset($dhcpv6ifconf['ddnsupdate']) &&
1917
					    isset($dhcpv6ifconf['ddnsforcehostname'])) {
1918
						$dhcpdv6conf .= "	ddns-hostname \"{$dhhostname}\";\n";
1919
					}
1920
				}
1921
				if ($sm['filename']) {
1922
					$dhcpdv6conf .= "	filename \"{$sm['filename']}\";\n";
1923
				}
1924

    
1925
				if ($sm['rootpath']) {
1926
					$dhcpdv6conf .= "	option root-path \"{$sm['rootpath']}\";\n";
1927
				}
1928

    
1929
				$dhcpdv6conf .= "}\n";
1930
				$i++;
1931
			}
1932
		}
1933

    
1934
		if ($dhcpv6ifconf['ddnsdomain']) {
1935
			$dhcpdv6conf .= dhcpdkey($dhcpv6ifconf);
1936
			$dhcpdv6conf .= dhcpdzones($ddns_zones);
1937
		}
1938

    
1939
		if (($config['dhcpdv6'][$dhcpv6if]['ramode'] != "unmanaged") &&
1940
		    (isset($config['interfaces'][$dhcpv6if]['enable']) ||
1941
		    preg_match("/poes/", $dhcpv6if))) {
1942
			if (preg_match("/poes/si", $dhcpv6if)) {
1943
				/* magic here */
1944
				$dhcpdv6ifs = array_merge($dhcpdv6ifs, get_pppoes_child_interfaces($dhcpv6if));
1945
			} else {
1946
				$realif = get_real_interface($dhcpv6if, "inet6");
1947
				if (stristr("$realif", "bridge")) {
1948
					$mac = get_interface_mac($realif);
1949
					$v6address = generate_ipv6_from_mac($mac);
1950
					/* Create link local address for bridges */
1951
					mwexec("/sbin/ifconfig {$realif} inet6 {$v6address}");
1952
				}
1953
				$realif = escapeshellcmd($realif);
1954
				$dhcpdv6ifs[] = $realif;
1955
			}
1956
		}
1957
	}
1958

    
1959
	if ($nsupdate) {
1960
		$dhcpdv6conf .= "ddns-update-style interim;\n";
1961
		$dhcpdv6conf .= "update-static-leases on;\n";
1962
	} else {
1963
		$dhcpdv6conf .= "ddns-update-style none;\n";
1964
	}
1965

    
1966
	/* write dhcpdv6.conf */
1967
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf", $dhcpdv6conf)) {
1968
		log_error("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1969
		if (platform_booting()) {
1970
			printf("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1971
		}
1972
		unset($dhcpdv6conf);
1973
		return 1;
1974
	}
1975
	unset($dhcpdv6conf);
1976

    
1977
	/* create an empty leases v6 database */
1978
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases")) {
1979
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1980
	}
1981

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

    
1986
	/* fire up dhcpd in a chroot */
1987
	if (count($dhcpdv6ifs) > 0) {
1988
		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 " .
1989
			join(" ", $dhcpdv6ifs));
1990
		mwexec("/usr/local/sbin/dhcpleases6 -c \"/usr/local/bin/php-cgi -f /usr/local/sbin/prefixes.php\" -l {$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1991
	}
1992
	if (platform_booting()) {
1993
		print gettext("done.") . "\n";
1994
	}
1995

    
1996
	return 0;
1997
}
1998

    
1999
function services_igmpproxy_configure($interface='') {
2000
	global $config, $g;
2001

    
2002
	if (!empty($interface) && is_array($config['igmpproxy']['igmpentry'])) { 
2003
		foreach ($config['igmpproxy']['igmpentry'] as $igmpentry) {
2004
			if ($igmpentry['ifname'] == $interface) {
2005
				$igmpinf = true;
2006
				break;
2007
			}
2008
		}
2009
		if (!$igmpinf) {
2010
			return false;
2011
		}
2012
	}
2013

    
2014
	if (!isset($config['igmpproxy']['enable'])) {
2015
		if (isvalidproc("igmpproxy")) {
2016
			log_error(gettext("Stopping IGMP Proxy service."));
2017
			killbyname("igmpproxy");
2018
		}
2019
		return true;
2020
	}
2021
	if (!is_array($config['igmpproxy']['igmpentry']) || (count($config['igmpproxy']['igmpentry']) == 0)) {
2022
		return false;
2023
	}
2024

    
2025
	if (platform_booting()) {
2026
		echo gettext("Starting IGMP Proxy service...");
2027
	}
2028

    
2029
	if (isvalidproc("igmpproxy")) {
2030
		log_error(gettext("Restarting IGMP Proxy service."));
2031
		killbyname("igmpproxy");
2032
	}
2033

    
2034
	$iflist = get_configured_interface_list();
2035

    
2036
	$igmpconf = <<<EOD
2037

    
2038
##------------------------------------------------------
2039
## Enable Quickleave mode (Sends Leave instantly)
2040
##------------------------------------------------------
2041
quickleave
2042

    
2043
EOD;
2044

    
2045
	foreach ($config['igmpproxy']['igmpentry'] as $igmpcf) {
2046
		if (empty($config['interfaces'][$igmpcf['ifname']]['ipaddr'])) {
2047
			continue;
2048
		}
2049
		unset($iflist[$igmpcf['ifname']]);
2050
		$realif = get_real_interface($igmpcf['ifname']);
2051
		if (empty($igmpcf['threshold'])) {
2052
			$threshld = 1;
2053
		} else {
2054
			$threshld = $igmpcf['threshold'];
2055
		}
2056
		$igmpconf .= "phyint {$realif} {$igmpcf['type']} ratelimit 0 threshold {$threshld}\n";
2057

    
2058
		if ($igmpcf['address'] <> "") {
2059
			$item = explode(" ", $igmpcf['address']);
2060
			foreach ($item as $iww) {
2061
				$igmpconf .= "altnet {$iww}\n";
2062
			}
2063
		}
2064
		$igmpconf .= "\n";
2065
		if ($igmpcf['type'] == 'upstream') {
2066
		       $upstream = true;	
2067
		} else {
2068
		       $downstream = true;	
2069
		}
2070
	}
2071
	foreach ($iflist as $ifn) {
2072
		$realif = get_real_interface($ifn);
2073
		$igmpconf .= "phyint {$realif} disabled\n";
2074
	}
2075
	$igmpconf .= "\n";
2076

    
2077
	if (!$upstream || !$downstream) {
2078
		log_error(gettext("Could not find upstream or downstream IGMP Proxy interfaces!"));
2079
		return;
2080
	}
2081

    
2082
	$igmpfl = fopen($g['varetc_path'] . "/igmpproxy.conf", "w");
2083
	if (!$igmpfl) {
2084
		log_error(gettext("Could not write IGMP Proxy configuration file!"));
2085
		return;
2086
	}
2087
	fwrite($igmpfl, $igmpconf);
2088
	fclose($igmpfl);
2089
	unset($igmpconf);
2090

    
2091
	if (isset($config['syslog']['igmpxverbose'])) {
2092
		mwexec_bg("/usr/local/sbin/igmpproxy -v {$g['varetc_path']}/igmpproxy.conf");
2093
	} else {
2094
		mwexec_bg("/usr/local/sbin/igmpproxy {$g['varetc_path']}/igmpproxy.conf");
2095
	}
2096

    
2097
	log_error(gettext("Started IGMP Proxy service."));
2098

    
2099
	if (platform_booting()) {
2100
		echo gettext("done.") . "\n";
2101
	}
2102

    
2103
	return true;
2104
}
2105

    
2106
function services_dhcrelay_configure() {
2107
	global $config, $g;
2108

    
2109
	if (isset($config['system']['developerspew'])) {
2110
		$mt = microtime();
2111
		echo "services_dhcrelay_configure() being called $mt\n";
2112
	}
2113

    
2114
	/* kill any running dhcrelay */
2115
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
2116

    
2117
	init_config_arr(array('dhcrelay'));
2118
	$dhcrelaycfg = &$config['dhcrelay'];
2119

    
2120
	/* DHCPRelay enabled on any interfaces? */
2121
	if (!isset($dhcrelaycfg['enable'])) {
2122
		return 0;
2123
	}
2124

    
2125
	/* Start/Restart DHCP Relay, if a CARP VIP is set, check its status and act
2126
	* appropriately. */
2127
	if (isset($dhcrelaycfg['carpstatusvip']) && ($dhcrelaycfg['carpstatusvip'] != "none")) {
2128
		$status = get_carp_interface_status($dhcrelaycfg['carpstatusvip']);
2129
		switch (strtoupper($status)) {
2130
			// Do not start DHCP Relay service if the VIP is in BACKUP or INIT state.
2131
			case "BACKUP":
2132
			case "INIT":
2133
				log_error("Stopping DHCP Relay (CARP BACKUP/INIT)");
2134
				return 0;
2135
				break;
2136
			// Start the service if the VIP is MASTER state.
2137
			case "MASTER":
2138
			// Assume it's up if the status can't be determined.
2139
			default:
2140
				break;
2141
		}
2142
	}
2143

    
2144
	if (platform_booting()) {
2145
		echo gettext("Starting DHCP Relay service...");
2146
	} else {
2147
		sleep(1);
2148
	}
2149

    
2150
	$iflist = get_configured_interface_list();
2151

    
2152
	$dhcrelayifs = array();
2153
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
2154
	foreach ($dhcifaces as $dhcrelayif) {
2155
		if (!isset($iflist[$dhcrelayif])) {
2156
			continue;
2157
		}
2158

    
2159
		if (get_interface_ip($dhcrelayif)) {
2160
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
2161
		}
2162
	}
2163
	$dhcrelayifs = array_unique($dhcrelayifs);
2164

    
2165
	/*
2166
	 * In order for the relay to work, it needs to be active
2167
	 * on the interface in which the destination server sits.
2168
	 */
2169
	$srvips = explode(",", $dhcrelaycfg['server']);
2170
	if (!is_array($srvips)) {
2171
		log_error(gettext("No destination IP has been configured!"));
2172
		return;
2173
	}
2174
	$srvifaces = array();
2175
	foreach ($srvips as $srcidx => $srvip) {
2176
		$destif = guess_interface_from_ip($srvip);
2177
		if (!empty($destif) && !is_pseudo_interface($destif)) {
2178
			$srvifaces[] = $destif;
2179
		}
2180
	}
2181
	$srvifaces = array_unique($srvifaces);
2182

    
2183
	/* Check for relays in the same subnet as clients so they can bind for
2184
	 * either direction (up or down) */
2185
	$srvrelayifs = array_intersect($dhcrelayifs, $srvifaces);
2186

    
2187
	/* The server interface(s) should not be in this list */
2188
	$dhcrelayifs = array_diff($dhcrelayifs, $srvifaces);
2189

    
2190
	/* Remove the dual-role interfaces from up and down lists */
2191
	$srvifaces = array_diff($srvifaces, $srvrelayifs);
2192
	$dhcrelayifs = array_diff($dhcrelayifs, $srvrelayifs);
2193

    
2194
	/* fire up dhcrelay */
2195
	if (empty($dhcrelayifs) && empty($srvrelayifs)) {
2196
		log_error(gettext("No suitable downstream interfaces found for running dhcrelay!"));
2197
		return; /* XXX */
2198
	}
2199
	if (empty($srvifaces) && empty($srvrelayifs)) {
2200
		log_error(gettext("No suitable upstream interfaces found for running dhcrelay!"));
2201
		return; /* XXX */
2202
	}
2203

    
2204
	$cmd = "/usr/local/sbin/dhcrelay";
2205

    
2206
	if (!empty($dhcrelayifs)) {
2207
		$cmd .= " -id " . implode(" -id ", $dhcrelayifs);
2208
	}
2209
	if (!empty($srvifaces)) {
2210
		$cmd .= " -iu " . implode(" -iu ", $srvifaces);
2211
	}
2212
	if (!empty($srvrelayifs)) {
2213
		$cmd .= " -i " . implode(" -i ", $srvrelayifs);
2214
	}
2215

    
2216
	if (isset($dhcrelaycfg['agentoption'])) {
2217
		$cmd .= " -a -m replace";
2218
	}
2219

    
2220
	$cmd .= " " . implode(" ", $srvips);
2221
	mwexec($cmd);
2222
	unset($cmd);
2223

    
2224
	return 0;
2225
}
2226

    
2227
function services_dhcrelay6_configure() {
2228
	global $config, $g;
2229

    
2230
	if (isset($config['system']['developerspew'])) {
2231
		$mt = microtime();
2232
		echo "services_dhcrelay6_configure() being called $mt\n";
2233
	}
2234

    
2235
	/* kill any running dhcrelay */
2236
	killbypid("{$g['varrun_path']}/dhcrelay6.pid");
2237

    
2238
	init_config_arr(array('dhcrelay6'));
2239
	$dhcrelaycfg = &$config['dhcrelay6'];
2240

    
2241
	/* DHCPv6 Relay enabled on any interfaces? */
2242
	if (!isset($dhcrelaycfg['enable'])) {
2243
		return 0;
2244
	}
2245

    
2246
	/* Start/Restart DHCPv6 Relay, if a CARP VIP is set, check its status and act
2247
	* appropriately. */
2248
	if (isset($dhcrelaycfg['carpstatusvip']) && ($dhcrelaycfg['carpstatusvip'] != "none")) {
2249
		$status = get_carp_interface_status($dhcrelaycfg['carpstatusvip']);
2250
		switch (strtoupper($status)) {
2251
			// Do not start DHCP Relay service if the VIP is in BACKUP or INIT state.
2252
			case "BACKUP":
2253
			case "INIT":
2254
				log_error("Stopping DHCPv6 Relay (CARP BACKUP/INIT)");
2255
				return 0;
2256
				break;
2257
			// Start the service if the VIP is MASTER state.
2258
			case "MASTER":
2259
			// Assume it's up if the status can't be determined.
2260
			default:
2261
				break;
2262
		}
2263
	}
2264

    
2265
	if (platform_booting()) {
2266
		echo gettext("Starting DHCPv6 Relay service...");
2267
	} else {
2268
		sleep(1);
2269
	}
2270

    
2271
	$iflist = get_configured_interface_list();
2272

    
2273
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
2274
	foreach ($dhcifaces as $dhcrelayif) {
2275
		if (!isset($iflist[$dhcrelayif])) {
2276
			continue;
2277
		}
2278

    
2279
		if (get_interface_ipv6($dhcrelayif)) {
2280
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
2281
		}
2282
	}
2283
	$dhcrelayifs = array_unique($dhcrelayifs);
2284

    
2285
	/*
2286
	 * In order for the relay to work, it needs to be active
2287
	 * on the interface in which the destination server sits.
2288
	 */
2289
	$srvips = explode(",", $dhcrelaycfg['server']);
2290
	$srvifaces = array();
2291
	foreach ($srvips as $srcidx => $srvip) {
2292
		$destif = guess_interface_from_ip($srvip);
2293
		if (!empty($destif) && !is_pseudo_interface($destif)) {
2294
			$srvifaces[] = "{$srvip}%{$destif}";
2295
		}
2296
	}
2297

    
2298
	/* fire up dhcrelay */
2299
	if (empty($dhcrelayifs) || empty($srvifaces)) {
2300
		log_error(gettext("No suitable interface found for running dhcrelay -6!"));
2301
		return; /* XXX */
2302
	}
2303

    
2304
	$cmd = "/usr/local/sbin/dhcrelay -6 -pf \"{$g['varrun_path']}/dhcrelay6.pid\"";
2305
	foreach ($dhcrelayifs as $dhcrelayif) {
2306
		$cmd .= " -l {$dhcrelayif}";
2307
	}
2308
	foreach ($srvifaces as $srviface) {
2309
		$cmd .= " -u \"{$srviface}\"";
2310
	}
2311
	mwexec($cmd);
2312
	unset($cmd);
2313

    
2314
	return 0;
2315
}
2316

    
2317
function services_dyndns_configure_client($conf) {
2318

    
2319
	if (!isset($conf['enable'])) {
2320
		return;
2321
	}
2322

    
2323
	/* load up the dyndns.class */
2324
	require_once("dyndns.class");
2325

    
2326
	$dns = new updatedns($dnsService = $conf['type'],
2327
		$dnsHost = $conf['host'],
2328
		$dnsDomain = $conf['domainname'],
2329
		$dnsUser = $conf['username'],
2330
		$dnsPass = $conf['password'],
2331
		$dnsWildcard = $conf['wildcard'],
2332
		$dnsProxied = $conf['proxied'],
2333
		$dnsMX = $conf['mx'],
2334
		$dnsIf = "{$conf['interface']}",
2335
		$dnsBackMX = NULL,
2336
		$dnsServer = NULL,
2337
		$dnsPort = NULL,
2338
		$dnsUpdateURL = "{$conf['updateurl']}",
2339
		$forceUpdate = $conf['force'],
2340
		$dnsZoneID = $conf['zoneid'],
2341
		$dnsTTL = $conf['ttl'],
2342
		$dnsResultMatch = "{$conf['resultmatch']}",
2343
		$dnsRequestIf = "{$conf['requestif']}",
2344
		$dnsMaxCacheAge = $conf['maxcacheage'],
2345
		$dnsID = "{$conf['id']}",
2346
		$dnsVerboseLog = $conf['verboselog'],
2347
		$curlIpresolveV4 = $conf['curl_ipresolve_v4'],
2348
		$curlSslVerifypeer = $conf['curl_ssl_verifypeer'],
2349
		$curlProxy = $conf['curl_proxy']);
2350
}
2351

    
2352
function services_dyndns_configure($int = "") {
2353
	global $config, $g;
2354
	if (isset($config['system']['developerspew'])) {
2355
		$mt = microtime();
2356
		echo "services_dyndns_configure() being called $mt\n";
2357
	}
2358

    
2359
	if (isset($config['dyndnses']['dyndns']) && is_array($config['dyndnses']['dyndns'])) {
2360
		$dyndnscfg = $config['dyndnses']['dyndns'];
2361
	} else {
2362
		return 0;
2363
	}
2364
	$gwgroups = return_gateway_groups_array(true);
2365
	if (is_array($dyndnscfg)) {
2366
		if (platform_booting()) {
2367
			echo gettext("Starting DynDNS clients...");
2368
		}
2369

    
2370
		foreach ($dyndnscfg as $dyndns) {
2371
			/*
2372
			 * If it's using a gateway group, check if interface is
2373
			 * the active gateway for that group
2374
			 */
2375
			$group_int = '';
2376
			$friendly_group_int = '';
2377
			$gwgroup_member = false;
2378
			if (is_array($gwgroups[$dyndns['interface']])) {
2379
				if (!empty($gwgroups[$dyndns['interface']][0]['vip'])) {
2380
					$group_int = $gwgroups[$dyndns['interface']][0]['vip'];
2381
				} else {
2382
					$group_int = $gwgroups[$dyndns['interface']][0]['int'];
2383
					$friendly_group_int =
2384
					    convert_real_interface_to_friendly_interface_name(
2385
						$group_int);
2386
					if (!empty($int)) {
2387
						$gwgroup_member =
2388
						    interface_gateway_group_member(get_real_interface($int),
2389
						    $dyndns['interface']);
2390
					}
2391
				}
2392
			}
2393
			if ((empty($int)) || ($int == $dyndns['interface']) || $gwgroup_member ||
2394
			    ($int == $group_int) || ($int == $friendly_group_int)) {
2395
				$dyndns['verboselog'] = isset($dyndns['verboselog']);
2396
				$dyndns['curl_ipresolve_v4'] = isset($dyndns['curl_ipresolve_v4']);
2397
				$dyndns['curl_ssl_verifypeer'] = isset($dyndns['curl_ssl_verifypeer']);
2398
				$dyndns['proxied'] = isset($dyndns['proxied']);
2399
				$dyndns['wildcard'] = isset($dyndns['wildcard']);
2400
				services_dyndns_configure_client($dyndns);
2401
				sleep(1);
2402
			}
2403
		}
2404

    
2405
		if (platform_booting()) {
2406
			echo gettext("done.") . "\n";
2407
		}
2408
	}
2409

    
2410
	return 0;
2411
}
2412

    
2413
function dyndnsCheckIP($int) {
2414
	global $config, $factory_default_checkipservice;
2415
	$ip_address = get_interface_ip($int);
2416
	if (is_private_ip($ip_address)) {
2417
		$gateways_status = return_gateways_status(true);
2418
		// If the gateway for this interface is down, then the external check cannot work.
2419
		// Avoid the long wait for the external check to timeout.
2420
		if (stristr($gateways_status[$config['interfaces'][$int]['gateway']]['status'], "down")) {
2421
			return "down";
2422
		}
2423

    
2424
		// Append the factory default check IP service to the list (if not disabled).
2425
		if (!isset($config['checkipservices']['disable_factory_default'])) {
2426
			if (!is_array($config['checkipservices'])) {
2427
				$config['checkipservices'] = array();
2428
			}
2429
			if (!is_array($config['checkipservices']['checkipservice'])) {
2430
				$config['checkipservices']['checkipservice'] = array();
2431
			}
2432
			$config['checkipservices']['checkipservice'][] = $factory_default_checkipservice;
2433
		}
2434

    
2435
		// Use the first enabled check IP service as the default.
2436
		if (is_array($config['checkipservices']['checkipservice'])) {
2437
			foreach ($config['checkipservices']['checkipservice'] as $i => $checkipservice) {
2438
				if (isset($checkipservice['enable'])) {
2439
					$url = $checkipservice['url'];
2440
					$username = $checkipservice['username'];
2441
					$password = $checkipservice['password'];
2442
					$verifysslpeer = isset($checkipservice['verifysslpeer']);
2443
					$curl_proxy = isset($checkipservice['curl_proxy']);
2444
					break;
2445
				}
2446
			}
2447
		}
2448

    
2449
		$hosttocheck = $url;
2450
		$ip_ch = curl_init($hosttocheck);
2451
		curl_setopt($ip_ch, CURLOPT_RETURNTRANSFER, 1);
2452
		curl_setopt($ip_ch, CURLOPT_SSL_VERIFYPEER, $verifysslpeer);
2453
		curl_setopt($ip_ch, CURLOPT_INTERFACE, 'host!' . $ip_address);
2454
		curl_setopt($ip_ch, CURLOPT_CONNECTTIMEOUT, '30');
2455
		curl_setopt($ip_ch, CURLOPT_TIMEOUT, 120);
2456
		curl_setopt($ip_ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
2457
		curl_setopt($ip_ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
2458
		curl_setopt($ip_ch, CURLOPT_USERPWD, "{$username}:{$password}");
2459
		if ($curl_proxy) {
2460
			set_curlproxy($ip_ch);
2461
		}
2462
		$ip_result_page = curl_exec($ip_ch);
2463
		curl_close($ip_ch);
2464
		$ip_result_decoded = urldecode($ip_result_page);
2465
		preg_match('=Current IP Address: (.*)</body>=siU', $ip_result_decoded, $matches);
2466

    
2467
		if ($matches[1]) {
2468
			$parsed_ip = trim($matches[1]);
2469
		} else {
2470
			$parsed_ip = trim($ip_result_decoded);
2471
		}
2472

    
2473
		preg_match('=((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])=', $parsed_ip, $matches);
2474
		if ($matches[0]) {
2475
			$ip_address = $matches[0];
2476
		}
2477
	}
2478
	return $ip_address;
2479
}
2480

    
2481
function services_dnsmasq_configure($restart_dhcp = true) {
2482
	global $config, $g;
2483
	$return = 0;
2484

    
2485
	// hard coded args: will be removed to avoid duplication if specified in custom_options
2486
	$standard_args = array(
2487
		"dns-forward-max" => "--dns-forward-max=5000",
2488
		"cache-size" => "--cache-size=10000",
2489
		"local-ttl" => "--local-ttl=1"
2490
	);
2491

    
2492

    
2493
	if (isset($config['system']['developerspew'])) {
2494
		$mt = microtime();
2495
		echo "services_dnsmasq_configure() being called $mt\n";
2496
	}
2497

    
2498
	/* kill any running dnsmasq */
2499
	if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) {
2500
		sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
2501
	}
2502

    
2503
	if (isset($config['dnsmasq']['enable'])) {
2504

    
2505
		if (platform_booting()) {
2506
			echo gettext("Starting DNS forwarder...");
2507
		} else {
2508
			sleep(1);
2509
		}
2510

    
2511
		/* generate hosts file */
2512
		if (system_hosts_generate() != 0) {
2513
			$return = 1;
2514
		}
2515

    
2516
		$args = "";
2517

    
2518
		if (isset($config['dnsmasq']['regdhcp'])) {
2519
			$args .= " --dhcp-hostsfile={$g['etc_path']}/hosts ";
2520
		}
2521

    
2522
		/* Setup listen port, if non-default */
2523
		if (is_port($config['dnsmasq']['port'])) {
2524
			$args .= " --port={$config['dnsmasq']['port']} ";
2525
		}
2526

    
2527
		$listen_addresses = "";
2528
		if (isset($config['dnsmasq']['interface'])) {
2529
			$interfaces = explode(",", $config['dnsmasq']['interface']);
2530
			foreach ($interfaces as $interface) {
2531
				$if = get_real_interface($interface);
2532
				if (does_interface_exist($if)) {
2533
					$laddr = get_interface_ip($interface);
2534
					if (is_ipaddrv4($laddr)) {
2535
						$listen_addresses .= " --listen-address={$laddr} ";
2536
					}
2537
					$laddr6 = get_interface_ipv6($interface);
2538
					if (is_ipaddrv6($laddr6) && !isset($config['dnsmasq']['strictbind'])) {
2539
						/*
2540
						 * XXX: Since dnsmasq does not support link-local address
2541
						 * with scope specified. These checks are being done.
2542
						 */
2543
						if (is_linklocal($laddr6) && strstr($laddr6, "%")) {
2544
							$tmpaddrll6 = explode("%", $laddr6);
2545
							$listen_addresses .= " --listen-address={$tmpaddrll6[0]} ";
2546
						} else {
2547
							$listen_addresses .= " --listen-address={$laddr6} ";
2548
						}
2549
					}
2550
				}
2551
			}
2552
			if (!empty($listen_addresses)) {
2553
				$args .= " {$listen_addresses} ";
2554
				if (isset($config['dnsmasq']['strictbind'])) {
2555
					$args .= " --bind-interfaces ";
2556
				}
2557
			}
2558
		}
2559

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

    
2567
			// Build an array of domain overrides to help in checking for matches.
2568
			$override_a = array();
2569
			if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2570
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2571
					$override_a[$override['domain']] = "y";
2572
				}
2573
			}
2574

    
2575
			// Build an array of the private reverse lookup domain names
2576
			$reverse_domain_a = array("10.in-addr.arpa", "168.192.in-addr.arpa");
2577
			// Unfortunately the 172.16.0.0/12 range does not map nicely to the in-addr.arpa scheme.
2578
			for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) {
2579
				$reverse_domain_a[] = "$subnet_num.172.in-addr.arpa";
2580
			}
2581

    
2582
			// Set the --server parameter to nowhere for each reverse domain name that was not specifically specified in a domain override.
2583
			foreach ($reverse_domain_a as $reverse_domain) {
2584
				if (!isset($override_a[$reverse_domain])) {
2585
					$args .= " --server=/$reverse_domain/ ";
2586
				}
2587
			}
2588
			unset($override_a);
2589
			unset($reverse_domain_a);
2590
		}
2591

    
2592
		/* Setup forwarded domains */
2593
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2594
			foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2595
				if ($override['ip'] == "!") {
2596
					$override['ip'] = "";
2597
				}
2598
				$args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
2599
			}
2600
		}
2601

    
2602
		/* Allow DNS Rebind for forwarded domains */
2603
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2604
			if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2605
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2606
					$args .= ' --rebind-domain-ok=/' . $override['domain'] . '/ ';
2607
				}
2608
			}
2609
		}
2610

    
2611
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2612
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2613
		}
2614

    
2615
		if (isset($config['dnsmasq']['strict_order'])) {
2616
			$args .= " --strict-order ";
2617
		}
2618

    
2619
		if (isset($config['dnsmasq']['domain_needed'])) {
2620
			$args .= " --domain-needed ";
2621
		}
2622

    
2623
		if ($config['dnsmasq']['custom_options']) {
2624
			foreach (preg_split('/\s+/', $config['dnsmasq']['custom_options']) as $c) {
2625
				$args .= " " . escapeshellarg("--{$c}");
2626
				$p = explode('=', $c);
2627
				if (array_key_exists($p[0], $standard_args)) {
2628
					unset($standard_args[$p[0]]);
2629
				}
2630
			}
2631
		}
2632
		$args .= ' ' . implode(' ', array_values($standard_args));
2633

    
2634
		/* run dnsmasq. Use "-C /dev/null" since we use command line args only (Issue #6730) */
2635
		$cmd = "/usr/local/sbin/dnsmasq --all-servers -C /dev/null {$dns_rebind} {$args}";
2636
		//log_error("dnsmasq command: {$cmd}");
2637
		mwexec_bg($cmd);
2638
		unset($args);
2639

    
2640
		system_dhcpleases_configure();
2641

    
2642
		if (platform_booting()) {
2643
			echo gettext("done.") . "\n";
2644
		}
2645
	}
2646

    
2647
	if (!platform_booting() && $restart_dhcp) {
2648
		if (services_dhcpd_configure() != 0) {
2649
			$return = 1;
2650
		}
2651
	}
2652

    
2653
	return $return;
2654
}
2655

    
2656
function services_unbound_configure($restart_dhcp = true, $interface = '') {
2657
	global $config, $g;
2658
	$return = 0;
2659

    
2660
	if (isset($config['system']['developerspew'])) {
2661
		$mt = microtime();
2662
		echo "services_unbound_configure() being called $mt\n";
2663
	}
2664

    
2665
	if (!empty($interface) && isset($config['unbound']['enable']) &&
2666
	    !in_array($interface, explode(',', $config['unbound']['active_interface'])) &&
2667
	    !in_array($interface, explode(',', $config['unbound']['outgoing_interface']))) {
2668
		return $return;
2669
	}
2670

    
2671
	if (isset($config['unbound']['enable'])) {
2672
		require_once('/etc/inc/unbound.inc');
2673

    
2674
		/* Stop Unbound using TERM */
2675
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2676
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
2677
		}
2678

    
2679
		/* If unbound is still running, wait up to 30 seconds for it to terminate. */
2680
		for ($i=1; $i <= 30; $i++) {
2681
			if (is_process_running('unbound')) {
2682
				sleep(1);
2683
			}
2684
		}
2685

    
2686
		$python_mode = false;
2687
		if (isset($config['unbound']['python']) && !empty($config['unbound']['python_script'])) {
2688
			$python_mode = true;
2689
		}
2690

    
2691
		/* Include any additional functions as defined by python script include file */
2692
		if (file_exists("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc")) {
2693
			exec("/usr/local/bin/php -l " . escapeshellarg("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc")
2694
				. " 2>&1", $py_output, $py_retval);
2695
			if ($py_retval == 0) {
2696
				require_once("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc");
2697
			}
2698
		}
2699

    
2700
		/* DNS Resolver python integration */
2701
		if ($python_mode) {
2702
			if (!is_dir("{$g['unbound_chroot_path']}/dev")) {
2703
				safe_mkdir("{$g['unbound_chroot_path']}/dev");
2704
			}
2705
			$status = "/sbin/mount | /usr/bin/grep " .  escapeshellarg("{$g['unbound_chroot_path']}/dev");
2706
			if (!trim($status)) {
2707
				exec("/sbin/mount -t devfs devfs " . escapeshellarg("{$g['unbound_chroot_path']}/dev"));
2708
			}
2709
		} else {
2710
			if (is_dir("{$g['unbound_chroot_path']}/dev")) {
2711
				exec("/sbin/umount -f " . escapeshellarg("{$g['unbound_chroot_path']}/dev"));
2712
			}
2713
		}
2714
		$base_folder = '/usr/local';
2715
		foreach (array('/bin', '/lib') as $dir) {
2716
			$validate = exec("/sbin/mount | /usr/bin/grep " . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir} (nullfs") . " 2>&1");
2717
			if ($python_mode) {
2718

    
2719
				// Add DNS Resolver python integration
2720
				if (empty($validate)) {
2721
					if (!is_dir("{$g['unbound_chroot_path']}{$base_folder}{$dir}")) {
2722
						safe_mkdir("{$g['unbound_chroot_path']}{$base_folder}{$dir}");
2723
					}
2724
					$output = $retval = '';
2725
					exec("/sbin/mount_nullfs -o ro " . escapeshellarg("/usr/local{$dir}") . ' '
2726
					    . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir}") . " 2>&1", $output, $retval);
2727

    
2728
					// Disable Unbound python on mount failure
2729
					if ($retval != 0) {
2730
						$config['unbound']['python'] = '';
2731
						$log_msg = "[Unbound-pymod]: Disabling Unbound python due to failed mount";
2732
						write_config($log_msg);
2733
						log_error($log_msg);
2734
					}
2735
				}
2736
			}
2737

    
2738
			// Remove DNS Resolver python integration
2739
			elseif (!empty($validate)) {
2740
				exec("/sbin/umount -t nullfs " . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir}") . " 2>&1", $output, $retval);
2741
				if ($retval == 0) {
2742
					foreach (array( "/usr/local{$dir}", '/usr/local', '/usr') as $folder) {
2743
						if (!empty($g['unbound_chroot_path']) && $g['unbound_chroot_path'] != '/' && is_dir("{$g['unbound_chroot_path']}{$folder}")) {
2744
							@rmdir(escapeshellarg("{$g['unbound_chroot_path']}{$folder}"));
2745
						}
2746

    
2747
						// Delete remaining subfolders on next loop
2748
						if ($dir == '/bin') {
2749
							break;
2750
						}
2751
					}
2752
				}
2753
				else {
2754
					log_error("[Unbound-pymod]: Failed to unmount!");
2755
				}
2756
			}
2757
		}
2758

    
2759
		if (platform_booting()) {
2760
			echo gettext("Starting DNS Resolver...");
2761
		} else {
2762
			sleep(1);
2763
		}
2764

    
2765
		/* generate hosts file */
2766
		if (system_hosts_generate() != 0) {
2767
			$return = 1;
2768
		}
2769

    
2770
		/* Check here for dhcp6 complete - wait upto 10 seconds */
2771
		if($config['interfaces']["wan"]['ipaddrv6'] == 'dhcp6') {
2772
			$wanif = get_real_interface("wan", "inet6");
2773
			if (platform_booting()) {
2774
				for ($i=1; $i <= 10; $i++) {
2775
					if (!file_exists("/tmp/{$wanif}_dhcp6_complete")) {
2776
						log_error(gettext("Unbound start waiting on dhcp6c."));
2777
						sleep(1);
2778
					} else {
2779
						unlink_if_exists("/tmp/{$wanif}_dhcp6_complete");
2780
						log_error(gettext("dhcp6 init complete. Continuing"));
2781
						break;
2782
					}
2783
				}
2784
			}
2785
		}
2786

    
2787
		sync_unbound_service();
2788
		if (platform_booting()) {
2789
			log_error(gettext("sync unbound done."));
2790
			echo gettext("done.") . "\n";
2791
		}
2792

    
2793
		system_dhcpleases_configure();
2794
	} else {
2795
		/* kill Unbound since it should not be enabled */
2796
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2797
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "KILL");
2798
		}
2799
	}
2800

    
2801
	if (!platform_booting() && $restart_dhcp) {
2802
		if (services_dhcpd_configure() != 0) {
2803
			$return = 1;
2804
		}
2805
	}
2806

    
2807
	return $return;
2808
}
2809

    
2810
function services_snmpd_configure($interface='') {
2811
	global $config, $g;
2812
	if (isset($config['system']['developerspew'])) {
2813
		$mt = microtime();
2814
		echo "services_snmpd_configure() being called $mt\n";
2815
	}
2816

    
2817
	if (!empty($interface) &&
2818
	    !empty($config['snmpd']['bindip']) &&
2819
	    isset($config['snmpd']['enable'])) {
2820
		foreach (explode(",", $config['snmpd']['bindip']) as $bind_to_ip) {
2821
			if ($bind_to_ip == $interface) {
2822
				$interface_restart = true;
2823
				break;
2824
			}
2825
		}
2826
		if (!$interface_restart) {
2827
			return 0;
2828
		}
2829
	}
2830

    
2831
	/* kill any running snmpd */
2832
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
2833
	sleep(2);
2834
	if (is_process_running("bsnmpd")) {
2835
		mwexec("/usr/bin/killall bsnmpd", true);
2836
	}
2837

    
2838
	if (isset($config['snmpd']['enable'])) {
2839

    
2840
		if (platform_booting()) {
2841
			echo gettext("Starting SNMP daemon... ");
2842
		}
2843

    
2844
		/* Make sure a printcap file exists or else bsnmpd will log errors. See https://redmine.pfsense.org/issues/6838 */
2845
		if (!file_exists('/etc/printcap')) {
2846
			@file_put_contents('/etc/printcap', "# Empty file to prevent bsnmpd from logging errors.\n");
2847
		}
2848

    
2849
		/* generate snmpd.conf */
2850
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
2851
		if (!$fd) {
2852
			printf(gettext("Error: cannot open snmpd.conf in services_snmpd_configure().%s"), "\n");
2853
			return 1;
2854
		}
2855

    
2856

    
2857
		$snmpdconf = <<<EOD
2858
location := "{$config['snmpd']['syslocation']}"
2859
contact := "{$config['snmpd']['syscontact']}"
2860
read := "{$config['snmpd']['rocommunity']}"
2861

    
2862
EOD;
2863

    
2864
/* No docs on what write strings do there so disable for now.
2865
		if (isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])) {
2866
			$snmpdconf .= <<<EOD
2867
# write string
2868
write := "{$config['snmpd']['rwcommunity']}"
2869

    
2870
EOD;
2871
		}
2872
*/
2873

    
2874

    
2875
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2876
			$snmpdconf .= <<<EOD
2877
# SNMP Trap support.
2878
traphost := {$config['snmpd']['trapserver']}
2879
trapport := {$config['snmpd']['trapserverport']}
2880
trap := "{$config['snmpd']['trapstring']}"
2881

    
2882

    
2883
EOD;
2884
		}
2885

    
2886
		$sysDescr = "{$g['product_label']} {$config['system']['hostname']}.{$config['system']['domain']}" .
2887
			" {$g['product_version_string']} " . php_uname("s") .
2888
			" " . php_uname("r") . " " . php_uname("m");
2889

    
2890
		$snmpdconf .= <<<EOD
2891
system := 1     # pfSense
2892
%snmpd
2893
sysDescr			= "{$sysDescr}"
2894
begemotSnmpdDebugDumpPdus       = 2
2895
begemotSnmpdDebugSyslogPri      = 7
2896
begemotSnmpdCommunityString.0.1 = $(read)
2897

    
2898
EOD;
2899

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

    
2905
EOD;
2906
		}
2907
*/
2908

    
2909

    
2910
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2911
			$snmpdconf .= <<<EOD
2912
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
2913
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
2914
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
2915

    
2916
EOD;
2917
		}
2918

    
2919

    
2920
		$snmpdconf .= <<<EOD
2921
begemotSnmpdCommunityDisable    = 1
2922

    
2923
EOD;
2924

    
2925
		$bind_to_ips = array();
2926
		$bind_to_ip6s = array();
2927
		if (isset($config['snmpd']['bindip'])) {
2928
			if (!isset($config['snmpd']['ipprotocol']) ||
2929
			    (isset($config['snmpd']['ipprotocol']) &&
2930
			    strstr($config['snmpd']['ipprotocol'], "4"))) {
2931
				$inet4 = true;
2932
			}
2933
			if (isset($config['snmpd']['ipprotocol']) &&
2934
			    strstr($config['snmpd']['ipprotocol'], "6")) {
2935
				$inet6 = true;
2936
			}
2937
			foreach (explode(",", $config['snmpd']['bindip']) as $bind_to_ip) {
2938
				if (is_ipaddr($bind_to_ip)) {
2939
					$bind_to_ips[] = $bind_to_ip;
2940
				} else {
2941
					$if = get_real_interface($bind_to_ip);
2942
					if (does_interface_exist($if)) {
2943
						if ($inet4) {
2944
							$bindip = get_interface_ip($bind_to_ip);
2945
							if (is_ipaddrv4($bindip)) {
2946
								$bind_to_ips[] = $bindip;
2947
							}
2948
						}
2949
						if ($inet6) {
2950
							$bindip6 = get_interface_ipv6($bind_to_ip);
2951
							if (is_ipaddrv6($bindip6)) {
2952
								$bind_to_ip6s[] = $bindip6;
2953
							}
2954
						}
2955
					}
2956
				}
2957
			}
2958
		}
2959
		if (!count($bind_to_ips) && $inet4) {
2960
			$bind_to_ips = array("0.0.0.0");
2961
		}
2962
		if (!count($bind_to_ip6s) && $inet6) {
2963
			$bind_to_ip6s = array("::");
2964
		}
2965

    
2966
		if (is_port($config['snmpd']['pollport'])) {
2967
			foreach ($bind_to_ips as $bind_to_ip) {
2968
				$snmpdconf .= <<<EOD
2969
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
2970

    
2971
EOD;
2972

    
2973
			}
2974
			foreach ($bind_to_ip6s as $bind_to_ip6) {
2975
				$bind_to_ip6 = ip6_to_asn1($bind_to_ip6);
2976
				$snmpdconf .= <<<EOD
2977
begemotSnmpdTransInetStatus.2.16.{$bind_to_ip6}{$config['snmpd']['pollport']}.1 = 4
2978

    
2979
EOD;
2980

    
2981
			}
2982
		}
2983

    
2984
		$snmpdconf .= <<<EOD
2985
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
2986
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
2987

    
2988
# These are bsnmp macros not php vars.
2989
sysContact      = $(contact)
2990
sysLocation     = $(location)
2991
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
2992

    
2993
snmpEnableAuthenTraps = 2
2994

    
2995
EOD;
2996

    
2997
		if (is_array($config['snmpd']['modules'])) {
2998
			if (isset($config['snmpd']['modules']['mibii'])) {
2999
			$snmpdconf .= <<<EOD
3000
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
3001

    
3002
EOD;
3003
			}
3004

    
3005
			if (isset($config['snmpd']['modules']['netgraph'])) {
3006
				$snmpdconf .= <<<EOD
3007
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
3008
%netgraph
3009
begemotNgControlNodeName = "snmpd"
3010

    
3011
EOD;
3012
			}
3013

    
3014
			if (isset($config['snmpd']['modules']['pf'])) {
3015
				$snmpdconf .= <<<EOD
3016
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
3017

    
3018
EOD;
3019
			}
3020

    
3021
			if (isset($config['snmpd']['modules']['hostres'])) {
3022
				$snmpdconf .= <<<EOD
3023
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
3024

    
3025
EOD;
3026
			}
3027

    
3028
			if (isset($config['snmpd']['modules']['bridge'])) {
3029
				$snmpdconf .= <<<EOD
3030
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
3031
# config must end with blank line
3032

    
3033
EOD;
3034
			}
3035
			if (isset($config['snmpd']['modules']['ucd'])) {
3036
				$snmpdconf .= <<<EOD
3037
begemotSnmpdModulePath."ucd"     = "/usr/local/lib/snmp_ucd.so"
3038

    
3039
EOD;
3040
			}
3041
			if (isset($config['snmpd']['modules']['regex'])) {
3042
				$snmpdconf .= <<<EOD
3043
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"
3044

    
3045
EOD;
3046
			}
3047
		}
3048

    
3049
		fwrite($fd, $snmpdconf);
3050
		fclose($fd);
3051
		unset($snmpdconf);
3052

    
3053
		/* run bsnmpd */
3054
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
3055
			" -p {$g['varrun_path']}/snmpd.pid");
3056

    
3057
		if (platform_booting()) {
3058
			echo gettext("done.") . "\n";
3059
		}
3060
	}
3061

    
3062
	return 0;
3063
}
3064

    
3065
function services_dnsupdate_process($int = "", $updatehost = "", $forced = false) {
3066
	global $config, $g;
3067
	if (isset($config['system']['developerspew'])) {
3068
		$mt = microtime();
3069
		echo "services_dnsupdate_process() being called $mt\n";
3070
	}
3071

    
3072
	/* Dynamic DNS updating active? */
3073
	if (!is_array($config['dnsupdates']['dnsupdate'])) {
3074
		return 0;
3075
	}
3076

    
3077
	$notify_text = "";
3078
	$gwgroups = return_gateway_groups_array(true);
3079
	foreach ($config['dnsupdates']['dnsupdate'] as $i => $dnsupdate) {
3080
		if (!isset($dnsupdate['enable'])) {
3081
			continue;
3082
		}
3083
		/*
3084
		 * If it's using a gateway group, check if interface is
3085
		 * the active gateway for that group
3086
		 */
3087
		$group_int = '';
3088
		$friendly_group_int = '';
3089
		$gwgroup_member = false;
3090
		if (is_array($gwgroups[$dnsupdate['interface']])) {
3091
			if (!empty($gwgroups[$dnsupdate['interface']][0]['vip'])) {
3092
				$group_int = $gwgroups[$dnsupdate['interface']][0]['vip'];
3093
			} else {
3094
				$group_int = $gwgroups[$dnsupdate['interface']][0]['int'];
3095
				$friendly_group_int =
3096
				    convert_real_interface_to_friendly_interface_name(
3097
					$group_int);
3098
				if (!empty($int)) {
3099
					$gwgroup_member =
3100
					    interface_gateway_group_member(get_real_interface($int),
3101
					    $dnsupdate['interface']);
3102
				}
3103
			}
3104
		}
3105
		if (!empty($int) && ($int != $dnsupdate['interface']) && !$gwgroup_member &&
3106
		    ($int != $group_int) && ($int != $friendly_group_int)) {
3107
			continue;
3108
		}
3109
		if (!empty($updatehost) && ($updatehost != $dnsupdate['host'])) {
3110
			continue;
3111
		}
3112

    
3113
		/* determine interface name */
3114
		$if = get_failover_interface($dnsupdate['interface']);
3115

    
3116
		/* Determine address to update and default binding address */
3117
		if (isset($dnsupdate['usepublicip'])) {
3118
			$wanip = dyndnsCheckIP($if);
3119
			if (is_private_ip($wanip)) {
3120
				log_error(sprintf(gettext(
3121
				    "phpDynDNS: Not updating %s A record because the public IP address cannot be determined."),
3122
				    $dnsupdate['host']));
3123
				continue;
3124
			}
3125
			$bindipv4 = get_interface_ip($if);
3126
		} else {
3127
			$wanip = get_interface_ip($if);
3128
			$bindipv4 = $wanip;
3129
		}
3130
		if (is_stf_interface($dnsupdate['interface'])) { 
3131
			$wanipv6 = get_interface_ipv6($dnsupdate['interface'] . '_stf');
3132
		} else {
3133
			$wanipv6 = get_interface_ipv6($if);
3134
		}
3135
		$bindipv6 = $wanipv6;
3136

    
3137
		/* Handle non-default interface bindings */
3138
		if ($dnsupdate['updatesource'] == "none") {
3139
			/* When empty, the directive will be omitted. */
3140
			$bindipv4 = "";
3141
			$bindipv6 = "";
3142
		} elseif (!empty($dnsupdate['updatesource'])) {
3143
			/* Find the alternate binding address */
3144
			$bindipv4 = get_interface_ip($dnsupdate['updatesource']);
3145
			if (is_stf_interface($dnsupdate['interface'])) { 
3146
				$bindipv6 = get_interface_ipv6($dnsupdate['updatesource'] . '_stf');
3147
			} else {
3148
				$bindipv6 = get_interface_ipv6($dnsupdate['updatesource']);
3149
			}
3150
		}
3151

    
3152
		/* Handle IPv4/IPv6 selection for the update source interface/VIP */
3153
		switch ($dnsupdate['updatesourcefamily']) {
3154
			case "inet":
3155
				$bindip = $bindipv4;
3156
				break;
3157
			case "inet6":
3158
				$bindip = $bindipv6;
3159
				break;
3160
			case "":
3161
			default:
3162
				/* Try IPv4 first, if that is empty, try IPv6. */
3163
				/* Only specify the address if it's present, otherwise omit. */
3164
				if (!empty($bindipv4)) {
3165
					$bindip = $bindipv4;
3166
				} elseif (!empty($bindipv6)) {
3167
					$bindip = $bindipv6;
3168
				}
3169
				break;
3170
		}
3171

    
3172
		$cacheFile = $g['conf_path'] .
3173
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
3174
		    escapeshellarg($dnsupdate['host']) .
3175
		    "_{$dnsupdate['server']}.cache";
3176
		$cacheFilev6 = $g['conf_path'] .
3177
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
3178
		    escapeshellarg($dnsupdate['host']) .
3179
		    "_{$dnsupdate['server']}_v6.cache";
3180
		$currentTime = time();
3181

    
3182
		if (!$wanip && !$wanipv6) {
3183
			continue;
3184
		}
3185

    
3186
		$keyname = $dnsupdate['keyname'];
3187
		/* trailing dot */
3188
		if (substr($keyname, -1) != ".") {
3189
			$keyname .= ".";
3190
		}
3191

    
3192
		$hostname = $dnsupdate['host'];
3193
		/* trailing dot */
3194
		if (substr($hostname, -1) != ".") {
3195
			$hostname .= ".";
3196
		}
3197

    
3198
		/* write key file */
3199
		$algorithm = empty($dnsupdate['keyalgorithm']) ? 'hmac-md5' : $dnsupdate['keyalgorithm'];
3200
		$upkey = <<<EOD
3201
key "{$keyname}" {
3202
	algorithm {$algorithm};
3203
	secret "{$dnsupdate['keydata']}";
3204
};
3205

    
3206
EOD;
3207
		@file_put_contents("{$g['varetc_path']}/nsupdatekey{$i}", $upkey);
3208

    
3209
		/* generate update instructions */
3210
		$upinst = "";
3211
		if (!empty($dnsupdate['server'])) {
3212
			$upinst .= "server {$dnsupdate['server']}\n";
3213
		}
3214

    
3215
		if (!empty($dnsupdate['zone'])) {
3216
			$upinst .= "zone {$dnsupdate['zone']}\n";
3217
		}
3218

    
3219
		$cachedipv4 = '';
3220
		$cacheTimev4 = 0;
3221
		if (file_exists($cacheFile)) {
3222
			list($cachedipv4, $cacheTimev4) = explode("|",
3223
			    file_get_contents($cacheFile));
3224
		}
3225
		$cachedipv6 = '';
3226
		$cacheTimev6 = 0;
3227
		if (file_exists($cacheFilev6)) {
3228
			list($cachedipv6, $cacheTimev6) = explode("|",
3229
			    file_get_contents($cacheFilev6));
3230
		}
3231

    
3232
		// 25 Days
3233
		$maxCacheAgeSecs = 25 * 24 * 60 * 60;
3234
		$need_update = false;
3235

    
3236
		/* Update IPv4 if we have it. */
3237
		if (is_ipaddrv4($wanip) && $dnsupdate['recordtype'] != "AAAA") {
3238
			if (($wanip != $cachedipv4) || $forced ||
3239
			    (($currentTime - $cacheTimev4) > $maxCacheAgeSecs)) {
3240
				$upinst .= "update delete " .
3241
				    "{$dnsupdate['host']}. A\n";
3242
				$upinst .= "update add {$dnsupdate['host']}. " .
3243
				    "{$dnsupdate['ttl']} A {$wanip}\n";
3244
				if (!empty($bindip)) {
3245
					$upinst .= "local {$bindip}\n";
3246
				}
3247
				$need_update = true;
3248
			} else {
3249
				log_error(sprintf(gettext(
3250
				    "phpDynDNS: Not updating %s A record because the IP address has not changed."),
3251
				    $dnsupdate['host']));
3252
			}
3253
		} else {
3254
			@unlink($cacheFile);
3255
			unset($cacheFile);
3256
		}
3257

    
3258
		/* Update IPv6 if we have it. */
3259
		if (is_ipaddrv6($wanipv6) && $dnsupdate['recordtype'] != "A") {
3260
			if (($wanipv6 != $cachedipv6) || $forced ||
3261
			    (($currentTime - $cacheTimev6) > $maxCacheAgeSecs)) {
3262
				$upinst .= "update delete " .
3263
				    "{$dnsupdate['host']}. AAAA\n";
3264
				$upinst .= "update add {$dnsupdate['host']}. " .
3265
				    "{$dnsupdate['ttl']} AAAA {$wanipv6}\n";
3266
				$need_update = true;
3267
			} else {
3268
				log_error(sprintf(gettext(
3269
				    "phpDynDNS: Not updating %s AAAA record because the IPv6 address has not changed."),
3270
				    $dnsupdate['host']));
3271
			}
3272
		} else {
3273
			@unlink($cacheFilev6);
3274
			unset($cacheFilev6);
3275
		}
3276

    
3277
		$upinst .= "\n";	/* mind that trailing newline! */
3278

    
3279
		if (!$need_update) {
3280
			continue;
3281
		}
3282

    
3283
		@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}", $upinst);
3284
		unset($upinst);
3285
		/* invoke nsupdate */
3286
		$cmd = "/usr/local/bin/nsupdate -k {$g['varetc_path']}/nsupdatekey{$i}";
3287

    
3288
		if (isset($dnsupdate['usetcp'])) {
3289
			$cmd .= " -v";
3290
		}
3291

    
3292
		$cmd .= " {$g['varetc_path']}/nsupdatecmds{$i}";
3293

    
3294
		if (mwexec($cmd) == 0) {
3295
			if (!empty($cacheFile)) {
3296
				@file_put_contents($cacheFile,
3297
				    "{$wanip}|{$currentTime}");
3298
				log_error(sprintf(gettext(
3299
				    'phpDynDNS: updating cache file %1$s: %2$s'),
3300
				    $cacheFile, $wanip));
3301
				$notify_text .= sprintf(gettext(
3302
				    'DynDNS updated IP Address (A) for %1$s on %2$s (%3$s) to %4$s'),
3303
				    $dnsupdate['host'],
3304
				    convert_real_interface_to_friendly_descr($if),
3305
				    $if, $wanip) . "\n";
3306
			}
3307
			if (!empty($cacheFilev6)) {
3308
				@file_put_contents($cacheFilev6,
3309
				    "{$wanipv6}|{$currentTime}");
3310
				log_error(sprintf(gettext(
3311
				    'phpDynDNS: updating cache file %1$s: %2$s'),
3312
				    $cacheFilev6, $wanipv6));
3313
				$notify_text .= sprintf(gettext(
3314
				    'DynDNS updated IPv6 Address (AAAA) for %1$s on %2$s (%3$s) to %4$s'),
3315
				    $dnsupdate['host'],
3316
				    convert_real_interface_to_friendly_descr($if),
3317
				    $if, $wanipv6) . "\n";
3318
			}
3319
		} else {
3320
			if (!empty($cacheFile)) {
3321
				log_error(sprintf(gettext(
3322
				    'phpDynDNS: ERROR while updating IP Address (A) for %1$s (%2$s)'),
3323
				    $dnsupdate['host'], $wanip));
3324
			}
3325
			if (!empty($cacheFilev6)) {
3326
				log_error(sprintf(gettext(
3327
				    'phpDynDNS: ERROR while updating IP Address (AAAA) for %1$s (%2$s)'),
3328
				    $dnsupdate['host'], $wanipv6));
3329
			}
3330
		}
3331
		unset($cmd);
3332
	}
3333

    
3334
	if (!empty($notify_text)) {
3335
		notify_all_remote($notify_text);
3336
	}
3337

    
3338
	return 0;
3339
}
3340

    
3341
/* configure cron service */
3342
function configure_cron() {
3343
	global $g, $config;
3344

    
3345
	/* preserve existing crontab entries */
3346
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
3347

    
3348
	for ($i = 0; $i < count($crontab_contents); $i++) {
3349
		$cron_item = &$crontab_contents[$i];
3350
		if (strpos($cron_item, "# pfSense specific crontab entries") !== false) {
3351
			array_splice($crontab_contents, $i - 1);
3352
			break;
3353
		}
3354
	}
3355
	$crontab_contents = implode("\n", $crontab_contents) . "\n";
3356

    
3357

    
3358
	if (is_array($config['cron']['item'])) {
3359
		$crontab_contents .= "#\n";
3360
		$crontab_contents .= "# pfSense specific crontab entries\n";
3361
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
3362
		$crontab_contents .= "#\n";
3363

    
3364
		if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) {
3365
			$http_proxy = $config['system']['proxyurl'];
3366
			if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) {
3367
				$http_proxy .= ':' . $config['system']['proxyport'];
3368
			}
3369
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
3370

    
3371
			if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
3372
				$crontab_contents .= "HTTP_PROXY_AUTH=basic:*:{$config['system']['proxyuser']}:{$config['system']['proxypass']}";
3373
			}
3374
		}
3375

    
3376
		foreach ($config['cron']['item'] as $item) {
3377
			$crontab_contents .= "\n{$item['minute']}\t";
3378
			$crontab_contents .= "{$item['hour']}\t";
3379
			$crontab_contents .= "{$item['mday']}\t";
3380
			$crontab_contents .= "{$item['month']}\t";
3381
			$crontab_contents .= "{$item['wday']}\t";
3382
			$crontab_contents .= "{$item['who']}\t";
3383
			$crontab_contents .= "{$item['command']}";
3384
		}
3385

    
3386
		$crontab_contents .= "\n#\n";
3387
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
3388
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
3389
		$crontab_contents .= "#\n\n";
3390
	}
3391

    
3392
	/* please maintain the newline at the end of file */
3393
	file_put_contents("/etc/crontab", $crontab_contents);
3394
	unset($crontab_contents);
3395

    
3396
	/* make sure that cron is running and start it if it got killed somehow */
3397
	if (!is_process_running("cron")) {
3398
		exec("cd /tmp && /usr/sbin/cron -s 2>/dev/null");
3399
	} else {
3400
	/* do a HUP kill to force sync changes */
3401
		sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP");
3402
	}
3403

    
3404
}
3405

    
3406
function upnp_action ($action) {
3407
	global $g, $config;
3408
	switch ($action) {
3409
		case "start":
3410
			if (file_exists('/var/etc/miniupnpd.conf')) {
3411
				@unlink("{$g['varrun_path']}/miniupnpd.pid");
3412
				mwexec_bg("/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf -P {$g['varrun_path']}/miniupnpd.pid");
3413
			}
3414
			break;
3415
		case "stop":
3416
			killbypid("{$g['varrun_path']}/miniupnpd.pid");
3417
			while ((int)exec("/bin/pgrep -a miniupnpd | wc -l") > 0) {
3418
				mwexec('/usr/bin/killall miniupnpd 2>/dev/null', true);
3419
			}
3420
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
3421
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
3422
			break;
3423
		case "restart":
3424
			upnp_action('stop');
3425
			upnp_action('start');
3426
			break;
3427
	}
3428
}
3429

    
3430
function upnp_start() {
3431
	global $config;
3432

    
3433
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
3434
		return;
3435
	}
3436

    
3437
	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
3438
		echo gettext("Starting UPnP service... ");
3439
		require_once('/usr/local/pkg/miniupnpd.inc');
3440
		sync_package_miniupnpd();
3441
		echo "done.\n";
3442
	}
3443
}
3444

    
3445
function install_cron_job($command, $active = false, $minute = "0", $hour = "*", $monthday = "*", $month = "*", $weekday = "*", $who = "root", $write_config = true) {
3446
	global $config, $g;
3447

    
3448
	$is_installed = false;
3449
	$cron_changed = true;
3450
	$change_message = "";
3451

    
3452
	if (!is_array($config['cron'])) {
3453
		$config['cron'] = array();
3454
	}
3455
	if (!is_array($config['cron']['item'])) {
3456
		$config['cron']['item'] = array();
3457
	}
3458

    
3459
	$x = 0;
3460
	foreach ($config['cron']['item'] as $item) {
3461
		if (strstr($item['command'], $command)) {
3462
			$is_installed = true;
3463
			break;
3464
		}
3465
		$x++;
3466
	}
3467

    
3468
	if ($active) {
3469
		$cron_item = array();
3470
		$cron_item['minute'] = $minute;
3471
		$cron_item['hour'] = $hour;
3472
		$cron_item['mday'] = $monthday;
3473
		$cron_item['month'] = $month;
3474
		$cron_item['wday'] = $weekday;
3475
		$cron_item['who'] = $who;
3476
		$cron_item['command'] = $command;
3477
		if (!$is_installed) {
3478
			$config['cron']['item'][] = $cron_item;
3479
			$change_message = "Installed cron job for %s";
3480
		} else {
3481
			if ($config['cron']['item'][$x] == $cron_item) {
3482
				$cron_changed = false;
3483
			} else {
3484
				$config['cron']['item'][$x] = $cron_item;
3485
				$change_message = "Updated cron job for %s";
3486
			}
3487
		}
3488
	} else {
3489
		if ($is_installed == true) {
3490
			array_splice($config['cron']['item'], $x, 1);
3491
			$change_message = "Removed cron job for %s";
3492
		} else {
3493
			$cron_changed = false;
3494
		}
3495
	}
3496

    
3497
	if ($cron_changed) {
3498
		/* Optionally write the configuration if this function made changes.
3499
		 * Performing a write_config() in this way can have unintended side effects. See #7146
3500
		 * Base system instances of this function do not need to write, packages may.
3501
		 */
3502
		if ($write_config) {
3503
			write_config(sprintf(gettext($change_message), $command));
3504
		}
3505
		configure_cron();
3506
	}
3507
}
3508

    
3509
?>
(46-46/61)