Project

General

Profile

Download (106 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'])) {
83
			if (strstr($dhcpv6ifconf['rainterface'], "_vip")) {
84
				if (is_linklocal(get_configured_vip_ipv6($dhcpv6ifconf['rainterface']))) {
85
					$rasrcaddr = get_configured_vip_ipv6($dhcpv6ifconf['rainterface']);
86
				}
87
				elseif (get_carp_interface_status($dhcpv6ifconf['rainterface']) == "MASTER") {
88
					$dhcpv6if = $dhcpv6ifconf['rainterface'];
89
					$racarpif = true;
90
				} else {
91
					continue;
92
				}
93
			}
94
		}
95

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
495
	unlock($dhcpdconfigurelck);
496
}
497

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

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

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

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

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

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

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

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

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

    
589
	$dhcpdconf = <<<EOD
590

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

    
603
EOD;
604

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

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

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

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

    
628
EOD;
629

    
630
		}
631
		break;
632
	}
633

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

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

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

    
655
		interfaces_staticarp_configure($dhcpif);
656

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

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

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

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

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

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

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

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

    
744
		$dnscfg = "";
745

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
933
			$pdnscfg = "";
934

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1214
EOD;
1215

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

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

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

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

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

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

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

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

    
1259
				$smdnscfg = "";
1260

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1407

    
1408
				$i++;
1409
			}
1410
		}
1411

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

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

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

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

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

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

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

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

    
1459
	return 0;
1460
}
1461

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

    
1472
	return $dhcpdconf;
1473
}
1474

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

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

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

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

    
1537
	return $dhcpdconf;
1538
}
1539

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

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

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

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

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

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

    
1573

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

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

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

    
1593
	$dhcpdv6conf = <<<EOD
1594

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

    
1607
EOD;
1608

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

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

    
1617
	$dhcpdv6ifs = array();
1618

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

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

    
1624
		$ddns_zones = array();
1625

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

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

    
1644
		$dnscfgv6 = "";
1645

    
1646
		if ($dhcpv6ifconf['domain']) {
1647
			$dnscfgv6 .= "	option domain-name \"{$dhcpv6ifconf['domain']}\";\n";
1648
		}
1649

    
1650
		if ($dhcpv6ifconf['domainsearchlist'] <> "") {
1651
			$dnscfgv6 .= "	option dhcp6.domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpv6ifconf['domainsearchlist'])) . "\";\n";
1652
		}
1653

    
1654
		if (isset($dhcpv6ifconf['ddnsupdate'])) {
1655
			if ($dhcpv6ifconf['ddnsdomain'] <> "") {
1656
				$dnscfgv6 .= "	ddns-domainname \"{$dhcpv6ifconf['ddnsdomain']}\";\n";
1657
			}
1658
			if (empty($dhcpv6ifconf['ddnsclientupdates'])) {
1659
				$ddnsclientupdates = 'allow';
1660
			} else {
1661
				$ddnsclientupdates = $dhcpv6ifconf['ddnsclientupdates'];
1662
			}
1663
			$dnscfgv6 .= "	{$ddnsclientupdates} client-updates;\n";
1664
			$nsupdate = true;
1665
		} else {
1666
			$dnscfgv6 .= "	do-forward-updates false;\n";
1667
		}
1668

    
1669
		if ($dhcpv6ifconf['dhcp6c-dns'] != 'disabled') {
1670
			if (is_array($dhcpv6ifconf['dnsserver']) && ($dhcpv6ifconf['dnsserver'][0])) {
1671
				$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dhcpv6ifconf['dnsserver']) . ";\n";
1672
			} else if (((isset($config['dnsmasq']['enable'])) || isset($config['unbound']['enable'])) && (is_ipaddrv6($ifcfgipv6))) {
1673
				$dnscfgv6 .= "	option dhcp6.name-servers {$ifcfgipv6};\n";
1674
			} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1675
				$dns_arrv6 = array();
1676
				foreach ($syscfg['dnsserver'] as $dnsserver) {
1677
					if (is_ipaddrv6($dnsserver)) {
1678
						if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1679
						    Net_IPv6::isInNetmask($dnsserver, '::', $pdlen)) {
1680
							$dnsserver = merge_ipv6_delegated_prefix($ifcfgipv6, $dnsserver, $pdlen);
1681
						}
1682
						$dns_arrv6[] = $dnsserver;
1683
					}
1684
				}
1685
				if (!empty($dns_arrv6)) {
1686
					$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dns_arrv6) . ";\n";
1687
				}
1688
			}
1689
		} else {
1690
			$dnscfgv6 .= "	#option dhcp6.name-servers --;\n";
1691
		}
1692

    
1693
		if (!is_ipaddrv6($ifcfgipv6)) {
1694
			$ifcfgsnv6 = "64";
1695
			$subnetv6 = gen_subnetv6($dhcpv6ifconf['range']['from'], $ifcfgsnv6);
1696
		}
1697

    
1698
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1699

    
1700
		if (isset($dhcpv6ifconf['ddnsupdate']) &&
1701
		    !empty($dhcpv6ifconf['ddnsdomain'])) {
1702
			$newzone = array();
1703
			$newzone['domain-name'] = $dhcpv6ifconf['ddnsdomain'];
1704
			$newzone['dns-servers'] = array($dhcpv6ifconf['ddnsdomainprimary'], $dhcpv6ifconf['ddnsdomainsecondary']);
1705
			$newzone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1706
			$newzone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1707
			$ddns_zones[] = $newzone;
1708
			if (isset($dhcpv6ifconf['ddnsreverse'])) {
1709
				$ptr_zones = get_v6_ptr_zones($subnetv6, $ifcfgsnv6);
1710
				foreach ($ptr_zones as $ptr_zone) {
1711
					$reversezone = array();
1712
					$reversezone['ptr-domain'] = $ptr_zone;
1713
					$reversezone['dns-servers'] = array($dhcpv6ifconf['ddnsdomainprimary'], $dhcpv6ifconf['ddnsdomainsecondary']);
1714
					$reversezone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1715
					$reversezone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1716
					$ddns_zones[] = $reversezone;
1717
				}
1718
			}
1719
		}
1720

    
1721
		$dhcpdv6conf .= " {\n";
1722

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

    
1730
		if (!empty($dhcpv6ifconf['range']['from']) && !empty($dhcpv6ifconf['range']['to'])) {
1731
			$dhcpdv6conf .= "	range6 {$range_from} {$range_to};\n";
1732
		}
1733

    
1734
		$dhcpdv6conf .= $dnscfgv6;
1735

    
1736
		if (is_ipaddrv6($dhcpv6ifconf['prefixrange']['from']) && is_ipaddrv6($dhcpv6ifconf['prefixrange']['to'])) {
1737
			$dhcpdv6conf .= "	prefix6 {$dhcpv6ifconf['prefixrange']['from']} {$dhcpv6ifconf['prefixrange']['to']} /{$dhcpv6ifconf['prefixrange']['prefixlength']};\n";
1738
		}
1739
		if (is_ipaddrv6($dhcpv6ifconf['dns6ip'])) {
1740
			$dns6ip = $dhcpv6ifconf['dns6ip'];
1741
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1742
			    Net_IPv6::isInNetmask($dns6ip, '::', $pdlen)) {
1743
				$dns6ip = merge_ipv6_delegated_prefix($ifcfgipv6, $dns6ip, $pdlen);
1744
			}
1745
			$dhcpdv6conf .= "	option dhcp6.name-servers {$dns6ip};\n";
1746
		}
1747
		// default-lease-time
1748
		if ($dhcpv6ifconf['defaultleasetime']) {
1749
			$dhcpdv6conf .= "	default-lease-time {$dhcpv6ifconf['defaultleasetime']};\n";
1750
		}
1751

    
1752
		// max-lease-time
1753
		if ($dhcpv6ifconf['maxleasetime']) {
1754
			$dhcpdv6conf .= "	max-lease-time {$dhcpv6ifconf['maxleasetime']};\n";
1755
		}
1756

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

    
1781
		// Handle option, number rowhelper values
1782
		$dhcpdv6conf .= "\n";
1783
		if (isset($dhcpv6ifconf['numberoptions']['item']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1784
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1785
				$itemv6_value = base64_decode($itemv6['value']);
1786
				$dhcpdv6conf .= "	option custom-{$dhcpv6if}-{$itemv6idx} \"{$itemv6_value}\";\n";
1787
			}
1788
		}
1789

    
1790
		// ldap-server
1791
		if ($dhcpv6ifconf['ldap'] <> "") {
1792
			$ldapserver = $dhcpv6ifconf['ldap'];
1793
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1794
			    Net_IPv6::isInNetmask($ldapserver, '::', $pdlen)) {
1795
				$ldapserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ldapserver, $pdlen);
