Project

General

Profile

Download (109 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 $g;
35

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

    
41
	init_config_arr(['dhcpdv6']);
42

    
43
	$Iflist = get_configured_interface_list();
44
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
45

    
46
	$radvdconf = "# Automatically Generated, do not edit\n";
47

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

    
51
	/* handle manually configured DHCP6 server settings first */
52
	foreach (config_get_path('dhcpdv6', []) as $dhcpv6if => $dhcpv6ifconf) {
53
		if (!config_path_enabled("interfaces/{$dhcpv6if}")) {
54
			continue;
55
		}
56

    
57
		/* Do not put in the config an interface which is down */
58
		if (isset($blacklist[$dhcpv6if])) {
59
			continue;
60
		}
61
		if (!isset($dhcpv6ifconf['ramode'])) {
62
			$dhcpv6ifconf['ramode'] = $dhcpv6ifconf['mode'];
63
		}
64

    
65
		/* are router advertisements enabled? */
66
		if ($dhcpv6ifconf['ramode'] == "disabled") {
67
			continue;
68
		}
69

    
70
		if (!isset($dhcpv6ifconf['rapriority'])) {
71
			$dhcpv6ifconf['rapriority'] = "medium";
72
		}
73

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

    
90
		$realif = get_real_interface($dhcpv6if, "inet6");
91

    
92
		if (isset($radvdifs[$realif])) {
93
			continue;
94
		}
95

    
96
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
97
		if (!is_ipaddrv6($ifcfgipv6)) {
98
			continue;
99
		}
100

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

    
109
		$radvdconf .= "# Generated for DHCPv6 Server $dhcpv6if\n";
110
		$radvdconf .= "interface {$realif} {\n";
111
		if (strstr($realif, "ovpn")) {
112
			$radvdconf .= "\tUnicastOnly on;\n";
113
		}
114
		$radvdconf .= "\tAdvSendAdvert on;\n";
115

    
116
		if ($rasrcaddr) {
117
			$radvdconf .= "\tAdvRASrcAddress {\n";
118
			$radvdconf .= "\t\t{$rasrcaddr};\n";
119
			$radvdconf .= "\t};\n";
120
		}
121

    
122
		if (is_numericint($dhcpv6ifconf['raminrtradvinterval'])) {
123
			$radvdconf .= "\tMinRtrAdvInterval {$dhcpv6ifconf['raminrtradvinterval']};\n";
124
		} else {
125
			$radvdconf .= "\tMinRtrAdvInterval 200;\n";
126
		}
127

    
128
		if (is_numericint($dhcpv6ifconf['ramaxrtradvinterval'])) {
129
			$ramaxrtradvinterval = $dhcpv6ifconf['ramaxrtradvinterval'];
130
		} else {
131
			$ramaxrtradvinterval = 600;
132
		}
133
		$radvdconf .= "\tMaxRtrAdvInterval {$ramaxrtradvinterval};\n";
134
		if (is_numericint($dhcpv6ifconf['raadvdefaultlifetime'])) {
135
			$raadvdefaultlifetime = $dhcpv6ifconf['raadvdefaultlifetime'];
136
		} else {
137
			$raadvdefaultlifetime = $ramaxrtradvinterval * 3;
138
		}
139
		$radvdconf .= "\tAdvDefaultLifetime {$raadvdefaultlifetime};\n";
140

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

    
195
		if (is_numericint($dhcpv6ifconf['ravalidlifetime'])) {
196
		  $radvdconf .= "\t\tAdvValidLifetime {$dhcpv6ifconf['ravalidlifetime']};\n";
197
		} else {
198
		  $radvdconf .= "\t\tAdvValidLifetime 86400;\n";
199
		}
200

    
201
		if (is_numericint($dhcpv6ifconf['rapreferredlifetime'])) {
202
		  $radvdconf .= "\t\tAdvPreferredLifetime {$dhcpv6ifconf['rapreferredlifetime']};\n";
203
		} else {
204
		  $radvdconf .= "\t\tAdvPreferredLifetime 14400;\n";
205
		}
206

    
207
		$radvdconf .= "\t};\n";
208

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

    
249
		if ($rasrcaddr) {
250
			$radvdconf .= "\t\tRemoveRoute off;\n";
251
		}
252
		else {
253
			$radvdconf .= "\t\tRemoveRoute on;\n";
254
		}
255
		$radvdconf .= "\t};\n";
256

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

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

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

    
349
		$realif = get_real_interface($if, "inet6");
350

    
351
		/* prevent duplicate entries, manual overrides */
352
		if (isset($radvdifs[$realif])) {
353
			continue;
354
		}
355

    
356
		$ifcfgipv6 = get_interface_ipv6($if);
357
		if (!is_ipaddrv6($ifcfgipv6)) {
358
			$subnetv6 = "::";
359
			$ifcfgsnv6 = "64";
360
		} else {
361
			$ifcfgsnv6 = get_interface_subnetv6($if);
362
			$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
363
		}
364
		$radvdifs[$realif] = $realif;
365

    
366
		$autotype = config_get_path("interfaces/{$trackif}/ipaddrv6");
367

    
368
		if ($g['debug']) {
369
			log_error("configuring RA on {$if} for type {$autotype} radvd subnet {$subnetv6}/{$ifcfgsnv6}");
370
		}
371

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

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

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

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

    
454
function services_dhcpd_configure($family = "all", $blacklist = array()) {
455
	global $g;
456

    
457
	$dhcpdconfigurelck = lock("dhcpdconfigure", LOCK_EX);
458

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

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

    
482
	if ($family == "all" || $family == "inet") {
483
		services_dhcpdv4_configure();
484
	}
485
	if ($family == "all" || $family == "inet6") {
486
		services_dhcpdv6_configure($blacklist);
487
		services_radvd_configure($blacklist);
488
	}
489

    
490
	unlock($dhcpdconfigurelck);
491
}
492

    
493
function services_dhcpdv4_configure() {
494
	global $g;
495
	$need_ddns_updates = false;
496
	$ddns_zones = array();
497

    
498
	if ($g['services_dhcp_server_enable'] == false) {
499
		return;
500
	}
501

    
502
	if (config_path_enabled('system','developerspew')) {
503
		$mt = microtime();
504
		echo "services_dhcpdv4_configure($if) being called $mt\n";
505
	}
506

    
507
	/* kill any running dhcpd */
508
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid")) {
509
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid");
510
	}
511

    
512
	/* DHCP enabled on any interfaces? */
513
	if (!is_dhcp_server_enabled()) {
514
		return 0;
515
	}
516

    
517
	$syscfg = config_get_path('system');
518
	init_config_arr(['dhcpd']);
519
	$dhcpdcfg = config_get_path('dhcpd');
520
	$Iflist = get_configured_interface_list();
521

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

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

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

    
618
	$dhcpdconf = <<<EOD
619

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

    
632
EOD;
633

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

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

    
646
		// OMAPI Settings
647
		if (isset($dhcpifconf['omapi_port']) && is_numeric($dhcpifconf['omapi_port'])) {
648
			$dhcpdconf .= <<<EOD
649

    
650
key omapi_key {
651
  algorithm {$dhcpifconf['omapi_key_algorithm']};
652
  secret "{$dhcpifconf['omapi_key']}";
653
};
654
omapi-port {$dhcpifconf['omapi_port']};
655
omapi-key omapi_key;
656

    
657
EOD;
658

    
659
		}
660
		break;
661
	}
662

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

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

    
680
		if (!config_path_enabled("interfaces/{$dhcpif}")) {
681
			continue;
682
		}
683

    
684
		interfaces_staticarp_configure($dhcpif);
685

    
686
		if (!isset($dhcpifconf['enable'])) {
687
			continue;
688
		}
689

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

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

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

    
754
		$newzone = array();
755
		$ifcfg = config_get_path("interfaces/{$dhcpif}");
756

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

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

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

    
775
		$dnscfg = "";
776

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
964
			$pdnscfg = "";
965

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1235
			$pxeif = false;
1236
			if (is_array($pxe_files) && !empty($pxe_files)) {
1237
				foreach ($pxe_files as $pxe) {
1238
					if ($pxe[0] == 'HTTPClient') {
1239
						$expr = "substring (option vendor-class-identifier, 0, 10) = \"HTTPClient\" {\n";
1240
					} else {
1241
						$expr = "option arch = {$pxe[0]} {\n";
1242
					}
1243
					if (!$pxeif) {
1244
						$dhcpdconf .= "	if " . $expr; 
1245
						$pxeif = true;
1246
					} else {
1247
						$dhcpdconf .= " else if " . $expr; 
1248
					}
1249
					$dhcpdconf .= "		filename \"{$pxe[1]}\";\n";
1250
					$dhcpdconf .= "	}";
1251
				}
1252
				if ($filename) {
1253
					$dhcpdconf .= " else {\n";
1254
					$dhcpdconf .= "		filename \"{$filename}\";\n";
1255
					$dhcpdconf .= "	}";
1256
				}
1257
				$dhcpdconf .= "\n\n";
1258
			} elseif (!empty($filename)) {
1259
				$dhcpdconf .= "	filename \"{$filename}\";\n";
1260
			}
1261
			unset($filename);
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
				if (empty($sm)) {
1280
					continue;
1281
				}
1282
				$cid = '';
1283
				$dhcpdconf .= "host s_{$dhcpif}_{$i} {\n";
1284

    
1285
				if ($sm['mac']) {
1286
					$dhcpdconf .= "	hardware ethernet {$sm['mac']};\n";
1287
				}
1288

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

    
1294
				if ($sm['ipaddr']) {
1295
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
1296
				}
1297

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

    
1310
				if ($sm['rootpath']) {
1311
					$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1312
				}
1313

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

    
1318
				$smdnscfg = "";
1319

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1455
				$dhcpdconf .= "}\n";
1456

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

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

    
1486

    
1487
				$i++;
1488
			}
