Project

General

Profile

Download (107 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 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,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
		if (is_array($dhcpifconf['numberoptions']) && is_array($dhcpifconf['numberoptions']['item'])) {
547
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
548
				if (!empty($item['type'])) {
549
					$itemtype = $item['type'];
550
				} else {
551
					$itemtype = "text";
552
				}
553
				$custoptions .= "option custom-{$dhcpif}-{$itemidx} code {$item['number']} = {$itemtype};\n";
554
			}
555
		}
556
		if (is_array($dhcpifconf['pool'])) {
557
			foreach ($dhcpifconf['pool'] as $poolidx => $poolconf) {
558
				if (is_array($poolconf['numberoptions']) && is_array($poolconf['numberoptions']['item'])) {
559
					foreach ($poolconf['numberoptions']['item'] as $itemidx => $item) {
560
						if (!empty($item['type'])) {
561
							$itemtype = $item['type'];
562
						} else {
563
							$itemtype = "text";
564
						}
565
						$custoptions .= "option custom-{$dhcpif}-{$poolidx}-{$itemidx} code {$item['number']} = {$itemtype};\n";
566
					}
567
				}
568
			}
569
		}
570
		if (is_array($dhcpifconf['staticmap'])) {
571
			$i = 0;
572
			foreach ($dhcpifconf['staticmap'] as $sm) {
573
				if (is_array($sm['numberoptions']) && is_array($sm['numberoptions']['item'])) {
574
					foreach ($sm['numberoptions']['item'] as $itemidx => $item) {
575
						if (!empty($item['type'])) {
576
							$itemtype = $item['type'];
577
						} else {
578
							$itemtype = "text";
579
						}
580
						$custoptions .= "option custom-s_{$dhcpif}_{$i}-{$itemidx} code {$item['number']} = {$itemtype};\n";
581
					}
582
				}
583
				$i++;
584
			}
585
		}
586
	}
587

    
588
	$dhcpdconf = <<<EOD
589

    
590
option domain-name "{$syscfg['domain']}";
591
option ldap-server code 95 = text;
592
option domain-search-list code 119 = text;
593
option arch code 93 = unsigned integer 16; # RFC4578
594
{$custoptions}
595
default-lease-time 7200;
596
max-lease-time 86400;
597
log-facility local7;
598
one-lease-per-client true;
599
deny duplicates;
600
update-conflict-detection false;
601

    
602
EOD;
603

    
604
	/* take these settings from the first DHCP configured interface,
605
	 * see https://redmine.pfsense.org/issues/10270 
606
	 * TODO: Global Settings tab, see https://redmine.pfsense.org/issues/5080 */
607
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
608
		if (!isset($dhcpifconf['disableauthoritative'])) {
609
			$dhcpdconf .= "authoritative;\n";
610
		}
611

    
612
		if (isset($dhcpifconf['alwaysbroadcast'])) {
613
			$dhcpdconf .= "always-broadcast on\n";
614
		}
615

    
616
		// OMAPI Settings
617
		if (isset($dhcpifconf['omapi_port']) && is_numeric($dhcpifconf['omapi_port'])) {
618
			$dhcpdconf .= <<<EOD
619

    
620
key omapi_key {
621
  algorithm {$dhcpifconf['omapi_key_algorithm']};
622
  secret "{$dhcpifconf['omapi_key']}";
623
};
624
omapi-port {$dhcpifconf['omapi_port']};
625
omapi-key omapi_key;
626

    
627
EOD;
628

    
629
		}
630
		break;
631
	}
632

    
633
	$dhcpdifs = array();
634
	$enable_add_routers = false;
635
	$gateways_arr = return_gateways_array();
636
	/* only add a routers line if the system has any IPv4 gateway at all */
637
	/* a static route has a gateway, manually overriding this field always works */
638
	foreach ($gateways_arr as $gwitem) {
639
		if ($gwitem['ipprotocol'] == "inet") {
640
			$enable_add_routers = true;
641
			break;
642
		}
643
	}
644

    
645
	/*    loop through and determine if we need to setup
646
	 *    failover peer "bleh" entries
647
	 */
648
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
649

    
650
		if (!isset($config['interfaces'][$dhcpif]['enable'])) {
651
			continue;
652
		}
653

    
654
		interfaces_staticarp_configure($dhcpif);
655

    
656
		if (!isset($dhcpifconf['enable'])) {
657
			continue;
658
		}
659

    
660
		if ($dhcpifconf['failover_peerip'] <> "") {
661
			$intip = get_interface_ip($dhcpif);
662
			/*
663
			 *    yep, failover peer is defined.
664
			 *    does it match up to a defined vip?
665
			 */
666
			$skew = 110;
667
			if (is_array($config['virtualip']['vip'])) {
668
				foreach ($config['virtualip']['vip'] as $vipent) {
669
					if ($vipent['mode'] != 'carp') {
670
						continue;
671
					}
672
					if ($vipent['interface'] == $dhcpif) {
673
						$carp_nw = gen_subnet($config['interfaces'][$dhcpif]['ipaddr'],
674
						    $config['interfaces'][$dhcpif]['subnet']);
675
						$carp_nw .= "/{$config['interfaces'][$dhcpif]['subnet']}";
676
						if (ip_in_subnet($dhcpifconf['failover_peerip'], $carp_nw)) {
677
							/* this is the interface! */
678
							if (is_numeric($vipent['advskew']) && (intval($vipent['advskew']) < 20)) {
679
								$skew = 0;
680
								break;
681
							}
682
						}
683
					}
684
				}
685
			} else {
686
				log_error(gettext("Warning!  DHCP Failover setup and no CARP virtual IPs defined!"));
687
			}
688
			if ($skew > 10) {
689
				$type = "secondary";
690
				$my_port = "520";
691
				$peer_port = "519";
692
				$dhcpdconf_pri = '';
693
			} else {
694
				$my_port = "519";
695
				$peer_port = "520";
696
				$type = "primary";
697
				$dhcpdconf_pri = "split 128;\n";
698
				$dhcpdconf_pri .= "  mclt 600;\n";
699
			}
700

    
701
			if (is_ipaddrv4($intip)) {
702
				$dhcpdconf .= <<<EOPP
703
failover peer "dhcp_{$dhcpif}" {
704
  {$type};
705
  address {$intip};
706
  port {$my_port};
707
  peer address {$dhcpifconf['failover_peerip']};
708
  peer port {$peer_port};
709
  max-response-delay 10;
710
  max-unacked-updates 10;
711
  {$dhcpdconf_pri}
712
  load balance max seconds 3;
713
}
714
\n
715
EOPP;
716
			}
717
		}
718
	}
719

    
720
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
721

    
722
		$newzone = array();
723
		$ifcfg = $config['interfaces'][$dhcpif];
724

    
725
		if (!isset($dhcpifconf['enable']) || !isset($Iflist[$dhcpif])) {
726
			continue;
727
		}
728
		$ifcfgip = get_interface_ip($dhcpif);
729
		$ifcfgsn = get_interface_subnet($dhcpif);
730
		$subnet = gen_subnet($ifcfgip, $ifcfgsn);
731
		$subnetmask = gen_subnet_mask($ifcfgsn);
732

    
733
		if (!is_ipaddr($subnet)) {
734
			continue;
735
		}
736

    
737
		$all_pools = array();
738
		$all_pools[] = $dhcpifconf;
739
		if (is_array($dhcpifconf['pool'])) {
740
			$all_pools = array_merge($all_pools, $dhcpifconf['pool']);
741
		}
742

    
743
		$dnscfg = "";
744

    
745
		if ($dhcpifconf['domain']) {
746
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
747
		}
748

    
749
		if ($dhcpifconf['domainsearchlist'] <> "") {
750
			$dnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpifconf['domainsearchlist'])) . "\";\n";
751
		}
752

    
753
		if (isset($dhcpifconf['ddnsupdate'])) {
754
			$need_ddns_updates = true;
755
			$newzone = array();
756
			if ($dhcpifconf['ddnsdomain'] <> "") {
757
				$newzone['domain-name'] = $dhcpifconf['ddnsdomain'];
758
				$dnscfg .= "	ddns-domainname \"{$dhcpifconf['ddnsdomain']}\";\n";
759
			} else {
760
				$newzone['domain-name'] = $config['system']['domain'];
761
			}
762

    
763
			if (empty($dhcpifconf['ddnsclientupdates'])) {
764
				$ddnsclientupdates = 'allow';
765
			} else {
766
				$ddnsclientupdates = $dhcpifconf['ddnsclientupdates'];
767
			}
768

    
769
			$dnscfg .= "	{$ddnsclientupdates} client-updates;\n";
770

    
771
			$revsubnet = array_reverse(explode('.',$subnet));
772

    
773
			$subnet_mask_bits = 32 - $ifcfgsn;
774
			$start_octet = $subnet_mask_bits >> 3;
775
			$octet_mask_bits = $subnet_mask_bits & ($subnet_mask_bits % 8);
776
			if ($octet_mask_bits) {
777
			    $octet_mask = (1 << $octet_mask_bits) - 1;
778
			    $octet_start = $revsubnet[$start_octet] & ~$octet_mask;
779
			    $revsubnet[$start_octet] = $octet_start . "-" . ($octet_start + $octet_mask);
780
			}
781

    
782
			$ptr_domain = '';
783
			for ($octet = 0; $octet <= 3; $octet++) {
784
				if ($octet < $start_octet) {
785
					continue;
786
				}
787
				$ptr_domain .= ((empty($ptr_domain) && $ptr_domain !== "0") ? '' : '.');
788
				$ptr_domain .= $revsubnet[$octet];
789
			}
790
			$ptr_domain .= ".in-addr.arpa";
791
			$newzone['ptr-domain'] = $ptr_domain;
792
			unset($ptr_domain, $revsubnet, $start_octet);
793
		}
794

    
795
		if (is_array($dhcpifconf['dnsserver']) && ($dhcpifconf['dnsserver'][0])) {
796
			$dnscfg .= "	option domain-name-servers " . join(",", $dhcpifconf['dnsserver']) . ";";
797
			if ($newzone['domain-name']) {
798
				$newzone['dns-servers'] = $dhcpifconf['dnsserver'];
799
			}
800
		} else if (isset($config['dnsmasq']['enable'])) {
801
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
802
			if ($newzone['domain-name'] && is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
803
				$newzone['dns-servers'] = $syscfg['dnsserver'];
804
			}
805
		} else if (isset($config['unbound']['enable'])) {
806
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
807
		} else if (!empty($dns_arrv4)) {
808
			$dnscfg .= "	option domain-name-servers " . join(",", $dns_arrv4) . ";";
809
			if ($newzone['domain-name']) {
810
				$newzone['dns-servers'] = $dns_arrv4;
811
			}
812
		}
813

    
814
		/* Create classes - These all contain comma separated lists. Join them into one
815
		   big comma separated string then split them all up. */
816
		$all_mac_strings = array();
817
		if (is_array($dhcpifconf['pool'])) {
818
			foreach ($all_pools as $poolconf) {
819
				$all_mac_strings[] = $poolconf['mac_allow'];
820
				$all_mac_strings[] = $poolconf['mac_deny'];
821
			}
822
		}
823
		$all_mac_strings[] = $dhcpifconf['mac_allow'];
824
		$all_mac_strings[] = $dhcpifconf['mac_deny'];
825
		if (!empty($all_mac_strings)) {
826
			$all_mac_list = array_unique(explode(',', implode(',', $all_mac_strings)));
827
			foreach ($all_mac_list as $mac) {
828
				if (empty($mac)) {
829
					continue;
830
				}
831
				$dhcpdconf .= 'class "' . str_replace(':', '', $mac) . '" {' . "\n";
832
				// Skip the first octet of the MAC address - for media type, typically Ethernet ("01") and match the rest.
833
				$dhcpdconf .= '	match if substring (hardware, 1, ' . (substr_count($mac, ':') + 1) . ') = ' . $mac . ';' . "\n";
834
				$dhcpdconf .= '}' . "\n";
835
			}
836
		}
837

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

    
841
		$dhcpdconf .= "subnet {$subnet} netmask {$subnetmask} {\n";
842

    
843
		// Setup pool options
844
		foreach ($all_pools as $all_pools_idx => $poolconf) {
845
			if (!(ip_in_subnet($poolconf['range']['from'], "{$subnet}/{$ifcfgsn}") && ip_in_subnet($poolconf['range']['to'], "{$subnet}/{$ifcfgsn}"))) {
846
				// If the user has changed the subnet from the interfaces page and applied,
847
				// but has not updated the DHCP range, then the range to/from of the pool can be outside the subnet.
848
				// This can also happen when implementing the batch of changes when the setup wizard reloads the new settings.
849
				$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);
850
				$do_file_notice = true;
851
				$conf_ipv4_address = $ifcfg['ipaddr'];
852
				$conf_ipv4_subnetmask = $ifcfg['subnet'];
853
				if (is_ipaddrv4($conf_ipv4_address) && is_subnet("{$conf_ipv4_address}/{$conf_ipv4_subnetmask}")) {
854
					$conf_subnet_base = gen_subnet($conf_ipv4_address, $conf_ipv4_subnetmask);
855
					if (ip_in_subnet($poolconf['range']['from'], "{$conf_subnet_base}/{$conf_ipv4_subnetmask}") &&
856
					    ip_in_subnet($poolconf['range']['to'], "{$conf_subnet_base}/{$conf_ipv4_subnetmask}")) {
857
						// Even though the running interface subnet does not match the pool range,
858
						// the interface subnet in the config file contains the pool range.
859
						// We are somewhere part-way through a settings reload, e.g. after running the setup wizard.
860
						// services_dhcpdv4_configure will be called again later when the new interface settings from
861
						// the config are applied and at that time everything will match up.
862
						// Ignore this pool on this interface for now and just log the error to the system log.
863
						log_error($error_msg);
864
						$do_file_notice = false;
865
					}
866
				}
867
				if ($do_file_notice) {
868
					file_notice("DHCP", $error_msg);
869
				}
870
				continue;
871
			}
872
			$dhcpdconf .= "	pool {\n";
873
			/* is failover dns setup? */
874
			if (is_array($poolconf['dnsserver']) && $poolconf['dnsserver'][0] <> "") {
875
				$dhcpdconf .= "		option domain-name-servers {$poolconf['dnsserver'][0]}";
876
				if ($poolconf['dnsserver'][1] <> "") {
877
					$dhcpdconf .= ",{$poolconf['dnsserver'][1]}";
878
				}
879
				if ($poolconf['dnsserver'][2] <> "") {
880
					$dhcpdconf .= ",{$poolconf['dnsserver'][2]}";
881
				}
882
				if ($poolconf['dnsserver'][3] <> "") {
883
					$dhcpdconf .= ",{$poolconf['dnsserver'][3]}";
884
				}
885
				$dhcpdconf .= ";\n";
886
			}
887

    
888
			/* allow/deny MACs */
889
			$mac_allow_list = array_unique(explode(',', $poolconf['mac_allow']));
890
			foreach ($mac_allow_list as $mac) {
891
				if (empty($mac)) {
892
					continue;
893
				}
894
				$dhcpdconf .= "		allow members of \"" . str_replace(':', '', $mac) . "\";\n";
895
			}