1796
			}
1797
			$dhcpdv6conf .= "	option ldap-server \"{$ldapserver}\";\n";
1798
		}
1799

    
1800
		// net boot information
1801
		if (isset($dhcpv6ifconf['netboot'])) {
1802
			if (!empty($dhcpv6ifconf['bootfile_url'])) {
1803
				$dhcpdv6conf .= "	option dhcp6.bootfile-url \"{$dhcpv6ifconf['bootfile_url']}\";\n";
1804
			}
1805
		}
1806

    
1807
		$dhcpdv6conf .= "}\n";
1808

    
1809
		/* add static mappings */
1810
		/* Needs to use DUID */
1811
		if (is_array($dhcpv6ifconf['staticmap'])) {
1812
			$i = 0;
1813
			foreach ($dhcpv6ifconf['staticmap'] as $sm) {
1814
				$dhcpdv6conf .= <<<EOD
1815
host s_{$dhcpv6if}_{$i} {
1816
	host-identifier option dhcp6.client-id {$sm['duid']};
1817

    
1818
EOD;
1819
				if ($sm['ipaddrv6']) {
1820
					$ipaddrv6 = $sm['ipaddrv6'];
1821
					if ($ifcfgv6['ipaddrv6'] == 'track6') {
1822
						$ipaddrv6 = merge_ipv6_delegated_prefix($ifcfgipv6, $ipaddrv6, $pdlen);
1823
					}
1824
					$dhcpdv6conf .= "	fixed-address6 {$ipaddrv6};\n";
1825
				}
1826

    
1827
				if ($sm['hostname']) {
1828
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1829
					$dhhostname = str_replace(".", "_", $dhhostname);
1830
					$dhcpdv6conf .= "	option host-name {$dhhostname};\n";
1831
					if (isset($dhcpv6ifconf['ddnsupdate']) &&
1832
					    isset($dhcpv6ifconf['ddnsforcehostname'])) {
1833
						$dhcpdv6conf .= "	ddns-hostname \"{$dhhostname}\";\n";
1834
					}
1835
				}
1836
				if ($sm['filename']) {
1837
					$dhcpdv6conf .= "	filename \"{$sm['filename']}\";\n";
1838
				}
1839

    
1840
				if ($sm['rootpath']) {
1841
					$dhcpdv6conf .= "	option root-path \"{$sm['rootpath']}\";\n";
1842
				}
1843

    
1844
				$dhcpdv6conf .= "}\n";
1845
				$i++;
1846
			}
1847
		}
1848

    
1849
		if ($dhcpv6ifconf['ddnsdomain']) {
1850
			$dhcpdv6conf .= dhcpdkey($dhcpv6ifconf);
1851
			$dhcpdv6conf .= dhcpdzones($ddns_zones);
1852
		}
1853

    
1854
		if (($config['dhcpdv6'][$dhcpv6if]['ramode'] != "unmanaged") &&
1855
		    (isset($config['interfaces'][$dhcpv6if]['enable']) ||
1856
		    preg_match("/poes/", $dhcpv6if))) {
1857
			if (preg_match("/poes/si", $dhcpv6if)) {
1858
				/* magic here */
1859
				$dhcpdv6ifs = array_merge($dhcpdv6ifs, get_pppoes_child_interfaces($dhcpv6if));
1860
			} else {
1861
				$realif = get_real_interface($dhcpv6if, "inet6");
1862
				if (stristr("$realif", "bridge")) {
1863
					$mac = get_interface_mac($realif);
1864
					$v6address = generate_ipv6_from_mac($mac);
1865
					/* Create link local address for bridges */
1866
					mwexec("/sbin/ifconfig {$realif} inet6 {$v6address}");
1867
				}
1868
				$realif = escapeshellcmd($realif);
1869
				$dhcpdv6ifs[] = $realif;
1870
			}
1871
		}
1872
	}
1873

    
1874
	if ($nsupdate) {
1875
		$dhcpdv6conf .= "ddns-update-style interim;\n";
1876
		$dhcpdv6conf .= "update-static-leases on;\n";
1877
	} else {
1878
		$dhcpdv6conf .= "ddns-update-style none;\n";
1879
	}
1880

    
1881
	/* write dhcpdv6.conf */
1882
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf", $dhcpdv6conf)) {
1883
		log_error("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1884
		if (platform_booting()) {
1885
			printf("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1886
		}
1887
		unset($dhcpdv6conf);
1888
		return 1;
1889
	}
1890
	unset($dhcpdv6conf);
1891

    
1892
	/* create an empty leases v6 database */
1893
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases")) {
1894
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1895
	}
1896

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

    
1901
	/* fire up dhcpd in a chroot */
1902
	if (count($dhcpdv6ifs) > 0) {
1903
		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 " .
1904
			join(" ", $dhcpdv6ifs));
1905
		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");
1906
	}
1907
	if (platform_booting()) {
1908
		print gettext("done.") . "\n";
1909
	}
1910

    
1911
	return 0;
