Project

General

Profile

Download (88.3 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * services.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2004-2018 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 citynetwork cloudflare cloudflare-v6 cloudns custom custom-v6 dnsexit dnsimple dnsmadeeasy dnsomatic dreamhost dreamhost-v6 duiadns duiadns-v6 dyndns dyndns-custom dyndns-static dyns easydns eurodns freedns freedns-v6 glesys godaddy godaddy-v6 googledomains gratisdns he-net he-net-v6 he-net-tunnelbroker hover 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,City Network,CloudFlare,CloudFlare (v6),ClouDNS,Custom,Custom (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,GoDaddy,GoDaddy (v6),Google Domains,GratisDNS,HE.net,HE.net (v6),HE.net Tunnelbroker,Hover,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
		$radvdconf .= "\t\tRemoveRoute on;\n";
236
		$radvdconf .= "\t};\n";
237

    
238
		/* add DNS servers */
239
		$dnslist = array();
240
		if (isset($dhcpv6ifconf['rasamednsasdhcp6']) && is_array($dhcpv6ifconf['dnsserver']) && !empty($dhcpv6ifconf['dnsserver'])) {
241
			foreach ($dhcpv6ifconf['dnsserver'] as $server) {
242
				if (is_ipaddrv6($server)) {
243
					$dnslist[] = $server;
244
				}
245
			}
246
		} elseif (!isset($dhcpv6ifconf['rasamednsasdhcp6']) && isset($dhcpv6ifconf['radnsserver']) && is_array($dhcpv6ifconf['radnsserver'])) {
247
			foreach ($dhcpv6ifconf['radnsserver'] as $server) {
248
				if (is_ipaddrv6($server)) {
249
					$dnslist[] = $server;
250
				}
251
			}
252
		} elseif (isset($config['dnsmasq']['enable']) || isset($config['unbound']['enable'])) {
253
			$dnslist[] = get_interface_ipv6($realif);
254
		} elseif (is_array($config['system']['dnsserver']) && !empty($config['system']['dnsserver'])) {
255
			foreach ($config['system']['dnsserver'] as $server) {
256
				if (is_ipaddrv6($server)) {
257
					$dnslist[] = $server;
258
				}
259
			}
260
		}
261
		if (count($dnslist) > 0) {
262
			$dnsstring = implode(" ", $dnslist);
263
			if ($dnsstring <> "") {
264
				$radvdconf .= "\tRDNSS {$dnsstring} { };\n";
265
			}
266
		}
267

    
268
		$searchlist = array();
269
		$domainsearchlist = explode(';', $dhcpv6ifconf['radomainsearchlist']);
270
		foreach ($domainsearchlist as $sd) {
271
			$sd = trim($sd);
272
			if (is_hostname($sd)) {
273
				$searchlist[] = $sd;
274
			}
275
		}
276
		if (count($searchlist) > 0) {
277
			$searchliststring = trim(implode(" ", $searchlist));
278
		}
279
		if (!empty($dhcpv6ifconf['domain'])) {
280
			$radvdconf .= "\tDNSSL {$dhcpv6ifconf['domain']} {$searchliststring} { };\n";
281
		} elseif (!empty($config['system']['domain'])) {
282
			$radvdconf .= "\tDNSSL {$config['system']['domain']} {$searchliststring} { };\n";
283
		}
284
		$radvdconf .= "};\n";
285
	}
286

    
287
	/* handle DHCP-PD prefixes and 6RD dynamic interfaces */
288
	foreach ($Iflist as $if => $ifdescr) {
289
		if (!isset($config['interfaces'][$if]['track6-interface']) ||
290
		    !isset($config['interfaces'][$if]['ipaddrv6']) ||
291
		    $config['interfaces'][$if]['ipaddrv6'] != 'track6') {
292
			continue;
293
		}
294
		if (!isset($config['interfaces'][$if]['enable'])) {
295
			continue;
296
		}
297
		if ($config['dhcpdv6'][$if]['ramode'] == "disabled") {
298
			continue;
299
		}
300
		/* Do not put in the config an interface which is down */
301
		if (isset($blacklist[$if])) {
302
			continue;
303
		}
304
		$trackif = $config['interfaces'][$if]['track6-interface'];
305
		if (empty($config['interfaces'][$trackif])) {
306
			continue;
307
		}
308

    
309
		$realif = get_real_interface($if, "inet6");
310

    
311
		/* prevent duplicate entries, manual overrides */
312
		if (isset($radvdifs[$realif])) {
313
			continue;
314
		}
315

    
316
		$ifcfgipv6 = get_interface_ipv6($if);
317
		if (!is_ipaddrv6($ifcfgipv6)) {
318
			$subnetv6 = "::";
319
			$ifcfgsnv6 = "64";
320
		} else {
321
			$ifcfgsnv6 = get_interface_subnetv6($if);
322
			$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
323
		}
324
		$radvdifs[$realif] = $realif;
325

    
326
		$autotype = $config['interfaces'][$trackif]['ipaddrv6'];
327

    
328
		if ($g['debug']) {
329
			log_error("configuring RA on {$if} for type {$autotype} radvd subnet {$subnetv6}/{$ifcfgsnv6}");
330
		}
331

    
332
		$radvdconf .= "# Generated config for {$autotype} delegation from {$trackif} on {$if}\n";
333
		$radvdconf .= "interface {$realif} {\n";
334
		$radvdconf .= "\tAdvSendAdvert on;\n";
335
		if (is_numericint($dhcpv6ifconf['raminrtradvinterval'])) {
336
			$radvdconf .= "\tMinRtrAdvInterval {$dhcpv6ifconf['raminrtradvinterval']};\n";
337
		} else {
338
			$radvdconf .= "\tMinRtrAdvInterval 5;\n";
339
                }
340
		if (is_numericint($dhcpv6ifconf['ramaxrtradvinterval'])) {
341
			$radvdconf .= "\tMaxRtrAdvInterval {$dhcpv6ifconf['ramaxrtradvinterval']};\n";
342
		} else {
343
			$radvdconf .= "\tMaxRtrAdvInterval 10;\n";
344
		}
345
		$mtu = get_interface_mtu($realif);
346
		if (is_numeric($mtu)) {
347
			$radvdconf .= "\tAdvLinkMTU {$mtu};\n";
348
		} else {
349
			$radvdconf .= "\tAdvLinkMTU 1280;\n";
350
		}
351
		$radvdconf .= "\tAdvOtherConfigFlag on;\n";
352
		$radvdconf .= "\tprefix {$subnetv6}/{$ifcfgsnv6} {\n";
353
		$radvdconf .= "\t\tAdvOnLink on;\n";
354
		$radvdconf .= "\t\tAdvAutonomous on;\n";
355
		$radvdconf .= "\t\tAdvRouterAddr on;\n";
356
		$radvdconf .= "\t};\n";
357

    
358
		/* add DNS servers */
359
		$dnslist = array();
360
		if (isset($config['dnsmasq']['enable']) || isset($config['unbound']['enable'])) {
361
			$dnslist[] = $ifcfgipv6;
362
		} elseif (is_array($config['system']['dnsserver']) && !empty($config['system']['dnsserver'])) {
363
			foreach ($config['system']['dnsserver'] as $server) {
364
				if (is_ipaddrv6($server)) {
365
					$dnslist[] = $server;
366
				}
367
			}
368
		}
369
		if (count($dnslist) > 0) {
370
			$dnsstring = implode(" ", $dnslist);
371
			if (!empty($dnsstring)) {
372
				$radvdconf .= "\tRDNSS {$dnsstring} { };\n";
373
			}
374
		}
375
		if (!empty($config['system']['domain'])) {
376
			$radvdconf .= "\tDNSSL {$config['system']['domain']} { };\n";
377
		}
378
		$radvdconf .= "};\n";
379
	}
380

    
381
	/* write radvd.conf */
382
	if (!@file_put_contents("{$g['varetc_path']}/radvd.conf", $radvdconf)) {
383
		log_error(gettext("Error: cannot open radvd.conf in services_radvd_configure()."));
384
		if (platform_booting()) {
385
			printf("Error: cannot open radvd.conf in services_radvd_configure().\n");
386
		}
387
	}
388
	unset($radvdconf);
389

    
390
	if (count($radvdifs) > 0) {
391
		if (isvalidpid("{$g['varrun_path']}/radvd.pid")) {
392
			sigkillbypid("{$g['varrun_path']}/radvd.pid", "HUP");
393
		} else {
394
			mwexec("/usr/local/sbin/radvd -p {$g['varrun_path']}/radvd.pid -C {$g['varetc_path']}/radvd.conf -m syslog");
395
		}
396
	} else {
397
		/* we need to shut down the radvd cleanly, it will send out the prefix
398
		 * information with a lifetime of 0 to notify clients of a (possible) new prefix */
399
		if (isvalidpid("{$g['varrun_path']}/radvd.pid")) {
400
			log_error(gettext("Shutting down Router Advertisment daemon cleanly"));
401
			killbypid("{$g['varrun_path']}/radvd.pid");
402
			@unlink("{$g['varrun_path']}/radvd.pid");
403
		}
404
	}
405
	return 0;
406
}
407

    
408
function services_dhcpd_configure($family = "all", $blacklist = array()) {
409
	global $config, $g;
410

    
411
	$dhcpdconfigurelck = lock("dhcpdconfigure", LOCK_EX);
412

    
413
	/* configure DHCPD chroot once */
414
	$fd = fopen("{$g['tmp_path']}/dhcpd.sh", "w");
415
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}\n");
416
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/dev\n");
417
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/etc\n");
418
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/usr/local/sbin\n");
419
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db\n");
420
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run\n");
421
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/usr\n");
422
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/lib\n");
423
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/run\n");
424
	fwrite($fd, "/usr/sbin/chown -R dhcpd:_dhcp {$g['dhcpd_chroot_path']}/*\n");
425
	fwrite($fd, "/bin/cp -n /lib/libc.so.* {$g['dhcpd_chroot_path']}/lib/\n");
426
	fwrite($fd, "/bin/cp -n /usr/local/sbin/dhcpd {$g['dhcpd_chroot_path']}/usr/local/sbin/\n");
427
	fwrite($fd, "/bin/chmod a+rx {$g['dhcpd_chroot_path']}/usr/local/sbin/dhcpd\n");
428

    
429
	$status = `/sbin/mount | /usr/bin/grep -v grep | /usr/bin/grep "{$g['dhcpd_chroot_path']}/dev"`;
