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-2023 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 (empty($dhcpv6ifconf)) {
54
			continue;
55
		}
56
		if (!config_path_enabled("interfaces/{$dhcpv6if}")) {
57
			continue;
58
		}
59

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

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

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

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

    
93
		$realif = get_real_interface($dhcpv6if, "inet6");
94

    
95
		if (isset($radvdifs[$realif])) {
96
			continue;
97
		}
98

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

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

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

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

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

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

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

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

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

    
210
		$radvdconf .= "\t};\n";
211

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

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

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

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

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

    
352
		$realif = get_real_interface($if, "inet6");
353

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

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

    
369
		$autotype = config_get_path("interfaces/{$trackif}/ipaddrv6");
370

    
371
		if (g_get('debug')) {
372
			log_error("configuring RA on {$if} for type {$autotype} radvd subnet {$subnetv6}/{$ifcfgsnv6}");
373
		}
374

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

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

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

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

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

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

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

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

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

    
493
	unlock($dhcpdconfigurelck);
494
}
495

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

    
501
	if (g_get('services_dhcp_server_enable') == false) {
502
		return;
503
	}
504

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

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

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

    
520
	$syscfg = config_get_path('system');
521
	init_config_arr(['dhcpd']);
522
	$dhcpdcfg = config_get_path('dhcpd');
523
	$Iflist = get_configured_interface_list();
524

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

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

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

    
624
	$dhcpdconf = <<<EOD
625

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

    
638
EOD;
639

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

    
651
		if (isset($dhcpifconf['alwaysbroadcast'])) {
652
			$dhcpdconf .= "always-broadcast on\n";
653
		}
654

    
655
		// OMAPI Settings
656
		if (isset($dhcpifconf['omapi_port']) && is_numeric($dhcpifconf['omapi_port'])) {
657
			$dhcpdconf .= <<<EOD
658

    
659
key omapi_key {
660
  algorithm {$dhcpifconf['omapi_key_algorithm']};
661
  secret "{$dhcpifconf['omapi_key']}";
662
};
663
omapi-port {$dhcpifconf['omapi_port']};
664
omapi-key omapi_key;
665

    
666
EOD;
667

    
668
		}
669
		break;
670
	}
671

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

    
684
	/*    loop through and determine if we need to setup
685
	 *    failover peer "bleh" entries
686
	 */
687
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
688
		if (empty($dhcpifconf)) {
689
			continue;
690
		}
691

    
692
		if (!config_path_enabled("interfaces/{$dhcpif}")) {
693
			continue;
694
		}
695

    
696
		interfaces_staticarp_configure($dhcpif);
697

    
698
		if (!isset($dhcpifconf['enable'])) {
699
			continue;
700
		}
701

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

    
745
			if (is_ipaddrv4($intip)) {
746
				$dhcpdconf .= <<<EOPP
747
failover peer "dhcp_{$dhcpif}" {
748
  {$type};
749
  address {$intip};
750
  port {$my_port};
751
  peer address {$dhcpifconf['failover_peerip']};
752
  peer port {$peer_port};
753
  max-response-delay 10;
754
  max-unacked-updates 10;
755
  {$dhcpdconf_pri}
756
  load balance max seconds 3;
757
}
758
\n
759
EOPP;
760
			}
761
		}
762
	}
763

    
764
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
765
		if (empty($dhcpifconf)) {
766
			continue;
767
		}
768

    
769
		$newzone = array();
770
		$ifcfg = config_get_path("interfaces/{$dhcpif}");
771

    
772
		if (!isset($dhcpifconf['enable']) || !isset($Iflist[$dhcpif])) {
773
			continue;
774
		}
775
		$ifcfgip = get_interface_ip($dhcpif);
776
		$ifcfgsn = get_interface_subnet($dhcpif);
777
		$subnet = gen_subnet($ifcfgip, $ifcfgsn);
778
		$subnetmask = gen_subnet_mask($ifcfgsn);
779

    
780
		if (!is_ipaddr($subnet)) {
781
			continue;
782
		}
783

    
784
		$all_pools = array();
785
		$all_pools[] = $dhcpifconf;
786
		if (is_array($dhcpifconf['pool'])) {
787
			$all_pools = array_merge($all_pools, $dhcpifconf['pool']);
788
		}
789

    
790
		$dnscfg = "";
791

    
792
		if ($dhcpifconf['domain']) {
793
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
794
		}
795

    
796
		if ($dhcpifconf['domainsearchlist'] <> "") {
797
			$dnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpifconf['domainsearchlist'])) . "\";\n";
798
		}
799

    
800
		if (isset($dhcpifconf['ddnsupdate'])) {
801
			$need_ddns_updates = true;
802
			$newzone = array();
803
			if ($dhcpifconf['ddnsdomain'] <> "") {
804
				$newzone['domain-name'] = $dhcpifconf['ddnsdomain'];
805
				$dnscfg .= "	ddns-domainname \"{$dhcpifconf['ddnsdomain']}\";\n";
806
			} else {
807
				$newzone['domain-name'] = config_get_path('system/domain');
808
			}
809

    
810
			if (empty($dhcpifconf['ddnsclientupdates'])) {
811
				$ddnsclientupdates = 'allow';
812
			} else {
813
				$ddnsclientupdates = $dhcpifconf['ddnsclientupdates'];
814
			}
815

    
816
			$dnscfg .= "	{$ddnsclientupdates} client-updates;\n";
817

    
818
			$revsubnet = array_reverse(explode('.',$subnet));
819

    
820
			$subnet_mask_bits = 32 - $ifcfgsn;
821
			$start_octet = $subnet_mask_bits >> 3;
822
			$octet_mask_bits = $subnet_mask_bits & ($subnet_mask_bits % 8);
823
			if ($octet_mask_bits) {
824
			    $octet_mask = (1 << $octet_mask_bits) - 1;
825
			    $octet_start = $revsubnet[$start_octet] & ~$octet_mask;
826
			    $revsubnet[$start_octet] = $octet_start . "-" . ($octet_start + $octet_mask);
827
			}
828

    
829
			$ptr_domain = '';
830
			for ($octet = 0; $octet <= 3; $octet++) {
831
				if ($octet < $start_octet) {
832
					continue;
833
				}
834
				$ptr_domain .= ((empty($ptr_domain) && $ptr_domain !== "0") ? '' : '.');
835
				$ptr_domain .= $revsubnet[$octet];
836
			}
837
			$ptr_domain .= ".in-addr.arpa";
838
			$newzone['ptr-domain'] = $ptr_domain;
839
			unset($ptr_domain, $revsubnet, $start_octet);
840
		}
841

    
842
		if (is_array($dhcpifconf['dnsserver']) && ($dhcpifconf['dnsserver'][0])) {
843
			$dnscfg .= "	option domain-name-servers " . join(",", $dhcpifconf['dnsserver']) . ";";
844
			if ($newzone['domain-name']) {
845
				$newzone['dns-servers'] = $dhcpifconf['dnsserver'];
846
			}
847
		} else if (config_path_enabled('dnsmasq')) {
848
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
849
			if ($newzone['domain-name'] && is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
850
				$newzone['dns-servers'] = $syscfg['dnsserver'];
851
			}
852
		} else if (config_path_enabled('unbound')) {
853
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
854
		} else if (!empty($dns_arrv4)) {
855
			$dnscfg .= "	option domain-name-servers " . join(",", $dns_arrv4) . ";";
856
			if ($newzone['domain-name']) {
857
				$newzone['dns-servers'] = $dns_arrv4;
858
			}
859
		}
860

    
861
		/* Create classes - These all contain comma separated lists. Join them into one
862
		   big comma separated string then split them all up. */
863
		$all_mac_strings = array();
864
		if (is_array($dhcpifconf['pool'])) {
865
			foreach ($all_pools as $poolconf) {
866
				$all_mac_strings[] = $poolconf['mac_allow'];
867
				$all_mac_strings[] = $poolconf['mac_deny'];
868
			}
869
		}
870
		$all_mac_strings[] = $dhcpifconf['mac_allow'];
871
		$all_mac_strings[] = $dhcpifconf['mac_deny'];
872
		if (!empty($all_mac_strings)) {
873
			$all_mac_list = array_unique(explode(',', implode(',', $all_mac_strings)));
874
			foreach ($all_mac_list as $mac) {
875
				if (empty($mac)) {
876
					continue;
877
				}
878
				$dhcpdconf .= 'class "' . str_replace(':', '', $mac) . '" {' . "\n";
879
				// Skip the first octet of the MAC address - for media type, typically Ethernet ("01") and match the rest.
880
				$dhcpdconf .= '	match if substring (hardware, 1, ' . (substr_count($mac, ':') + 1) . ') = ' . $mac . ';' . "\n";
881
				$dhcpdconf .= '}' . "\n";
882
			}
883
		}
884

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

    
888
		$dhcpdconf .= "subnet {$subnet} netmask {$subnetmask} {\n";
889

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

    
935
			/* allow/deny MACs */
936
			$mac_allow_list = array_unique(explode(',', $poolconf['mac_allow']));
937
			foreach ($mac_allow_list as $mac) {
938
				if (empty($mac)) {
939
					continue;
940
				}
941
				$dhcpdconf .= "		allow members of \"" . str_replace(':', '', $mac) . "\";\n";
942
			}
943
			$deny_action = "deny";
944
			if (isset($poolconf['nonak']) && empty($poolconf['failover_peerip'])) {
945
				$deny_action = "ignore";
946
			}
947
			$mac_deny_list = array_unique(explode(',', $poolconf['mac_deny']));
948
			foreach ($mac_deny_list as $mac) {
949
				if (empty($mac)) {
950
					continue;
951
				}
952
				$dhcpdconf .= "		deny members of \"" . str_replace(':', '', $mac) . "\";\n";
953
			}
954

    
955
			if ($poolconf['failover_peerip'] <> "") {
956
				$dhcpdconf .= "		$deny_action dynamic bootp clients;\n";
957
			}
958

    
959
			// set pool MAC limitations
960
			if (isset($poolconf['denyunknown'])) {
961
				if ($poolconf['denyunknown'] == "class") {
962
					$dhcpdconf .= "		allow members of \"s_{$dhcpif}\";\n";
963
					$dhcpdconf .= "		$deny_action unknown-clients;\n";
964
				} else if ($poolconf['denyunknown'] == "disabled") {
965
					// add nothing to $dhcpdconf; condition added to prevent next condition applying if ever engine changes such that: isset("disabled") == true
966
				} else {	// "catch-all" covering "enabled" value post-PR#4066, and covering non-upgraded boolean option (i.e. literal value "enabled")
967
					$dhcpdconf .= "		$deny_action unknown-clients;\n";
968
				}
969
			}
970

    
971
			if ($poolconf['gateway'] && $poolconf['gateway'] != "none" && ($poolconf['gateway'] != $dhcpifconf['gateway'])) {
972
				$dhcpdconf .= "		option routers {$poolconf['gateway']};\n";
973
			}
974

    
975
			if ($dhcpifconf['failover_peerip'] <> "") {
976
				$dhcpdconf .= "		failover peer \"dhcp_{$dhcpif}\";\n";
977
			}
978

    
979
			$pdnscfg = "";
980

    
981
			if ($poolconf['domain'] && ($poolconf['domain'] != $dhcpifconf['domain'])) {
982
				$pdnscfg .= "		option domain-name \"{$poolconf['domain']}\";\n";
983
			}