1912
}
1913

    
1914
function services_igmpproxy_configure() {
1915
	global $config, $g;
1916

    
1917
	/* kill any running igmpproxy */
1918
	killbyname("igmpproxy");
1919

    
1920
	if (!isset($config['igmpproxy']['enable'])) {
1921
		return 0;
1922
	}
1923
	if (!is_array($config['igmpproxy']['igmpentry']) || (count($config['igmpproxy']['igmpentry']) == 0)) {
1924
		return 1;
1925
	}
1926

    
1927
	$iflist = get_configured_interface_list();
1928

    
1929
	$igmpconf = <<<EOD
1930

    
1931
##------------------------------------------------------
1932
## Enable Quickleave mode (Sends Leave instantly)
1933
##------------------------------------------------------
1934
quickleave
1935

    
1936
EOD;
1937

    
1938
	foreach ($config['igmpproxy']['igmpentry'] as $igmpcf) {
1939
		unset($iflist[$igmpcf['ifname']]);
1940
		$realif = get_real_interface($igmpcf['ifname']);
1941
		if (empty($igmpcf['threshold'])) {
1942
			$threshld = 1;
1943
		} else {
1944
			$threshld = $igmpcf['threshold'];
1945
		}
1946
		$igmpconf .= "phyint {$realif} {$igmpcf['type']} ratelimit 0 threshold {$threshld}\n";
1947

    
1948
		if ($igmpcf['address'] <> "") {
1949
			$item = explode(" ", $igmpcf['address']);
1950
			foreach ($item as $iww) {
1951
				$igmpconf .= "altnet {$iww}\n";
1952
			}
1953
		}
1954
		$igmpconf .= "\n";
1955
	}
1956
	foreach ($iflist as $ifn) {
1957
		$realif = get_real_interface($ifn);
1958
		$igmpconf .= "phyint {$realif} disabled\n";
1959
	}
1960
	$igmpconf .= "\n";
1961

    
1962
	$igmpfl = fopen($g['varetc_path'] . "/igmpproxy.conf", "w");
1963
	if (!$igmpfl) {
1964
		log_error(gettext("Could not write Igmpproxy configuration file!"));
1965
		return;
1966
	}
1967
	fwrite($igmpfl, $igmpconf);
1968
	fclose($igmpfl);
1969
	unset($igmpconf);
1970

    
1971
	if (isset($config['syslog']['igmpxverbose'])) {
1972
		mwexec_bg("/usr/local/sbin/igmpproxy -v {$g['varetc_path']}/igmpproxy.conf");
1973
	} else {
1974
		mwexec_bg("/usr/local/sbin/igmpproxy {$g['varetc_path']}/igmpproxy.conf");
1975
	}
1976

    
1977
	log_error(gettext("Started IGMP proxy service."));
1978

    
1979
	return 0;
1980
}
1981

    
1982
function services_dhcrelay_configure() {
1983
	global $config, $g;
1984

    
1985
	if (isset($config['system']['developerspew'])) {
1986
		$mt = microtime();
1987
		echo "services_dhcrelay_configure() being called $mt\n";
1988
	}
1989

    
1990
	/* kill any running dhcrelay */
1991
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
1992

    
1993
	init_config_arr(array('dhcrelay'));
1994
	$dhcrelaycfg = &$config['dhcrelay'];
1995

    
1996
	/* DHCPRelay enabled on any interfaces? */
1997
	if (!isset($dhcrelaycfg['enable'])) {
1998
		return 0;
1999
	}
2000

    
2001
	/* Start/Restart DHCP Relay, if a CARP VIP is set, check its status and act
2002
	* appropriately. */
2003
	if (isset($dhcrelaycfg['carpstatusvip']) && ($dhcrelaycfg['carpstatusvip'] != "none")) {
2004
		$status = get_carp_interface_status($dhcrelaycfg['carpstatusvip']);
2005
		switch (strtoupper($status)) {
2006
			// Do not start DHCP Relay service if the VIP is in BACKUP or INIT state.
2007
			case "BACKUP":
2008
			case "INIT":
2009
				log_error("Stopping DHCP Relay (CARP BACKUP/INIT)");
2010
				return 0;
2011
				break;
2012
			// Start the service if the VIP is MASTER state.
2013
			case "MASTER":
2014
			// Assume it's up if the status can't be determined.
2015
			default:
2016
				break;
2017
		}
2018
	}
2019

    
2020
	if (platform_booting()) {
2021
		echo gettext("Starting DHCP Relay service...");
2022
	} else {
2023
		sleep(1);
2024
	}
2025

    
2026
	$iflist = get_configured_interface_list();
2027

    
2028
	$dhcrelayifs = array();
2029
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
2030
	foreach ($dhcifaces as $dhcrelayif) {
2031
		if (!isset($iflist[$dhcrelayif])) {
2032
			continue;
2033
		}
2034

    
2035
		if (get_interface_ip($dhcrelayif)) {
2036
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
2037
		}
2038
	}
2039
	$dhcrelayifs = array_unique($dhcrelayifs);
2040

    
2041
	/*
2042
	 * In order for the relay to work, it needs to be active
2043
	 * on the interface in which the destination server sits.
2044
	 */
2045
	$srvips = explode(",", $dhcrelaycfg['server']);
2046
	if (!is_array($srvips)) {
2047
		log_error(gettext("No destination IP has been configured!"));
2048
		return;
2049
	}
2050
	$srvifaces = array();
2051
	foreach ($srvips as $srcidx => $srvip) {
2052
		$destif = guess_interface_from_ip($srvip);
2053
		if (!empty($destif) && !is_pseudo_interface($destif)) {
2054
			$srvifaces[] = $destif;
2055
		}
2056
	}
2057
	$srvifaces = array_unique($srvifaces);
2058

    
2059
	/* Check for relays in the same subnet as clients so they can bind for
2060
	 * either direction (up or down) */
2061
	$srvrelayifs = array_intersect($dhcrelayifs, $srvifaces);
2062

    
2063
	/* The server interface(s) should not be in this list */
2064
	$dhcrelayifs = array_diff($dhcrelayifs, $srvifaces);
2065

    
2066
	/* Remove the dual-role interfaces from up and down lists */
2067
	$srvifaces = array_diff($srvifaces, $srvrelayifs);
2068
	$dhcrelayifs = array_diff($dhcrelayifs, $srvrelayifs);
2069

    
2070
	/* fire up dhcrelay */
2071
	if (empty($dhcrelayifs) && empty($srvrelayifs)) {
2072
		log_error(gettext("No suitable downstream interfaces found for running dhcrelay!"));
2073
		return; /* XXX */
2074
	}
2075
	if (empty($srvifaces) && empty($srvrelayifs)) {
2076
		log_error(gettext("No suitable upstream interfaces found for running dhcrelay!"));
2077
		return; /* XXX */
2078
	}
2079

    
2080
	$cmd = "/usr/local/sbin/dhcrelay";
2081

    
2082
	if (!empty($dhcrelayifs)) {
2083
		$cmd .= " -id " . implode(" -id ", $dhcrelayifs);
2084
	}
2085
	if (!empty($srvifaces)) {
2086
		$cmd .= " -iu " . implode(" -iu ", $srvifaces);
2087
	}
2088
	if (!empty($srvrelayifs)) {
2089
		$cmd .= " -i " . implode(" -i ", $srvrelayifs);
2090
	}
2091

    
2092
	if (isset($dhcrelaycfg['agentoption'])) {
2093
		$cmd .= " -a -m replace";
2094
	}
2095

    
2096
	$cmd .= " " . implode(" ", $srvips);
2097
	mwexec($cmd);
2098
	unset($cmd);
2099

    
2100
	return 0;
2101
}
2102

    
2103
function services_dhcrelay6_configure() {
2104
	global $config, $g;
2105

    
2106
	if (isset($config['system']['developerspew'])) {
2107
		$mt = microtime();
2108
		echo "services_dhcrelay6_configure() being called $mt\n";
2109
	}
2110

    
2111
	/* kill any running dhcrelay */
2112
	killbypid("{$g['varrun_path']}/dhcrelay6.pid");
2113

    
2114
	init_config_arr(array('dhcrelay6'));
2115
	$dhcrelaycfg = &$config['dhcrelay6'];
2116

    
2117
	/* DHCPv6 Relay enabled on any interfaces? */
2118
	if (!isset($dhcrelaycfg['enable'])) {
2119
		return 0;
2120
	}
2121

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

    
2141
	if (platform_booting()) {
2142
		echo gettext("Starting DHCPv6 Relay service...");
2143
	} else {
2144
		sleep(1);
2145
	}
2146

    
2147
	$iflist = get_configured_interface_list();
2148

    
2149
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
2150
	foreach ($dhcifaces as $dhcrelayif) {
2151
		if (!isset($iflist[$dhcrelayif])) {
2152
			continue;
2153
		}
2154

    
2155
		if (get_interface_ipv6($dhcrelayif)) {
2156
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
2157
		}
2158
	}
2159
	$dhcrelayifs = array_unique($dhcrelayifs);
2160

    
2161
	/*
2162
	 * In order for the relay to work, it needs to be active
2163
	 * on the interface in which the destination server sits.
2164
	 */
2165
	$srvips = explode(",", $dhcrelaycfg['server']);
2166
	$srvifaces = array();
2167
	foreach ($srvips as $srcidx => $srvip) {
2168
		$destif = guess_interface_from_ip($srvip);
2169
		if (!empty($destif) && !is_pseudo_interface($destif)) {
2170
			$srvifaces[] = "{$srvip}%{$destif}";
2171
		}
2172
	}
2173

    
2174
	/* fire up dhcrelay */
2175
	if (empty($dhcrelayifs) || empty($srvifaces)) {
2176
		log_error(gettext("No suitable interface found for running dhcrelay -6!"));
2177
		return; /* XXX */
2178
	}
2179

    
2180
	$cmd = "/usr/local/sbin/dhcrelay -6 -pf \"{$g['varrun_path']}/dhcrelay6.pid\"";
2181
	foreach ($dhcrelayifs as $dhcrelayif) {
2182
		$cmd .= " -l {$dhcrelayif}";
2183
	}
2184
	foreach ($srvifaces as $srviface) {
2185
		$cmd .= " -u \"{$srviface}\"";
2186
	}
2187
	mwexec($cmd);
2188
	unset($cmd);
2189

    
2190
	return 0;
2191
}
2192

    
2193
function services_dyndns_configure_client($conf) {
2194

    
2195
	if (!isset($conf['enable'])) {
2196
		return;
2197
	}
2198

    
2199
	/* load up the dyndns.class */
2200
	require_once("dyndns.class");
2201

    
2202
	$dns = new updatedns($dnsService = $conf['type'],
2203
		$dnsHost = $conf['host'],
2204
		$dnsDomain = $conf['domainname'],
2205
		$dnsUser = $conf['username'],
2206
		$dnsPass = $conf['password'],
2207
		$dnsWildcard = $conf['wildcard'],
2208
		$dnsProxied = $conf['proxied'],
2209
		$dnsMX = $conf['mx'],
2210
		$dnsIf = "{$conf['interface']}",
2211
		$dnsBackMX = NULL,
2212
		$dnsServer = NULL,
2213
		$dnsPort = NULL,
2214
		$dnsUpdateURL = "{$conf['updateurl']}",
2215
		$forceUpdate = $conf['force'],
2216
		$dnsZoneID = $conf['zoneid'],
2217
		$dnsTTL = $conf['ttl'],
2218
		$dnsResultMatch = "{$conf['resultmatch']}",
2219
		$dnsRequestIf = "{$conf['requestif']}",
2220
		$dnsMaxCacheAge = $conf['maxcacheage'],
2221
		$dnsID = "{$conf['id']}",
2222
		$dnsVerboseLog = $conf['verboselog'],
2223
		$curlIpresolveV4 = $conf['curl_ipresolve_v4'],
2224
		$curlSslVerifypeer = $conf['curl_ssl_verifypeer'],
2225
		$curlProxy = $conf['curl_proxy']);
2226
}
2227

    
2228
function services_dyndns_configure($int = "") {
2229
	global $config, $g;
2230
	if (isset($config['system']['developerspew'])) {
2231
		$mt = microtime();
2232
		echo "services_dyndns_configure() being called $mt\n";
2233
	}
2234

    
2235
	if (isset($config['dyndnses']['dyndns']) && is_array($config['dyndnses']['dyndns'])) {
2236
		$dyndnscfg = $config['dyndnses']['dyndns'];
2237
	} else {
2238
		return 0;
2239
	}
2240
	$gwgroups = return_gateway_groups_array(true);
2241
	if (is_array($dyndnscfg)) {
2242
		if (platform_booting()) {
2243
			echo gettext("Starting DynDNS clients...");
2244
		}
2245

    
2246
		foreach ($dyndnscfg as $dyndns) {
2247
			/*
2248
			 * If it's using a gateway group, check if interface is
2249
			 * the active gateway for that group
2250
			 */
2251
			$group_int = '';
2252
			$friendly_group_int = '';
2253
			$gwgroup_member = false;
2254
			if (is_array($gwgroups[$dyndns['interface']])) {
2255
				if (!empty($gwgroups[$dyndns['interface']][0]['vip'])) {
2256
					$group_int = $gwgroups[$dyndns['interface']][0]['vip'];
2257
				} else {
2258
					$group_int = $gwgroups[$dyndns['interface']][0]['int'];
2259
					$friendly_group_int =
2260
					    convert_real_interface_to_friendly_interface_name(
2261
						$group_int);
2262
					if (!empty($int)) {
2263
						$gwgroup_member =
2264
						    interface_gateway_group_member(get_real_interface($int),
2265
						    $dyndns['interface']);
2266
					}
2267
				}
2268
			}
2269
			if ((empty($int)) || ($int == $dyndns['interface']) || $gwgroup_member ||
2270
			    ($int == $group_int) || ($int == $friendly_group_int)) {
2271
				$dyndns['verboselog'] = isset($dyndns['verboselog']);
2272
				$dyndns['curl_ipresolve_v4'] = isset($dyndns['curl_ipresolve_v4']);
2273
				$dyndns['curl_ssl_verifypeer'] = isset($dyndns['curl_ssl_verifypeer']);
2274
				$dyndns['proxied'] = isset($dyndns['proxied']);
2275
				$dyndns['wildcard'] = isset($dyndns['wildcard']);
2276
				services_dyndns_configure_client($dyndns);
2277
				sleep(1);
2278
			}
2279
		}
2280

    
2281
		if (platform_booting()) {
2282
			echo gettext("done.") . "\n";
2283
		}
2284
	}
2285

    
2286
	return 0;
2287
}
2288

    
2289
function dyndnsCheckIP($int) {
2290
	global $config, $factory_default_checkipservice;
2291
	$ip_address = get_interface_ip($int);
2292
	if (is_private_ip($ip_address)) {
2293
		$gateways_status = return_gateways_status(true);
2294
		// If the gateway for this interface is down, then the external check cannot work.
2295
		// Avoid the long wait for the external check to timeout.
2296
		if (stristr($gateways_status[$config['interfaces'][$int]['gateway']]['status'], "down")) {
2297
			return "down";
2298
		}
2299

    
2300
		// Append the factory default check IP service to the list (if not disabled).
2301
		if (!isset($config['checkipservices']['disable_factory_default'])) {
2302
			if (!is_array($config['checkipservices'])) {
2303
				$config['checkipservices'] = array();
2304
			}
2305
			if (!is_array($config['checkipservices']['checkipservice'])) {
2306
				$config['checkipservices']['checkipservice'] = array();
2307
			}
2308
			$config['checkipservices']['checkipservice'][] = $factory_default_checkipservice;
2309
		}
2310

    
2311
		// Use the first enabled check IP service as the default.
2312
		if (is_array($config['checkipservices']['checkipservice'])) {
2313
			foreach ($config['checkipservices']['checkipservice'] as $i => $checkipservice) {
2314
				if (isset($checkipservice['enable'])) {
2315
					$url = $checkipservice['url'];
2316
					$username = $checkipservice['username'];
2317
					$password = $checkipservice['password'];
2318
					$verifysslpeer = isset($checkipservice['verifysslpeer']);
2319
					$curl_proxy = isset($checkipservice['curl_proxy']);
2320
					break;
2321
				}
2322
			}
2323
		}
2324

    
2325
		$hosttocheck = $url;
2326
		$ip_ch = curl_init($hosttocheck);
2327
		curl_setopt($ip_ch, CURLOPT_RETURNTRANSFER, 1);
2328
		curl_setopt($ip_ch, CURLOPT_SSL_VERIFYPEER, $verifysslpeer);
2329
		curl_setopt($ip_ch, CURLOPT_INTERFACE, 'host!' . $ip_address);
2330
		curl_setopt($ip_ch, CURLOPT_CONNECTTIMEOUT, '30');
2331
		curl_setopt($ip_ch, CURLOPT_TIMEOUT, 120);
2332
		curl_setopt($ip_ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
2333
		curl_setopt($ip_ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
2334
		curl_setopt($ip_ch, CURLOPT_USERPWD, "{$username}:{$password}");
2335
		if ($curl_proxy) {
2336
			set_curlproxy($ip_ch);
2337
		}
2338
		$ip_result_page = curl_exec($ip_ch);
2339
		curl_close($ip_ch);
2340
		$ip_result_decoded = urldecode($ip_result_page);
2341
		preg_match('=Current IP Address: (.*)</body>=siU', $ip_result_decoded, $matches);
2342

    
2343
		if ($matches[1]) {
2344
			$parsed_ip = trim($matches[1]);
2345
		} else {
2346
			$parsed_ip = trim($ip_result_decoded);
2347
		}
2348

    
2349
		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);
2350
		if ($matches[0]) {
2351
			$ip_address = $matches[0];
2352
		}
2353
	}
2354
	return $ip_address;
2355
}
2356

    
2357
function services_dnsmasq_configure($restart_dhcp = true) {
2358
	global $config, $g;
2359
	$return = 0;
2360

    
2361
	// hard coded args: will be removed to avoid duplication if specified in custom_options
2362
	$standard_args = array(
2363
		"dns-forward-max" => "--dns-forward-max=5000",
2364
		"cache-size" => "--cache-size=10000",
2365
		"local-ttl" => "--local-ttl=1"
2366
	);
2367

    
2368

    
2369
	if (isset($config['system']['developerspew'])) {
2370
		$mt = microtime();
2371
		echo "services_dnsmasq_configure() being called $mt\n";
2372
	}
2373

    
2374
	/* kill any running dnsmasq */
2375
	if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) {
2376
		sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
2377
	}
2378

    
2379
	if (isset($config['dnsmasq']['enable'])) {
2380

    
2381
		if (platform_booting()) {
2382
			echo gettext("Starting DNS forwarder...");
2383
		} else {
2384
			sleep(1);
2385
		}
2386

    
2387
		/* generate hosts file */
2388
		if (system_hosts_generate() != 0) {
2389
			$return = 1;
2390
		}
2391

    
2392
		$args = "";
2393

    
2394
		if (isset($config['dnsmasq']['regdhcp'])) {
2395
			$args .= " --dhcp-hostsfile={$g['etc_path']}/hosts ";
2396
		}
2397

    
2398
		/* Setup listen port, if non-default */
2399
		if (is_port($config['dnsmasq']['port'])) {
2400
			$args .= " --port={$config['dnsmasq']['port']} ";
2401
		}
2402

    
2403
		$listen_addresses = "";
2404
		if (isset($config['dnsmasq']['interface'])) {
2405
			$interfaces = explode(",", $config['dnsmasq']['interface']);
2406
			foreach ($interfaces as $interface) {
2407
				$if = get_real_interface($interface);
2408
				if (does_interface_exist($if)) {
2409
					$laddr = get_interface_ip($interface);
2410
					if (is_ipaddrv4($laddr)) {
2411
						$listen_addresses .= " --listen-address={$laddr} ";
2412
					}
2413
					$laddr6 = get_interface_ipv6($interface);
2414
					if (is_ipaddrv6($laddr6) && !isset($config['dnsmasq']['strictbind'])) {
2415
						/*
2416
						 * XXX: Since dnsmasq does not support link-local address
2417
						 * with scope specified. These checks are being done.
2418
						 */
2419
						if (is_linklocal($laddr6) && strstr($laddr6, "%")) {
2420
							$tmpaddrll6 = explode("%", $laddr6);
2421
							$listen_addresses .= " --listen-address={$tmpaddrll6[0]} ";
2422
						} else {
2423
							$listen_addresses .= " --listen-address={$laddr6} ";
2424
						}
2425
					}
2426
				}
2427
			}
2428
			if (!empty($listen_addresses)) {
2429
				$args .= " {$listen_addresses} ";
2430
				if (isset($config['dnsmasq']['strictbind'])) {
2431
					$args .= " --bind-interfaces ";
2432
				}
2433
			}
2434
		}
2435

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

    
2443
			// Build an array of domain overrides to help in checking for matches.
2444
			$override_a = array();
2445
			if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2446
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2447
					$override_a[$override['domain']] = "y";
2448
				}
2449
			}