430
	if (!trim($status)) {
431
		fwrite($fd, "/sbin/mount -t devfs devfs {$g['dhcpd_chroot_path']}/dev\n");
432
	}
433
	fclose($fd);
434
	mwexec("/bin/sh {$g['tmp_path']}/dhcpd.sh");
435

    
436
	if ($family == "all" || $family == "inet") {
437
		services_dhcpdv4_configure();
438
	}
439
	if ($family == "all" || $family == "inet6") {
440
		services_dhcpdv6_configure($blacklist);
441
		services_radvd_configure($blacklist);
442
	}
443

    
444
	unlock($dhcpdconfigurelck);
445
}
446

    
447
function services_dhcpdv4_configure() {
448
	global $config, $g;
449
	$need_ddns_updates = false;
450
	$ddns_zones = array();
451

    
452
	if ($g['services_dhcp_server_enable'] == false) {
453
		return;
454
	}
455

    
456
	if (isset($config['system']['developerspew'])) {
457
		$mt = microtime();
458
		echo "services_dhcpdv4_configure($if) being called $mt\n";
459
	}
460

    
461
	/* kill any running dhcpd */
462
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid")) {
463
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid");
464
	}
465

    
466
	/* DHCP enabled on any interfaces? */
467
	if (!is_dhcp_server_enabled()) {
468
		return 0;
469
	}
470

    
471
	/* if OLSRD is enabled, allow WAN to house DHCP. */
472
	if (!function_exists('is_package_installed')) {
473
		require_once('pkg-utils.inc');
474
	}
475
	if (is_package_installed('olsrd') && isset($config['installedpackages']['olsrd'])) {
476
		foreach ($config['installedpackages']['olsrd']['config'] as $olsrd) {
477
			if (isset($olsrd['enable']) && $olsrd['enable'] == "on") {
478
				$is_olsr_enabled = true;
479
				break;
480
			}
481
		}
482
	}
483

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

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

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

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

    
535
	$dhcpdconf = <<<EOD
536

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

    
550
EOD;
551

    
552
	if (!isset($dhcpifconf['disableauthoritative'])) {
553
		$dhcpdconf .= "authoritative;\n";
554
	}
555

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

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

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

    
577
		if (!isset($config['interfaces'][$dhcpif]['enable'])) {
578
			continue;
579
		}
580

    
581
		interfaces_staticarp_configure($dhcpif);
582

    
583
		if (!isset($dhcpifconf['enable'])) {
584
			continue;
585
		}
586

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

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

    
647
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
648

    
649
		$newzone = array();
650
		$ifcfg = $config['interfaces'][$dhcpif];
651

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

    
660
		if (!is_ipaddr($subnet)) {
661
			continue;
662
		}
663

    
664
		if ($is_olsr_enabled == true) {
665
			if ($dhcpifconf['netmask']) {
666
				$subnetmask = gen_subnet_mask($dhcpifconf['netmask']);
667
			}
668
		}
669

    
670
		$all_pools = array();
671
		$all_pools[] = $dhcpifconf;
672
		if (is_array($dhcpifconf['pool'])) {
673
			$all_pools = array_merge($all_pools, $dhcpifconf['pool']);
674
		}
675

    
676
		$dnscfg = "";
677

    
678
		if ($dhcpifconf['domain']) {
679
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
680
		}
681

    
682
		if ($dhcpifconf['domainsearchlist'] <> "") {
683
			$dnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpifconf['domainsearchlist'])) . "\";\n";
684
		}
685

    
686
		if (isset($dhcpifconf['ddnsupdate'])) {
687
			$need_ddns_updates = true;
688
			$newzone = array();
689
			if ($dhcpifconf['ddnsdomain'] <> "") {
690
				$newzone['domain-name'] = $dhcpifconf['ddnsdomain'];
691
				$dnscfg .= "	ddns-domainname \"{$dhcpifconf['ddnsdomain']}\";\n";
692
			} else {
693
				$newzone['domain-name'] = $config['system']['domain'];
694
			}
695

    
696
			if (empty($dhcpifconf['ddnsclientupdates'])) {
697
				$ddnsclientupdates = 'allow';
698
			} else {
699
				$ddnsclientupdates = $dhcpifconf['ddnsclientupdates'];
700
			}
701

    
702
			$dnscfg .= "	{$ddnsclientupdates} client-updates;\n";
703

    
704
			$revsubnet = array_reverse(explode('.',$subnet));
705

    
706
			/* Take care of full classes first */
707
			switch ($ifcfgsn) {
708
				case 8:
709
					$start_octet = 3;
710
					break;
711
				case 16:
712
					$start_octet = 2;
713
					break;
714
				case 24:
715
					$start_octet = 1;
716
					break;
717
				default:
718
					$start_octet = 0;
719
					/* Add subnet bitmask to first octet */
720
					$revsubnet[0] .= '-' . $ifcfgsn;
721
					break;
722

    
723
			}
724

    
725
			$ptr_domain = '';
726
			for ($octet = 0; $octet <= 3; $octet++) {
727
				if ($octet < $start_octet) {
728
					continue;
729
				}
730
				$ptr_domain .= ((empty($ptr_domain) && $ptr_domain !== "0") ? '' : '.');
731
				$ptr_domain .= $revsubnet[$octet];
732
			}
733
			$ptr_domain .= ".in-addr.arpa";
734
			$newzone['ptr-domain'] = $ptr_domain;
735
			unset($ptr_domain, $revsubnet, $start_octet);
736
		}
737

    
738
		if (is_array($dhcpifconf['dnsserver']) && ($dhcpifconf['dnsserver'][0])) {
739
			$dnscfg .= "	option domain-name-servers " . join(",", $dhcpifconf['dnsserver']) . ";";
740
			if ($newzone['domain-name']) {
741
				$newzone['dns-servers'] = $dhcpifconf['dnsserver'];
742
			}
743
		} else if (isset($config['dnsmasq']['enable'])) {
744
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
745
			if ($newzone['domain-name'] && is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
746
				$newzone['dns-servers'] = $syscfg['dnsserver'];
747
			}
748
		} else if (isset($config['unbound']['enable'])) {
749
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
750
		} else if (!empty($dns_arrv4)) {
751
			$dnscfg .= "	option domain-name-servers " . join(",", $dns_arrv4) . ";";
752
			if ($newzone['domain-name']) {
753
				$newzone['dns-servers'] = $dns_arrv4;
754
			}
755
		}
756

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

    
781
		$dhcpdconf .= "subnet {$subnet} netmask {$subnetmask} {\n";
782

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

    
828
			/* allow/deny MACs */
829
			$mac_allow_list = array_unique(explode(',', $poolconf['mac_allow']));
830
			foreach ($mac_allow_list as $mac) {
831
				if (empty($mac)) {
832
					continue;
833
				}
834
				$dhcpdconf .= "		allow members of \"" . str_replace(':', '', $mac) . "\";\n";
835
			}
836
			$deny_action = "deny";
837
			if (isset($poolconf['nonak']) && empty($poolconf['failover_peerip'])) {
838
				$deny_action = "ignore";
839
			}
840
			$mac_deny_list = array_unique(explode(',', $poolconf['mac_deny']));
841
			foreach ($mac_deny_list as $mac) {
842
				if (empty($mac)) {
843
					continue;
844
				}
845
				$dhcpdconf .= "		$deny_action members of \"" . str_replace(':', '', $mac) . "\";\n";
846
			}
847

    
848
			if ($poolconf['failover_peerip'] <> "") {
849
				$dhcpdconf .= "		$deny_action dynamic bootp clients;\n";
850
			}
851

    
852
			if (isset($poolconf['denyunknown'])) {
853
				$dhcpdconf .= "		$deny_action unknown-clients;\n";
854
			}
855

    
856
			if ($poolconf['gateway'] && $poolconf['gateway'] != "none" && ($poolconf['gateway'] != $dhcpifconf['gateway'])) {
857
				$dhcpdconf .= "		option routers {$poolconf['gateway']};\n";
858
			}
859

    
860
			if ($dhcpifconf['failover_peerip'] <> "") {
861
				$dhcpdconf .= "		failover peer \"dhcp_{$dhcpif}\";\n";
862
			}
863

    
864
			$pdnscfg = "";
865

    
866
			if ($poolconf['domain'] && ($poolconf['domain'] != $dhcpifconf['domain'])) {
867
				$pdnscfg .= "		option domain-name \"{$poolconf['domain']}\";\n";
868
			}