984

    
985
			if (!empty($poolconf['domainsearchlist']) && ($poolconf['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
986
				$pdnscfg .= "		option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $poolconf['domainsearchlist'])) . "\";\n";
987
			}
988

    
989
			if (isset($poolconf['ddnsupdate'])) {
990
				if (($poolconf['ddnsdomain'] <> "") && ($poolconf['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
991
					$pdnscfg .= "		ddns-domainname \"{$poolconf['ddnsdomain']}\";\n";
992
				}
993
				$pdnscfg .= "		ddns-update-style interim;\n";
994
			}
995

    
996
			$dhcpdconf .= "{$pdnscfg}";
997

    
998
			// default-lease-time
999
			if ($poolconf['defaultleasetime'] && ($poolconf['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
1000
				$dhcpdconf .= "		default-lease-time {$poolconf['defaultleasetime']};\n";
1001
			}
1002

    
1003
			// max-lease-time
1004
			if ($poolconf['maxleasetime'] && ($poolconf['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
1005
				$dhcpdconf .= "		max-lease-time {$poolconf['maxleasetime']};\n";
1006
			}
1007

    
1008
			// ignore bootp
1009
			if (isset($poolconf['ignorebootp'])) {
1010
				$dhcpdconf .= "		ignore bootp;\n";
1011
			}
1012

    
1013
			// ignore-client-uids
1014
			if (isset($poolconf['ignoreclientuids'])) {
1015
				$dhcpdconf .= "		ignore-client-uids true;\n";
1016
			}
1017

    
1018
			// netbios-name*
1019
			if (is_array($poolconf['winsserver']) && $poolconf['winsserver'][0] && ($poolconf['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
1020
				$dhcpdconf .= "		option netbios-name-servers " . join(",", $poolconf['winsserver']) . ";\n";
1021
				$dhcpdconf .= "		option netbios-node-type 8;\n";
1022
			}
1023

    
1024
			// ntp-servers
1025
			if (is_array($poolconf['ntpserver']) && $poolconf['ntpserver'][0] && ($poolconf['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
1026
				$dhcpdconf .= "		option ntp-servers " . join(",", $poolconf['ntpserver']) . ";\n";
1027
			}
1028

    
1029
			// tftp-server-name
1030
			if (!empty($poolconf['tftp']) && ($poolconf['tftp'] != $dhcpifconf['tftp'])) {
1031
				$dhcpdconf .= "		option tftp-server-name \"{$poolconf['tftp']}\";\n";
1032
			}
1033

    
1034
			// Handle pool-specific options
1035
			$dhcpdconf .= "\n";
1036
			// Ignore the first pool, which is the "overall" pool when $all_pools_idx is 0 - those are put outside the pool block later
1037
			$idx = 0;
1038
			$httpclient = false;
1039
			if (isset($poolconf['numberoptions']['item']) && is_array($poolconf['numberoptions']['item']) && ($all_pools_idx > 0)) {
1040
				// Use the "real" pool index from the config, excluding the "overall" pool, and based from 0.
1041
				// This matches the way $poolidx was used when generating the $custoptions string earlier.
1042
				$poolidx = $all_pools_idx - 1;
1043
				foreach ($poolconf['numberoptions']['item'] as $itemidx => $item) {
1044
					$item_value = base64_decode($item['value']);
1045
					if (empty($item['type']) || $item['type'] == "text") {
1046
						$dhcpdconf .= "		option custom-{$dhcpif}-{$poolidx}-{$itemidx} \"{$item_value}\";\n";
1047
					} else {
1048
						$dhcpdconf .= "		option custom-{$dhcpif}-{$poolidx}-{$itemidx} {$item_value};\n";
1049
					}
1050
					if (($item['type'] == "text") &&
1051
					    ($item['number'] == 60) &&
1052
					    (base64_decode($item['value']) == "HTTPClient")) {
1053
						$httpclient = true;
1054
					}
1055
					$idx++;
1056
				}
1057
			}
1058
			if (!empty($poolconf['uefihttpboot']) && isset($poolconf['netboot']) && !$httpclient &&
1059
			    (!isset($dhcpifconf['uefihttpboot']) ||
1060
			    ($poolconf['uefihttpboot'] != $dhcpifconf['uefihttpboot']))) {
1061
				$dhcpdconf .= "		option custom-{$dhcpif}-{$poolidx}-{$idx} \"HTTPClient\";\n";
1062
			}
1063

    
1064
			// ldap-server
1065
			if (!empty($poolconf['ldap']) && ($poolconf['ldap'] != $dhcpifconf['ldap'])) {
1066
				$dhcpdconf .= "		option ldap-server \"{$poolconf['ldap']}\";\n";
1067
			}
1068

    
1069
			// net boot information
1070
			if (isset($poolconf['netboot'])) {
1071
				if (!empty($poolconf['nextserver']) && ($poolconf['nextserver'] != $dhcpifconf['nextserver'])) {
1072
					$dhcpdconf .= "		next-server {$poolconf['nextserver']};\n";
1073
				}
1074

    
1075
				$pxe_files = array();
1076
				if (!empty($poolconf['filename']) &&
1077
				    (!isset($dhcpifconf['filename']) ||
1078
				    ($poolconf['filename'] != $dhcpifconf['filename']))) {
1079
					$filename = $poolconf['filename'];
1080
				}
1081
				if (!empty($poolconf['uefihttpboot']) &&
1082
				    (!isset($dhcpifconf['uefihttpboot']) ||
1083
				    ($poolconf['uefihttpboot'] != $dhcpifconf['uefihttpboot']))) {
1084
					$pxe_files[] = array('HTTPClient', $poolconf['uefihttpboot']);
1085
				}
1086
				if (!empty($poolconf['filename32']) &&
1087
				    (!isset($dhcpifconf['filename32']) ||
1088
				    ($poolconf['filename32'] != $dhcpifconf['filename32']))) {
1089
					$pxe_files[] = array('00:06', $poolconf['filename32']);
1090
				}
1091
				if (!empty($poolconf['filename64']) &&
1092
				    (!isset($dhcpifconf['filename64']) ||
1093
				    ($poolconf['filename64'] != $dhcpifconf['filename64']))) {
1094
					$pxe_files[] = array('00:07', $poolconf['filename64']);
1095
					$pxe_files[] = array('00:09', $poolconf['filename64']);
1096
				}
1097
				if (!empty($poolconf['filename32arm']) &&
1098
				    (!isset($dhcpifconf['filename32arm']) ||
1099
				    ($poolconf['filename32arm'] != $dhcpifconf['filename32arm']))) {
1100
					$pxe_files[] = array('00:0a', $poolconf['filename32arm']);
1101
				}
1102
				if (!empty($poolconf['filename64arm']) &&
1103
				    (!isset($dhcpifconf['filename64arm']) ||
1104
				    ($poolconf['filename64arm'] != $dhcpifconf['filename64arm']))) {
1105
					$pxe_files[] = array('00:0b', $poolconf['filename64arm']);
1106
				}
1107

    
1108
				$pxeif = false;
1109
				if (is_array($pxe_files) && !empty($pxe_files)) {
1110
					foreach ($pxe_files as $pxe) {
1111
						if ($pxe[0] == 'HTTPClient') {
1112
							$expr = "substring (option vendor-class-identifier, 0, 10) = \"HTTPClient\" {\n";
1113
						} else {
1114
							$expr = "option arch = {$pxe[0]} {\n";
1115
						}
1116
						if (!$pxeif) {
1117
							$dhcpdconf .= "		if " . $expr;
1118
							$pxeif = true;
1119
						} else {
1120
							$dhcpdconf .= " else if " . $expr;
1121
						}
1122
						$dhcpdconf .= "			filename \"{$pxe[1]}\";\n";
1123
						$dhcpdconf .= "		}";
1124
					}
1125
					if ($filename) {
1126
						$dhcpdconf .= " else {\n";
1127
						$dhcpdconf .= "			filename \"{$filename}\";\n";
1128
						$dhcpdconf .= "		}";
1129
					}
1130
					$dhcpdconf .= "\n\n";
1131
				} elseif (!empty($filename)) {
1132
					$dhcpdconf .= "		filename \"{$filename}\";\n";
1133
				}
1134
				unset($filename);
1135

    
1136
				if (!empty($poolconf['rootpath']) && ($poolconf['rootpath'] != $dhcpifconf['rootpath'])) {
1137
					$dhcpdconf .= "		option root-path \"{$poolconf['rootpath']}\";\n";
1138
				}
1139
			}
1140
			$dhcpdconf .= "		range {$poolconf['range']['from']} {$poolconf['range']['to']};\n";
1141
			$dhcpdconf .= "	}\n\n";
1142
		}
1143
// End of settings inside pools
1144

    
1145
		if ($dhcpifconf['gateway'] && $dhcpifconf['gateway'] != "none") {
1146
			$routers = $dhcpifconf['gateway'];
1147
			$add_routers = true;
1148
		} elseif ($dhcpifconf['gateway'] == "none") {
1149
			$add_routers = false;
1150
		} else {
1151
			$add_routers = $enable_add_routers;
1152
			$routers = $ifcfgip;
1153
		}
1154
		if ($add_routers) {
1155
			$dhcpdconf .= "	option routers {$routers};\n";
1156
		}
1157

    
1158
		$dhcpdconf .= <<<EOD
1159
$dnscfg
1160

    
1161
EOD;
1162
		// default-lease-time
1163
		if ($dhcpifconf['defaultleasetime']) {
1164
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
1165
		}
1166

    
1167
		// max-lease-time
1168
		if ($dhcpifconf['maxleasetime']) {
1169
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
1170
		}
1171

    
1172
		if (!isset($dhcpifconf['disablepingcheck'])) {
1173
			$dhcpdconf .= "	ping-check true;\n";
1174
		} else {
1175
			$dhcpdconf .= "	ping-check false;\n";
1176
		}
1177

    
1178
		// netbios-name*
1179
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
1180
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
1181
			$dhcpdconf .= "	option netbios-node-type 8;\n";
1182
		}
1183

    
1184
		// ntp-servers
1185
		if (is_array($dhcpifconf['ntpserver']) && $dhcpifconf['ntpserver'][0]) {
1186
			$dhcpdconf .= "	option ntp-servers " . join(",", $dhcpifconf['ntpserver']) . ";\n";
1187
		}
1188

    
1189
		// tftp-server-name
1190
		if ($dhcpifconf['tftp'] <> "") {
1191
			$dhcpdconf .= "	option tftp-server-name \"{$dhcpifconf['tftp']}\";\n";
1192
		}
1193

    
1194
		// Handle option, number rowhelper values
1195
		$dhcpdconf .= "\n";
1196
		$idx = 0;
1197
		$httpclient = false;
1198
		if (isset($dhcpifconf['numberoptions']['item']) && is_array($dhcpifconf['numberoptions']['item'])) {
1199
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
1200
				$item_value = base64_decode($item['value']);
1201
				if (empty($item['type']) || $item['type'] == "text") {
1202
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} \"{$item_value}\";\n";
1203
				} else {
1204
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} {$item_value};\n";
1205
				}
1206
				if (($item['type'] == "text") &&
1207
				    ($item['number'] == 60) &&
1208
				    (base64_decode($item['value']) == "HTTPClient")) {
1209
					$httpclient = true;
1210
				}
1211
				$idx++;
1212
			}
1213
		}
1214
		if (!empty($dhcpifconf['uefihttpboot']) && isset($dhcpifconf['netboot']) && !$httpclient) {
1215
			$dhcpdconf .= "	option custom-{$dhcpif}-{$idx} \"HTTPClient\";\n";
1216
		}
1217

    
1218
		// ldap-server
1219
		if ($dhcpifconf['ldap'] <> "") {
1220
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
1221
		}
1222

    
1223
		// net boot information
1224
		if (isset($dhcpifconf['netboot'])) {
1225
			if ($dhcpifconf['nextserver'] <> "") {
1226
				$dhcpdconf .= "	next-server {$dhcpifconf['nextserver']};\n";
1227
			}
1228

    
1229
			$pxe_files = array();
1230
			if (!empty($dhcpifconf['filename'])) {
1231
				$filename = $dhcpifconf['filename'];
1232
			}
1233
			if (!empty($dhcpifconf['uefihttpboot'])) {
1234
				$pxe_files[] = array('HTTPClient', $dhcpifconf['uefihttpboot']);
1235
			}
1236
			if (!empty($dhcpifconf['filename32'])) {
1237
				$pxe_files[] = array('00:06', $dhcpifconf['filename32']);
1238
			}
1239
			if (!empty($dhcpifconf['filename64'])) {
1240
				$pxe_files[] = array('00:07', $dhcpifconf['filename64']);
1241
				$pxe_files[] = array('00:09', $dhcpifconf['filename64']);
1242
			}
1243
			if (!empty($dhcpifconf['filename32arm'])) {
1244
				$pxe_files[] = array('00:0a', $dhcpifconf['filename32arm']);
1245
			}
1246
			if (!empty($dhcpifconf['filename64arm'])) {
1247
				$pxe_files[] = array('00:0b', $dhcpifconf['filename64arm']);
1248
			}
1249

    
1250
			$pxeif = false;
1251
			if (is_array($pxe_files) && !empty($pxe_files)) {
1252
				foreach ($pxe_files as $pxe) {
1253
					if ($pxe[0] == 'HTTPClient') {
1254
						$expr = "substring (option vendor-class-identifier, 0, 10) = \"HTTPClient\" {\n";
1255
					} else {
1256
						$expr = "option arch = {$pxe[0]} {\n";
1257
					}
1258
					if (!$pxeif) {
1259
						$dhcpdconf .= "	if " . $expr;
1260
						$pxeif = true;
1261
					} else {
1262
						$dhcpdconf .= " else if " . $expr;
1263
					}
1264
					$dhcpdconf .= "		filename \"{$pxe[1]}\";\n";
1265
					$dhcpdconf .= "	}";
1266
				}
1267
				if ($filename) {
1268
					$dhcpdconf .= " else {\n";
1269
					$dhcpdconf .= "		filename \"{$filename}\";\n";
1270
					$dhcpdconf .= "	}";
1271
				}
1272
				$dhcpdconf .= "\n\n";
1273
			} elseif (!empty($filename)) {
1274
				$dhcpdconf .= "	filename \"{$filename}\";\n";
1275
			}
1276
			unset($filename);
1277
			if (!empty($dhcpifconf['rootpath'])) {
1278
				$dhcpdconf .= "	option root-path \"{$dhcpifconf['rootpath']}\";\n";
1279
			}
1280
		}
1281

    
1282
		$dhcpdconf .= <<<EOD
1283
}
1284

    
1285
EOD;
1286

    
1287
		/* add static mappings */
1288
		if (is_array($dhcpifconf['staticmap'])) {
1289

    
1290
			$i = 0;
1291
			$sm_newzone[] = array();
1292
			$need_sm_ddns_updates = false;
1293
			foreach ($dhcpifconf['staticmap'] as $sm) {
1294
				if (empty($sm)) {
1295
					continue;
1296
				}
1297
				$cid = '';
1298
				$dhcpdconf .= "host s_{$dhcpif}_{$i} {\n";
1299

    
1300
				if ($sm['mac']) {
1301
					$dhcpdconf .= "	hardware ethernet {$sm['mac']};\n";
1302
				}
1303

    
1304
				if ($sm['cid']) {
1305
					$cid = str_replace('"', '\"', $sm['cid']);
1306
					$dhcpdconf .= "	option dhcp-client-identifier \"{$cid}\";\n";
1307
				}
1308

    
1309
				if ($sm['ipaddr']) {
1310
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
1311
				}
1312

    
1313
				if ($sm['hostname']) {
1314
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1315
					$dhhostname = str_replace(".", "_", $dhhostname);
1316
					$dhcpdconf .= "	option host-name \"{$dhhostname}\";\n";
1317
					if ((isset($dhcpifconf['ddnsupdate']) || isset($sm['ddnsupdate'])) && (isset($dhcpifconf['ddnsforcehostname']) || isset($sm['ddnsforcehostname']))) {
1318
						$dhcpdconf .= "	ddns-hostname \"{$dhhostname}\";\n";
1319
					}
1320
				}
1321
				if ($sm['filename']) {
1322
					$dhcpdconf .= "	filename \"{$sm['filename']}\";\n";
1323
				}
1324

    
1325
				if ($sm['rootpath']) {
1326
					$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1327
				}
1328

    
1329
				if ($sm['gateway'] && ($sm['gateway'] != $dhcpifconf['gateway'])) {
1330
					$dhcpdconf .= "	option routers {$sm['gateway']};\n";
1331
				}
1332

    
1333
				$smdnscfg = "";
1334

    
1335
				if ($sm['domain'] && ($sm['domain'] != $dhcpifconf['domain'])) {
1336
					$smdnscfg .= "	option domain-name \"{$sm['domain']}\";\n";
1337
				}
1338

    
1339
				if (!empty($sm['domainsearchlist']) && ($sm['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
1340
					$smdnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $sm['domainsearchlist'])) . "\";\n";
1341
				}
1342

    
1343
				if (isset($sm['ddnsupdate'])) {
1344
					if (($sm['ddnsdomain'] <> "") && ($sm['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
1345
						$smdnscfg .= "	ddns-domainname \"{$sm['ddnsdomain']}\";\n";
1346
				 		$need_sm_ddns_updates = true;
1347
					}
1348
					$smdnscfg .= "	ddns-update-style interim;\n";
1349
				}
1350

    
1351
				if (is_array($sm['dnsserver']) && ($sm['dnsserver'][0]) && ($sm['dnsserver'][0] != $dhcpifconf['dnsserver'][0])) {
1352
					$smdnscfg .= "	option domain-name-servers " . join(",", $sm['dnsserver']) . ";\n";
1353
				}
1354
				$dhcpdconf .= "{$smdnscfg}";
1355

    
1356
				// default-lease-time
1357
				if ($sm['defaultleasetime'] && ($sm['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
1358
					$dhcpdconf .= "	default-lease-time {$sm['defaultleasetime']};\n";
1359
				}
1360

    
1361
				// max-lease-time
1362
				if ($sm['maxleasetime'] && ($sm['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
1363
					$dhcpdconf .= "	max-lease-time {$sm['maxleasetime']};\n";
1364
				}
1365

    
1366
				// netbios-name*
1367
				if (is_array($sm['winsserver']) && $sm['winsserver'][0] && ($sm['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
1368
					$dhcpdconf .= "	option netbios-name-servers " . join(",", $sm['winsserver']) . ";\n";
1369
					$dhcpdconf .= "	option netbios-node-type 8;\n";
1370
				}
1371

    
1372
				// ntp-servers
1373
				if (is_array($sm['ntpserver']) && $sm['ntpserver'][0] && ($sm['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
1374
					$dhcpdconf .= "	option ntp-servers " . join(",", $sm['ntpserver']) . ";\n";
1375
				}
1376

    
1377
				// tftp-server-name
1378
				if (!empty($sm['tftp']) && ($sm['tftp'] != $dhcpifconf['tftp'])) {
1379
					$dhcpdconf .= "	option tftp-server-name \"{$sm['tftp']}\";\n";
1380
				}
1381

    
1382
				// Handle option, number rowhelper values
1383
				$dhcpdconf .= "\n";
1384
				$idx = 0;
1385
				$httpclient = false;
1386
				if (isset($sm['numberoptions']['item']) && is_array($sm['numberoptions']['item'])) {
1387
					foreach ($sm['numberoptions']['item'] as $itemidx => $item) {
1388
						$item_value = base64_decode($item['value']);
1389
						if (empty($item['type']) || $item['type'] == "text") {
1390
							$dhcpdconf .= "	option custom-s_{$dhcpif}_{$i}-{$itemidx} \"{$item_value}\";\n";
1391
						} else {
1392
							$dhcpdconf .= "	option custom-s_{$dhcpif}_{$i}-{$itemidx} {$item_value};\n";
1393
						}
1394
					}
1395
					if (($item['type'] == "text") &&
1396
					    ($item['number'] == 60) &&
1397
					    (base64_decode($item['value']) == "HTTPClient")) {
1398
						$httpclient = true;
1399
					}
1400
					$idx++;
1401
				}
1402
				if (!empty($sm['uefihttpboot']) && isset($sm['netboot']) && !$httpclient) {
1403
					$dhcpdconf .= "	option custom-s_{$dhcpif}_{$i}-{$idx} \"HTTPClient\";\n";
1404
				}
1405

    
1406
				// ldap-server
1407
				if (!empty($sm['ldap']) && ($sm['ldap'] != $dhcpifconf['ldap'])) {
1408
					$dhcpdconf .= "	option ldap-server \"{$sm['ldap']}\";\n";
1409
				}
1410

    
1411
				// net boot information
1412
				if (isset($sm['netboot'])) {
1413
					if ($sm['nextserver'] <> "") {
1414
						$dhcpdconf .= "	next-server {$sm['nextserver']};\n";
1415
					}
1416

    
1417
					$pxe_files = array();
1418
					if (!empty($sm['filename'])) {
1419
						$filename = $sm['filename'];
1420
					}
1421
					if (!empty($sm['uefihttpboot'])) {
1422
						$pxe_files[] = array('HTTPClient', $sm['uefihttpboot']);
1423
					}
1424
					if (!empty($sm['filename32'])) {
1425
						$pxe_files[] = array('00:06', $sm['filename32']);
1426
					}
1427
					if (!empty($sm['filename64'])) {
1428
						$pxe_files[] = array('00:07', $sm['filename64']);
1429
						$pxe_files[] = array('00:09', $sm['filename64']);
1430
					}
1431
					if (!empty($sm['filename32arm'])) {
1432
						$pxe_files[] = array('00:0a', $sm['filename32arm']);
1433
					}
1434
					if (!empty($sm['filename64arm'])) {
1435
						$pxe_files[] = array('00:0b', $sm['filename64arm']);
1436
					}
1437

    
1438
					$pxeif = false;
1439
					if (is_array($pxe_files) && !empty($pxe_files)) {
1440
						foreach ($pxe_files as $pxe) {
1441
							if ($pxe[0] == 'HTTPClient') {
1442
								$expr = "substring (option vendor-class-identifier, 0, 10) = \"HTTPClient\" {\n";
1443
							} else {
1444
								$expr = "option arch = {$pxe[0]} {\n";
1445
							}
1446
							if (!$pxeif) {
1447
								$dhcpdconf .= "	if " . $expr;
1448
								$pxeif = true;
1449
							} else {
1450
								$dhcpdconf .= " else if " . $expr;
1451
							}
1452
							$dhcpdconf .= "		filename \"{$pxe[1]}\";\n";
1453
							$dhcpdconf .= "	}";
1454
						}
1455
						if ($filename) {
1456
							$dhcpdconf .= " else {\n";
1457
							$dhcpdconf .= "		filename \"{$filename}\";\n";
1458
							$dhcpdconf .= "	}";
1459
						}
1460
						$dhcpdconf .= "\n\n";
1461
					} elseif (!empty($filename)) {
1462
						$dhcpdconf .= "	filename \"{$filename}\";\n";
1463
					}
1464
					unset($filename);
1465
					if (!empty($dhcpifconf['rootpath'])) {
1466
						$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1467
					}
1468
				}
1469

    
1470
				$dhcpdconf .= "}\n";
1471

    
1472
				// add zone DDNS key/server to $ddns_zone[] if required
1473
				if ($need_sm_ddns_updates) {
1474
					$ddnsduplicate = false;
1475
					foreach ($ddns_zones as $ddnszone) {
1476
						if ($ddnszone['domain-name'] == $sm['ddnsdomain']) {
1477
							$ddnsduplicate = true;
1478
						}
1479
					}
1480
					if (!$ddnsduplicate) {
1481
						$sm_newzone['dns-servers'] = array($sm['ddnsdomainprimary'], $sm['ddnsdomainsecondary']);
1482
						$sm_newzone['domain-name'] = $sm['ddnsdomain'];
1483
						$sm_newzone['ddnsdomainkeyname'] = $sm['ddnsdomainkeyname'];
1484
						$sm_newzone['ddnsdomainkeyalgorithm'] = $sm['ddnsdomainkeyalgorithm'];
1485
						$sm_newzone['ddnsdomainkey'] = $sm['ddnsdomainkey'];
1486
						$dhcpdconf .= dhcpdkey($sm_newzone);
1487
						$ddns_zones[] = $sm_newzone;
1488
						$need_ddns_updates = true;
1489
					}
1490
				}
1491

    
1492
				// subclass for DHCP limiting
1493
				if (!empty($sm['mac'])) {
1494
					// assuming ALL addresses are ethernet hardware type ("1:" prefix)
1495
					$dhcpdconf .= "subclass \"s_{$dhcpif}\" 1:{$sm['mac']};\n";
1496
				}
1497
				if (!empty($cid)) {
1498
					$dhcpdconf .= "subclass \"s_{$dhcpif}\" \"{$cid}\";\n";
1499
				}
1500

    
1501

    
1502
				$i++;
1503
			}
1504
		}
1505

    
1506
		$dhcpdifs[] = get_real_interface($dhcpif);
1507
		if ($newzone['domain-name']) {
1508
			if ($need_ddns_updates) {
1509
				$newzone['dns-servers'] = array($dhcpifconf['ddnsdomainprimary'], $dhcpifconf['ddnsdomainsecondary']);
1510
				$newzone['ddnsdomainkeyname'] = $dhcpifconf['ddnsdomainkeyname'];
1511
				$newzone['ddnsdomainkeyalgorithm'] = $dhcpifconf['ddnsdomainkeyalgorithm'];
1512
				$newzone['ddnsdomainkey'] = $dhcpifconf['ddnsdomainkey'];
1513
				$dhcpdconf .= dhcpdkey($dhcpifconf);
1514
			}
1515
			$ddns_zones[] = $newzone;
1516
		}
1517
	}
1518

    
1519
	if ($need_ddns_updates) {
1520
		$dhcpdconf .= "ddns-update-style interim;\n";
1521
		$dhcpdconf .= "update-static-leases on;\n";
1522

    
1523
		$dhcpdconf .= dhcpdzones($ddns_zones);
1524
	}
1525

    
1526
	/* write dhcpd.conf */
1527
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpd.conf", $dhcpdconf)) {
1528
		printf(gettext("Error: cannot open dhcpd.conf in services_dhcpdv4_configure().%s"), "\n");
1529
		unset($dhcpdconf);
1530
		return 1;
1531
	}
1532
	unset($dhcpdconf);
1533

    
1534
	/* create an empty leases database */
1535
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
1536
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
1537
	}
1538

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

    
1543
	/* fire up dhcpd in a chroot */
1544
	if (count($dhcpdifs) > 0) {
1545
		mwexec("/usr/local/sbin/dhcpd -user dhcpd -group _dhcp -chroot {$g['dhcpd_chroot_path']} -cf /etc/dhcpd.conf -pf {$g['varrun_path']}/dhcpd.pid " .
1546
			join(" ", $dhcpdifs));
1547
	}
1548

    
1549
	if (platform_booting()) {
1550
		print "done.\n";
1551
	}
1552

    
1553
	return 0;
1554
}
1555

    
1556
function dhcpdkey($dhcpifconf) {
1557
	$dhcpdconf = "";
1558
	if (!empty($dhcpifconf['ddnsdomainkeyname']) && !empty($dhcpifconf['ddnsdomainkey'])) {
1559
		$algorithm = empty($dhcpifconf['ddnsdomainkeyalgorithm']) ? 'hmac-md5' : $dhcpifconf['ddnsdomainkeyalgorithm'];
1560
		$dhcpdconf .= "key \"{$dhcpifconf['ddnsdomainkeyname']}\" {\n";
1561
		$dhcpdconf .= "	algorithm {$algorithm};\n";
1562
		$dhcpdconf .= "	secret {$dhcpifconf['ddnsdomainkey']};\n";
1563
		$dhcpdconf .= "}\n";
1564
	}
1565

    
1566
	return $dhcpdconf;
1567
}
1568

    
1569
function dhcpdzones($ddns_zones) {
1570
	$dhcpdconf = "";
1571

    
1572
	if (is_array($ddns_zones)) {
1573
		$added_zones = array();
1574
		foreach ($ddns_zones as $zone) {
1575
			if (!is_array($zone) || empty($zone) || !is_array($zone['dns-servers'])) {
1576
				continue;
1577
			}
1578
			$primary = $zone['dns-servers'][0];
1579
			$secondary = empty($zone['dns-servers'][1]) ? "" : $zone['dns-servers'][1];
1580

    
1581
			// Make sure we aren't using any invalid servers.
1582
			if (!is_ipaddr($primary)) {
1583
				if (is_ipaddr($secondary)) {
1584
					$primary = $secondary;
1585
					$secondary = "";
1586
				} else {
1587
					continue;
1588
				}
1589
			}
1590

    
1591
			// We don't need to add zones multiple times.
1592
			if ($zone['domain-name'] && !in_array($zone['domain-name'], $added_zones)) {
1593
				$dhcpdconf .= "zone {$zone['domain-name']}. {\n";
1594
				if (is_ipaddrv4($primary)) {
1595
					$dhcpdconf .= "	primary {$primary};\n";
1596
				} else {
1597
					$dhcpdconf .= "	primary6 {$primary};\n";
1598
				}
1599
				if (is_ipaddrv4($secondary)) {
1600
					$dhcpdconf .= "	secondary {$secondary};\n";
1601
				} elseif (is_ipaddrv6($secondary)) {
1602
					$dhcpdconf .= "	secondary6 {$secondary};\n";
1603
				}
1604
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1605
					$dhcpdconf .= "	key \"{$zone['ddnsdomainkeyname']}\";\n";
1606
				}
1607
				$dhcpdconf .= "}\n";
1608
				$added_zones[] = $zone['domain-name'];
1609
			}
1610
			if ($zone['ptr-domain'] && !in_array($zone['ptr-domain'], $added_zones)) {
1611
				$dhcpdconf .= "zone {$zone['ptr-domain']}. {\n";
1612
				if (is_ipaddrv4($primary)) {
1613
					$dhcpdconf .= "	primary {$primary};\n";
1614
				} else {
1615
					$dhcpdconf .= "	primary6 {$primary};\n";
1616
				}
1617
				if (is_ipaddrv4($secondary)) {
1618
					$dhcpdconf .= "	secondary {$secondary};\n";
1619
				} elseif (is_ipaddrv6($secondary)) {
1620
					$dhcpdconf .= "	secondary6 {$secondary};\n";
1621
				}
1622
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1623
					$dhcpdconf .= "	key \"{$zone['ddnsdomainkeyname']}\";\n";
1624
				}
1625
				$dhcpdconf .= "}\n";
1626
				$added_zones[] = $zone['ptr-domain'];
1627
			}
1628
		}
1629
	}
1630

    
1631
	return $dhcpdconf;
1632
}
1633

    
1634
function services_dhcpdv6_configure($blacklist = array()) {
1635
	global $g;
1636

    
1637
	if (g_get('services_dhcp_server_enable') == false) {
1638
		return;
1639
	}
1640

    
1641
	if (config_path_enabled('system','developerspew')) {
1642
		$mt = microtime();
1643
		echo "services_dhcpd_configure($if) being called $mt\n";
1644
	}
1645

    
1646
	/* kill any running dhcpd */
1647
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid")) {
1648
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid");
1649
	}
1650

    
1651
	/* DHCP enabled on any interfaces? */
1652
	if (!is_dhcpv6_server_enabled()) {
1653
		return 0;
1654
	}
1655

    
1656
	$syscfg = config_get_path('system');
1657
	init_config_arr(['dhcpdv6']);
1658
	$dhcpdv6cfg = config_get_path('dhcpdv6');
1659
	$Iflist = get_configured_interface_list();
1660
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
1661

    
1662

    
1663
	if (platform_booting()) {
1664
		echo "Starting DHCPv6 service...";
1665
	} else {
1666
		sleep(1);
1667
	}
1668

    
1669
	$custoptionsv6 = "";
1670
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1671
		if (empty($dhcpv6ifconf)) {
1672
			continue;
1673
		}
1674
		if (is_array($dhcpv6ifconf['numberoptions']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1675
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1676
				$custoptionsv6 .= "option custom-{$dhcpv6if}-{$itemv6idx} code {$itemv6['number']} = text;\n";
1677
			}
1678
		}
1679
	}
1680

    
1681
	if (isset($dhcpv6ifconf['netboot']) && !empty($dhcpv6ifconf['bootfile_url'])) {
1682
		$custoptionsv6 .= "option dhcp6.bootfile-url code 59 = string;\n";
1683
	}
1684

    
1685
	$dhcpdv6conf = <<<EOD
1686

    
1687
option domain-name "{$syscfg['domain']}";
1688
option ldap-server code 95 = text;
1689
option domain-search-list code 119 = text;
1690
{$custoptionsv6}
1691
default-lease-time 7200;
1692
max-lease-time 86400;
1693
log-facility local7;
1694
one-lease-per-client true;
1695
deny duplicates;
1696
ping-check true;
1697
update-conflict-detection false;
1698

    
1699
EOD;
1700

    
1701
	if (!isset($dhcpv6ifconf['disableauthoritative'])) {
1702
		$dhcpdv6conf .= "authoritative;\n";
1703
	}
1704

    
1705
	if (isset($dhcpv6ifconf['alwaysbroadcast'])) {
1706
		$dhcpdv6conf .= "always-broadcast on\n";
1707
	}
1708

    
1709
	$dhcpdv6ifs = array();
1710

    
1711
	$dhcpv6num = 0;
1712
	$nsupdate = false;
1713

    
1714
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1715
		if (empty($dhcpv6ifconf)) {
1716
			continue;
1717
		}
1718

    
1719
		$ddns_zones = array();
1720

    
1721
		$ifcfgv6 = config_get_path("interfaces/{$dhcpv6if}");
1722

    
1723
		if (!isset($dhcpv6ifconf['enable']) || !isset($Iflist[$dhcpv6if]) ||
1724
		    (!isset($ifcfgv6['enable']) && !preg_match("/poes/", $dhcpv6if))) {
1725
			continue;
1726
		}
1727
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1728
		if (!is_ipaddrv6($ifcfgipv6) && !preg_match("/poes/", $dhcpv6if)) {
1729
			continue;
1730
		}
1731
		$ifcfgsnv6 = get_interface_subnetv6($dhcpv6if);
1732
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1733
		// We might have some prefix-delegation on WAN (e.g. /48),
1734
		// but then it is split and given out to individual interfaces
1735
		// (LAN, OPT1, OPT2...) as multiple /64 subnets. So the size
1736
		// of each subnet here is always /64.
1737
		$pdlen = 64;
1738

    
1739
		$range_from = $dhcpv6ifconf['range']['from'];
1740
		$range_to = $dhcpv6ifconf['range']['to'];
1741
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
1742
			$range_from = merge_ipv6_delegated_prefix($ifcfgipv6, $range_from, $pdlen);
1743
			$range_to = merge_ipv6_delegated_prefix($ifcfgipv6, $range_to, $pdlen);
1744
		}
1745

    
1746
		if (is_ipaddrv6($ifcfgipv6)) {
1747
			$subnet_start = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1748
			$subnet_end = gen_subnetv6_max($ifcfgipv6, $ifcfgsnv6);
1749
			if ((!is_inrange_v6($range_from, $subnet_start, $subnet_end)) ||
1750
			    (!is_inrange_v6($range_to, $subnet_start, $subnet_end))) {
1751
				log_error(gettext("The specified range lies outside of the current subnet. Skipping DHCP6 entry."));
1752
				continue;
1753
			}
1754
		}
1755

    
1756
		$dnscfgv6 = "";
1757

    
1758
		if ($dhcpv6ifconf['domain']) {
1759
			$dnscfgv6 .= "	option domain-name \"{$dhcpv6ifconf['domain']}\";\n";
1760
		}
1761

    
1762
		if ($dhcpv6ifconf['domainsearchlist'] <> "") {
1763
			$dnscfgv6 .= "	option dhcp6.domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpv6ifconf['domainsearchlist'])) . "\";\n";
1764
		}
1765

    
1766
		if (isset($dhcpv6ifconf['ddnsupdate'])) {
1767
			if ($dhcpv6ifconf['ddnsdomain'] <> "") {
1768
				$dnscfgv6 .= "	ddns-domainname \"{$dhcpv6ifconf['ddnsdomain']}\";\n";
1769
			}
1770
			if (empty($dhcpv6ifconf['ddnsclientupdates'])) {
1771
				$ddnsclientupdates = 'allow';
1772
			} else {
1773
				$ddnsclientupdates = $dhcpv6ifconf['ddnsclientupdates'];
1774
			}
1775
			$dnscfgv6 .= "	{$ddnsclientupdates} client-updates;\n";
1776
			$nsupdate = true;
1777
		} else {
1778
			$dnscfgv6 .= "	do-forward-updates false;\n";
1779
		}
1780

    
1781
		if ($dhcpv6ifconf['dhcp6c-dns'] != 'disabled') {
1782
			if (is_array($dhcpv6ifconf['dnsserver']) && ($dhcpv6ifconf['dnsserver'][0])) {
1783
				$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dhcpv6ifconf['dnsserver']) . ";\n";
1784
			} else if (((config_path_enabled('dnsmasq')) || config_path_enabled('unbound')) && is_ipaddrv6($ifcfgipv6)) {
1785
				$dnscfgv6 .= "	option dhcp6.name-servers {$ifcfgipv6};\n";
1786
			} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1787
				$dns_arrv6 = array();
1788
				foreach ($syscfg['dnsserver'] as $dnsserver) {
1789
					if (is_ipaddrv6($dnsserver)) {
1790
						if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1791
						    Net_IPv6::isInNetmask($dnsserver, '::', $pdlen)) {
1792
							$dnsserver = merge_ipv6_delegated_prefix($ifcfgipv6, $dnsserver, $pdlen);
1793
						}
1794
						$dns_arrv6[] = $dnsserver;
1795
					}
1796
				}
1797
				if (!empty($dns_arrv6)) {
1798
					$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dns_arrv6) . ";\n";
1799
				}
1800
			}
1801
		} else {
1802
			$dnscfgv6 .= "	#option dhcp6.name-servers --;\n";
1803
		}
1804

    
1805
		if (!is_ipaddrv6($ifcfgipv6)) {
1806
			$ifcfgsnv6 = "64";
1807
			$subnetv6 = gen_subnetv6($range_from, $ifcfgsnv6);
1808
		}
1809

    
1810
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1811

    
1812
		if (isset($dhcpv6ifconf['ddnsupdate']) &&
1813
		    !empty($dhcpv6ifconf['ddnsdomain'])) {
1814
			$newzone = array();
1815
			$newzone['domain-name'] = $dhcpv6ifconf['ddnsdomain'];
1816
			$newzone['dns-servers'] = array($dhcpv6ifconf['ddnsdomainprimary'], $dhcpv6ifconf['ddnsdomainsecondary']);
1817
			$newzone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1818
			$newzone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1819
			$ddns_zones[] = $newzone;
1820
			if (isset($dhcpv6ifconf['ddnsreverse'])) {
1821
				$ptr_zones = get_v6_ptr_zones($subnetv6, $ifcfgsnv6);
1822
				foreach ($ptr_zones as $ptr_zone) {
1823
					$reversezone = array();
1824
					$reversezone['ptr-domain'] = $ptr_zone;
1825
					$reversezone['dns-servers'] = array($dhcpv6ifconf['ddnsdomainprimary'], $dhcpv6ifconf['ddnsdomainsecondary']);
1826
					$reversezone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1827
					$reversezone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1828
					$ddns_zones[] = $reversezone;
1829
				}
1830
			}
1831
		}
1832

    
1833
		$dhcpdv6conf .= " {\n";
1834

    
1835
		if (!empty($range_from) && !empty($range_to)) {
1836
			$dhcpdv6conf .= "	range6 {$range_from} {$range_to};\n";
1837
		}
1838

    
1839
		$dhcpdv6conf .= $dnscfgv6;
1840

    
1841
		if (is_ipaddrv6($dhcpv6ifconf['prefixrange']['from']) && is_ipaddrv6($dhcpv6ifconf['prefixrange']['to'])) {
1842
			$dhcpdv6conf .= "	prefix6 {$dhcpv6ifconf['prefixrange']['from']} {$dhcpv6ifconf['prefixrange']['to']} /{$dhcpv6ifconf['prefixrange']['prefixlength']};\n";
1843
		}
1844
		if (is_ipaddrv6($dhcpv6ifconf['dns6ip'])) {
1845
			$dns6ip = $dhcpv6ifconf['dns6ip'];
1846
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1847
			    Net_IPv6::isInNetmask($dns6ip, '::', $pdlen)) {
1848
				$dns6ip = merge_ipv6_delegated_prefix($ifcfgipv6, $dns6ip, $pdlen);
1849
			}
1850
			$dhcpdv6conf .= "	option dhcp6.name-servers {$dns6ip};\n";
1851
		}
1852
		// default-lease-time
1853
		if ($dhcpv6ifconf['defaultleasetime']) {
1854
			$dhcpdv6conf .= "	default-lease-time {$dhcpv6ifconf['defaultleasetime']};\n";
1855
		}
1856

    
1857
		// max-lease-time
1858
		if ($dhcpv6ifconf['maxleasetime']) {
1859
			$dhcpdv6conf .= "	max-lease-time {$dhcpv6ifconf['maxleasetime']};\n";
1860
		}
1861

    
1862
		// ntp-servers
1863
		if (is_array($dhcpv6ifconf['ntpserver']) && $dhcpv6ifconf['ntpserver'][0]) {
1864
			$ntpservers = array();
1865
			foreach ($dhcpv6ifconf['ntpserver'] as $ntpserver) {
1866
				if (!is_ipaddrv6($ntpserver)) {
1867
					continue;
1868
				}
1869
				if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1870
				    Net_IPv6::isInNetmask($ntpserver, '::', $pdlen)) {
1871
					$ntpserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ntpserver, $pdlen);
1872
				}
1873
				$ntpservers[] = $ntpserver;
1874
			}
1875
			if (count($ntpservers) > 0) {
1876
				$dhcpdv6conf .= "        option dhcp6.sntp-servers " . join(",", $dhcpv6ifconf['ntpserver']) . ";\n";
1877
			}
1878
		}
1879
		// tftp-server-name
1880
		/* Needs ISC DHCPD support
1881
		 if ($dhcpv6ifconf['tftp'] <> "") {
1882
			$dhcpdv6conf .= "	option tftp-server-name \"{$dhcpv6ifconf['tftp']}\";\n";
1883
		 }
1884
		*/
1885

    
1886
		// Handle option, number rowhelper values
1887
		$dhcpdv6conf .= "\n";
1888
		if (isset($dhcpv6ifconf['numberoptions']['item']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1889
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1890
				$itemv6_value = base64_decode($itemv6['value']);
1891
				$dhcpdv6conf .= "	option custom-{$dhcpv6if}-{$itemv6idx} \"{$itemv6_value}\";\n";
1892
			}
1893
		}
1894

    
1895
		// ldap-server
1896
		if ($dhcpv6ifconf['ldap'] <> "") {
1897
			$ldapserver = $dhcpv6ifconf['ldap'];
1898
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1899
			    Net_IPv6::isInNetmask($ldapserver, '::', $pdlen)) {
1900
				$ldapserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ldapserver, $pdlen);
1901
			}
