Project

General

Profile

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

    
28

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
494
	unlock($dhcpdconfigurelck);
495
}
496

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

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

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

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

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

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

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

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

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

    
621
	$dhcpdconf = <<<EOD
622

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

    
635
EOD;
636

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

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

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

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

    
660
EOD;
661

    
662
		}
663
		break;
664
	}
665

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

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

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

    
687
		interfaces_staticarp_configure($dhcpif);
688

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

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

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

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

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

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

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

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

    
776
		$dnscfg = "";
777

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
965
			$pdnscfg = "";
966

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1271
EOD;
1272

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

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

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

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

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

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

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

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

    
1316
				$smdnscfg = "";
1317

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1453
				$dhcpdconf .= "}\n";
1454

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

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

    
1484

    
1485
				$i++;
1486
			}
1487
		}
1488

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

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

    
1506
		$dhcpdconf .= dhcpdzones($ddns_zones);
1507
	}
1508

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

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

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

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

    
1532
	if (platform_booting()) {
1533
		print "done.\n";
1534
	}
1535

    
1536
	return 0;
1537
}
1538

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

    
1549
	return $dhcpdconf;
1550
}
1551

    
1552
function dhcpdzones($ddns_zones) {
1553
	$dhcpdconf = "";
1554

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

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

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

    
1614
	return $dhcpdconf;
1615
}
1616

    
1617
function services_dhcpdv6_configure($blacklist = array()) {
1618
	global $config, $g;
1619

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

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

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

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

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

    
1650

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

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

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

    
1670
	$dhcpdv6conf = <<<EOD
1671

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

    
1684
EOD;
1685

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

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

    
1694
	$dhcpdv6ifs = array();
1695

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

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

    
1701
		$ddns_zones = array();
1702

    
1703
		$ifcfgv6 = $config['interfaces'][$dhcpv6if];
1704

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

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

    
1731
		$dnscfgv6 = "";
1732

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

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

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

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

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

    
1785
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1786

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

    
1808
		$dhcpdv6conf .= " {\n";
1809

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

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

    
1821
		$dhcpdv6conf .= $dnscfgv6;
1822

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

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

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

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

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

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

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

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

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

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

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

    
1931
				$dhcpdv6conf .= "}\n";
1932
				$i++;
1933
			}
1934
		}
1935

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

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

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

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

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

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

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

    
1998
	return 0;
1999
}
2000

    
2001
function services_igmpproxy_configure($interface='') {
2002
	global $config, $g;
2003

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

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

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

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

    
2036
	$iflist = get_configured_interface_list();
2037

    
2038
	$igmpconf = <<<EOD
2039

    
2040
##------------------------------------------------------
2041
## Enable Quickleave mode (Sends Leave instantly)
2042
##------------------------------------------------------
2043
quickleave
2044

    
2045
EOD;
2046

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

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

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

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

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

    
2099
	log_error(gettext("Started IGMP Proxy service."));
2100

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

    
2105
	return true;
2106
}
2107

    
2108
function services_dhcrelay_configure() {
2109
	global $config, $g;
2110

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

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

    
2119
	init_config_arr(array('dhcrelay'));
2120
	$dhcrelaycfg = &$config['dhcrelay'];
2121

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

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

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

    
2152
	$iflist = get_configured_interface_list();
2153

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

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

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

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

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

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

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

    
2206
	$cmd = "/usr/local/sbin/dhcrelay";
2207

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

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

    
2222
	$cmd .= " " . implode(" ", $srvips);
2223
	mwexec($cmd);
2224
	unset($cmd);
2225

    
2226
	return 0;
2227
}
2228

    
2229
function services_dhcrelay6_configure() {
2230
	global $config, $g;
2231

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

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

    
2240
	init_config_arr(array('dhcrelay6'));
2241
	$dhcrelaycfg = &$config['dhcrelay6'];
2242

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

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

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

    
2273
	$iflist = get_configured_interface_list();
2274

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

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

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

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

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

    
2316
	return 0;
2317
}
2318

    
2319
function services_dyndns_configure_client($conf) {
2320

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

    
2325
	/* load up the dyndns.class */
2326
	require_once("dyndns.class");
2327

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

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

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

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

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

    
2412
	return 0;
2413
}
2414

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

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

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

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

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

    
2475
		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);
