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 porkbun porkbun-v6');
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,Porkbun,Porkbun (v6)');
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']}/var/db\n");
468
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run\n");
469
	fwrite($fd, "/usr/sbin/chown -R dhcpd:_dhcp {$g['dhcpd_chroot_path']}/*\n");
470
	fwrite($fd, "/sbin/mount -t devfs devfs {$g['dhcpd_chroot_path']}/dev\n");
471
	fclose($fd);
472

    
473
	mwexec("/bin/sh {$g['tmp_path']}/dhcpd.sh");
474

    
475
	if ($family == "all" || $family == "inet") {
476
		services_dhcpdv4_configure();
477
	}
478
	if ($family == "all" || $family == "inet6") {
479
		services_dhcpdv6_configure($blacklist);
480
		services_radvd_configure($blacklist);
481
	}
482

    
483
	unlock($dhcpdconfigurelck);
484
}
485

    
486
function services_dhcpdv4_configure() {
487
	global $g;
488
	$need_ddns_updates = false;
489
	$ddns_zones = array();
490

    
491
	if (g_get('services_dhcp_server_enable') == false) {
492
		return;
493
	}
494

    
495
	if (config_path_enabled('system','developerspew')) {
496
		$mt = microtime();
497
		echo "services_dhcpdv4_configure($if) being called $mt\n";
498
	}
499

    
500
	/* kill any running dhcpd */
501
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid")) {
502
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid");
503
	}
504

    
505
	/* DHCP enabled on any interfaces? */
506
	if (!is_dhcp_server_enabled()) {
507
		return 0;
508
	}
509

    
510
	$syscfg = config_get_path('system');
511
	init_config_arr(['dhcpd']);
512
	$dhcpdcfg = config_get_path('dhcpd');
513
	$Iflist = get_configured_interface_list();
514

    
515
	/* Only consider DNS servers with IPv4 addresses for the IPv4 DHCP server. */
516
	$dns_arrv4 = array();
517
	if (is_array($syscfg['dnsserver'])) {
518
		foreach ($syscfg['dnsserver'] as $dnsserver) {
519
			if (is_ipaddrv4($dnsserver)) {
520
				$dns_arrv4[] = $dnsserver;
521
			}
522
		}
523
	}
524

    
525
	if (platform_booting()) {
526
		echo gettext("Starting DHCP service...");
527
	} else {
528
		sleep(1);
529
	}
530

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

    
614
	$dhcpdconf = <<<EOD
615

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

    
628
EOD;
629

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

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

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

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

    
656
EOD;
657

    
658
		}
659
		break;
660
	}
661

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

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

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

    
686
		interfaces_staticarp_configure($dhcpif);
687

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

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

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

    
754
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
755
		if (empty($dhcpifconf)) {
756
			continue;
757
		}
758

    
759
		$newzone = array();
760
		$ifcfg = config_get_path("interfaces/{$dhcpif}");
761

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

    
770
		if (!is_ipaddr($subnet)) {
771
			continue;
772
		}
773

    
774
		$all_pools = array();
775
		$all_pools[] = $dhcpifconf;
776
		if (is_array($dhcpifconf['pool'])) {
777
			$all_pools = array_merge($all_pools, $dhcpifconf['pool']);
778
		}
779

    
780
		$dnscfg = "";
781

    
782
		if ($dhcpifconf['domain']) {
783
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
784
		}
785

    
786
		if ($dhcpifconf['domainsearchlist'] <> "") {
787
			$dnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpifconf['domainsearchlist'])) . "\";\n";
788
		}
789

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

    
800
			if (empty($dhcpifconf['ddnsclientupdates'])) {
801
				$ddnsclientupdates = 'allow';
802
			} else {
803
				$ddnsclientupdates = $dhcpifconf['ddnsclientupdates'];
804
			}
805

    
806
			$dnscfg .= "	{$ddnsclientupdates} client-updates;\n";
807

    
808
			$revsubnet = array_reverse(explode('.',$subnet));
809

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

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

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

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

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

    
878
		$dhcpdconf .= "subnet {$subnet} netmask {$subnetmask} {\n";
879

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

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

    
945
			if ($poolconf['failover_peerip'] <> "") {
946
				$dhcpdconf .= "		$deny_action dynamic bootp clients;\n";
947
			}
948

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

    
961
			if ($poolconf['gateway'] && $poolconf['gateway'] != "none" && ($poolconf['gateway'] != $dhcpifconf['gateway'])) {
962
				$dhcpdconf .= "		option routers {$poolconf['gateway']};\n";
963
			}
964

    
965
			if ($dhcpifconf['failover_peerip'] <> "") {
966
				$dhcpdconf .= "		failover peer \"dhcp_{$dhcpif}\";\n";
967
			}
968

    
969
			$pdnscfg = "";
970

    
971
			if ($poolconf['domain'] && ($poolconf['domain'] != $dhcpifconf['domain'])) {
972
				$pdnscfg .= "		option domain-name \"{$poolconf['domain']}\";\n";
973
			}