896
			$deny_action = "deny";
897
			if (isset($poolconf['nonak']) && empty($poolconf['failover_peerip'])) {
898
				$deny_action = "ignore";
899
			}
900
			$mac_deny_list = array_unique(explode(',', $poolconf['mac_deny']));
901
			foreach ($mac_deny_list as $mac) {
902
				if (empty($mac)) {
903
					continue;
904
				}
905
				$dhcpdconf .= "		$deny_action members of \"" . str_replace(':', '', $mac) . "\";\n";
906
			}
907

    
908
			if ($poolconf['failover_peerip'] <> "") {
909
				$dhcpdconf .= "		$deny_action dynamic bootp clients;\n";
910
			}
911

    
912
			// set pool MAC limitations
913
			if (isset($poolconf['denyunknown'])) {
914
				if ($poolconf['denyunknown'] == "class") {
915
					$dhcpdconf .= "		allow members of \"s_{$dhcpif}\";\n";
916
					$dhcpdconf .= "		$deny_action unknown-clients;\n";
917
				} else if ($poolconf['denyunknown'] == "disabled") {
918
					// add nothing to $dhcpdconf; condition added to prevent next condition applying if ever engine changes such that: isset("disabled") == true
919
				} else {	// "catch-all" covering "enabled" value post-PR#4066, and covering non-upgraded boolean option (i.e. literal value "enabled")
920
					$dhcpdconf .= "		$deny_action unknown-clients;\n";
921
				}
922
			}
923

    
924
			if ($poolconf['gateway'] && $poolconf['gateway'] != "none" && ($poolconf['gateway'] != $dhcpifconf['gateway'])) {
925
				$dhcpdconf .= "		option routers {$poolconf['gateway']};\n";
926
			}
927

    
928
			if ($dhcpifconf['failover_peerip'] <> "") {
929
				$dhcpdconf .= "		failover peer \"dhcp_{$dhcpif}\";\n";
930
			}
931

    
932
			$pdnscfg = "";
933

    
934
			if ($poolconf['domain'] && ($poolconf['domain'] != $dhcpifconf['domain'])) {
935
				$pdnscfg .= "		option domain-name \"{$poolconf['domain']}\";\n";
936
			}