2450

    
2451
			// Build an array of the private reverse lookup domain names
2452
			$reverse_domain_a = array("10.in-addr.arpa", "168.192.in-addr.arpa");
2453
			// Unfortunately the 172.16.0.0/12 range does not map nicely to the in-addr.arpa scheme.
2454
			for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) {
2455
				$reverse_domain_a[] = "$subnet_num.172.in-addr.arpa";
2456
			}
2457

    
2458
			// Set the --server parameter to nowhere for each reverse domain name that was not specifically specified in a domain override.
2459
			foreach ($reverse_domain_a as $reverse_domain) {
2460
				if (!isset($override_a[$reverse_domain])) {
2461
					$args .= " --server=/$reverse_domain/ ";
2462
				}
2463
			}
2464
			unset($override_a);
2465
			unset($reverse_domain_a);
2466
		}
2467

    
2468
		/* Setup forwarded domains */
2469
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2470
			foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2471
				if ($override['ip'] == "!") {
2472
					$override['ip'] = "";
2473
				}
2474
				$args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
2475
			}
2476
		}
2477

    
2478
		/* Allow DNS Rebind for forwarded domains */
2479
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2480
			if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2481
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2482
					$args .= ' --rebind-domain-ok=/' . $override['domain'] . '/ ';
2483
				}