974

    
975
			if (!empty($poolconf['domainsearchlist']) && ($poolconf['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
976
				$pdnscfg .= "		option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $poolconf['domainsearchlist'])) . "\";\n";
977
			}
978

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

    
986
			$dhcpdconf .= "{$pdnscfg}";
987

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

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

    
998
			// ignore bootp
999
			if (isset($poolconf['ignorebootp'])) {
1000
				$dhcpdconf .= "		ignore bootp;\n";
1001
			}
1002

    
1003
			// ignore-client-uids
1004
			if (isset($poolconf['ignoreclientuids'])) {
1005
				$dhcpdconf .= "		ignore-client-uids true;\n";
1006
			}
1007

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

    
1014
			// ntp-servers
1015
			if (is_array($poolconf['ntpserver']) && $poolconf['ntpserver'][0] && ($poolconf['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
1016
				$dhcpdconf .= "		option ntp-servers " . join(",", $poolconf['ntpserver']) . ";\n";
1017
			}
1018

    
1019
			// tftp-server-name
1020
			if (!empty($poolconf['tftp']) && ($poolconf['tftp'] != $dhcpifconf['tftp'])) {
1021
				$dhcpdconf .= "		option tftp-server-name \"{$poolconf['tftp']}\";\n";
1022
			}
1023

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

    
1054
			// ldap-server
1055
			if (!empty($poolconf['ldap']) && ($poolconf['ldap'] != $dhcpifconf['ldap'])) {
1056
				$dhcpdconf .= "		option ldap-server \"{$poolconf['ldap']}\";\n";
1057
			}
1058

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

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

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

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

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

    
1148
		$dhcpdconf .= <<<EOD
1149
$dnscfg
1150

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

    
1157
		// max-lease-time
1158
		if ($dhcpifconf['maxleasetime']) {
1159
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
1160
		}
1161

    
1162
		if (!isset($dhcpifconf['disablepingcheck'])) {
1163
			$dhcpdconf .= "	ping-check true;\n";
1164
		} else {
1165
			$dhcpdconf .= "	ping-check false;\n";
1166
		}
1167

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

    
1174
		// ntp-servers
1175
		if (is_array($dhcpifconf['ntpserver']) && $dhcpifconf['ntpserver'][0]) {
1176
			$dhcpdconf .= "	option ntp-servers " . join(",", $dhcpifconf['ntpserver']) . ";\n";
1177
		}
1178

    
1179
		// tftp-server-name
1180
		if ($dhcpifconf['tftp'] <> "") {
1181
			$dhcpdconf .= "	option tftp-server-name \"{$dhcpifconf['tftp']}\";\n";
1182
		}
1183

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

    
1208
		// ldap-server
1209
		if ($dhcpifconf['ldap'] <> "") {
1210
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
1211
		}
1212

    
1213
		// net boot information
1214
		if (isset($dhcpifconf['netboot'])) {
1215
			if ($dhcpifconf['nextserver'] <> "") {
1216
				$dhcpdconf .= "	next-server {$dhcpifconf['nextserver']};\n";
1217
			}
1218

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

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

    
1272
		$dhcpdconf .= <<<EOD
1273
}
1274

    
1275
EOD;
1276

    
1277
		/* add static mappings */
1278
		if (is_array($dhcpifconf['staticmap'])) {
1279

    
1280
			$i = 0;
1281
			$sm_newzone[] = array();
1282
			$need_sm_ddns_updates = false;
1283
			foreach ($dhcpifconf['staticmap'] as $sm) {
1284
				if (empty($sm)) {
1285
					continue;
1286
				}
1287
				$cid = '';
1288
				$dhcpdconf .= "host s_{$dhcpif}_{$i} {\n";
1289

    
1290
				if ($sm['mac']) {
1291
					$dhcpdconf .= "	hardware ethernet {$sm['mac']};\n";
1292
				}
1293

    
1294
				if ($sm['cid']) {
1295
					$cid = str_replace('"', '\"', $sm['cid']);
1296
					$dhcpdconf .= "	option dhcp-client-identifier \"{$cid}\";\n";
1297
				}
1298

    
1299
				if ($sm['ipaddr']) {
1300
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
1301
				}
1302

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

    
1315
				if ($sm['rootpath']) {
1316
					$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1317
				}
1318

    
1319
				if ($sm['gateway'] && ($sm['gateway'] != $dhcpifconf['gateway'])) {
1320
					$dhcpdconf .= "	option routers {$sm['gateway']};\n";
1321
				}
1322

    
1323
				$smdnscfg = "";
1324

    
1325
				if ($sm['domain'] && ($sm['domain'] != $dhcpifconf['domain'])) {
1326
					$smdnscfg .= "	option domain-name \"{$sm['domain']}\";\n";
1327
				}
1328

    
1329
				if (!empty($sm['domainsearchlist']) && ($sm['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
1330
					$smdnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $sm['domainsearchlist'])) . "\";\n";
1331
				}
1332

    
1333
				if (isset($sm['ddnsupdate'])) {
1334
					if (($sm['ddnsdomain'] <> "") && ($sm['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
1335
						$smdnscfg .= "	ddns-domainname \"{$sm['ddnsdomain']}\";\n";
1336
				 		$need_sm_ddns_updates = true;
1337
					}
1338
					$smdnscfg .= "	ddns-update-style interim;\n";
1339
				}
1340

    
1341
				if (is_array($sm['dnsserver']) && ($sm['dnsserver'][0]) && ($sm['dnsserver'][0] != $dhcpifconf['dnsserver'][0])) {
1342
					$smdnscfg .= "	option domain-name-servers " . join(",", $sm['dnsserver']) . ";\n";
1343
				}
1344
				$dhcpdconf .= "{$smdnscfg}";
1345

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

    
1351
				// max-lease-time
1352
				if ($sm['maxleasetime'] && ($sm['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
1353
					$dhcpdconf .= "	max-lease-time {$sm['maxleasetime']};\n";
1354
				}
1355

    
1356
				// netbios-name*
1357
				if (is_array($sm['winsserver']) && $sm['winsserver'][0] && ($sm['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
1358
					$dhcpdconf .= "	option netbios-name-servers " . join(",", $sm['winsserver']) . ";\n";
1359
					$dhcpdconf .= "	option netbios-node-type 8;\n";
1360
				}
1361

    
1362
				// ntp-servers
1363
				if (is_array($sm['ntpserver']) && $sm['ntpserver'][0] && ($sm['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
1364
					$dhcpdconf .= "	option ntp-servers " . join(",", $sm['ntpserver']) . ";\n";
1365
				}
1366

    
1367
				// tftp-server-name
1368
				if (!empty($sm['tftp']) && ($sm['tftp'] != $dhcpifconf['tftp'])) {
1369
					$dhcpdconf .= "	option tftp-server-name \"{$sm['tftp']}\";\n";
1370
				}
1371

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

    
1396
				// ldap-server
1397
				if (!empty($sm['ldap']) && ($sm['ldap'] != $dhcpifconf['ldap'])) {
1398
					$dhcpdconf .= "	option ldap-server \"{$sm['ldap']}\";\n";
1399
				}
1400

    
1401
				// net boot information
1402
				if (isset($sm['netboot'])) {
1403
					if ($sm['nextserver'] <> "") {
1404
						$dhcpdconf .= "	next-server {$sm['nextserver']};\n";
1405
					}
1406

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

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

    
1460
				$dhcpdconf .= "}\n";
1461

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

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

    
1491

    
1492
				$i++;
1493
			}
1494
		}
1495

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

    
1509
	if ($need_ddns_updates) {
1510
		$dhcpdconf .= "ddns-update-style interim;\n";
1511
		$dhcpdconf .= "update-static-leases on;\n";
1512

    
1513
		$dhcpdconf .= dhcpdzones($ddns_zones);
1514
	}
1515

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

    
1524
	/* create an empty leases database */
1525
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
1526
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
1527
	}
1528

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

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

    
1539
	if (platform_booting()) {
1540
		print "done.\n";
1541
	}
1542

    
1543
	return 0;
1544
}
1545

    
1546
function dhcpdkey($dhcpifconf) {
1547
	$dhcpdconf = "";
1548
	if (!empty($dhcpifconf['ddnsdomainkeyname']) && !empty($dhcpifconf['ddnsdomainkey'])) {
1549
		$algorithm = empty($dhcpifconf['ddnsdomainkeyalgorithm']) ? 'hmac-md5' : $dhcpifconf['ddnsdomainkeyalgorithm'];
1550
		$dhcpdconf .= "key \"{$dhcpifconf['ddnsdomainkeyname']}\" {\n";
1551
		$dhcpdconf .= "	algorithm {$algorithm};\n";
1552
		$dhcpdconf .= "	secret {$dhcpifconf['ddnsdomainkey']};\n";
1553
		$dhcpdconf .= "}\n";
1554
	}
1555

    
1556
	return $dhcpdconf;
1557
}
1558

    
1559
function dhcpdzones($ddns_zones) {
1560
	$dhcpdconf = "";
1561

    
1562
	if (is_array($ddns_zones)) {
1563
		$added_zones = array();
1564
		foreach ($ddns_zones as $zone) {
1565
			if (!is_array($zone) || empty($zone) || !is_array($zone['dns-servers'])) {
1566
				continue;
1567
			}
1568
			$primary = $zone['dns-servers'][0];
1569
			$secondary = empty($zone['dns-servers'][1]) ? "" : $zone['dns-servers'][1];
1570

    
1571
			// Make sure we aren't using any invalid servers.
1572
			if (!is_ipaddr($primary)) {
1573
				if (is_ipaddr($secondary)) {
1574
					$primary = $secondary;
1575
					$secondary = "";
1576
				} else {
1577
					continue;
1578
				}
1579
			}
1580

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

    
1621
	return $dhcpdconf;
1622
}
1623

    
1624
function services_dhcpdv6_configure($blacklist = array()) {
1625
	global $g;
1626

    
1627
	if (g_get('services_dhcp_server_enable') == false) {
1628
		return;
1629
	}
1630

    
1631
	if (config_path_enabled('system','developerspew')) {
1632
		$mt = microtime();
1633
		echo "services_dhcpd_configure($if) being called $mt\n";
1634
	}
1635

    
1636
	/* kill any running dhcpd */
1637
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid")) {
1638
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid");
1639
	}
1640

    
1641
	/* kill any running dhcpleases6 */
1642
	if (isvalidpid("{$g['varrun_path']}/dhcpleases6.pid")) {
1643
		killbypid("{$g['varrun_path']}/dhcpleases6.pid");
1644
	}
1645

    
1646
	/* DHCP enabled on any interfaces? */
1647
	if (!is_dhcpv6_server_enabled()) {
1648
		return 0;
1649
	}
1650

    
1651
	$syscfg = config_get_path('system');
1652
	init_config_arr(['dhcpdv6']);
1653
	$dhcpdv6cfg = config_get_path('dhcpdv6');
1654
	$Iflist = get_configured_interface_list();
1655
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
1656

    
1657

    
1658
	if (platform_booting()) {
1659
		echo "Starting DHCPv6 service...";
1660
	} else {
1661
		sleep(1);
1662
	}
1663

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

    
1676
	if (isset($dhcpv6ifconf['netboot']) && !empty($dhcpv6ifconf['bootfile_url'])) {
1677
		$custoptionsv6 .= "option dhcp6.bootfile-url code 59 = string;\n";
1678
	}
1679

    
1680
	$dhcpdv6conf = <<<EOD
1681

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

    
1694
EOD;
1695

    
1696
	if (!isset($dhcpv6ifconf['disableauthoritative'])) {
1697
		$dhcpdv6conf .= "authoritative;\n";
1698
	}
1699

    
1700
	if (isset($dhcpv6ifconf['alwaysbroadcast'])) {
1701
		$dhcpdv6conf .= "always-broadcast on\n";
1702
	}
1703

    
1704
	$dhcpdv6ifs = array();
1705

    
1706
	$dhcpv6num = 0;
1707
	$nsupdate = false;
1708

    
1709
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1710
		if (empty($dhcpv6ifconf)) {
1711
			continue;
1712
		}
1713

    
1714
		$ddns_zones = array();
1715

    
1716
		$ifcfgv6 = config_get_path("interfaces/{$dhcpv6if}");
1717

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

    
1734
		$range_from = $dhcpv6ifconf['range']['from'];
1735
		$range_to = $dhcpv6ifconf['range']['to'];
1736
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
1737
			$range_from = merge_ipv6_delegated_prefix($ifcfgipv6, $range_from, $pdlen);
1738
			$range_to = merge_ipv6_delegated_prefix($ifcfgipv6, $range_to, $pdlen);
1739
		}
1740

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

    
1751
		$dnscfgv6 = "";
1752

    
1753
		if ($dhcpv6ifconf['domain']) {
1754
			$dnscfgv6 .= "	option domain-name \"{$dhcpv6ifconf['domain']}\";\n";
1755
		}
1756

    
1757
		if ($dhcpv6ifconf['domainsearchlist'] <> "") {
1758
			$dnscfgv6 .= "	option dhcp6.domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpv6ifconf['domainsearchlist'])) . "\";\n";
1759
		}
1760

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

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

    
1800
		if (!is_ipaddrv6($ifcfgipv6)) {
1801
			$ifcfgsnv6 = "64";
1802
			$subnetv6 = gen_subnetv6($range_from, $ifcfgsnv6);
1803
		}
1804

    
1805
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1806

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

    
1828
		$dhcpdv6conf .= " {\n";
1829

    
1830
		if (!empty($range_from) && !empty($range_to)) {
1831
			$dhcpdv6conf .= "	range6 {$range_from} {$range_to};\n";
1832
		}
1833

    
1834
		$dhcpdv6conf .= $dnscfgv6;
1835

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

    
1852
		// max-lease-time
1853
		if ($dhcpv6ifconf['maxleasetime']) {
1854
			$dhcpdv6conf .= "	max-lease-time {$dhcpv6ifconf['maxleasetime']};\n";
1855
		}
1856

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

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

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

    
1900
		// net boot information
1901
		if (isset($dhcpv6ifconf['netboot'])) {
1902
			if (!empty($dhcpv6ifconf['bootfile_url'])) {
1903
				$dhcpdv6conf .= "	option dhcp6.bootfile-url \"{$dhcpv6ifconf['bootfile_url']}\";\n";
1904
			}
1905
		}
1906

    
1907
		$dhcpdv6conf .= "}\n";
1908

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

    
1921
EOD;
1922
				if ($sm['ipaddrv6']) {
1923
					$ipaddrv6 = $sm['ipaddrv6'];
1924
					if ($ifcfgv6['ipaddrv6'] == 'track6') {
1925
						$ipaddrv6 = merge_ipv6_delegated_prefix($ifcfgipv6, $ipaddrv6, $pdlen);
1926
					}
1927
					$dhcpdv6conf .= "	fixed-address6 {$ipaddrv6};\n";
1928
				}
1929

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

    
1943
				if ($sm['rootpath']) {
1944
					$dhcpdv6conf .= "	option root-path \"{$sm['rootpath']}\";\n";
1945
				}
1946

    
1947
				$dhcpdv6conf .= "}\n";
1948
				$i++;
1949
			}
1950
		}
1951

    
1952
		if ($dhcpv6ifconf['ddnsdomain']) {
1953
			$dhcpdv6conf .= dhcpdkey($dhcpv6ifconf);
1954
			$dhcpdv6conf .= dhcpdzones($ddns_zones);
1955
		}
1956

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

    
1977
	if ($nsupdate) {
1978
		$dhcpdv6conf .= "ddns-update-style interim;\n";
1979
		$dhcpdv6conf .= "update-static-leases on;\n";
1980
	} else {
1981
		$dhcpdv6conf .= "ddns-update-style none;\n";
1982
	}
1983

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

    
1995
	/* create an empty leases v6 database */
1996
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases")) {
1997
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1998
	}
1999

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

    
2004
	/* fire up dhcpd in a chroot */
2005
	if (count($dhcpdv6ifs) > 0) {
2006
		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));
2007
		mwexec("/usr/local/sbin/dhcpleases6 -c \"/usr/local/bin/php-cgi -f /usr/local/sbin/prefixes.php\" -l {$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
2008
	}
2009
	if (platform_booting()) {
2010
		print gettext("done.") . "\n";
2011
	}
2012

    
2013
	return 0;
2014
}
2015

    
2016
function services_igmpproxy_configure($interface='') {
2017
	global $g;
2018

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

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

    
2043
	if (platform_booting()) {
2044
		echo gettext("Starting IGMP Proxy service...");
2045
	}
2046

    
2047
	if (isvalidproc("igmpproxy")) {
2048
		log_error(gettext("Restarting IGMP Proxy service."));
2049
		killbyname("igmpproxy");
2050
	}
2051

    
2052
	$iflist = get_configured_interface_list();
2053

    
2054
	$igmpconf = <<<EOD
2055

    
2056
##------------------------------------------------------
2057
## Enable Quickleave mode (Sends Leave instantly)
2058
##------------------------------------------------------
2059
quickleave
2060

    
2061
EOD;
2062

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

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

    
2095
	if (!$upstream || !$downstream) {
2096
		log_error(gettext("Could not find upstream or downstream IGMP Proxy interfaces!"));
2097
		return;
2098
	}
2099

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

    
2109
	if (config_path_enabled('syslog','igmpxverbose')) {
2110
		mwexec_bg("/usr/local/sbin/igmpproxy -v {$g['varetc_path']}/igmpproxy.conf");
2111
	} else {
2112
		mwexec_bg("/usr/local/sbin/igmpproxy {$g['varetc_path']}/igmpproxy.conf");
2113
	}
2114

    
2115
	log_error(gettext("Started IGMP Proxy service."));
2116

    
2117
	if (platform_booting()) {
2118
		echo gettext("done.") . "\n";
2119
	}
2120

    
2121
	return true;
2122
}
2123

    
2124
function services_dhcrelay_configure() {
2125
	global $g;
2126

    
2127
	if (config_path_enabled('system','developerspew')) {
2128
		$mt = microtime();
2129
		echo "services_dhcrelay_configure() being called $mt\n";
2130
	}
2131

    
2132
	/* kill any running dhcrelay */
2133
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
2134

    
2135
	init_config_arr(array('dhcrelay'));
2136
	$dhcrelaycfg = config_get_path('dhcrelay');
2137

    
2138
	/* DHCPRelay enabled on any interfaces? */
2139
	if (!isset($dhcrelaycfg['enable'])) {
2140
		return 0;
2141
	}
2142

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

    
2162
	if (platform_booting()) {
2163
		echo gettext("Starting DHCP Relay service...");
2164
	} else {
2165
		sleep(1);
2166
	}
2167

    
2168
	$iflist = get_configured_interface_list();
2169

    
2170
	$dhcrelayifs = array();
2171
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
2172
	foreach ($dhcifaces as $dhcrelayif) {
2173
		if (!isset($iflist[$dhcrelayif])) {
2174
			continue;
2175
		}
2176

    
2177
		if (get_interface_ip($dhcrelayif)) {
2178
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
2179
		}
2180
	}
2181
	$dhcrelayifs = array_unique($dhcrelayifs);
2182

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

    
2201
	/* Check for relays in the same subnet as clients so they can bind for
2202
	 * either direction (up or down) */
2203
	$srvrelayifs = array_intersect($dhcrelayifs, $srvifaces);
2204

    
2205
	/* The server interface(s) should not be in this list */
2206
	$dhcrelayifs = array_diff($dhcrelayifs, $srvifaces);
2207

    
2208
	/* Remove the dual-role interfaces from up and down lists */
2209
	$srvifaces = array_diff($srvifaces, $srvrelayifs);
2210
	$dhcrelayifs = array_diff($dhcrelayifs, $srvrelayifs);
2211

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

    
2222
	$cmd = "/usr/local/sbin/dhcrelay";
2223

    
2224
	if (!empty($dhcrelayifs)) {
2225
		$cmd .= " -id " . implode(" -id ", $dhcrelayifs);
2226
	}
2227
	if (!empty($srvifaces)) {
2228
		$cmd .= " -iu " . implode(" -iu ", $srvifaces);
2229
	}
2230
	if (!empty($srvrelayifs)) {
2231
		$cmd .= " -i " . implode(" -i ", $srvrelayifs);
2232
	}
2233

    
2234
	if (isset($dhcrelaycfg['agentoption'])) {
2235
		$cmd .= " -a -m replace";
2236
	}
2237

    
2238
	$cmd .= " " . implode(" ", $srvips);
2239
	mwexec($cmd);
2240
	unset($cmd);
2241

    
2242
	return 0;
2243
}
2244

    
2245
function services_dhcrelay6_configure() {
2246
	global $g;
2247

    
2248
	if (config_path_enabled('system','developerspew')) {
2249
		$mt = microtime();
2250
		echo "services_dhcrelay6_configure() being called $mt\n";
2251
	}
2252

    
2253
	/* kill any running dhcrelay */
2254
	killbypid("{$g['varrun_path']}/dhcrelay6.pid");
2255

    
2256
	init_config_arr(array('dhcrelay6'));
2257
	$dhcrelaycfg = config_get_path('dhcrelay6');
2258

    
2259
	/* DHCPv6 Relay enabled on any interfaces? */
2260
	if (!isset($dhcrelaycfg['enable'])) {
2261
		return 0;
2262
	}
2263

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

    
2283
	if (platform_booting()) {
2284
		echo gettext("Starting DHCPv6 Relay service...");
2285
	} else {
2286
		sleep(1);
2287
	}
2288

    
2289
	$iflist = get_configured_interface_list();
2290

    
2291
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
2292
	foreach ($dhcifaces as $dhcrelayif) {
2293
		if (!isset($iflist[$dhcrelayif])) {
2294
			continue;
2295
		}
2296

    
2297
		if (get_interface_ipv6($dhcrelayif)) {
2298
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
2299
		}
2300
	}
2301
	$dhcrelayifs = array_unique($dhcrelayifs);
2302

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

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

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

    
2332
	return 0;
2333
}
2334

    
2335
function services_dyndns_configure_client($conf) {
2336

    
2337
	if (!isset($conf['enable'])) {
2338
		return;
2339
	}
2340

    
2341
	/* load up the dyndns.class */
2342
	require_once("dyndns.class");
2343

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

    
2370
function services_dyndns_configure($int = "") {
2371
	if (config_path_enabled('system','developerspew')) {
2372
		$mt = microtime();
2373
		echo "services_dyndns_configure() being called $mt\n";
2374
	}
2375

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

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

    
2424
		if (platform_booting()) {
2425
			echo gettext("done.") . "\n";
2426
		}
2427
	}
2428

    
2429
	return 0;
2430
}
2431

    
2432
function dyndnsCheckIP($int) {
2433
	global $factory_default_checkipservice;
2434
	$ip_address = get_interface_ip($int);
2435

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

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

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

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

    
2480
		if ($matches[1]) {
2481
			$parsed_ip = trim($matches[1]);
2482
		} else {
2483
			$parsed_ip = trim($ip_result_decoded);
2484
		}
2485

    
2486
		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);
2487
		if ($matches[0]) {
2488
			$ip_address = $matches[0];
2489
		}
2490
	}
2491
	return $ip_address;
2492
}
2493

    
2494
function services_dnsmasq_configure($restart_dhcp = true) {
2495
	global $g;
2496
	$return = 0;
2497

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

    
2505

    
2506
	if (config_path_enabled('system','developerspew')) {
2507
		$mt = microtime();
2508
		echo "services_dnsmasq_configure() being called $mt\n";
2509
	}
2510

    
2511
	/* kill any running dnsmasq */
2512
	if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) {
2513
		sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
2514
	}
2515

    
2516
	if (config_path_enabled('dnsmasq')) {
2517

    
2518
		if (platform_booting()) {
2519
			echo gettext("Starting DNS forwarder...");
2520
		} else {
2521
			sleep(1);
2522
		}
2523

    
2524
		/* generate hosts file */
2525
		if (system_hosts_generate() != 0) {
2526
			$return = 1;
2527
		}
2528

    
2529
		$args = "";
2530

    
2531
		if (config_path_enabled('dnsmasq','regdhcp')) {
2532
			$args .= " --dhcp-hostsfile={$g['etc_path']}/hosts ";
2533
		}
2534

    
2535
		/* Setup listen port, if non-default */
2536
		$port = config_get_path('dnsmasq/port');
2537
		if (is_port($port)) {
2538
			$args .= " --port={$port} ";
2539
		}
2540

    
2541
		$listen_addresses = "";
2542

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

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

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

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

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

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

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

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

    
2627
		if (!config_path_enabled('system/webgui', 'nodnsrebindcheck')) {
2628
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2629
		}
2630

    
2631
		if (config_path_enabled('dnsmasq','strict_order')) {
2632
			$args .= " --strict-order ";
2633
		} else {
2634
			$args .= " --all-servers ";
2635
		}
2636

    
2637
		if (config_path_enabled('dnsmasq','domain_needed')) {
2638
			$args .= " --domain-needed ";
2639
		}
2640

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

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

    
2659
		system_dhcpleases_configure();
2660

    
2661
		if (platform_booting()) {
2662
			echo gettext("done.") . "\n";
2663
		}
2664
	}
2665

    
2666
	if (!platform_booting() && $restart_dhcp) {
2667
		if (services_dhcpd_configure() != 0) {
2668
			$return = 1;
2669
		}
2670
	}
2671

    
2672
	return $return;
2673
}
2674

    
2675
function services_unbound_configure($restart_dhcp = true, $interface = '') {
2676
	global $g;
2677
	$return = 0;
2678

    
2679
	if (config_path_enabled('system','developerspew')) {
2680
		$mt = microtime();
2681
		echo "services_unbound_configure() being called $mt\n";
2682
	}
2683

    
2684
	if (!empty($interface) && config_path_enabled('unbound') &&
2685
	    !in_array($interface, explode(',', config_get_path('unbound/active_interface'))) &&
2686
	    !in_array($interface, explode(',', config_get_path('unbound/outgoing_interface')))) {
2687
		return $return;
2688
	}
2689

    
2690
	if (config_path_enabled('unbound')) {
2691
		require_once('/etc/inc/unbound.inc');
2692

    
2693
		/* Stop Unbound using TERM */
2694
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2695
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
2696
		}
2697

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

    
2705
		$python_mode = false;
2706
		$python_script = config_get_path('unbound/python_script');
2707
		if (config_path_enabled('unbound','python') && !empty($python_script)) {
2708
			$python_mode = true;
2709
		}
2710

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

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

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

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

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

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

    
2779
		if (platform_booting()) {
2780
			echo gettext("Starting DNS Resolver...");
2781
		} else {
2782
			sleep(1);
2783
		}
2784

    
2785
		/* generate hosts file */
2786
		if (system_hosts_generate() != 0) {
2787
			$return = 1;
2788
		}
2789

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

    
2807
		sync_unbound_service();
2808
		if (platform_booting()) {
2809
			log_error(gettext("sync unbound done."));
2810
			echo gettext("done.") . "\n";
2811
		}
2812

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

    
2821
	if (!platform_booting() && $restart_dhcp) {
2822
		if (services_dhcpd_configure() != 0) {
2823
			$return = 1;
2824
		}
2825
	}
2826

    
2827
	return $return;
2828
}
2829

    
2830
function services_snmpd_configure($interface='') {
2831
	global $g;
2832
	if (config_path_enabled('system','developerspew')) {
2833
		$mt = microtime();
2834
		echo "services_snmpd_configure() being called $mt\n";
2835
	}
2836

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

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

    
2859
	if (config_path_enabled('snmpd')) {
2860

    
2861
		if (platform_booting()) {
2862
			echo gettext("Starting SNMP daemon... ");
2863
		}
2864

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

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

    
2877
		$snmpdcfg = config_get_path('snmpd');
2878
		$snmpdconf = <<<EOD
2879
location := "{$snmpdcfg['syslocation']}"
2880
contact := "{$snmpdcfg['syscontact']}"
2881
read := "{$snmpdcfg['rocommunity']}"
2882

    
2883
EOD;
2884

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

    
2891
EOD;
2892
		}
2893
*/
2894

    
2895

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

    
2903

    
2904
EOD;
2905
		}
2906

    
2907
		$sysDescr = "{$g['product_label']} " .
2908
				  config_get_path('system/hostname') . '.' .config_get_path('system/domain') .
2909
			" {$g['product_version_string']} " . php_uname("s") .
2910
			" " . php_uname("r") . " " . php_uname("m");
2911

    
2912
		$snmpdconf .= <<<EOD
2913
system := 1     # pfSense
2914
%snmpd
2915
sysDescr			= "{$sysDescr}"
2916
begemotSnmpdDebugDumpPdus       = 2
2917
begemotSnmpdDebugSyslogPri      = 7
2918
begemotSnmpdCommunityString.0.1 = $(read)
2919

    
2920
EOD;
2921

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

    
2927
EOD;
2928
		}
2929
*/
2930

    
2931

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

    
2938
EOD;
2939
		}
2940

    
2941

    
2942
		$snmpdconf .= <<<EOD
2943
begemotSnmpdCommunityDisable    = 1
2944

    
2945
EOD;
2946

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

    
2986
		$pollport = config_get_path('snmpd/pollport');
2987
		if (is_port($pollport)) {
2988
			foreach ($bind_to_ips as $bind_to_ip) {
2989
				$snmpdconf .= <<<EOD
2990
begemotSnmpdPortStatus.{$bind_to_ip}.{$pollport} = 1
2991

    
2992
EOD;
2993

    
2994
			}
2995
			foreach ($bind_to_ip6s as $bind_to_ip6) {
2996
				$bind_to_ip6 = ip6_to_asn1($bind_to_ip6);
2997
				$snmpdconf .= <<<EOD
2998
begemotSnmpdTransInetStatus.2.16.{$bind_to_ip6}{$pollport}.1 = 4
2999

    
3000
EOD;
3001

    
3002
			}
3003
		}
3004

    
3005
		$snmpdconf .= <<<EOD
3006
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
3007
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
3008

    
3009
# These are bsnmp macros not php vars.
3010
sysContact      = $(contact)
3011
sysLocation     = $(location)
3012
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
3013

    
3014
snmpEnableAuthenTraps = 2
3015

    
3016
EOD;
3017

    
3018
		if (config_path_enabled('snmpd/modules', 'mibii')) {
3019
			$snmpdconf .= <<<EOD
3020
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
3021

    
3022
EOD;
3023
		}
3024

    
3025
		if (config_path_enabled('snmpd/modules', 'netgraph')) {
3026
			$snmpdconf .= <<<EOD
3027
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
3028
%netgraph
3029
begemotNgControlNodeName = "snmpd"
3030

    
3031
EOD;
3032
		}
3033

    
3034
		if (config_path_enabled('snmpd/modules', 'pf')) {
3035
			$snmpdconf .= <<<EOD
3036
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
3037

    
3038
EOD;
3039
		}
3040

    
3041
		if (config_path_enabled('snmpd/modules', 'hostres')) {
3042
			$snmpdconf .= <<<EOD
3043
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
3044

    
3045
EOD;
3046
		}
3047

    
3048
		if (config_path_enabled('snmpd/modules', 'bridge')) {
3049
			$snmpdconf .= <<<EOD
3050
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
3051
# config must end with blank line
3052

    
3053
EOD;
3054
		}
3055
		if (config_path_enabled('snmpd/modules', 'ucd')) {
3056
			$snmpdconf .= <<<EOD
3057
begemotSnmpdModulePath."ucd"     = "/usr/local/lib/snmp_ucd.so"
3058

    
3059
EOD;
3060
		}
3061
		if (config_path_enabled('snmpd/modules', 'regex')) {
3062
				$snmpdconf .= <<<EOD
3063
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"
3064

    
3065
EOD;
3066
		}
3067

    
3068
		fwrite($fd, $snmpdconf);
3069
		fclose($fd);
3070
		unset($snmpdconf);
3071

    
3072
		/* run bsnmpd */
3073
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
3074
			" -p {$g['varrun_path']}/snmpd.pid");
3075

    
3076
		if (platform_booting()) {
3077
			echo gettext("done.") . "\n";
3078
		}
3079
	}