937

    
938
			if (!empty($poolconf['domainsearchlist']) && ($poolconf['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
939
				$pdnscfg .= "		option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $poolconf['domainsearchlist'])) . "\";\n";
940
			}
941

    
942
			if (isset($poolconf['ddnsupdate'])) {
943
				if (($poolconf['ddnsdomain'] <> "") && ($poolconf['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
944
					$pdnscfg .= "		ddns-domainname \"{$poolconf['ddnsdomain']}\";\n";
945
				}
946
				$pdnscfg .= "		ddns-update-style interim;\n";
947
			}
948

    
949
			$dhcpdconf .= "{$pdnscfg}";
950

    
951
			// default-lease-time
952
			if ($poolconf['defaultleasetime'] && ($poolconf['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
953
				$dhcpdconf .= "		default-lease-time {$poolconf['defaultleasetime']};\n";
954
			}
955

    
956
			// max-lease-time
957
			if ($poolconf['maxleasetime'] && ($poolconf['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
958
				$dhcpdconf .= "		max-lease-time {$poolconf['maxleasetime']};\n";
959
			}
960

    
961
			// ignore bootp
962
			if (isset($poolconf['ignorebootp'])) {
963
				$dhcpdconf .= "		ignore bootp;\n";
964
			}
965

    
966
			// ignore-client-uids
967
			if (isset($poolconf['ignoreclientuids'])) {
968
				$dhcpdconf .= "		ignore-client-uids true;\n";
969
			}
970

    
971
			// netbios-name*
972
			if (is_array($poolconf['winsserver']) && $poolconf['winsserver'][0] && ($poolconf['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
973
				$dhcpdconf .= "		option netbios-name-servers " . join(",", $poolconf['winsserver']) . ";\n";
974
				$dhcpdconf .= "		option netbios-node-type 8;\n";
975
			}
976

    
977
			// ntp-servers
978
			if (is_array($poolconf['ntpserver']) && $poolconf['ntpserver'][0] && ($poolconf['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
979
				$dhcpdconf .= "		option ntp-servers " . join(",", $poolconf['ntpserver']) . ";\n";
980
			}
981

    
982
			// tftp-server-name
983
			if (!empty($poolconf['tftp']) && ($poolconf['tftp'] != $dhcpifconf['tftp'])) {
984
				$dhcpdconf .= "		option tftp-server-name \"{$poolconf['tftp']}\";\n";
985
			}
986

    
987
			// Handle pool-specific options
988
			$dhcpdconf .= "\n";
989
			// Ignore the first pool, which is the "overall" pool when $all_pools_idx is 0 - those are put outside the pool block later
990
			if (isset($poolconf['numberoptions']['item']) && is_array($poolconf['numberoptions']['item']) && ($all_pools_idx > 0)) {
991
				// Use the "real" pool index from the config, excluding the "overall" pool, and based from 0.
992
				// This matches the way $poolidx was used when generating the $custoptions string earlier.
993
				$poolidx = $all_pools_idx - 1;
994
				foreach ($poolconf['numberoptions']['item'] as $itemidx => $item) {
995
					$item_value = base64_decode($item['value']);
996
					if (empty($item['type']) || $item['type'] == "text") {
997
						$dhcpdconf .= "		option custom-{$dhcpif}-{$poolidx}-{$itemidx} \"{$item_value}\";\n";
998
					} else {
999
						$dhcpdconf .= "		option custom-{$dhcpif}-{$poolidx}-{$itemidx} {$item_value};\n";
1000
					}
1001
				}
1002
			}
1003

    
1004
			// ldap-server
1005
			if (!empty($poolconf['ldap']) && ($poolconf['ldap'] != $dhcpifconf['ldap'])) {
1006
				$dhcpdconf .= "		option ldap-server \"{$poolconf['ldap']}\";\n";
1007
			}
1008

    
1009
			// net boot information
1010
			if (isset($poolconf['netboot'])) {
1011
				if (!empty($poolconf['nextserver']) && ($poolconf['nextserver'] != $dhcpifconf['nextserver'])) {
1012
					$dhcpdconf .= "		next-server {$poolconf['nextserver']};\n";
1013
				}
1014

    
1015
				$pxe_files = array();
1016
				if (!empty($poolconf['filename']) &&
1017
				    (!isset($dhcpifconf['filename']) ||
1018
				    ($poolconf['filename'] != $dhcpifconf['filename']))) {
1019
					$filename = $poolconf['filename'];
1020
				}
1021
				if (!empty($poolconf['uefihttpboot']) &&
1022
				    (!isset($dhcpifconf['uefihttpboot']) ||
1023
				    ($poolconf['uefihttpboot'] != $dhcpifconf['uefihttpboot']))) {
1024
					$pxe_files[] = array('HTTPClient', $poolconf['uefihttpboot']);
1025
				}
1026
				if (!empty($poolconf['filename32']) &&
1027
				    (!isset($dhcpifconf['filename32']) ||
1028
				    ($poolconf['filename32'] != $dhcpifconf['filename32']))) {
1029
					$pxe_files[] = array('00:06', $poolconf['filename32']);
1030
				}
1031
				if (!empty($poolconf['filename64']) &&
1032
				    (!isset($dhcpifconf['filename64']) ||
1033
				    ($poolconf['filename64'] != $dhcpifconf['filename64']))) {
1034
					$pxe_files[] = array('00:07', $poolconf['filename64']);
1035
					$pxe_files[] = array('00:09', $poolconf['filename64']);
1036
				}
1037
				if (!empty($poolconf['filename32arm']) &&
1038
				    (!isset($dhcpifconf['filename32arm']) ||
1039
				    ($poolconf['filename32arm'] != $dhcpifconf['filename32arm']))) {
1040
					$pxe_files[] = array('00:0a', $poolconf['filename32arm']);
1041
				}
1042
				if (!empty($poolconf['filename64arm']) &&
1043
				    (!isset($dhcpifconf['filename64arm']) ||
1044
				    ($poolconf['filename64arm'] != $dhcpifconf['filename64arm']))) {
1045
					$pxe_files[] = array('00:0b', $poolconf['filename64arm']);
1046
				}
1047

    
1048
				$pxeif = false;
1049
				if (is_array($pxe_files) && !empty($pxe_files)) {
1050
					foreach ($pxe_files as $pxe) {
1051
						if ($pxe[0] == 'HTTPClient') {
1052
							$expr = "substring (option vendor-class-identifier, 0, 10) = \"HTTPClient\" {\n";
1053
						} else {
1054
							$expr = "option arch = {$pxe[0]} {\n";
1055
						}
1056
						if (!$pxeif) {
1057
							$dhcpdconf .= "		if " . $expr;
1058
							$pxeif = true;
1059
						} else {
1060
							$dhcpdconf .= " else if " . $expr;
1061
						}
1062
						$dhcpdconf .= "			filename \"{$pxe[1]}\";\n";
1063
						$dhcpdconf .= "		}";
1064
					}
1065
					if ($filename) {
1066
						$dhcpdconf .= " else {\n";
1067
						$dhcpdconf .= "			filename \"{$filename}\";\n";
1068
						$dhcpdconf .= "		}";
1069
					}
1070
					$dhcpdconf .= "\n\n";
1071
				} elseif (!empty($filename)) {
1072
					$dhcpdconf .= "		filename \"{$filename}\";\n";
1073
				}
1074
				unset($filename);
1075

    
1076
				if (!empty($poolconf['rootpath']) && ($poolconf['rootpath'] != $dhcpifconf['rootpath'])) {
1077
					$dhcpdconf .= "		option root-path \"{$poolconf['rootpath']}\";\n";
1078
				}
1079
			}
1080
			$dhcpdconf .= "		range {$poolconf['range']['from']} {$poolconf['range']['to']};\n";
1081
			$dhcpdconf .= "	}\n\n";
1082
		}
1083
// End of settings inside pools
1084

    
1085
		if ($dhcpifconf['gateway'] && $dhcpifconf['gateway'] != "none") {
1086
			$routers = $dhcpifconf['gateway'];
1087
			$add_routers = true;
1088
		} elseif ($dhcpifconf['gateway'] == "none") {
1089
			$add_routers = false;
1090
		} else {
1091
			$add_routers = $enable_add_routers;
1092
			$routers = $ifcfgip;
1093
		}
1094
		if ($add_routers) {
1095
			$dhcpdconf .= "	option routers {$routers};\n";
1096
		}
1097

    
1098
		$dhcpdconf .= <<<EOD
1099
$dnscfg
1100

    
1101
EOD;
1102
		// default-lease-time
1103
		if ($dhcpifconf['defaultleasetime']) {
1104
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
1105
		}
1106

    
1107
		// max-lease-time
1108
		if ($dhcpifconf['maxleasetime']) {
1109
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
1110
		}
1111

    
1112
		if (!isset($dhcpifconf['disablepingcheck'])) {
1113
			$dhcpdconf .= "	ping-check true;\n";
1114
		} else {
1115
			$dhcpdconf .= "	ping-check false;\n";
1116
		}
1117

    
1118
		// netbios-name*
1119
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
1120
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
1121
			$dhcpdconf .= "	option netbios-node-type 8;\n";
1122
		}
1123

    
1124
		// ntp-servers
1125
		if (is_array($dhcpifconf['ntpserver']) && $dhcpifconf['ntpserver'][0]) {
1126
			$dhcpdconf .= "	option ntp-servers " . join(",", $dhcpifconf['ntpserver']) . ";\n";
1127
		}
1128

    
1129
		// tftp-server-name
1130
		if ($dhcpifconf['tftp'] <> "") {
1131
			$dhcpdconf .= "	option tftp-server-name \"{$dhcpifconf['tftp']}\";\n";
1132
		}
1133

    
1134
		// Handle option, number rowhelper values
1135
		$dhcpdconf .= "\n";
1136
		if (isset($dhcpifconf['numberoptions']['item']) && is_array($dhcpifconf['numberoptions']['item'])) {
1137
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
1138
				$item_value = base64_decode($item['value']);
1139
				if (empty($item['type']) || $item['type'] == "text") {
1140
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} \"{$item_value}\";\n";
1141
				} else {
1142
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} {$item_value};\n";
1143
				}
1144
			}
1145
		}
1146

    
1147
		// ldap-server
1148
		if ($dhcpifconf['ldap'] <> "") {
1149
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
1150
		}
1151

    
1152
		// net boot information
1153
		if (isset($dhcpifconf['netboot'])) {
1154
			if ($dhcpifconf['nextserver'] <> "") {
1155
				$dhcpdconf .= "	next-server {$dhcpifconf['nextserver']};\n";
1156
			}
1157

    
1158
			$pxe_files = array();
1159
			if (!empty($dhcpifconf['filename'])) {
1160
				$filename = $dhcpifconf['filename'];
1161
			}
1162
			if (!empty($dhcpifconf['uefihttpboot'])) {
1163
				$pxe_files[] = array('HTTPClient', $dhcpifconf['uefihttpboot']);
1164
			}
1165
			if (!empty($dhcpifconf['filename32'])) {
1166
				$pxe_files[] = array('00:06', $dhcpifconf['filename32']);
1167
			}
1168
			if (!empty($dhcpifconf['filename64'])) {
1169
				$pxe_files[] = array('00:07', $dhcpifconf['filename64']);
1170
				$pxe_files[] = array('00:09', $dhcpifconf['filename64']);
1171
			}
1172
			if (!empty($dhcpifconf['filename32arm'])) {
1173
				$pxe_files[] = array('00:0a', $dhcpifconf['filename32arm']);
1174
			}
1175
			if (!empty($dhcpifconf['filename64arm'])) {
1176
				$pxe_files[] = array('00:0b', $dhcpifconf['filename64arm']);
1177
			}
1178

    
1179
			$pxeif = false;
1180
			if (is_array($pxe_files) && !empty($pxe_files)) {
1181
				foreach ($pxe_files as $pxe) {
1182
					if ($pxe[0] == 'HTTPClient') {
1183
						$expr = "substring (option vendor-class-identifier, 0, 10) = \"HTTPClient\" {\n";
1184
					} else {
1185
						$expr = "option arch = {$pxe[0]} {\n";
1186
					}
1187
					if (!$pxeif) {
1188
						$dhcpdconf .= "	if " . $expr; 
1189
						$pxeif = true;
1190
					} else {
1191
						$dhcpdconf .= " else if " . $expr; 
1192
					}
1193
					$dhcpdconf .= "		filename \"{$pxe[1]}\";\n";
1194
					$dhcpdconf .= "	}";
1195
				}
1196
				if ($filename) {
1197
					$dhcpdconf .= " else {\n";
1198
					$dhcpdconf .= "		filename \"{$filename}\";\n";
1199
					$dhcpdconf .= "	}";
1200
				}
1201
				$dhcpdconf .= "\n\n";
1202
			} elseif (!empty($filename)) {
1203
				$dhcpdconf .= "		filename \"{$filename}\";\n";
1204
			}
1205
			if (!empty($dhcpifconf['rootpath'])) {
1206
				$dhcpdconf .= "	option root-path \"{$dhcpifconf['rootpath']}\";\n";
1207
			}
1208
		}
1209

    
1210
		$dhcpdconf .= <<<EOD
1211
}
1212

    
1213
EOD;
1214

    
1215
		/* add static mappings */
1216
		if (is_array($dhcpifconf['staticmap'])) {
1217

    
1218
			$i = 0;
1219
			$sm_newzone[] = array();
1220
			$need_sm_ddns_updates = false;
1221
			foreach ($dhcpifconf['staticmap'] as $sm) {
1222
				$cid = '';
1223
				$dhcpdconf .= "host s_{$dhcpif}_{$i} {\n";
1224

    
1225
				if ($sm['mac']) {
1226
					$dhcpdconf .= "	hardware ethernet {$sm['mac']};\n";
1227
				}
1228

    
1229
				if ($sm['cid']) {
1230
					$cid = str_replace('"', '\"', $sm['cid']);
1231
					$dhcpdconf .= "	option dhcp-client-identifier \"{$cid}\";\n";
1232
				}
1233

    
1234
				if ($sm['ipaddr']) {
1235
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
1236
				}
1237

    
1238
				if ($sm['hostname']) {
1239
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1240
					$dhhostname = str_replace(".", "_", $dhhostname);
1241
					$dhcpdconf .= "	option host-name \"{$dhhostname}\";\n";
1242
					if ((isset($dhcpifconf['ddnsupdate']) || isset($sm['ddnsupdate'])) && (isset($dhcpifconf['ddnsforcehostname']) || isset($sm['ddnsforcehostname']))) {
1243
						$dhcpdconf .= "	ddns-hostname \"{$dhhostname}\";\n";
1244
					}
1245
				}
1246
				if ($sm['filename']) {
1247
					$dhcpdconf .= "	filename \"{$sm['filename']}\";\n";
1248
				}
1249

    
1250
				if ($sm['rootpath']) {
1251
					$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1252
				}
1253

    
1254
				if ($sm['gateway'] && ($sm['gateway'] != $dhcpifconf['gateway'])) {
1255
					$dhcpdconf .= "	option routers {$sm['gateway']};\n";
1256
				}
1257

    
1258
				$smdnscfg = "";
1259

    
1260
				if ($sm['domain'] && ($sm['domain'] != $dhcpifconf['domain'])) {
1261
					$smdnscfg .= "	option domain-name \"{$sm['domain']}\";\n";
1262
				}
1263

    
1264
				if (!empty($sm['domainsearchlist']) && ($sm['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
1265
					$smdnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $sm['domainsearchlist'])) . "\";\n";
1266
				}
1267

    
1268
				if (isset($sm['ddnsupdate'])) {
1269
					if (($sm['ddnsdomain'] <> "") && ($sm['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
1270
						$smdnscfg .= "	ddns-domainname \"{$sm['ddnsdomain']}\";\n";
1271
				 		$need_sm_ddns_updates = true;	
1272
					}
1273
					$smdnscfg .= "	ddns-update-style interim;\n";
1274
				}
1275

    
1276
				if (is_array($sm['dnsserver']) && ($sm['dnsserver'][0]) && ($sm['dnsserver'][0] != $dhcpifconf['dnsserver'][0])) {
1277
					$smdnscfg .= "	option domain-name-servers " . join(",", $sm['dnsserver']) . ";\n";
1278
				}
1279
				$dhcpdconf .= "{$smdnscfg}";
1280

    
1281
				// default-lease-time
1282
				if ($sm['defaultleasetime'] && ($sm['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
1283
					$dhcpdconf .= "	default-lease-time {$sm['defaultleasetime']};\n";
1284
				}
1285

    
1286
				// max-lease-time
1287
				if ($sm['maxleasetime'] && ($sm['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
1288
					$dhcpdconf .= "	max-lease-time {$sm['maxleasetime']};\n";
1289
				}
1290

    
1291
				// netbios-name*
1292
				if (is_array($sm['winsserver']) && $sm['winsserver'][0] && ($sm['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
1293
					$dhcpdconf .= "	option netbios-name-servers " . join(",", $sm['winsserver']) . ";\n";
1294
					$dhcpdconf .= "	option netbios-node-type 8;\n";
1295
				}
1296

    
1297
				// ntp-servers
1298
				if (is_array($sm['ntpserver']) && $sm['ntpserver'][0] && ($sm['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
1299
					$dhcpdconf .= "	option ntp-servers " . join(",", $sm['ntpserver']) . ";\n";
1300
				}
1301

    
1302
				// tftp-server-name
1303
				if (!empty($sm['tftp']) && ($sm['tftp'] != $dhcpifconf['tftp'])) {
1304
					$dhcpdconf .= "	option tftp-server-name \"{$sm['tftp']}\";\n";
1305
				}
1306

    
1307
				// Handle option, number rowhelper values
1308
				$dhcpdconf .= "\n";
1309
				if (isset($sm['numberoptions']['item']) && is_array($sm['numberoptions']['item'])) {
1310
					foreach ($sm['numberoptions']['item'] as $itemidx => $item) {
1311
						$item_value = base64_decode($item['value']);
1312
						if (empty($item['type']) || $item['type'] == "text") {
1313
							$dhcpdconf .= "	option custom-s_{$dhcpif}_{$i}-{$itemidx} \"{$item_value}\";\n";
1314
						} else {
1315
							$dhcpdconf .= "	option custom-s_{$dhcpif}_{$i}-{$itemidx} {$item_value};\n";
1316
						}
1317
					}
1318
				}
1319

    
1320
				// ldap-server
1321
				if (!empty($sm['ldap']) && ($sm['ldap'] != $dhcpifconf['ldap'])) {
1322
					$dhcpdconf .= "	option ldap-server \"{$sm['ldap']}\";\n";
1323
				}
1324

    
1325
				// net boot information
1326
				if (isset($sm['netboot'])) {
1327
					if ($sm['nextserver'] <> "") {
1328
						$dhcpdconf .= "	next-server {$sm['nextserver']};\n";
1329
					}
1330

    
1331
					$pxe_files = array();
1332
					if (!empty($sm['filename'])) {
1333
						$filename = $sm['filename'];
1334
					}
1335
					if (!empty($sm['filename32'])) {
1336
						$pxe_files[] = array('00:06', $sm['filename32']);
1337
					}
1338
					if (!empty($sm['filename64'])) {
1339
						$pxe_files[] = array('00:07', $sm['filename64']);
1340
						$pxe_files[] = array('00:09', $sm['filename64']);
1341
					}
1342
					if (!empty($sm['filename32arm'])) {
1343
						$pxe_files[] = array('00:0a', $sm['filename32arm']);
1344
					}
1345
					if (!empty($sm['filename64arm'])) {
1346
						$pxe_files[] = array('00:0b', $sm['filename64arm']);
1347
					}
1348

    
1349
					$pxeif = false;
1350
					if (is_array($pxe_files) && !empty($pxe_files)) {
1351
						foreach ($pxe_files as $pxe) {
1352
							if (!$pxeif) {
1353
								$dhcpdconf .= "	if option arch = {$pxe[0]} {\n";
1354
								$pxeif = true;
1355
							} else {
1356
								$dhcpdconf .= " else if option arch = {$pxe[0]} {\n";
1357
							}
1358
							$dhcpdconf .= "		filename \"{$pxe[1]}\";\n";
1359
							$dhcpdconf .= "	}";
1360
						}
1361
						if ($filename) {
1362
							$dhcpdconf .= " else {\n";
1363
							$dhcpdconf .= "		filename \"{$filename}\";\n";
1364
							$dhcpdconf .= "	}";
1365
						}
1366
						$dhcpdconf .= "\n\n";
1367
					} elseif (!empty($filename)) {
1368
						$dhcpdconf .= "		filename \"{$filename}\";\n";
1369
					}
1370
					if (!empty($dhcpifconf['rootpath'])) {
1371
						$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1372
					}
1373
				}
1374

    
1375
				$dhcpdconf .= "}\n";
1376

    
1377
				// add zone DDNS key/server to $ddns_zone[] if required
1378
				if ($need_sm_ddns_updates) {
1379
					$ddnsduplicate = false;
1380
					foreach ($ddns_zones as $ddnszone) {
1381
						if ($ddnszone['domain-name'] == $sm['ddnsdomain']) {
1382
							$ddnsduplicate = true;
1383
						}
1384
					}
1385
					if (!$ddnsduplicate) {
1386
						$sm_newzone['dns-servers'] = array($sm['ddnsdomainprimary'], $sm['ddnsdomainsecondary']);
1387
						$sm_newzone['domain-name'] = $sm['ddnsdomain'];
1388
						$sm_newzone['ddnsdomainkeyname'] = $sm['ddnsdomainkeyname'];
1389
						$sm_newzone['ddnsdomainkeyalgorithm'] = $sm['ddnsdomainkeyalgorithm'];
1390
						$sm_newzone['ddnsdomainkey'] = $sm['ddnsdomainkey'];
1391
						$dhcpdconf .= dhcpdkey($sm_newzone);
1392
						$ddns_zones[] = $sm_newzone;
1393
						$need_ddns_updates = true;
1394
					}
1395
				}
1396

    
1397
				// subclass for DHCP limiting
1398
				if (!empty($sm['mac'])) {
1399
					// assuming ALL addresses are ethernet hardware type ("1:" prefix)
1400
					$dhcpdconf .= "subclass \"s_{$dhcpif}\" 1:{$sm['mac']};\n";
1401
				}
1402
				if (!empty($cid)) {
1403
					$dhcpdconf .= "subclass \"s_{$dhcpif}\" \"{$cid}\";\n";
1404
				}
1405

    
1406

    
1407
				$i++;
1408
			}
1409
		}
1410

    
1411
		$dhcpdifs[] = get_real_interface($dhcpif);
1412
		if ($newzone['domain-name']) {
1413
			if ($need_ddns_updates) {
1414
				$newzone['dns-servers'] = array($dhcpifconf['ddnsdomainprimary'], $dhcpifconf['ddnsdomainsecondary']);
1415
				$newzone['ddnsdomainkeyname'] = $dhcpifconf['ddnsdomainkeyname'];
1416
				$newzone['ddnsdomainkeyalgorithm'] = $dhcpifconf['ddnsdomainkeyalgorithm'];
1417
				$newzone['ddnsdomainkey'] = $dhcpifconf['ddnsdomainkey'];
1418
				$dhcpdconf .= dhcpdkey($dhcpifconf);
1419
			}
1420
			$ddns_zones[] = $newzone;
1421
		}
1422
	}
1423

    
1424
	if ($need_ddns_updates) {
1425
		$dhcpdconf .= "ddns-update-style interim;\n";
1426
		$dhcpdconf .= "update-static-leases on;\n";
1427

    
1428
		$dhcpdconf .= dhcpdzones($ddns_zones);
1429
	}
1430

    
1431
	/* write dhcpd.conf */
1432
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpd.conf", $dhcpdconf)) {
1433
		printf(gettext("Error: cannot open dhcpd.conf in services_dhcpdv4_configure().%s"), "\n");
1434
		unset($dhcpdconf);
1435
		return 1;
1436
	}
1437
	unset($dhcpdconf);
1438

    
1439
	/* create an empty leases database */
1440
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
1441
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
1442
	}
1443

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

    
1448
	/* fire up dhcpd in a chroot */
1449
	if (count($dhcpdifs) > 0) {
1450
		mwexec("/usr/local/sbin/dhcpd -user dhcpd -group _dhcp -chroot {$g['dhcpd_chroot_path']} -cf /etc/dhcpd.conf -pf {$g['varrun_path']}/dhcpd.pid " .
1451
			join(" ", $dhcpdifs));
1452
	}
1453

    
1454
	if (platform_booting()) {
1455
		print "done.\n";
1456
	}
1457

    
1458
	return 0;
1459
}
1460

    
1461
function dhcpdkey($dhcpifconf) {
1462
	$dhcpdconf = "";
1463
	if (!empty($dhcpifconf['ddnsdomainkeyname']) && !empty($dhcpifconf['ddnsdomainkey'])) {
1464
		$algorithm = empty($dhcpifconf['ddnsdomainkeyalgorithm']) ? 'hmac-md5' : $dhcpifconf['ddnsdomainkeyalgorithm'];
1465
		$dhcpdconf .= "key \"{$dhcpifconf['ddnsdomainkeyname']}\" {\n";
1466
		$dhcpdconf .= "	algorithm {$algorithm};\n";
1467
		$dhcpdconf .= "	secret {$dhcpifconf['ddnsdomainkey']};\n";
1468
		$dhcpdconf .= "}\n";
1469
	}
1470

    
1471
	return $dhcpdconf;
1472
}
1473

    
1474
function dhcpdzones($ddns_zones) {
1475
	$dhcpdconf = "";
1476

    
1477
	if (is_array($ddns_zones)) {
1478
		$added_zones = array();
1479
		foreach ($ddns_zones as $zone) {
1480
			if (!is_array($zone) || empty($zone) || !is_array($zone['dns-servers'])) {
1481
				continue;
1482
			}
1483
			$primary = $zone['dns-servers'][0];
1484
			$secondary = empty($zone['dns-servers'][1]) ? "" : $zone['dns-servers'][1];
1485

    
1486
			// Make sure we aren't using any invalid servers.
1487
			if (!is_ipaddr($primary)) {
1488
				if (is_ipaddr($secondary)) {
1489
					$primary = $secondary;
1490
					$secondary = "";
1491
				} else {
1492
					continue;
1493
				}
1494
			}
1495

    
1496
			// We don't need to add zones multiple times.
1497
			if ($zone['domain-name'] && !in_array($zone['domain-name'], $added_zones)) {
1498
				$dhcpdconf .= "zone {$zone['domain-name']}. {\n";
1499
				if (is_ipaddrv4($primary)) {
1500
					$dhcpdconf .= "	primary {$primary};\n";
1501
				} else {
1502
					$dhcpdconf .= "	primary6 {$primary};\n";
1503
				}
1504
				if (is_ipaddrv4($secondary)) {
1505
					$dhcpdconf .= "	secondary {$secondary};\n";
1506
				} elseif (is_ipaddrv6($secondary)) {
1507
					$dhcpdconf .= "	secondary6 {$secondary};\n";
1508
				}
1509
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1510
					$dhcpdconf .= "	key \"{$zone['ddnsdomainkeyname']}\";\n";
1511
				}
1512
				$dhcpdconf .= "}\n";
1513
				$added_zones[] = $zone['domain-name'];
1514
			}
1515
			if ($zone['ptr-domain'] && !in_array($zone['ptr-domain'], $added_zones)) {
1516
				$dhcpdconf .= "zone {$zone['ptr-domain']}. {\n";
1517
				if (is_ipaddrv4($primary)) {
1518
					$dhcpdconf .= "	primary {$primary};\n";
1519
				} else {
1520
					$dhcpdconf .= "	primary6 {$primary};\n";
1521
				}
1522
				if (is_ipaddrv4($secondary)) {
1523
					$dhcpdconf .= "	secondary {$secondary};\n";
1524
				} elseif (is_ipaddrv6($secondary)) {
1525
					$dhcpdconf .= "	secondary6 {$secondary};\n";
1526
				}
1527
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1528
					$dhcpdconf .= "	key \"{$zone['ddnsdomainkeyname']}\";\n";
1529
				}
1530
				$dhcpdconf .= "}\n";
1531
				$added_zones[] = $zone['ptr-domain'];
1532
			}
1533
		}
1534
	}
1535

    
1536
	return $dhcpdconf;
1537
}
1538

    
1539
function services_dhcpdv6_configure($blacklist = array()) {
1540
	global $config, $g;
1541

    
1542
	if ($g['services_dhcp_server_enable'] == false) {
1543
		return;
1544
	}
1545

    
1546
	if (isset($config['system']['developerspew'])) {
1547
		$mt = microtime();
1548
		echo "services_dhcpd_configure($if) being called $mt\n";
1549
	}
1550

    
1551
	/* kill any running dhcpd */
1552
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid")) {
1553
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid");
1554
	}
1555
	if (isvalidpid("{$g['varrun_path']}/dhcpleases6.pid")) {
1556
		killbypid("{$g['varrun_path']}/dhcpleases6.pid");
1557
	}
1558

    
1559
	/* DHCP enabled on any interfaces? */
1560
	if (!is_dhcpv6_server_enabled()) {
1561
		return 0;
1562
	}
1563

    
1564
	$syscfg = $config['system'];
1565
	if (!is_array($config['dhcpdv6'])) {
1566
		$config['dhcpdv6'] = array();
1567
	}
1568
	$dhcpdv6cfg = $config['dhcpdv6'];
1569
	$Iflist = get_configured_interface_list();
1570
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
1571

    
1572

    
1573
	if (platform_booting()) {
1574
		echo "Starting DHCPv6 service...";
1575
	} else {
1576
		sleep(1);
1577
	}
1578

    
1579
	$custoptionsv6 = "";
1580
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1581
		if (is_array($dhcpv6ifconf['numberoptions']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1582
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1583
				$custoptionsv6 .= "option custom-{$dhcpv6if}-{$itemv6idx} code {$itemv6['number']} = text;\n";
1584
			}
1585
		}
1586
	}
1587

    
1588
	if (isset($dhcpv6ifconf['netboot']) && !empty($dhcpv6ifconf['bootfile_url'])) {
1589
		$custoptionsv6 .= "option dhcp6.bootfile-url code 59 = string;\n";
1590
	}
1591

    
1592
	$dhcpdv6conf = <<<EOD
1593

    
1594
option domain-name "{$syscfg['domain']}";
1595
option ldap-server code 95 = text;
1596
option domain-search-list code 119 = text;
1597
{$custoptionsv6}
1598
default-lease-time 7200;
1599
max-lease-time 86400;
1600
log-facility local7;
1601
one-lease-per-client true;
1602
deny duplicates;
1603
ping-check true;
1604
update-conflict-detection false;
1605

    
1606
EOD;
1607

    
1608
	if (!isset($dhcpv6ifconf['disableauthoritative'])) {
1609
		$dhcpdv6conf .= "authoritative;\n";
1610
	}
1611

    
1612
	if (isset($dhcpv6ifconf['alwaysbroadcast'])) {
1613
		$dhcpdv6conf .= "always-broadcast on\n";
1614
	}
1615

    
1616
	$dhcpdv6ifs = array();
1617

    
1618
	$dhcpv6num = 0;
1619
	$nsupdate = false;
1620

    
1621
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1622

    
1623
		$ddns_zones = array();
1624

    
1625
		$ifcfgv6 = $config['interfaces'][$dhcpv6if];
1626

    
1627
		if (!isset($dhcpv6ifconf['enable']) || !isset($Iflist[$dhcpv6if]) ||
1628
		    (!isset($ifcfgv6['enable']) && !preg_match("/poes/", $dhcpv6if))) {
1629
			continue;
1630
		}
1631
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1632
		if (!is_ipaddrv6($ifcfgipv6) && !preg_match("/poes/", $dhcpv6if)) {
1633
			continue;
1634
		}
1635
		$ifcfgsnv6 = get_interface_subnetv6($dhcpv6if);
1636
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1637
		// We might have some prefix-delegation on WAN (e.g. /48),
1638
		// but then it is split and given out to individual interfaces
1639
		// (LAN, OPT1, OPT2...) as multiple /64 subnets. So the size
1640
		// of each subnet here is always /64.
1641
		$pdlen = 64;
1642

    
1643
		if (is_ipaddrv6($ifcfgipv6)) {
1644
			$subnet_start = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1645
			$subnet_end = gen_subnetv6_max($ifcfgipv6, $ifcfgsnv6);
1646
			if ((!is_inrange_v6($dhcpv6ifconf['range']['from'], $subnet_start, $subnet_end)) ||
1647
			    (!is_inrange_v6($dhcpv6ifconf['range']['to'], $subnet_start, $subnet_end))) {
1648
				log_error(gettext("The specified range lies outside of the current subnet. Skipping DHCP6 entry."));
1649
				continue;
1650
			}
1651
		}
1652

    
1653
		$dnscfgv6 = "";
1654

    
1655
		if ($dhcpv6ifconf['domain']) {
1656
			$dnscfgv6 .= "	option domain-name \"{$dhcpv6ifconf['domain']}\";\n";
1657
		}
1658

    
1659
		if ($dhcpv6ifconf['domainsearchlist'] <> "") {
1660
			$dnscfgv6 .= "	option dhcp6.domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpv6ifconf['domainsearchlist'])) . "\";\n";
1661
		}
1662

    
1663
		if (isset($dhcpv6ifconf['ddnsupdate'])) {
1664
			if ($dhcpv6ifconf['ddnsdomain'] <> "") {
1665
				$dnscfgv6 .= "	ddns-domainname \"{$dhcpv6ifconf['ddnsdomain']}\";\n";
1666
			}
1667
			if (empty($dhcpv6ifconf['ddnsclientupdates'])) {
1668
				$ddnsclientupdates = 'allow';
1669
			} else {
1670
				$ddnsclientupdates = $dhcpv6ifconf['ddnsclientupdates'];
1671
			}
1672
			$dnscfgv6 .= "	{$ddnsclientupdates} client-updates;\n";
1673
			$nsupdate = true;
1674
		} else {
1675
			$dnscfgv6 .= "	do-forward-updates false;\n";
1676
		}
1677

    
1678
		if ($dhcpv6ifconf['dhcp6c-dns'] != 'disabled') {
1679
			if (is_array($dhcpv6ifconf['dnsserver']) && ($dhcpv6ifconf['dnsserver'][0])) {
1680
				$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dhcpv6ifconf['dnsserver']) . ";\n";
1681
			} else if (((isset($config['dnsmasq']['enable'])) || isset($config['unbound']['enable'])) && (is_ipaddrv6($ifcfgipv6))) {
1682
				$dnscfgv6 .= "	option dhcp6.name-servers {$ifcfgipv6};\n";
1683
			} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1684
				$dns_arrv6 = array();
1685
				foreach ($syscfg['dnsserver'] as $dnsserver) {
1686
					if (is_ipaddrv6($dnsserver)) {
1687
						if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1688
						    Net_IPv6::isInNetmask($dnsserver, '::', $pdlen)) {
1689
							$dnsserver = merge_ipv6_delegated_prefix($ifcfgipv6, $dnsserver, $pdlen);
1690
						}
1691
						$dns_arrv6[] = $dnsserver;
1692
					}
1693
				}
1694
				if (!empty($dns_arrv6)) {
1695
					$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dns_arrv6) . ";\n";
1696
				}
1697
			}
1698
		} else {
1699
			$dnscfgv6 .= "	#option dhcp6.name-servers --;\n";
1700
		}
1701

    
1702
		if (!is_ipaddrv6($ifcfgipv6)) {
1703
			$ifcfgsnv6 = "64";
1704
			$subnetv6 = gen_subnetv6($dhcpv6ifconf['range']['from'], $ifcfgsnv6);
1705
		}
1706

    
1707
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1708

    
1709
		if (isset($dhcpv6ifconf['ddnsupdate']) &&
1710
		    !empty($dhcpv6ifconf['ddnsdomain'])) {
1711
			$newzone = array();
1712
			$newzone['domain-name'] = $dhcpv6ifconf['ddnsdomain'];
1713
			$newzone['dns-servers'] = array($dhcpv6ifconf['ddnsdomainprimary'], $dhcpv6ifconf['ddnsdomainsecondary']);
1714
			$newzone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1715
			$newzone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1716
			$ddns_zones[] = $newzone;
1717
			if (isset($dhcpv6ifconf['ddnsreverse'])) {
1718
				$ptr_zones = get_v6_ptr_zones($subnetv6, $ifcfgsnv6);
1719
				foreach ($ptr_zones as $ptr_zone) {
1720
					$reversezone = array();
1721
					$reversezone['ptr-domain'] = $ptr_zone;
1722
					$reversezone['dns-servers'] = array($dhcpv6ifconf['ddnsdomainprimary'], $dhcpv6ifconf['ddnsdomainsecondary']);
1723
					$reversezone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1724
					$reversezone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1725
					$ddns_zones[] = $reversezone;
1726
				}
1727
			}
1728
		}
1729

    
1730
		$dhcpdv6conf .= " {\n";
1731

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

    
1739
		if (!empty($dhcpv6ifconf['range']['from']) && !empty($dhcpv6ifconf['range']['to'])) {
1740
			$dhcpdv6conf .= "	range6 {$range_from} {$range_to};\n";
1741
		}
1742

    
1743
		$dhcpdv6conf .= $dnscfgv6;
1744

    
1745
		if (is_ipaddrv6($dhcpv6ifconf['prefixrange']['from']) && is_ipaddrv6($dhcpv6ifconf['prefixrange']['to'])) {
1746
			$dhcpdv6conf .= "	prefix6 {$dhcpv6ifconf['prefixrange']['from']} {$dhcpv6ifconf['prefixrange']['to']} /{$dhcpv6ifconf['prefixrange']['prefixlength']};\n";
1747
		}
1748
		if (is_ipaddrv6($dhcpv6ifconf['dns6ip'])) {
1749
			$dns6ip = $dhcpv6ifconf['dns6ip'];
1750
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1751
			    Net_IPv6::isInNetmask($dns6ip, '::', $pdlen)) {
1752
				$dns6ip = merge_ipv6_delegated_prefix($ifcfgipv6, $dns6ip, $pdlen);
1753
			}
1754
			$dhcpdv6conf .= "	option dhcp6.name-servers {$dns6ip};\n";
1755
		}
1756
		// default-lease-time
1757
		if ($dhcpv6ifconf['defaultleasetime']) {
1758
			$dhcpdv6conf .= "	default-lease-time {$dhcpv6ifconf['defaultleasetime']};\n";
1759
		}
1760

    
1761
		// max-lease-time
1762
		if ($dhcpv6ifconf['maxleasetime']) {
1763
			$dhcpdv6conf .= "	max-lease-time {$dhcpv6ifconf['maxleasetime']};\n";
1764
		}
1765

    
1766
		// ntp-servers
1767
		if (is_array($dhcpv6ifconf['ntpserver']) && $dhcpv6ifconf['ntpserver'][0]) {
1768
			$ntpservers = array();
1769
			foreach ($dhcpv6ifconf['ntpserver'] as $ntpserver) {
1770
				if (!is_ipaddrv6($ntpserver)) {
1771
					continue;
1772
				}
1773
				if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1774
				    Net_IPv6::isInNetmask($ntpserver, '::', $pdlen)) {
1775
					$ntpserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ntpserver, $pdlen);
1776
				}
1777
				$ntpservers[] = $ntpserver;
1778
			}
1779
			if (count($ntpservers) > 0) {
1780
				$dhcpdv6conf .= "        option dhcp6.sntp-servers " . join(",", $dhcpv6ifconf['ntpserver']) . ";\n";
1781
			}
1782
		}
1783
		// tftp-server-name
1784
		/* Needs ISC DHCPD support
1785
		 if ($dhcpv6ifconf['tftp'] <> "") {
1786
			$dhcpdv6conf .= "	option tftp-server-name \"{$dhcpv6ifconf['tftp']}\";\n";
1787
		 }
1788
		*/
1789

    
1790
		// Handle option, number rowhelper values
1791
		$dhcpdv6conf .= "\n";
1792
		if (isset($dhcpv6ifconf['numberoptions']['item']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1793
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1794
				$itemv6_value = base64_decode($itemv6['value']);
1795
				$dhcpdv6conf .= "	option custom-{$dhcpv6if}-{$itemv6idx} \"{$itemv6_value}\";\n";
1796
			}
1797
		}
1798

    
1799
		// ldap-server
1800
		if ($dhcpv6ifconf['ldap'] <> "") {
1801
			$ldapserver = $dhcpv6ifconf['ldap'];
1802
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1803
			    Net_IPv6::isInNetmask($ldapserver, '::', $pdlen)) {
1804
				$ldapserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ldapserver, $pdlen);
1805
			}
1806
			$dhcpdv6conf .= "	option ldap-server \"{$ldapserver}\";\n";
1807
		}