1489
		}
1490

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

    
1504
	if ($need_ddns_updates) {
1505
		$dhcpdconf .= "ddns-update-style interim;\n";
1506
		$dhcpdconf .= "update-static-leases on;\n";
1507

    
1508
		$dhcpdconf .= dhcpdzones($ddns_zones);
1509
	}
1510

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

    
1519
	/* create an empty leases database */
1520
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
1521
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
1522
	}
1523

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

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

    
1534
	if (platform_booting()) {
1535
		print "done.\n";
1536
	}
1537

    
1538
	return 0;
1539
}
1540

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

    
1551
	return $dhcpdconf;
1552
}
1553

    
1554
function dhcpdzones($ddns_zones) {
1555
	$dhcpdconf = "";
1556

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

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

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

    
1616
	return $dhcpdconf;
1617
}
1618

    
1619
function services_dhcpdv6_configure($blacklist = array()) {
1620
	global $g;
1621

    
1622
	if ($g['services_dhcp_server_enable'] == false) {
1623
		return;
1624
	}
1625

    
1626
	if (config_path_enabled('system','developerspew')) {
1627
		$mt = microtime();
1628
		echo "services_dhcpd_configure($if) being called $mt\n";
1629
	}
1630

    
1631
	/* kill any running dhcpd */
1632
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid")) {
1633
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid");
1634
	}