2476
		if ($matches[0]) {
2477
			$ip_address = $matches[0];
2478
		}
2479
	}
2480
	return $ip_address;
2481
}
2482

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

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

    
2494

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

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

    
2505
	if (isset($config['dnsmasq']['enable'])) {
2506

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

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

    
2518
		$args = "";
2519

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

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

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

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

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

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

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

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

    
2604
		/* avoid 127.0.0.1 dns loop,
2605
		 * see https://redmine.pfsense.org/issues/12902 */
2606
		$args .= ' --no-resolv';
2607
		foreach (get_dns_nameservers(false, true) as $dns) {
2608
			if ($dns != '127.0.0.1') {
2609
				$args .= ' --server=' . $dns;
2610
			}
2611
		}
2612

    
2613
		/* Allow DNS Rebind for forwarded domains */
2614
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2615
			if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2616
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2617
					$args .= ' --rebind-domain-ok=/' . $override['domain'] . '/ ';
2618
				}
2619
			}
2620
		}
2621

    
2622
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2623
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2624
		}
2625

    
2626
		if (isset($config['dnsmasq']['strict_order'])) {
2627
			$args .= " --strict-order ";
2628
		}
2629

    
2630
		if (isset($config['dnsmasq']['domain_needed'])) {
2631
			$args .= " --domain-needed ";
2632
		}
2633

    
2634
		if ($config['dnsmasq']['custom_options']) {
2635
			foreach (preg_split('/\s+/', base64_decode($config['dnsmasq']['custom_options'])) as $c) {
2636
				$args .= " " . escapeshellarg("--{$c}");
2637
				$p = explode('=', $c);
2638
				if (array_key_exists($p[0], $standard_args)) {
2639
					unset($standard_args[$p[0]]);
2640
				}
2641
			}
2642
		}
2643
		$args .= ' ' . implode(' ', array_values($standard_args));
2644

    
2645
		/* run dnsmasq. Use "-C /dev/null" since we use command line args only (Issue #6730) */
2646
		$cmd = "/usr/local/sbin/dnsmasq --all-servers -C /dev/null {$dns_rebind} {$args}";
2647
		//log_error("dnsmasq command: {$cmd}");
2648
		mwexec_bg($cmd);
2649
		unset($args);
2650

    
2651
		system_dhcpleases_configure();
2652

    
2653
		if (platform_booting()) {
2654
			echo gettext("done.") . "\n";
2655
		}
2656
	}
2657

    
2658
	if (!platform_booting() && $restart_dhcp) {
2659
		if (services_dhcpd_configure() != 0) {
2660
			$return = 1;
2661
		}
2662
	}
2663

    
2664
	return $return;