869

    
870
			if (!empty($poolconf['domainsearchlist']) && ($poolconf['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
871
				$pdnscfg .= "		option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $poolconf['domainsearchlist'])) . "\";\n";
872
			}
873

    
874
			if (isset($poolconf['ddnsupdate'])) {
875
				if (($poolconf['ddnsdomain'] <> "") && ($poolconf['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
876
					$pdnscfg .= "		ddns-domainname \"{$poolconf['ddnsdomain']}\";\n";
877
				}
878
				$pdnscfg .= "		ddns-update-style interim;\n";
879
			}
880

    
881
			$dhcpdconf .= "{$pdnscfg}";
882

    
883
			// default-lease-time
884
			if ($poolconf['defaultleasetime'] && ($poolconf['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
885
				$dhcpdconf .= "		default-lease-time {$poolconf['defaultleasetime']};\n";
886
			}
887

    
888
			// max-lease-time
889
			if ($poolconf['maxleasetime'] && ($poolconf['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
890
				$dhcpdconf .= "		max-lease-time {$poolconf['maxleasetime']};\n";
891
			}
892

    
893
			// ignore bootp
894
			if (isset($poolconf['ignorebootp'])) {
895
				$dhcpdconf .= "		ignore bootp;\n";
896
			}
897

    
898
			// ignore-client-uids
899
			if (isset($poolconf['ignoreclientuids'])) {
900
				$dhcpdconf .= "		ignore-client-uids true;\n";
901
			}
902

    
903
			// netbios-name*
904
			if (is_array($poolconf['winsserver']) && $poolconf['winsserver'][0] && ($poolconf['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
905
				$dhcpdconf .= "		option netbios-name-servers " . join(",", $poolconf['winsserver']) . ";\n";
906
				$dhcpdconf .= "		option netbios-node-type 8;\n";
907
			}
908

    
909
			// ntp-servers
910
			if (is_array($poolconf['ntpserver']) && $poolconf['ntpserver'][0] && ($poolconf['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
911
				$dhcpdconf .= "		option ntp-servers " . join(",", $poolconf['ntpserver']) . ";\n";
912
			}
913

    
914
			// tftp-server-name
915
			if (!empty($poolconf['tftp']) && ($poolconf['tftp'] != $dhcpifconf['tftp'])) {
916
				$dhcpdconf .= "		option tftp-server-name \"{$poolconf['tftp']}\";\n";
917
			}
918

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

    
936
			// ldap-server
937
			if (!empty($poolconf['ldap']) && ($poolconf['ldap'] != $dhcpifconf['ldap'])) {
938
				$dhcpdconf .= "		option ldap-server \"{$poolconf['ldap']}\";\n";
939
			}
940

    
941
			// net boot information
942
			if (isset($poolconf['netboot'])) {
943
				if (!empty($poolconf['nextserver']) && ($poolconf['nextserver'] != $dhcpifconf['nextserver'])) {
944
					$dhcpdconf .= "		next-server {$poolconf['nextserver']};\n";
945
				}
946

    
947
				if (!empty($poolconf['filename']) &&
948
				    (!isset($dhcpifconf['filename']) ||
949
				    ($poolconf['filename'] != $dhcpifconf['filename']))) {
950
					$filename = $poolconf['filename'];
951
				}
952
				if (!empty($poolconf['filename32']) &&
953
				    (!isset($dhcpifconf['filename32']) ||
954
				    ($poolconf['filename32'] != $dhcpifconf['filename32']))) {
955
					$filename32 = $poolconf['filename32'];
956
				}
957
				if (!empty($poolconf['filename64']) &&
958
				    (!isset($dhcpifconf['filename64']) ||
959
				    ($poolconf['filename64'] != $dhcpifconf['filename64']))) {
960
					$filename64 = $poolconf['filename64'];
961
				}
962

    
963
				if (!empty($filename32) || !empty($filename64)) {
964
					if (empty($filename) && !empty($dhcpifconf['filename'])) {
965
						$filename = $dhcpifconf['filename'];
966
					}
967
					if (empty($filename32) && !empty($dhcpifconf['filename32'])) {
968
						$filename32 = $dhcpifconf['filename32'];
969
					}
970
					if (empty($filename64) && !empty($dhcpifconf['filename64'])) {
971
						$filename64 = $dhcpifconf['filename64'];
972
					}
973
				}
974

    
975
				if (!empty($filename) && !empty($filename32) && !empty($filename64)) {
976
					$dhcpdconf .= "		if option arch = 00:06 {\n";
977
					$dhcpdconf .= "			filename \"{$filename32}\";\n";
978
					$dhcpdconf .= "		} else if option arch = 00:07 {\n";
979
					$dhcpdconf .= "			filename \"{$filename64}\";\n";
980
					$dhcpdconf .= "		} else if option arch = 00:09 {\n";
981
					$dhcpdconf .= "			filename \"{$filename64}\";\n";
982
					$dhcpdconf .= "		} else {\n";
983
					$dhcpdconf .= "			filename \"{$filename}\";\n";
984
					$dhcpdconf .= "		}\n\n";
985
				} elseif (!empty($filename)) {
986
					$dhcpdconf .= "		filename \"{$filename}\";\n";
987
				}
988
				unset($filename, $filename32, $filename64);
989

    
990
				if (!empty($poolconf['rootpath']) && ($poolconf['rootpath'] != $dhcpifconf['rootpath'])) {
991
					$dhcpdconf .= "		option root-path \"{$poolconf['rootpath']}\";\n";
992
				}
993
			}
994
			$dhcpdconf .= "		range {$poolconf['range']['from']} {$poolconf['range']['to']};\n";
995
			$dhcpdconf .= "	}\n\n";
996
		}
997
// End of settings inside pools
998

    
999
		if ($dhcpifconf['gateway'] && $dhcpifconf['gateway'] != "none") {
1000
			$routers = $dhcpifconf['gateway'];
1001
			$add_routers = true;
1002
		} elseif ($dhcpifconf['gateway'] == "none") {
1003
			$add_routers = false;
1004
		} else {
1005
			$add_routers = $enable_add_routers;
1006
			$routers = $ifcfgip;
1007
		}
1008
		if ($add_routers) {
1009
			$dhcpdconf .= "	option routers {$routers};\n";
1010
		}
1011

    
1012
		$dhcpdconf .= <<<EOD
1013
$dnscfg
1014

    
1015
EOD;
1016
		// default-lease-time
1017
		if ($dhcpifconf['defaultleasetime']) {
1018
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
1019
		}
1020

    
1021
		// max-lease-time
1022
		if ($dhcpifconf['maxleasetime']) {
1023
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
1024
		}
1025

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

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

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

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

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

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

    
1083
		$dhcpdconf .= <<<EOD
1084
}
1085

    
1086
EOD;
1087

    
1088
		/* add static mappings */
1089
		if (is_array($dhcpifconf['staticmap'])) {
1090

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

    
1095
				if ($sm['mac']) {
1096
					$dhcpdconf .= "        hardware ethernet {$sm['mac']};\n";
1097
				}
1098

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

    
1103
				if ($sm['ipaddr']) {
1104
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
1105
				}
1106

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

    
1119
				if ($sm['rootpath']) {
1120
					$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1121
				}
1122

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

    
1127
				$smdnscfg = "";
1128

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

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

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

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

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

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

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

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

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

    
1175
				$dhcpdconf .= "}\n";
1176
				$i++;
1177
			}
1178
		}
1179

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

    
1193
	if ($need_ddns_updates) {
1194
		$dhcpdconf .= "ddns-update-style interim;\n";
1195
		$dhcpdconf .= "update-static-leases on;\n";
1196

    
1197
		$dhcpdconf .= dhcpdzones($ddns_zones);
1198
	}
1199

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

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

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

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

    
1223
	if (platform_booting()) {
1224
		print "done.\n";
1225
	}
1226

    
1227
	return 0;
1228
}
1229

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

    
1240
	return $dhcpdconf;
1241
}
1242

    
1243
function dhcpdzones($ddns_zones) {
1244
	$dhcpdconf = "";
1245

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

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

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

    
1293
	return $dhcpdconf;
1294
}
1295

    
1296
function services_dhcpdv6_configure($blacklist = array()) {
1297
	global $config, $g;
1298

    
1299
	if ($g['services_dhcp_server_enable'] == false) {
1300
		return;
1301
	}
1302

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

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

    
1316
	/* DHCP enabled on any interfaces? */
1317
	if (!is_dhcpv6_server_enabled()) {
1318
		return 0;
1319
	}
1320

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

    
1329

    
1330
	if (platform_booting()) {
1331
		echo "Starting DHCPv6 service...";
1332
	} else {
1333
		sleep(1);
1334
	}
1335

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

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

    
1349
	$dhcpdv6conf = <<<EOD
1350

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

    
1363
EOD;
1364

    
1365
	if (!isset($dhcpv6ifconf['disableauthoritative'])) {
1366
		$dhcpdv6conf .= "authoritative;\n";
1367
	}
1368

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

    
1373
	$dhcpdv6ifs = array();
1374

    
1375
	$dhcpv6num = 0;
1376
	$nsupdate = false;
1377

    
1378
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1379

    
1380
		$ddns_zones = array();
1381

    
1382
		$ifcfgv6 = $config['interfaces'][$dhcpv6if];
1383

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

    
1399
		if ($is_olsr_enabled == true) {
1400
			if ($dhcpv6ifconf['netmask']) {
1401
				$subnetmask = gen_subnet_maskv6($dhcpv6ifconf['netmask']);
1402
			}
1403
		}
1404

    
1405
		$dnscfgv6 = "";
1406

    
1407
		if ($dhcpv6ifconf['domain']) {
1408
			$dnscfgv6 .= "	option domain-name \"{$dhcpv6ifconf['domain']}\";\n";
1409
		}
1410

    
1411
		if ($dhcpv6ifconf['domainsearchlist'] <> "") {
1412
			$dnscfgv6 .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpv6ifconf['domainsearchlist'])) . "\";\n";
1413
		}
1414

    
1415
		if (isset($dhcpv6ifconf['ddnsupdate'])) {
1416
			if ($dhcpv6ifconf['ddnsdomain'] <> "") {
1417
				$dnscfgv6 .= "	ddns-domainname \"{$dhcpv6ifconf['ddnsdomain']}\";\n";
1418
			}
1419
			if (empty($dhcpv6ifconf['ddnsclientupdates'])) {
1420
				$ddnsclientupdates = 'allow';
1421
			} else {
1422
				$ddnsclientupdates = $dhcpv6ifconf['ddnsclientupdates'];
1423
			}
1424
			$dnscfgv6 .= "	{$ddnsclientupdates} client-updates;\n";
1425
			$nsupdate = true;
1426
		} else {
1427
			$dnscfgv6 .= "	do-forward-updates false;\n";
1428
		}
1429

    
1430
		if (is_array($dhcpv6ifconf['dnsserver']) && ($dhcpv6ifconf['dnsserver'][0])) {
1431
			$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dhcpv6ifconf['dnsserver']) . ";";
1432
		} else if (((isset($config['dnsmasq']['enable'])) || isset($config['unbound']['enable'])) && (is_ipaddrv6($ifcfgipv6))) {
1433
			$dnscfgv6 .= "	option dhcp6.name-servers {$ifcfgipv6};";
1434
		} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1435
			$dns_arrv6 = array();
1436
			foreach ($syscfg['dnsserver'] as $dnsserver) {
1437
				if (is_ipaddrv6($dnsserver)) {
1438
					$dns_arrv6[] = $dnsserver;
1439
				}
1440
			}
1441
			if (!empty($dns_arrv6)) {
1442
				$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dns_arrv6) . ";";
1443
			}
1444
		}
1445

    
1446
		if (!is_ipaddrv6($ifcfgipv6)) {
1447
			$ifcfgsnv6 = "64";
1448
			$subnetv6 = gen_subnetv6($dhcpv6ifconf['range']['from'], $ifcfgsnv6);
1449
		}
1450

    
1451
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1452

    
1453
		if (isset($dhcpv6ifconf['ddnsupdate']) &&
1454
		    !empty($dhcpv6ifconf['ddnsdomain'])) {
1455
			$newzone = array();
1456
			$newzone['domain-name'] = $dhcpv6ifconf['ddnsdomain'];
1457
			$newzone['dns-servers'][] = $dhcpv6ifconf['ddnsdomainprimary'];
1458
			$newzone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1459
			$newzone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1460
			$ddns_zones[] = $newzone;
1461
			if (isset($dhcpv6ifconf['ddnsreverse'])) {
1462
				$ptr_zones = get_v6_ptr_zones($subnetv6, $ifcfgsnv6);
1463
				foreach ($ptr_zones as $ptr_zone) {
1464
					$reversezone = array();
1465
					$reversezone['ptr-domain'] = $ptr_zone;
1466
					$reversezone['dns-servers'][] = $dhcpv6ifconf['ddnsdomainprimary'];
1467
					$reversezone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1468
					$reversezone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1469
					$ddns_zones[] = $reversezone;
1470
				}
1471
			}
1472
		}
1473

    
1474
		$dhcpdv6conf .= " {\n";
1475

    
1476
		$range_from = $dhcpv6ifconf['range']['from'];
1477
		$range_to = $dhcpv6ifconf['range']['to'];
1478
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
1479
			$range_from = merge_ipv6_delegated_prefix($ifcfgipv6, $range_from, $pdlen);
1480
			$range_to = merge_ipv6_delegated_prefix($ifcfgipv6, $range_to, $pdlen);
1481
		}
1482

    
1483
		$dhcpdv6conf .= <<<EOD
1484
	range6 {$range_from} {$range_to};
1485
$dnscfgv6
1486

    
1487
EOD;
1488

    
1489
		if (is_ipaddrv6($dhcpv6ifconf['prefixrange']['from']) && is_ipaddrv6($dhcpv6ifconf['prefixrange']['to'])) {
1490
			$dhcpdv6conf .= "	prefix6 {$dhcpv6ifconf['prefixrange']['from']} {$dhcpv6ifconf['prefixrange']['to']} /{$dhcpv6ifconf['prefixrange']['prefixlength']};\n";
1491
		}
1492
		if (is_ipaddrv6($dhcpv6ifconf['dns6ip'])) {
1493
			$dns6ip = $dhcpv6ifconf['dns6ip'];
1494
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1495
			    Net_IPv6::isInNetmask($dns6ip, '::', $pdlen)) {
1496
				$dns6ip = merge_ipv6_delegated_prefix($ifcfgipv6, $dns6ip, $pdlen);
1497
			}
1498
			$dhcpdv6conf .= "	option dhcp6.name-servers {$dns6ip};\n";
1499
		}
1500
		// default-lease-time
1501
		if ($dhcpv6ifconf['defaultleasetime']) {
1502
			$dhcpdv6conf .= "	default-lease-time {$dhcpv6ifconf['defaultleasetime']};\n";
1503
		}
1504

    
1505
		// max-lease-time
1506
		if ($dhcpv6ifconf['maxleasetime']) {
1507
			$dhcpdv6conf .= "	max-lease-time {$dhcpv6ifconf['maxleasetime']};\n";
1508
		}
1509

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

    
1534
		// Handle option, number rowhelper values
1535
		$dhcpdv6conf .= "\n";
1536
		if ($dhcpv6ifconf['numberoptions']['item']) {
1537
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1538
				$itemv6_value = base64_decode($itemv6['value']);
1539
				$dhcpdv6conf .= "	option custom-{$dhcpv6if}-{$itemv6idx} \"{$itemv6_value}\";\n";
1540
			}
1541
		}
