Project

General

Profile

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

    
26

    
27
define('DYNDNS_PROVIDER_VALUES', 'all-inkl azure azurev6 citynetwork cloudflare cloudflare-v6 cloudns custom custom-v6 digitalocean digitalocean-v6 dnsexit dnsimple dnsmadeeasy dnsomatic dreamhost dreamhost-v6 duiadns duiadns-v6 dyndns dyndns-custom dyndns-static dyns easydns eurodns freedns freedns-v6 glesys gandi-livedns godaddy godaddy-v6 googledomains gratisdns he-net he-net-v6 he-net-tunnelbroker hover linode linode-v6 loopia namecheap noip noip-free ods opendns ovh-dynhost route53 route53-v6 selfhost spdyn spdyn-v6 zoneedit');
28
define('DYNDNS_PROVIDER_DESCRIPTIONS', 'All-Inkl.com,Azure DNS,Azure DNS (v6),City Network,Cloudflare,Cloudflare (v6),ClouDNS,Custom,Custom (v6),DigitalOcean,DigitalOcean (v6),DNSexit,DNSimple,DNS Made Easy,DNS-O-Matic,DreamHost,Dreamhost (v6),DuiaDns.net,DuiaDns.net (v6),DynDNS (dynamic),DynDNS (custom),DynDNS (static),DyNS,easyDNS,Euro Dns,freeDNS,freeDNS (v6),GleSYS,Gandi Live DNS,GoDaddy,GoDaddy (v6),Google Domains,GratisDNS,HE.net,HE.net (v6),HE.net Tunnelbroker,Hover,Linode,Linode (v6),Loopia,Namecheap,No-IP,No-IP (free),ODS.org,OpenDNS,OVH DynHOST,Route 53,Route 53 (v6),SelfHost,SPDYN,SPDYN (v6),ZoneEdit');
29

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

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

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

    
43
	$Iflist = get_configured_interface_list();
44
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
45

    
46
	$radvdconf = "# Automatically Generated, do not edit\n";
47

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

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

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

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

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

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

    
90
		$realif = get_real_interface($dhcpv6if, "inet6");
91

    
92
		if (isset($radvdifs[$realif])) {
93
			continue;
94
		}
95

    
96
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
97
		if (!is_ipaddrv6($ifcfgipv6)) {
98
			continue;
99
		}
100

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

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

    
116
		if (is_numericint($dhcpv6ifconf['raminrtradvinterval'])) {
117
			$radvdconf .= "\tMinRtrAdvInterval {$dhcpv6ifconf['raminrtradvinterval']};\n";
118
		} else {
119
			$radvdconf .= "\tMinRtrAdvInterval 5;\n";
120
		}
121

    
122
		if (is_numericint($dhcpv6ifconf['ramaxrtradvinterval'])) {
123
			$radvdconf .= "\tMaxRtrAdvInterval {$dhcpv6ifconf['ramaxrtradvinterval']};\n";
124
		} else {
125
			$radvdconf .= "\tMaxRtrAdvInterval 20;\n";
126
		}
127
		if (is_numericint($dhcpv6ifconf['raadvdefaultlifetime'])) {
128
			$radvdconf .= "\tAdvDefaultLifetime {$dhcpv6ifconf['raadvdefaultlifetime']};\n";
129
		}
130

    
131
		$mtu = get_interface_mtu($realif);
132
		if (is_numeric($mtu)) {
133
			$radvdconf .= "\tAdvLinkMTU {$mtu};\n";
134
		} else {
135
			$radvdconf .= "\tAdvLinkMTU 1280;\n";
136
		}
137
		switch ($dhcpv6ifconf['rapriority']) {
138
			case "low":
139
				$radvdconf .= "\tAdvDefaultPreference low;\n";
140
				break;
141
			case "high":
142
				$radvdconf .= "\tAdvDefaultPreference high;\n";
143
				break;
144
			default:
145
				$radvdconf .= "\tAdvDefaultPreference medium;\n";
146
				break;
147
		}
148
		switch ($dhcpv6ifconf['ramode']) {
149
			case "managed":
150
			case "assist":
151
				$radvdconf .= "\tAdvManagedFlag on;\n";
152
				$radvdconf .= "\tAdvOtherConfigFlag on;\n";
153
				break;
154
			case "stateless_dhcp":
155
				$radvdconf .= "\tAdvManagedFlag off;\n";
156
				$radvdconf .= "\tAdvOtherConfigFlag on;\n";
157
				break;
158
		}
159
		$radvdconf .= "\tprefix {$subnetv6}/{$ifcfgsnv6} {\n";
160
		if ($racarpif == true) {
161
			$radvdconf .= "\t\tDeprecatePrefix off;\n";
162
		} else {
163
			$radvdconf .= "\t\tDeprecatePrefix on;\n";
164
		}
165
		switch ($dhcpv6ifconf['ramode']) {
166
			case "managed":
167
				$radvdconf .= "\t\tAdvOnLink on;\n";
168
				$radvdconf .= "\t\tAdvAutonomous off;\n";
169
				$radvdconf .= "\t\tAdvRouterAddr on;\n";
170
				break;
171
			case "router":
172
				$radvdconf .= "\t\tAdvOnLink off;\n";
173
				$radvdconf .= "\t\tAdvAutonomous off;\n";
174
				$radvdconf .= "\t\tAdvRouterAddr on;\n";
175
				break;
176
			case "stateless_dhcp":
177
			case "assist":
178
				$radvdconf .= "\t\tAdvOnLink on;\n";
179
				$radvdconf .= "\t\tAdvAutonomous on;\n";
180
				$radvdconf .= "\t\tAdvRouterAddr on;\n";
181
				break;
182
			case "unmanaged":
183
				$radvdconf .= "\t\tAdvOnLink on;\n";
184
				$radvdconf .= "\t\tAdvAutonomous on;\n";
185
				$radvdconf .= "\t\tAdvRouterAddr on;\n";
186
				break;
187
		}
188

    
189
		if (is_numericint($dhcpv6ifconf['ravalidlifetime'])) {
190
		  $radvdconf .= "\t\tAdvValidLifetime {$dhcpv6ifconf['ravalidlifetime']};\n";
191
		} else {
192
		  $radvdconf .= "\t\tAdvValidLifetime 86400;\n";
193
		}
194

    
195
		if (is_numericint($dhcpv6ifconf['rapreferredlifetime'])) {
196
		  $radvdconf .= "\t\tAdvPreferredLifetime {$dhcpv6ifconf['rapreferredlifetime']};\n";
197
		} else {
198
		  $radvdconf .= "\t\tAdvPreferredLifetime 14400;\n";
199
		}
200

    
201
		$radvdconf .= "\t};\n";
202

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

    
249
		/* add DNS servers */
250
		$dnslist = array();
251
		if (isset($dhcpv6ifconf['rasamednsasdhcp6']) && is_array($dhcpv6ifconf['dnsserver']) && !empty($dhcpv6ifconf['dnsserver'])) {
252
			foreach ($dhcpv6ifconf['dnsserver'] as $server) {
253
				if (is_ipaddrv6($server)) {
254
					$dnslist[] = $server;
255
				}
256
			}
257
		} elseif (!isset($dhcpv6ifconf['rasamednsasdhcp6']) && isset($dhcpv6ifconf['radnsserver']) && is_array($dhcpv6ifconf['radnsserver'])) {
258
			foreach ($dhcpv6ifconf['radnsserver'] as $server) {
259
				if (is_ipaddrv6($server)) {
260
					$dnslist[] = $server;
261
				}
262
			}
263
		} elseif (isset($config['dnsmasq']['enable']) || isset($config['unbound']['enable'])) {
264
			$dnslist[] = get_interface_ipv6($realif);
265
		} elseif (is_array($config['system']['dnsserver']) && !empty($config['system']['dnsserver'])) {
266
			foreach ($config['system']['dnsserver'] as $server) {
267
				if (is_ipaddrv6($server)) {
268
					$dnslist[] = $server;
269
				}
270
			}
271
		}
272
		if (count($dnslist) > 0) {
273
			$dnsstring = implode(" ", $dnslist);
274
			if ($dnsstring <> "") {
275
				$radvdconf .= "\tRDNSS {$dnsstring} { };\n";
276
			}
277
		}
278

    
279
		$searchlist = array();
280
		$domainsearchlist = explode(';', $dhcpv6ifconf['radomainsearchlist']);
281
		foreach ($domainsearchlist as $sd) {
282
			$sd = trim($sd);
283
			if (is_hostname($sd)) {
284
				$searchlist[] = $sd;
285
			}
286
		}
287
		if (count($searchlist) > 0) {
288
			$searchliststring = trim(implode(" ", $searchlist));
289
		}
290
		if (!empty($dhcpv6ifconf['domain'])) {
291
			$radvdconf .= "\tDNSSL {$dhcpv6ifconf['domain']} {$searchliststring} { };\n";
292
		} elseif (!empty($config['system']['domain'])) {
293
			$radvdconf .= "\tDNSSL {$config['system']['domain']} {$searchliststring} { };\n";
294
		}
295
		$radvdconf .= "};\n";
296
	}
297

    
298
	/* handle DHCP-PD prefixes and 6RD dynamic interfaces */
299
	foreach ($Iflist as $if => $ifdescr) {
300
		if (!isset($config['interfaces'][$if]['track6-interface']) ||
301
		    !isset($config['interfaces'][$if]['ipaddrv6']) ||
302
		    $config['interfaces'][$if]['ipaddrv6'] != 'track6') {
303
			continue;
304
		}
305
		if (!isset($config['interfaces'][$if]['enable'])) {
306
			continue;
307
		}
308
		if ($config['dhcpdv6'][$if]['ramode'] == "disabled") {
309
			continue;
310
		}
311
		/* Do not put in the config an interface which is down */
312
		if (isset($blacklist[$if])) {
313
			continue;
314
		}
315
		$trackif = $config['interfaces'][$if]['track6-interface'];
316
		if (empty($config['interfaces'][$trackif])) {
317
			continue;
318
		}
319

    
320
		$realif = get_real_interface($if, "inet6");
321

    
322
		/* prevent duplicate entries, manual overrides */
323
		if (isset($radvdifs[$realif])) {
324
			continue;
325
		}
326

    
327
		$ifcfgipv6 = get_interface_ipv6($if);
328
		if (!is_ipaddrv6($ifcfgipv6)) {
329
			$subnetv6 = "::";
330
			$ifcfgsnv6 = "64";
331
		} else {
332
			$ifcfgsnv6 = get_interface_subnetv6($if);
333
			$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
334
		}
335
		$radvdifs[$realif] = $realif;
336

    
337
		$autotype = $config['interfaces'][$trackif]['ipaddrv6'];
338

    
339
		if ($g['debug']) {
340
			log_error("configuring RA on {$if} for type {$autotype} radvd subnet {$subnetv6}/{$ifcfgsnv6}");
341
		}
342

    
343
		$radvdconf .= "# Generated config for {$autotype} delegation from {$trackif} on {$if}\n";
344
		$radvdconf .= "interface {$realif} {\n";
345
		$radvdconf .= "\tAdvSendAdvert on;\n";
346
		if (is_numericint($dhcpv6ifconf['raminrtradvinterval'])) {
347
			$radvdconf .= "\tMinRtrAdvInterval {$dhcpv6ifconf['raminrtradvinterval']};\n";
348
		} else {
349
			$radvdconf .= "\tMinRtrAdvInterval 5;\n";
350
                }
351
		if (is_numericint($dhcpv6ifconf['ramaxrtradvinterval'])) {
352
			$radvdconf .= "\tMaxRtrAdvInterval {$dhcpv6ifconf['ramaxrtradvinterval']};\n";
353
		} else {
354
			$radvdconf .= "\tMaxRtrAdvInterval 10;\n";
355
		}
356
		$mtu = get_interface_mtu($realif);
357
		if (is_numeric($mtu)) {
358
			$radvdconf .= "\tAdvLinkMTU {$mtu};\n";
359
		} else {
360
			$radvdconf .= "\tAdvLinkMTU 1280;\n";
361
		}
362
		$radvdconf .= "\tAdvOtherConfigFlag on;\n";
363
		$radvdconf .= "\tprefix {$subnetv6}/{$ifcfgsnv6} {\n";
364
		$radvdconf .= "\t\tAdvOnLink on;\n";
365
		$radvdconf .= "\t\tAdvAutonomous on;\n";
366
		$radvdconf .= "\t\tAdvRouterAddr on;\n";
367
		$radvdconf .= "\t};\n";
368

    
369
		/* add DNS servers */
370
		$dnslist = array();
371
		if (isset($config['dnsmasq']['enable']) || isset($config['unbound']['enable'])) {
372
			$dnslist[] = $ifcfgipv6;
373
		} elseif (is_array($config['system']['dnsserver']) && !empty($config['system']['dnsserver'])) {
374
			foreach ($config['system']['dnsserver'] as $server) {
375
				if (is_ipaddrv6($server)) {
376
					$dnslist[] = $server;
377
				}
378
			}
379
		}
380
		if (count($dnslist) > 0) {
381
			$dnsstring = implode(" ", $dnslist);
382
			if (!empty($dnsstring)) {
383
				$radvdconf .= "\tRDNSS {$dnsstring} { };\n";
384
			}
385
		}
386
		if (!empty($config['system']['domain'])) {
387
			$radvdconf .= "\tDNSSL {$config['system']['domain']} { };\n";
388
		}
389
		$radvdconf .= "};\n";
390
	}
391

    
392
	/* write radvd.conf */
393
	if (!@file_put_contents("{$g['varetc_path']}/radvd.conf", $radvdconf)) {
394
		log_error(gettext("Error: cannot open radvd.conf in services_radvd_configure()."));
395
		if (platform_booting()) {
396
			printf("Error: cannot open radvd.conf in services_radvd_configure().\n");
397
		}
398
	}
399
	unset($radvdconf);
400

    
401
	if (count($radvdifs) > 0) {
402
		if (isvalidpid("{$g['varrun_path']}/radvd.pid")) {
403
			sigkillbypid("{$g['varrun_path']}/radvd.pid", "HUP");
404
		} else {
405
			mwexec("/usr/local/sbin/radvd -p {$g['varrun_path']}/radvd.pid -C {$g['varetc_path']}/radvd.conf -m syslog");
406
		}
407
	} else {
408
		/* we need to shut down the radvd cleanly, it will send out the prefix
409
		 * information with a lifetime of 0 to notify clients of a (possible) new prefix */
410
		if (isvalidpid("{$g['varrun_path']}/radvd.pid")) {
411
			log_error(gettext("Shutting down Router Advertisment daemon cleanly"));
412
			killbypid("{$g['varrun_path']}/radvd.pid");
413
			@unlink("{$g['varrun_path']}/radvd.pid");
414
		}
415
	}