1635
	if (isvalidpid("{$g['varrun_path']}/dhcpleases6.pid")) {
1636
		killbypid("{$g['varrun_path']}/dhcpleases6.pid");
1637
	}
1638

    
1639
	/* DHCP enabled on any interfaces? */
1640
	if (!is_dhcpv6_server_enabled()) {
1641
		return 0;
1642
	}
1643

    
1644
	$syscfg = config_get_path('system');
1645
	init_config_arr(['dhcpdv6']);
1646
	$dhcpdv6cfg = config_get_path('dhcpdv6');
1647
	$Iflist = get_configured_interface_list();
1648
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
1649

    
1650

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

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

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

    
1670
	$dhcpdv6conf = <<<EOD
1671

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

    
1684
EOD;
1685

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

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

    
1694
	$dhcpdv6ifs = array();
1695

    
1696
	$dhcpv6num = 0;
1697
	$nsupdate = false;
1698

    
1699
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1700

    
1701
		$ddns_zones = array();
1702

    
1703
		$ifcfgv6 = config_get_path("interfaces/{$dhcpv6if}");
1704

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

    
1721
		$range_from = $dhcpv6ifconf['range']['from'];
1722
		$range_to = $dhcpv6ifconf['range']['to'];
1723
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
1724
			$range_from = merge_ipv6_delegated_prefix($ifcfgipv6, $range_from, $pdlen);
1725
			$range_to = merge_ipv6_delegated_prefix($ifcfgipv6, $range_to, $pdlen);
1726
		}
1727

    
1728
		if (is_ipaddrv6($ifcfgipv6)) {
1729
			$subnet_start = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1730
			$subnet_end = gen_subnetv6_max($ifcfgipv6, $ifcfgsnv6);
1731
			if ((!is_inrange_v6($range_from, $subnet_start, $subnet_end)) ||
1732
			    (!is_inrange_v6($range_to, $subnet_start, $subnet_end))) {
1733
				log_error(gettext("The specified range lies outside of the current subnet. Skipping DHCP6 entry."));
1734
				continue;
1735
			}
1736
		}
1737

    
1738
		$dnscfgv6 = "";
1739

    
1740
		if ($dhcpv6ifconf['domain']) {
1741
			$dnscfgv6 .= "	option domain-name \"{$dhcpv6ifconf['domain']}\";\n";
1742
		}
1743

    
1744
		if ($dhcpv6ifconf['domainsearchlist'] <> "") {
1745
			$dnscfgv6 .= "	option dhcp6.domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpv6ifconf['domainsearchlist'])) . "\";\n";
1746
		}
1747

    
1748
		if (isset($dhcpv6ifconf['ddnsupdate'])) {
1749
			if ($dhcpv6ifconf['ddnsdomain'] <> "") {
1750
				$dnscfgv6 .= "	ddns-domainname \"{$dhcpv6ifconf['ddnsdomain']}\";\n";
1751
			}
1752
			if (empty($dhcpv6ifconf['ddnsclientupdates'])) {
1753
				$ddnsclientupdates = 'allow';
1754
			} else {
1755
				$ddnsclientupdates = $dhcpv6ifconf['ddnsclientupdates'];
1756
			}
1757
			$dnscfgv6 .= "	{$ddnsclientupdates} client-updates;\n";
1758
			$nsupdate = true;
1759
		} else {
1760
			$dnscfgv6 .= "	do-forward-updates false;\n";
1761
		}
1762

    
1763
		if ($dhcpv6ifconf['dhcp6c-dns'] != 'disabled') {
1764
			if (is_array($dhcpv6ifconf['dnsserver']) && ($dhcpv6ifconf['dnsserver'][0])) {
1765
				$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dhcpv6ifconf['dnsserver']) . ";\n";
1766
			} else if (((config_path_enabled('dnsmasq')) || config_path_enabled('unbound')) && is_ipaddrv6($ifcfgipv6)) {
1767
				$dnscfgv6 .= "	option dhcp6.name-servers {$ifcfgipv6};\n";
1768
			} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1769
				$dns_arrv6 = array();
1770
				foreach ($syscfg['dnsserver'] as $dnsserver) {
1771
					if (is_ipaddrv6($dnsserver)) {
1772
						if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1773
						    Net_IPv6::isInNetmask($dnsserver, '::', $pdlen)) {
1774
							$dnsserver = merge_ipv6_delegated_prefix($ifcfgipv6, $dnsserver, $pdlen);
1775
						}
1776
						$dns_arrv6[] = $dnsserver;
1777
					}
1778
				}
1779
				if (!empty($dns_arrv6)) {
1780
					$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dns_arrv6) . ";\n";
1781
				}
1782
			}
1783
		} else {
1784
			$dnscfgv6 .= "	#option dhcp6.name-servers --;\n";
1785
		}
1786

    
1787
		if (!is_ipaddrv6($ifcfgipv6)) {
1788
			$ifcfgsnv6 = "64";
1789
			$subnetv6 = gen_subnetv6($range_from, $ifcfgsnv6);
1790
		}