2484
			}
2485
		}
2486

    
2487
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2488
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2489
		}
2490

    
2491
		if (isset($config['dnsmasq']['strict_order'])) {
2492
			$args .= " --strict-order ";
2493
		}
2494

    
2495
		if (isset($config['dnsmasq']['domain_needed'])) {
2496
			$args .= " --domain-needed ";
2497
		}
2498

    
2499
		if ($config['dnsmasq']['custom_options']) {
2500
			foreach (preg_split('/\s+/', $config['dnsmasq']['custom_options']) as $c) {
2501
				$args .= " " . escapeshellarg("--{$c}");
2502
				$p = explode('=', $c);
2503
				if (array_key_exists($p[0], $standard_args)) {
2504
					unset($standard_args[$p[0]]);
2505
				}
2506
			}
2507
		}
2508
		$args .= ' ' . implode(' ', array_values($standard_args));
2509

    
2510
		/* run dnsmasq. Use "-C /dev/null" since we use command line args only (Issue #6730) */
2511
		$cmd = "/usr/local/sbin/dnsmasq --all-servers -C /dev/null {$dns_rebind} {$args}";
2512
		//log_error("dnsmasq command: {$cmd}");
2513
		mwexec_bg($cmd);
2514
		unset($args);
2515

    
2516
		system_dhcpleases_configure();
2517

    
2518
		if (platform_booting()) {
2519
			echo gettext("done.") . "\n";
2520
		}
2521
	}
2522

    
2523
	if (!platform_booting() && $restart_dhcp) {
2524
		if (services_dhcpd_configure() != 0) {
2525
			$return = 1;
2526
		}
2527
	}
2528

    
2529
	return $return;
2530
}
2531

    
2532
function services_unbound_configure($restart_dhcp = true) {
2533
	global $config, $g;
2534
	$return = 0;
2535

    
2536
	if (isset($config['system']['developerspew'])) {
2537
		$mt = microtime();
2538
		echo "services_unbound_configure() being called $mt\n";
2539
	}
2540

    
2541
	if (isset($config['unbound']['enable'])) {
2542
		require_once('/etc/inc/unbound.inc');
2543

    
2544
		/* Stop Unbound using TERM */
2545
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2546
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
2547
		}
2548

    
2549
		/* If unbound is still running, wait up to 30 seconds for it to terminate. */
2550
		for ($i=1; $i <= 30; $i++) {
2551
			if (is_process_running('unbound')) {
2552
				sleep(1);
2553
			}
2554
		}
2555

    
2556
		$python_mode = false;
2557
		if (isset($config['unbound']['python']) && !empty($config['unbound']['python_script'])) {
2558
			$python_mode = true;
2559
		}
2560

    
2561
		/* Include any additional functions as defined by python script include file */
2562
		if (file_exists("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc")) {
2563
			exec("/usr/local/bin/php -l " . escapeshellarg("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc")
2564
				. " 2>&1", $py_output, $py_retval);
2565
			if ($py_retval == 0) {
2566
				require_once("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc");
2567
			}
2568
		}
2569

    
2570
		/* DNS Resolver python integration */
2571
		if ($python_mode) {
2572
			if (!is_dir("{$g['unbound_chroot_path']}/dev")) {
2573
				safe_mkdir("{$g['unbound_chroot_path']}/dev");
2574
			}
2575
			$status = "/sbin/mount | /usr/bin/grep " .  escapeshellarg("{$g['unbound_chroot_path']}/dev");
2576
			if (!trim($status)) {
2577
				exec("/sbin/mount -t devfs devfs " . escapeshellarg("{$g['unbound_chroot_path']}/dev"));
2578
			}
2579
		} else {
2580
			if (is_dir("{$g['unbound_chroot_path']}/dev")) {
2581
				exec("/sbin/umount -f " . escapeshellarg("{$g['unbound_chroot_path']}/dev"));
2582
			}
2583
		}
2584
		$base_folder = '/usr/local';
2585
		foreach (array('/bin', '/lib') as $dir) {
2586
			$validate = exec("/sbin/mount | /usr/bin/grep " . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir} (nullfs") . " 2>&1");
2587
			if ($python_mode) {
2588

    
2589
				// Add DNS Resolver python integration
2590
				if (empty($validate)) {
2591
					if (!is_dir("{$g['unbound_chroot_path']}{$base_folder}{$dir}")) {
2592
						safe_mkdir("{$g['unbound_chroot_path']}{$base_folder}{$dir}");
2593
					}
2594
					$output = $retval = '';
2595
					exec("/sbin/mount_nullfs -o ro " . escapeshellarg("/usr/local{$dir}") . ' '
2596
					    . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir}") . " 2>&1", $output, $retval);
2597

    
2598
					// Disable Unbound python on mount failure
2599
					if ($retval != 0) {
2600
						$config['unbound']['python'] = '';
2601
						$log_msg = "[Unbound-pymod]: Disabling Unbound python due to failed mount";
2602
						write_config($log_msg);
2603
						log_error($log_msg);
2604
					}
2605
				}
2606
			}
2607

    
2608
			// Remove DNS Resolver python integration
2609
			elseif (!empty($validate)) {
2610
				exec("/sbin/umount -t nullfs " . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir}") . " 2>&1", $output, $retval);
2611
				if ($retval == 0) {
2612
					foreach (array( "/usr/local{$dir}", '/usr/local', '/usr') as $folder) {
2613
						if (!empty($g['unbound_chroot_path']) && $g['unbound_chroot_path'] != '/' && is_dir("{$g['unbound_chroot_path']}{$folder}")) {
2614
							@rmdir(escapeshellarg("{$g['unbound_chroot_path']}{$folder}"));
2615
						}
2616

    
2617
						// Delete remaining subfolders on next loop
2618
						if ($dir == '/bin') {
2619
							break;
2620
						}
2621
					}
2622
				}
2623
				else {
2624
					log_error("[Unbound-pymod]: Failed to unmount!");
2625
				}
2626
			}
2627
		}
2628

    
2629
		if (platform_booting()) {
2630
			echo gettext("Starting DNS Resolver...");
2631
		} else {
2632
			sleep(1);
2633
		}
2634

    
2635
		/* generate hosts file */
2636
		if (system_hosts_generate() != 0) {
2637
			$return = 1;
2638
		}
2639

    
2640
		/* Check here for dhcp6 complete - wait upto 10 seconds */
2641
		if($config['interfaces']["wan"]['ipaddrv6'] == 'dhcp6') {
2642
			$wanif = get_real_interface("wan", "inet6");
2643
			if (platform_booting()) {
2644
				for ($i=1; $i <= 10; $i++) {
2645
					if (!file_exists("/tmp/{$wanif}_dhcp6_complete")) {
2646
						log_error(gettext("Unbound start waiting on dhcp6c."));
2647
						sleep(1);
2648
					} else {
2649
						unlink_if_exists("/tmp/{$wanif}_dhcp6_complete");
2650
						log_error(gettext("dhcp6 init complete. Continuing"));
2651
						break;
2652
					}
2653
				}
2654
			}
2655
		}
2656

    
2657
		sync_unbound_service();
2658
		if (platform_booting()) {
2659
			log_error(gettext("sync unbound done."));
2660
			echo gettext("done.") . "\n";
2661
		}
2662

    
2663
		system_dhcpleases_configure();
2664
	} else {
2665
		/* kill Unbound since it should not be enabled */
2666
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2667
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "KILL");
2668
		}