1808

    
1809
		// net boot information
1810
		if (isset($dhcpv6ifconf['netboot'])) {
1811
			if (!empty($dhcpv6ifconf['bootfile_url'])) {
1812
				$dhcpdv6conf .= "	option dhcp6.bootfile-url \"{$dhcpv6ifconf['bootfile_url']}\";\n";
1813
			}
1814
		}
1815

    
1816
		$dhcpdv6conf .= "}\n";
1817

    
1818
		/* add static mappings */
1819
		/* Needs to use DUID */
1820
		if (is_array($dhcpv6ifconf['staticmap'])) {
1821
			$i = 0;
1822
			foreach ($dhcpv6ifconf['staticmap'] as $sm) {
1823
				$dhcpdv6conf .= <<<EOD
1824
host s_{$dhcpv6if}_{$i} {
1825
	host-identifier option dhcp6.client-id {$sm['duid']};
1826

    
1827
EOD;
1828
				if ($sm['ipaddrv6']) {
1829
					$ipaddrv6 = $sm['ipaddrv6'];
1830
					if ($ifcfgv6['ipaddrv6'] == 'track6') {
1831
						$ipaddrv6 = merge_ipv6_delegated_prefix($ifcfgipv6, $ipaddrv6, $pdlen);
1832
					}
1833
					$dhcpdv6conf .= "	fixed-address6 {$ipaddrv6};\n";
1834
				}
1835

    
1836
				if ($sm['hostname']) {
1837
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1838
					$dhhostname = str_replace(".", "_", $dhhostname);
1839
					$dhcpdv6conf .= "	option host-name {$dhhostname};\n";
1840
					if (isset($dhcpv6ifconf['ddnsupdate']) &&
1841
					    isset($dhcpv6ifconf['ddnsforcehostname'])) {
1842
						$dhcpdv6conf .= "	ddns-hostname \"{$dhhostname}\";\n";
1843
					}
1844
				}
1845
				if ($sm['filename']) {
1846
					$dhcpdv6conf .= "	filename \"{$sm['filename']}\";\n";
1847
				}
1848

    
1849
				if ($sm['rootpath']) {
1850
					$dhcpdv6conf .= "	option root-path \"{$sm['rootpath']}\";\n";
1851
				}
1852

    
1853
				$dhcpdv6conf .= "}\n";
1854
				$i++;
1855
			}
1856
		}
1857

    
1858
		if ($dhcpv6ifconf['ddnsdomain']) {
1859
			$dhcpdv6conf .= dhcpdkey($dhcpv6ifconf);
1860
			$dhcpdv6conf .= dhcpdzones($ddns_zones);
1861
		}
1862

    
1863
		if (($config['dhcpdv6'][$dhcpv6if]['ramode'] != "unmanaged") &&
1864
		    (isset($config['interfaces'][$dhcpv6if]['enable']) ||
1865
		    preg_match("/poes/", $dhcpv6if))) {
1866
			if (preg_match("/poes/si", $dhcpv6if)) {
1867
				/* magic here */
1868
				$dhcpdv6ifs = array_merge($dhcpdv6ifs, get_pppoes_child_interfaces($dhcpv6if));
1869
			} else {
1870
				$realif = get_real_interface($dhcpv6if, "inet6");
1871
				if (stristr("$realif", "bridge")) {
1872
					$mac = get_interface_mac($realif);
1873
					$v6address = generate_ipv6_from_mac($mac);
1874
					/* Create link local address for bridges */
1875
					mwexec("/sbin/ifconfig {$realif} inet6 {$v6address}");
1876
				}
1877
				$realif = escapeshellcmd($realif);
1878
				$dhcpdv6ifs[] = $realif;
1879
			}
1880
		}
1881
	}