1791

    
1792
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1793

    
1794
		if (isset($dhcpv6ifconf['ddnsupdate']) &&
1795
		    !empty($dhcpv6ifconf['ddnsdomain'])) {
1796
			$newzone = array();
1797
			$newzone['domain-name'] = $dhcpv6ifconf['ddnsdomain'];
1798
			$newzone['dns-servers'] = array($dhcpv6ifconf['ddnsdomainprimary'], $dhcpv6ifconf['ddnsdomainsecondary']);
1799
			$newzone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1800
			$newzone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1801
			$ddns_zones[] = $newzone;
1802
			if (isset($dhcpv6ifconf['ddnsreverse'])) {
1803
				$ptr_zones = get_v6_ptr_zones($subnetv6, $ifcfgsnv6);
1804
				foreach ($ptr_zones as $ptr_zone) {
1805
					$reversezone = array();
1806
					$reversezone['ptr-domain'] = $ptr_zone;
1807
					$reversezone['dns-servers'] = array($dhcpv6ifconf['ddnsdomainprimary'], $dhcpv6ifconf['ddnsdomainsecondary']);
1808
					$reversezone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1809
					$reversezone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1810
					$ddns_zones[] = $reversezone;
1811
				}
1812
			}
1813
		}
1814

    
1815
		$dhcpdv6conf .= " {\n";
1816

    
1817
		if (!empty($range_from) && !empty($range_to)) {
1818
			$dhcpdv6conf .= "	range6 {$range_from} {$range_to};\n";
1819
		}
1820

    
1821
		$dhcpdv6conf .= $dnscfgv6;
1822

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

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

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

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

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

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

    
1894
		$dhcpdv6conf .= "}\n";
1895

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

    
1908
EOD;
1909
				if ($sm['ipaddrv6']) {
1910
					$ipaddrv6 = $sm['ipaddrv6'];
1911
					if ($ifcfgv6['ipaddrv6'] == 'track6') {
1912
						$ipaddrv6 = merge_ipv6_delegated_prefix($ifcfgipv6, $ipaddrv6, $pdlen);
1913
					}
1914
					$dhcpdv6conf .= "	fixed-address6 {$ipaddrv6};\n";
1915
				}
1916

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

    
1930
				if ($sm['rootpath']) {
1931
					$dhcpdv6conf .= "	option root-path \"{$sm['rootpath']}\";\n";
1932
				}
1933

    
1934
				$dhcpdv6conf .= "}\n";
1935
				$i++;
1936
			}
1937
		}
1938

    
1939
		if ($dhcpv6ifconf['ddnsdomain']) {
1940
			$dhcpdv6conf .= dhcpdkey($dhcpv6ifconf);
1941
			$dhcpdv6conf .= dhcpdzones($ddns_zones);
1942
		}
1943

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

    
1964
	if ($nsupdate) {
1965
		$dhcpdv6conf .= "ddns-update-style interim;\n";
1966
		$dhcpdv6conf .= "update-static-leases on;\n";
1967
	} else {
1968
		$dhcpdv6conf .= "ddns-update-style none;\n";
1969
	}
1970

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

    
1982
	/* create an empty leases v6 database */
1983
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases")) {
1984
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1985
	}
1986

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

    
1991
	/* fire up dhcpd in a chroot */
1992
	if (count($dhcpdv6ifs) > 0) {
1993
		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 " .
1994
			join(" ", $dhcpdv6ifs));
1995
		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");
1996
	}
1997
	if (platform_booting()) {
1998
		print gettext("done.") . "\n";
1999
	}
2000

    
2001
	return 0;