1902
			$dhcpdv6conf .= "	option ldap-server \"{$ldapserver}\";\n";
1903
		}
1904

    
1905
		// net boot information
1906
		if (isset($dhcpv6ifconf['netboot'])) {
1907
			if (!empty($dhcpv6ifconf['bootfile_url'])) {
1908
				$dhcpdv6conf .= "	option dhcp6.bootfile-url \"{$dhcpv6ifconf['bootfile_url']}\";\n";
1909
			}
1910
		}
1911

    
1912
		$dhcpdv6conf .= "}\n";
1913

    
1914
		/* add static mappings */
1915
		/* Needs to use DUID */
1916
		if (is_array($dhcpv6ifconf['staticmap'])) {
1917
			$i = 0;
1918
			foreach ($dhcpv6ifconf['staticmap'] as $sm) {
1919
				if (empty($sm)) {
1920
					continue;
1921
				}
1922
				$dhcpdv6conf .= <<<EOD
1923
host s_{$dhcpv6if}_{$i} {
1924
	host-identifier option dhcp6.client-id {$sm['duid']};
1925

    
1926
EOD;
1927
				if ($sm['ipaddrv6']) {
1928
					$ipaddrv6 = $sm['ipaddrv6'];
1929
					if ($ifcfgv6['ipaddrv6'] == 'track6') {
1930
						$ipaddrv6 = merge_ipv6_delegated_prefix($ifcfgipv6, $ipaddrv6, $pdlen);
1931
					}
1932
					$dhcpdv6conf .= "	fixed-address6 {$ipaddrv6};\n";
1933
				}
1934

    
1935
				if ($sm['hostname']) {
1936
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1937
					$dhhostname = str_replace(".", "_", $dhhostname);
1938
					$dhcpdv6conf .= "	option host-name {$dhhostname};\n";
1939
					if (isset($dhcpv6ifconf['ddnsupdate']) &&
1940
					    isset($dhcpv6ifconf['ddnsforcehostname'])) {
1941
						$dhcpdv6conf .= "	ddns-hostname \"{$dhhostname}\";\n";
1942
					}
1943
				}
1944
				if ($sm['filename']) {
1945
					$dhcpdv6conf .= "	filename \"{$sm['filename']}\";\n";
1946
				}
1947

    
1948
				if ($sm['rootpath']) {
1949
					$dhcpdv6conf .= "	option root-path \"{$sm['rootpath']}\";\n";
1950
				}
1951

    
1952
				$dhcpdv6conf .= "}\n";
1953
				$i++;
1954
			}
1955
		}
1956

    
1957
		if ($dhcpv6ifconf['ddnsdomain']) {
1958
			$dhcpdv6conf .= dhcpdkey($dhcpv6ifconf);
1959
			$dhcpdv6conf .= dhcpdzones($ddns_zones);
1960
		}
1961

    
1962
		if ((config_get_path("dhcpdv6/{$dhcpv6if}/ramode") != "unmanaged") &&
1963
		    (config_path_enabled("interfaces/{$dhcpv6if}") ||
1964
		    preg_match("/poes/", $dhcpv6if))) {
1965
			if (preg_match("/poes/si", $dhcpv6if)) {
1966
				/* magic here */
1967
				$dhcpdv6ifs = array_merge($dhcpdv6ifs, get_pppoes_child_interfaces($dhcpv6if));
1968
			} else {
1969
				$realif = get_real_interface($dhcpv6if, "inet6");
1970
				if (stristr("$realif", "bridge")) {
1971
					$mac = get_interface_mac($realif);
1972
					$v6address = generate_ipv6_from_mac($mac);
1973
					/* Create link local address for bridges */
1974
					mwexec("/sbin/ifconfig {$realif} inet6 {$v6address}");
1975
				}
1976
				$realif = escapeshellcmd($realif);
1977
				$dhcpdv6ifs[] = $realif;
1978
			}
1979
		}
1980
	}