2669
	}
2670

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

    
2677
	return $return;
2678
}
2679

    
2680
function services_snmpd_configure() {
2681
	global $config, $g;
2682
	if (isset($config['system']['developerspew'])) {
2683
		$mt = microtime();
2684
		echo "services_snmpd_configure() being called $mt\n";
2685
	}
2686

    
2687
	/* kill any running snmpd */
2688
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
2689
	sleep(2);
2690
	if (is_process_running("bsnmpd")) {
2691
		mwexec("/usr/bin/killall bsnmpd", true);
2692
	}
2693

    
2694
	if (isset($config['snmpd']['enable'])) {
2695

    
2696
		if (platform_booting()) {
2697
			echo gettext("Starting SNMP daemon... ");
2698
		}
2699

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

    
2705
		/* generate snmpd.conf */
2706
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
2707
		if (!$fd) {
2708
			printf(gettext("Error: cannot open snmpd.conf in services_snmpd_configure().%s"), "\n");
2709
			return 1;
2710
		}
2711

    
2712

    
2713
		$snmpdconf = <<<EOD
2714
location := "{$config['snmpd']['syslocation']}"
2715
contact := "{$config['snmpd']['syscontact']}"
2716
read := "{$config['snmpd']['rocommunity']}"
2717

    
2718
EOD;
2719

    
2720
/* No docs on what write strings do there so disable for now.
2721
		if (isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])) {
2722
			$snmpdconf .= <<<EOD
2723
# write string
2724
write := "{$config['snmpd']['rwcommunity']}"
2725

    
2726
EOD;
2727
		}
2728
*/
2729

    
2730

    
2731
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2732
			$snmpdconf .= <<<EOD
2733
# SNMP Trap support.
2734
traphost := {$config['snmpd']['trapserver']}
2735
trapport := {$config['snmpd']['trapserverport']}
2736
trap := "{$config['snmpd']['trapstring']}"
2737

    
2738

    
2739
EOD;
2740
		}
2741

    
2742
		$sysDescr = "{$g['product_label']} {$config['system']['hostname']}.{$config['system']['domain']}" .
2743
			" {$g['product_version_string']} " . php_uname("s") .
2744
			" " . php_uname("r") . " " . php_uname("m");
2745

    
2746
		$snmpdconf .= <<<EOD
2747
system := 1     # pfSense
2748
%snmpd
2749
sysDescr			= "{$sysDescr}"
2750
begemotSnmpdDebugDumpPdus       = 2
2751
begemotSnmpdDebugSyslogPri      = 7
2752
begemotSnmpdCommunityString.0.1 = $(read)
2753

    
2754
EOD;
2755

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

    
2761
EOD;
2762
		}
2763
*/
2764

    
2765

    
2766
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2767
			$snmpdconf .= <<<EOD
2768
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
2769
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
2770
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
2771

    
2772
EOD;
2773
		}
2774

    
2775

    
2776
		$snmpdconf .= <<<EOD
2777
begemotSnmpdCommunityDisable    = 1
2778

    
2779
EOD;
2780

    
2781
		$bind_to_ips = array();
2782
		$bind_to_ip6s = array();
2783
		if (isset($config['snmpd']['bindip'])) {
2784
			if (!isset($config['snmpd']['ipprotocol']) ||
2785
			    (isset($config['snmpd']['ipprotocol']) &&
2786
			    strstr($config['snmpd']['ipprotocol'], "4"))) {
2787
				$inet4 = true;
2788
			}
2789
			if (isset($config['snmpd']['ipprotocol']) &&
2790
			    strstr($config['snmpd']['ipprotocol'], "6")) {
2791
				$inet6 = true;
2792
			}
2793
			foreach (explode(",", $config['snmpd']['bindip']) as $bind_to_ip) {
2794
				if (is_ipaddr($bind_to_ip)) {
2795
					$bind_to_ips[] = $bind_to_ip;
2796
				} else {
2797
					$if = get_real_interface($bind_to_ip);
2798
					if (does_interface_exist($if)) {
2799
						if ($inet4) {
2800
							$bindip = get_interface_ip($bind_to_ip);
2801
							if (is_ipaddrv4($bindip)) {
2802
								$bind_to_ips[] = $bindip;
2803
							}
2804
						}
2805
						if ($inet6) {
2806
							$bindip6 = get_interface_ipv6($bind_to_ip);
2807
							if (is_ipaddrv6($bindip6)) {
2808
								$bind_to_ip6s[] = $bindip6;
2809
							}
2810
						}
2811
					}
2812
				}
2813
			}
2814
		}
2815
		if (!count($bind_to_ips) && $inet4) {
2816
			$bind_to_ips = array("0.0.0.0");
2817
		}
2818
		if (!count($bind_to_ip6s) && $inet6) {
2819
			$bind_to_ip6s = array("::");
2820
		}
2821

    
2822
		if (is_port($config['snmpd']['pollport'])) {
2823
			foreach ($bind_to_ips as $bind_to_ip) {
2824
				$snmpdconf .= <<<EOD
2825
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
2826

    
2827
EOD;
2828

    
2829
			}
2830
			foreach ($bind_to_ip6s as $bind_to_ip6) {
2831
				$bind_to_ip6 = ip6_to_asn1($bind_to_ip6);
2832
				$snmpdconf .= <<<EOD
2833
begemotSnmpdTransInetStatus.2.16.{$bind_to_ip6}{$config['snmpd']['pollport']}.1 = 4
2834

    
2835
EOD;
2836

    
2837
			}
2838
		}
2839

    
2840
		$snmpdconf .= <<<EOD
2841
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
2842
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
2843

    
2844
# These are bsnmp macros not php vars.
2845
sysContact      = $(contact)
2846
sysLocation     = $(location)
2847
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
2848

    
2849
snmpEnableAuthenTraps = 2
2850

    
2851
EOD;
2852

    
2853
		if (is_array($config['snmpd']['modules'])) {
2854
			if (isset($config['snmpd']['modules']['mibii'])) {
2855
			$snmpdconf .= <<<EOD
2856
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
2857

    
2858
EOD;
2859
			}
2860

    
2861
			if (isset($config['snmpd']['modules']['netgraph'])) {
2862
				$snmpdconf .= <<<EOD
2863
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
2864
%netgraph
2865
begemotNgControlNodeName = "snmpd"
2866

    
2867
EOD;
2868
			}
2869

    
2870
			if (isset($config['snmpd']['modules']['pf'])) {
2871
				$snmpdconf .= <<<EOD
2872
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
2873

    
2874
EOD;
2875
			}
2876

    
2877
			if (isset($config['snmpd']['modules']['hostres'])) {
2878
				$snmpdconf .= <<<EOD
2879
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
2880

    
2881
EOD;
2882
			}
2883

    
2884
			if (isset($config['snmpd']['modules']['bridge'])) {
2885
				$snmpdconf .= <<<EOD
2886
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
2887
# config must end with blank line
2888

    
2889
EOD;
2890
			}
2891
			if (isset($config['snmpd']['modules']['ucd'])) {
2892
				$snmpdconf .= <<<EOD
2893
begemotSnmpdModulePath."ucd"     = "/usr/local/lib/snmp_ucd.so"
2894

    
2895
EOD;
2896
			}
2897
			if (isset($config['snmpd']['modules']['regex'])) {
2898
				$snmpdconf .= <<<EOD
2899
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"
2900

    
2901
EOD;
2902
			}
2903
		}
2904

    
2905
		fwrite($fd, $snmpdconf);
2906
		fclose($fd);
2907
		unset($snmpdconf);
2908

    
2909
		/* run bsnmpd */
2910
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
2911
			" -p {$g['varrun_path']}/snmpd.pid");
2912

    
2913
		if (platform_booting()) {
2914
			echo gettext("done.") . "\n";
2915
		}
2916
	}
2917

    
2918
	return 0;