3080

    
3081
	return 0;
3082
}
3083

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

    
3091
	/* Dynamic DNS updating active? */
3092
	if (empty(config_get_path('dnsupdates/dnsupdate'))) {
3093
		return 0;
3094
	}
3095

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

    
3134
		/* determine interface name */
3135
		$if = get_failover_interface($dnsupdate['interface']);
3136

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

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

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

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

    
3203
		if (!$wanip && !$wanipv6) {
3204
			continue;
3205
		}
3206

    
3207
		$keyname = $dnsupdate['keyname'];
3208
		/* trailing dot */
3209
		if (substr($keyname, -1) != ".") {
3210
			$keyname .= ".";
3211
		}
3212

    
3213
		$hostname = $dnsupdate['host'];
3214
		/* trailing dot */
3215
		if (substr($hostname, -1) != ".") {
3216
			$hostname .= ".";
3217
		}
3218

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

    
3227
EOD;
3228
		@file_put_contents("{$g['varetc_path']}/nsupdatekey{$i}", $upkey);
3229

    
3230
		/* generate update instructions */
3231
		$upinst = "";
3232
		if (!empty($dnsupdate['server'])) {
3233
			$upinst .= "server {$dnsupdate['server']}\n";
3234
		}
3235

    
3236
		if (!empty($dnsupdate['zone'])) {
3237
			$upinst .= "zone {$dnsupdate['zone']}\n";
3238
		}