2665
}
2666

    
2667
function services_unbound_configure($restart_dhcp = true, $interface = '') {
2668
	global $config, $g;
2669
	$return = 0;
2670

    
2671
	if (isset($config['system']['developerspew'])) {
2672
		$mt = microtime();
2673
		echo "services_unbound_configure() being called $mt\n";
2674
	}
2675

    
2676
	if (!empty($interface) && isset($config['unbound']['enable']) &&
2677
	    !in_array($interface, explode(',', $config['unbound']['active_interface'])) &&
2678
	    !in_array($interface, explode(',', $config['unbound']['outgoing_interface']))) {
2679
		return $return;
2680
	}
2681

    
2682
	if (isset($config['unbound']['enable'])) {
2683
		require_once('/etc/inc/unbound.inc');
2684

    
2685
		/* Stop Unbound using TERM */
2686
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2687
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
2688
		}
2689

    
2690
		/* If unbound is still running, wait up to 30 seconds for it to terminate. */
2691
		for ($i=1; $i <= 30; $i++) {
2692
			if (is_process_running('unbound')) {
2693
				sleep(1);
2694
			}
2695
		}
2696

    
2697
		$python_mode = false;
2698
		if (isset($config['unbound']['python']) && !empty($config['unbound']['python_script'])) {
2699
			$python_mode = true;
2700
		}
2701

    
2702
		/* Include any additional functions as defined by python script include file */
2703
		if (file_exists("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc")) {
2704
			exec("/usr/local/bin/php -l " . escapeshellarg("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc")
2705
				. " 2>&1", $py_output, $py_retval);
2706
			if ($py_retval == 0) {
2707
				require_once("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc");
2708
			}
2709
		}
2710

    
2711
		/* DNS Resolver python integration */
2712
		if ($python_mode) {
2713
			if (!is_dir("{$g['unbound_chroot_path']}/dev")) {
2714
				safe_mkdir("{$g['unbound_chroot_path']}/dev");
2715
			}
2716
			$status = "/sbin/mount | /usr/bin/grep " .  escapeshellarg("{$g['unbound_chroot_path']}/dev");
2717
			if (!trim($status)) {
2718
				exec("/sbin/mount -t devfs devfs " . escapeshellarg("{$g['unbound_chroot_path']}/dev"));
2719
			}
2720
		} else {
2721
			if (is_dir("{$g['unbound_chroot_path']}/dev")) {
2722
				exec("/sbin/umount -f " . escapeshellarg("{$g['unbound_chroot_path']}/dev"));
2723
			}
2724
		}
2725
		$base_folder = '/usr/local';
2726
		foreach (array('/bin', '/lib') as $dir) {
2727
			$validate = exec("/sbin/mount | /usr/bin/grep " . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir} (nullfs") . " 2>&1");
2728
			if ($python_mode) {
2729

    
2730
				// Add DNS Resolver python integration
2731
				if (empty($validate)) {
2732
					if (!is_dir("{$g['unbound_chroot_path']}{$base_folder}{$dir}")) {
2733
						safe_mkdir("{$g['unbound_chroot_path']}{$base_folder}{$dir}");
2734
					}
2735
					$output = $retval = '';
2736
					exec("/sbin/mount_nullfs -o ro " . escapeshellarg("/usr/local{$dir}") . ' '
2737
					    . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir}") . " 2>&1", $output, $retval);
2738

    
2739
					// Disable Unbound python on mount failure
2740
					if ($retval != 0) {
2741
						$config['unbound']['python'] = '';
2742
						$log_msg = "[Unbound-pymod]: Disabling Unbound python due to failed mount";
2743
						write_config($log_msg);
2744
						log_error($log_msg);
2745
					}
2746
				}
2747
			}
2748

    
2749
			// Remove DNS Resolver python integration
2750
			elseif (!empty($validate)) {
2751
				exec("/sbin/umount -t nullfs " . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir}") . " 2>&1", $output, $retval);
2752
				if ($retval == 0) {
2753
					foreach (array( "/usr/local{$dir}", '/usr/local', '/usr') as $folder) {
2754
						if (!empty($g['unbound_chroot_path']) && $g['unbound_chroot_path'] != '/' && is_dir("{$g['unbound_chroot_path']}{$folder}")) {
2755
							@rmdir(escapeshellarg("{$g['unbound_chroot_path']}{$folder}"));
2756
						}
2757

    
2758
						// Delete remaining subfolders on next loop
2759
						if ($dir == '/bin') {
2760
							break;
2761
						}
2762
					}
2763
				}
2764
				else {
2765
					log_error("[Unbound-pymod]: Failed to unmount!");
2766
				}
2767
			}
2768
		}
2769

    
2770
		if (platform_booting()) {
2771
			echo gettext("Starting DNS Resolver...");
2772
		} else {
2773
			sleep(1);
2774
		}
2775

    
2776
		/* generate hosts file */
2777
		if (system_hosts_generate() != 0) {
2778
			$return = 1;
2779
		}
2780

    
2781
		/* Check here for dhcp6 complete - wait upto 10 seconds */
2782
		if($config['interfaces']["wan"]['ipaddrv6'] == 'dhcp6') {
2783
			$wanif = get_real_interface("wan", "inet6");
2784
			if (platform_booting()) {
2785
				for ($i=1; $i <= 10; $i++) {
2786
					if (!file_exists("/tmp/{$wanif}_dhcp6_complete")) {
2787
						log_error(gettext("Unbound start waiting on dhcp6c."));
2788
						sleep(1);
2789
					} else {
2790
						unlink_if_exists("/tmp/{$wanif}_dhcp6_complete");
2791
						log_error(gettext("dhcp6 init complete. Continuing"));
2792
						break;
2793
					}
2794
				}
2795
			}
2796
		}
2797

    
2798
		sync_unbound_service();
2799
		if (platform_booting()) {
2800
			log_error(gettext("sync unbound done."));
2801
			echo gettext("done.") . "\n";
2802
		}
2803

    
2804
		system_dhcpleases_configure();
2805
	} else {
2806
		/* kill Unbound since it should not be enabled */
2807
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2808
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "KILL");
2809
		}