1542

    
1543
		// ldap-server
1544
		if ($dhcpv6ifconf['ldap'] <> "") {
1545
			$ldapserver = $dhcpv6ifconf['ldap'];
1546
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1547
			    Net_IPv6::isInNetmask($ldapserver, '::', $pdlen)) {
1548
				$ldapserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ldapserver, $pdlen);
1549
			}
1550
			$dhcpdv6conf .= "	option ldap-server \"{$ldapserver}\";\n";
1551
		}
1552

    
1553
		// net boot information
1554
		if (isset($dhcpv6ifconf['netboot'])) {
1555
			if (!empty($dhcpv6ifconf['bootfile_url'])) {
1556
				$dhcpdv6conf .= "	option dhcp6.bootfile-url \"{$dhcpv6ifconf['bootfile_url']}\";\n";
1557
			}
1558
		}
1559

    
1560
		$dhcpdv6conf .= "}\n";
1561

    
1562
		/* add static mappings */
1563
		/* Needs to use DUID */
1564
		if (is_array($dhcpv6ifconf['staticmap'])) {
1565
			$i = 0;
1566
			foreach ($dhcpv6ifconf['staticmap'] as $sm) {
1567
				$dhcpdv6conf .= <<<EOD
1568
host s_{$dhcpv6if}_{$i} {
1569
	host-identifier option dhcp6.client-id {$sm['duid']};
1570

    
1571
EOD;
1572
				if ($sm['ipaddrv6']) {
1573
					$ipaddrv6 = $sm['ipaddrv6'];
1574
					if ($ifcfgv6['ipaddrv6'] == 'track6') {
1575
						$ipaddrv6 = merge_ipv6_delegated_prefix($ifcfgipv6, $ipaddrv6, $pdlen);
1576
					}
1577
					$dhcpdv6conf .= "	fixed-address6 {$ipaddrv6};\n";
1578
				}
1579

    
1580
				if ($sm['hostname']) {
1581
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1582
					$dhhostname = str_replace(".", "_", $dhhostname);
1583
					$dhcpdv6conf .= "	option host-name {$dhhostname};\n";
1584
					if (isset($dhcpv6ifconf['ddnsupdate']) &&
1585
					    isset($dhcpv6ifconf['ddnsforcehostname'])) {
1586
						$dhcpdv6conf .= "	ddns-hostname \"{$dhhostname}\";\n";
1587
					}
1588
				}
1589
				if ($sm['filename']) {
1590
					$dhcpdv6conf .= "	filename \"{$sm['filename']}\";\n";
1591
				}
1592

    
1593
				if ($sm['rootpath']) {
1594
					$dhcpdv6conf .= "	option root-path \"{$sm['rootpath']}\";\n";
1595
				}
1596

    
1597
				$dhcpdv6conf .= "}\n";
1598
				$i++;
1599
			}
1600
		}
1601

    
1602
		if ($dhcpv6ifconf['ddnsdomain']) {
1603
			$dhcpdv6conf .= dhcpdkey($dhcpv6ifconf);
1604
			$dhcpdv6conf .= dhcpdzones($ddns_zones);
1605
		}
1606

    
1607
		if ($config['dhcpdv6'][$dhcpv6if]['ramode'] <> "unmanaged" && isset($config['interfaces'][$dhcpv6if]['enable'])) {
1608
			if (preg_match("/poes/si", $dhcpv6if)) {
1609
				/* magic here */
1610
				$dhcpdv6ifs = array_merge($dhcpdv6ifs, get_pppoes_child_interfaces($dhcpv6if));
1611
			} else {
1612
				$realif = get_real_interface($dhcpv6if, "inet6");
1613
				if (stristr("$realif", "bridge")) {
1614
					$mac = get_interface_mac($realif);
1615
					$v6address = generate_ipv6_from_mac($mac);
1616
					/* Create link local address for bridges */
1617
					mwexec("/sbin/ifconfig {$realif} inet6 {$v6address}");
1618
				}
1619
				$realif = escapeshellcmd($realif);
1620
				$dhcpdv6ifs[] = $realif;
1621
			}
1622
		}
1623
	}
1624

    
1625
	if ($nsupdate) {
1626
		$dhcpdv6conf .= "ddns-update-style interim;\n";
1627
	} else {
1628
		$dhcpdv6conf .= "ddns-update-style none;\n";
1629
	}
1630

    
1631
	/* write dhcpdv6.conf */
1632
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf", $dhcpdv6conf)) {
1633
		log_error("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1634
		if (platform_booting()) {
1635
			printf("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1636
		}
1637
		unset($dhcpdv6conf);
1638
		return 1;
1639
	}
1640
	unset($dhcpdv6conf);
1641

    
1642
	/* create an empty leases v6 database */
1643
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases")) {
1644
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1645
	}
1646

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

    
1651
	/* fire up dhcpd in a chroot */
1652
	if (count($dhcpdv6ifs) > 0) {
1653
		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 " .
1654
			join(" ", $dhcpdv6ifs));
1655
		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");
1656
	}
1657
	if (platform_booting()) {
1658
		print gettext("done.") . "\n";
1659
	}
1660

    
1661
	return 0;