2919
}
2920

    
2921
function services_dnsupdate_process($int = "", $updatehost = "", $forced = false) {
2922
	global $config, $g;
2923
	if (isset($config['system']['developerspew'])) {
2924
		$mt = microtime();
2925
		echo "services_dnsupdate_process() being called $mt\n";
2926
	}
2927

    
2928
	/* Dynamic DNS updating active? */
2929
	if (!is_array($config['dnsupdates']['dnsupdate'])) {
2930
		return 0;
2931
	}
2932

    
2933
	$notify_text = "";
2934
	$gwgroups = return_gateway_groups_array(true);
2935
	foreach ($config['dnsupdates']['dnsupdate'] as $i => $dnsupdate) {
2936
		if (!isset($dnsupdate['enable'])) {
2937
			continue;
2938
		}
2939
		/*
2940
		 * If it's using a gateway group, check if interface is
2941
		 * the active gateway for that group
2942
		 */
2943
		$group_int = '';
2944
		$friendly_group_int = '';
2945
		$gwgroup_member = false;
2946
		if (is_array($gwgroups[$dnsupdate['interface']])) {
2947
			if (!empty($gwgroups[$dnsupdate['interface']][0]['vip'])) {
2948
				$group_int = $gwgroups[$dnsupdate['interface']][0]['vip'];
2949
			} else {
2950
				$group_int = $gwgroups[$dnsupdate['interface']][0]['int'];
2951
				$friendly_group_int =
2952
				    convert_real_interface_to_friendly_interface_name(
2953
					$group_int);
2954
				if (!empty($int)) {
2955
					$gwgroup_member =
2956
					    interface_gateway_group_member(get_real_interface($int),
2957
					    $dnsupdate['interface']);
2958
				}
2959
			}
2960
		}
2961
		if (!empty($int) && ($int != $dnsupdate['interface']) && !$gwgroup_member &&
2962
		    ($int != $group_int) && ($int != $friendly_group_int)) {
2963
			continue;
2964
		}
2965
		if (!empty($updatehost) && ($updatehost != $dnsupdate['host'])) {
2966
			continue;
2967
		}
2968

    
2969
		/* determine interface name */
2970
		$if = get_failover_interface($dnsupdate['interface']);
2971

    
2972
		/* Determine address to update and default binding address */
2973
		if (isset($dnsupdate['usepublicip'])) {
2974
			$wanip = dyndnsCheckIP($if);
2975
			if (is_private_ip($wanip)) {
2976
				log_error(sprintf(gettext(
2977
				    "phpDynDNS: Not updating %s A record because the public IP address cannot be determined."),
2978
				    $dnsupdate['host']));
2979
				continue;
2980
			}
2981
			$bindipv4 = get_interface_ip($if);
2982
		} else {
2983
			$wanip = get_interface_ip($if);
2984
			$bindipv4 = $wanip;
2985
		}
2986
		if (is_stf_interface($dnsupdate['interface'])) { 
2987
			$wanipv6 = get_interface_ipv6($dnsupdate['interface'] . '_stf');
2988
		} else {
2989
			$wanipv6 = get_interface_ipv6($if);
2990
		}
2991
		$bindipv6 = $wanipv6;
2992

    
2993
		/* Handle non-default interface bindings */
2994
		if ($dnsupdate['updatesource'] == "none") {
2995
			/* When empty, the directive will be omitted. */
2996
			$bindipv4 = "";
2997
			$bindipv6 = "";
2998
		} elseif (!empty($dnsupdate['updatesource'])) {
2999
			/* Find the alternate binding address */
3000
			$bindipv4 = get_interface_ip($dnsupdate['updatesource']);
3001
			if (is_stf_interface($dnsupdate['interface'])) { 
3002
				$bindipv6 = get_interface_ipv6($dnsupdate['updatesource'] . '_stf');
3003
			} else {
3004
				$bindipv6 = get_interface_ipv6($dnsupdate['updatesource']);
3005
			}
3006
		}
3007

    
3008
		/* Handle IPv4/IPv6 selection for the update source interface/VIP */
3009
		switch ($dnsupdate['updatesourcefamily']) {
3010
			case "inet":
3011
				$bindip = $bindipv4;
3012
				break;
3013
			case "inet6":
3014
				$bindip = $bindipv6;
3015
				break;
3016
			case "":
3017
			default:
3018
				/* Try IPv4 first, if that is empty, try IPv6. */
3019
				/* Only specify the address if it's present, otherwise omit. */
3020
				if (!empty($bindipv4)) {
3021
					$bindip = $bindipv4;
3022
				} elseif (!empty($bindipv6)) {
3023
					$bindip = $bindipv6;
3024
				}
3025
				break;
3026
		}
3027

    
3028
		$cacheFile = $g['conf_path'] .
3029
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
3030
		    escapeshellarg($dnsupdate['host']) .
3031
		    "_{$dnsupdate['server']}.cache";
3032
		$cacheFilev6 = $g['conf_path'] .
3033
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
3034
		    escapeshellarg($dnsupdate['host']) .
3035
		    "_{$dnsupdate['server']}_v6.cache";
3036
		$currentTime = time();
3037

    
3038
		if (!$wanip && !$wanipv6) {
3039
			continue;
3040
		}
3041

    
3042
		$keyname = $dnsupdate['keyname'];
3043
		/* trailing dot */
3044
		if (substr($keyname, -1) != ".") {
3045
			$keyname .= ".";
3046
		}
3047

    
3048
		$hostname = $dnsupdate['host'];
3049
		/* trailing dot */
3050
		if (substr($hostname, -1) != ".") {
3051
			$hostname .= ".";
3052
		}
3053

    
3054
		/* write key file */
3055
		$algorithm = empty($dnsupdate['keyalgorithm']) ? 'hmac-md5' : $dnsupdate['keyalgorithm'];
3056
		$upkey = <<<EOD
3057
key "{$keyname}" {
3058
	algorithm {$algorithm};
3059
	secret "{$dnsupdate['keydata']}";
3060
};
3061

    
3062
EOD;
3063
		@file_put_contents("{$g['varetc_path']}/nsupdatekey{$i}", $upkey);
3064

    
3065
		/* generate update instructions */
3066
		$upinst = "";
3067
		if (!empty($dnsupdate['server'])) {
3068
			$upinst .= "server {$dnsupdate['server']}\n";
3069
		}
3070

    
3071
		if (!empty($dnsupdate['zone'])) {
3072
			$upinst .= "zone {$dnsupdate['zone']}\n";
3073
		}
3074

    
3075
		$cachedipv4 = '';
3076
		$cacheTimev4 = 0;
3077
		if (file_exists($cacheFile)) {
3078
			list($cachedipv4, $cacheTimev4) = explode("|",
3079
			    file_get_contents($cacheFile));
3080
		}
3081
		$cachedipv6 = '';
3082
		$cacheTimev6 = 0;
3083
		if (file_exists($cacheFilev6)) {
3084
			list($cachedipv6, $cacheTimev6) = explode("|",
3085
			    file_get_contents($cacheFilev6));
3086
		}
3087

    
3088
		// 25 Days
3089
		$maxCacheAgeSecs = 25 * 24 * 60 * 60;
3090
		$need_update = false;
3091

    
3092
		/* Update IPv4 if we have it. */
3093
		if (is_ipaddrv4($wanip) && $dnsupdate['recordtype'] != "AAAA") {
3094
			if (($wanip != $cachedipv4) || $forced ||
3095
			    (($currentTime - $cacheTimev4) > $maxCacheAgeSecs)) {
3096
				$upinst .= "update delete " .
3097
				    "{$dnsupdate['host']}. A\n";
3098
				$upinst .= "update add {$dnsupdate['host']}. " .
3099
				    "{$dnsupdate['ttl']} A {$wanip}\n";
3100
				if (!empty($bindip)) {
3101
					$upinst .= "local {$bindip}\n";
3102
				}
3103
				$need_update = true;
3104
			} else {
3105
				log_error(sprintf(gettext(
3106
				    "phpDynDNS: Not updating %s A record because the IP address has not changed."),
3107
				    $dnsupdate['host']));
3108
			}
3109
		} else {
3110
			@unlink($cacheFile);
3111
			unset($cacheFile);
3112
		}
3113

    
3114
		/* Update IPv6 if we have it. */
3115
		if (is_ipaddrv6($wanipv6) && $dnsupdate['recordtype'] != "A") {
3116
			if (($wanipv6 != $cachedipv6) || $forced ||
3117
			    (($currentTime - $cacheTimev6) > $maxCacheAgeSecs)) {
3118
				$upinst .= "update delete " .
3119
				    "{$dnsupdate['host']}. AAAA\n";
3120
				$upinst .= "update add {$dnsupdate['host']}. " .
3121
				    "{$dnsupdate['ttl']} AAAA {$wanipv6}\n";
3122
				$need_update = true;
3123
			} else {
3124
				log_error(sprintf(gettext(
3125
				    "phpDynDNS: Not updating %s AAAA record because the IPv6 address has not changed."),
3126
				    $dnsupdate['host']));
3127
			}
3128
		} else {
3129
			@unlink($cacheFilev6);
3130
			unset($cacheFilev6);
3131
		}
3132

    
3133
		$upinst .= "\n";	/* mind that trailing newline! */
3134

    
3135
		if (!$need_update) {
3136
			continue;
3137
		}
3138

    
3139
		@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}", $upinst);
3140
		unset($upinst);
3141
		/* invoke nsupdate */
3142
		$cmd = "/usr/local/bin/nsupdate -k {$g['varetc_path']}/nsupdatekey{$i}";
3143

    
3144
		if (isset($dnsupdate['usetcp'])) {
3145
			$cmd .= " -v";
3146
		}
3147

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

    
3150
		if (mwexec($cmd) == 0) {
3151
			if (!empty($cacheFile)) {
3152
				@file_put_contents($cacheFile,
3153
				    "{$wanip}|{$currentTime}");
3154
				log_error(sprintf(gettext(
3155
				    'phpDynDNS: updating cache file %1$s: %2$s'),
3156
				    $cacheFile, $wanip));
3157
				$notify_text .= sprintf(gettext(
3158
				    'DynDNS updated IP Address (A) for %1$s on %2$s (%3$s) to %4$s'),
3159
				    $dnsupdate['host'],
3160
				    convert_real_interface_to_friendly_descr($if),
3161
				    $if, $wanip) . "\n";
3162
			}
3163
			if (!empty($cacheFilev6)) {
3164
				@file_put_contents($cacheFilev6,
3165
				    "{$wanipv6}|{$currentTime}");
3166
				log_error(sprintf(gettext(
3167
				    'phpDynDNS: updating cache file %1$s: %2$s'),
3168
				    $cacheFilev6, $wanipv6));
3169
				$notify_text .= sprintf(gettext(
3170
				    'DynDNS updated IPv6 Address (AAAA) for %1$s on %2$s (%3$s) to %4$s'),
3171
				    $dnsupdate['host'],
3172
				    convert_real_interface_to_friendly_descr($if),
3173
				    $if, $wanipv6) . "\n";
3174
			}
3175
		} else {
3176
			if (!empty($cacheFile)) {
3177
				log_error(sprintf(gettext(
3178
				    'phpDynDNS: ERROR while updating IP Address (A) for %1$s (%2$s)'),
3179
				    $dnsupdate['host'], $wanip));
3180
			}
3181
			if (!empty($cacheFilev6)) {
3182
				log_error(sprintf(gettext(
3183
				    'phpDynDNS: ERROR while updating IP Address (AAAA) for %1$s (%2$s)'),
3184
				    $dnsupdate['host'], $wanipv6));
3185
			}
3186
		}
3187
		unset($cmd);
3188
	}