416
	return 0;
417
}
418

    
419
function services_dhcpd_configure($family = "all", $blacklist = array()) {
420
	global $config, $g;
421

    
422
	$dhcpdconfigurelck = lock("dhcpdconfigure", LOCK_EX);
423

    
424
	/* configure DHCPD chroot once */
425
	$fd = fopen("{$g['tmp_path']}/dhcpd.sh", "w");
426
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}\n");
427
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/dev\n");
428
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/etc\n");
429
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/usr/local/sbin\n");
430
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db\n");
431
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run\n");
432
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/usr\n");
433
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/lib\n");
434
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/run\n");
435
	fwrite($fd, "/usr/sbin/chown -R dhcpd:_dhcp {$g['dhcpd_chroot_path']}/*\n");
436
	fwrite($fd, "/bin/cp -n /lib/libc.so.* {$g['dhcpd_chroot_path']}/lib/\n");
437
	fwrite($fd, "/bin/cp -n /usr/local/sbin/dhcpd {$g['dhcpd_chroot_path']}/usr/local/sbin/\n");
438
	fwrite($fd, "/bin/chmod a+rx {$g['dhcpd_chroot_path']}/usr/local/sbin/dhcpd\n");
439

    
440
	$status = `/sbin/mount | /usr/bin/grep -v grep | /usr/bin/grep "{$g['dhcpd_chroot_path']}/dev"`;
441
	if (!trim($status)) {
442
		fwrite($fd, "/sbin/mount -t devfs devfs {$g['dhcpd_chroot_path']}/dev\n");
443
	}
444
	fclose($fd);
445
	mwexec("/bin/sh {$g['tmp_path']}/dhcpd.sh");
446

    
447
	if ($family == "all" || $family == "inet") {
448
		services_dhcpdv4_configure();
449
	}
450
	if ($family == "all" || $family == "inet6") {
451
		services_dhcpdv6_configure($blacklist);
452
		services_radvd_configure($blacklist);
453
	}
454

    
455
	unlock($dhcpdconfigurelck);
456
}
457

    
458
function services_dhcpdv4_configure() {
459
	global $config, $g;
460
	$need_ddns_updates = false;
461
	$ddns_zones = array();
462

    
463
	if ($g['services_dhcp_server_enable'] == false) {
464
		return;
465
	}
466

    
467
	if (isset($config['system']['developerspew'])) {
468
		$mt = microtime();
469
		echo "services_dhcpdv4_configure($if) being called $mt\n";
470
	}
471

    
472
	/* kill any running dhcpd */
473
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid")) {
474
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid");
475
	}
476

    
477
	/* DHCP enabled on any interfaces? */
478
	if (!is_dhcp_server_enabled()) {
479
		return 0;
480
	}
481

    
482
	$syscfg = $config['system'];
483
	if (!is_array($config['dhcpd'])) {
484
		$config['dhcpd'] = array();
485
	}
486
	$dhcpdcfg = $config['dhcpd'];
487
	$Iflist = get_configured_interface_list();
488

    
489
	/* Only consider DNS servers with IPv4 addresses for the IPv4 DHCP server. */
490
	$dns_arrv4 = array();
491
	if (is_array($syscfg['dnsserver'])) {
492
		foreach ($syscfg['dnsserver'] as $dnsserver) {
493
			if (is_ipaddrv4($dnsserver)) {
494
				$dns_arrv4[] = $dnsserver;
495
			}
496
		}
497
	}
498

    
499
	if (platform_booting()) {
500
		echo gettext("Starting DHCP service...");
501
	} else {
502
		sleep(1);
503
	}
504

    
505
	$custoptions = "";
506
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
507
		if (is_array($dhcpifconf['numberoptions']) && is_array($dhcpifconf['numberoptions']['item'])) {
508
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
509
				if (!empty($item['type'])) {
510
					$itemtype = $item['type'];
511
				} else {
512
					$itemtype = "text";
513
				}
514
				$custoptions .= "option custom-{$dhcpif}-{$itemidx} code {$item['number']} = {$itemtype};\n";
515
			}
516
		}
517
		if (is_array($dhcpifconf['pool'])) {
518
			foreach ($dhcpifconf['pool'] as $poolidx => $poolconf) {
519
				if (is_array($poolconf['numberoptions']) && is_array($poolconf['numberoptions']['item'])) {
520
					foreach ($poolconf['numberoptions']['item'] as $itemidx => $item) {
521
						if (!empty($item['type'])) {
522
							$itemtype = $item['type'];
523
						} else {
524
							$itemtype = "text";
525
						}
526
						$custoptions .= "option custom-{$dhcpif}-{$poolidx}-{$itemidx} code {$item['number']} = {$itemtype};\n";
527
					}
528
				}
529
			}
530
		}
531
	}
532

    
533
	$dhcpdconf = <<<EOD
534

    
535
option domain-name "{$syscfg['domain']}";
536
option ldap-server code 95 = text;
537
option domain-search-list code 119 = text;
538
option arch code 93 = unsigned integer 16; # RFC4578
539
{$custoptions}
540
default-lease-time 7200;
541
max-lease-time 86400;
542
log-facility local7;
543
one-lease-per-client true;
544
deny duplicates;
545
update-conflict-detection false;
546

    
547
EOD;
548

    
549
	if (!isset($dhcpifconf['disableauthoritative'])) {
550
		$dhcpdconf .= "authoritative;\n";
551
	}
552

    
553
	if (isset($dhcpifconf['alwaysbroadcast'])) {
554
		$dhcpdconf .= "always-broadcast on\n";
555
	}
556

    
557
	$dhcpdifs = array();
558
	$enable_add_routers = false;
559
	$gateways_arr = return_gateways_array();
560
	/* only add a routers line if the system has any IPv4 gateway at all */
561
	/* a static route has a gateway, manually overriding this field always works */
562
	foreach ($gateways_arr as $gwitem) {
563
		if ($gwitem['ipprotocol'] == "inet") {
564
			$enable_add_routers = true;
565
			break;
566
		}
567
	}
568

    
569
	/*    loop through and determine if we need to setup
570
	 *    failover peer "bleh" entries
571
	 */
572
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
573

    
574
		if (!isset($config['interfaces'][$dhcpif]['enable'])) {
575
			continue;
576
		}
577

    
578
		interfaces_staticarp_configure($dhcpif);
579

    
580
		if (!isset($dhcpifconf['enable'])) {
581
			continue;
582
		}
583

    
584
		if ($dhcpifconf['failover_peerip'] <> "") {
585
			$intip = get_interface_ip($dhcpif);
586
			/*
587
			 *    yep, failover peer is defined.
588
			 *    does it match up to a defined vip?
589
			 */
590
			$skew = 110;
591
			if (is_array($config['virtualip']['vip'])) {
592
				foreach ($config['virtualip']['vip'] as $vipent) {
593
					if ($vipent['mode'] != 'carp') {
594
						continue;
595
					}
596
					if ($vipent['interface'] == $dhcpif) {
597
						$carp_nw = gen_subnet($config['interfaces'][$dhcpif]['ipaddr'],
598
						    $config['interfaces'][$dhcpif]['subnet']);
599
						$carp_nw .= "/{$config['interfaces'][$dhcpif]['subnet']}";
600
						if (ip_in_subnet($dhcpifconf['failover_peerip'], $carp_nw)) {
601
							/* this is the interface! */
602
							if (is_numeric($vipent['advskew']) && (intval($vipent['advskew']) < 20)) {
603
								$skew = 0;
604
								break;
605
							}
606
						}
607
					}
608
				}
609
			} else {
610
				log_error(gettext("Warning!  DHCP Failover setup and no CARP virtual IPs defined!"));
611
			}
612
			if ($skew > 10) {
613
				$type = "secondary";
614
				$my_port = "520";
615
				$peer_port = "519";
616
				$dhcpdconf_pri = '';
617
			} else {
618
				$my_port = "519";
619
				$peer_port = "520";
620
				$type = "primary";
621
				$dhcpdconf_pri = "split 128;\n";
622
				$dhcpdconf_pri .= "  mclt 600;\n";
623
			}
624

    
625
			if (is_ipaddrv4($intip)) {
626
				$dhcpdconf .= <<<EOPP
627
failover peer "dhcp_{$dhcpif}" {
628
  {$type};
629
  address {$intip};
630
  port {$my_port};
631
  peer address {$dhcpifconf['failover_peerip']};
632
  peer port {$peer_port};
633
  max-response-delay 10;
634
  max-unacked-updates 10;
635
  {$dhcpdconf_pri}
636
  load balance max seconds 3;
637
}
638
\n
639
EOPP;
640
			}
641
		}
642
	}
643

    
644
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
645

    
646
		$newzone = array();
647
		$ifcfg = $config['interfaces'][$dhcpif];
648

    
649
		if (!isset($dhcpifconf['enable']) || !isset($Iflist[$dhcpif])) {
650
			continue;
651
		}
652
		$ifcfgip = get_interface_ip($dhcpif);
653
		$ifcfgsn = get_interface_subnet($dhcpif);
654
		$subnet = gen_subnet($ifcfgip, $ifcfgsn);
655
		$subnetmask = gen_subnet_mask($ifcfgsn);
656

    
657
		if (!is_ipaddr($subnet)) {
658
			continue;
659
		}
660

    
661
		$all_pools = array();
662
		$all_pools[] = $dhcpifconf;
663
		if (is_array($dhcpifconf['pool'])) {
664
			$all_pools = array_merge($all_pools, $dhcpifconf['pool']);
665
		}
666

    
667
		$dnscfg = "";
668

    
669
		if ($dhcpifconf['domain']) {
670
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
671
		}
672

    
673
		if ($dhcpifconf['domainsearchlist'] <> "") {
674
			$dnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpifconf['domainsearchlist'])) . "\";\n";
675
		}
676

    
677
		if (isset($dhcpifconf['ddnsupdate'])) {
678
			$need_ddns_updates = true;
679
			$newzone = array();
680
			if ($dhcpifconf['ddnsdomain'] <> "") {
681
				$newzone['domain-name'] = $dhcpifconf['ddnsdomain'];
682
				$dnscfg .= "	ddns-domainname \"{$dhcpifconf['ddnsdomain']}\";\n";
683
			} else {
684
				$newzone['domain-name'] = $config['system']['domain'];
685
			}
686

    
687
			if (empty($dhcpifconf['ddnsclientupdates'])) {
688
				$ddnsclientupdates = 'allow';
689
			} else {
690
				$ddnsclientupdates = $dhcpifconf['ddnsclientupdates'];
691
			}
692

    
693
			$dnscfg .= "	{$ddnsclientupdates} client-updates;\n";
694

    
695
			$revsubnet = array_reverse(explode('.',$subnet));
696

    
697
			/* Take care of full classes first */
698
			switch ($ifcfgsn) {
699
				case 8:
700
					$start_octet = 3;
701
					break;
702
				case 16:
703
					$start_octet = 2;
704
					break;
705
				case 24:
706
					$start_octet = 1;
707
					break;
708
				default:
709
					$start_octet = 0;
710
					/* Add subnet bitmask to first octet */
711
					$revsubnet[0] .= '-' . $ifcfgsn;
712
					break;
713

    
714
			}
715

    
716
			$ptr_domain = '';
717
			for ($octet = 0; $octet <= 3; $octet++) {
718
				if ($octet < $start_octet) {
719
					continue;
720
				}
721
				$ptr_domain .= ((empty($ptr_domain) && $ptr_domain !== "0") ? '' : '.');
722
				$ptr_domain .= $revsubnet[$octet];
723
			}
724
			$ptr_domain .= ".in-addr.arpa";
725
			$newzone['ptr-domain'] = $ptr_domain;
726
			unset($ptr_domain, $revsubnet, $start_octet);
727
		}
728

    
729
		if (is_array($dhcpifconf['dnsserver']) && ($dhcpifconf['dnsserver'][0])) {
730
			$dnscfg .= "	option domain-name-servers " . join(",", $dhcpifconf['dnsserver']) . ";";
731
			if ($newzone['domain-name']) {
732
				$newzone['dns-servers'] = $dhcpifconf['dnsserver'];
733
			}
734
		} else if (isset($config['dnsmasq']['enable'])) {
735
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
736
			if ($newzone['domain-name'] && is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
737
				$newzone['dns-servers'] = $syscfg['dnsserver'];
738
			}
739
		} else if (isset($config['unbound']['enable'])) {
740
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
741
		} else if (!empty($dns_arrv4)) {
742
			$dnscfg .= "	option domain-name-servers " . join(",", $dns_arrv4) . ";";
743
			if ($newzone['domain-name']) {
744
				$newzone['dns-servers'] = $dns_arrv4;
745
			}
746
		}
747

    
748
		/* Create classes - These all contain comma separated lists. Join them into one
749
		   big comma separated string then split them all up. */
750
		$all_mac_strings = array();
751
		if (is_array($dhcpifconf['pool'])) {
752
			foreach ($all_pools as $poolconf) {
753
				$all_mac_strings[] = $poolconf['mac_allow'];
754
				$all_mac_strings[] = $poolconf['mac_deny'];
755
			}
756
		}
757
		$all_mac_strings[] = $dhcpifconf['mac_allow'];
758
		$all_mac_strings[] = $dhcpifconf['mac_deny'];
759
		if (!empty($all_mac_strings)) {
760
			$all_mac_list = array_unique(explode(',', implode(',', $all_mac_strings)));
761
			foreach ($all_mac_list as $mac) {
762
				if (empty($mac)) {
763
					continue;
764
				}
765
				$dhcpdconf .= 'class "' . str_replace(':', '', $mac) . '" {' . "\n";
766
				// Skip the first octet of the MAC address - for media type, typically Ethernet ("01") and match the rest.
767
				$dhcpdconf .= '	match if substring (hardware, 1, ' . (substr_count($mac, ':') + 1) . ') = ' . $mac . ';' . "\n";
768
				$dhcpdconf .= '}' . "\n";
769
			}
770
		}
771

    
772
		$dhcpdconf .= "subnet {$subnet} netmask {$subnetmask} {\n";
773

    
774
		// Setup pool options