1981

    
1982
	if ($nsupdate) {
1983
		$dhcpdv6conf .= "ddns-update-style interim;\n";
1984
		$dhcpdv6conf .= "update-static-leases on;\n";
1985
	} else {
1986
		$dhcpdv6conf .= "ddns-update-style none;\n";
1987
	}
1988

    
1989
	/* write dhcpdv6.conf */
1990
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf", $dhcpdv6conf)) {
1991
		log_error("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1992
		if (platform_booting()) {
1993
			printf("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1994
		}
1995
		unset($dhcpdv6conf);
1996
		return 1;
1997
	}
1998
	unset($dhcpdv6conf);
1999

    
2000
	/* create an empty leases v6 database */
2001
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases")) {
2002
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
2003
	}
2004

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

    
2009
	/* fire up dhcpd in a chroot */
2010
	if (count($dhcpdv6ifs) > 0) {
2011
		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 " . join(" ", $dhcpdv6ifs));
2012
	}
2013
	if (platform_booting()) {
2014
		print gettext("done.") . "\n";
2015
	}
2016

    
2017
	return 0;
2018
}
2019

    
2020
function services_igmpproxy_configure($interface='') {
2021
	global $g;
2022

    
2023
	if (!empty($interface) && !empty(config_get_path('igmpproxy/igmpentry'))) {
2024
		$igmpinf = "";
2025
		foreach (config_get_path('igmpproxy/igmpentry', []) as $igmpentry) {
2026
			if ($igmpentry['ifname'] == $interface) {
2027
				$igmpinf = true;
2028
				break;
2029
			}
2030
		}
2031
		if (!$igmpinf) {
2032
			return false;
2033
		}
2034
	}
2035

    
2036
	if (!config_path_enabled('igmpproxy')) {
2037
		if (isvalidproc("igmpproxy")) {
2038
			log_error(gettext("Stopping IGMP Proxy service."));
2039
			killbyname("igmpproxy");
2040
		}
2041
		return true;
2042
	}
2043
	if (count(config_get_path('igmpproxy/igmpentry', [])) == 0) {
2044
		return false;
2045
	}
2046

    
2047
	if (platform_booting()) {
2048
		echo gettext("Starting IGMP Proxy service...");
2049
	}
2050

    
2051
	if (isvalidproc("igmpproxy")) {
2052
		log_error(gettext("Restarting IGMP Proxy service."));
2053
		killbyname("igmpproxy");
2054
	}
2055

    
2056
	$iflist = get_configured_interface_list();
2057

    
2058
	$igmpconf = <<<EOD
2059

    
2060
##------------------------------------------------------
2061
## Enable Quickleave mode (Sends Leave instantly)
2062
##------------------------------------------------------
2063
quickleave
2064

    
2065
EOD;
2066

    
2067
	foreach (config_get_path('igmpproxy/igmpentry', []) as $igmpcf) {
2068
		if (empty(config_get_path("interfaces/{$igmpcf['ifname']}/ipaddr"))) {
2069
			continue;
2070
		}
2071
		unset($iflist[$igmpcf['ifname']]);
2072
		$realif = get_real_interface($igmpcf['ifname']);
2073
		if (empty($igmpcf['threshold'])) {
2074
			$threshld = 1;
2075
		} else {
2076
			$threshld = $igmpcf['threshold'];
2077
		}
2078
		$igmpconf .= "phyint {$realif} {$igmpcf['type']} ratelimit 0 threshold {$threshld}\n";
2079

    
2080
		if ($igmpcf['address'] <> "") {
2081
			$item = explode(" ", $igmpcf['address']);
2082
			foreach ($item as $iww) {
2083
				$igmpconf .= "altnet {$iww}\n";
2084
			}
2085
		}
2086
		$igmpconf .= "\n";
2087
		if ($igmpcf['type'] == 'upstream') {
2088
		       $upstream = true;
2089
		} else {
2090
		       $downstream = true;
2091
		}
2092
	}
2093
	foreach ($iflist as $ifn) {
2094
		$realif = get_real_interface($ifn);
2095
		$igmpconf .= "phyint {$realif} disabled\n";
2096
	}
2097
	$igmpconf .= "\n";
2098

    
2099
	if (!$upstream || !$downstream) {
2100
		log_error(gettext("Could not find upstream or downstream IGMP Proxy interfaces!"));
2101
		return;
2102
	}
2103

    
2104
	$igmpfl = fopen(g_get('varetc_path') . "/igmpproxy.conf", "w");
2105
	if (!$igmpfl) {
2106
		log_error(gettext("Could not write IGMP Proxy configuration file!"));
2107
		return;
2108
	}
2109
	fwrite($igmpfl, $igmpconf);
2110
	fclose($igmpfl);
2111
	unset($igmpconf);
2112

    
2113
	if (config_path_enabled('syslog','igmpxverbose')) {
2114
		mwexec_bg("/usr/local/sbin/igmpproxy -v {$g['varetc_path']}/igmpproxy.conf");
2115
	} else {
2116
		mwexec_bg("/usr/local/sbin/igmpproxy {$g['varetc_path']}/igmpproxy.conf");
2117
	}
2118

    
2119
	log_error(gettext("Started IGMP Proxy service."));
2120

    
2121
	if (platform_booting()) {
2122
		echo gettext("done.") . "\n";
2123
	}
2124

    
2125
	return true;
2126
}
2127

    
2128
function services_dhcrelay_configure() {
2129
	global $g;
2130

    
2131
	if (config_path_enabled('system','developerspew')) {
2132
		$mt = microtime();
2133
		echo "services_dhcrelay_configure() being called $mt\n";
2134
	}
2135

    
2136
	/* kill any running dhcrelay */
2137
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
2138

    
2139
	init_config_arr(array('dhcrelay'));
2140
	$dhcrelaycfg = config_get_path('dhcrelay');
2141

    
2142
	/* DHCPRelay enabled on any interfaces? */
2143
	if (!isset($dhcrelaycfg['enable'])) {
2144
		return 0;
2145
	}
2146

    
2147
	/* Start/Restart DHCP Relay, if a CARP VIP is set, check its status and act
2148
	* appropriately. */
2149
	if (isset($dhcrelaycfg['carpstatusvip']) && ($dhcrelaycfg['carpstatusvip'] != "none")) {
2150
		$status = get_carp_interface_status($dhcrelaycfg['carpstatusvip']);
2151
		switch (strtoupper($status)) {
2152
			// Do not start DHCP Relay service if the VIP is in BACKUP or INIT state.
2153
			case "BACKUP":
2154
			case "INIT":
2155
				log_error("Stopping DHCP Relay (CARP BACKUP/INIT)");
2156
				return 0;
2157
				break;
2158
			// Start the service if the VIP is MASTER state.
2159
			case "MASTER":
2160
			// Assume it's up if the status can't be determined.
2161
			default:
2162
				break;
2163
		}
2164
	}
2165

    
2166
	if (platform_booting()) {
2167
		echo gettext("Starting DHCP Relay service...");
2168
	} else {
2169
		sleep(1);
2170
	}
2171

    
2172
	$iflist = get_configured_interface_list();
2173

    
2174
	$dhcrelayifs = array();
2175
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
2176
	foreach ($dhcifaces as $dhcrelayif) {
2177
		if (!isset($iflist[$dhcrelayif])) {
2178
			continue;
2179
		}
2180

    
2181
		if (get_interface_ip($dhcrelayif)) {
2182
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
2183
		}
2184
	}
2185
	$dhcrelayifs = array_unique($dhcrelayifs);
2186

    
2187
	/*
2188
	 * In order for the relay to work, it needs to be active
2189
	 * on the interface in which the destination server sits.
2190
	 */
2191
	$srvips = explode(",", $dhcrelaycfg['server']);
2192
	if (!is_array($srvips)) {
2193
		log_error(gettext("No destination IP has been configured!"));
2194
		return;
2195
	}
2196
	$srvifaces = array();
2197
	foreach ($srvips as $srcidx => $srvip) {
2198
		$destif = guess_interface_from_ip($srvip);
2199
		if (!empty($destif) && !is_pseudo_interface($destif)) {
2200
			$srvifaces[] = $destif;
2201
		}
2202
	}
2203
	$srvifaces = array_unique($srvifaces);
2204

    
2205
	/* Check for relays in the same subnet as clients so they can bind for
2206
	 * either direction (up or down) */
2207
	$srvrelayifs = array_intersect($dhcrelayifs, $srvifaces);
2208

    
2209
	/* The server interface(s) should not be in this list */
2210
	$dhcrelayifs = array_diff($dhcrelayifs, $srvifaces);
2211

    
2212
	/* Remove the dual-role interfaces from up and down lists */
2213
	$srvifaces = array_diff($srvifaces, $srvrelayifs);
2214
	$dhcrelayifs = array_diff($dhcrelayifs, $srvrelayifs);
2215

    
2216
	/* fire up dhcrelay */
2217
	if (empty($dhcrelayifs) && empty($srvrelayifs)) {
2218
		log_error(gettext("No suitable downstream interfaces found for running dhcrelay!"));
2219
		return; /* XXX */
2220
	}
2221
	if (empty($srvifaces) && empty($srvrelayifs)) {
2222
		log_error(gettext("No suitable upstream interfaces found for running dhcrelay!"));
2223
		return; /* XXX */
2224
	}
2225

    
2226
	$cmd = "/usr/local/sbin/dhcrelay";
2227

    
2228
	if (!empty($dhcrelayifs)) {
2229
		$cmd .= " -id " . implode(" -id ", $dhcrelayifs);
2230
	}
2231
	if (!empty($srvifaces)) {
2232
		$cmd .= " -iu " . implode(" -iu ", $srvifaces);
2233
	}
2234
	if (!empty($srvrelayifs)) {
2235
		$cmd .= " -i " . implode(" -i ", $srvrelayifs);
2236
	}
2237

    
2238
	if (isset($dhcrelaycfg['agentoption'])) {
2239
		$cmd .= " -a -m replace";
2240
	}
2241

    
2242
	$cmd .= " " . implode(" ", $srvips);
2243
	mwexec($cmd);
2244
	unset($cmd);
2245

    
2246
	return 0;
2247
}
2248

    
2249
function services_dhcrelay6_configure() {
2250
	global $g;
2251

    
2252
	if (config_path_enabled('system','developerspew')) {
2253
		$mt = microtime();
2254
		echo "services_dhcrelay6_configure() being called $mt\n";
2255
	}
2256

    
2257
	/* kill any running dhcrelay */
2258
	killbypid("{$g['varrun_path']}/dhcrelay6.pid");
2259

    
2260
	init_config_arr(array('dhcrelay6'));
2261
	$dhcrelaycfg = config_get_path('dhcrelay6');
2262

    
2263
	/* DHCPv6 Relay enabled on any interfaces? */
2264
	if (!isset($dhcrelaycfg['enable'])) {
2265
		return 0;
2266
	}
2267

    
2268
	/* Start/Restart DHCPv6 Relay, if a CARP VIP is set, check its status and act
2269
	* appropriately. */
2270
	if (isset($dhcrelaycfg['carpstatusvip']) && ($dhcrelaycfg['carpstatusvip'] != "none")) {
2271
		$status = get_carp_interface_status($dhcrelaycfg['carpstatusvip']);
2272
		switch (strtoupper($status)) {
2273
			// Do not start DHCP Relay service if the VIP is in BACKUP or INIT state.
2274
			case "BACKUP":
2275
			case "INIT":
2276
				log_error("Stopping DHCPv6 Relay (CARP BACKUP/INIT)");
2277
				return 0;
2278
				break;
2279
			// Start the service if the VIP is MASTER state.
2280
			case "MASTER":
2281
			// Assume it's up if the status can't be determined.
2282
			default:
2283
				break;
2284
		}
2285
	}
2286

    
2287
	if (platform_booting()) {
2288
		echo gettext("Starting DHCPv6 Relay service...");
2289
	} else {
2290
		sleep(1);
2291
	}
2292

    
2293
	$iflist = get_configured_interface_list();
2294

    
2295
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
2296
	foreach ($dhcifaces as $dhcrelayif) {
2297
		if (!isset($iflist[$dhcrelayif])) {
2298
			continue;
2299
		}
2300

    
2301
		if (get_interface_ipv6($dhcrelayif)) {
2302
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
2303
		}
2304
	}
2305
	$dhcrelayifs = array_unique($dhcrelayifs);
2306

    
2307
	/*
2308
	 * In order for the relay to work, it needs to be active
2309
	 * on the interface in which the destination server sits.
2310
	 */
2311
	$srvips = explode(",", $dhcrelaycfg['server']);
2312
	$srvifaces = array();
2313
	foreach ($srvips as $srcidx => $srvip) {
2314
		$destif = guess_interface_from_ip($srvip);
2315
		if (!empty($destif) && !is_pseudo_interface($destif)) {
2316
			$srvifaces[] = "{$srvip}%{$destif}";
2317
		}
2318
	}
2319

    
2320
	/* fire up dhcrelay */
2321
	if (empty($dhcrelayifs) || empty($srvifaces)) {
2322
		log_error(gettext("No suitable interface found for running dhcrelay -6!"));
2323
		return; /* XXX */
2324
	}
2325

    
2326
	$cmd = "/usr/local/sbin/dhcrelay -6 -pf \"{$g['varrun_path']}/dhcrelay6.pid\"";
2327
	foreach ($dhcrelayifs as $dhcrelayif) {
2328
		$cmd .= " -l {$dhcrelayif}";
2329
	}
2330
	foreach ($srvifaces as $srviface) {
2331
		$cmd .= " -u \"{$srviface}\"";
2332
	}
2333
	mwexec($cmd);
2334
	unset($cmd);
2335

    
2336
	return 0;
2337
}
2338

    
2339
function services_dyndns_configure_client($conf) {
2340

    
2341
	if (!isset($conf['enable'])) {
2342
		return;
2343
	}
2344

    
2345
	/* load up the dyndns.class */
2346
	require_once("dyndns.class");
2347

    
2348
	$dns = new updatedns($dnsService = $conf['type'],
2349
		$dnsHost = $conf['host'],
2350
		$dnsDomain = $conf['domainname'],
2351
		$dnsUser = $conf['username'],
2352
		$dnsPass = $conf['password'],
2353
		$dnsWildcard = $conf['wildcard'],
2354
		$dnsProxied = $conf['proxied'],
2355
		$dnsMX = $conf['mx'],
2356
		$dnsIf = "{$conf['interface']}",
2357
		$dnsBackMX = NULL,
2358
		$dnsServer = NULL,
2359
		$dnsPort = NULL,
2360
		$dnsUpdateURL = "{$conf['updateurl']}",
2361
		$forceUpdate = $conf['force'],
2362
		$dnsZoneID = $conf['zoneid'],
2363
		$dnsTTL = $conf['ttl'],
2364
		$dnsResultMatch = "{$conf['resultmatch']}",
2365
		$dnsRequestIf = "{$conf['requestif']}",
2366
		$dnsMaxCacheAge = $conf['maxcacheage'],
2367
		$dnsID = "{$conf['id']}",
2368
		$dnsVerboseLog = $conf['verboselog'],
2369
		$curlIpresolveV4 = $conf['curl_ipresolve_v4'],
2370
		$curlSslVerifypeer = $conf['curl_ssl_verifypeer'],
2371
		$curlProxy = $conf['curl_proxy']);
2372
}
2373

    
2374
function services_dyndns_configure($int = "") {
2375
	if (config_path_enabled('system','developerspew')) {
2376
		$mt = microtime();
2377
		echo "services_dyndns_configure() being called $mt\n";
2378
	}
2379

    
2380
	$dyndnscfg = config_get_path('dyndnses/dyndns');
2381
	if (empty($dyndnscfg)) {
2382
		return 0;
2383
	}
2384
	$gwgroups = return_gateway_groups_array(true);
2385
	if (is_array($dyndnscfg)) {
2386
		if (platform_booting()) {
2387
			echo gettext("Starting DynDNS clients...");
2388
		}
2389

    
2390
		foreach ($dyndnscfg as $dyndns) {
2391
			if (!is_array($dyndns) || empty($dyndns)) {
2392
				continue;
2393
			}
2394
			/*
2395
			 * If it's using a gateway group, check if interface is
2396
			 * the active gateway for that group
2397
			 */
2398
			$group_int = '';
2399
			$friendly_group_int = '';
2400
			$gwgroup_member = false;
2401
			if (is_array($gwgroups[$dyndns['interface']])) {
2402
				if (!empty($gwgroups[$dyndns['interface']][0]['vip'])) {
2403
					$group_int = $gwgroups[$dyndns['interface']][0]['vip'];
2404
				} else {
2405
					$group_int = $gwgroups[$dyndns['interface']][0]['int'];
2406
					$friendly_group_int =
2407
					    convert_real_interface_to_friendly_interface_name(
2408
						$group_int);
2409
					if (!empty($int)) {
2410
						$gwgroup_member =
2411
						    interface_gateway_group_member(get_real_interface($int),
2412
						    $dyndns['interface']);
2413
					}
2414
				}
2415
			}
2416
			if ((empty($int)) || ($int == $dyndns['interface']) || $gwgroup_member ||
2417
			    ($int == $group_int) || ($int == $friendly_group_int)) {
2418
				$dyndns['verboselog'] = isset($dyndns['verboselog']);
2419
				$dyndns['curl_ipresolve_v4'] = isset($dyndns['curl_ipresolve_v4']);
2420
				$dyndns['curl_ssl_verifypeer'] = isset($dyndns['curl_ssl_verifypeer']);
2421
				$dyndns['proxied'] = isset($dyndns['proxied']);
2422
				$dyndns['wildcard'] = isset($dyndns['wildcard']);
2423
				services_dyndns_configure_client($dyndns);
2424
				sleep(1);
2425
			}
2426
		}
2427

    
2428
		if (platform_booting()) {
2429
			echo gettext("done.") . "\n";
2430
		}
2431
	}
2432

    
2433
	return 0;
2434
}
2435

    
2436
function dyndnsCheckIP($int) {
2437
	global $factory_default_checkipservice;
2438
	$ip_address = get_interface_ip($int);
2439

    
2440
	if (is_private_ip($ip_address)) {
2441
		$gateways_status = return_gateways_status(true);
2442
		// If the gateway for this interface is down, then the external check cannot work.
2443
		// Avoid the long wait for the external check to timeout.
2444
		if (stristr(array_get_path($gateways_status, config_get_path("interfaces/{$int}/gateway") . "/status"), "down")) {
2445
			return "down";
2446
		}
2447

    
2448
		$available_ci_services = config_get_path('checkipservices/checkipservice', []);
2449
		// Append the factory default check IP service to the list (if not disabled).
2450
		if (!config_path_enabled('checkipservices','disable_factory_default')) {
2451
			$available_ci_services[] = $factory_default_checkipservice;
2452
		}
2453

    
2454
		// Use the first enabled check IP service as the default.
2455
		foreach ($available_ci_services as $checkipservice) {
2456
			if (isset($checkipservice['enable'])) {
2457
				$url = $checkipservice['url'];
2458
				$username = $checkipservice['username'];
2459
				$password = $checkipservice['password'];
2460
				$verifysslpeer = isset($checkipservice['verifysslpeer']);
2461
				$curl_proxy = isset($checkipservice['curl_proxy']);
2462
				break;
2463
			}
2464
		}
2465

    
2466
		$hosttocheck = $url;
2467
		$ip_ch = curl_init($hosttocheck);
2468
		curl_setopt($ip_ch, CURLOPT_RETURNTRANSFER, 1);
2469
		curl_setopt($ip_ch, CURLOPT_SSL_VERIFYPEER, $verifysslpeer);
2470
		curl_setopt($ip_ch, CURLOPT_INTERFACE, 'host!' . $ip_address);
2471
		curl_setopt($ip_ch, CURLOPT_CONNECTTIMEOUT, '30');
2472
		curl_setopt($ip_ch, CURLOPT_TIMEOUT, 120);
2473
		curl_setopt($ip_ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
2474
		curl_setopt($ip_ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
2475
		curl_setopt($ip_ch, CURLOPT_USERPWD, "{$username}:{$password}");
2476
		if ($curl_proxy) {
2477
			set_curlproxy($ip_ch);
2478
		}
2479
		$ip_result_page = curl_exec($ip_ch);
2480
		curl_close($ip_ch);
2481
		$ip_result_decoded = urldecode($ip_result_page);
2482
		preg_match('=Current IP Address: (.*)</body>=siU', $ip_result_decoded, $matches);
2483

    
2484
		if ($matches[1]) {
2485
			$parsed_ip = trim($matches[1]);
2486
		} else {
2487
			$parsed_ip = trim($ip_result_decoded);
2488
		}
2489

    
2490
		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);
2491
		if ($matches[0]) {
2492
			$ip_address = $matches[0];
2493
		}
2494
	}
2495
	return $ip_address;
2496
}
2497

    
2498
function services_dnsmasq_configure($restart_dhcp = true) {
2499
	global $g;
2500
	$return = 0;
2501

    
2502
	// hard coded args: will be removed to avoid duplication if specified in custom_options
2503
	$standard_args = array(
2504
		"dns-forward-max" => "--dns-forward-max=5000",
2505
		"cache-size" => "--cache-size=10000",
2506
		"local-ttl" => "--local-ttl=1"
2507
	);
2508

    
2509

    
2510
	if (config_path_enabled('system','developerspew')) {
2511
		$mt = microtime();
2512
		echo "services_dnsmasq_configure() being called $mt\n";
2513
	}
2514

    
2515
	/* kill any running dnsmasq */
2516
	if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) {
2517
		sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
2518
	}
2519

    
2520
	if (config_path_enabled('dnsmasq')) {
2521

    
2522
		if (platform_booting()) {
2523
			echo gettext("Starting DNS forwarder...");
2524
		} else {
2525
			sleep(1);
2526
		}
2527

    
2528
		/* generate hosts file */
2529
		if (system_hosts_generate() != 0) {
2530
			$return = 1;
2531
		}
2532

    
2533
		$args = "";
2534

    
2535
		if (config_path_enabled('dnsmasq','regdhcp')) {
2536
			$args .= " --dhcp-hostsfile={$g['etc_path']}/hosts ";
2537
		}
2538

    
2539
		/* Setup listen port, if non-default */
2540
		$port = config_get_path('dnsmasq/port');
2541
		if (is_port($port)) {
2542
			$args .= " --port={$port} ";
2543
		}
2544

    
2545
		$listen_addresses = "";
2546

    
2547
		$interfaces = explode(",", config_get_path('dnsmasq/interface', ""));
2548
		foreach ($interfaces as $interface) {
2549
			$if = get_real_interface($interface);
2550
			if (does_interface_exist($if)) {
2551
				$laddr = get_interface_ip($interface);
2552
				if (is_ipaddrv4($laddr)) {
2553
					$listen_addresses .= " --listen-address={$laddr} ";
2554
				}
2555
				$laddr6 = get_interface_ipv6($interface);
2556
				if (is_ipaddrv6($laddr6) && !config_path_enabled('dnsmasq','strictbind')) {
2557
					/*
2558
					 * XXX: Since dnsmasq does not support link-local address
2559
					 * with scope specified. These checks are being done.
2560
					 */
2561
					if (is_linklocal($laddr6) && strstr($laddr6, "%")) {
2562
						$tmpaddrll6 = explode("%", $laddr6);
2563
						$listen_addresses .= " --listen-address={$tmpaddrll6[0]} ";
2564
					} else {
2565
						$listen_addresses .= " --listen-address={$laddr6} ";
2566
					}
2567
				}
2568
			}
2569
		}
2570
		if (!empty($listen_addresses)) {
2571
			$args .= " {$listen_addresses} ";
2572
			if (config_path_enabled('dnsmasq','strictbind')) {
2573
				$args .= " --bind-interfaces ";
2574
			}
2575
		}
2576

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

    
2584
			// Build an array of domain overrides to help in checking for matches.
2585
			$override_a = array();
2586
			foreach (config_get_path('dnsmasq/domainoverrides', []) as $override) {
2587
				$override_a[$override['domain']] = "y";
2588
			}
2589

    
2590
			// Build an array of the private reverse lookup domain names
2591
			$reverse_domain_a = array("10.in-addr.arpa", "168.192.in-addr.arpa");
2592
			// Unfortunately the 172.16.0.0/12 range does not map nicely to the in-addr.arpa scheme.
2593
			for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) {
2594
				$reverse_domain_a[] = "$subnet_num.172.in-addr.arpa";
2595
			}
2596

    
2597
			// Set the --server parameter to nowhere for each reverse domain name that was not specifically specified in a domain override.
2598
			foreach ($reverse_domain_a as $reverse_domain) {
2599
				if (!isset($override_a[$reverse_domain])) {
2600
					$args .= " --server=/$reverse_domain/ ";
2601
				}
2602
			}
2603
			unset($override_a);
2604
			unset($reverse_domain_a);
2605
		}