3189

    
3190
	if (!empty($notify_text)) {
3191
		notify_all_remote($notify_text);
3192
	}
3193

    
3194
	return 0;
3195
}
3196

    
3197
/* configure cron service */
3198
function configure_cron() {
3199
	global $g, $config;
3200

    
3201
	/* preserve existing crontab entries */
3202
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
3203

    
3204
	for ($i = 0; $i < count($crontab_contents); $i++) {
3205
		$cron_item = &$crontab_contents[$i];
3206
		if (strpos($cron_item, "# pfSense specific crontab entries") !== false) {
3207
			array_splice($crontab_contents, $i - 1);
3208
			break;
3209
		}
3210
	}
3211
	$crontab_contents = implode("\n", $crontab_contents) . "\n";
3212

    
3213

    
3214
	if (is_array($config['cron']['item'])) {
3215
		$crontab_contents .= "#\n";
3216
		$crontab_contents .= "# pfSense specific crontab entries\n";
3217
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
3218
		$crontab_contents .= "#\n";
3219

    
3220
		if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) {
3221
			$http_proxy = $config['system']['proxyurl'];
3222
			if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) {
3223
				$http_proxy .= ':' . $config['system']['proxyport'];
3224
			}
3225
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
3226

    
3227
			if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
3228
				$crontab_contents .= "HTTP_PROXY_AUTH=basic:*:{$config['system']['proxyuser']}:{$config['system']['proxypass']}";
3229
			}
3230
		}
3231

    
3232
		foreach ($config['cron']['item'] as $item) {
3233
			$crontab_contents .= "\n{$item['minute']}\t";
3234
			$crontab_contents .= "{$item['hour']}\t";
3235
			$crontab_contents .= "{$item['mday']}\t";
3236
			$crontab_contents .= "{$item['month']}\t";
3237
			$crontab_contents .= "{$item['wday']}\t";
3238
			$crontab_contents .= "{$item['who']}\t";
3239
			$crontab_contents .= "{$item['command']}";
3240
		}
3241

    
3242
		$crontab_contents .= "\n#\n";
3243
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
3244
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
3245
		$crontab_contents .= "#\n\n";
3246
	}
3247

    
3248
	/* please maintain the newline at the end of file */
3249
	file_put_contents("/etc/crontab", $crontab_contents);
3250
	unset($crontab_contents);
3251

    
3252
	/* make sure that cron is running and start it if it got killed somehow */
3253
	if (!is_process_running("cron")) {
3254
		exec("cd /tmp && /usr/sbin/cron -s 2>/dev/null");
3255
	} else {
3256
	/* do a HUP kill to force sync changes */
3257
		sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP");
3258
	}
3259

    
3260
}
3261

    
3262
function upnp_action ($action) {
3263
	global $g, $config;
3264
	switch ($action) {
3265
		case "start":
3266
			if (file_exists('/var/etc/miniupnpd.conf')) {
3267
				@unlink("{$g['varrun_path']}/miniupnpd.pid");
3268
				mwexec_bg("/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf -P {$g['varrun_path']}/miniupnpd.pid");
3269
			}
3270
			break;
3271
		case "stop":
3272
			killbypid("{$g['varrun_path']}/miniupnpd.pid");
3273
			while ((int)exec("/bin/pgrep -a miniupnpd | wc -l") > 0) {
3274
				mwexec('/usr/bin/killall miniupnpd 2>/dev/null', true);
3275
			}
3276
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
3277
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
3278
			break;
3279
		case "restart":
3280
			upnp_action('stop');
3281
			upnp_action('start');
3282
			break;
3283
	}
3284
}
3285

    
3286
function upnp_start() {
3287
	global $config;
3288

    
3289
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
3290
		return;
3291
	}
3292

    
3293
	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
3294
		echo gettext("Starting UPnP service... ");
3295
		require_once('/usr/local/pkg/miniupnpd.inc');
3296
		sync_package_miniupnpd();
3297
		echo "done.\n";
3298
	}
3299
}
3300

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

    
3304
	$is_installed = false;
3305
	$cron_changed = true;
3306
	$change_message = "";
3307

    
3308
	if (!is_array($config['cron'])) {
3309
		$config['cron'] = array();
3310
	}
3311
	if (!is_array($config['cron']['item'])) {
3312
		$config['cron']['item'] = array();
3313
	}
3314

    
3315
	$x = 0;
3316
	foreach ($config['cron']['item'] as $item) {
3317
		if (strstr($item['command'], $command)) {
3318
			$is_installed = true;
3319
			break;
3320
		}
3321
		$x++;
3322
	}
3323

    
3324
	if ($active) {
3325
		$cron_item = array();
3326
		$cron_item['minute'] = $minute;
3327
		$cron_item['hour'] = $hour;
3328
		$cron_item['mday'] = $monthday;
3329
		$cron_item['month'] = $month;
3330
		$cron_item['wday'] = $weekday;
3331
		$cron_item['who'] = $who;
3332
		$cron_item['command'] = $command;
3333
		if (!$is_installed) {
3334
			$config['cron']['item'][] = $cron_item;
3335
			$change_message = "Installed cron job for %s";
3336
		} else {
3337
			if ($config['cron']['item'][$x] == $cron_item) {
3338
				$cron_changed = false;
3339
			} else {
3340
				$config['cron']['item'][$x] = $cron_item;
3341
				$change_message = "Updated cron job for %s";
3342
			}
3343
		}
3344
	} else {
3345
		if ($is_installed == true) {
3346
			array_splice($config['cron']['item'], $x, 1);
3347
			$change_message = "Removed cron job for %s";
3348
		} else {
3349
			$cron_changed = false;
3350
		}
3351
	}
3352

    
3353
	if ($cron_changed) {
3354
		/* Optionally write the configuration if this function made changes.
3355
		 * Performing a write_config() in this way can have unintended side effects. See #7146
3356
		 * Base system instances of this function do not need to write, packages may.
3357
		 */
3358
		if ($write_config) {
3359
			write_config(sprintf(gettext($change_message), $command));
3360
		}
3361
		configure_cron();
3362
	}
3363
}
3364

    
3365
?>
(46-46/61)