3239

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

    
3253
		// 25 Days
3254
		$maxCacheAgeSecs = 25 * 24 * 60 * 60;
3255
		$need_update = false;
3256

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

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

    
3298
		$upinst .= "\n";	/* mind that trailing newline! */
3299

    
3300
		if (!$need_update) {
3301
			continue;
3302
		}
3303

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

    
3309
		if (isset($dnsupdate['usetcp'])) {
3310
			$cmd .= " -v";
3311
		}
3312

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

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

    
3355
	if (!empty($notify_text)) {
3356
		notify_all_remote($notify_text);
3357
	}
3358

    
3359
	return 0;
3360
}
3361

    
3362
/* configure cron service */
3363
function configure_cron() {
3364
	global $g;
3365

    
3366
	$crontab_contents = "";
3367

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

    
3376
		$http_proxy = config_get_path('system/proxyurl');
3377
		$http_proxyport = config_get_path('system/proxyport');
3378
		if (!empty($http_proxy)) {
3379
			if (!empty($http_proxyport)) {
3380
				$http_proxy .= ':' . $http_proxyport;
3381
			}
3382
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
3383

    
3384
			$proxyuser = config_get_path('system/proxyuser');
3385
			$proxypass = config_get_path('system/proxypass');
3386
			if (!empty($proxyuser) && !empty($proxypass)) {
3387
				$crontab_contents .= "HTTP_PROXY_AUTH=basic:*:{$proxyuser}:{$proxypass}";
3388
			}
3389
		}
3390

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

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

    
3407
	/* please maintain the newline at the end of file */
3408
	file_put_contents("/etc/crontab", $crontab_contents);
3409
	unset($crontab_contents);
3410

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

    
3419
}
3420

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

    
3445
function upnp_start() {
3446
	if (empty(config_get_path('installedpackages/miniupnpd/config'))) {
3447
		return;
3448
	}
3449

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

    
3458
function install_cron_job($command, $active = false, $minute = "0", $hour = "*", $monthday = "*", $month = "*", $weekday = "*", $who = "root", $write_config = true) {
3459
	$is_installed = false;
3460
	$cron_changed = true;
3461
	$change_message = "";
3462

    
3463
	init_config_arr(['cron','item']);
3464

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

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

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

    
3517
?>
(47-47/61)