1662
}
1663

    
1664
function services_igmpproxy_configure() {
1665
	global $config, $g;
1666

    
1667
	/* kill any running igmpproxy */
1668
	killbyname("igmpproxy");
1669

    
1670
	if (!is_array($config['igmpproxy']['igmpentry']) || (count($config['igmpproxy']['igmpentry']) == 0)) {
1671
		return 1;
1672
	}
1673

    
1674
	$iflist = get_configured_interface_list();
1675

    
1676
	$igmpconf = <<<EOD
1677

    
1678
##------------------------------------------------------
1679
## Enable Quickleave mode (Sends Leave instantly)
1680
##------------------------------------------------------
1681
quickleave
1682

    
1683
EOD;
1684

    
1685
	foreach ($config['igmpproxy']['igmpentry'] as $igmpcf) {
1686
		unset($iflist[$igmpcf['ifname']]);
1687
		$realif = get_real_interface($igmpcf['ifname']);
1688
		if (empty($igmpcf['threshold'])) {
1689
			$threshld = 1;
1690
		} else {
1691
			$threshld = $igmpcf['threshold'];
1692
		}
1693
		$igmpconf .= "phyint {$realif} {$igmpcf['type']} ratelimit 0 threshold {$threshld}\n";
1694

    
1695
		if ($igmpcf['address'] <> "") {
1696
			$item = explode(" ", $igmpcf['address']);
1697
			foreach ($item as $iww) {
1698
				$igmpconf .= "altnet {$iww}\n";
1699
			}
1700
		}
1701
		$igmpconf .= "\n";
1702
	}
1703
	foreach ($iflist as $ifn) {
1704
		$realif = get_real_interface($ifn);
1705
		$igmpconf .= "phyint {$realif} disabled\n";
1706
	}
1707
	$igmpconf .= "\n";
1708

    
1709
	$igmpfl = fopen($g['varetc_path'] . "/igmpproxy.conf", "w");
1710
	if (!$igmpfl) {
1711
		log_error(gettext("Could not write Igmpproxy configuration file!"));
1712
		return;
1713
	}
1714
	fwrite($igmpfl, $igmpconf);
1715
	fclose($igmpfl);
1716
	unset($igmpconf);
1717

    
1718
	if (isset($config['syslog']['igmpxverbose'])) {
1719
		mwexec_bg("/usr/local/sbin/igmpproxy -v {$g['varetc_path']}/igmpproxy.conf");
1720
	} else {
1721
		mwexec_bg("/usr/local/sbin/igmpproxy {$g['varetc_path']}/igmpproxy.conf");
1722
	}
1723

    
1724
	log_error(gettext("Started IGMP proxy service."));
1725

    
1726
	return 0;
1727
}
1728

    
1729
function services_dhcrelay_configure() {
1730
	global $config, $g;
1731

    
1732
	if (isset($config['system']['developerspew'])) {
1733
		$mt = microtime();
1734
		echo "services_dhcrelay_configure() being called $mt\n";
1735
	}
1736

    
1737
	/* kill any running dhcrelay */
1738
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
1739

    
1740
	$dhcrelaycfg =& $config['dhcrelay'];
1741

    
1742
	/* DHCPRelay enabled on any interfaces? */
1743
	if (!isset($dhcrelaycfg['enable'])) {
1744
		return 0;
1745
	}
1746

    
1747
	if (platform_booting()) {
1748
		echo gettext("Starting DHCP relay service...");
1749
	} else {
1750
		sleep(1);
1751
	}
1752

    
1753
	$iflist = get_configured_interface_list();
1754

    
1755
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1756
	foreach ($dhcifaces as $dhcrelayif) {
1757
		if (!isset($iflist[$dhcrelayif]) ||
1758
		    link_interface_to_bridge($dhcrelayif)) {
1759
			continue;
1760
		}
1761

    
1762
		if (is_ipaddr(get_interface_ip($dhcrelayif))) {
1763
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1764
		}
1765
	}
1766

    
1767
	/*
1768
	 * In order for the relay to work, it needs to be active
1769
	 * on the interface in which the destination server sits.
1770
	 */
1771
	$srvips = explode(",", $dhcrelaycfg['server']);
1772
	if (!is_array($srvips)) {
1773
		log_error(gettext("No destination IP has been configured!"));
1774
		return;
1775
	}
1776

    
1777
	foreach ($srvips as $srcidx => $srvip) {
1778
		$destif = guess_interface_from_ip($srvip);
1779
		if (!empty($destif)) {
1780
			$dhcrelayifs[] = $destif;
1781
		}
1782
	}
1783
	$dhcrelayifs = array_unique($dhcrelayifs);
1784

    
1785
	/* fire up dhcrelay */
1786
	if (empty($dhcrelayifs)) {
1787
		log_error(gettext("No suitable interface found for running dhcrelay!"));
1788
		return; /* XXX */
1789
	}
1790

    
1791
	$cmd = "/usr/local/sbin/dhcrelay -i " . implode(" -i ", $dhcrelayifs);
1792

    
1793
	if (isset($dhcrelaycfg['agentoption'])) {
1794
		$cmd .= " -a -m replace";
1795
	}
1796

    
1797
	$cmd .= " " . implode(" ", $srvips);
1798
	mwexec($cmd);
1799
	unset($cmd);
1800

    
1801
	return 0;
1802
}
1803

    
1804
function services_dhcrelay6_configure() {
1805
	global $config, $g;
1806

    
1807
	if (isset($config['system']['developerspew'])) {
1808
		$mt = microtime();
1809
		echo "services_dhcrelay6_configure() being called $mt\n";
1810
	}
1811

    
1812
	/* kill any running dhcrelay */
1813
	killbypid("{$g['varrun_path']}/dhcrelay6.pid");
1814

    
1815
	$dhcrelaycfg =& $config['dhcrelay6'];
1816

    
1817
	/* DHCPv6 Relay enabled on any interfaces? */
1818
	if (!isset($dhcrelaycfg['enable'])) {
1819
		return 0;
1820
	}
1821

    
1822
	if (platform_booting()) {
1823
		echo gettext("Starting DHCPv6 relay service...");
1824
	} else {
1825
		sleep(1);
1826
	}
1827

    
1828
	$iflist = get_configured_interface_list();
1829

    
1830
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1831
	foreach ($dhcifaces as $dhcrelayif) {
1832
		if (!isset($iflist[$dhcrelayif]) ||
1833
		    link_interface_to_bridge($dhcrelayif)) {
1834
			continue;
1835
		}
1836

    
1837
		if (is_ipaddrv6(get_interface_ipv6($dhcrelayif))) {
1838
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1839
		}
1840
	}
1841
	$dhcrelayifs = array_unique($dhcrelayifs);
1842

    
1843
	/*
1844
	 * In order for the relay to work, it needs to be active
1845
	 * on the interface in which the destination server sits.
1846
	 */
1847
	$srvips = explode(",", $dhcrelaycfg['server']);
1848
	$srvifaces = array();
1849
	foreach ($srvips as $srcidx => $srvip) {
1850
		$destif = guess_interface_from_ip($srvip);
1851
		if (!empty($destif)) {
1852
			$srvifaces[] = "{$srvip}%{$destif}";
1853
		}
1854
	}
1855

    
1856
	/* fire up dhcrelay */
1857
	if (empty($dhcrelayifs) || empty($srvifaces)) {
1858
		log_error(gettext("No suitable interface found for running dhcrelay -6!"));
1859
		return; /* XXX */
1860
	}
1861

    
1862
	$cmd = "/usr/local/sbin/dhcrelay -6 -pf \"{$g['varrun_path']}/dhcrelay6.pid\"";
1863
	foreach ($dhcrelayifs as $dhcrelayif) {
1864
		$cmd .= " -l {$dhcrelayif}";
1865
	}
1866
	foreach ($srvifaces as $srviface) {
1867
		$cmd .= " -u \"{$srviface}\"";
1868
	}
1869
	mwexec($cmd);
1870
	unset($cmd);
1871

    
1872
	return 0;
1873
}
1874

    
1875
function services_dyndns_configure_client($conf) {
1876

    
1877
	if (!isset($conf['enable'])) {
1878
		return;
1879
	}
1880

    
1881
	/* load up the dyndns.class */
1882
	require_once("dyndns.class");
1883

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

    
1908
function services_dyndns_configure($int = "") {
1909
	global $config, $g;
1910
	if (isset($config['system']['developerspew'])) {
1911
		$mt = microtime();
1912
		echo "services_dyndns_configure() being called $mt\n";
1913
	}
1914

    
1915
	$dyndnscfg = $config['dyndnses']['dyndns'];
1916
	$gwgroups = return_gateway_groups_array();
1917
	if (is_array($dyndnscfg)) {
1918
		if (platform_booting()) {
1919
			echo gettext("Starting DynDNS clients...");
1920
		}
1921

    
1922
		foreach ($dyndnscfg as $dyndns) {
1923
			/*
1924
			 * If it's using a gateway group, check if interface is
1925
			 * the active gateway for that group
1926
			 */
1927
			$group_int = '';
1928
			$friendly_group_int = '';
1929
			if (is_array($gwgroups[$dyndns['interface']])) {
1930
				if (!empty($gwgroups[$dyndns['interface']][0]['vip'])) {
1931
					$group_int = $gwgroups[$dyndns['interface']][0]['vip'];
1932
				} else {
1933
					$group_int = $gwgroups[$dyndns['interface']][0]['int'];
1934
					$friendly_group_int =
1935
					    convert_real_interface_to_friendly_interface_name(
1936
						$group_int);
1937
				}
1938
			}
1939
			if ((empty($int)) || ($int == $dyndns['interface']) ||
1940
			    ($int == $group_int) || ($int == $friendly_group_int)) {
1941
				$dyndns['verboselog'] = isset($dyndns['verboselog']);
1942
				$dyndns['curl_ipresolve_v4'] = isset($dyndns['curl_ipresolve_v4']);
1943
				$dyndns['curl_ssl_verifypeer'] = isset($dyndns['curl_ssl_verifypeer']);
1944
				services_dyndns_configure_client($dyndns);
1945
				sleep(1);
1946
			}
1947
		}
1948

    
1949
		if (platform_booting()) {
1950
			echo gettext("done.") . "\n";
1951
		}
1952
	}
1953

    
1954
	return 0;
1955
}
1956

    
1957
function dyndnsCheckIP($int) {
1958
	global $config, $factory_default_checkipservice;
1959
	$ip_address = get_interface_ip($int);
1960
	if (is_private_ip($ip_address)) {
1961
		$gateways_status = return_gateways_status(true);
1962
		// If the gateway for this interface is down, then the external check cannot work.
1963
		// Avoid the long wait for the external check to timeout.
1964
		if (stristr($gateways_status[$config['interfaces'][$int]['gateway']]['status'], "down")) {
1965
			return "down";
1966
		}
1967

    
1968
		// Append the factory default check IP service to the list (if not disabled).
1969
		if (!isset($config['checkipservices']['disable_factory_default'])) {
1970
			$config['checkipservices']['checkipservice'][] = $factory_default_checkipservice;
1971
		}
1972

    
1973
		// Use the first enabled check IP service as the default.
1974
		if (is_array($config['checkipservices']['checkipservice'])) {
1975
			foreach ($config['checkipservices']['checkipservice'] as $i => $checkipservice) {
1976
				if (isset($checkipservice['enable'])) {
1977
					$url = $checkipservice['url'];
1978
					$username = $checkipservice['username'];
1979
					$password = $checkipservice['password'];
1980
					$verifysslpeer = isset($checkipservice['verifysslpeer']);
1981
					break;
1982
				}
1983
			}
1984
		}
1985

    
1986
		$hosttocheck = $url;
1987
		$ip_ch = curl_init($hosttocheck);
1988
		curl_setopt($ip_ch, CURLOPT_RETURNTRANSFER, 1);
1989
		curl_setopt($ip_ch, CURLOPT_SSL_VERIFYPEER, $verifysslpeer);
1990
		curl_setopt($ip_ch, CURLOPT_INTERFACE, 'host!' . $ip_address);
1991
		curl_setopt($ip_ch, CURLOPT_CONNECTTIMEOUT, '30');
1992
		curl_setopt($ip_ch, CURLOPT_TIMEOUT, 120);
1993
		curl_setopt($ip_ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
1994
		curl_setopt($ip_ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
1995
		curl_setopt($ip_ch, CURLOPT_USERPWD, "{$username}:{$password}");
1996
		$ip_result_page = curl_exec($ip_ch);
1997
		curl_close($ip_ch);
1998
		$ip_result_decoded = urldecode($ip_result_page);
1999
		preg_match('=Current IP Address: (.*)</body>=siU', $ip_result_decoded, $matches);
2000
		$ip_address = trim($matches[1]);
2001
	}
2002
	return $ip_address;
2003
}
2004

    
2005
function services_dnsmasq_configure($restart_dhcp = true) {
2006
	global $config, $g;
2007
	$return = 0;
2008

    
2009
	// hard coded args: will be removed to avoid duplication if specified in custom_options
2010
	$standard_args = array(
2011
		"dns-forward-max" => "--dns-forward-max=5000",
2012
		"cache-size" => "--cache-size=10000",
2013
		"local-ttl" => "--local-ttl=1"
2014
	);
2015

    
2016

    
2017
	if (isset($config['system']['developerspew'])) {
2018
		$mt = microtime();
2019
		echo "services_dnsmasq_configure() being called $mt\n";
2020
	}
2021

    
2022
	/* kill any running dnsmasq */
2023
	if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) {
2024
		sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
2025
	}
2026

    
2027
	if (isset($config['dnsmasq']['enable'])) {
2028

    
2029
		if (platform_booting()) {
2030
			echo gettext("Starting DNS forwarder...");
2031
		} else {
2032
			sleep(1);
2033
		}
2034

    
2035
		/* generate hosts file */
2036
		if (system_hosts_generate() != 0) {
2037
			$return = 1;
2038
		}
2039

    
2040
		$args = "";
2041

    
2042
		if (isset($config['dnsmasq']['regdhcp'])) {
2043
			$args .= " --dhcp-hostsfile={$g['etc_path']}/hosts ";
2044
		}
2045

    
2046
		/* Setup listen port, if non-default */
2047
		if (is_port($config['dnsmasq']['port'])) {
2048
			$args .= " --port={$config['dnsmasq']['port']} ";
2049
		}
2050

    
2051
		$listen_addresses = "";
2052
		if (isset($config['dnsmasq']['interface'])) {
2053
			$interfaces = explode(",", $config['dnsmasq']['interface']);
2054
			foreach ($interfaces as $interface) {
2055
				$if = get_real_interface($interface);
2056
				if (does_interface_exist($if)) {
2057
					$laddr = get_interface_ip($interface);
2058
					if (is_ipaddrv4($laddr)) {
2059
						$listen_addresses .= " --listen-address={$laddr} ";
2060
					}
2061
					$laddr6 = get_interface_ipv6($interface);
2062
					if (is_ipaddrv6($laddr6) && !isset($config['dnsmasq']['strictbind'])) {
2063
						/*
2064
						 * XXX: Since dnsmasq does not support link-local address
2065
						 * with scope specified. These checks are being done.
2066
						 */
2067
						if (is_linklocal($laddr6) && strstr($laddr6, "%")) {
2068
							$tmpaddrll6 = explode("%", $laddr6);
2069
							$listen_addresses .= " --listen-address={$tmpaddrll6[0]} ";
2070
						} else {
2071
							$listen_addresses .= " --listen-address={$laddr6} ";
2072
						}
2073
					}
2074
				}
2075
			}
2076
			if (!empty($listen_addresses)) {
2077
				$args .= " {$listen_addresses} ";
2078
				if (isset($config['dnsmasq']['strictbind'])) {
2079
					$args .= " --bind-interfaces ";
2080
				}
2081
			}
2082
		}
2083

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

    
2091
			// Build an array of domain overrides to help in checking for matches.
2092
			$override_a = array();
2093
			if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2094
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2095
					$override_a[$override['domain']] = "y";
2096
				}
2097
			}
2098

    
2099
			// Build an array of the private reverse lookup domain names
2100
			$reverse_domain_a = array("10.in-addr.arpa", "168.192.in-addr.arpa");
2101
			// Unfortunately the 172.16.0.0/12 range does not map nicely to the in-addr.arpa scheme.
2102
			for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) {
2103
				$reverse_domain_a[] = "$subnet_num.172.in-addr.arpa";
2104
			}
2105

    
2106
			// Set the --server parameter to nowhere for each reverse domain name that was not specifically specified in a domain override.
2107
			foreach ($reverse_domain_a as $reverse_domain) {
2108
				if (!isset($override_a[$reverse_domain])) {
2109
					$args .= " --server=/$reverse_domain/ ";
2110
				}
2111
			}
2112
			unset($override_a);
2113
			unset($reverse_domain_a);
2114
		}