775
		foreach ($all_pools as $all_pools_idx => $poolconf) {
776
			if (!(ip_in_subnet($poolconf['range']['from'], "{$subnet}/{$ifcfgsn}") && ip_in_subnet($poolconf['range']['to'], "{$subnet}/{$ifcfgsn}"))) {
777
				// If the user has changed the subnet from the interfaces page and applied,
778
				// but has not updated the DHCP range, then the range to/from of the pool can be outside the subnet.
779
				// This can also happen when implementing the batch of changes when the setup wizard reloads the new settings.
780
				$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);
781
				$do_file_notice = true;
782
				$conf_ipv4_address = $ifcfg['ipaddr'];
783
				$conf_ipv4_subnetmask = $ifcfg['subnet'];
784
				if (is_ipaddrv4($conf_ipv4_address) && is_subnet("{$conf_ipv4_address}/{$conf_ipv4_subnetmask}")) {
785
					$conf_subnet_base = gen_subnet($conf_ipv4_address, $conf_ipv4_subnetmask);
786
					if (ip_in_subnet($poolconf['range']['from'], "{$conf_subnet_base}/{$conf_ipv4_subnetmask}") &&
787
					    ip_in_subnet($poolconf['range']['to'], "{$conf_subnet_base}/{$conf_ipv4_subnetmask}")) {
788
						// Even though the running interface subnet does not match the pool range,
789
						// the interface subnet in the config file contains the pool range.
790
						// We are somewhere part-way through a settings reload, e.g. after running the setup wizard.
791
						// services_dhcpdv4_configure will be called again later when the new interface settings from
792
						// the config are applied and at that time everything will match up.
793
						// Ignore this pool on this interface for now and just log the error to the system log.
794
						log_error($error_msg);
795
						$do_file_notice = false;
796
					}
797
				}
798
				if ($do_file_notice) {
799
					file_notice("DHCP", $error_msg);
800
				}
801
				continue;
802
			}
803
			$dhcpdconf .= "	pool {\n";
804
			/* is failover dns setup? */
805
			if (is_array($poolconf['dnsserver']) && $poolconf['dnsserver'][0] <> "") {
806
				$dhcpdconf .= "		option domain-name-servers {$poolconf['dnsserver'][0]}";
807
				if ($poolconf['dnsserver'][1] <> "") {
808
					$dhcpdconf .= ",{$poolconf['dnsserver'][1]}";
809
				}
810
				if ($poolconf['dnsserver'][2] <> "") {
811
					$dhcpdconf .= ",{$poolconf['dnsserver'][2]}";
812
				}
813
				if ($poolconf['dnsserver'][3] <> "") {
814
					$dhcpdconf .= ",{$poolconf['dnsserver'][3]}";
815
				}
816
				$dhcpdconf .= ";\n";
817
			}
818

    
819
			/* allow/deny MACs */
820
			$mac_allow_list = array_unique(explode(',', $poolconf['mac_allow']));
821
			foreach ($mac_allow_list as $mac) {
822
				if (empty($mac)) {
823
					continue;
824
				}
825
				$dhcpdconf .= "		allow members of \"" . str_replace(':', '', $mac) . "\";\n";
826
			}
827
			$deny_action = "deny";
828
			if (isset($poolconf['nonak']) && empty($poolconf['failover_peerip'])) {
829
				$deny_action = "ignore";
830
			}
831
			$mac_deny_list = array_unique(explode(',', $poolconf['mac_deny']));
832
			foreach ($mac_deny_list as $mac) {
833
				if (empty($mac)) {
834
					continue;
835
				}
836
				$dhcpdconf .= "		$deny_action members of \"" . str_replace(':', '', $mac) . "\";\n";
837
			}
838

    
839
			if ($poolconf['failover_peerip'] <> "") {
840
				$dhcpdconf .= "		$deny_action dynamic bootp clients;\n";
841
			}
842

    
843
			if (isset($poolconf['denyunknown'])) {
844
				$dhcpdconf .= "		$deny_action unknown-clients;\n";
845
			}
846

    
847
			if ($poolconf['gateway'] && $poolconf['gateway'] != "none" && ($poolconf['gateway'] != $dhcpifconf['gateway'])) {
848
				$dhcpdconf .= "		option routers {$poolconf['gateway']};\n";
849
			}
850

    
851
			if ($dhcpifconf['failover_peerip'] <> "") {
852
				$dhcpdconf .= "		failover peer \"dhcp_{$dhcpif}\";\n";
853
			}
854

    
855
			$pdnscfg = "";
856

    
857
			if ($poolconf['domain'] && ($poolconf['domain'] != $dhcpifconf['domain'])) {
858
				$pdnscfg .= "		option domain-name \"{$poolconf['domain']}\";\n";
859
			}