2002
}
2003

    
2004
function services_igmpproxy_configure($interface='') {
2005
	global $g;
2006

    
2007
	if (!empty($interface) && !empty(config_get_path('igmpproxy/igmpentry'))) {
2008
		$igmpinf = "";
2009
		foreach (config_get_path('igmpproxy/igmpentry', []) as $igmpentry) {
2010
			if ($igmpentry['ifname'] == $interface) {
2011
				$igmpinf = true;
2012
				break;
2013
			}
2014
		}
2015
		if (!$igmpinf) {
2016
			return false;
2017
		}
2018
	}
2019

    
2020
	if (!config_path_enabled('igmpproxy')) {
2021
		if (isvalidproc("igmpproxy")) {
2022
			log_error(gettext("Stopping IGMP Proxy service."));
2023
			killbyname("igmpproxy");
2024
		}
2025
		return true;
2026
	}
2027
	if (count(config_get_path('igmpproxy/igmpentry', [])) == 0) {
2028
		return false;
2029
	}
2030

    
2031
	if (platform_booting()) {
2032
		echo gettext("Starting IGMP Proxy service...");
2033
	}
2034

    
2035
	if (isvalidproc("igmpproxy")) {
2036
		log_error(gettext("Restarting IGMP Proxy service."));
2037
		killbyname("igmpproxy");
2038
	}
2039

    
2040
	$iflist = get_configured_interface_list();
2041

    
2042
	$igmpconf = <<<EOD
2043

    
2044
##------------------------------------------------------
2045
## Enable Quickleave mode (Sends Leave instantly)
2046
##------------------------------------------------------
2047
quickleave
2048

    
2049
EOD;
2050

    
2051
	foreach (config_get_path('igmpproxy/igmpentry', []) as $igmpcf) {
2052
		if (empty(config_get_path("interfaces/{$igmpcf['ifname']}/ipaddr"))) {
2053
			continue;
2054
		}
2055
		unset($iflist[$igmpcf['ifname']]);
2056
		$realif = get_real_interface($igmpcf['ifname']);
2057
		if (empty($igmpcf['threshold'])) {
2058
			$threshld = 1;
2059
		} else {
2060
			$threshld = $igmpcf['threshold'];
2061
		}
2062
		$igmpconf .= "phyint {$realif} {$igmpcf['type']} ratelimit 0 threshold {$threshld}\n";
2063

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

    
2083
	if (!$upstream || !$downstream) {
2084
		log_error(gettext("Could not find upstream or downstream IGMP Proxy interfaces!"));
2085
		return;
2086
	}
2087

    
2088
	$igmpfl = fopen($g['varetc_path'] . "/igmpproxy.conf", "w");
2089
	if (!$igmpfl) {
2090
		log_error(gettext("Could not write IGMP Proxy configuration file!"));
2091
		return;
2092
	}
2093
	fwrite($igmpfl, $igmpconf);
2094
	fclose($igmpfl);
2095
	unset($igmpconf);
2096

    
2097
	if (config_path_enabled('syslog','igmpxverbose')) {
2098
		mwexec_bg("/usr/local/sbin/igmpproxy -v {$g['varetc_path']}/igmpproxy.conf");
2099
	} else {
2100
		mwexec_bg("/usr/local/sbin/igmpproxy {$g['varetc_path']}/igmpproxy.conf");
2101
	}
2102

    
2103
	log_error(gettext("Started IGMP Proxy service."));
2104

    
2105
	if (platform_booting()) {
2106
		echo gettext("done.") . "\n";
2107
	}
2108

    
2109
	return true;
2110
}
2111

    
2112
function services_dhcrelay_configure() {
2113
	global $g;
2114

    
2115
	if (config_path_enabled('system','developerspew')) {
2116
		$mt = microtime();
2117
		echo "services_dhcrelay_configure() being called $mt\n";
2118
	}
2119

    
2120
	/* kill any running dhcrelay */
2121
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
2122

    
2123
	init_config_arr(array('dhcrelay'));
2124
	$dhcrelaycfg = config_get_path('dhcrelay');
2125

    
2126
	/* DHCPRelay enabled on any interfaces? */
2127
	if (!isset($dhcrelaycfg['enable'])) {
2128
		return 0;
2129
	}
2130

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

    
2150
	if (platform_booting()) {
2151
		echo gettext("Starting DHCP Relay service...");
2152
	} else {
2153
		sleep(1);
2154
	}
2155

    
2156
	$iflist = get_configured_interface_list();
2157

    
2158
	$dhcrelayifs = array();
2159
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
2160
	foreach ($dhcifaces as $dhcrelayif) {
2161
		if (!isset($iflist[$dhcrelayif])) {
2162
			continue;
2163
		}
2164

    
2165
		if (get_interface_ip($dhcrelayif)) {
2166
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
2167
		}
2168
	}
2169
	$dhcrelayifs = array_unique($dhcrelayifs);
2170

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

    
2189
	/* Check for relays in the same subnet as clients so they can bind for
2190
	 * either direction (up or down) */
2191
	$srvrelayifs = array_intersect($dhcrelayifs, $srvifaces);
2192

    
2193
	/* The server interface(s) should not be in this list */
2194
	$dhcrelayifs = array_diff($dhcrelayifs, $srvifaces);
2195

    
2196
	/* Remove the dual-role interfaces from up and down lists */
2197
	$srvifaces = array_diff($srvifaces, $srvrelayifs);
2198
	$dhcrelayifs = array_diff($dhcrelayifs, $srvrelayifs);
2199

    
2200
	/* fire up dhcrelay */
2201
	if (empty($dhcrelayifs) && empty($srvrelayifs)) {
2202
		log_error(gettext("No suitable downstream interfaces found for running dhcrelay!"));
2203
		return; /* XXX */
2204
	}
2205
	if (empty($srvifaces) && empty($srvrelayifs)) {
2206
		log_error(gettext("No suitable upstream interfaces found for running dhcrelay!"));
2207
		return; /* XXX */
2208
	}
2209

    
2210
	$cmd = "/usr/local/sbin/dhcrelay";
2211

    
2212
	if (!empty($dhcrelayifs)) {
2213
		$cmd .= " -id " . implode(" -id ", $dhcrelayifs);
2214
	}
2215
	if (!empty($srvifaces)) {
2216
		$cmd .= " -iu " . implode(" -iu ", $srvifaces);
2217
	}
2218
	if (!empty($srvrelayifs)) {
2219
		$cmd .= " -i " . implode(" -i ", $srvrelayifs);
2220
	}
2221

    
2222
	if (isset($dhcrelaycfg['agentoption'])) {
2223
		$cmd .= " -a -m replace";
2224
	}
2225

    
2226
	$cmd .= " " . implode(" ", $srvips);
2227
	mwexec($cmd);
2228
	unset($cmd);
2229

    
2230
	return 0;
2231
}
2232

    
2233
function services_dhcrelay6_configure() {
2234
	global $g;
2235

    
2236
	if (config_path_enabled('system','developerspew')) {
2237
		$mt = microtime();
2238
		echo "services_dhcrelay6_configure() being called $mt\n";
2239
	}
2240

    
2241
	/* kill any running dhcrelay */
2242
	killbypid("{$g['varrun_path']}/dhcrelay6.pid");
2243

    
2244
	init_config_arr(array('dhcrelay6'));
2245
	$dhcrelaycfg = config_get_path('dhcrelay6');
2246

    
2247
	/* DHCPv6 Relay enabled on any interfaces? */
2248
	if (!isset($dhcrelaycfg['enable'])) {
2249
		return 0;
2250
	}
2251

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

    
2271
	if (platform_booting()) {
2272
		echo gettext("Starting DHCPv6 Relay service...");
2273
	} else {
2274
		sleep(1);
2275
	}
2276

    
2277
	$iflist = get_configured_interface_list();
2278

    
2279
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
2280
	foreach ($dhcifaces as $dhcrelayif) {
2281
		if (!isset($iflist[$dhcrelayif])) {
2282
			continue;
2283
		}
2284

    
2285
		if (get_interface_ipv6($dhcrelayif)) {
2286
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
2287
		}
2288
	}
2289
	$dhcrelayifs = array_unique($dhcrelayifs);
2290

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

    
2304
	/* fire up dhcrelay */
2305
	if (empty($dhcrelayifs) || empty($srvifaces)) {
2306
		log_error(gettext("No suitable interface found for running dhcrelay -6!"));
2307
		return; /* XXX */
2308
	}
2309

    
2310
	$cmd = "/usr/local/sbin/dhcrelay -6 -pf \"{$g['varrun_path']}/dhcrelay6.pid\"";
2311
	foreach ($dhcrelayifs as $dhcrelayif) {
2312
		$cmd .= " -l {$dhcrelayif}";
2313
	}
2314
	foreach ($srvifaces as $srviface) {
2315
		$cmd .= " -u \"{$srviface}\"";
2316
	}
2317
	mwexec($cmd);
2318
	unset($cmd);
2319

    
2320
	return 0;
2321
}
2322

    
2323
function services_dyndns_configure_client($conf) {
2324

    
2325
	if (!isset($conf['enable'])) {
2326
		return;
2327
	}
2328

    
2329
	/* load up the dyndns.class */
2330
	require_once("dyndns.class");
2331

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

    
2358
function services_dyndns_configure($int = "") {
2359
	if (config_path_enabled('system','developerspew')) {
2360
		$mt = microtime();
2361
		echo "services_dyndns_configure() being called $mt\n";
2362
	}
2363

    
2364
	$dyndnscfg = config_get_path('dyndnses/dyndns');
2365
	if (empty($dyndnscfg)) {
2366
		return 0;
2367
	}
2368
	$gwgroups = return_gateway_groups_array(true);
2369
	if (is_array($dyndnscfg)) {
2370
		if (platform_booting()) {
2371
			echo gettext("Starting DynDNS clients...");
2372
		}
2373

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

    
2409
		if (platform_booting()) {
2410
			echo gettext("done.") . "\n";
2411
		}
2412
	}
2413

    
2414
	return 0;
2415
}
2416

    
2417
function dyndnsCheckIP($int) {
2418
	global $factory_default_checkipservice;
2419
	$ip_address = get_interface_ip($int);
2420

    
2421
	if (is_private_ip($ip_address)) {
2422
		$gateways_status = return_gateways_status(true);
2423
		// If the gateway for this interface is down, then the external check cannot work.
2424
		// Avoid the long wait for the external check to timeout.
2425
		if (stristr(array_get_path($gateways_status, config_get_path("interfaces/{$int}/gateway") . "/status"), "down")) {
2426
			return "down";
2427
		}
2428

    
2429
		// Append the factory default check IP service to the list (if not disabled).
2430
		if (!config_path_enabled('checkipservices','disable_factory_default')) {
2431
			config_set_path('checkipservices/checkipservice', $factory_default_checkipservice);
2432
		}
2433

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

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

    
2464
		if ($matches[1]) {
2465
			$parsed_ip = trim($matches[1]);
2466
		} else {
2467
			$parsed_ip = trim($ip_result_decoded);
2468
		}
2469

    
2470
		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);
2471
		if ($matches[0]) {
2472
			$ip_address = $matches[0];
2473
		}
2474
	}
2475
	return $ip_address;
2476
}
2477

    
2478
function services_dnsmasq_configure($restart_dhcp = true) {
2479
	global $g;
2480
	$return = 0;
2481

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

    
2489

    
2490
	if (config_path_enabled('system','developerspew')) {
2491
		$mt = microtime();
2492
		echo "services_dnsmasq_configure() being called $mt\n";
2493
	}
2494

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

    
2500
	if (config_path_enabled('dnsmasq')) {
2501

    
2502
		if (platform_booting()) {
2503
			echo gettext("Starting DNS forwarder...");
2504
		} else {
2505
			sleep(1);
2506
		}
2507

    
2508
		/* generate hosts file */
2509
		if (system_hosts_generate() != 0) {
2510
			$return = 1;
2511
		}
2512

    
2513
		$args = "";
2514

    
2515
		if (config_path_enabled('dnsmasq','regdhcp')) {
2516
			$args .= " --dhcp-hostsfile={$g['etc_path']}/hosts ";
2517
		}
2518

    
2519
		/* Setup listen port, if non-default */
2520
		$port = config_get_path('dnsmasq/port');
2521
		if (is_port($port)) {
2522
			$args .= " --port={$port} ";
2523
		}
2524

    
2525
		$listen_addresses = "";
2526

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

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

    
2564
			// Build an array of domain overrides to help in checking for matches.
2565
			$override_a = array();
2566
			foreach (config_get_path('dnsmasq/domainoverrides', []) as $override) {
2567
				$override_a[$override['domain']] = "y";
2568
			}
2569

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

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

    
2587
		/* Setup forwarded domains */
2588
		foreach (config_get_path('dnsmasq/domainoverrides', []) as $override) {
2589
			if ($override['ip'] == "!") {
2590
				$override['ip'] = "";
2591
			}
2592
			$args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
2593
		}
2594

    
2595
		/* avoid 127.0.0.1 dns loop,
2596
		 * see https://redmine.pfsense.org/issues/12902 */
2597
		$args .= ' --no-resolv';
2598
		foreach (get_dns_nameservers(false, true) as $dns) {
2599
			if ($dns != '127.0.0.1') {
2600
				$args .= ' --server=' . $dns;
2601
			}
2602
		}
2603

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

    
2611
		if (!config_path_enabled('system/webgui', 'nodnsrebindcheck')) {
2612
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2613
		}
2614

    
2615
		if (config_path_enabled('dnsmasq','strict_order')) {
2616
			$args .= " --strict-order ";
2617
		}
2618

    
2619
		if (config_path_enabled('dnsmasq','domain_needed')) {
2620
			$args .= " --domain-needed ";
2621
		}
2622

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

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

    
2641
		system_dhcpleases_configure();
2642

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

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

    
2654
	return $return;
2655
}
2656

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

    
2661
	if (config_path_enabled('system','developerspew')) {
2662
		$mt = microtime();
2663
		echo "services_unbound_configure() being called $mt\n";
2664
	}
2665

    
2666
	if (!empty($interface) && config_path_enabled('unbound') &&
2667
	    !in_array($interface, explode(',', config_get_path('unbound/active_interface'))) &&
2668
	    !in_array($interface, explode(',', config_get_path('unbound/outgoing_interface')))) {
2669
		return $return;
2670
	}
2671

    
2672
	if (config_path_enabled('unbound')) {
2673
		require_once('/etc/inc/unbound.inc');
2674

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

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

    
2687
		$python_mode = false;
2688
		$python_script = config_get_path('unbound/python_script');
2689
		if (config_path_enabled('unbound','python') && !empty($python_script)) {
2690
			$python_mode = true;
2691
		}
2692

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

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

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

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

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

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

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

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

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

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

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

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

    
2809
	return $return;
2810
}
2811

    
2812
function services_snmpd_configure($interface='') {
2813
	global $g;
2814
	if (config_path_enabled('system','developerspew')) {
2815
		$mt = microtime();
2816
		echo "services_snmpd_configure() being called $mt\n";
2817
	}
2818

    
2819
	$bindip = config_get_path('snmpd/bindip', "");
2820
	if (!empty($interface) &&
2821
	    !empty($bind_ip) &&
2822
	    config_path_enabled('snmpd')) {
2823
		foreach (explode(",", $bindip) as $bind_to_ip) {
2824
			if ($bind_to_ip == $interface) {
2825
				$interface_restart = true;
2826
				break;
2827
			}
2828
		}
2829
		if (!$interface_restart) {
2830
			return 0;
2831
		}
2832
	}
2833

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

    
2841
	if (config_path_enabled('snmpd')) {
2842

    
2843
		if (platform_booting()) {
2844
			echo gettext("Starting SNMP daemon... ");
2845
		}
2846

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

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

    
2859
		$snmpdcfg = config_get_path('snmpd');
2860
		$snmpdconf = <<<EOD
2861
location := "{$snmpdcfg['syslocation']}"
2862
contact := "{$snmpdcfg['syscontact']}"
2863
read := "{$snmpdcfg['rocommunity']}"
2864

    
2865
EOD;
2866

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

    
2873
EOD;
2874
		}
2875
*/
2876

    
2877

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

    
2885

    
2886
EOD;
2887
		}
2888

    
2889
		$sysDescr = "{$g['product_label']} " .
2890
				  config_get_path('system/hostname') . '.' .config_get_path('system/domain') .
2891
			" {$g['product_version_string']} " . php_uname("s") .
2892
			" " . php_uname("r") . " " . php_uname("m");
2893

    
2894
		$snmpdconf .= <<<EOD
2895
system := 1     # pfSense
2896
%snmpd
2897
sysDescr			= "{$sysDescr}"
2898
begemotSnmpdDebugDumpPdus       = 2
2899
begemotSnmpdDebugSyslogPri      = 7
2900
begemotSnmpdCommunityString.0.1 = $(read)
2901

    
2902
EOD;
2903

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

    
2909
EOD;
2910
		}
2911
*/
2912

    
2913

    
2914
		if (config_path_enabled('snmpd','trapenable') && preg_match('/^\S+$/', config_get_path('snmpd/trapserver'))) {
2915
			$snmpdconf .= <<<EOD
2916
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
2917
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
2918
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
2919

    
2920
EOD;
2921
		}
2922

    
2923

    
2924
		$snmpdconf .= <<<EOD
2925
begemotSnmpdCommunityDisable    = 1
2926

    
2927
EOD;
2928

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

    
2968
		$pollport = config_get_path('snmpd/pollport');
2969
		if (is_port($pollport)) {
2970
			foreach ($bind_to_ips as $bind_to_ip) {
2971
				$snmpdconf .= <<<EOD
2972
begemotSnmpdPortStatus.{$bind_to_ip}.{$pollport} = 1
2973

    
2974
EOD;
2975

    
2976
			}
2977
			foreach ($bind_to_ip6s as $bind_to_ip6) {
2978
				$bind_to_ip6 = ip6_to_asn1($bind_to_ip6);
2979
				$snmpdconf .= <<<EOD
2980
begemotSnmpdTransInetStatus.2.16.{$bind_to_ip6}{$pollport}.1 = 4
2981

    
2982
EOD;
2983

    
2984
			}
2985
		}
2986

    
2987
		$snmpdconf .= <<<EOD
2988
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
2989
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
2990

    
2991
# These are bsnmp macros not php vars.
2992
sysContact      = $(contact)
2993
sysLocation     = $(location)
2994
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
2995

    
2996
snmpEnableAuthenTraps = 2
2997

    
2998
EOD;
2999

    
3000
		if (config_path_enabled('snmpd/modules', 'mibii')) {
3001
			$snmpdconf .= <<<EOD
3002
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
3003

    
3004
EOD;
3005
		}
3006

    
3007
		if (config_path_enabled('snmpd/modules', 'netgraph')) {
3008
			$snmpdconf .= <<<EOD
3009
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
3010
%netgraph
3011
begemotNgControlNodeName = "snmpd"
3012

    
3013
EOD;
3014
		}
3015

    
3016
		if (config_path_enabled('snmpd/modules', 'pf')) {
3017
			$snmpdconf .= <<<EOD
3018
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
3019

    
3020
EOD;
3021
		}
3022

    
3023
		if (config_path_enabled('snmpd/modules', 'hostres')) {
3024
			$snmpdconf .= <<<EOD
3025
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
3026

    
3027
EOD;
3028
		}
3029

    
3030
		if (config_path_enabled('snmpd/modules', 'bridge')) {
3031
			$snmpdconf .= <<<EOD
3032
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
3033
# config must end with blank line
3034

    
3035
EOD;
3036
		}
3037
		if (config_path_enabled('snmpd/modules', 'ucd')) {
3038
			$snmpdconf .= <<<EOD
3039
begemotSnmpdModulePath."ucd"     = "/usr/local/lib/snmp_ucd.so"
3040

    
3041
EOD;
3042
		}
3043
		if (config_path_enabled('snmpd/modules', 'regex')) {
3044
				$snmpdconf .= <<<EOD
3045
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"
3046

    
3047
EOD;
3048
		}
3049

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

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

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

    
3063
	return 0;
3064
}
3065

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

    
3073
	/* Dynamic DNS updating active? */