2606

    
2607
		/* Setup forwarded domains */
2608
		foreach (config_get_path('dnsmasq/domainoverrides', []) as $override) {
2609
			if ($override['ip'] == "!") {
2610
				$override['ip'] = "";
2611
			}
2612
			$args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
2613
		}
2614

    
2615
		/* avoid 127.0.0.1 dns loop,
2616
		 * see https://redmine.pfsense.org/issues/12902 */
2617
		$args .= ' --no-resolv';
2618
		foreach (get_dns_nameservers(false, true) as $dns) {
2619
			if ($dns != '127.0.0.1') {
2620
				$args .= ' --server=' . $dns;
2621
			}
2622
		}
2623

    
2624
		/* Allow DNS Rebind for forwarded domains */
2625
		if (!config_path_enabled('system/webgui','nodnsrebindcheck')) {
2626
			foreach (config_get_path('dnsmasq/domainoverrides', []) as $override) {
2627
				$args .= ' --rebind-domain-ok=/' . $override['domain'] . '/ ';
2628
			}
2629
		}
2630

    
2631
		if (!config_path_enabled('system/webgui', 'nodnsrebindcheck')) {
2632
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2633
		}
2634

    
2635
		if (config_path_enabled('dnsmasq','strict_order')) {
2636
			$args .= " --strict-order ";
2637
		} else {
2638
			$args .= " --all-servers ";
2639
		}