2810
	}
2811

    
2812
	if (!platform_booting() && $restart_dhcp) {
2813
		if (services_dhcpd_configure() != 0) {
2814
			$return = 1;
2815
		}
2816
	}
2817

    
2818
	return $return;
2819
}
2820

    
2821
function services_snmpd_configure($interface='') {
2822
	global $config, $g;
2823
	if (isset($config['system']['developerspew'])) {
2824
		$mt = microtime();
2825
		echo "services_snmpd_configure() being called $mt\n";
2826
	}
2827

    
2828
	if (!empty($interface) &&
2829
	    !empty($config['snmpd']['bindip']) &&
2830
	    isset($config['snmpd']['enable'])) {
2831
		foreach (explode(",", $config['snmpd']['bindip']) as $bind_to_ip) {
2832
			if ($bind_to_ip == $interface) {
2833
				$interface_restart = true;
2834
				break;
2835
			}
2836
		}
2837
		if (!$interface_restart) {
2838
			return 0;
2839
		}
2840
	}
2841

    
2842
	/* kill any running snmpd */
2843
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
2844
	sleep(2);
2845
	if (is_process_running("bsnmpd")) {
2846
		mwexec("/usr/bin/killall bsnmpd", true);
2847
	}
2848

    
2849
	if (isset($config['snmpd']['enable'])) {
2850

    
2851
		if (platform_booting()) {
2852
			echo gettext("Starting SNMP daemon... ");
2853
		}
2854

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

    
2860
		/* generate snmpd.conf */
2861
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
2862
		if (!$fd) {
2863
			printf(gettext("Error: cannot open snmpd.conf in services_snmpd_configure().%s"), "\n");
2864
			return 1;
2865
		}
2866

    
2867

    
2868
		$snmpdconf = <<<EOD
2869
location := "{$config['snmpd']['syslocation']}"
2870
contact := "{$config['snmpd']['syscontact']}"
2871
read := "{$config['snmpd']['rocommunity']}"
2872

    
2873
EOD;
2874

    
2875
/* No docs on what write strings do there so disable for now.
2876
		if (isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])) {
2877
			$snmpdconf .= <<<EOD
2878
# write string
2879
write := "{$config['snmpd']['rwcommunity']}"
2880

    
2881
EOD;
2882
		}
2883
*/
2884

    
2885

    
2886
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2887
			$snmpdconf .= <<<EOD
2888
# SNMP Trap support.
2889
traphost := {$config['snmpd']['trapserver']}
2890
trapport := {$config['snmpd']['trapserverport']}
2891
trap := "{$config['snmpd']['trapstring']}"
2892

    
2893

    
2894
EOD;
2895
		}
2896

    
2897
		$sysDescr = "{$g['product_label']} {$config['system']['hostname']}.{$config['system']['domain']}" .
2898
			" {$g['product_version_string']} " . php_uname("s") .
2899
			" " . php_uname("r") . " " . php_uname("m");
2900

    
2901
		$snmpdconf .= <<<EOD
2902
system := 1     # pfSense
2903
%snmpd
2904
sysDescr			= "{$sysDescr}"
2905
begemotSnmpdDebugDumpPdus       = 2
2906
begemotSnmpdDebugSyslogPri      = 7
2907
begemotSnmpdCommunityString.0.1 = $(read)
2908

    
2909
EOD;
2910

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

    
2916
EOD;
2917
		}