3074
	if (empty(config_get_path('dnsupdates/dnsupdate'))) {
3075
		return 0;
3076
	}
3077

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3339
	return 0;
3340
}
3341

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

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

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

    
3358

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

    
3365
		$http_proxy = config_get_path('system/proxyurl');
3366
		$http_proxyport = config_get_path('system/proxyport');
3367
		if (!empty($http_proxy)) {
3368
			if (!empty($http_proxyport)) {
3369
				$http_proxy .= ':' . $http_proxyport;
3370
			}
3371
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
3372

    
3373
			$proxyuser = config_get_path('system/proxyuser');
3374
			$proxypass = config_get_path('system/proxypass');
3375
			if (!empty($proxyuser) && !empty($proxypass)) {
3376
				$crontab_contents .= "HTTP_PROXY_AUTH=basic:*:{$proxyuser}:{$proxypass}";
3377
			}
3378
		}
3379

    
3380
		foreach (config_get_path('cron/item', []) as $item) {
3381
			$crontab_contents .= "\n{$item['minute']}\t";
3382
			$crontab_contents .= "{$item['hour']}\t";
3383
			$crontab_contents .= "{$item['mday']}\t";
3384
			$crontab_contents .= "{$item['month']}\t";
3385
			$crontab_contents .= "{$item['wday']}\t";
3386
			$crontab_contents .= "{$item['who']}\t";
3387
			$crontab_contents .= "{$item['command']}";
3388
		}