2640

    
2641
		if (config_path_enabled('dnsmasq','domain_needed')) {
2642
			$args .= " --domain-needed ";
2643
		}
2644

    
2645
		foreach (preg_split('/\s+/', base64_decode(config_get_path('dnsmasq/custom_options', ""))) as $c) {
2646
			if (empty($c)) {
2647
				continue;
2648
			}
2649
			$args .= " " . escapeshellarg("--{$c}");
2650
			$p = explode('=', $c);
2651
			if (array_key_exists($p[0], $standard_args)) {
2652
				unset($standard_args[$p[0]]);
2653
			}
2654
		}
2655
		$args .= ' ' . implode(' ', array_values($standard_args));
2656

    
2657
		/* run dnsmasq. Use "-C /dev/null" since we use command line args only (Issue #6730) */
2658
		$cmd = "/usr/local/sbin/dnsmasq -C /dev/null {$dns_rebind} {$args}";
2659
		//log_error("dnsmasq command: {$cmd}");
2660
		mwexec_bg($cmd);
2661
		unset($args);
2662

    
2663
		system_dhcpleases_configure();
2664

    
2665
		if (platform_booting()) {
2666
			echo gettext("done.") . "\n";
2667
		}
2668
	}
2669

    
2670
	if (!platform_booting() && $restart_dhcp) {
2671
		if (services_dhcpd_configure() != 0) {
2672
			$return = 1;
2673
		}
2674
	}
2675

    
2676
	return $return;
2677
}
2678

    
2679
function services_unbound_configure($restart_dhcp = true, $interface = '') {
2680
	global $g;
2681
	$return = 0;
2682

    
2683
	if (config_path_enabled('system','developerspew')) {
2684
		$mt = microtime();
2685
		echo "services_unbound_configure() being called $mt\n";
2686
	}
2687

    
2688
	if (!empty($interface) && config_path_enabled('unbound') &&
2689
	    !in_array($interface, explode(',', config_get_path('unbound/active_interface'))) &&
2690
	    !in_array($interface, explode(',', config_get_path('unbound/outgoing_interface')))) {
2691
		return $return;
2692
	}
2693

    
2694
	if (config_path_enabled('unbound')) {
2695
		require_once('/etc/inc/unbound.inc');
2696

    
2697
		/* Stop Unbound using TERM */
2698
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2699
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
2700
		}
2701

    
2702
		/* If unbound is still running, wait up to 30 seconds for it to terminate. */
2703
		for ($i=1; $i <= 30; $i++) {
2704
			if (is_process_running('unbound')) {
2705
				sleep(1);
2706
			}
2707
		}
2708

    
2709
		$python_mode = false;
2710
		$python_script = config_get_path('unbound/python_script');
2711
		if (config_path_enabled('unbound','python') && !empty($python_script)) {
2712
			$python_mode = true;
2713
		}
2714

    
2715
		/* Include any additional functions as defined by python script include file */
2716
		if (file_exists("{$g['unbound_chroot_path']}/{$python_script}_include.inc")) {
2717
			exec("/usr/local/bin/php -l " . escapeshellarg("{$g['unbound_chroot_path']}/{$python_script}_include.inc")
2718
				. " 2>&1", $py_output, $py_retval);
2719
			if ($py_retval == 0) {
2720
				require_once("{$g['unbound_chroot_path']}/{$python_script}_include.inc");
2721
			}
2722
		}
2723

    
2724
		/* DNS Resolver python integration */
2725
		if ($python_mode) {
2726
			if (!is_dir("{$g['unbound_chroot_path']}/dev")) {
2727
				safe_mkdir("{$g['unbound_chroot_path']}/dev");
2728
			}
2729
			$status = "/sbin/mount | /usr/bin/grep " .  escapeshellarg("{$g['unbound_chroot_path']}/dev");
2730
			if (!trim($status)) {
2731
				exec("/sbin/mount -t devfs devfs " . escapeshellarg("{$g['unbound_chroot_path']}/dev"));
2732
			}
2733
		} else {
2734
			if (is_dir("{$g['unbound_chroot_path']}/dev")) {
2735
				exec("/sbin/umount -f " . escapeshellarg("{$g['unbound_chroot_path']}/dev"));
2736
			}
2737
		}
2738
		$base_folder = '/usr/local';
2739
		foreach (array('/bin', '/lib') as $dir) {
2740
			$validate = exec("/sbin/mount | /usr/bin/grep " . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir} (nullfs") . " 2>&1");
2741
			if ($python_mode) {
2742

    
2743
				// Add DNS Resolver python integration
2744
				if (empty($validate)) {
2745
					if (!is_dir("{$g['unbound_chroot_path']}{$base_folder}{$dir}")) {
2746
						safe_mkdir("{$g['unbound_chroot_path']}{$base_folder}{$dir}");
2747
					}
2748
					$output = $retval = '';
2749
					exec("/sbin/mount_nullfs -o ro " . escapeshellarg("/usr/local{$dir}") . ' '
2750
					    . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir}") . " 2>&1", $output, $retval);
2751

    
2752
					// Disable Unbound python on mount failure
2753
					if ($retval != 0) {
2754
						config_set_path('unbound/python','');
2755
						$log_msg = "[Unbound-pymod]: Disabling Unbound python due to failed mount";
2756
						write_config($log_msg);
2757
						log_error($log_msg);
2758
					}
2759
				}
2760
			}
2761

    
2762
			// Remove DNS Resolver python integration
2763
			elseif (!empty($validate)) {
2764
				exec("/sbin/umount -t nullfs " . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir}") . " 2>&1", $output, $retval);
2765
				if ($retval == 0) {
2766
					foreach (array( "/usr/local{$dir}", '/usr/local', '/usr') as $folder) {
2767
						if (!empty(g_get('unbound_chroot_path')) && g_get('unbound_chroot_path') != '/' && is_dir("{$g['unbound_chroot_path']}{$folder}")) {
2768
							@rmdir(escapeshellarg("{$g['unbound_chroot_path']}{$folder}"));
2769
						}
2770

    
2771
						// Delete remaining subfolders on next loop
2772
						if ($dir == '/bin') {
2773
							break;
2774
						}
2775
					}
2776
				}
2777
				else {
2778
					log_error("[Unbound-pymod]: Failed to unmount!");
2779
				}
2780
			}
2781
		}
2782

    
2783
		if (platform_booting()) {
2784
			echo gettext("Starting DNS Resolver...");
2785
		} else {
2786
			sleep(1);
2787
		}
2788

    
2789
		/* generate hosts file */
2790
		if (system_hosts_generate() != 0) {
2791
			$return = 1;
2792
		}
2793

    
2794
		/* Check here for dhcp6 complete - wait upto 10 seconds */
2795
		if(config_get_path('interfaces/wan/ipaddrv6') == 'dhcp6') {
2796
			$wanif = get_real_interface("wan", "inet6");
2797
			if (platform_booting()) {
2798
				for ($i=1; $i <= 10; $i++) {
2799
					if (!file_exists("/tmp/{$wanif}_dhcp6_complete")) {
2800
						log_error(gettext("Unbound start waiting on dhcp6c."));
2801
						sleep(1);
2802
					} else {
2803
						unlink_if_exists("/tmp/{$wanif}_dhcp6_complete");
2804
						log_error(gettext("dhcp6 init complete. Continuing"));
2805
						break;
2806
					}
2807
				}
2808
			}
2809
		}
2810

    
2811
		sync_unbound_service();
2812
		if (platform_booting()) {
2813
			log_error(gettext("sync unbound done."));
2814
			echo gettext("done.") . "\n";
2815
		}
2816

    
2817
		system_dhcpleases_configure();
2818
	} else {
2819
		/* kill Unbound since it should not be enabled */
2820
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2821
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "KILL");
2822
		}