2115

    
2116
		/* Setup forwarded domains */
2117
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2118
			foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2119
				if ($override['ip'] == "!") {
2120
					$override[ip] = "";
2121
				}
2122
				$args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
2123
			}
2124
		}
2125

    
2126
		/* Allow DNS Rebind for forwarded domains */
2127
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2128
			if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2129
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2130
					$args .= ' --rebind-domain-ok=/' . $override['domain'] . '/ ';
2131
				}
2132
			}
2133
		}
2134

    
2135
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2136
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2137
		}
2138

    
2139
		if (isset($config['dnsmasq']['strict_order'])) {
2140
			$args .= " --strict-order ";
2141
		}
2142

    
2143
		if (isset($config['dnsmasq']['domain_needed'])) {
2144
			$args .= " --domain-needed ";
2145
		}
2146

    
2147
		if ($config['dnsmasq']['custom_options']) {
2148
			foreach (preg_split('/\s+/', $config['dnsmasq']['custom_options']) as $c) {
2149
				$args .= " " . escapeshellarg("--{$c}");
2150
				$p = explode('=', $c);
2151
				if (array_key_exists($p[0], $standard_args)) {
2152
					unset($standard_args[$p[0]]);
2153
				}
2154
			}
2155
		}
2156
		$args .= ' ' . implode(' ', array_values($standard_args));
2157

    
2158
		/* run dnsmasq. Use "-C /dev/null" since we use command line args only (Issue #6730) */
2159
		$cmd = "/usr/local/sbin/dnsmasq --all-servers -C /dev/null {$dns_rebind} {$args}";
2160
		//log_error("dnsmasq command: {$cmd}");
2161
		mwexec_bg($cmd);
2162
		unset($args);
2163

    
2164
		system_dhcpleases_configure();
2165

    
2166
		if (platform_booting()) {
2167
			echo gettext("done.") . "\n";
2168
		}
2169
	}
2170

    
2171
	if (!platform_booting() && $restart_dhcp) {
2172
		if (services_dhcpd_configure() != 0) {
2173
			$return = 1;
2174
		}
2175
	}
2176

    
2177
	return $return;
2178
}
2179

    
2180
function services_unbound_configure($restart_dhcp = true) {
2181
	global $config, $g;
2182
	$return = 0;
2183

    
2184
	if (isset($config['system']['developerspew'])) {
2185
		$mt = microtime();
2186
		echo "services_unbound_configure() being called $mt\n";
2187
	}
2188

    
2189
	if (isset($config['unbound']['enable'])) {
2190
		require_once('/etc/inc/unbound.inc');
2191

    
2192
		/* Stop Unbound using TERM */
2193
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2194
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
2195
		}
2196

    
2197
		/* If unbound is still running, wait up to 30 seconds for it to terminate. */
2198
		for ($i=1; $i <= 30; $i++) {
2199
			if (is_process_running('unbound')) {
2200
				sleep(1);
2201
			}
2202
		}
2203

    
2204
		if (platform_booting()) {
2205
			echo gettext("Starting DNS Resolver...");
2206
		} else {
2207
			sleep(1);
2208
		}
2209

    
2210
		/* generate hosts file */
2211
		if (system_hosts_generate() != 0) {
2212
			$return = 1;
2213
		}
2214

    
2215
		/* Check here for dhcp6 complete - wait upto 10 seconds */
2216
		if($config['interfaces']["wan"]['ipaddrv6'] == 'dhcp6') {
2217
			$wanif = get_real_interface("wan", "inet6");
2218
			if (platform_booting()) {
2219
				for ($i=1; $i <= 10; $i++) {
2220
					if (!file_exists("/tmp/{$wanif}_dhcp6_complete")) {
2221
						log_error(gettext("Unbound start waiting on dhcp6c."));
2222
						sleep(1);
2223
					} else {
2224
						unlink_if_exists("/tmp/{$wanif}_dhcp6_complete");
2225
						log_error(gettext("dhcp6 init complete. Continuing"));
2226
						break;
2227
					}
2228
				}
2229
			}
2230
		}
2231

    
2232
		sync_unbound_service();
2233
		if (platform_booting()) {
2234
			log_error(gettext("sync unbound done."));
2235
			echo gettext("done.") . "\n";
2236
		}
2237

    
2238
		system_dhcpleases_configure();
2239
	} else {
2240
		/* kill Unbound since it should not be enabled */
2241
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2242
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "KILL");
2243
		}
2244
	}
2245

    
2246
	if (!platform_booting() && $restart_dhcp) {
2247
		if (services_dhcpd_configure() != 0) {
2248
			$return = 1;
2249
		}
2250
	}
2251

    
2252
	return $return;
2253
}
2254

    
2255
function services_snmpd_configure() {
2256
	global $config, $g;
2257
	if (isset($config['system']['developerspew'])) {
2258
		$mt = microtime();
2259
		echo "services_snmpd_configure() being called $mt\n";
2260
	}
2261

    
2262
	/* kill any running snmpd */
2263
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
2264
	sleep(2);
2265
	if (is_process_running("bsnmpd")) {
2266
		mwexec("/usr/bin/killall bsnmpd", true);
2267
	}
2268

    
2269
	if (isset($config['snmpd']['enable'])) {
2270

    
2271
		if (platform_booting()) {
2272
			echo gettext("Starting SNMP daemon... ");
2273
		}
2274

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

    
2280
		/* generate snmpd.conf */
2281
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
2282
		if (!$fd) {
2283
			printf(gettext("Error: cannot open snmpd.conf in services_snmpd_configure().%s"), "\n");
2284
			return 1;
2285
		}
2286

    
2287

    
2288
		$snmpdconf = <<<EOD
2289
location := "{$config['snmpd']['syslocation']}"
2290
contact := "{$config['snmpd']['syscontact']}"
2291
read := "{$config['snmpd']['rocommunity']}"
2292

    
2293
EOD;
2294

    
2295
/* No docs on what write strings do there so disable for now.
2296
		if (isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])) {
2297
			$snmpdconf .= <<<EOD
2298
# write string
2299
write := "{$config['snmpd']['rwcommunity']}"
2300

    
2301
EOD;
2302
		}
2303
*/
2304

    
2305

    
2306
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2307
			$snmpdconf .= <<<EOD
2308
# SNMP Trap support.
2309
traphost := {$config['snmpd']['trapserver']}
2310
trapport := {$config['snmpd']['trapserverport']}
2311
trap := "{$config['snmpd']['trapstring']}"
2312

    
2313

    
2314
EOD;
2315
		}
2316

    
2317
		$sysDescr = "{$g['product_name']} " . php_uname("n") .
2318
			" {$g['product_version']} {$g['platform']} " . php_uname("s") .
2319
			" " . php_uname("r") . " " . php_uname("m");
2320

    
2321
		$snmpdconf .= <<<EOD
2322
system := 1     # pfSense
2323
%snmpd
2324
sysDescr			= "{$sysDescr}"
2325
begemotSnmpdDebugDumpPdus       = 2
2326
begemotSnmpdDebugSyslogPri      = 7
2327
begemotSnmpdCommunityString.0.1 = $(read)
2328

    
2329
EOD;
2330

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

    
2336
EOD;
2337
		}