2918
*/
2919

    
2920

    
2921
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2922
			$snmpdconf .= <<<EOD
2923
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
2924
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
2925
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
2926

    
2927
EOD;
2928
		}
2929

    
2930

    
2931
		$snmpdconf .= <<<EOD
2932
begemotSnmpdCommunityDisable    = 1
2933

    
2934
EOD;
2935

    
2936
		$bind_to_ips = array();
2937
		$bind_to_ip6s = array();
2938
		if (isset($config['snmpd']['bindip'])) {
2939
			if (!isset($config['snmpd']['ipprotocol']) ||
2940
			    (isset($config['snmpd']['ipprotocol']) &&
2941
			    strstr($config['snmpd']['ipprotocol'], "4"))) {
2942
				$inet4 = true;
2943
			}
2944
			if (isset($config['snmpd']['ipprotocol']) &&
2945
			    strstr($config['snmpd']['ipprotocol'], "6")) {
2946
				$inet6 = true;
2947
			}
2948
			foreach (explode(",", $config['snmpd']['bindip']) as $bind_to_ip) {
2949
				if (is_ipaddr($bind_to_ip)) {
2950
					$bind_to_ips[] = $bind_to_ip;
2951
				} else {
2952
					$if = get_real_interface($bind_to_ip);
2953
					if (does_interface_exist($if)) {
2954
						if ($inet4) {
2955
							$bindip = get_interface_ip($bind_to_ip);
2956
							if (is_ipaddrv4($bindip)) {
2957
								$bind_to_ips[] = $bindip;
2958
							}
2959
						}
2960
						if ($inet6) {
2961
							$bindip6 = get_interface_ipv6($bind_to_ip);
2962
							if (is_ipaddrv6($bindip6)) {
2963
								$bind_to_ip6s[] = $bindip6;
2964
							}
2965
						}
2966
					}
2967
				}
2968
			}
2969
		}
2970
		if (!count($bind_to_ips) && $inet4) {
2971
			$bind_to_ips = array("0.0.0.0");
2972
		}
2973
		if (!count($bind_to_ip6s) && $inet6) {
2974
			$bind_to_ip6s = array("::");
2975
		}
2976

    
2977
		if (is_port($config['snmpd']['pollport'])) {
2978
			foreach ($bind_to_ips as $bind_to_ip) {
2979
				$snmpdconf .= <<<EOD
2980
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
2981

    
2982
EOD;
2983

    
2984
			}
2985
			foreach ($bind_to_ip6s as $bind_to_ip6) {
2986
				$bind_to_ip6 = ip6_to_asn1($bind_to_ip6);
2987
				$snmpdconf .= <<<EOD
2988
begemotSnmpdTransInetStatus.2.16.{$bind_to_ip6}{$config['snmpd']['pollport']}.1 = 4
2989

    
2990
EOD;
2991

    
2992
			}
2993
		}
2994

    
2995
		$snmpdconf .= <<<EOD