860

    
861
			if (!empty($poolconf['domainsearchlist']) && ($poolconf['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
862
				$pdnscfg .= "		option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $poolconf['domainsearchlist'])) . "\";\n";
863
			}
864

    
865
			if (isset($poolconf['ddnsupdate'])) {
866
				if (($poolconf['ddnsdomain'] <> "") && ($poolconf['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
867
					$pdnscfg .= "		ddns-domainname \"{$poolconf['ddnsdomain']}\";\n";
868
				}
869
				$pdnscfg .= "		ddns-update-style interim;\n";
870
			}
871

    
872
			$dhcpdconf .= "{$pdnscfg}";
873

    
874
			// default-lease-time
875
			if ($poolconf['defaultleasetime'] && ($poolconf['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
876
				$dhcpdconf .= "		default-lease-time {$poolconf['defaultleasetime']};\n";
877
			}
878

    
879
			// max-lease-time
880
			if ($poolconf['maxleasetime'] && ($poolconf['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
881
				$dhcpdconf .= "		max-lease-time {$poolconf['maxleasetime']};\n";
882
			}
883

    
884
			// ignore bootp
885
			if (isset($poolconf['ignorebootp'])) {
886
				$dhcpdconf .= "		ignore bootp;\n";
887
			}
888

    
889
			// ignore-client-uids
890
			if (isset($poolconf['ignoreclientuids'])) {
891
				$dhcpdconf .= "		ignore-client-uids true;\n";
892
			}
893

    
894
			// netbios-name*
895
			if (is_array($poolconf['winsserver']) && $poolconf['winsserver'][0] && ($poolconf['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
896
				$dhcpdconf .= "		option netbios-name-servers " . join(",", $poolconf['winsserver']) . ";\n";
897
				$dhcpdconf .= "		option netbios-node-type 8;\n";
898
			}
899

    
900
			// ntp-servers
901
			if (is_array($poolconf['ntpserver']) && $poolconf['ntpserver'][0] && ($poolconf['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
902
				$dhcpdconf .= "		option ntp-servers " . join(",", $poolconf['ntpserver']) . ";\n";
903
			}
904

    
905
			// tftp-server-name
906
			if (!empty($poolconf['tftp']) && ($poolconf['tftp'] != $dhcpifconf['tftp'])) {
907
				$dhcpdconf .= "		option tftp-server-name \"{$poolconf['tftp']}\";\n";
908
			}
909

    
910
			// Handle pool-specific options
911
			$dhcpdconf .= "\n";
912
			// Ignore the first pool, which is the "overall" pool when $all_pools_idx is 0 - those are put outside the pool block later
913
			if ($poolconf['numberoptions']['item'] && ($all_pools_idx > 0)) {
914
				// Use the "real" pool index from the config, excluding the "overall" pool, and based from 0.
915
				// This matches the way $poolidx was used when generating the $custoptions string earlier.
916
				$poolidx = $all_pools_idx - 1;
917
				foreach ($poolconf['numberoptions']['item'] as $itemidx => $item) {
918
					$item_value = base64_decode($item['value']);
919
					if (empty($item['type']) || $item['type'] == "text") {
920
						$dhcpdconf .= "		option custom-{$dhcpif}-{$poolidx}-{$itemidx} \"{$item_value}\";\n";
921
					} else {
922
						$dhcpdconf .= "		option custom-{$dhcpif}-{$poolidx}-{$itemidx} {$item_value};\n";
923
					}
924
				}
925
			}
926

    
927
			// ldap-server
928
			if (!empty($poolconf['ldap']) && ($poolconf['ldap'] != $dhcpifconf['ldap'])) {
929
				$dhcpdconf .= "		option ldap-server \"{$poolconf['ldap']}\";\n";
930
			}
931

    
932
			// net boot information
933
			if (isset($poolconf['netboot'])) {
934
				if (!empty($poolconf['nextserver']) && ($poolconf['nextserver'] != $dhcpifconf['nextserver'])) {
935
					$dhcpdconf .= "		next-server {$poolconf['nextserver']};\n";
936
				}
937

    
938
				if (!empty($poolconf['filename']) &&
939
				    (!isset($dhcpifconf['filename']) ||
940
				    ($poolconf['filename'] != $dhcpifconf['filename']))) {
941
					$filename = $poolconf['filename'];
942
				}
943
				if (!empty($poolconf['filename32']) &&
944
				    (!isset($dhcpifconf['filename32']) ||
945
				    ($poolconf['filename32'] != $dhcpifconf['filename32']))) {
946
					$filename32 = $poolconf['filename32'];
947
				}
948
				if (!empty($poolconf['filename64']) &&
949
				    (!isset($dhcpifconf['filename64']) ||
950
				    ($poolconf['filename64'] != $dhcpifconf['filename64']))) {
951
					$filename64 = $poolconf['filename64'];
952
				}
953

    
954
				if (!empty($filename32) || !empty($filename64)) {
955
					if (empty($filename) && !empty($dhcpifconf['filename'])) {
956
						$filename = $dhcpifconf['filename'];
957
					}
958
					if (empty($filename32) && !empty($dhcpifconf['filename32'])) {
959
						$filename32 = $dhcpifconf['filename32'];
960
					}
961
					if (empty($filename64) && !empty($dhcpifconf['filename64'])) {
962
						$filename64 = $dhcpifconf['filename64'];
963
					}
964
				}
965

    
966
				if (!empty($filename) && !empty($filename32) && !empty($filename64)) {
967
					$dhcpdconf .= "		if option arch = 00:06 {\n";
968
					$dhcpdconf .= "			filename \"{$filename32}\";\n";
969
					$dhcpdconf .= "		} else if option arch = 00:07 {\n";
970
					$dhcpdconf .= "			filename \"{$filename64}\";\n";
971
					$dhcpdconf .= "		} else if option arch = 00:09 {\n";
972
					$dhcpdconf .= "			filename \"{$filename64}\";\n";
973
					$dhcpdconf .= "		} else {\n";
974
					$dhcpdconf .= "			filename \"{$filename}\";\n";
975
					$dhcpdconf .= "		}\n\n";
976
				} elseif (!empty($filename)) {
977
					$dhcpdconf .= "		filename \"{$filename}\";\n";
978
				}
979
				unset($filename, $filename32, $filename64);
980

    
981
				if (!empty($poolconf['rootpath']) && ($poolconf['rootpath'] != $dhcpifconf['rootpath'])) {
982
					$dhcpdconf .= "		option root-path \"{$poolconf['rootpath']}\";\n";
983
				}
984
			}
985
			$dhcpdconf .= "		range {$poolconf['range']['from']} {$poolconf['range']['to']};\n";
986
			$dhcpdconf .= "	}\n\n";
987
		}
988
// End of settings inside pools
989

    
990
		if ($dhcpifconf['gateway'] && $dhcpifconf['gateway'] != "none") {
991
			$routers = $dhcpifconf['gateway'];
992
			$add_routers = true;
993
		} elseif ($dhcpifconf['gateway'] == "none") {
994
			$add_routers = false;
995
		} else {
996
			$add_routers = $enable_add_routers;
997
			$routers = $ifcfgip;
998
		}
999
		if ($add_routers) {
1000
			$dhcpdconf .= "	option routers {$routers};\n";
1001
		}
1002

    
1003
		$dhcpdconf .= <<<EOD
1004
$dnscfg
1005

    
1006
EOD;
1007
		// default-lease-time
1008
		if ($dhcpifconf['defaultleasetime']) {
1009
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
1010
		}
1011

    
1012
		// max-lease-time
1013
		if ($dhcpifconf['maxleasetime']) {
1014
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
1015
		}
1016

    
1017
		if (!isset($dhcpifconf['disablepingcheck'])) {
1018
			$dhcpdconf .= "	ping-check true;\n";
1019
		} else {
1020
			$dhcpdconf .= "	ping-check false;\n";
1021
		}
1022

    
1023
		// netbios-name*
1024
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
1025
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
1026
			$dhcpdconf .= "	option netbios-node-type 8;\n";
1027
		}
1028

    
1029
		// ntp-servers
1030
		if (is_array($dhcpifconf['ntpserver']) && $dhcpifconf['ntpserver'][0]) {
1031
			$dhcpdconf .= "	option ntp-servers " . join(",", $dhcpifconf['ntpserver']) . ";\n";
1032
		}
1033

    
1034
		// tftp-server-name
1035
		if ($dhcpifconf['tftp'] <> "") {
1036
			$dhcpdconf .= "	option tftp-server-name \"{$dhcpifconf['tftp']}\";\n";
1037
		}
1038

    
1039
		// Handle option, number rowhelper values
1040
		$dhcpdconf .= "\n";
1041
		if ($dhcpifconf['numberoptions']['item']) {
1042
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
1043
				$item_value = base64_decode($item['value']);
1044
				if (empty($item['type']) || $item['type'] == "text") {
1045
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} \"{$item_value}\";\n";
1046
				} else {
1047
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} {$item_value};\n";
1048
				}
1049
			}
1050
		}
1051

    
1052
		// ldap-server
1053
		if ($dhcpifconf['ldap'] <> "") {
1054
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
1055
		}
1056

    
1057
		// net boot information
1058
		if (isset($dhcpifconf['netboot'])) {
1059
			if ($dhcpifconf['nextserver'] <> "") {
1060
				$dhcpdconf .= "	next-server {$dhcpifconf['nextserver']};\n";
1061
			}
1062
			if (!empty($dhcpifconf['filename']) && !empty($dhcpifconf['filename32']) && !empty($dhcpifconf['filename64'])) {
1063
				$dhcpdconf .= "	if option arch = 00:06 {\n";
1064
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename32']}\";\n";
1065
				$dhcpdconf .= "	} else if option arch = 00:07 {\n";
1066
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1067
				$dhcpdconf .= "	} else if option arch = 00:09 {\n";
1068
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1069
				$dhcpdconf .= "	} else {\n";
1070
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename']}\";\n";
1071
				$dhcpdconf .= "	}\n\n";
1072
			} elseif (!empty($dhcpifconf['filename'])) {
1073
				$dhcpdconf .= "	filename \"{$dhcpifconf['filename']}\";\n";
1074
			}
1075
			if (!empty($dhcpifconf['rootpath'])) {
1076
				$dhcpdconf .= "	option root-path \"{$dhcpifconf['rootpath']}\";\n";
1077
			}
1078
		}
1079

    
1080
		$dhcpdconf .= <<<EOD
1081
}
1082

    
1083
EOD;
1084

    
1085
		/* add static mappings */
1086
		if (is_array($dhcpifconf['staticmap'])) {
1087

    
1088
			$i = 0;
1089
			foreach ($dhcpifconf['staticmap'] as $sm) {
1090
				$dhcpdconf .= "host s_{$dhcpif}_{$i} {\n";
1091

    
1092
				if ($sm['mac']) {
1093
					$dhcpdconf .= "        hardware ethernet {$sm['mac']};\n";
1094
				}
1095

    
1096
				if ($sm['cid']) {
1097
					$dhcpdconf .= "        option dhcp-client-identifier \"{$sm['cid']}\";\n";
1098
				}
1099

    
1100
				if ($sm['ipaddr']) {
1101
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
1102
				}
1103

    
1104
				if ($sm['hostname']) {
1105
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1106
					$dhhostname = str_replace(".", "_", $dhhostname);
1107
					$dhcpdconf .= "	option host-name \"{$dhhostname}\";\n";
1108
					if ((isset($dhcpifconf['ddnsupdate']) || isset($sm['ddnsupdate'])) && (isset($dhcpifconf['ddnsforcehostname']) || isset($sm['ddnsforcehostname']))) {
1109
						$dhcpdconf .= "	ddns-hostname \"{$dhhostname}\";\n";
1110
					}
1111
				}
1112
				if ($sm['filename']) {
1113
					$dhcpdconf .= "	filename \"{$sm['filename']}\";\n";
1114
				}
1115

    
1116
				if ($sm['rootpath']) {
1117
					$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1118
				}
1119

    
1120
				if ($sm['gateway'] && ($sm['gateway'] != $dhcpifconf['gateway'])) {
1121
					$dhcpdconf .= "	option routers {$sm['gateway']};\n";
1122
				}
1123

    
1124
				$smdnscfg = "";
1125

    
1126
				if ($sm['domain'] && ($sm['domain'] != $dhcpifconf['domain'])) {
1127
					$smdnscfg .= "	option domain-name \"{$sm['domain']}\";\n";
1128
				}
1129

    
1130
				if (!empty($sm['domainsearchlist']) && ($sm['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
1131
					$smdnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $sm['domainsearchlist'])) . "\";\n";
1132
				}
1133

    
1134
				if (isset($sm['ddnsupdate'])) {
1135
					if (($sm['ddnsdomain'] <> "") && ($sm['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
1136
						$smdnscfg .= "		ddns-domainname \"{$sm['ddnsdomain']}\";\n";
1137
					}
1138
					$smdnscfg .= "		ddns-update-style interim;\n";
1139
				}
1140

    
1141
				if (is_array($sm['dnsserver']) && ($sm['dnsserver'][0]) && ($sm['dnsserver'][0] != $dhcpifconf['dnsserver'][0])) {
1142
					$smdnscfg .= "	option domain-name-servers " . join(",", $sm['dnsserver']) . ";\n";
1143
				}
1144
				$dhcpdconf .= "{$smdnscfg}";
1145

    
1146
				// default-lease-time
1147
				if ($sm['defaultleasetime'] && ($sm['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
1148
					$dhcpdconf .= "	default-lease-time {$sm['defaultleasetime']};\n";
1149
				}
1150

    
1151
				// max-lease-time
1152
				if ($sm['maxleasetime'] && ($sm['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
1153
					$dhcpdconf .= "	max-lease-time {$sm['maxleasetime']};\n";
1154
				}
1155

    
1156
				// netbios-name*
1157
				if (is_array($sm['winsserver']) && $sm['winsserver'][0] && ($sm['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
1158
					$dhcpdconf .= "	option netbios-name-servers " . join(",", $sm['winsserver']) . ";\n";
1159
					$dhcpdconf .= "	option netbios-node-type 8;\n";
1160
				}
1161

    
1162
				// ntp-servers
1163
				if (is_array($sm['ntpserver']) && $sm['ntpserver'][0] && ($sm['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
1164
					$dhcpdconf .= "	option ntp-servers " . join(",", $sm['ntpserver']) . ";\n";
1165
				}
1166

    
1167
				// tftp-server-name
1168
				if (!empty($sm['tftp']) && ($sm['tftp'] != $dhcpifconf['tftp'])) {
1169
					$dhcpdconf .= "	option tftp-server-name \"{$sm['tftp']}\";\n";
1170
				}
1171

    
1172
				$dhcpdconf .= "}\n";
1173
				$i++;
1174
			}
1175
		}
1176

    
1177
		$dhcpdifs[] = get_real_interface($dhcpif);
1178
		if ($newzone['domain-name']) {
1179
			if ($need_ddns_updates) {
1180
				$newzone['dns-servers'] = array($dhcpifconf['ddnsdomainprimary']);
1181
				$newzone['ddnsdomainkeyname'] = $dhcpifconf['ddnsdomainkeyname'];
1182
				$newzone['ddnsdomainkeyalgorithm'] = $dhcpifconf['ddnsdomainkeyalgorithm'];
1183
				$newzone['ddnsdomainkey'] = $dhcpifconf['ddnsdomainkey'];
1184
				$dhcpdconf .= dhcpdkey($dhcpifconf);
1185
			}
1186
			$ddns_zones[] = $newzone;
1187
		}
1188
	}
1189

    
1190
	if ($need_ddns_updates) {
1191
		$dhcpdconf .= "ddns-update-style interim;\n";
1192
		$dhcpdconf .= "update-static-leases on;\n";
1193

    
1194
		$dhcpdconf .= dhcpdzones($ddns_zones);
1195
	}
1196

    
1197
	/* write dhcpd.conf */
1198
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpd.conf", $dhcpdconf)) {
1199
		printf(gettext("Error: cannot open dhcpd.conf in services_dhcpdv4_configure().%s"), "\n");
1200
		unset($dhcpdconf);
1201
		return 1;
1202
	}
1203
	unset($dhcpdconf);
1204

    
1205
	/* create an empty leases database */
1206
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
1207
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
1208
	}
1209

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

    
1214
	/* fire up dhcpd in a chroot */
1215
	if (count($dhcpdifs) > 0) {
1216
		mwexec("/usr/local/sbin/dhcpd -user dhcpd -group _dhcp -chroot {$g['dhcpd_chroot_path']} -cf /etc/dhcpd.conf -pf {$g['varrun_path']}/dhcpd.pid " .
1217
			join(" ", $dhcpdifs));
1218
	}
1219

    
1220
	if (platform_booting()) {
1221
		print "done.\n";
1222
	}
1223

    
1224
	return 0;
1225
}
1226

    
1227
function dhcpdkey($dhcpifconf) {
1228
	$dhcpdconf = "";
1229
	if (!empty($dhcpifconf['ddnsdomainkeyname']) && !empty($dhcpifconf['ddnsdomainkey'])) {
1230
		$algorithm = empty($dhcpifconf['ddnsdomainkeyalgorithm']) ? 'hmac-md5' : $dhcpifconf['ddnsdomainkeyalgorithm'];
1231
		$dhcpdconf .= "key {$dhcpifconf['ddnsdomainkeyname']} {\n";
1232
		$dhcpdconf .= "	algorithm {$algorithm};\n";
1233
		$dhcpdconf .= "	secret {$dhcpifconf['ddnsdomainkey']};\n";
1234
		$dhcpdconf .= "}\n";
1235
	}
1236

    
1237
	return $dhcpdconf;
1238
}
1239

    
1240
function dhcpdzones($ddns_zones) {
1241
	$dhcpdconf = "";
1242

    
1243
	if (is_array($ddns_zones)) {
1244
		$added_zones = array();
1245
		foreach ($ddns_zones as $zone) {
1246
			if (!is_array($zone) || empty($zone) || !is_array($zone['dns-servers'])) {
1247
				continue;
1248
			}
1249
			$primary = $zone['dns-servers'][0];
1250
			$secondary = empty($zone['dns-servers'][1]) ? "" : $zone['dns-servers'][1];
1251

    
1252
			// Make sure we aren't using any invalid or IPv6 DNS servers.
1253
			if (!is_ipaddrv4($primary)) {
1254
				if (is_ipaddrv4($secondary)) {
1255
					$primary = $secondary;
1256
					$secondary = "";
1257
				} else {
1258
					continue;
1259
				}
1260
			}
1261

    
1262
			// We don't need to add zones multiple times.
1263
			if ($zone['domain-name'] && !in_array($zone['domain-name'], $added_zones)) {
1264
				$dhcpdconf .= "zone {$zone['domain-name']}. {\n";
1265
				$dhcpdconf .= "	primary {$primary};\n";
1266
				if (is_ipaddrv4($secondary)) {
1267
					$dhcpdconf .= "	secondary {$secondary};\n";
1268
				}
1269
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1270
					$dhcpdconf .= "	key {$zone['ddnsdomainkeyname']};\n";
1271
				}
1272
				$dhcpdconf .= "}\n";
1273
				$added_zones[] = $zone['domain-name'];
1274
			}
1275
			if ($zone['ptr-domain'] && !in_array($zone['ptr-domain'], $added_zones)) {
1276
				$dhcpdconf .= "zone {$zone['ptr-domain']} {\n";
1277
				$dhcpdconf .= "	primary {$primary};\n";
1278
				if (is_ipaddrv4($secondary)) {
1279
					$dhcpdconf .= "	secondary {$secondary};\n";
1280
				}
1281
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1282
					$dhcpdconf .= "	key {$zone['ddnsdomainkeyname']};\n";
1283
				}
1284
				$dhcpdconf .= "}\n";
1285
				$added_zones[] = $zone['ptr-domain'];
1286
			}
1287
		}
1288
	}
1289

    
1290
	return $dhcpdconf;
1291
}
1292

    
1293
function services_dhcpdv6_configure($blacklist = array()) {
1294
	global $config, $g;
1295

    
1296
	if ($g['services_dhcp_server_enable'] == false) {
1297
		return;
1298
	}
1299

    
1300
	if (isset($config['system']['developerspew'])) {
1301
		$mt = microtime();
1302
		echo "services_dhcpd_configure($if) being called $mt\n";
1303
	}
1304

    
1305
	/* kill any running dhcpd */
1306
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid")) {
1307
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid");
1308
	}
1309
	if (isvalidpid("{$g['varrun_path']}/dhcpleases6.pid")) {
1310
		killbypid("{$g['varrun_path']}/dhcpleases6.pid");
1311
	}
1312

    
1313
	/* DHCP enabled on any interfaces? */
1314
	if (!is_dhcpv6_server_enabled()) {
1315
		return 0;
1316
	}
1317

    
1318
	$syscfg = $config['system'];
1319
	if (!is_array($config['dhcpdv6'])) {
1320
		$config['dhcpdv6'] = array();
1321
	}
1322
	$dhcpdv6cfg = $config['dhcpdv6'];
1323
	$Iflist = get_configured_interface_list();
1324
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
1325

    
1326

    
1327
	if (platform_booting()) {
1328
		echo "Starting DHCPv6 service...";
1329
	} else {
1330
		sleep(1);
1331
	}
1332

    
1333
	$custoptionsv6 = "";
1334
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1335
		if (is_array($dhcpv6ifconf['numberoptions']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1336
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1337
				$custoptionsv6 .= "option custom-{$dhcpv6if}-{$itemv6idx} code {$itemv6['number']} = text;\n";
1338
			}
1339
		}
1340
	}
1341

    
1342
	if (isset($dhcpv6ifconf['netboot']) && !empty($dhcpv6ifconf['bootfile_url'])) {
1343
		$custoptionsv6 .= "option dhcp6.bootfile-url code 59 = string;\n";
1344
	}
1345

    
1346
	$dhcpdv6conf = <<<EOD
1347

    
1348
option domain-name "{$syscfg['domain']}";
1349
option ldap-server code 95 = text;
1350
option domain-search-list code 119 = text;
1351
{$custoptionsv6}
1352
default-lease-time 7200;
1353
max-lease-time 86400;
1354
log-facility local7;
1355
one-lease-per-client true;
1356
deny duplicates;
1357
ping-check true;
1358
update-conflict-detection false;
1359

    
1360
EOD;
1361

    
1362
	if (!isset($dhcpv6ifconf['disableauthoritative'])) {
1363
		$dhcpdv6conf .= "authoritative;\n";
1364
	}
1365

    
1366
	if (isset($dhcpv6ifconf['alwaysbroadcast'])) {
1367
		$dhcpdv6conf .= "always-broadcast on\n";
1368
	}
1369

    
1370
	$dhcpdv6ifs = array();
1371

    
1372
	$dhcpv6num = 0;
1373
	$nsupdate = false;
1374

    
1375
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1376

    
1377
		$ddns_zones = array();
1378

    
1379
		$ifcfgv6 = $config['interfaces'][$dhcpv6if];
1380

    
1381
		if (!isset($dhcpv6ifconf['enable']) || !isset($Iflist[$dhcpv6if]) || !isset($ifcfgv6['enable'])) {
1382
			continue;
1383
		}
1384
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1385
		if (!is_ipaddrv6($ifcfgipv6)) {
1386
			continue;
1387
		}
1388
		$ifcfgsnv6 = get_interface_subnetv6($dhcpv6if);
1389
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1390
		// We might have some prefix-delegation on WAN (e.g. /48),
1391
		// but then it is split and given out to individual interfaces
1392
		// (LAN, OPT1, OPT2...) as multiple /64 subnets. So the size
1393
		// of each subnet here is always /64.
1394
		$pdlen = 64;
1395

    
1396
		$dnscfgv6 = "";
1397

    
1398
		if ($dhcpv6ifconf['domain']) {
1399
			$dnscfgv6 .= "	option domain-name \"{$dhcpv6ifconf['domain']}\";\n";
1400
		}
1401

    
1402
		if ($dhcpv6ifconf['domainsearchlist'] <> "") {
1403
			$dnscfgv6 .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpv6ifconf['domainsearchlist'])) . "\";\n";
1404
		}
1405

    
1406
		if (isset($dhcpv6ifconf['ddnsupdate'])) {
1407
			if ($dhcpv6ifconf['ddnsdomain'] <> "") {
1408
				$dnscfgv6 .= "	ddns-domainname \"{$dhcpv6ifconf['ddnsdomain']}\";\n";
1409
			}
1410
			if (empty($dhcpv6ifconf['ddnsclientupdates'])) {
1411
				$ddnsclientupdates = 'allow';
1412
			} else {
1413
				$ddnsclientupdates = $dhcpv6ifconf['ddnsclientupdates'];
1414
			}
1415
			$dnscfgv6 .= "	{$ddnsclientupdates} client-updates;\n";
1416
			$nsupdate = true;
1417
		} else {
1418
			$dnscfgv6 .= "	do-forward-updates false;\n";
1419
		}
1420

    
1421
		if (is_array($dhcpv6ifconf['dnsserver']) && ($dhcpv6ifconf['dnsserver'][0])) {
1422
			$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dhcpv6ifconf['dnsserver']) . ";";
1423
		} else if (((isset($config['dnsmasq']['enable'])) || isset($config['unbound']['enable'])) && (is_ipaddrv6($ifcfgipv6))) {
1424
			$dnscfgv6 .= "	option dhcp6.name-servers {$ifcfgipv6};";
1425
		} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1426
			$dns_arrv6 = array();
1427
			foreach ($syscfg['dnsserver'] as $dnsserver) {
1428
				if (is_ipaddrv6($dnsserver)) {
1429
					$dns_arrv6[] = $dnsserver;
1430
				}
1431
			}
1432
			if (!empty($dns_arrv6)) {
1433
				$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dns_arrv6) . ";";
1434
			}
1435
		}
1436

    
1437
		if (!is_ipaddrv6($ifcfgipv6)) {
1438
			$ifcfgsnv6 = "64";
1439
			$subnetv6 = gen_subnetv6($dhcpv6ifconf['range']['from'], $ifcfgsnv6);
1440
		}
1441

    
1442
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1443

    
1444
		if (isset($dhcpv6ifconf['ddnsupdate']) &&
1445
		    !empty($dhcpv6ifconf['ddnsdomain'])) {
1446
			$newzone = array();
1447
			$newzone['domain-name'] = $dhcpv6ifconf['ddnsdomain'];
1448
			$newzone['dns-servers'][] = $dhcpv6ifconf['ddnsdomainprimary'];
1449
			$newzone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1450
			$newzone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1451
			$ddns_zones[] = $newzone;
1452
			if (isset($dhcpv6ifconf['ddnsreverse'])) {
1453
				$ptr_zones = get_v6_ptr_zones($subnetv6, $ifcfgsnv6);
1454
				foreach ($ptr_zones as $ptr_zone) {
1455
					$reversezone = array();
1456
					$reversezone['ptr-domain'] = $ptr_zone;
1457
					$reversezone['dns-servers'][] = $dhcpv6ifconf['ddnsdomainprimary'];
1458
					$reversezone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1459
					$reversezone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1460
					$ddns_zones[] = $reversezone;
1461
				}
1462
			}
1463
		}
1464

    
1465
		$dhcpdv6conf .= " {\n";
1466

    
1467
		$range_from = $dhcpv6ifconf['range']['from'];
1468
		$range_to = $dhcpv6ifconf['range']['to'];
1469
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
1470
			$range_from = merge_ipv6_delegated_prefix($ifcfgipv6, $range_from, $pdlen);
1471
			$range_to = merge_ipv6_delegated_prefix($ifcfgipv6, $range_to, $pdlen);
1472
		}
1473

    
1474
		$dhcpdv6conf .= <<<EOD
1475
	range6 {$range_from} {$range_to};
1476
$dnscfgv6
1477

    
1478
EOD;
1479

    
1480
		if (is_ipaddrv6($dhcpv6ifconf['prefixrange']['from']) && is_ipaddrv6($dhcpv6ifconf['prefixrange']['to'])) {
1481
			$dhcpdv6conf .= "	prefix6 {$dhcpv6ifconf['prefixrange']['from']} {$dhcpv6ifconf['prefixrange']['to']} /{$dhcpv6ifconf['prefixrange']['prefixlength']};\n";
1482
		}
1483
		if (is_ipaddrv6($dhcpv6ifconf['dns6ip'])) {
1484
			$dns6ip = $dhcpv6ifconf['dns6ip'];
1485
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1486
			    Net_IPv6::isInNetmask($dns6ip, '::', $pdlen)) {
1487
				$dns6ip = merge_ipv6_delegated_prefix($ifcfgipv6, $dns6ip, $pdlen);
1488
			}
1489
			$dhcpdv6conf .= "	option dhcp6.name-servers {$dns6ip};\n";
1490
		}
1491
		// default-lease-time
1492
		if ($dhcpv6ifconf['defaultleasetime']) {
1493
			$dhcpdv6conf .= "	default-lease-time {$dhcpv6ifconf['defaultleasetime']};\n";
1494
		}
1495

    
1496
		// max-lease-time
1497
		if ($dhcpv6ifconf['maxleasetime']) {
1498
			$dhcpdv6conf .= "	max-lease-time {$dhcpv6ifconf['maxleasetime']};\n";
1499
		}
1500

    
1501
		// ntp-servers
1502
		if (is_array($dhcpv6ifconf['ntpserver']) && $dhcpv6ifconf['ntpserver'][0]) {
1503
			$ntpservers = array();
1504
			foreach ($dhcpv6ifconf['ntpserver'] as $ntpserver) {
1505
				if (!is_ipaddrv6($ntpserver)) {
1506
					continue;
1507
				}
1508
				if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1509
				    Net_IPv6::isInNetmask($ntpserver, '::', $pdlen)) {
1510
					$ntpserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ntpserver, $pdlen);
1511
				}
1512
				$ntpservers[] = $ntpserver;
1513
			}
1514
			if (count($ntpservers) > 0) {
1515
				$dhcpdv6conf .= "        option dhcp6.sntp-servers " . join(",", $dhcpv6ifconf['ntpserver']) . ";\n";
1516
			}
1517
		}