2338
*/
2339

    
2340

    
2341
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2342
			$snmpdconf .= <<<EOD
2343
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
2344
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
2345
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
2346

    
2347
EOD;
2348
		}
2349

    
2350

    
2351
		$snmpdconf .= <<<EOD
2352
begemotSnmpdCommunityDisable    = 1
2353

    
2354
EOD;
2355

    
2356
		$bind_to_ips = array();
2357
		if (isset($config['snmpd']['bindip'])) {
2358
			foreach (explode(",", $config['snmpd']['bindip']) as $bind_to_ip) {
2359
				if (is_ipaddr($bind_to_ip)) {
2360
					$bind_to_ips[] = $bind_to_ip;
2361
				} else {
2362
					$if = get_real_interface($bind_to_ip);
2363
					if (does_interface_exist($if)) {
2364
						$bindip = get_interface_ip($bind_to_ip);
2365
						if (is_ipaddr($bindip)) {
2366
							$bind_to_ips[] = $bindip;
2367
						}
2368
					}
2369
				}
2370
			}
2371
		}
2372
		if (!count($bind_to_ips)) {
2373
			$bind_to_ips = array("0.0.0.0");
2374
		}
2375

    
2376
		if (is_port($config['snmpd']['pollport'])) {
2377
			foreach ($bind_to_ips as $bind_to_ip) {
2378
				$snmpdconf .= <<<EOD
2379
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
2380

    
2381
EOD;
2382

    
2383
			}
2384
		}
2385

    
2386
		$snmpdconf .= <<<EOD
2387
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
2388
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
2389

    
2390
# These are bsnmp macros not php vars.
2391
sysContact      = $(contact)
2392
sysLocation     = $(location)
2393
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
2394

    
2395
snmpEnableAuthenTraps = 2
2396

    
2397
EOD;
2398

    
2399
		if (is_array($config['snmpd']['modules'])) {
2400
			if (isset($config['snmpd']['modules']['mibii'])) {
2401
			$snmpdconf .= <<<EOD
2402
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
2403

    
2404
EOD;
2405
			}
2406

    
2407
			if (isset($config['snmpd']['modules']['netgraph'])) {
2408
				$snmpdconf .= <<<EOD
2409
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
2410
%netgraph
2411
begemotNgControlNodeName = "snmpd"
2412

    
2413
EOD;
2414
			}
2415

    
2416
			if (isset($config['snmpd']['modules']['pf'])) {
2417
				$snmpdconf .= <<<EOD
2418
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
2419

    
2420
EOD;
2421
			}
2422

    
2423
			if (isset($config['snmpd']['modules']['hostres'])) {
2424
				$snmpdconf .= <<<EOD
2425
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
2426

    
2427
EOD;
2428
			}
2429

    
2430
			if (isset($config['snmpd']['modules']['bridge'])) {
2431
				$snmpdconf .= <<<EOD
2432
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
2433
# config must end with blank line
2434

    
2435
EOD;
2436
			}
2437
			if (isset($config['snmpd']['modules']['ucd'])) {
2438
				$snmpdconf .= <<<EOD
2439
begemotSnmpdModulePath."ucd"     = "/usr/local/lib/snmp_ucd.so"
2440

    
2441
EOD;
2442
			}
2443
			if (isset($config['snmpd']['modules']['regex'])) {
2444
				$snmpdconf .= <<<EOD
2445
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"
2446

    
2447
EOD;
2448
			}
2449
		}
2450

    
2451
		fwrite($fd, $snmpdconf);
2452
		fclose($fd);
2453
		unset($snmpdconf);
2454

    
2455
		/* run bsnmpd */
2456
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
2457
			" -p {$g['varrun_path']}/snmpd.pid");
2458

    
2459
		if (platform_booting()) {
2460
			echo gettext("done.") . "\n";
2461
		}
2462
	}
2463

    
2464
	return 0;
2465
}
2466

    
2467
function services_dnsupdate_process($int = "", $updatehost = "", $forced = false) {
2468
	global $config, $g;
2469
	if (isset($config['system']['developerspew'])) {
2470
		$mt = microtime();
2471
		echo "services_dnsupdate_process() being called $mt\n";
2472
	}
2473

    
2474
	/* Dynamic DNS updating active? */
2475
	if (!is_array($config['dnsupdates']['dnsupdate'])) {
2476
		return 0;
2477
	}
2478

    
2479
	$notify_text = "";
2480
	$gwgroups = return_gateway_groups_array();
2481
	foreach ($config['dnsupdates']['dnsupdate'] as $i => $dnsupdate) {
2482
		if (!isset($dnsupdate['enable'])) {
2483
			continue;
2484
		}
2485
		/*
2486
		 * If it's using a gateway group, check if interface is
2487
		 * the active gateway for that group
2488
		 */
2489
		$group_int = '';
2490
		$friendly_group_int = '';
2491
		if (is_array($gwgroups[$dnsupdate['interface']])) {
2492
			if (!empty($gwgroups[$dnsupdate['interface']][0]['vip'])) {
2493
				$group_int = $gwgroups[$dnsupdate['interface']][0]['vip'];
2494
			} else {
2495
				$group_int = $gwgroups[$dnsupdate['interface']][0]['int'];
2496
				$friendly_group_int =
2497
				    convert_real_interface_to_friendly_interface_name(
2498
					$group_int);
2499
			}
2500
		}
2501
		if (!empty($int) && ($int != $dnsupdate['interface']) &&
2502
		    ($int != $group_int) && ($int != $friendly_group_int)) {
2503
			continue;
2504
		}
2505
		if (!empty($updatehost) && ($updatehost != $dnsupdate['host'])) {
2506
			continue;
2507
		}
2508

    
2509
		/* determine interface name */
2510
		$if = get_failover_interface($dnsupdate['interface']);
2511

    
2512
		/* Determine address to update and default binding address */
2513
		if (isset($dnsupdate['usepublicip'])) {
2514
			$wanip = dyndnsCheckIP($if);
2515
			$bindipv4 = get_interface_ip($if);
2516
		} else {
2517
			$wanip = get_interface_ip($if);
2518
			$bindipv4 = $wanip;
2519
		}
2520
		$wanipv6 = get_interface_ipv6($if);
2521
		$bindipv6 = $wanipv6;
2522

    
2523
		/* Handle non-default interface bindings */
2524
		if ($dnsupdate['updatesource'] == "none") {
2525
			/* When empty, the directive will be omitted. */
2526
			$bindipv4 = "";
2527
			$bindipv6 = "";
2528
		} elseif (!empty($dnsupdate['updatesource'])) {
2529
			/* Find the alternate binding address */
2530
			$bindipv4 = get_interface_ip($dnsupdate['updatesource']);
2531
			$bindipv6 = get_interface_ipv6($dnsupdate['updatesource']);
2532
		}
2533

    
2534
		/* Handle IPv4/IPv6 selection for the update source interface/VIP */
2535
		switch ($dnsupdate['updatesourcefamily']) {
2536
			case "inet":
2537
				$bindip = $bindipv4;
2538
				break;
2539
			case "inet6":
2540
				$bindip = $bindipv6;
2541
				break;
2542
			case "":
2543
			default:
2544
				/* Try IPv4 first, if that is empty, try IPv6. */
2545
				/* Only specify the address if it's present, otherwise omit. */
2546
				if (!empty($bindipv4)) {
2547
					$bindip = $bindipv4;
2548
				} elseif (!empty($bindipv6)) {
2549
					$bindip = $bindipv6;
2550
				}
2551
				break;
2552
		}
2553

    
2554
		$cacheFile = $g['conf_path'] .
2555
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2556
		    escapeshellarg($dnsupdate['host']) .
2557
		    "_{$dnsupdate['server']}.cache";
2558
		$cacheFilev6 = $g['conf_path'] .
2559
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2560
		    escapeshellarg($dnsupdate['host']) .
2561
		    "_{$dnsupdate['server']}_v6.cache";
2562
		$currentTime = time();
2563

    
2564
		if (!$wanip && !$wanipv6) {
2565
			continue;
2566
		}
2567

    
2568
		$keyname = $dnsupdate['keyname'];
2569
		/* trailing dot */
2570
		if (substr($keyname, -1) != ".") {
2571
			$keyname .= ".";
2572
		}
2573

    
2574
		$hostname = $dnsupdate['host'];
2575
		/* trailing dot */
2576
		if (substr($hostname, -1) != ".") {
2577
			$hostname .= ".";
2578
		}
2579

    
2580
		/* write key file */
2581
		$algorithm = empty($dnsupdate['keyalgorithm']) ? 'hmac-md5' : $dnsupdate['keyalgorithm'];
2582
		$upkey = <<<EOD
2583
key "{$keyname}" {
2584
	algorithm {$algorithm};
2585
	secret "{$dnsupdate['keydata']}";
2586
};
2587

    
2588
EOD;
2589
		@file_put_contents("{$g['varetc_path']}/nsupdatekey{$i}", $upkey);
2590

    
2591
		/* generate update instructions */
2592
		$upinst = "";
2593
		if (!empty($dnsupdate['server'])) {
2594
			$upinst .= "server {$dnsupdate['server']}\n";
2595
		}
2596

    
2597
		$cachedipv4 = '';
2598
		$cacheTimev4 = 0;
2599
		if (file_exists($cacheFile)) {
2600
			list($cachedipv4, $cacheTimev4) = explode("|",
2601
			    file_get_contents($cacheFile));
2602
		}
2603
		$cachedipv6 = '';
2604
		$cacheTimev6 = 0;
2605
		if (file_exists($cacheFilev6)) {
2606
			list($cachedipv6, $cacheTimev6) = explode("|",
2607
			    file_get_contents($cacheFilev6));
2608
		}
2609

    
2610
		// 25 Days
2611
		$maxCacheAgeSecs = 25 * 24 * 60 * 60;
2612
		$need_update = false;
2613

    
2614
		/* Update IPv4 if we have it. */
2615
		if (is_ipaddrv4($wanip) && $dnsupdate['recordtype'] != "AAAA") {
2616
			if (($wanip != $cachedipv4) || $forced ||
2617
			    (($currentTime - $cacheTimev4) > $maxCacheAgeSecs)) {
2618
				$upinst .= "update delete " .
2619
				    "{$dnsupdate['host']}. A\n";
2620
				$upinst .= "update add {$dnsupdate['host']}. " .
2621
				    "{$dnsupdate['ttl']} A {$wanip}\n";
2622
				if (!empty($bindip)) {
2623
					$upinst .= "local {$bindip}\n";
2624
				}
2625
				$need_update = true;
2626
			} else {
2627
				log_error(sprintf(gettext(
2628
				    "phpDynDNS: Not updating %s A record because the IP address has not changed."),
2629
				    $dnsupdate['host']));
2630
			}
2631
		} else {
2632
			@unlink($cacheFile);
2633
			unset($cacheFile);
2634
		}
2635

    
2636
		/* Update IPv6 if we have it. */
2637
		if (is_ipaddrv6($wanipv6) && $dnsupdate['recordtype'] != "A") {
2638
			if (($wanipv6 != $cachedipv6) || $forced ||
2639
			    (($currentTime - $cacheTimev6) > $maxCacheAgeSecs)) {
2640
				$upinst .= "update delete " .
2641
				    "{$dnsupdate['host']}. AAAA\n";
2642
				$upinst .= "update add {$dnsupdate['host']}. " .
2643
				    "{$dnsupdate['ttl']} AAAA {$wanipv6}\n";
2644
				$need_update = true;
2645
			} else {
2646
				log_error(sprintf(gettext(
2647
				    "phpDynDNS: Not updating %s AAAA record because the IPv6 address has not changed."),
2648
				    $dnsupdate['host']));
2649
			}
2650
		} else {
2651
			@unlink($cacheFilev6);
2652
			unset($cacheFilev6);
2653
		}
2654

    
2655
		$upinst .= "\n";	/* mind that trailing newline! */
2656

    
2657
		if (!$need_update) {
2658
			continue;
2659
		}
2660

    
2661
		@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}", $upinst);
2662
		unset($upinst);
2663
		/* invoke nsupdate */
2664
		$cmd = "/usr/local/bin/nsupdate -k {$g['varetc_path']}/nsupdatekey{$i}";
2665

    
2666
		if (isset($dnsupdate['usetcp'])) {
2667
			$cmd .= " -v";
2668
		}
2669

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

    
2672
		if (mwexec($cmd) == 0) {
2673
			if (!empty($cacheFile)) {
2674
				@file_put_contents($cacheFile,
2675
				    "{$wanip}|{$currentTime}");
2676
				log_error(sprintf(gettext(
2677
				    'phpDynDNS: updating cache file %1$s: %2$s'),
2678
				    $cacheFile, $wanip));
2679
				$notify_text .= sprintf(gettext(
2680
				    'DynDNS updated IP Address (A) for %1$s on %2$s (%3$s) to %4$s'),
2681
				    $dnsupdate['host'],
2682
				    convert_real_interface_to_friendly_descr($if),
2683
				    $if, $wanip) . "\n";
2684
			}
2685
			if (!empty($cacheFilev6)) {
2686
				@file_put_contents($cacheFilev6,
2687
				    "{$wanipv6}|{$currentTime}");
2688
				log_error(sprintf(gettext(
2689
				    'phpDynDNS: updating cache file %1$s: %2$s'),
2690
				    $cacheFilev6, $wanipv6));
2691
				$notify_text .= sprintf(gettext(
2692
				    'DynDNS updated IPv6 Address (AAAA) for %1$s on %2$s (%3$s) to %4$s'),
2693
				    $dnsupdate['host'],
2694
				    convert_real_interface_to_friendly_descr($if),
2695
				    $if, $wanipv6) . "\n";
2696
			}
2697
		} else {
2698
			if (!empty($cacheFile)) {
2699
				log_error(sprintf(gettext(
2700
				    'phpDynDNS: ERROR while updating IP Address (A) for %1$s (%2$s)'),
2701
				    $dnsupdate['host'], $wanip));
2702
			}
2703
			if (!empty($cacheFilev6)) {
2704
				log_error(sprintf(gettext(
2705
				    'phpDynDNS: ERROR while updating IP Address (AAAA) for %1$s (%2$s)'),
2706
				    $dnsupdate['host'], $wanipv6));
2707
			}
2708
		}
2709
		unset($cmd);
2710
	}