3389

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

    
3396
	/* please maintain the newline at the end of file */
3397
	file_put_contents("/etc/crontab", $crontab_contents);
3398
	unset($crontab_contents);
3399

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

    
3408
}
3409

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

    
3434
function upnp_start() {
3435
	if (empty(config_get_path('installedpackages/miniupnpd/config'))) {
3436
		return;
3437
	}
3438

    
3439
	if (config_path_enabled('installedpackages/miniupnpd/config/0')) {
3440
		echo gettext("Starting UPnP service... ");
3441
		require_once('/usr/local/pkg/miniupnpd.inc');
3442
		sync_package_miniupnpd();
3443
		echo "done.\n";
3444
	}
3445
}
3446

    
3447
function install_cron_job($command, $active = false, $minute = "0", $hour = "*", $monthday = "*", $month = "*", $weekday = "*", $who = "root", $write_config = true) {
3448
	$is_installed = false;
3449
	$cron_changed = true;
3450
	$change_message = "";
3451

    
3452
	init_config_arr(['cron','item']);
3453

    
3454
	$x = 0;
3455
	foreach (config_get_path('cron/item', []) as $item) {
3456
		if (strstr($item['command'], $command)) {
3457
			$is_installed = true;
3458
			break;
3459
		}
3460
		$x++;
3461
	}
3462

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

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

    
3506
?>
(47-47/62)