1518
		// tftp-server-name
1519
		/* Needs ISC DHCPD support
1520
		 if ($dhcpv6ifconf['tftp'] <> "") {
1521
			$dhcpdv6conf .= "	option tftp-server-name \"{$dhcpv6ifconf['tftp']}\";\n";
1522
		 }
1523
		*/
1524

    
1525
		// Handle option, number rowhelper values
1526
		$dhcpdv6conf .= "\n";
1527
		if ($dhcpv6ifconf['numberoptions']['item']) {
1528
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1529
				$itemv6_value = base64_decode($itemv6['value']);
1530
				$dhcpdv6conf .= "	option custom-{$dhcpv6if}-{$itemv6idx} \"{$itemv6_value}\";\n";
1531
			}
1532
		}
1533

    
1534
		// ldap-server
1535
		if ($dhcpv6ifconf['ldap'] <> "") {
1536
			$ldapserver = $dhcpv6ifconf['ldap'];
1537
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1538
			    Net_IPv6::isInNetmask($ldapserver, '::', $pdlen)) {
1539
				$ldapserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ldapserver, $pdlen);
1540
			}
1541
			$dhcpdv6conf .= "	option ldap-server \"{$ldapserver}\";\n";
1542
		}
1543

    
1544
		// net boot information
1545
		if (isset($dhcpv6ifconf['netboot'])) {
1546
			if (!empty($dhcpv6ifconf['bootfile_url'])) {
1547
				$dhcpdv6conf .= "	option dhcp6.bootfile-url \"{$dhcpv6ifconf['bootfile_url']}\";\n";
1548
			}
1549
		}
1550

    
1551
		$dhcpdv6conf .= "}\n";
1552

    
1553
		/* add static mappings */
1554
		/* Needs to use DUID */
1555
		if (is_array($dhcpv6ifconf['staticmap'])) {
1556
			$i = 0;
1557
			foreach ($dhcpv6ifconf['staticmap'] as $sm) {
1558
				$dhcpdv6conf .= <<<EOD
1559
host s_{$dhcpv6if}_{$i} {
1560
	host-identifier option dhcp6.client-id {$sm['duid']};
1561

    
1562
EOD;
1563
				if ($sm['ipaddrv6']) {
1564
					$ipaddrv6 = $sm['ipaddrv6'];
1565
					if ($ifcfgv6['ipaddrv6'] == 'track6') {
1566
						$ipaddrv6 = merge_ipv6_delegated_prefix($ifcfgipv6, $ipaddrv6, $pdlen);
1567
					}
1568
					$dhcpdv6conf .= "	fixed-address6 {$ipaddrv6};\n";
1569
				}
1570

    
1571
				if ($sm['hostname']) {
1572
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1573
					$dhhostname = str_replace(".", "_", $dhhostname);
1574
					$dhcpdv6conf .= "	option host-name {$dhhostname};\n";
1575
					if (isset($dhcpv6ifconf['ddnsupdate']) &&
1576
					    isset($dhcpv6ifconf['ddnsforcehostname'])) {
1577
						$dhcpdv6conf .= "	ddns-hostname \"{$dhhostname}\";\n";
1578
					}
1579
				}
1580
				if ($sm['filename']) {
1581
					$dhcpdv6conf .= "	filename \"{$sm['filename']}\";\n";
1582
				}
1583

    
1584
				if ($sm['rootpath']) {
1585
					$dhcpdv6conf .= "	option root-path \"{$sm['rootpath']}\";\n";
1586
				}
1587

    
1588
				$dhcpdv6conf .= "}\n";
1589
				$i++;
1590
			}
1591
		}
1592

    
1593
		if ($dhcpv6ifconf['ddnsdomain']) {
1594
			$dhcpdv6conf .= dhcpdkey($dhcpv6ifconf);
1595
			$dhcpdv6conf .= dhcpdzones($ddns_zones);
1596
		}
1597

    
1598
		if ($config['dhcpdv6'][$dhcpv6if]['ramode'] <> "unmanaged" && isset($config['interfaces'][$dhcpv6if]['enable'])) {
1599
			if (preg_match("/poes/si", $dhcpv6if)) {
1600
				/* magic here */
1601
				$dhcpdv6ifs = array_merge($dhcpdv6ifs, get_pppoes_child_interfaces($dhcpv6if));
1602
			} else {
1603
				$realif = get_real_interface($dhcpv6if, "inet6");
1604
				if (stristr("$realif", "bridge")) {
1605
					$mac = get_interface_mac($realif);
1606
					$v6address = generate_ipv6_from_mac($mac);
1607
					/* Create link local address for bridges */
1608
					mwexec("/sbin/ifconfig {$realif} inet6 {$v6address}");
1609
				}
1610
				$realif = escapeshellcmd($realif);
1611
				$dhcpdv6ifs[] = $realif;
1612
			}
1613
		}
1614
	}
1615

    
1616
	if ($nsupdate) {
1617
		$dhcpdv6conf .= "ddns-update-style interim;\n";
1618
	} else {
1619
		$dhcpdv6conf .= "ddns-update-style none;\n";
1620
	}
1621

    
1622
	/* write dhcpdv6.conf */
1623
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf", $dhcpdv6conf)) {
1624
		log_error("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1625
		if (platform_booting()) {
1626
			printf("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1627
		}
1628
		unset($dhcpdv6conf);
1629
		return 1;
1630
	}
1631
	unset($dhcpdv6conf);
1632

    
1633
	/* create an empty leases v6 database */
1634
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases")) {
1635
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1636
	}
1637

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

    
1642
	/* fire up dhcpd in a chroot */
1643
	if (count($dhcpdv6ifs) > 0) {
1644
		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 " .
1645
			join(" ", $dhcpdv6ifs));
1646
		mwexec("/usr/local/sbin/dhcpleases6 -c \"/usr/local/bin/php-cgi -f /usr/local/sbin/prefixes.php|/bin/sh\" -l {$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1647
	}
1648
	if (platform_booting()) {
1649
		print gettext("done.") . "\n";
1650
	}
1651

    
1652
	return 0;