2996
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
2997
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
2998

    
2999
# These are bsnmp macros not php vars.
3000
sysContact      = $(contact)
3001
sysLocation     = $(location)
3002
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
3003

    
3004
snmpEnableAuthenTraps = 2
3005

    
3006
EOD;
3007

    
3008
		if (is_array($config['snmpd']['modules'])) {
3009
			if (isset($config['snmpd']['modules']['mibii'])) {
3010
			$snmpdconf .= <<<EOD
3011
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
3012

    
3013
EOD;
3014
			}
3015

    
3016
			if (isset($config['snmpd']['modules']['netgraph'])) {
3017
				$snmpdconf .= <<<EOD
3018
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
3019
%netgraph
3020
begemotNgControlNodeName = "snmpd"
3021

    
3022
EOD;
3023
			}
3024

    
3025
			if (isset($config['snmpd']['modules']['pf'])) {
3026
				$snmpdconf .= <<<EOD
3027
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
3028

    
3029
EOD;
3030
			}
3031

    
3032
			if (isset($config['snmpd']['modules']['hostres'])) {
3033
				$snmpdconf .= <<<EOD
3034
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
3035

    
3036
EOD;
3037
			}
3038

    
3039
			if (isset($config['snmpd']['modules']['bridge'])) {
3040
				$snmpdconf .= <<<EOD
3041
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
3042
# config must end with blank line
3043

    
3044
EOD;
3045
			}
3046
			if (isset($config['snmpd']['modules']['ucd'])) {
3047
				$snmpdconf .= <<<EOD
3048
begemotSnmpdModulePath."ucd"     = "/usr/local/lib/snmp_ucd.so"
3049

    
3050
EOD;
3051
			}
3052
			if (isset($config['snmpd']['modules']['regex'])) {
3053
				$snmpdconf .= <<<EOD
3054
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"
3055

    
3056
EOD;
3057
			}
3058
		}
3059

    
3060
		fwrite($fd, $snmpdconf);
3061
		fclose($fd);
3062
		unset($snmpdconf);
3063

    
3064
		/* run bsnmpd */
3065
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
3066
			" -p {$g['varrun_path']}/snmpd.pid");
3067

    
3068
		if (platform_booting()) {
3069
			echo gettext("done.") . "\n";
3070
		}
3071
	}
3072

    
3073
	return 0;