2823
	}
2824

    
2825
	if (!platform_booting() && $restart_dhcp) {
2826
		if (services_dhcpd_configure() != 0) {
2827
			$return = 1;
2828
		}
2829
	}
2830

    
2831
	return $return;
2832
}
2833

    
2834
function services_snmpd_configure($interface='') {
2835
	global $g;
2836
	if (config_path_enabled('system','developerspew')) {
2837
		$mt = microtime();
2838
		echo "services_snmpd_configure() being called $mt\n";
2839
	}
2840

    
2841
	$bindip = config_get_path('snmpd/bindip', "");
2842
	if (!empty($interface) &&
2843
	    !empty($bind_ip) &&
2844
	    config_path_enabled('snmpd')) {
2845
		foreach (explode(",", $bindip) as $bind_to_ip) {
2846
			if ($bind_to_ip == $interface) {
2847
				$interface_restart = true;
2848
				break;
2849
			}
2850
		}
2851
		if (!$interface_restart) {
2852
			return 0;
2853
		}
2854
	}
2855

    
2856
	/* kill any running snmpd */
2857
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
2858
	sleep(2);
2859
	if (is_process_running("bsnmpd")) {
2860
		mwexec("/usr/bin/killall bsnmpd", true);
2861
	}
2862

    
2863
	if (config_path_enabled('snmpd')) {
2864

    
2865
		if (platform_booting()) {
2866
			echo gettext("Starting SNMP daemon... ");
2867
		}
2868

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

    
2874
		/* generate snmpd.conf */
2875
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
2876
		if (!$fd) {
2877
			printf(gettext("Error: cannot open snmpd.conf in services_snmpd_configure().%s"), "\n");
2878
			return 1;
2879
		}
2880

    
2881
		$snmpdcfg = config_get_path('snmpd');
2882
		$snmpdconf = <<<EOD
2883
location := "{$snmpdcfg['syslocation']}"
2884
contact := "{$snmpdcfg['syscontact']}"
2885
read := "{$snmpdcfg['rocommunity']}"
2886

    
2887
EOD;
2888

    
2889
/* No docs on what write strings do there so disable for now.
2890
		if (config_path_enabled('snmpd','rwenable') && preg_match('/^\S+$/', $snmpdcfg['rwcommunity'])) {
2891
			$snmpdconf .= <<<EOD
2892
# write string
2893
write := "{$snmpdcfg['rwcommunity']}"
2894

    
2895
EOD;
2896
		}
2897
*/
2898

    
2899

    
2900
		if (config_path_enabled('snmpd','trapenable') && preg_match('/^\S+$/', $snmpdcfg['trapserver'])) {
2901
			$snmpdconf .= <<<EOD
2902
# SNMP Trap support.
2903
traphost := {$snmpdcfg['trapserver']}
2904
trapport := {$snmpdcfg['trapserverport']}
2905
trap := "{$snmpdcfg['trapstring']}"
2906

    
2907

    
2908
EOD;
2909
		}
2910

    
2911
		$sysDescr = "{$g['product_label']} " .
2912
				  config_get_path('system/hostname') . '.' .config_get_path('system/domain') .
2913
			" {$g['product_version_string']} " . php_uname("s") .
2914
			" " . php_uname("r") . " " . php_uname("m");
2915

    
2916
		$snmpdconf .= <<<EOD
2917
system := 1     # pfSense
2918
%snmpd
2919
sysDescr			= "{$sysDescr}"
2920
begemotSnmpdDebugDumpPdus       = 2
2921
begemotSnmpdDebugSyslogPri      = 7
2922
begemotSnmpdCommunityString.0.1 = $(read)
2923

    
2924
EOD;
2925

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

    
2931
EOD;
2932
		}
2933
*/
2934

    
2935

    
2936
		if (config_path_enabled('snmpd','trapenable') && preg_match('/^\S+$/', config_get_path('snmpd/trapserver'))) {
2937
			$snmpdconf .= <<<EOD
2938
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
2939
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
2940
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
2941

    
2942
EOD;
2943
		}
2944

    
2945

    
2946
		$snmpdconf .= <<<EOD
2947
begemotSnmpdCommunityDisable    = 1
2948

    
2949
EOD;
2950

    
2951
		$bind_to_ips = array();
2952
		$bind_to_ip6s = array();
2953
		if (config_path_enabled('snmpd','bindip')) {
2954
			$ipproto = config_get_path('snmpd/ipprotocol', "4");
2955
			if (strstr($ipproto, "4")) {
2956
				$inet4 = true;
2957
			}
2958
			if (strstr($ipproto, "6")) {
2959
				$inet6 = true;
2960
			}
2961
			foreach (explode(",", config_get_path('snmpd/bindip', "")) as $bind_to_ip) {
2962
				if (is_ipaddr($bind_to_ip)) {
2963
					$bind_to_ips[] = $bind_to_ip;
2964
				} else {
2965
					$if = get_real_interface($bind_to_ip);
2966
					if (does_interface_exist($if)) {
2967
						if ($inet4) {
2968
							$bindip = get_interface_ip($bind_to_ip);
2969
							if (is_ipaddrv4($bindip)) {
2970
								$bind_to_ips[] = $bindip;
2971
							}
2972
						}
2973
						if ($inet6) {
2974
							$bindip6 = get_interface_ipv6($bind_to_ip);
2975
							if (is_ipaddrv6($bindip6)) {
2976
								$bind_to_ip6s[] = $bindip6;
2977
							}
2978
						}
2979
					}
2980
				}
2981
			}
2982
		}
2983
		if (!count($bind_to_ips) && $inet4) {
2984
			$bind_to_ips = array("0.0.0.0");
2985
		}
2986
		if (!count($bind_to_ip6s) && $inet6) {
2987
			$bind_to_ip6s = array("::");
2988
		}
2989

    
2990
		$pollport = config_get_path('snmpd/pollport');
2991
		if (is_port($pollport)) {
2992
			foreach ($bind_to_ips as $bind_to_ip) {
2993
				$snmpdconf .= <<<EOD
2994
begemotSnmpdPortStatus.{$bind_to_ip}.{$pollport} = 1
2995

    
2996
EOD;
2997

    
2998
			}
2999
			foreach ($bind_to_ip6s as $bind_to_ip6) {
3000
				$bind_to_ip6 = ip6_to_asn1($bind_to_ip6);
3001
				$snmpdconf .= <<<EOD
3002
begemotSnmpdTransInetStatus.2.16.{$bind_to_ip6}{$pollport}.1 = 4
3003

    
3004
EOD;
3005

    
3006
			}
3007
		}
3008

    
3009
		$snmpdconf .= <<<EOD
3010
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
3011
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
3012

    
3013
# These are bsnmp macros not php vars.
3014
sysContact      = $(contact)
3015
sysLocation     = $(location)
3016
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
3017

    
3018
snmpEnableAuthenTraps = 2
3019

    
3020
EOD;
3021

    
3022
		if (config_path_enabled('snmpd/modules', 'mibii')) {
3023
			$snmpdconf .= <<<EOD
3024
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
3025

    
3026
EOD;
3027
		}
3028

    
3029
		if (config_path_enabled('snmpd/modules', 'netgraph')) {
3030
			$snmpdconf .= <<<EOD
3031
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
3032
%netgraph
3033
begemotNgControlNodeName = "snmpd"
3034

    
3035
EOD;
3036
		}
3037

    
3038
		if (config_path_enabled('snmpd/modules', 'pf')) {
3039
			$snmpdconf .= <<<EOD
3040
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
3041

    
3042
EOD;
3043
		}
3044

    
3045
		if (config_path_enabled('snmpd/modules', 'hostres')) {
3046
			$snmpdconf .= <<<EOD
3047
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
3048

    
3049
EOD;
3050
		}
3051

    
3052
		if (config_path_enabled('snmpd/modules', 'bridge')) {
3053
			$snmpdconf .= <<<EOD
3054
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
3055
# config must end with blank line
3056

    
3057
EOD;
3058
		}
3059
		if (config_path_enabled('snmpd/modules', 'ucd')) {
3060
			$snmpdconf .= <<<EOD
3061
begemotSnmpdModulePath."ucd"     = "/usr/local/lib/snmp_ucd.so"
3062

    
3063
EOD;
3064
		}
3065
		if (config_path_enabled('snmpd/modules', 'regex')) {
3066
				$snmpdconf .= <<<EOD
3067
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"
3068

    
3069
EOD;
3070
		}
3071

    
3072
		fwrite($fd, $snmpdconf);
3073
		fclose($fd);
3074
		unset($snmpdconf);
3075

    
3076
		/* run bsnmpd */
3077
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
3078
			" -p {$g['varrun_path']}/snmpd.pid");
3079

    
3080
		if (platform_booting()) {
3081
			echo gettext("done.") . "\n";
3082
		}
3083
	}
3084

    
3085
	return 0;