1882

    
1883
	if ($nsupdate) {
1884
		$dhcpdv6conf .= "ddns-update-style interim;\n";
1885
		$dhcpdv6conf .= "update-static-leases on;\n";
1886
	} else {
1887
		$dhcpdv6conf .= "ddns-update-style none;\n";
1888
	}
1889

    
1890
	/* write dhcpdv6.conf */
1891
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf", $dhcpdv6conf)) {
1892
		log_error("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1893
		if (platform_booting()) {
1894
			printf("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1895
		}
1896
		unset($dhcpdv6conf);
1897
		return 1;
1898
	}
1899
	unset($dhcpdv6conf);
1900

    
1901
	/* create an empty leases v6 database */
1902
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases")) {
1903
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1904
	}
1905

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

    
1910
	/* fire up dhcpd in a chroot */
1911
	if (count($dhcpdv6ifs) > 0) {
1912
		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 " .
1913
			join(" ", $dhcpdv6ifs));
1914
		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");
1915
	}
1916
	if (platform_booting()) {
1917
		print gettext("done.") . "\n";
1918
	}
1919

    
1920
	return 0;
1921
}
1922

    
1923
function services_igmpproxy_configure($interface='') {
1924
	global $config, $g;
1925

    
1926
	if (!empty($interface) && is_array($config['igmpproxy']['igmpentry'])) { 
1927
		foreach ($config['igmpproxy']['igmpentry'] as $igmpentry) {
1928
			if ($igmpentry['ifname'] == $interface) {
1929
				$igmpinf = true;
1930
				break;
1931
			}
1932
		}
1933
		if (!$igmpinf) {
1934
			return false;
1935
		}
1936
	}
1937

    
1938
	if (!isset($config['igmpproxy']['enable'])) {
1939
		if (isvalidproc("igmpproxy")) {
1940
			log_error(gettext("Stopping IGMP Proxy service."));
1941
			killbyname("igmpproxy");
1942
		}
1943
		return true;
1944
	}
1945
	if (!is_array($config['igmpproxy']['igmpentry']) || (count($config['igmpproxy']['igmpentry']) == 0)) {
1946
		return false;
1947
	}
1948

    
1949
	if (platform_booting()) {
1950
		echo gettext("Starting IGMP Proxy service...");
1951
	}
1952

    
1953
	if (isvalidproc("igmpproxy")) {
1954
		log_error(gettext("Restarting IGMP Proxy service."));
1955
		killbyname("igmpproxy");
1956
	}
1957

    
1958
	$iflist = get_configured_interface_list();
1959

    
1960
	$igmpconf = <<<EOD
1961

    
1962
##------------------------------------------------------
1963
## Enable Quickleave mode (Sends Leave instantly)
1964
##------------------------------------------------------
1965
quickleave
1966

    
1967
EOD;
1968

    
1969
	foreach ($config['igmpproxy']['igmpentry'] as $igmpcf) {
1970
		if (empty($config['interfaces'][$igmpcf['ifname']]['ipaddr'])) {
1971
			continue;
1972
		}
1973
		unset($iflist[$igmpcf['ifname']]);
1974
		$realif = get_real_interface($igmpcf['ifname']);
1975
		if (empty($igmpcf['threshold'])) {
1976
			$threshld = 1;
1977
		} else {
1978
			$threshld = $igmpcf['threshold'];
1979
		}
1980
		$igmpconf .= "phyint {$realif} {$igmpcf['type']} ratelimit 0 threshold {$threshld}\n";
1981

    
1982
		if ($igmpcf['address'] <> "") {
1983
			$item = explode(" ", $igmpcf['address']);
1984
			foreach ($item as $iww) {
1985
				$igmpconf .= "altnet {$iww}\n";
1986
			}
1987
		}
1988
		$igmpconf .= "\n";
1989
		if ($igmpcf['type'] == 'upstream') {
1990
		       $upstream = true;	
1991
		} else {
1992
		       $downstream = true;	
1993
		}
1994
	}
1995
	foreach ($iflist as $ifn) {
1996
		$realif = get_real_interface($ifn);
1997
		$igmpconf .= "phyint {$realif} disabled\n";
1998
	}
1999
	$igmpconf .= "\n";
2000

    
2001
	if (!$upstream || !$downstream) {
2002
		log_error(gettext("Could not find upstream or downstream IGMP Proxy interfaces!"));
2003
		return;
2004
	}
2005

    
2006
	$igmpfl = fopen($g['varetc_path'] . "/igmpproxy.conf", "w");
2007
	if (!$igmpfl) {
2008
		log_error(gettext("Could not write IGMP Proxy configuration file!"));
2009
		return;
2010
	}
2011
	fwrite($igmpfl, $igmpconf);
2012
	fclose($igmpfl);
2013
	unset($igmpconf);
2014

    
2015
	if (isset($config['syslog']['igmpxverbose'])) {
2016
		mwexec_bg("/usr/local/sbin/igmpproxy -v {$g['varetc_path']}/igmpproxy.conf");
2017
	} else {
2018
		mwexec_bg("/usr/local/sbin/igmpproxy {$g['varetc_path']}/igmpproxy.conf");
2019
	}
2020

    
2021
	log_error(gettext("Started IGMP Proxy service."));
2022

    
2023
	if (platform_booting()) {
2024
		echo gettext("done.") . "\n";
2025
	}
2026

    
2027
	return true;
2028
}
2029

    
2030
function services_dhcrelay_configure() {
2031
	global $config, $g;
2032

    
2033
	if (isset($config['system']['developerspew'])) {
2034
		$mt = microtime();
2035
		echo "services_dhcrelay_configure() being called $mt\n";
2036
	}
2037

    
2038
	/* kill any running dhcrelay */
2039
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
2040

    
2041
	init_config_arr(array('dhcrelay'));
2042
	$dhcrelaycfg = &$config['dhcrelay'];
2043

    
2044
	/* DHCPRelay enabled on any interfaces? */
2045
	if (!isset($dhcrelaycfg['enable'])) {
2046
		return 0;
2047
	}
2048

    
2049
	/* Start/Restart DHCP Relay, if a CARP VIP is set, check its status and act
2050
	* appropriately. */
2051
	if (isset($dhcrelaycfg['carpstatusvip']) && ($dhcrelaycfg['carpstatusvip'] != "none")) {
2052
		$status = get_carp_interface_status($dhcrelaycfg['carpstatusvip']);
2053
		switch (strtoupper($status)) {
2054
			// Do not start DHCP Relay service if the VIP is in BACKUP or INIT state.
2055
			case "BACKUP":
2056
			case "INIT":
2057
				log_error("Stopping DHCP Relay (CARP BACKUP/INIT)");
2058
				return 0;
2059
				break;
2060
			// Start the service if the VIP is MASTER state.
2061
			case "MASTER":
2062
			// Assume it's up if the status can't be determined.
2063
			default:
2064
				break;
2065
		}
2066
	}
2067

    
2068
	if (platform_booting()) {
2069
		echo gettext("Starting DHCP Relay service...");
2070
	} else {
2071
		sleep(1);
2072
	}
2073

    
2074
	$iflist = get_configured_interface_list();
2075

    
2076
	$dhcrelayifs = array();
2077
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
2078
	foreach ($dhcifaces as $dhcrelayif) {
2079
		if (!isset($iflist[$dhcrelayif])) {
2080
			continue;
2081
		}
2082

    
2083
		if (get_interface_ip($dhcrelayif)) {
2084
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
2085
		}
2086
	}
2087
	$dhcrelayifs = array_unique($dhcrelayifs);
2088

    
2089
	/*
2090
	 * In order for the relay to work, it needs to be active
2091
	 * on the interface in which the destination server sits.
2092
	 */
2093
	$srvips = explode(",", $dhcrelaycfg['server']);
2094
	if (!is_array($srvips)) {
2095
		log_error(gettext("No destination IP has been configured!"));
2096
		return;
2097
	}
2098
	$srvifaces = array();
2099
	foreach ($srvips as $srcidx => $srvip) {
2100
		$destif = guess_interface_from_ip($srvip);
2101
		if (!empty($destif) && !is_pseudo_interface($destif)) {
2102
			$srvifaces[] = $destif;
2103
		}
2104
	}
2105
	$srvifaces = array_unique($srvifaces);
2106

    
2107
	/* Check for relays in the same subnet as clients so they can bind for
2108
	 * either direction (up or down) */
2109
	$srvrelayifs = array_intersect($dhcrelayifs, $srvifaces);
2110

    
2111
	/* The server interface(s) should not be in this list */
2112
	$dhcrelayifs = array_diff($dhcrelayifs, $srvifaces);
2113

    
2114
	/* Remove the dual-role interfaces from up and down lists */
2115
	$srvifaces = array_diff($srvifaces, $srvrelayifs);
2116
	$dhcrelayifs = array_diff($dhcrelayifs, $srvrelayifs);
2117

    
2118
	/* fire up dhcrelay */
2119
	if (empty($dhcrelayifs) && empty($srvrelayifs)) {
2120
		log_error(gettext("No suitable downstream interfaces found for running dhcrelay!"));
2121
		return; /* XXX */
2122
	}
2123
	if (empty($srvifaces) && empty($srvrelayifs)) {
2124
		log_error(gettext("No suitable upstream interfaces found for running dhcrelay!"));
2125
		return; /* XXX */
2126
	}
2127

    
2128
	$cmd = "/usr/local/sbin/dhcrelay";
2129

    
2130
	if (!empty($dhcrelayifs)) {
2131
		$cmd .= " -id " . implode(" -id ", $dhcrelayifs);
2132
	}
2133
	if (!empty($srvifaces)) {
2134
		$cmd .= " -iu " . implode(" -iu ", $srvifaces);
2135
	}
2136
	if (!empty($srvrelayifs)) {
2137
		$cmd .= " -i " . implode(" -i ", $srvrelayifs);
2138
	}
2139

    
2140
	if (isset($dhcrelaycfg['agentoption'])) {
2141
		$cmd .= " -a -m replace";
2142
	}
2143

    
2144
	$cmd .= " " . implode(" ", $srvips);
2145
	mwexec($cmd);
2146
	unset($cmd);
2147

    
2148
	return 0;
2149
}
2150

    
2151
function services_dhcrelay6_configure() {
2152
	global $config, $g;
2153

    
2154
	if (isset($config['system']['developerspew'])) {
2155
		$mt = microtime();
2156
		echo "services_dhcrelay6_configure() being called $mt\n";
2157
	}
2158

    
2159
	/* kill any running dhcrelay */
2160
	killbypid("{$g['varrun_path']}/dhcrelay6.pid");
2161

    
2162
	init_config_arr(array('dhcrelay6'));
2163
	$dhcrelaycfg = &$config['dhcrelay6'];
2164

    
2165
	/* DHCPv6 Relay enabled on any interfaces? */
2166
	if (!isset($dhcrelaycfg['enable'])) {
2167
		return 0;
2168
	}
2169

    
2170
	/* Start/Restart DHCPv6 Relay, if a CARP VIP is set, check its status and act
2171
	* appropriately. */
2172
	if (isset($dhcrelaycfg['carpstatusvip']) && ($dhcrelaycfg['carpstatusvip'] != "none")) {
2173
		$status = get_carp_interface_status($dhcrelaycfg['carpstatusvip']);
2174
		switch (strtoupper($status)) {
2175
			// Do not start DHCP Relay service if the VIP is in BACKUP or INIT state.
2176
			case "BACKUP":
2177
			case "INIT":
2178
				log_error("Stopping DHCPv6 Relay (CARP BACKUP/INIT)");
2179
				return 0;
2180
				break;
2181
			// Start the service if the VIP is MASTER state.
2182
			case "MASTER":
2183
			// Assume it's up if the status can't be determined.
2184
			default:
2185
				break;
2186
		}
2187
	}
2188

    
2189
	if (platform_booting()) {
2190
		echo gettext("Starting DHCPv6 Relay service...");
2191
	} else {
2192
		sleep(1);
2193
	}
2194

    
2195
	$iflist = get_configured_interface_list();
2196

    
2197
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
2198
	foreach ($dhcifaces as $dhcrelayif) {
2199
		if (!isset($iflist[$dhcrelayif])) {
2200
			continue;
2201
		}
2202

    
2203
		if (get_interface_ipv6($dhcrelayif)) {
2204
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
2205
		}
2206
	}
2207
	$dhcrelayifs = array_unique($dhcrelayifs);
2208

    
2209
	/*
2210
	 * In order for the relay to work, it needs to be active
2211
	 * on the interface in which the destination server sits.
2212
	 */
2213
	$srvips = explode(",", $dhcrelaycfg['server']);
2214
	$srvifaces = array();
2215
	foreach ($srvips as $srcidx => $srvip) {
2216
		$destif = guess_interface_from_ip($srvip);
2217
		if (!empty($destif) && !is_pseudo_interface($destif)) {
2218
			$srvifaces[] = "{$srvip}%{$destif}";
2219
		}
2220
	}
2221

    
2222
	/* fire up dhcrelay */
2223
	if (empty($dhcrelayifs) || empty($srvifaces)) {
2224
		log_error(gettext("No suitable interface found for running dhcrelay -6!"));
2225
		return; /* XXX */
2226
	}
2227

    
2228
	$cmd = "/usr/local/sbin/dhcrelay -6 -pf \"{$g['varrun_path']}/dhcrelay6.pid\"";
2229
	foreach ($dhcrelayifs as $dhcrelayif) {
2230
		$cmd .= " -l {$dhcrelayif}";
2231
	}
2232
	foreach ($srvifaces as $srviface) {
2233
		$cmd .= " -u \"{$srviface}\"";
2234
	}
2235
	mwexec($cmd);
2236
	unset($cmd);
2237

    
2238
	return 0;
2239
}
2240

    
2241
function services_dyndns_configure_client($conf) {
2242

    
2243
	if (!isset($conf['enable'])) {
2244
		return;
2245
	}
2246

    
2247
	/* load up the dyndns.class */
2248
	require_once("dyndns.class");
2249

    
2250
	$dns = new updatedns($dnsService = $conf['type'],
2251
		$dnsHost = $conf['host'],
2252
		$dnsDomain = $conf['domainname'],
2253
		$dnsUser = $conf['username'],
2254
		$dnsPass = $conf['password'],
2255
		$dnsWildcard = $conf['wildcard'],
2256
		$dnsProxied = $conf['proxied'],
2257
		$dnsMX = $conf['mx'],
2258
		$dnsIf = "{$conf['interface']}",
2259
		$dnsBackMX = NULL,
2260
		$dnsServer = NULL,
2261
		$dnsPort = NULL,
2262
		$dnsUpdateURL = "{$conf['updateurl']}",
2263
		$forceUpdate = $conf['force'],
2264
		$dnsZoneID = $conf['zoneid'],
2265
		$dnsTTL = $conf['ttl'],
2266
		$dnsResultMatch = "{$conf['resultmatch']}",
2267
		$dnsRequestIf = "{$conf['requestif']}",
2268
		$dnsMaxCacheAge = $conf['maxcacheage'],
2269
		$dnsID = "{$conf['id']}",
2270
		$dnsVerboseLog = $conf['verboselog'],
2271
		$curlIpresolveV4 = $conf['curl_ipresolve_v4'],
2272
		$curlSslVerifypeer = $conf['curl_ssl_verifypeer'],
2273
		$curlProxy = $conf['curl_proxy']);
2274
}
2275

    
2276
function services_dyndns_configure($int = "") {
2277
	global $config, $g;
2278
	if (isset($config['system']['developerspew'])) {
2279
		$mt = microtime();
2280
		echo "services_dyndns_configure() being called $mt\n";
2281
	}
2282

    
2283
	if (isset($config['dyndnses']['dyndns']) && is_array($config['dyndnses']['dyndns'])) {
2284
		$dyndnscfg = $config['dyndnses']['dyndns'];
2285
	} else {
2286
		return 0;
2287
	}
2288
	$gwgroups = return_gateway_groups_array(true);
2289
	if (is_array($dyndnscfg)) {
2290
		if (platform_booting()) {
2291
			echo gettext("Starting DynDNS clients...");
2292
		}
2293

    
2294
		foreach ($dyndnscfg as $dyndns) {
2295
			/*
2296
			 * If it's using a gateway group, check if interface is
2297
			 * the active gateway for that group
2298
			 */
2299
			$group_int = '';
2300
			$friendly_group_int = '';
2301
			$gwgroup_member = false;
2302
			if (is_array($gwgroups[$dyndns['interface']])) {
2303
				if (!empty($gwgroups[$dyndns['interface']][0]['vip'])) {
2304
					$group_int = $gwgroups[$dyndns['interface']][0]['vip'];
2305
				} else {
2306
					$group_int = $gwgroups[$dyndns['interface']][0]['int'];
2307
					$friendly_group_int =
2308
					    convert_real_interface_to_friendly_interface_name(
2309
						$group_int);
2310
					if (!empty($int)) {
2311
						$gwgroup_member =
2312
						    interface_gateway_group_member(get_real_interface($int),
2313
						    $dyndns['interface']);
2314
					}
2315
				}
2316
			}
2317
			if ((empty($int)) || ($int == $dyndns['interface']) || $gwgroup_member ||
2318
			    ($int == $group_int) || ($int == $friendly_group_int)) {
2319
				$dyndns['verboselog'] = isset($dyndns['verboselog']);
2320
				$dyndns['curl_ipresolve_v4'] = isset($dyndns['curl_ipresolve_v4']);
2321
				$dyndns['curl_ssl_verifypeer'] = isset($dyndns['curl_ssl_verifypeer']);
2322
				$dyndns['proxied'] = isset($dyndns['proxied']);
2323
				$dyndns['wildcard'] = isset($dyndns['wildcard']);
2324
				services_dyndns_configure_client($dyndns);
2325
				sleep(1);
2326
			}
2327
		}
2328

    
2329
		if (platform_booting()) {
2330
			echo gettext("done.") . "\n";
2331
		}
2332
	}
2333

    
2334
	return 0;
2335
}
2336

    
2337
function dyndnsCheckIP($int) {
2338
	global $config, $factory_default_checkipservice;
2339
	$ip_address = get_interface_ip($int);
2340
	if (is_private_ip($ip_address)) {
2341
		$gateways_status = return_gateways_status(true);
2342
		// If the gateway for this interface is down, then the external check cannot work.
2343
		// Avoid the long wait for the external check to timeout.
2344
		if (stristr($gateways_status[$config['interfaces'][$int]['gateway']]['status'], "down")) {
2345
			return "down";
2346
		}
2347

    
2348
		// Append the factory default check IP service to the list (if not disabled).
2349
		if (!isset($config['checkipservices']['disable_factory_default'])) {
2350
			if (!is_array($config['checkipservices'])) {
2351
				$config['checkipservices'] = array();
2352
			}
2353
			if (!is_array($config['checkipservices']['checkipservice'])) {
2354
				$config['checkipservices']['checkipservice'] = array();
2355
			}
2356
			$config['checkipservices']['checkipservice'][] = $factory_default_checkipservice;
2357
		}
2358

    
2359
		// Use the first enabled check IP service as the default.
2360
		if (is_array($config['checkipservices']['checkipservice'])) {
2361
			foreach ($config['checkipservices']['checkipservice'] as $i => $checkipservice) {
2362
				if (isset($checkipservice['enable'])) {
2363
					$url = $checkipservice['url'];
2364
					$username = $checkipservice['username'];
2365
					$password = $checkipservice['password'];
2366
					$verifysslpeer = isset($checkipservice['verifysslpeer']);
2367
					$curl_proxy = isset($checkipservice['curl_proxy']);
2368
					break;
2369
				}
2370
			}
2371
		}
2372

    
2373
		$hosttocheck = $url;
2374
		$ip_ch = curl_init($hosttocheck);
2375
		curl_setopt($ip_ch, CURLOPT_RETURNTRANSFER, 1);
2376
		curl_setopt($ip_ch, CURLOPT_SSL_VERIFYPEER, $verifysslpeer);
2377
		curl_setopt($ip_ch, CURLOPT_INTERFACE, 'host!' . $ip_address);
2378
		curl_setopt($ip_ch, CURLOPT_CONNECTTIMEOUT, '30');
2379
		curl_setopt($ip_ch, CURLOPT_TIMEOUT, 120);
2380
		curl_setopt($ip_ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
2381
		curl_setopt($ip_ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
2382
		curl_setopt($ip_ch, CURLOPT_USERPWD, "{$username}:{$password}");
2383
		if ($curl_proxy) {
2384
			set_curlproxy($ip_ch);
2385
		}
2386
		$ip_result_page = curl_exec($ip_ch);
2387
		curl_close($ip_ch);
2388
		$ip_result_decoded = urldecode($ip_result_page);
2389
		preg_match('=Current IP Address: (.*)</body>=siU', $ip_result_decoded, $matches);
2390

    
2391
		if ($matches[1]) {
2392
			$parsed_ip = trim($matches[1]);
2393
		} else {
2394
			$parsed_ip = trim($ip_result_decoded);
2395
		}
2396

    
2397
		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);
2398
		if ($matches[0]) {
2399
			$ip_address = $matches[0];
2400
		}
2401
	}
2402
	return $ip_address;
2403
}
2404

    
2405
function services_dnsmasq_configure($restart_dhcp = true) {
2406
	global $config, $g;
2407
	$return = 0;
2408

    
2409
	// hard coded args: will be removed to avoid duplication if specified in custom_options
2410
	$standard_args = array(
2411
		"dns-forward-max" => "--dns-forward-max=5000",
2412
		"cache-size" => "--cache-size=10000",
2413
		"local-ttl" => "--local-ttl=1"
2414
	);
2415

    
2416

    
2417
	if (isset($config['system']['developerspew'])) {
2418
		$mt = microtime();
2419
		echo "services_dnsmasq_configure() being called $mt\n";
2420
	}
2421

    
2422
	/* kill any running dnsmasq */
2423
	if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) {
2424
		sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
2425
	}
2426

    
2427
	if (isset($config['dnsmasq']['enable'])) {
2428

    
2429
		if (platform_booting()) {
2430
			echo gettext("Starting DNS forwarder...");
2431
		} else {
2432
			sleep(1);
2433
		}
2434

    
2435
		/* generate hosts file */
2436
		if (system_hosts_generate() != 0) {
2437
			$return = 1;
2438
		}
2439

    
2440
		$args = "";
2441

    
2442
		if (isset($config['dnsmasq']['regdhcp'])) {
2443
			$args .= " --dhcp-hostsfile={$g['etc_path']}/hosts ";
2444
		}
2445

    
2446
		/* Setup listen port, if non-default */
2447
		if (is_port($config['dnsmasq']['port'])) {
2448
			$args .= " --port={$config['dnsmasq']['port']} ";
2449
		}
2450

    
2451
		$listen_addresses = "";
2452
		if (isset($config['dnsmasq']['interface'])) {
2453
			$interfaces = explode(",", $config['dnsmasq']['interface']);
2454
			foreach ($interfaces as $interface) {
2455
				$if = get_real_interface($interface);
2456
				if (does_interface_exist($if)) {
2457
					$laddr = get_interface_ip($interface);
2458
					if (is_ipaddrv4($laddr)) {
2459
						$listen_addresses .= " --listen-address={$laddr} ";
2460
					}
2461
					$laddr6 = get_interface_ipv6($interface);
2462
					if (is_ipaddrv6($laddr6) && !isset($config['dnsmasq']['strictbind'])) {
2463
						/*
2464
						 * XXX: Since dnsmasq does not support link-local address
2465
						 * with scope specified. These checks are being done.
2466
						 */
2467
						if (is_linklocal($laddr6) && strstr($laddr6, "%")) {
2468
							$tmpaddrll6 = explode("%", $laddr6);
2469
							$listen_addresses .= " --listen-address={$tmpaddrll6[0]} ";
2470
						} else {
2471
							$listen_addresses .= " --listen-address={$laddr6} ";
2472
						}
2473
					}
2474
				}
2475
			}
2476
			if (!empty($listen_addresses)) {
2477
				$args .= " {$listen_addresses} ";
2478
				if (isset($config['dnsmasq']['strictbind'])) {
2479
					$args .= " --bind-interfaces ";
2480
				}
2481
			}
2482
		}
2483

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

    
2491
			// Build an array of domain overrides to help in checking for matches.
2492
			$override_a = array();
2493
			if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2494
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2495
					$override_a[$override['domain']] = "y";
2496
				}
2497
			}