3074
}
3075

    
3076
function services_dnsupdate_process($int = "", $updatehost = "", $forced = false) {
3077
	global $config, $g;
3078
	if (isset($config['system']['developerspew'])) {
3079
		$mt = microtime();
3080
		echo "services_dnsupdate_process() being called $mt\n";
3081
	}
3082

    
3083
	/* Dynamic DNS updating active? */
3084
	if (!is_array($config['dnsupdates']['dnsupdate'])) {
3085
		return 0;
3086
	}
3087

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

    
3124
		/* determine interface name */
3125
		$if = get_failover_interface($dnsupdate['interface']);
3126

    
3127
		/* Determine address to update and default binding address */
3128
		if (isset($dnsupdate['usepublicip'])) {
3129
			$wanip = dyndnsCheckIP($if);
3130
			if (is_private_ip($wanip)) {
3131
				log_error(sprintf(gettext(
3132
				    "phpDynDNS: Not updating %s A record because the public IP address cannot be determined."),
3133
				    $dnsupdate['host']));
3134
				continue;
3135
			}
3136
			$bindipv4 = get_interface_ip($if);
3137
		} else {
3138
			$wanip = get_interface_ip($if);
3139
			$bindipv4 = $wanip;
3140
		}
3141
		if (is_stf_interface($dnsupdate['interface'])) { 
3142
			$wanipv6 = get_interface_ipv6($dnsupdate['interface'] . '_stf');
3143
		} else {
3144
			$wanipv6 = get_interface_ipv6($if);
3145
		}
3146
		$bindipv6 = $wanipv6;
3147

    
3148
		/* Handle non-default interface bindings */
3149
		if ($dnsupdate['updatesource'] == "none") {
3150
			/* When empty, the directive will be omitted. */
3151
			$bindipv4 = "";
3152
			$bindipv6 = "";
3153
		} elseif (!empty($dnsupdate['updatesource'])) {
3154
			/* Find the alternate binding address */
3155
			$bindipv4 = get_interface_ip($dnsupdate['updatesource']);
3156
			if (is_stf_interface($dnsupdate['interface'])) { 
3157
				$bindipv6 = get_interface_ipv6($dnsupdate['updatesource'] . '_stf');
3158
			} else {
3159
				$bindipv6 = get_interface_ipv6($dnsupdate['updatesource']);
3160
			}
3161
		}
3162

    
3163
		/* Handle IPv4/IPv6 selection for the update source interface/VIP */
3164
		switch ($dnsupdate['updatesourcefamily']) {
3165
			case "inet":
3166
				$bindip = $bindipv4;
3167
				break;
3168
			case "inet6":
3169
				$bindip = $bindipv6;
3170
				break;
3171
			case "":
3172
			default:
3173
				/* Try IPv4 first, if that is empty, try IPv6. */
3174
				/* Only specify the address if it's present, otherwise omit. */
3175
				if (!empty($bindipv4)) {
3176
					$bindip = $bindipv4;
3177
				} elseif (!empty($bindipv6)) {
3178
					$bindip = $bindipv6;
3179
				}
3180
				break;
3181
		}
3182

    
3183
		$cacheFile = $g['conf_path'] .
3184
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
3185
		    escapeshellarg($dnsupdate['host']) .
3186
		    "_{$dnsupdate['server']}.cache";
3187
		$cacheFilev6 = $g['conf_path'] .
3188
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
3189
		    escapeshellarg($dnsupdate['host']) .
3190
		    "_{$dnsupdate['server']}_v6.cache";
3191
		$currentTime = time();
3192

    
3193
		if (!$wanip && !$wanipv6) {
3194
			continue;
3195
		}
3196

    
3197
		$keyname = $dnsupdate['keyname'];
3198
		/* trailing dot */
3199
		if (substr($keyname, -1) != ".") {
3200
			$keyname .= ".";
3201
		}
3202

    
3203
		$hostname = $dnsupdate['host'];
3204
		/* trailing dot */
3205
		if (substr($hostname, -1) != ".") {
3206
			$hostname .= ".";
3207
		}
3208

    
3209
		/* write key file */
3210
		$algorithm = empty($dnsupdate['keyalgorithm']) ? 'hmac-md5' : $dnsupdate['keyalgorithm'];
3211
		$upkey = <<<EOD
3212
key "{$keyname}" {
3213
	algorithm {$algorithm};
3214
	secret "{$dnsupdate['keydata']}";
3215
};
3216

    
3217
EOD;
3218
		@file_put_contents("{$g['varetc_path']}/nsupdatekey{$i}", $upkey);
3219

    
3220
		/* generate update instructions */
3221
		$upinst = "";
3222
		if (!empty($dnsupdate['server'])) {
3223
			$upinst .= "server {$dnsupdate['server']}\n";
3224
		}
3225

    
3226
		if (!empty($dnsupdate['zone'])) {
3227
			$upinst .= "zone {$dnsupdate['zone']}\n";
3228
		}
3229

    
3230
		$cachedipv4 = '';
3231
		$cacheTimev4 = 0;
3232
		if (file_exists($cacheFile)) {
3233
			list($cachedipv4, $cacheTimev4) = explode("|",
3234
			    file_get_contents($cacheFile));
3235
		}
3236
		$cachedipv6 = '';
3237
		$cacheTimev6 = 0;
3238
		if (file_exists($cacheFilev6)) {
3239
			list($cachedipv6, $cacheTimev6) = explode("|",
3240
			    file_get_contents($cacheFilev6));
3241
		}
3242

    
3243
		// 25 Days
3244
		$maxCacheAgeSecs = 25 * 24 * 60 * 60;
3245
		$need_update = false;
3246

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

    
3269
		/* Update IPv6 if we have it. */
3270
		if (is_ipaddrv6($wanipv6) && $dnsupdate['recordtype'] != "A") {
3271
			if (($wanipv6 != $cachedipv6) || $forced ||
3272
			    (($currentTime - $cacheTimev6) > $maxCacheAgeSecs)) {
3273
				$upinst .= "update delete " .
3274
				    "{$dnsupdate['host']}. AAAA\n";
3275
				$upinst .= "update add {$dnsupdate['host']}. " .
3276
				    "{$dnsupdate['ttl']} AAAA {$wanipv6}\n";
3277
				$need_update = true;
3278
			} else {
3279
				log_error(sprintf(gettext(
3280
				    "phpDynDNS: Not updating %s AAAA record because the IPv6 address has not changed."),
3281
				    $dnsupdate['host']));
3282
			}
3283
		} else {
3284
			@unlink($cacheFilev6);
3285
			unset($cacheFilev6);
3286
		}
3287

    
3288
		$upinst .= "\n";	/* mind that trailing newline! */
3289

    
3290
		if (!$need_update) {
3291
			continue;
3292
		}
3293

    
3294
		@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}", $upinst);