1653
}
1654

    
1655
function services_igmpproxy_configure() {
1656
	global $config, $g;
1657

    
1658
	/* kill any running igmpproxy */
1659
	killbyname("igmpproxy");
1660

    
1661
	if (!isset($config['igmpproxy']['enable'])) {
1662
		return 0;
1663
	}
1664
	if (!is_array($config['igmpproxy']['igmpentry']) || (count($config['igmpproxy']['igmpentry']) == 0)) {
1665
		return 1;
1666
	}
1667

    
1668
	$iflist = get_configured_interface_list();
1669

    
1670
	$igmpconf = <<<EOD
1671

    
1672
##------------------------------------------------------
1673
## Enable Quickleave mode (Sends Leave instantly)
1674
##------------------------------------------------------
1675
quickleave
1676

    
1677
EOD;
1678

    
1679
	foreach ($config['igmpproxy']['igmpentry'] as $igmpcf) {
1680
		unset($iflist[$igmpcf['ifname']]);
1681
		$realif = get_real_interface($igmpcf['ifname']);
1682
		if (empty($igmpcf['threshold'])) {
1683
			$threshld = 1;
1684
		} else {
1685
			$threshld = $igmpcf['threshold'];
1686
		}
1687
		$igmpconf .= "phyint {$realif} {$igmpcf['type']} ratelimit 0 threshold {$threshld}\n";
1688

    
1689
		if ($igmpcf['address'] <> "") {
1690
			$item = explode(" ", $igmpcf['address']);
1691
			foreach ($item as $iww) {
1692
				$igmpconf .= "altnet {$iww}\n";
1693
			}
1694
		}
1695
		$igmpconf .= "\n";
1696
	}
1697
	foreach ($iflist as $ifn) {
1698
		$realif = get_real_interface($ifn);
1699
		$igmpconf .= "phyint {$realif} disabled\n";
1700
	}
1701
	$igmpconf .= "\n";
1702

    
1703
	$igmpfl = fopen($g['varetc_path'] . "/igmpproxy.conf", "w");
1704
	if (!$igmpfl) {
1705
		log_error(gettext("Could not write Igmpproxy configuration file!"));
1706
		return;
1707
	}
1708
	fwrite($igmpfl, $igmpconf);
1709
	fclose($igmpfl);
1710
	unset($igmpconf);
1711

    
1712
	if (isset($config['syslog']['igmpxverbose'])) {
1713
		mwexec_bg("/usr/local/sbin/igmpproxy -v {$g['varetc_path']}/igmpproxy.conf");
1714
	} else {
1715
		mwexec_bg("/usr/local/sbin/igmpproxy {$g['varetc_path']}/igmpproxy.conf");
1716
	}
1717

    
1718
	log_error(gettext("Started IGMP proxy service."));
1719

    
1720
	return 0;
1721
}
1722

    
1723
function services_dhcrelay_configure() {
1724
	global $config, $g;
1725

    
1726
	if (isset($config['system']['developerspew'])) {
1727
		$mt = microtime();
1728
		echo "services_dhcrelay_configure() being called $mt\n";
1729
	}
1730

    
1731
	/* kill any running dhcrelay */
1732
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
1733

    
1734
	init_config_arr(array('dhcrelay'));
1735
	$dhcrelaycfg = &$config['dhcrelay'];
1736

    
1737
	/* DHCPRelay enabled on any interfaces? */
1738
	if (!isset($dhcrelaycfg['enable'])) {
1739
		return 0;
1740
	}
1741

    
1742
	if (platform_booting()) {
1743
		echo gettext("Starting DHCP relay service...");
1744
	} else {
1745
		sleep(1);
1746
	}
1747

    
1748
	$iflist = get_configured_interface_list();
1749

    
1750
	$dhcrelayifs = array();
1751
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1752
	foreach ($dhcifaces as $dhcrelayif) {
1753
		if (!isset($iflist[$dhcrelayif]) ||
1754
		    link_interface_to_bridge($dhcrelayif)) {
1755
			continue;
1756
		}
1757

    
1758
		if (is_ipaddr(get_interface_ip($dhcrelayif))) {
1759
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1760
		}
1761
	}
1762
	$dhcrelayifs = array_unique($dhcrelayifs);
1763

    
1764
	/*
1765
	 * In order for the relay to work, it needs to be active
1766
	 * on the interface in which the destination server sits.
1767
	 */
1768
	$srvips = explode(",", $dhcrelaycfg['server']);
1769
	if (!is_array($srvips)) {
1770
		log_error(gettext("No destination IP has been configured!"));
1771
		return;
1772
	}
1773
	$srvifaces = array();
1774
	foreach ($srvips as $srcidx => $srvip) {
1775
		$destif = guess_interface_from_ip($srvip);
1776
		if (!empty($destif)) {
1777
			$srvifaces[] = $destif;
1778
		}
1779
	}
1780
	$srvifaces = array_unique($srvifaces);
1781

    
1782
	/* The server interface(s) should not be in this list */
1783
	$dhcrelayifs = array_diff($dhcrelayifs, $srvifaces);
1784

    
1785
	/* fire up dhcrelay */
1786
	if (empty($dhcrelayifs)) {
1787
		log_error(gettext("No suitable downstream interfaces found for running dhcrelay!"));
1788
		return; /* XXX */
1789
	}
1790
	if (empty($srvifaces)) {
1791
		log_error(gettext("No suitable upstream interfaces found for running dhcrelay!"));
1792
		return; /* XXX */
1793
	}
1794

    
1795
	$cmd = "/usr/local/sbin/dhcrelay";
1796
	$cmd .= " -id " . implode(" -id ", $dhcrelayifs);
1797
	$cmd .= " -iu " . implode(" -iu ", $srvifaces);
1798

    
1799
	if (isset($dhcrelaycfg['agentoption'])) {
1800
		$cmd .= " -a -m replace";
1801
	}
1802

    
1803
	$cmd .= " " . implode(" ", $srvips);
1804
	mwexec($cmd);
1805
	unset($cmd);
1806

    
1807
	return 0;
1808
}
1809

    
1810
function services_dhcrelay6_configure() {
1811
	global $config, $g;
1812

    
1813
	if (isset($config['system']['developerspew'])) {
1814
		$mt = microtime();
1815
		echo "services_dhcrelay6_configure() being called $mt\n";
1816
	}
1817

    
1818
	/* kill any running dhcrelay */
1819
	killbypid("{$g['varrun_path']}/dhcrelay6.pid");
1820

    
1821
	init_config_arr(array('dhcrelay6'));
1822
	$dhcrelaycfg = &$config['dhcrelay6'];
1823

    
1824
	/* DHCPv6 Relay enabled on any interfaces? */
1825
	if (!isset($dhcrelaycfg['enable'])) {
1826
		return 0;
1827
	}
1828

    
1829
	if (platform_booting()) {
1830
		echo gettext("Starting DHCPv6 relay service...");
1831
	} else {
1832
		sleep(1);
1833
	}
1834

    
1835
	$iflist = get_configured_interface_list();
1836

    
1837
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1838
	foreach ($dhcifaces as $dhcrelayif) {
1839
		if (!isset($iflist[$dhcrelayif]) ||
1840
		    link_interface_to_bridge($dhcrelayif)) {
1841
			continue;
1842
		}
1843

    
1844
		if (is_ipaddrv6(get_interface_ipv6($dhcrelayif))) {
1845
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1846
		}
1847
	}
1848
	$dhcrelayifs = array_unique($dhcrelayifs);
1849

    
1850
	/*
1851
	 * In order for the relay to work, it needs to be active
1852
	 * on the interface in which the destination server sits.
1853
	 */
1854
	$srvips = explode(",", $dhcrelaycfg['server']);
1855
	$srvifaces = array();
1856
	foreach ($srvips as $srcidx => $srvip) {
1857
		$destif = guess_interface_from_ip($srvip);
1858
		if (!empty($destif)) {
1859
			$srvifaces[] = "{$srvip}%{$destif}";
1860
		}
1861
	}
1862

    
1863
	/* fire up dhcrelay */
1864
	if (empty($dhcrelayifs) || empty($srvifaces)) {
1865
		log_error(gettext("No suitable interface found for running dhcrelay -6!"));
1866
		return; /* XXX */
1867
	}
1868

    
1869
	$cmd = "/usr/local/sbin/dhcrelay -6 -pf \"{$g['varrun_path']}/dhcrelay6.pid\"";
1870
	foreach ($dhcrelayifs as $dhcrelayif) {
1871
		$cmd .= " -l {$dhcrelayif}";
1872
	}
1873
	foreach ($srvifaces as $srviface) {
1874
		$cmd .= " -u \"{$srviface}\"";
1875
	}
1876
	mwexec($cmd);
1877
	unset($cmd);
1878

    
1879
	return 0;
1880
}
1881

    
1882
function services_dyndns_configure_client($conf) {
1883

    
1884
	if (!isset($conf['enable'])) {
1885
		return;
1886
	}
1887

    
1888
	/* load up the dyndns.class */
1889
	require_once("dyndns.class");
1890

    
1891
	$dns = new updatedns($dnsService = $conf['type'],
1892
		$dnsHost = $conf['host'],
1893
		$dnsDomain = $conf['domainname'],
1894
		$dnsUser = $conf['username'],
1895
		$dnsPass = $conf['password'],
1896
		$dnsWildcard = $conf['wildcard'],
1897
		$dnsProxied = $conf['proxied'],
1898
		$dnsMX = $conf['mx'],
1899
		$dnsIf = "{$conf['interface']}",
1900
		$dnsBackMX = NULL,
1901
		$dnsServer = NULL,
1902
		$dnsPort = NULL,
1903
		$dnsUpdateURL = "{$conf['updateurl']}",
1904
		$forceUpdate = $conf['force'],
1905
		$dnsZoneID = $conf['zoneid'],
1906
		$dnsTTL = $conf['ttl'],
1907
		$dnsResultMatch = "{$conf['resultmatch']}",
1908
		$dnsRequestIf = "{$conf['requestif']}",
1909
		$dnsID = "{$conf['id']}",
1910
		$dnsVerboseLog = $conf['verboselog'],
1911
		$curlIpresolveV4 = $conf['curl_ipresolve_v4'],
1912
		$curlSslVerifypeer = $conf['curl_ssl_verifypeer']);
1913
}
1914

    
1915
function services_dyndns_configure($int = "") {
1916
	global $config, $g;
1917
	if (isset($config['system']['developerspew'])) {
1918
		$mt = microtime();
1919
		echo "services_dyndns_configure() being called $mt\n";
1920
	}
1921

    
1922
	$dyndnscfg = $config['dyndnses']['dyndns'];
1923
	$gwgroups = return_gateway_groups_array(true);
1924
	if (is_array($dyndnscfg)) {
1925
		if (platform_booting()) {
1926
			echo gettext("Starting DynDNS clients...");
1927
		}
1928

    
1929
		foreach ($dyndnscfg as $dyndns) {
1930
			/*
1931
			 * If it's using a gateway group, check if interface is
1932
			 * the active gateway for that group
1933
			 */
1934
			$group_int = '';
1935
			$friendly_group_int = '';
1936
			$gwgroup_member = false;
1937
			if (is_array($gwgroups[$dyndns['interface']])) {
1938
				if (!empty($gwgroups[$dyndns['interface']][0]['vip'])) {
1939
					$group_int = $gwgroups[$dyndns['interface']][0]['vip'];
1940
				} else {
1941
					$group_int = $gwgroups[$dyndns['interface']][0]['int'];
1942
					$friendly_group_int =
1943
					    convert_real_interface_to_friendly_interface_name(
1944
						$group_int);
1945
					if (!empty($int)) {
1946
						$gwgroup_member =
1947
						    interface_gateway_group_member(get_real_interface($int),
1948
						    $dyndns['interface']);
1949
					}
1950
				}
1951
			}
1952
			if ((empty($int)) || ($int == $dyndns['interface']) || $gwgroup_member ||
1953
			    ($int == $group_int) || ($int == $friendly_group_int)) {
1954
				$dyndns['verboselog'] = isset($dyndns['verboselog']);
1955
				$dyndns['curl_ipresolve_v4'] = isset($dyndns['curl_ipresolve_v4']);
1956
				$dyndns['curl_ssl_verifypeer'] = isset($dyndns['curl_ssl_verifypeer']);
1957
				$dyndns['proxied'] = isset($dyndns['proxied']);
1958
				services_dyndns_configure_client($dyndns);
1959
				sleep(1);
1960
			}
1961
		}
1962

    
1963
		if (platform_booting()) {
1964
			echo gettext("done.") . "\n";
1965
		}
1966
	}
1967

    
1968
	return 0;
1969
}
1970

    
1971
function dyndnsCheckIP($int) {
1972
	global $config, $factory_default_checkipservice;
1973
	$ip_address = get_interface_ip($int);
1974
	if (is_private_ip($ip_address)) {
1975
		$gateways_status = return_gateways_status(true);
1976
		// If the gateway for this interface is down, then the external check cannot work.
1977
		// Avoid the long wait for the external check to timeout.
1978
		if (stristr($gateways_status[$config['interfaces'][$int]['gateway']]['status'], "down")) {
1979
			return "down";
1980
		}
1981

    
1982
		// Append the factory default check IP service to the list (if not disabled).
1983
		if (!isset($config['checkipservices']['disable_factory_default'])) {
1984
			if (!is_array($config['checkipservices'])) {
1985
				$config['checkipservices'] = array();
1986
			}
1987
			if (!is_array($config['checkipservices']['checkipservice'])) {
1988
				$config['checkipservices']['checkipservice'] = array();
1989
			}
1990
			$config['checkipservices']['checkipservice'][] = $factory_default_checkipservice;
1991
		}
1992

    
1993
		// Use the first enabled check IP service as the default.
1994
		if (is_array($config['checkipservices']['checkipservice'])) {
1995
			foreach ($config['checkipservices']['checkipservice'] as $i => $checkipservice) {
1996
				if (isset($checkipservice['enable'])) {
1997
					$url = $checkipservice['url'];
1998
					$username = $checkipservice['username'];
1999
					$password = $checkipservice['password'];
2000
					$verifysslpeer = isset($checkipservice['verifysslpeer']);
2001
					break;
2002
				}
2003
			}
2004
		}
2005

    
2006
		$hosttocheck = $url;
2007
		$ip_ch = curl_init($hosttocheck);
2008
		curl_setopt($ip_ch, CURLOPT_RETURNTRANSFER, 1);
2009
		curl_setopt($ip_ch, CURLOPT_SSL_VERIFYPEER, $verifysslpeer);
2010
		curl_setopt($ip_ch, CURLOPT_INTERFACE, 'host!' . $ip_address);
2011
		curl_setopt($ip_ch, CURLOPT_CONNECTTIMEOUT, '30');
2012
		curl_setopt($ip_ch, CURLOPT_TIMEOUT, 120);
2013
		curl_setopt($ip_ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
2014
		curl_setopt($ip_ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
2015
		curl_setopt($ip_ch, CURLOPT_USERPWD, "{$username}:{$password}");
2016
		$ip_result_page = curl_exec($ip_ch);
2017
		curl_close($ip_ch);
2018
		$ip_result_decoded = urldecode($ip_result_page);
2019
		preg_match('=Current IP Address: (.*)</body>=siU', $ip_result_decoded, $matches);
2020
		$ip_address = trim($matches[1]);
2021
	}
2022
	return $ip_address;
2023
}
2024

    
2025
function services_dnsmasq_configure($restart_dhcp = true) {
2026
	global $config, $g;
2027
	$return = 0;
2028

    
2029
	// hard coded args: will be removed to avoid duplication if specified in custom_options
2030
	$standard_args = array(
2031
		"dns-forward-max" => "--dns-forward-max=5000",
2032
		"cache-size" => "--cache-size=10000",
2033
		"local-ttl" => "--local-ttl=1"
2034
	);
2035

    
2036

    
2037
	if (isset($config['system']['developerspew'])) {
2038
		$mt = microtime();
2039
		echo "services_dnsmasq_configure() being called $mt\n";
2040
	}
2041

    
2042
	/* kill any running dnsmasq */
2043
	if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) {
2044
		sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
2045
	}
2046

    
2047
	if (isset($config['dnsmasq']['enable'])) {
2048

    
2049
		if (platform_booting()) {
2050
			echo gettext("Starting DNS forwarder...");
2051
		} else {
2052
			sleep(1);
2053
		}
2054

    
2055
		/* generate hosts file */
2056
		if (system_hosts_generate() != 0) {
2057
			$return = 1;
2058
		}
2059

    
2060
		$args = "";
2061

    
2062
		if (isset($config['dnsmasq']['regdhcp'])) {
2063
			$args .= " --dhcp-hostsfile={$g['etc_path']}/hosts ";
2064
		}
2065

    
2066
		/* Setup listen port, if non-default */
2067
		if (is_port($config['dnsmasq']['port'])) {
2068
			$args .= " --port={$config['dnsmasq']['port']} ";
2069
		}
2070

    
2071
		$listen_addresses = "";
2072
		if (isset($config['dnsmasq']['interface'])) {
2073
			$interfaces = explode(",", $config['dnsmasq']['interface']);
2074
			foreach ($interfaces as $interface) {
2075
				$if = get_real_interface($interface);
2076
				if (does_interface_exist($if)) {
2077
					$laddr = get_interface_ip($interface);
2078
					if (is_ipaddrv4($laddr)) {
2079
						$listen_addresses .= " --listen-address={$laddr} ";
2080
					}
2081
					$laddr6 = get_interface_ipv6($interface);
2082
					if (is_ipaddrv6($laddr6) && !isset($config['dnsmasq']['strictbind'])) {
2083
						/*
2084
						 * XXX: Since dnsmasq does not support link-local address
2085
						 * with scope specified. These checks are being done.
2086
						 */
2087
						if (is_linklocal($laddr6) && strstr($laddr6, "%")) {
2088
							$tmpaddrll6 = explode("%", $laddr6);
2089
							$listen_addresses .= " --listen-address={$tmpaddrll6[0]} ";
2090
						} else {
2091
							$listen_addresses .= " --listen-address={$laddr6} ";
2092
						}
2093
					}
2094
				}
2095
			}
2096
			if (!empty($listen_addresses)) {
2097
				$args .= " {$listen_addresses} ";
2098
				if (isset($config['dnsmasq']['strictbind'])) {
2099
					$args .= " --bind-interfaces ";
2100
				}
2101
			}
2102
		}
2103

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

    
2111
			// Build an array of domain overrides to help in checking for matches.
2112
			$override_a = array();
2113
			if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2114
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2115
					$override_a[$override['domain']] = "y";
2116
				}
2117
			}
2118

    
2119
			// Build an array of the private reverse lookup domain names
2120
			$reverse_domain_a = array("10.in-addr.arpa", "168.192.in-addr.arpa");
2121
			// Unfortunately the 172.16.0.0/12 range does not map nicely to the in-addr.arpa scheme.
2122
			for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) {
2123
				$reverse_domain_a[] = "$subnet_num.172.in-addr.arpa";
2124
			}