2498

    
2499
			// Build an array of the private reverse lookup domain names
2500
			$reverse_domain_a = array("10.in-addr.arpa", "168.192.in-addr.arpa");
2501
			// Unfortunately the 172.16.0.0/12 range does not map nicely to the in-addr.arpa scheme.
2502
			for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) {
2503
				$reverse_domain_a[] = "$subnet_num.172.in-addr.arpa";
2504
			}
2505

    
2506
			// Set the --server parameter to nowhere for each reverse domain name that was not specifically specified in a domain override.
2507
			foreach ($reverse_domain_a as $reverse_domain) {
2508
				if (!isset($override_a[$reverse_domain])) {
2509
					$args .= " --server=/$reverse_domain/ ";
2510
				}
2511
			}
2512
			unset($override_a);
2513
			unset($reverse_domain_a);
2514
		}
2515

    
2516
		/* Setup forwarded domains */
2517
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2518
			foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2519
				if ($override['ip'] == "!") {
2520
					$override['ip'] = "";
2521
				}
2522
				$args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
2523
			}
2524
		}
2525

    
2526
		/* Allow DNS Rebind for forwarded domains */
2527
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2528
			if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2529
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2530
					$args .= ' --rebind-domain-ok=/' . $override['domain'] . '/ ';
2531
				}
2532
			}
2533
		}
2534

    
2535
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2536
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2537
		}
2538

    
2539
		if (isset($config['dnsmasq']['strict_order'])) {
2540
			$args .= " --strict-order ";
2541
		}
2542

    
2543
		if (isset($config['dnsmasq']['domain_needed'])) {
2544
			$args .= " --domain-needed ";
2545
		}
2546

    
2547
		if ($config['dnsmasq']['custom_options']) {
2548
			foreach (preg_split('/\s+/', $config['dnsmasq']['custom_options']) as $c) {
2549
				$args .= " " . escapeshellarg("--{$c}");
2550
				$p = explode('=', $c);
2551
				if (array_key_exists($p[0], $standard_args)) {
2552
					unset($standard_args[$p[0]]);
2553
				}
2554
			}
2555
		}
2556
		$args .= ' ' . implode(' ', array_values($standard_args));
2557

    
2558
		/* run dnsmasq. Use "-C /dev/null" since we use command line args only (Issue #6730) */
2559
		$cmd = "/usr/local/sbin/dnsmasq --all-servers -C /dev/null {$dns_rebind} {$args}";
2560
		//log_error("dnsmasq command: {$cmd}");
2561
		mwexec_bg($cmd);
2562
		unset($args);
2563

    
2564
		system_dhcpleases_configure();
2565

    
2566
		if (platform_booting()) {
2567
			echo gettext("done.") . "\n";
2568
		}
2569
	}
2570

    
2571
	if (!platform_booting() && $restart_dhcp) {
2572
		if (services_dhcpd_configure() != 0) {
2573
			$return = 1;
2574
		}
2575
	}
2576

    
2577
	return $return;