3295
		unset($upinst);
3296
		/* invoke nsupdate */
3297
		$cmd = "/usr/local/bin/nsupdate -k {$g['varetc_path']}/nsupdatekey{$i}";
3298

    
3299
		if (isset($dnsupdate['usetcp'])) {
3300
			$cmd .= " -v";
3301
		}
3302

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

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

    
3345
	if (!empty($notify_text)) {
3346
		notify_all_remote($notify_text);
3347
	}
3348

    
3349
	return 0;
3350
}
3351

    
3352
/* configure cron service */
3353
function configure_cron() {
3354
	global $g, $config;
3355

    
3356
	/* preserve existing crontab entries */
3357
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
3358

    
3359
	for ($i = 0; $i < count($crontab_contents); $i++) {
3360
		$cron_item = &$crontab_contents[$i];
3361
		if (strpos($cron_item, "# pfSense specific crontab entries") !== false) {
3362
			array_splice($crontab_contents, $i - 1);
3363
			break;
3364
		}
3365
	}
3366
	$crontab_contents = implode("\n", $crontab_contents) . "\n";
3367

    
3368

    
3369
	if (is_array($config['cron']['item'])) {
3370
		$crontab_contents .= "#\n";
3371
		$crontab_contents .= "# pfSense specific crontab entries\n";
3372
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
3373
		$crontab_contents .= "#\n";
3374

    
3375
		if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) {
3376
			$http_proxy = $config['system']['proxyurl'];
3377
			if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) {
3378
				$http_proxy .= ':' . $config['system']['proxyport'];
3379
			}
3380
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
3381

    
3382
			if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
3383
				$crontab_contents .= "HTTP_PROXY_AUTH=basic:*:{$config['system']['proxyuser']}:{$config['system']['proxypass']}";
3384
			}
3385
		}
3386

    
3387
		foreach ($config['cron']['item'] as $item) {
3388
			$crontab_contents .= "\n{$item['minute']}\t";
3389
			$crontab_contents .= "{$item['hour']}\t";
3390
			$crontab_contents .= "{$item['mday']}\t";
3391
			$crontab_contents .= "{$item['month']}\t";
3392
			$crontab_contents .= "{$item['wday']}\t";
3393
			$crontab_contents .= "{$item['who']}\t";
3394
			$crontab_contents .= "{$item['command']}";
3395
		}
3396

    
3397
		$crontab_contents .= "\n#\n";
3398
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
3399
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
3400
		$crontab_contents .= "#\n\n";
3401
	}
3402

    
3403
	/* please maintain the newline at the end of file */
3404
	file_put_contents("/etc/crontab", $crontab_contents);
3405
	unset($crontab_contents);
3406

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

    
3415
}
3416

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

    
3441
function upnp_start() {
3442
	global $config;
3443

    
3444
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
3445
		return;
3446
	}
3447

    
3448
	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
3449
		echo gettext("Starting UPnP service... ");
3450
		require_once('/usr/local/pkg/miniupnpd.inc');
3451
		sync_package_miniupnpd();
3452
		echo "done.\n";
3453
	}
3454
}
3455

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

    
3459
	$is_installed = false;
3460
	$cron_changed = true;
3461
	$change_message = "";
3462

    
3463
	if (!is_array($config['cron'])) {
3464
		$config['cron'] = array();
3465
	}
3466
	if (!is_array($config['cron']['item'])) {
3467
		$config['cron']['item'] = array();
3468
	}
3469

    
3470
	$x = 0;
3471
	foreach ($config['cron']['item'] as $item) {
3472
		if (strstr($item['command'], $command)) {
3473
			$is_installed = true;
3474
			break;
3475
		}
3476
		$x++;
3477
	}
3478

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

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

    
3520
?>
(46-46/61)