3086
}
3087

    
3088
function services_dnsupdate_process($int = "", $updatehost = "", $forced = false) {
3089
	global $g;
3090
	if (config_path_enabled('system','developerspew')) {
3091
		$mt = microtime();
3092
		echo "services_dnsupdate_process() being called $mt\n";
3093
	}
3094

    
3095
	/* Dynamic DNS updating active? */
3096
	if (empty(config_get_path('dnsupdates/dnsupdate'))) {
3097
		return 0;
3098
	}
3099

    
3100
	$notify_text = "";
3101
	$gwgroups = return_gateway_groups_array(true);
3102
	foreach (config_get_path('dnsupdates/dnsupdate', []) as $i => $dnsupdate) {
3103
		if (!is_array($dnsupdate) ||
3104
		    empty($dnsupdate) ||
3105
		    !isset($dnsupdate['enable'])) {
3106
			continue;
3107
		}
3108
		/*
3109
		 * If it's using a gateway group, check if interface is
3110
		 * the active gateway for that group
3111
		 */
3112
		$group_int = '';
3113
		$friendly_group_int = '';
3114
		$gwgroup_member = false;
3115
		if (is_array($gwgroups[$dnsupdate['interface']])) {
3116
			if (!empty($gwgroups[$dnsupdate['interface']][0]['vip'])) {
3117
				$group_int = $gwgroups[$dnsupdate['interface']][0]['vip'];
3118
			} else {
3119
				$group_int = $gwgroups[$dnsupdate['interface']][0]['int'];
3120
				$friendly_group_int =
3121
				    convert_real_interface_to_friendly_interface_name(
3122
					$group_int);
3123
				if (!empty($int)) {
3124
					$gwgroup_member =
3125
					    interface_gateway_group_member(get_real_interface($int),
3126
					    $dnsupdate['interface']);
3127
				}
3128
			}
3129
		}
3130
		if (!empty($int) && ($int != $dnsupdate['interface']) && !$gwgroup_member &&
3131
		    ($int != $group_int) && ($int != $friendly_group_int)) {
3132
			continue;
3133
		}
3134
		if (!empty($updatehost) && ($updatehost != $dnsupdate['host'])) {
3135
			continue;
3136
		}
3137

    
3138
		/* determine interface name */
3139
		$if = get_failover_interface($dnsupdate['interface']);
3140

    
3141
		/* Determine address to update and default binding address */
3142
		if (isset($dnsupdate['usepublicip'])) {
3143
			$wanip = dyndnsCheckIP($if);
3144
			if (is_private_ip($wanip)) {
3145
				log_error(sprintf(gettext(
3146
				    "phpDynDNS: Not updating %s A record because the public IP address cannot be determined."),
3147
				    $dnsupdate['host']));
3148
				continue;
3149
			}
3150
			$bindipv4 = get_interface_ip($if);
3151
		} else {
3152
			$wanip = get_interface_ip($if);
3153
			$bindipv4 = $wanip;
3154
		}
3155
		if (is_stf_interface($dnsupdate['interface'])) {
3156
			$wanipv6 = get_interface_ipv6($dnsupdate['interface'] . '_stf');
3157
		} else {
3158
			$wanipv6 = get_interface_ipv6($if);
3159
		}
3160
		$bindipv6 = $wanipv6;
3161

    
3162
		/* Handle non-default interface bindings */
3163
		if ($dnsupdate['updatesource'] == "none") {
3164
			/* When empty, the directive will be omitted. */
3165
			$bindipv4 = "";
3166
			$bindipv6 = "";
3167
		} elseif (!empty($dnsupdate['updatesource'])) {
3168
			/* Find the alternate binding address */
3169
			$bindipv4 = get_interface_ip($dnsupdate['updatesource']);
3170
			if (is_stf_interface($dnsupdate['interface'])) {
3171
				$bindipv6 = get_interface_ipv6($dnsupdate['updatesource'] . '_stf');
3172
			} else {
3173
				$bindipv6 = get_interface_ipv6($dnsupdate['updatesource']);
3174
			}
3175
		}
3176

    
3177
		/* Handle IPv4/IPv6 selection for the update source interface/VIP */
3178
		switch ($dnsupdate['updatesourcefamily']) {
3179
			case "inet":
3180
				$bindip = $bindipv4;
3181
				break;
3182
			case "inet6":
3183
				$bindip = $bindipv6;
3184
				break;
3185
			case "":
3186
			default:
3187
				/* Try IPv4 first, if that is empty, try IPv6. */
3188
				/* Only specify the address if it's present, otherwise omit. */
3189
				if (!empty($bindipv4)) {
3190
					$bindip = $bindipv4;
3191
				} elseif (!empty($bindipv6)) {
3192
					$bindip = $bindipv6;
3193
				}
3194
				break;
3195
		}
3196

    
3197
		$cacheFile = g_get('conf_path') .
3198
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
3199
		    escapeshellarg($dnsupdate['host']) .
3200
		    "_{$dnsupdate['server']}.cache";
3201
		$cacheFilev6 = g_get('conf_path') .
3202
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
3203
		    escapeshellarg($dnsupdate['host']) .
3204
		    "_{$dnsupdate['server']}_v6.cache";
3205
		$currentTime = time();
3206

    
3207
		if (!$wanip && !$wanipv6) {
3208
			continue;
3209
		}
3210

    
3211
		$keyname = $dnsupdate['keyname'];
3212
		/* trailing dot */
3213
		if (substr($keyname, -1) != ".") {
3214
			$keyname .= ".";
3215
		}
3216

    
3217
		$hostname = $dnsupdate['host'];
3218
		/* trailing dot */
3219
		if (substr($hostname, -1) != ".") {
3220
			$hostname .= ".";
3221
		}
3222

    
3223
		/* write key file */
3224
		$algorithm = empty($dnsupdate['keyalgorithm']) ? 'hmac-md5' : $dnsupdate['keyalgorithm'];
3225
		$upkey = <<<EOD
3226
key "{$keyname}" {
3227
	algorithm {$algorithm};
3228
	secret "{$dnsupdate['keydata']}";
3229
};
3230

    
3231
EOD;
3232
		@file_put_contents("{$g['varetc_path']}/nsupdatekey{$i}", $upkey);
3233

    
3234
		/* generate update instructions */
3235
		$upinst = "";
3236
		if (!empty($dnsupdate['server'])) {
3237
			$upinst .= "server {$dnsupdate['server']}\n";
3238
		}
3239

    
3240
		if (!empty($dnsupdate['zone'])) {
3241
			$upinst .= "zone {$dnsupdate['zone']}\n";
3242
		}
3243

    
3244
		$cachedipv4 = '';
3245
		$cacheTimev4 = 0;
3246
		if (file_exists($cacheFile)) {
3247
			list($cachedipv4, $cacheTimev4) = explode("|",
3248
			    file_get_contents($cacheFile));
3249
		}
3250
		$cachedipv6 = '';
3251
		$cacheTimev6 = 0;
3252
		if (file_exists($cacheFilev6)) {
3253
			list($cachedipv6, $cacheTimev6) = explode("|",
3254
			    file_get_contents($cacheFilev6));
3255
		}
3256

    
3257
		// 25 Days
3258
		$maxCacheAgeSecs = 25 * 24 * 60 * 60;
3259
		$need_update = false;
3260

    
3261
		/* Update IPv4 if we have it. */
3262
		if (is_ipaddrv4($wanip) && $dnsupdate['recordtype'] != "AAAA") {
3263
			if (($wanip != $cachedipv4) || $forced ||
3264
			    (($currentTime - $cacheTimev4) > $maxCacheAgeSecs)) {
3265
				$upinst .= "update delete " .
3266
				    "{$dnsupdate['host']}. A\n";
3267
				$upinst .= "update add {$dnsupdate['host']}. " .
3268
				    "{$dnsupdate['ttl']} A {$wanip}\n";
3269
				if (!empty($bindip)) {
3270
					$upinst .= "local {$bindip}\n";
3271
				}
3272
				$need_update = true;
3273
			} else {
3274
				log_error(sprintf(gettext(
3275
				    "phpDynDNS: Not updating %s A record because the IP address has not changed."),
3276
				    $dnsupdate['host']));
3277
			}
3278
		} else {
3279
			@unlink($cacheFile);
3280
			unset($cacheFile);
3281
		}
3282

    
3283
		/* Update IPv6 if we have it. */
3284
		if (is_ipaddrv6($wanipv6) && $dnsupdate['recordtype'] != "A") {
3285
			if (($wanipv6 != $cachedipv6) || $forced ||
3286
			    (($currentTime - $cacheTimev6) > $maxCacheAgeSecs)) {
3287
				$upinst .= "update delete " .
3288
				    "{$dnsupdate['host']}. AAAA\n";
3289
				$upinst .= "update add {$dnsupdate['host']}. " .
3290
				    "{$dnsupdate['ttl']} AAAA {$wanipv6}\n";
3291
				$need_update = true;
3292
			} else {
3293
				log_error(sprintf(gettext(
3294
				    "phpDynDNS: Not updating %s AAAA record because the IPv6 address has not changed."),
3295
				    $dnsupdate['host']));
3296
			}
3297
		} else {
3298
			@unlink($cacheFilev6);
3299
			unset($cacheFilev6);
3300
		}
3301

    
3302
		$upinst .= "\n";	/* mind that trailing newline! */
3303

    
3304
		if (!$need_update) {
3305
			continue;
3306
		}
3307

    
3308
		@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}", $upinst);
3309
		unset($upinst);
3310
		/* invoke nsupdate */
3311
		$cmd = "/usr/local/bin/nsupdate -k {$g['varetc_path']}/nsupdatekey{$i}";
3312

    
3313
		if (isset($dnsupdate['usetcp'])) {
3314
			$cmd .= " -v";
3315
		}
3316

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

    
3319
		if (mwexec($cmd) == 0) {
3320
			if (!empty($cacheFile)) {
3321
				@file_put_contents($cacheFile,
3322
				    "{$wanip}|{$currentTime}");
3323
				log_error(sprintf(gettext(
3324
				    'phpDynDNS: updating cache file %1$s: %2$s'),
3325
				    $cacheFile, $wanip));
3326
				$notify_text .= sprintf(gettext(
3327
				    'DynDNS updated IP Address (A) for %1$s on %2$s (%3$s) to %4$s'),
3328
				    $dnsupdate['host'],
3329
				    convert_real_interface_to_friendly_descr($if),
3330
				    $if, $wanip) . "\n";
3331
			}
3332
			if (!empty($cacheFilev6)) {
3333
				@file_put_contents($cacheFilev6,
3334
				    "{$wanipv6}|{$currentTime}");
3335
				log_error(sprintf(gettext(
3336
				    'phpDynDNS: updating cache file %1$s: %2$s'),
3337
				    $cacheFilev6, $wanipv6));
3338
				$notify_text .= sprintf(gettext(
3339
				    'DynDNS updated IPv6 Address (AAAA) for %1$s on %2$s (%3$s) to %4$s'),
3340
				    $dnsupdate['host'],
3341
				    convert_real_interface_to_friendly_descr($if),
3342
				    $if, $wanipv6) . "\n";
3343
			}
3344
		} else {
3345
			if (!empty($cacheFile)) {
3346
				log_error(sprintf(gettext(
3347
				    'phpDynDNS: ERROR while updating IP Address (A) for %1$s (%2$s)'),
3348
				    $dnsupdate['host'], $wanip));
3349
			}
3350
			if (!empty($cacheFilev6)) {
3351
				log_error(sprintf(gettext(
3352
				    'phpDynDNS: ERROR while updating IP Address (AAAA) for %1$s (%2$s)'),
3353
				    $dnsupdate['host'], $wanipv6));
3354
			}
3355
		}
3356
		unset($cmd);
3357
	}
3358

    
3359
	if (!empty($notify_text)) {
3360
		notify_all_remote($notify_text);
3361
	}
3362

    
3363
	return 0;
3364
}
3365

    
3366
/* configure cron service */
3367
function configure_cron() {
3368
	global $g;
3369

    
3370
	$crontab_contents = "";
3371

    
3372
	if (!empty(config_get_path('cron/item', []))) {
3373
		$crontab_contents .= "#\n";
3374
		$crontab_contents .= "# pfSense specific crontab entries\n";
3375
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
3376
		$crontab_contents .= "#\n";
3377
		$crontab_contents .= "SHELL=/bin/sh\n";
3378
		$crontab_contents .= "PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin\n";
3379

    
3380
		$http_proxy = config_get_path('system/proxyurl');
3381
		$http_proxyport = config_get_path('system/proxyport');
3382
		if (!empty($http_proxy)) {
3383
			if (!empty($http_proxyport)) {
3384
				$http_proxy .= ':' . $http_proxyport;
3385
			}
3386
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
3387

    
3388
			$proxyuser = config_get_path('system/proxyuser');
3389
			$proxypass = config_get_path('system/proxypass');
3390
			if (!empty($proxyuser) && !empty($proxypass)) {
3391
				$crontab_contents .= "HTTP_PROXY_AUTH=basic:*:{$proxyuser}:{$proxypass}";
3392
			}
3393
		}
3394

    
3395
		foreach (config_get_path('cron/item', []) as $item) {
3396
			$crontab_contents .= "\n{$item['minute']}\t";
3397
			$crontab_contents .= "{$item['hour']}\t";
3398
			$crontab_contents .= "{$item['mday']}\t";
3399
			$crontab_contents .= "{$item['month']}\t";
3400
			$crontab_contents .= "{$item['wday']}\t";
3401
			$crontab_contents .= "{$item['who']}\t";
3402
			$crontab_contents .= "{$item['command']}";
3403
		}
3404

    
3405
		$crontab_contents .= "\n#\n";
3406
		$crontab_contents .= "# " . gettext("DO NOT EDIT THIS FILE MANUALLY!") . "\n";
3407
		$crontab_contents .= "# " . gettext("Use the cron package or create files in /etc/cron.d/.") . "\n";
3408
		$crontab_contents .= "#\n\n";
3409
	}
3410

    
3411
	/* please maintain the newline at the end of file */
3412
	file_put_contents("/etc/crontab", $crontab_contents);
3413
	unset($crontab_contents);
3414

    
3415
	/* make sure that cron is running and start it if it got killed somehow */
3416
	if (!is_process_running("cron")) {
3417
		exec("cd /tmp && /usr/sbin/cron -s 2>/dev/null");
3418
	} else {
3419
	/* do a HUP kill to force sync changes */
3420
		sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP");
3421
	}
3422

    
3423
}
3424

    
3425
function upnp_action ($action) {
3426
	global $g;
3427
	switch ($action) {
3428
		case "start":
3429
			if (file_exists('/var/etc/miniupnpd.conf')) {
3430
				@unlink("{$g['varrun_path']}/miniupnpd.pid");
3431
				mwexec_bg("/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf -P {$g['varrun_path']}/miniupnpd.pid");
3432
			}
3433
			break;
3434
		case "stop":
3435
			killbypid("{$g['varrun_path']}/miniupnpd.pid");
3436
			while ((int)exec("/bin/pgrep -a miniupnpd | wc -l") > 0) {
3437
				mwexec('/usr/bin/killall miniupnpd 2>/dev/null', true);
3438
			}
3439
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
3440
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
3441
			break;
3442
		case "restart":
3443
			upnp_action('stop');
3444
			upnp_action('start');
3445
			break;
3446
	}
3447
}
3448

    
3449
function upnp_start() {
3450
	if (empty(config_get_path('installedpackages/miniupnpd/config'))) {
3451
		return;
3452
	}
3453

    
3454
	if (config_get_path('installedpackages/miniupnpd/config/0/enable') == 'on') {
3455
		echo gettext("Starting UPnP service... ");
3456
		require_once('/usr/local/pkg/miniupnpd.inc');
3457
		sync_package_miniupnpd();
3458
		echo "done.\n";
3459
	}
3460
}
3461

    
3462
function install_cron_job($command, $active = false, $minute = "0", $hour = "*", $monthday = "*", $month = "*", $weekday = "*", $who = "root", $write_config = true) {
3463
	$is_installed = false;
3464
	$cron_changed = true;
3465
	$change_message = "";
3466

    
3467
	init_config_arr(['cron','item']);
3468

    
3469
	$job = null;
3470
	foreach (config_get_path('cron/item', []) as $idx => $item) {
3471
		if (strstr($item['command'], $command)) {
3472
			$is_installed = true;
3473
			$job = $idx;
3474
			break;
3475
		}
3476
	}
3477

    
3478
	if ($active) {
3479
		$cron_item = array();
3480
		$cron_item['minute'] = $minute;
3481
		$cron_item['hour'] = $hour;
3482
		$cron_item['mday'] = $monthday;
3483
		$cron_item['month'] = $month;
3484
		$cron_item['wday'] = $weekday;
3485
		$cron_item['who'] = $who;
3486
		$cron_item['command'] = $command;
3487
		if (!$is_installed) {
3488
			$cron_items = config_get_path('cron/item', []);
3489
			$cron_items[] = $cron_item;
3490
			config_set_path('cron/item', $cron_items);
3491
			$change_message = "Installed cron job for %s";
3492
		} else {
3493
			if (config_get_path("cron/item/{$job}") == $cron_item) {
3494
				$cron_changed = false;
3495
			} else {
3496
				config_set_path("cron/item/{$job}", $cron_item);
3497
				$change_message = "Updated cron job for %s";
3498
			}
3499
		}
3500
	} else {
3501
		if ($is_installed == true) {
3502
			config_del_path("cron/item/{$job}");
3503
			$change_message = "Removed cron job for %s";
3504
		} else {
3505
			$cron_changed = false;
3506
		}
3507
	}
3508

    
3509
	if ($cron_changed) {
3510
		/* Optionally write the configuration if this function made changes.
3511
		 * Performing a write_config() in this way can have unintended side effects. See #7146
3512
		 * Base system instances of this function do not need to write, packages may.
3513
		 */
3514
		if ($write_config) {
3515
			write_config(sprintf(gettext($change_message), $command));
3516
		}
3517
		configure_cron();
3518
	}
3519
}
3520

    
3521
?>
(47-47/61)