2578
}
2579

    
2580
function services_unbound_configure($restart_dhcp = true, $interface = '') {
2581
	global $config, $g;
2582
	$return = 0;
2583

    
2584
	if (isset($config['system']['developerspew'])) {
2585
		$mt = microtime();
2586
		echo "services_unbound_configure() being called $mt\n";
2587
	}
2588

    
2589
	if (!empty($interface) && isset($config['unbound']['enable']) &&
2590
	    !in_array($interface, explode(',', $config['unbound']['active_interface'])) &&
2591
	    !in_array($interface, explode(',', $config['unbound']['outgoing_interface']))) {
2592
		return $return;
2593
	}
2594

    
2595
	if (isset($config['unbound']['enable'])) {
2596
		require_once('/etc/inc/unbound.inc');
2597

    
2598
		/* Stop Unbound using TERM */
2599
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2600
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
2601
		}
2602

    
2603
		/* If unbound is still running, wait up to 30 seconds for it to terminate. */
2604
		for ($i=1; $i <= 30; $i++) {
2605
			if (is_process_running('unbound')) {
2606
				sleep(1);
2607
			}
2608
		}
2609

    
2610
		$python_mode = false;
2611
		if (isset($config['unbound']['python']) && !empty($config['unbound']['python_script'])) {
2612
			$python_mode = true;
2613
		}
2614

    
2615
		/* Include any additional functions as defined by python script include file */
2616
		if (file_exists("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc")) {
2617
			exec("/usr/local/bin/php -l " . escapeshellarg("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc")
2618
				. " 2>&1", $py_output, $py_retval);
2619
			if ($py_retval == 0) {
2620
				require_once("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc");
2621
			}
2622
		}
2623

    
2624
		/* DNS Resolver python integration */
2625
		if ($python_mode) {
2626
			if (!is_dir("{$g['unbound_chroot_path']}/dev")) {
2627
				safe_mkdir("{$g['unbound_chroot_path']}/dev");
2628
			}
2629
			$status = "/sbin/mount | /usr/bin/grep " .  escapeshellarg("{$g['unbound_chroot_path']}/dev");
2630
			if (!trim($status)) {
2631
				exec("/sbin/mount -t devfs devfs " . escapeshellarg("{$g['unbound_chroot_path']}/dev"));
2632
			}
2633
		} else {
2634
			if (is_dir("{$g['unbound_chroot_path']}/dev")) {
2635
				exec("/sbin/umount -f " . escapeshellarg("{$g['unbound_chroot_path']}/dev"));
2636
			}
2637
		}
2638
		$base_folder = '/usr/local';
2639
		foreach (array('/bin', '/lib') as $dir) {
2640
			$validate = exec("/sbin/mount | /usr/bin/grep " . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir} (nullfs") . " 2>&1");
2641
			if ($python_mode) {
2642

    
2643
				// Add DNS Resolver python integration
2644
				if (empty($validate)) {
2645
					if (!is_dir("{$g['unbound_chroot_path']}{$base_folder}{$dir}")) {
2646
						safe_mkdir("{$g['unbound_chroot_path']}{$base_folder}{$dir}");
2647
					}
2648
					$output = $retval = '';
2649
					exec("/sbin/mount_nullfs -o ro " . escapeshellarg("/usr/local{$dir}") . ' '
2650
					    . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir}") . " 2>&1", $output, $retval);
2651

    
2652
					// Disable Unbound python on mount failure
2653
					if ($retval != 0) {
2654
						$config['unbound']['python'] = '';
2655
						$log_msg = "[Unbound-pymod]: Disabling Unbound python due to failed mount";
2656
						write_config($log_msg);
2657
						log_error($log_msg);
2658
					}
2659
				}
2660
			}
2661

    
2662
			// Remove DNS Resolver python integration
2663
			elseif (!empty($validate)) {
2664
				exec("/sbin/umount -t nullfs " . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir}") . " 2>&1", $output, $retval);
2665
				if ($retval == 0) {
2666
					foreach (array( "/usr/local{$dir}", '/usr/local', '/usr') as $folder) {
2667
						if (!empty($g['unbound_chroot_path']) && $g['unbound_chroot_path'] != '/' && is_dir("{$g['unbound_chroot_path']}{$folder}")) {
2668
							@rmdir(escapeshellarg("{$g['unbound_chroot_path']}{$folder}"));
2669
						}
2670

    
2671
						// Delete remaining subfolders on next loop
2672
						if ($dir == '/bin') {
2673
							break;
2674
						}
2675
					}
2676
				}
2677
				else {
2678
					log_error("[Unbound-pymod]: Failed to unmount!");
2679
				}
2680
			}
2681
		}
2682

    
2683
		if (platform_booting()) {
2684
			echo gettext("Starting DNS Resolver...");
2685
		} else {
2686
			sleep(1);
2687
		}
2688

    
2689
		/* generate hosts file */
2690
		if (system_hosts_generate() != 0) {
2691
			$return = 1;
2692
		}
2693

    
2694
		/* Check here for dhcp6 complete - wait upto 10 seconds */
2695
		if($config['interfaces']["wan"]['ipaddrv6'] == 'dhcp6') {
2696
			$wanif = get_real_interface("wan", "inet6");
2697
			if (platform_booting()) {
2698
				for ($i=1; $i <= 10; $i++) {
2699
					if (!file_exists("/tmp/{$wanif}_dhcp6_complete")) {
2700
						log_error(gettext("Unbound start waiting on dhcp6c."));
2701
						sleep(1);
2702
					} else {
2703
						unlink_if_exists("/tmp/{$wanif}_dhcp6_complete");
2704
						log_error(gettext("dhcp6 init complete. Continuing"));
2705
						break;
2706
					}
2707
				}
2708
			}
2709
		}
2710

    
2711
		sync_unbound_service();
2712
		if (platform_booting()) {
2713
			log_error(gettext("sync unbound done."));
2714
			echo gettext("done.") . "\n";
2715
		}
2716

    
2717
		system_dhcpleases_configure();
2718
	} else {
2719
		/* kill Unbound since it should not be enabled */
2720
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2721
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "KILL");
2722
		}
2723
	}
2724

    
2725
	if (!platform_booting() && $restart_dhcp) {
2726
		if (services_dhcpd_configure() != 0) {
2727
			$return = 1;
2728
		}
2729
	}
2730

    
2731
	return $return;
2732
}
2733

    
2734
function services_snmpd_configure() {
2735
	global $config, $g;
2736
	if (isset($config['system']['developerspew'])) {
2737
		$mt = microtime();
2738
		echo "services_snmpd_configure() being called $mt\n";
2739
	}
2740

    
2741
	/* kill any running snmpd */
2742
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
2743
	sleep(2);
2744
	if (is_process_running("bsnmpd")) {
2745
		mwexec("/usr/bin/killall bsnmpd", true);
2746
	}
2747

    
2748
	if (isset($config['snmpd']['enable'])) {
2749

    
2750
		if (platform_booting()) {
2751
			echo gettext("Starting SNMP daemon... ");
2752
		}
2753

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

    
2759
		/* generate snmpd.conf */
2760
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
2761
		if (!$fd) {
2762
			printf(gettext("Error: cannot open snmpd.conf in services_snmpd_configure().%s"), "\n");
2763
			return 1;
2764
		}
2765

    
2766

    
2767
		$snmpdconf = <<<EOD
2768
location := "{$config['snmpd']['syslocation']}"
2769
contact := "{$config['snmpd']['syscontact']}"
2770
read := "{$config['snmpd']['rocommunity']}"
2771

    
2772
EOD;
2773

    
2774
/* No docs on what write strings do there so disable for now.
2775
		if (isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])) {
2776
			$snmpdconf .= <<<EOD
2777
# write string
2778
write := "{$config['snmpd']['rwcommunity']}"
2779

    
2780
EOD;
2781
		}
2782
*/
2783

    
2784

    
2785
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2786
			$snmpdconf .= <<<EOD
2787
# SNMP Trap support.
2788
traphost := {$config['snmpd']['trapserver']}
2789
trapport := {$config['snmpd']['trapserverport']}
2790
trap := "{$config['snmpd']['trapstring']}"
2791

    
2792

    
2793
EOD;
2794
		}
2795

    
2796
		$sysDescr = "{$g['product_label']} {$config['system']['hostname']}.{$config['system']['domain']}" .
2797
			" {$g['product_version_string']} " . php_uname("s") .
2798
			" " . php_uname("r") . " " . php_uname("m");
2799

    
2800
		$snmpdconf .= <<<EOD
2801
system := 1     # pfSense
2802
%snmpd
2803
sysDescr			= "{$sysDescr}"
2804
begemotSnmpdDebugDumpPdus       = 2
2805
begemotSnmpdDebugSyslogPri      = 7
2806
begemotSnmpdCommunityString.0.1 = $(read)
2807

    
2808
EOD;
2809

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

    
2815
EOD;
2816
		}
2817
*/
2818

    
2819

    
2820
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2821
			$snmpdconf .= <<<EOD
2822
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
2823
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
2824
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
2825

    
2826
EOD;
2827
		}
2828

    
2829

    
2830
		$snmpdconf .= <<<EOD
2831
begemotSnmpdCommunityDisable    = 1
2832

    
2833
EOD;
2834

    
2835
		$bind_to_ips = array();
2836
		$bind_to_ip6s = array();
2837
		if (isset($config['snmpd']['bindip'])) {
2838
			if (!isset($config['snmpd']['ipprotocol']) ||
2839
			    (isset($config['snmpd']['ipprotocol']) &&
2840
			    strstr($config['snmpd']['ipprotocol'], "4"))) {
2841
				$inet4 = true;
2842
			}
2843
			if (isset($config['snmpd']['ipprotocol']) &&
2844
			    strstr($config['snmpd']['ipprotocol'], "6")) {
2845
				$inet6 = true;
2846
			}
2847
			foreach (explode(",", $config['snmpd']['bindip']) as $bind_to_ip) {
2848
				if (is_ipaddr($bind_to_ip)) {
2849
					$bind_to_ips[] = $bind_to_ip;
2850
				} else {
2851
					$if = get_real_interface($bind_to_ip);
2852
					if (does_interface_exist($if)) {
2853
						if ($inet4) {
2854
							$bindip = get_interface_ip($bind_to_ip);
2855
							if (is_ipaddrv4($bindip)) {
2856
								$bind_to_ips[] = $bindip;
2857
							}
2858
						}
2859
						if ($inet6) {
2860
							$bindip6 = get_interface_ipv6($bind_to_ip);
2861
							if (is_ipaddrv6($bindip6)) {
2862
								$bind_to_ip6s[] = $bindip6;
2863
							}
2864
						}
2865
					}
2866
				}
2867
			}
2868
		}
2869
		if (!count($bind_to_ips) && $inet4) {
2870
			$bind_to_ips = array("0.0.0.0");
2871
		}
2872
		if (!count($bind_to_ip6s) && $inet6) {
2873
			$bind_to_ip6s = array("::");
2874
		}
2875

    
2876
		if (is_port($config['snmpd']['pollport'])) {
2877
			foreach ($bind_to_ips as $bind_to_ip) {
2878
				$snmpdconf .= <<<EOD
2879
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
2880

    
2881
EOD;
2882

    
2883
			}
2884
			foreach ($bind_to_ip6s as $bind_to_ip6) {
2885
				$bind_to_ip6 = ip6_to_asn1($bind_to_ip6);
2886
				$snmpdconf .= <<<EOD
2887
begemotSnmpdTransInetStatus.2.16.{$bind_to_ip6}{$config['snmpd']['pollport']}.1 = 4
2888

    
2889
EOD;
2890

    
2891
			}
2892
		}
2893

    
2894
		$snmpdconf .= <<<EOD
2895
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
2896
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
2897

    
2898
# These are bsnmp macros not php vars.
2899
sysContact      = $(contact)
2900
sysLocation     = $(location)
2901
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
2902

    
2903
snmpEnableAuthenTraps = 2
2904

    
2905
EOD;
2906

    
2907
		if (is_array($config['snmpd']['modules'])) {
2908
			if (isset($config['snmpd']['modules']['mibii'])) {
2909
			$snmpdconf .= <<<EOD
2910
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
2911

    
2912
EOD;
2913
			}
2914

    
2915
			if (isset($config['snmpd']['modules']['netgraph'])) {
2916
				$snmpdconf .= <<<EOD
2917
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
2918
%netgraph
2919
begemotNgControlNodeName = "snmpd"
2920

    
2921
EOD;
2922
			}
2923

    
2924
			if (isset($config['snmpd']['modules']['pf'])) {
2925
				$snmpdconf .= <<<EOD
2926
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
2927

    
2928
EOD;
2929
			}
2930

    
2931
			if (isset($config['snmpd']['modules']['hostres'])) {
2932
				$snmpdconf .= <<<EOD
2933
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
2934

    
2935
EOD;
2936
			}
2937

    
2938
			if (isset($config['snmpd']['modules']['bridge'])) {
2939
				$snmpdconf .= <<<EOD
2940
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
2941
# config must end with blank line
2942

    
2943
EOD;
2944
			}
2945
			if (isset($config['snmpd']['modules']['ucd'])) {
2946
				$snmpdconf .= <<<EOD
2947
begemotSnmpdModulePath."ucd"     = "/usr/local/lib/snmp_ucd.so"
2948

    
2949
EOD;
2950
			}
2951
			if (isset($config['snmpd']['modules']['regex'])) {
2952
				$snmpdconf .= <<<EOD
2953
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"
2954

    
2955
EOD;
2956
			}
2957
		}
2958

    
2959
		fwrite($fd, $snmpdconf);
2960
		fclose($fd);
2961
		unset($snmpdconf);
2962

    
2963
		/* run bsnmpd */
2964
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
2965
			" -p {$g['varrun_path']}/snmpd.pid");
2966

    
2967
		if (platform_booting()) {
2968
			echo gettext("done.") . "\n";
2969
		}
2970
	}
2971

    
2972
	return 0;