2125

    
2126
			// Set the --server parameter to nowhere for each reverse domain name that was not specifically specified in a domain override.
2127
			foreach ($reverse_domain_a as $reverse_domain) {
2128
				if (!isset($override_a[$reverse_domain])) {
2129
					$args .= " --server=/$reverse_domain/ ";
2130
				}
2131
			}
2132
			unset($override_a);
2133
			unset($reverse_domain_a);
2134
		}
2135

    
2136
		/* Setup forwarded domains */
2137
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2138
			foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2139
				if ($override['ip'] == "!") {
2140
					$override[ip] = "";
2141
				}
2142
				$args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
2143
			}
2144
		}
2145

    
2146
		/* Allow DNS Rebind for forwarded domains */
2147
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2148
			if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2149
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2150
					$args .= ' --rebind-domain-ok=/' . $override['domain'] . '/ ';
2151
				}
2152
			}
2153
		}
2154

    
2155
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2156
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2157
		}
2158

    
2159
		if (isset($config['dnsmasq']['strict_order'])) {
2160
			$args .= " --strict-order ";
2161
		}
2162

    
2163
		if (isset($config['dnsmasq']['domain_needed'])) {
2164
			$args .= " --domain-needed ";
2165
		}
2166

    
2167
		if ($config['dnsmasq']['custom_options']) {
2168
			foreach (preg_split('/\s+/', $config['dnsmasq']['custom_options']) as $c) {
2169
				$args .= " " . escapeshellarg("--{$c}");
2170
				$p = explode('=', $c);
2171
				if (array_key_exists($p[0], $standard_args)) {
2172
					unset($standard_args[$p[0]]);
2173
				}
2174
			}
2175
		}
2176
		$args .= ' ' . implode(' ', array_values($standard_args));
2177

    
2178
		/* run dnsmasq. Use "-C /dev/null" since we use command line args only (Issue #6730) */
2179
		$cmd = "/usr/local/sbin/dnsmasq --all-servers -C /dev/null {$dns_rebind} {$args}";
2180
		//log_error("dnsmasq command: {$cmd}");
2181
		mwexec_bg($cmd);
2182
		unset($args);
2183

    
2184
		system_dhcpleases_configure();
2185

    
2186
		if (platform_booting()) {
2187
			echo gettext("done.") . "\n";
2188
		}
2189
	}
2190

    
2191
	if (!platform_booting() && $restart_dhcp) {
2192
		if (services_dhcpd_configure() != 0) {
2193
			$return = 1;
2194
		}
2195
	}
2196

    
2197
	return $return;
2198
}
2199

    
2200
function services_unbound_configure($restart_dhcp = true) {
2201
	global $config, $g;
2202
	$return = 0;
2203

    
2204
	if (isset($config['system']['developerspew'])) {
2205
		$mt = microtime();
2206
		echo "services_unbound_configure() being called $mt\n";
2207
	}
2208

    
2209
	if (isset($config['unbound']['enable'])) {
2210
		require_once('/etc/inc/unbound.inc');
2211

    
2212
		/* Stop Unbound using TERM */
2213
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2214
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
2215
		}
2216

    
2217
		/* If unbound is still running, wait up to 30 seconds for it to terminate. */
2218
		for ($i=1; $i <= 30; $i++) {
2219
			if (is_process_running('unbound')) {
2220
				sleep(1);
2221
			}
2222
		}
2223

    
2224
		if (platform_booting()) {
2225
			echo gettext("Starting DNS Resolver...");
2226
		} else {
2227
			sleep(1);
2228
		}
2229

    
2230
		/* generate hosts file */
2231
		if (system_hosts_generate() != 0) {
2232
			$return = 1;
2233
		}
2234

    
2235
		/* Check here for dhcp6 complete - wait upto 10 seconds */
2236
		if($config['interfaces']["wan"]['ipaddrv6'] == 'dhcp6') {
2237
			$wanif = get_real_interface("wan", "inet6");
2238
			if (platform_booting()) {
2239
				for ($i=1; $i <= 10; $i++) {
2240
					if (!file_exists("/tmp/{$wanif}_dhcp6_complete")) {
2241
						log_error(gettext("Unbound start waiting on dhcp6c."));
2242
						sleep(1);
2243
					} else {
2244
						unlink_if_exists("/tmp/{$wanif}_dhcp6_complete");
2245
						log_error(gettext("dhcp6 init complete. Continuing"));
2246
						break;
2247
					}
2248
				}
2249
			}
2250
		}
2251

    
2252
		sync_unbound_service();
2253
		if (platform_booting()) {
2254
			log_error(gettext("sync unbound done."));
2255
			echo gettext("done.") . "\n";
2256
		}
2257

    
2258
		system_dhcpleases_configure();
2259
	} else {
2260
		/* kill Unbound since it should not be enabled */
2261
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2262
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "KILL");
2263
		}
2264
	}
2265

    
2266
	if (!platform_booting() && $restart_dhcp) {
2267
		if (services_dhcpd_configure() != 0) {
2268
			$return = 1;
2269
		}
2270
	}
2271

    
2272
	return $return;
2273
}
2274

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

    
2282
	/* kill any running snmpd */
2283
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
2284
	sleep(2);
2285
	if (is_process_running("bsnmpd")) {
2286
		mwexec("/usr/bin/killall bsnmpd", true);
2287
	}
2288

    
2289
	if (isset($config['snmpd']['enable'])) {
2290

    
2291
		if (platform_booting()) {
2292
			echo gettext("Starting SNMP daemon... ");
2293
		}
2294

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

    
2300
		/* generate snmpd.conf */
2301
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
2302
		if (!$fd) {
2303
			printf(gettext("Error: cannot open snmpd.conf in services_snmpd_configure().%s"), "\n");
2304
			return 1;
2305
		}
2306

    
2307

    
2308
		$snmpdconf = <<<EOD
2309
location := "{$config['snmpd']['syslocation']}"
2310
contact := "{$config['snmpd']['syscontact']}"
2311
read := "{$config['snmpd']['rocommunity']}"
2312

    
2313
EOD;
2314

    
2315
/* No docs on what write strings do there so disable for now.
2316
		if (isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])) {
2317
			$snmpdconf .= <<<EOD
2318
# write string
2319
write := "{$config['snmpd']['rwcommunity']}"
2320

    
2321
EOD;
2322
		}
2323
*/
2324

    
2325

    
2326
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2327
			$snmpdconf .= <<<EOD
2328
# SNMP Trap support.
2329
traphost := {$config['snmpd']['trapserver']}
2330
trapport := {$config['snmpd']['trapserverport']}
2331
trap := "{$config['snmpd']['trapstring']}"
2332

    
2333

    
2334
EOD;
2335
		}
2336
		
2337
		if ($g['product_version_string']) {
2338
			$sysDescr = "{$g['product_name']} {$config['system']['hostname']}.{$config['system']['domain']}" .
2339
				" {$g['product_version_string']} {$g['platform']} " . php_uname("s") .
2340
				" " . php_uname("r") . " " . php_uname("m");
2341
		}
2342
		else {
2343
			$sysDescr = "{$g['product_name']} {$config['system']['hostname']}.{$config['system']['domain']}" .
2344
				" {$g['product_version']} {$g['platform']} " . php_uname("s") .
2345
				" " . php_uname("r") . " " . php_uname("m");
2346
		}
2347

    
2348
		$snmpdconf .= <<<EOD
2349
system := 1     # pfSense
2350
%snmpd
2351
sysDescr			= "{$sysDescr}"
2352
begemotSnmpdDebugDumpPdus       = 2
2353
begemotSnmpdDebugSyslogPri      = 7
2354
begemotSnmpdCommunityString.0.1 = $(read)
2355

    
2356
EOD;
2357

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

    
2363
EOD;
2364
		}
2365
*/
2366

    
2367

    
2368
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2369
			$snmpdconf .= <<<EOD
2370
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
2371
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
2372
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
2373

    
2374
EOD;
2375
		}
2376

    
2377

    
2378
		$snmpdconf .= <<<EOD
2379
begemotSnmpdCommunityDisable    = 1
2380

    
2381
EOD;
2382

    
2383
		$bind_to_ips = array();
2384
		if (isset($config['snmpd']['bindip'])) {
2385
			foreach (explode(",", $config['snmpd']['bindip']) as $bind_to_ip) {
2386
				if (is_ipaddr($bind_to_ip)) {
2387
					$bind_to_ips[] = $bind_to_ip;
2388
				} else {
2389
					$if = get_real_interface($bind_to_ip);
2390
					if (does_interface_exist($if)) {
2391
						$bindip = get_interface_ip($bind_to_ip);
2392
						if (is_ipaddr($bindip)) {
2393
							$bind_to_ips[] = $bindip;
2394
						}
2395
					}
2396
				}
2397
			}
2398
		}
2399
		if (!count($bind_to_ips)) {
2400
			$bind_to_ips = array("0.0.0.0");
2401
		}
2402

    
2403
		if (is_port($config['snmpd']['pollport'])) {
2404
			foreach ($bind_to_ips as $bind_to_ip) {
2405
				$snmpdconf .= <<<EOD
2406
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
2407

    
2408
EOD;
2409

    
2410
			}
2411
		}
2412

    
2413
		$snmpdconf .= <<<EOD
2414
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
2415
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
2416

    
2417
# These are bsnmp macros not php vars.
2418
sysContact      = $(contact)
2419
sysLocation     = $(location)
2420
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
2421

    
2422
snmpEnableAuthenTraps = 2
2423

    
2424
EOD;
2425

    
2426
		if (is_array($config['snmpd']['modules'])) {
2427
			if (isset($config['snmpd']['modules']['mibii'])) {
2428
			$snmpdconf .= <<<EOD
2429
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
2430

    
2431
EOD;
2432
			}
2433

    
2434
			if (isset($config['snmpd']['modules']['netgraph'])) {
2435
				$snmpdconf .= <<<EOD
2436
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
2437
%netgraph
2438
begemotNgControlNodeName = "snmpd"
2439

    
2440
EOD;
2441
			}
2442

    
2443
			if (isset($config['snmpd']['modules']['pf'])) {
2444
				$snmpdconf .= <<<EOD
2445
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
2446

    
2447
EOD;
2448
			}
2449

    
2450
			if (isset($config['snmpd']['modules']['hostres'])) {
2451
				$snmpdconf .= <<<EOD
2452
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
2453

    
2454
EOD;
2455
			}
2456

    
2457
			if (isset($config['snmpd']['modules']['bridge'])) {
2458
				$snmpdconf .= <<<EOD
2459
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
2460
# config must end with blank line
2461

    
2462
EOD;
2463
			}
2464
			if (isset($config['snmpd']['modules']['ucd'])) {
2465
				$snmpdconf .= <<<EOD
2466
begemotSnmpdModulePath."ucd"     = "/usr/local/lib/snmp_ucd.so"
2467

    
2468
EOD;
2469
			}
2470
			if (isset($config['snmpd']['modules']['regex'])) {
2471
				$snmpdconf .= <<<EOD
2472
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"
2473

    
2474
EOD;
2475
			}
2476
		}
2477

    
2478
		fwrite($fd, $snmpdconf);
2479
		fclose($fd);
2480
		unset($snmpdconf);
2481

    
2482
		/* run bsnmpd */
2483
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
2484
			" -p {$g['varrun_path']}/snmpd.pid");
2485

    
2486
		if (platform_booting()) {
2487
			echo gettext("done.") . "\n";
2488
		}
2489
	}
2490

    
2491
	return 0;