2711

    
2712
	if (!empty($notify_text)) {
2713
		notify_all_remote($notify_text);
2714
	}
2715

    
2716
	return 0;
2717
}
2718

    
2719
/* configure cron service */
2720
function configure_cron() {
2721
	global $g, $config;
2722

    
2723
	/* preserve existing crontab entries */
2724
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2725

    
2726
	for ($i = 0; $i < count($crontab_contents); $i++) {
2727
		$cron_item =& $crontab_contents[$i];
2728
		if (strpos($cron_item, "# pfSense specific crontab entries") !== false) {
2729
			array_splice($crontab_contents, $i - 1);
2730
			break;
2731
		}
2732
	}
2733
	$crontab_contents = implode("\n", $crontab_contents) . "\n";
2734

    
2735

    
2736
	if (is_array($config['cron']['item'])) {
2737
		$crontab_contents .= "#\n";
2738
		$crontab_contents .= "# pfSense specific crontab entries\n";
2739
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
2740
		$crontab_contents .= "#\n";
2741

    
2742
		if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) {
2743
			$http_proxy = $config['system']['proxyurl'];
2744
			if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) {
2745
				$http_proxy .= ':' . $config['system']['proxyport'];
2746
			}
2747
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
2748

    
2749
			if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
2750
				$crontab_contents .= "HTTP_PROXY_AUTH=basic:*:{$config['system']['proxyuser']}:{$config['system']['proxypass']}";
2751
			}
2752
		}
2753

    
2754
		foreach ($config['cron']['item'] as $item) {
2755
			$crontab_contents .= "\n{$item['minute']}\t";
2756
			$crontab_contents .= "{$item['hour']}\t";
2757
			$crontab_contents .= "{$item['mday']}\t";
2758
			$crontab_contents .= "{$item['month']}\t";
2759
			$crontab_contents .= "{$item['wday']}\t";
2760
			$crontab_contents .= "{$item['who']}\t";
2761
			$crontab_contents .= "{$item['command']}";
2762
		}
2763

    
2764
		$crontab_contents .= "\n#\n";
2765
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
2766
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
2767
		$crontab_contents .= "#\n\n";
2768
	}
2769

    
2770
	/* please maintain the newline at the end of file */
2771
	file_put_contents("/etc/crontab", $crontab_contents);
2772
	unset($crontab_contents);
2773

    
2774
	/* make sure that cron is running and start it if it got killed somehow */
2775
	if (!is_process_running("cron")) {
2776
		exec("cd /tmp && /usr/sbin/cron -s 2>/dev/null");
2777
	} else {
2778
	/* do a HUP kill to force sync changes */
2779
		sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP");
2780
	}
2781

    
2782
}
2783

    
2784
function upnp_action ($action) {
2785
	global $g, $config;
2786
	switch ($action) {
2787
		case "start":
2788
			if (file_exists('/var/etc/miniupnpd.conf')) {
2789
				@unlink("{$g['varrun_path']}/miniupnpd.pid");
2790
				mwexec_bg("/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf -P {$g['varrun_path']}/miniupnpd.pid");
2791
			}
2792
			break;
2793
		case "stop":
2794
			killbypid("{$g['varrun_path']}/miniupnpd.pid");
2795
			while ((int)exec("/bin/pgrep -a miniupnpd | wc -l") > 0) {
2796
				mwexec('/usr/bin/killall miniupnpd 2>/dev/null', true);
2797
			}
2798
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
2799
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
2800
			break;
2801
		case "restart":
2802
			upnp_action('stop');
2803
			upnp_action('start');
2804
			break;
2805
	}
2806
}
2807

    
2808
function upnp_start() {
2809
	global $config;
2810

    
2811
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
2812
		return;
2813
	}
2814

    
2815
	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
2816
		echo gettext("Starting UPnP service... ");
2817
		require_once('/usr/local/pkg/miniupnpd.inc');
2818
		sync_package_miniupnpd();
2819
		echo "done.\n";
2820
	}
2821
}
2822

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

    
2826
	$is_installed = false;
2827
	$cron_changed = true;
2828
	$change_message = "";
2829

    
2830
	if (!is_array($config['cron'])) {
2831
		$config['cron'] = array();
2832
	}
2833
	if (!is_array($config['cron']['item'])) {
2834
		$config['cron']['item'] = array();
2835
	}
2836

    
2837
	$x = 0;
2838
	foreach ($config['cron']['item'] as $item) {
2839
		if (strstr($item['command'], $command)) {
2840
			$is_installed = true;
2841
			break;
2842
		}
2843
		$x++;
2844
	}
2845

    
2846
	if ($active) {
2847
		$cron_item = array();
2848
		$cron_item['minute'] = $minute;
2849
		$cron_item['hour'] = $hour;
2850
		$cron_item['mday'] = $monthday;
2851
		$cron_item['month'] = $month;
2852
		$cron_item['wday'] = $weekday;
2853
		$cron_item['who'] = $who;
2854
		$cron_item['command'] = $command;
2855
		if (!$is_installed) {
2856
			$config['cron']['item'][] = $cron_item;
2857
			$change_message = "Installed cron job for %s";
2858
		} else {
2859
			if ($config['cron']['item'][$x] == $cron_item) {
2860
				$cron_changed = false;
2861
			} else {
2862
				$config['cron']['item'][$x] = $cron_item;
2863
				$change_message = "Updated cron job for %s";
2864
			}
2865
		}
2866
	} else {
2867
		if ($is_installed == true) {
2868
			array_splice($config['cron']['item'], $x, 1);
2869
			$change_message = "Removed cron job for %s";
2870
		} else {
2871
			$cron_changed = false;
2872
		}
2873
	}
2874

    
2875
	if ($cron_changed) {
2876
		/* Optionally write the configuration if this function made changes.
2877
		 * Performing a write_config() in this way can have unintended side effects. See #7146
2878
		 * Base system instances of this function do not need to write, packages may.
2879
		 */
2880
		if ($write_config) {
2881
			write_config(sprintf(gettext($change_message), $command));
2882
		}
2883
		configure_cron();
2884
	}
2885
}
2886

    
2887
?>
(42-42/55)