2973
}
2974

    
2975
function services_dnsupdate_process($int = "", $updatehost = "", $forced = false) {
2976
	global $config, $g;
2977
	if (isset($config['system']['developerspew'])) {
2978
		$mt = microtime();
2979
		echo "services_dnsupdate_process() being called $mt\n";
2980
	}
2981

    
2982
	/* Dynamic DNS updating active? */
2983
	if (!is_array($config['dnsupdates']['dnsupdate'])) {
2984
		return 0;
2985
	}
2986

    
2987
	$notify_text = "";
2988
	$gwgroups = return_gateway_groups_array(true);
2989
	foreach ($config['dnsupdates']['dnsupdate'] as $i => $dnsupdate) {
2990
		if (!isset($dnsupdate['enable'])) {
2991
			continue;
2992
		}
2993
		/*
2994
		 * If it's using a gateway group, check if interface is
2995
		 * the active gateway for that group
2996
		 */
2997
		$group_int = '';
2998
		$friendly_group_int = '';
2999
		$gwgroup_member = false;
3000
		if (is_array($gwgroups[$dnsupdate['interface']])) {
3001
			if (!empty($gwgroups[$dnsupdate['interface']][0]['vip'])) {
3002
				$group_int = $gwgroups[$dnsupdate['interface']][0]['vip'];
3003
			} else {
3004
				$group_int = $gwgroups[$dnsupdate['interface']][0]['int'];
3005
				$friendly_group_int =
3006
				    convert_real_interface_to_friendly_interface_name(
3007
					$group_int);
3008
				if (!empty($int)) {
3009
					$gwgroup_member =
3010
					    interface_gateway_group_member(get_real_interface($int),
3011
					    $dnsupdate['interface']);
3012
				}
3013
			}
3014
		}
3015
		if (!empty($int) && ($int != $dnsupdate['interface']) && !$gwgroup_member &&
3016
		    ($int != $group_int) && ($int != $friendly_group_int)) {
3017
			continue;
3018
		}
3019
		if (!empty($updatehost) && ($updatehost != $dnsupdate['host'])) {
3020
			continue;
3021
		}
3022

    
3023
		/* determine interface name */
3024
		$if = get_failover_interface($dnsupdate['interface']);
3025

    
3026
		/* Determine address to update and default binding address */
3027
		if (isset($dnsupdate['usepublicip'])) {
3028
			$wanip = dyndnsCheckIP($if);
3029
			if (is_private_ip($wanip)) {
3030
				log_error(sprintf(gettext(
3031
				    "phpDynDNS: Not updating %s A record because the public IP address cannot be determined."),
3032
				    $dnsupdate['host']));
3033
				continue;
3034
			}
3035
			$bindipv4 = get_interface_ip($if);
3036
		} else {
3037
			$wanip = get_interface_ip($if);
3038
			$bindipv4 = $wanip;
3039
		}
3040
		if (is_stf_interface($dnsupdate['interface'])) { 
3041
			$wanipv6 = get_interface_ipv6($dnsupdate['interface'] . '_stf');
3042
		} else {
3043
			$wanipv6 = get_interface_ipv6($if);
3044
		}
3045
		$bindipv6 = $wanipv6;
3046

    
3047
		/* Handle non-default interface bindings */
3048
		if ($dnsupdate['updatesource'] == "none") {
3049
			/* When empty, the directive will be omitted. */
3050
			$bindipv4 = "";
3051
			$bindipv6 = "";
3052
		} elseif (!empty($dnsupdate['updatesource'])) {
3053
			/* Find the alternate binding address */
3054
			$bindipv4 = get_interface_ip($dnsupdate['updatesource']);
3055
			if (is_stf_interface($dnsupdate['interface'])) { 
3056
				$bindipv6 = get_interface_ipv6($dnsupdate['updatesource'] . '_stf');
3057
			} else {
3058
				$bindipv6 = get_interface_ipv6($dnsupdate['updatesource']);
3059
			}
3060
		}
3061

    
3062
		/* Handle IPv4/IPv6 selection for the update source interface/VIP */
3063
		switch ($dnsupdate['updatesourcefamily']) {
3064
			case "inet":
3065
				$bindip = $bindipv4;
3066
				break;
3067
			case "inet6":
3068
				$bindip = $bindipv6;
3069
				break;
3070
			case "":
3071
			default:
3072
				/* Try IPv4 first, if that is empty, try IPv6. */
3073
				/* Only specify the address if it's present, otherwise omit. */
3074
				if (!empty($bindipv4)) {
3075
					$bindip = $bindipv4;
3076
				} elseif (!empty($bindipv6)) {
3077
					$bindip = $bindipv6;
3078
				}
3079
				break;
3080
		}
3081

    
3082
		$cacheFile = $g['conf_path'] .
3083
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
3084
		    escapeshellarg($dnsupdate['host']) .
3085
		    "_{$dnsupdate['server']}.cache";
3086
		$cacheFilev6 = $g['conf_path'] .
3087
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
3088
		    escapeshellarg($dnsupdate['host']) .
3089
		    "_{$dnsupdate['server']}_v6.cache";
3090
		$currentTime = time();
3091

    
3092
		if (!$wanip && !$wanipv6) {
3093
			continue;
3094
		}
3095

    
3096
		$keyname = $dnsupdate['keyname'];
3097
		/* trailing dot */
3098
		if (substr($keyname, -1) != ".") {
3099
			$keyname .= ".";
3100
		}
3101

    
3102
		$hostname = $dnsupdate['host'];
3103
		/* trailing dot */
3104
		if (substr($hostname, -1) != ".") {
3105
			$hostname .= ".";
3106
		}
3107

    
3108
		/* write key file */
3109
		$algorithm = empty($dnsupdate['keyalgorithm']) ? 'hmac-md5' : $dnsupdate['keyalgorithm'];
3110
		$upkey = <<<EOD
3111
key "{$keyname}" {
3112
	algorithm {$algorithm};
3113
	secret "{$dnsupdate['keydata']}";
3114
};
3115

    
3116
EOD;
3117
		@file_put_contents("{$g['varetc_path']}/nsupdatekey{$i}", $upkey);
3118

    
3119
		/* generate update instructions */
3120
		$upinst = "";
3121
		if (!empty($dnsupdate['server'])) {
3122
			$upinst .= "server {$dnsupdate['server']}\n";
3123
		}
3124

    
3125
		if (!empty($dnsupdate['zone'])) {
3126
			$upinst .= "zone {$dnsupdate['zone']}\n";
3127
		}
3128

    
3129
		$cachedipv4 = '';
3130
		$cacheTimev4 = 0;
3131
		if (file_exists($cacheFile)) {
3132
			list($cachedipv4, $cacheTimev4) = explode("|",
3133
			    file_get_contents($cacheFile));
3134
		}
3135
		$cachedipv6 = '';
3136
		$cacheTimev6 = 0;
3137
		if (file_exists($cacheFilev6)) {
3138
			list($cachedipv6, $cacheTimev6) = explode("|",
3139
			    file_get_contents($cacheFilev6));
3140
		}
3141

    
3142
		// 25 Days
3143
		$maxCacheAgeSecs = 25 * 24 * 60 * 60;
3144
		$need_update = false;
3145

    
3146
		/* Update IPv4 if we have it. */
3147
		if (is_ipaddrv4($wanip) && $dnsupdate['recordtype'] != "AAAA") {
3148
			if (($wanip != $cachedipv4) || $forced ||
3149
			    (($currentTime - $cacheTimev4) > $maxCacheAgeSecs)) {
3150
				$upinst .= "update delete " .
3151
				    "{$dnsupdate['host']}. A\n";
3152
				$upinst .= "update add {$dnsupdate['host']}. " .
3153
				    "{$dnsupdate['ttl']} A {$wanip}\n";
3154
				if (!empty($bindip)) {
3155
					$upinst .= "local {$bindip}\n";
3156
				}
3157
				$need_update = true;
3158
			} else {
3159
				log_error(sprintf(gettext(
3160
				    "phpDynDNS: Not updating %s A record because the IP address has not changed."),
3161
				    $dnsupdate['host']));
3162
			}
3163
		} else {
3164
			@unlink($cacheFile);
3165
			unset($cacheFile);
3166
		}
3167

    
3168
		/* Update IPv6 if we have it. */
3169
		if (is_ipaddrv6($wanipv6) && $dnsupdate['recordtype'] != "A") {
3170
			if (($wanipv6 != $cachedipv6) || $forced ||
3171
			    (($currentTime - $cacheTimev6) > $maxCacheAgeSecs)) {
3172
				$upinst .= "update delete " .
3173
				    "{$dnsupdate['host']}. AAAA\n";
3174
				$upinst .= "update add {$dnsupdate['host']}. " .
3175
				    "{$dnsupdate['ttl']} AAAA {$wanipv6}\n";
3176
				$need_update = true;
3177
			} else {
3178
				log_error(sprintf(gettext(
3179
				    "phpDynDNS: Not updating %s AAAA record because the IPv6 address has not changed."),
3180
				    $dnsupdate['host']));
3181
			}
3182
		} else {
3183
			@unlink($cacheFilev6);
3184
			unset($cacheFilev6);
3185
		}
3186

    
3187
		$upinst .= "\n";	/* mind that trailing newline! */
3188

    
3189
		if (!$need_update) {
3190
			continue;
3191
		}
3192

    
3193
		@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}", $upinst);
3194
		unset($upinst);
3195
		/* invoke nsupdate */
3196
		$cmd = "/usr/local/bin/nsupdate -k {$g['varetc_path']}/nsupdatekey{$i}";
3197

    
3198
		if (isset($dnsupdate['usetcp'])) {
3199
			$cmd .= " -v";
3200
		}
3201

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

    
3204
		if (mwexec($cmd) == 0) {
3205
			if (!empty($cacheFile)) {
3206
				@file_put_contents($cacheFile,
3207
				    "{$wanip}|{$currentTime}");
3208
				log_error(sprintf(gettext(
3209
				    'phpDynDNS: updating cache file %1$s: %2$s'),
3210
				    $cacheFile, $wanip));
3211
				$notify_text .= sprintf(gettext(
3212
				    'DynDNS updated IP Address (A) for %1$s on %2$s (%3$s) to %4$s'),
3213
				    $dnsupdate['host'],
3214
				    convert_real_interface_to_friendly_descr($if),
3215
				    $if, $wanip) . "\n";
3216
			}
3217
			if (!empty($cacheFilev6)) {
3218
				@file_put_contents($cacheFilev6,
3219
				    "{$wanipv6}|{$currentTime}");
3220
				log_error(sprintf(gettext(
3221
				    'phpDynDNS: updating cache file %1$s: %2$s'),
3222
				    $cacheFilev6, $wanipv6));
3223
				$notify_text .= sprintf(gettext(
3224
				    'DynDNS updated IPv6 Address (AAAA) for %1$s on %2$s (%3$s) to %4$s'),
3225
				    $dnsupdate['host'],
3226
				    convert_real_interface_to_friendly_descr($if),
3227
				    $if, $wanipv6) . "\n";
3228
			}
3229
		} else {
3230
			if (!empty($cacheFile)) {
3231
				log_error(sprintf(gettext(
3232
				    'phpDynDNS: ERROR while updating IP Address (A) for %1$s (%2$s)'),
3233
				    $dnsupdate['host'], $wanip));
3234
			}
3235
			if (!empty($cacheFilev6)) {
3236
				log_error(sprintf(gettext(
3237
				    'phpDynDNS: ERROR while updating IP Address (AAAA) for %1$s (%2$s)'),
3238
				    $dnsupdate['host'], $wanipv6));
3239
			}
3240
		}
3241
		unset($cmd);
3242
	}
3243

    
3244
	if (!empty($notify_text)) {
3245
		notify_all_remote($notify_text);
3246
	}
3247

    
3248
	return 0;
3249
}
3250

    
3251
/* configure cron service */
3252
function configure_cron() {
3253
	global $g, $config;
3254

    
3255
	/* preserve existing crontab entries */
3256
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
3257

    
3258
	for ($i = 0; $i < count($crontab_contents); $i++) {
3259
		$cron_item = &$crontab_contents[$i];
3260
		if (strpos($cron_item, "# pfSense specific crontab entries") !== false) {
3261
			array_splice($crontab_contents, $i - 1);
3262
			break;
3263
		}
3264
	}
3265
	$crontab_contents = implode("\n", $crontab_contents) . "\n";
3266

    
3267

    
3268
	if (is_array($config['cron']['item'])) {
3269
		$crontab_contents .= "#\n";
3270
		$crontab_contents .= "# pfSense specific crontab entries\n";
3271
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
3272
		$crontab_contents .= "#\n";
3273

    
3274
		if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) {
3275
			$http_proxy = $config['system']['proxyurl'];
3276
			if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) {
3277
				$http_proxy .= ':' . $config['system']['proxyport'];
3278
			}
3279
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
3280

    
3281
			if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
3282
				$crontab_contents .= "HTTP_PROXY_AUTH=basic:*:{$config['system']['proxyuser']}:{$config['system']['proxypass']}";
3283
			}
3284
		}
3285

    
3286
		foreach ($config['cron']['item'] as $item) {
3287
			$crontab_contents .= "\n{$item['minute']}\t";
3288
			$crontab_contents .= "{$item['hour']}\t";
3289
			$crontab_contents .= "{$item['mday']}\t";
3290
			$crontab_contents .= "{$item['month']}\t";
3291
			$crontab_contents .= "{$item['wday']}\t";
3292
			$crontab_contents .= "{$item['who']}\t";
3293
			$crontab_contents .= "{$item['command']}";
3294
		}
3295

    
3296
		$crontab_contents .= "\n#\n";
3297
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
3298
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
3299
		$crontab_contents .= "#\n\n";
3300
	}
3301

    
3302
	/* please maintain the newline at the end of file */
3303
	file_put_contents("/etc/crontab", $crontab_contents);
3304
	unset($crontab_contents);
3305

    
3306
	/* make sure that cron is running and start it if it got killed somehow */
3307
	if (!is_process_running("cron")) {
3308
		exec("cd /tmp && /usr/sbin/cron -s 2>/dev/null");
3309
	} else {
3310
	/* do a HUP kill to force sync changes */
3311
		sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP");
3312
	}
3313

    
3314
}
3315

    
3316
function upnp_action ($action) {
3317
	global $g, $config;
3318
	switch ($action) {
3319
		case "start":
3320
			if (file_exists('/var/etc/miniupnpd.conf')) {
3321
				@unlink("{$g['varrun_path']}/miniupnpd.pid");
3322
				mwexec_bg("/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf -P {$g['varrun_path']}/miniupnpd.pid");
3323
			}
3324
			break;
3325
		case "stop":
3326
			killbypid("{$g['varrun_path']}/miniupnpd.pid");
3327
			while ((int)exec("/bin/pgrep -a miniupnpd | wc -l") > 0) {
3328
				mwexec('/usr/bin/killall miniupnpd 2>/dev/null', true);
3329
			}
3330
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
3331
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
3332
			break;
3333
		case "restart":
3334
			upnp_action('stop');
3335
			upnp_action('start');
3336
			break;
3337
	}
3338
}
3339

    
3340
function upnp_start() {
3341
	global $config;
3342

    
3343
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
3344
		return;
3345
	}
3346

    
3347
	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
3348
		echo gettext("Starting UPnP service... ");
3349
		require_once('/usr/local/pkg/miniupnpd.inc');
3350
		sync_package_miniupnpd();
3351
		echo "done.\n";
3352
	}
3353
}
3354

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

    
3358
	$is_installed = false;
3359
	$cron_changed = true;
3360
	$change_message = "";
3361

    
3362
	if (!is_array($config['cron'])) {
3363
		$config['cron'] = array();
3364
	}
3365
	if (!is_array($config['cron']['item'])) {
3366
		$config['cron']['item'] = array();
3367
	}
3368

    
3369
	$x = 0;
3370
	foreach ($config['cron']['item'] as $item) {
3371
		if (strstr($item['command'], $command)) {
3372
			$is_installed = true;
3373
			break;
3374
		}
3375
		$x++;
3376
	}
3377

    
3378
	if ($active) {
3379
		$cron_item = array();
3380
		$cron_item['minute'] = $minute;
3381
		$cron_item['hour'] = $hour;
3382
		$cron_item['mday'] = $monthday;
3383
		$cron_item['month'] = $month;
3384
		$cron_item['wday'] = $weekday;
3385
		$cron_item['who'] = $who;
3386
		$cron_item['command'] = $command;
3387
		if (!$is_installed) {
3388
			$config['cron']['item'][] = $cron_item;
3389
			$change_message = "Installed cron job for %s";
3390
		} else {
3391
			if ($config['cron']['item'][$x] == $cron_item) {
3392
				$cron_changed = false;
3393
			} else {
3394
				$config['cron']['item'][$x] = $cron_item;
3395
				$change_message = "Updated cron job for %s";
3396
			}
3397
		}
3398
	} else {
3399
		if ($is_installed == true) {
3400
			array_splice($config['cron']['item'], $x, 1);
3401
			$change_message = "Removed cron job for %s";
3402
		} else {
3403
			$cron_changed = false;
3404
		}
3405
	}
3406

    
3407
	if ($cron_changed) {
3408
		/* Optionally write the configuration if this function made changes.
3409
		 * Performing a write_config() in this way can have unintended side effects. See #7146
3410
		 * Base system instances of this function do not need to write, packages may.
3411
		 */
3412
		if ($write_config) {
3413
			write_config(sprintf(gettext($change_message), $command));
3414
		}
3415
		configure_cron();
3416
	}
3417
}
3418

    
3419
?>
(46-46/61)