2492
}
2493

    
2494
function services_dnsupdate_process($int = "", $updatehost = "", $forced = false) {
2495
	global $config, $g;
2496
	if (isset($config['system']['developerspew'])) {
2497
		$mt = microtime();
2498
		echo "services_dnsupdate_process() being called $mt\n";
2499
	}
2500

    
2501
	/* Dynamic DNS updating active? */
2502
	if (!is_array($config['dnsupdates']['dnsupdate'])) {
2503
		return 0;
2504
	}
2505

    
2506
	$notify_text = "";
2507
	$gwgroups = return_gateway_groups_array(true);
2508
	foreach ($config['dnsupdates']['dnsupdate'] as $i => $dnsupdate) {
2509
		if (!isset($dnsupdate['enable'])) {
2510
			continue;
2511
		}
2512
		/*
2513
		 * If it's using a gateway group, check if interface is
2514
		 * the active gateway for that group
2515
		 */
2516
		$group_int = '';
2517
		$friendly_group_int = '';
2518
		$gwgroup_member = false;
2519
		if (is_array($gwgroups[$dnsupdate['interface']])) {
2520
			if (!empty($gwgroups[$dnsupdate['interface']][0]['vip'])) {
2521
				$group_int = $gwgroups[$dnsupdate['interface']][0]['vip'];
2522
			} else {
2523
				$group_int = $gwgroups[$dnsupdate['interface']][0]['int'];
2524
				$friendly_group_int =
2525
				    convert_real_interface_to_friendly_interface_name(
2526
					$group_int);
2527
				if (!empty($int)) {
2528
					$gwgroup_member =
2529
					    interface_gateway_group_member(get_real_interface($int),
2530
					    $dnsupdate['interface']);
2531
				}
2532
			}
2533
		}
2534
		if (!empty($int) && ($int != $dnsupdate['interface']) && !$gwgroup_member &&
2535
		    ($int != $group_int) && ($int != $friendly_group_int)) {
2536
			continue;
2537
		}
2538
		if (!empty($updatehost) && ($updatehost != $dnsupdate['host'])) {
2539
			continue;
2540
		}
2541

    
2542
		/* determine interface name */
2543
		$if = get_failover_interface($dnsupdate['interface']);
2544

    
2545
		/* Determine address to update and default binding address */
2546
		if (isset($dnsupdate['usepublicip'])) {
2547
			$wanip = dyndnsCheckIP($if);
2548
			$bindipv4 = get_interface_ip($if);
2549
		} else {
2550
			$wanip = get_interface_ip($if);
2551
			$bindipv4 = $wanip;
2552
		}
2553
		$wanipv6 = get_interface_ipv6($if);
2554
		$bindipv6 = $wanipv6;
2555

    
2556
		/* Handle non-default interface bindings */
2557
		if ($dnsupdate['updatesource'] == "none") {
2558
			/* When empty, the directive will be omitted. */
2559
			$bindipv4 = "";
2560
			$bindipv6 = "";
2561
		} elseif (!empty($dnsupdate['updatesource'])) {
2562
			/* Find the alternate binding address */
2563
			$bindipv4 = get_interface_ip($dnsupdate['updatesource']);
2564
			$bindipv6 = get_interface_ipv6($dnsupdate['updatesource']);
2565
		}
2566

    
2567
		/* Handle IPv4/IPv6 selection for the update source interface/VIP */
2568
		switch ($dnsupdate['updatesourcefamily']) {
2569
			case "inet":
2570
				$bindip = $bindipv4;
2571
				break;
2572
			case "inet6":
2573
				$bindip = $bindipv6;
2574
				break;
2575
			case "":
2576
			default:
2577
				/* Try IPv4 first, if that is empty, try IPv6. */
2578
				/* Only specify the address if it's present, otherwise omit. */
2579
				if (!empty($bindipv4)) {
2580
					$bindip = $bindipv4;
2581
				} elseif (!empty($bindipv6)) {
2582
					$bindip = $bindipv6;
2583
				}
2584
				break;
2585
		}
2586

    
2587
		$cacheFile = $g['conf_path'] .
2588
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2589
		    escapeshellarg($dnsupdate['host']) .
2590
		    "_{$dnsupdate['server']}.cache";
2591
		$cacheFilev6 = $g['conf_path'] .
2592
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2593
		    escapeshellarg($dnsupdate['host']) .
2594
		    "_{$dnsupdate['server']}_v6.cache";
2595
		$currentTime = time();
2596

    
2597
		if (!$wanip && !$wanipv6) {
2598
			continue;
2599
		}
2600

    
2601
		$keyname = $dnsupdate['keyname'];
2602
		/* trailing dot */
2603
		if (substr($keyname, -1) != ".") {
2604
			$keyname .= ".";
2605
		}
2606

    
2607
		$hostname = $dnsupdate['host'];
2608
		/* trailing dot */
2609
		if (substr($hostname, -1) != ".") {
2610
			$hostname .= ".";
2611
		}
2612

    
2613
		/* write key file */
2614
		$algorithm = empty($dnsupdate['keyalgorithm']) ? 'hmac-md5' : $dnsupdate['keyalgorithm'];
2615
		$upkey = <<<EOD
2616
key "{$keyname}" {
2617
	algorithm {$algorithm};
2618
	secret "{$dnsupdate['keydata']}";
2619
};
2620

    
2621
EOD;
2622
		@file_put_contents("{$g['varetc_path']}/nsupdatekey{$i}", $upkey);
2623

    
2624
		/* generate update instructions */
2625
		$upinst = "";
2626
		if (!empty($dnsupdate['server'])) {
2627
			$upinst .= "server {$dnsupdate['server']}\n";
2628
		}
2629

    
2630
		$cachedipv4 = '';
2631
		$cacheTimev4 = 0;
2632
		if (file_exists($cacheFile)) {
2633
			list($cachedipv4, $cacheTimev4) = explode("|",
2634
			    file_get_contents($cacheFile));
2635
		}
2636
		$cachedipv6 = '';
2637
		$cacheTimev6 = 0;
2638
		if (file_exists($cacheFilev6)) {
2639
			list($cachedipv6, $cacheTimev6) = explode("|",
2640
			    file_get_contents($cacheFilev6));
2641
		}
2642

    
2643
		// 25 Days
2644
		$maxCacheAgeSecs = 25 * 24 * 60 * 60;
2645
		$need_update = false;
2646

    
2647
		/* Update IPv4 if we have it. */
2648
		if (is_ipaddrv4($wanip) && $dnsupdate['recordtype'] != "AAAA") {
2649
			if (($wanip != $cachedipv4) || $forced ||
2650
			    (($currentTime - $cacheTimev4) > $maxCacheAgeSecs)) {
2651
				$upinst .= "update delete " .
2652
				    "{$dnsupdate['host']}. A\n";
2653
				$upinst .= "update add {$dnsupdate['host']}. " .
2654
				    "{$dnsupdate['ttl']} A {$wanip}\n";
2655
				if (!empty($bindip)) {
2656
					$upinst .= "local {$bindip}\n";
2657
				}
2658
				$need_update = true;
2659
			} else {
2660
				log_error(sprintf(gettext(
2661
				    "phpDynDNS: Not updating %s A record because the IP address has not changed."),
2662
				    $dnsupdate['host']));
2663
			}
2664
		} else {
2665
			@unlink($cacheFile);
2666
			unset($cacheFile);
2667
		}
2668

    
2669
		/* Update IPv6 if we have it. */
2670
		if (is_ipaddrv6($wanipv6) && $dnsupdate['recordtype'] != "A") {
2671
			if (($wanipv6 != $cachedipv6) || $forced ||
2672
			    (($currentTime - $cacheTimev6) > $maxCacheAgeSecs)) {
2673
				$upinst .= "update delete " .
2674
				    "{$dnsupdate['host']}. AAAA\n";
2675
				$upinst .= "update add {$dnsupdate['host']}. " .
2676
				    "{$dnsupdate['ttl']} AAAA {$wanipv6}\n";
2677
				$need_update = true;
2678
			} else {
2679
				log_error(sprintf(gettext(
2680
				    "phpDynDNS: Not updating %s AAAA record because the IPv6 address has not changed."),
2681
				    $dnsupdate['host']));
2682
			}
2683
		} else {
2684
			@unlink($cacheFilev6);
2685
			unset($cacheFilev6);
2686
		}
2687

    
2688
		$upinst .= "\n";	/* mind that trailing newline! */
2689

    
2690
		if (!$need_update) {
2691
			continue;
2692
		}
2693

    
2694
		@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}", $upinst);
2695
		unset($upinst);
2696
		/* invoke nsupdate */
2697
		$cmd = "/usr/local/bin/nsupdate -k {$g['varetc_path']}/nsupdatekey{$i}";
2698

    
2699
		if (isset($dnsupdate['usetcp'])) {
2700
			$cmd .= " -v";
2701
		}
2702

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

    
2705
		if (mwexec($cmd) == 0) {
2706
			if (!empty($cacheFile)) {
2707
				@file_put_contents($cacheFile,
2708
				    "{$wanip}|{$currentTime}");
2709
				log_error(sprintf(gettext(
2710
				    'phpDynDNS: updating cache file %1$s: %2$s'),
2711
				    $cacheFile, $wanip));
2712
				$notify_text .= sprintf(gettext(
2713
				    'DynDNS updated IP Address (A) for %1$s on %2$s (%3$s) to %4$s'),
2714
				    $dnsupdate['host'],
2715
				    convert_real_interface_to_friendly_descr($if),
2716
				    $if, $wanip) . "\n";
2717
			}
2718
			if (!empty($cacheFilev6)) {
2719
				@file_put_contents($cacheFilev6,
2720
				    "{$wanipv6}|{$currentTime}");
2721
				log_error(sprintf(gettext(
2722
				    'phpDynDNS: updating cache file %1$s: %2$s'),
2723
				    $cacheFilev6, $wanipv6));
2724
				$notify_text .= sprintf(gettext(
2725
				    'DynDNS updated IPv6 Address (AAAA) for %1$s on %2$s (%3$s) to %4$s'),
2726
				    $dnsupdate['host'],
2727
				    convert_real_interface_to_friendly_descr($if),
2728
				    $if, $wanipv6) . "\n";
2729
			}
2730
		} else {
2731
			if (!empty($cacheFile)) {
2732
				log_error(sprintf(gettext(
2733
				    'phpDynDNS: ERROR while updating IP Address (A) for %1$s (%2$s)'),
2734
				    $dnsupdate['host'], $wanip));
2735
			}
2736
			if (!empty($cacheFilev6)) {
2737
				log_error(sprintf(gettext(
2738
				    'phpDynDNS: ERROR while updating IP Address (AAAA) for %1$s (%2$s)'),
2739
				    $dnsupdate['host'], $wanipv6));
2740
			}
2741
		}
2742
		unset($cmd);
2743
	}
2744

    
2745
	if (!empty($notify_text)) {
2746
		notify_all_remote($notify_text);
2747
	}
2748

    
2749
	return 0;
2750
}
2751

    
2752
/* configure cron service */
2753
function configure_cron() {
2754
	global $g, $config;
2755

    
2756
	/* preserve existing crontab entries */
2757
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2758

    
2759
	for ($i = 0; $i < count($crontab_contents); $i++) {
2760
		$cron_item = &$crontab_contents[$i];
2761
		if (strpos($cron_item, "# pfSense specific crontab entries") !== false) {
2762
			array_splice($crontab_contents, $i - 1);
2763
			break;
2764
		}
2765
	}
2766
	$crontab_contents = implode("\n", $crontab_contents) . "\n";
2767

    
2768

    
2769
	if (is_array($config['cron']['item'])) {
2770
		$crontab_contents .= "#\n";
2771
		$crontab_contents .= "# pfSense specific crontab entries\n";
2772
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
2773
		$crontab_contents .= "#\n";
2774

    
2775
		if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) {
2776
			$http_proxy = $config['system']['proxyurl'];
2777
			if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) {
2778
				$http_proxy .= ':' . $config['system']['proxyport'];
2779
			}
2780
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
2781

    
2782
			if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
2783
				$crontab_contents .= "HTTP_PROXY_AUTH=basic:*:{$config['system']['proxyuser']}:{$config['system']['proxypass']}";
2784
			}
2785
		}
2786

    
2787
		foreach ($config['cron']['item'] as $item) {
2788
			$crontab_contents .= "\n{$item['minute']}\t";
2789
			$crontab_contents .= "{$item['hour']}\t";
2790
			$crontab_contents .= "{$item['mday']}\t";
2791
			$crontab_contents .= "{$item['month']}\t";
2792
			$crontab_contents .= "{$item['wday']}\t";
2793
			$crontab_contents .= "{$item['who']}\t";
2794
			$crontab_contents .= "{$item['command']}";
2795
		}
2796

    
2797
		$crontab_contents .= "\n#\n";
2798
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
2799
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
2800
		$crontab_contents .= "#\n\n";
2801
	}
2802

    
2803
	/* please maintain the newline at the end of file */
2804
	file_put_contents("/etc/crontab", $crontab_contents);
2805
	unset($crontab_contents);
2806

    
2807
	/* make sure that cron is running and start it if it got killed somehow */
2808
	if (!is_process_running("cron")) {
2809
		exec("cd /tmp && /usr/sbin/cron -s 2>/dev/null");
2810
	} else {
2811
	/* do a HUP kill to force sync changes */
2812
		sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP");
2813
	}
2814

    
2815
}
2816

    
2817
function upnp_action ($action) {
2818
	global $g, $config;
2819
	switch ($action) {
2820
		case "start":
2821
			if (file_exists('/var/etc/miniupnpd.conf')) {
2822
				@unlink("{$g['varrun_path']}/miniupnpd.pid");
2823
				mwexec_bg("/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf -P {$g['varrun_path']}/miniupnpd.pid");
2824
			}
2825
			break;
2826
		case "stop":
2827
			killbypid("{$g['varrun_path']}/miniupnpd.pid");
2828
			while ((int)exec("/bin/pgrep -a miniupnpd | wc -l") > 0) {
2829
				mwexec('/usr/bin/killall miniupnpd 2>/dev/null', true);
2830
			}
2831
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
2832
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
2833
			break;
2834
		case "restart":
2835
			upnp_action('stop');
2836
			upnp_action('start');
2837
			break;
2838
	}
2839
}
2840

    
2841
function upnp_start() {
2842
	global $config;
2843

    
2844
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
2845
		return;
2846
	}
2847

    
2848
	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
2849
		echo gettext("Starting UPnP service... ");
2850
		require_once('/usr/local/pkg/miniupnpd.inc');
2851
		sync_package_miniupnpd();
2852
		echo "done.\n";
2853
	}
2854
}
2855

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

    
2859
	$is_installed = false;
2860
	$cron_changed = true;
2861
	$change_message = "";
2862

    
2863
	if (!is_array($config['cron'])) {
2864
		$config['cron'] = array();
2865
	}
2866
	if (!is_array($config['cron']['item'])) {
2867
		$config['cron']['item'] = array();
2868
	}
2869

    
2870
	$x = 0;
2871
	foreach ($config['cron']['item'] as $item) {
2872
		if (strstr($item['command'], $command)) {
2873
			$is_installed = true;
2874
			break;
2875
		}
2876
		$x++;
2877
	}
2878

    
2879
	if ($active) {
2880
		$cron_item = array();
2881
		$cron_item['minute'] = $minute;
2882
		$cron_item['hour'] = $hour;
2883
		$cron_item['mday'] = $monthday;
2884
		$cron_item['month'] = $month;
2885
		$cron_item['wday'] = $weekday;
2886
		$cron_item['who'] = $who;
2887
		$cron_item['command'] = $command;
2888
		if (!$is_installed) {
2889
			$config['cron']['item'][] = $cron_item;
2890
			$change_message = "Installed cron job for %s";
2891
		} else {
2892
			if ($config['cron']['item'][$x] == $cron_item) {
2893
				$cron_changed = false;
2894
			} else {
2895
				$config['cron']['item'][$x] = $cron_item;
2896
				$change_message = "Updated cron job for %s";
2897
			}
2898
		}
2899
	} else {
2900
		if ($is_installed == true) {
2901
			array_splice($config['cron']['item'], $x, 1);
2902
			$change_message = "Removed cron job for %s";
2903
		} else {
2904
			$cron_changed = false;
2905
		}
2906
	}
2907

    
2908
	if ($cron_changed) {
2909
		/* Optionally write the configuration if this function made changes.
2910
		 * Performing a write_config() in this way can have unintended side effects. See #7146
2911
		 * Base system instances of this function do not need to write, packages may.
2912
		 */
2913
		if ($write_config) {
2914
			write_config(sprintf(gettext($change_message), $command));
2915
		}
2916
		configure_cron();
2917
	}
2918
}
2919

    
2920
?>
(46-46/60)