Project

General

Profile

Download (88 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['interface'] == $dhcpif) {
597
						$carp_nw = gen_subnet($vipent['subnet'], $vipent['subnet_bits']);
598
						if (ip_in_subnet($dhcpifconf['failover_peerip'], "{$carp_nw}/{$vipent['subnet_bits']}")) {
599
							/* this is the interface! */
600
							if (is_numeric($vipent['advskew']) && (intval($vipent['advskew']) < 20)) {
601
								$skew = 0;
602
								break;
603
							}
604
						}
605
					}
606
				}
607
			} else {
608
				log_error(gettext("Warning!  DHCP Failover setup and no CARP virtual IPs defined!"));
609
			}
610
			if ($skew > 10) {
611
				$type = "secondary";
612
				$my_port = "520";
613
				$peer_port = "519";
614
				$dhcpdconf_pri = '';
615
			} else {
616
				$my_port = "519";
617
				$peer_port = "520";
618
				$type = "primary";
619
				$dhcpdconf_pri = "split 128;\n";
620
				$dhcpdconf_pri .= "  mclt 600;\n";
621
			}
622

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

    
642
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
643

    
644
		$newzone = array();
645
		$ifcfg = $config['interfaces'][$dhcpif];
646

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

    
655
		if (!is_ipaddr($subnet)) {
656
			continue;
657
		}
658

    
659
		if ($is_olsr_enabled == true) {
660
			if ($dhcpifconf['netmask']) {
661
				$subnetmask = gen_subnet_mask($dhcpifconf['netmask']);
662
			}
663
		}
664

    
665
		$all_pools = array();
666
		$all_pools[] = $dhcpifconf;
667
		if (is_array($dhcpifconf['pool'])) {
668
			$all_pools = array_merge($all_pools, $dhcpifconf['pool']);
669
		}
670

    
671
		$dnscfg = "";
672

    
673
		if ($dhcpifconf['domain']) {
674
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
675
		}
676

    
677
		if ($dhcpifconf['domainsearchlist'] <> "") {
678
			$dnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpifconf['domainsearchlist'])) . "\";\n";
679
		}
680

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

    
691
			$revsubnet = array_reverse(explode('.',$subnet));
692

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

    
710
			}
711

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

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

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

    
768
		$dhcpdconf .= "subnet {$subnet} netmask {$subnetmask} {\n";
769

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

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

    
835
			if ($poolconf['failover_peerip'] <> "") {
836
				$dhcpdconf .= "		$deny_action dynamic bootp clients;\n";
837
			}
838

    
839
			if (isset($poolconf['denyunknown'])) {
840
				$dhcpdconf .= "		$deny_action unknown-clients;\n";
841
			}
842

    
843
			if ($poolconf['gateway'] && $poolconf['gateway'] != "none" && ($poolconf['gateway'] != $dhcpifconf['gateway'])) {
844
				$dhcpdconf .= "		option routers {$poolconf['gateway']};\n";
845
			}
846

    
847
			if ($dhcpifconf['failover_peerip'] <> "") {
848
				$dhcpdconf .= "		failover peer \"dhcp_{$dhcpif}\";\n";
849
			}
850

    
851
			$pdnscfg = "";
852

    
853
			if ($poolconf['domain'] && ($poolconf['domain'] != $dhcpifconf['domain'])) {
854
				$pdnscfg .= "		option domain-name \"{$poolconf['domain']}\";\n";
855
			}
856

    
857
			if (!empty($poolconf['domainsearchlist']) && ($poolconf['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
858
				$pdnscfg .= "		option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $poolconf['domainsearchlist'])) . "\";\n";
859
			}
860

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

    
868
			$dhcpdconf .= "{$pdnscfg}";
869

    
870
			// default-lease-time
871
			if ($poolconf['defaultleasetime'] && ($poolconf['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
872
				$dhcpdconf .= "		default-lease-time {$poolconf['defaultleasetime']};\n";
873
			}
874

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

    
880
			// ignore bootp
881
			if (isset($poolconf['ignorebootp'])) {
882
				$dhcpdconf .= "		ignore bootp;\n";
883
			}
884

    
885
			// ignore-client-uids
886
			if (isset($poolconf['ignoreclientuids'])) {
887
				$dhcpdconf .= "		ignore-client-uids true;\n";
888
			}
889

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

    
896
			// ntp-servers
897
			if (is_array($poolconf['ntpserver']) && $poolconf['ntpserver'][0] && ($poolconf['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
898
				$dhcpdconf .= "		option ntp-servers " . join(",", $poolconf['ntpserver']) . ";\n";
899
			}
900

    
901
			// tftp-server-name
902
			if (!empty($poolconf['tftp']) && ($poolconf['tftp'] != $dhcpifconf['tftp'])) {
903
				$dhcpdconf .= "		option tftp-server-name \"{$poolconf['tftp']}\";\n";
904
			}
905

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

    
923
			// ldap-server
924
			if (!empty($poolconf['ldap']) && ($poolconf['ldap'] != $dhcpifconf['ldap'])) {
925
				$dhcpdconf .= "		option ldap-server \"{$poolconf['ldap']}\";\n";
926
			}
927

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

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

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

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

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

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

    
999
		$dhcpdconf .= <<<EOD
1000
$dnscfg
1001

    
1002
EOD;
1003
		// default-lease-time
1004
		if ($dhcpifconf['defaultleasetime']) {
1005
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
1006
		}
1007

    
1008
		// max-lease-time
1009
		if ($dhcpifconf['maxleasetime']) {
1010
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
1011
		}
1012

    
1013
		// netbios-name*
1014
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
1015
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
1016
			$dhcpdconf .= "	option netbios-node-type 8;\n";
1017
		}
1018

    
1019
		// ntp-servers
1020
		if (is_array($dhcpifconf['ntpserver']) && $dhcpifconf['ntpserver'][0]) {
1021
			$dhcpdconf .= "	option ntp-servers " . join(",", $dhcpifconf['ntpserver']) . ";\n";
1022
		}
1023

    
1024
		// tftp-server-name
1025
		if ($dhcpifconf['tftp'] <> "") {
1026
			$dhcpdconf .= "	option tftp-server-name \"{$dhcpifconf['tftp']}\";\n";
1027
		}
1028

    
1029
		// Handle option, number rowhelper values
1030
		$dhcpdconf .= "\n";
1031
		if ($dhcpifconf['numberoptions']['item']) {
1032
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
1033
				$item_value = base64_decode($item['value']);
1034
				if (empty($item['type']) || $item['type'] == "text") {
1035
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} \"{$item_value}\";\n";
1036
				} else {
1037
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} {$item_value};\n";
1038
				}
1039
			}
1040
		}
1041

    
1042
		// ldap-server
1043
		if ($dhcpifconf['ldap'] <> "") {
1044
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
1045
		}
1046

    
1047
		// net boot information
1048
		if (isset($dhcpifconf['netboot'])) {
1049
			if ($dhcpifconf['nextserver'] <> "") {
1050
				$dhcpdconf .= "	next-server {$dhcpifconf['nextserver']};\n";
1051
			}
1052
			if (!empty($dhcpifconf['filename']) && !empty($dhcpifconf['filename32']) && !empty($dhcpifconf['filename64'])) {
1053
				$dhcpdconf .= "	if option arch = 00:06 {\n";
1054
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename32']}\";\n";
1055
				$dhcpdconf .= "	} else if option arch = 00:07 {\n";
1056
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1057
				$dhcpdconf .= "	} else if option arch = 00:09 {\n";
1058
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1059
				$dhcpdconf .= "	} else {\n";
1060
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename']}\";\n";
1061
				$dhcpdconf .= "	}\n\n";
1062
			} elseif (!empty($dhcpifconf['filename'])) {
1063
				$dhcpdconf .= "	filename \"{$dhcpifconf['filename']}\";\n";
1064
			}
1065
			if (!empty($dhcpifconf['rootpath'])) {
1066
				$dhcpdconf .= "	option root-path \"{$dhcpifconf['rootpath']}\";\n";
1067
			}
1068
		}
1069

    
1070
		$dhcpdconf .= <<<EOD
1071
}
1072

    
1073
EOD;
1074

    
1075
		/* add static mappings */
1076
		if (is_array($dhcpifconf['staticmap'])) {
1077

    
1078
			$i = 0;
1079
			foreach ($dhcpifconf['staticmap'] as $sm) {
1080
				$dhcpdconf .= "host s_{$dhcpif}_{$i} {\n";
1081

    
1082
				if ($sm['mac']) {
1083
					$dhcpdconf .= "        hardware ethernet {$sm['mac']};\n";
1084
				}
1085

    
1086
				if ($sm['cid']) {
1087
					$dhcpdconf .= "        option dhcp-client-identifier \"{$sm['cid']}\";\n";
1088
				}
1089

    
1090
				if ($sm['ipaddr']) {
1091
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
1092
				}
1093

    
1094
				if ($sm['hostname']) {
1095
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1096
					$dhhostname = str_replace(".", "_", $dhhostname);
1097
					$dhcpdconf .= "	option host-name \"{$dhhostname}\";\n";
1098
					if ((isset($dhcpifconf['ddnsupdate']) || isset($sm['ddnsupdate'])) && (isset($dhcpifconf['ddnsforcehostname']) || isset($sm['ddnsforcehostname']))) {
1099
						$dhcpdconf .= "	ddns-hostname \"{$dhhostname}\";\n";
1100
					}
1101
				}
1102
				if ($sm['filename']) {
1103
					$dhcpdconf .= "	filename \"{$sm['filename']}\";\n";
1104
				}
1105

    
1106
				if ($sm['rootpath']) {
1107
					$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1108
				}
1109

    
1110
				if ($sm['gateway'] && ($sm['gateway'] != $dhcpifconf['gateway'])) {
1111
					$dhcpdconf .= "	option routers {$sm['gateway']};\n";
1112
				}
1113

    
1114
				$smdnscfg = "";
1115

    
1116
				if ($sm['domain'] && ($sm['domain'] != $dhcpifconf['domain'])) {
1117
					$smdnscfg .= "	option domain-name \"{$sm['domain']}\";\n";
1118
				}
1119

    
1120
				if (!empty($sm['domainsearchlist']) && ($sm['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
1121
					$smdnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $sm['domainsearchlist'])) . "\";\n";
1122
				}
1123

    
1124
				if (isset($sm['ddnsupdate'])) {
1125
					if (($sm['ddnsdomain'] <> "") && ($sm['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
1126
						$smdnscfg .= "		ddns-domainname \"{$sm['ddnsdomain']}\";\n";
1127
					}
1128
					$smdnscfg .= "		ddns-update-style interim;\n";
1129
				}
1130

    
1131
				if (is_array($sm['dnsserver']) && ($sm['dnsserver'][0]) && ($sm['dnsserver'][0] != $dhcpifconf['dnsserver'][0])) {
1132
					$smdnscfg .= "	option domain-name-servers " . join(",", $sm['dnsserver']) . ";\n";
1133
				}
1134
				$dhcpdconf .= "{$smdnscfg}";
1135

    
1136
				// default-lease-time
1137
				if ($sm['defaultleasetime'] && ($sm['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
1138
					$dhcpdconf .= "	default-lease-time {$sm['defaultleasetime']};\n";
1139
				}
1140

    
1141
				// max-lease-time
1142
				if ($sm['maxleasetime'] && ($sm['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
1143
					$dhcpdconf .= "	max-lease-time {$sm['maxleasetime']};\n";
1144
				}
1145

    
1146
				// netbios-name*
1147
				if (is_array($sm['winsserver']) && $sm['winsserver'][0] && ($sm['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
1148
					$dhcpdconf .= "	option netbios-name-servers " . join(",", $sm['winsserver']) . ";\n";
1149
					$dhcpdconf .= "	option netbios-node-type 8;\n";
1150
				}
1151

    
1152
				// ntp-servers
1153
				if (is_array($sm['ntpserver']) && $sm['ntpserver'][0] && ($sm['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
1154
					$dhcpdconf .= "	option ntp-servers " . join(",", $sm['ntpserver']) . ";\n";
1155
				}
1156

    
1157
				// tftp-server-name
1158
				if (!empty($sm['tftp']) && ($sm['tftp'] != $dhcpifconf['tftp'])) {
1159
					$dhcpdconf .= "	option tftp-server-name \"{$sm['tftp']}\";\n";
1160
				}
1161

    
1162
				$dhcpdconf .= "}\n";
1163
				$i++;
1164
			}
1165
		}
1166

    
1167
		$dhcpdifs[] = get_real_interface($dhcpif);
1168
		if ($newzone['domain-name']) {
1169
			if ($need_ddns_updates) {
1170
				$newzone['dns-servers'] = array($dhcpifconf['ddnsdomainprimary']);
1171
				$newzone['ddnsdomainkeyname'] = $dhcpifconf['ddnsdomainkeyname'];
1172
				$newzone['ddnsdomainkeyalgorithm'] = $dhcpifconf['ddnsdomainkeyalgorithm'];
1173
				$newzone['ddnsdomainkey'] = $dhcpifconf['ddnsdomainkey'];
1174
				$dhcpdconf .= dhcpdkey($dhcpifconf);
1175
			}
1176
			$ddns_zones[] = $newzone;
1177
		}
1178
	}
1179

    
1180
	if ($need_ddns_updates) {
1181
		$dhcpdconf .= "ddns-update-style interim;\n";
1182
		$dhcpdconf .= "update-static-leases on;\n";
1183

    
1184
		$dhcpdconf .= dhcpdzones($ddns_zones);
1185
	}
1186

    
1187
	/* write dhcpd.conf */
1188
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpd.conf", $dhcpdconf)) {
1189
		printf(gettext("Error: cannot open dhcpd.conf in services_dhcpdv4_configure().%s"), "\n");
1190
		unset($dhcpdconf);
1191
		return 1;
1192
	}
1193
	unset($dhcpdconf);
1194

    
1195
	/* create an empty leases database */
1196
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
1197
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
1198
	}
1199

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

    
1204
	/* fire up dhcpd in a chroot */
1205
	if (count($dhcpdifs) > 0) {
1206
		mwexec("/usr/local/sbin/dhcpd -user dhcpd -group _dhcp -chroot {$g['dhcpd_chroot_path']} -cf /etc/dhcpd.conf -pf {$g['varrun_path']}/dhcpd.pid " .
1207
			join(" ", $dhcpdifs));
1208
	}
1209

    
1210
	if (platform_booting()) {
1211
		print "done.\n";
1212
	}
1213

    
1214
	return 0;
1215
}
1216

    
1217
function dhcpdkey($dhcpifconf) {
1218
	$dhcpdconf = "";
1219
	if (!empty($dhcpifconf['ddnsdomainkeyname']) && !empty($dhcpifconf['ddnsdomainkey'])) {
1220
		$algorithm = empty($dhcpifconf['ddnsdomainkeyalgorithm']) ? 'hmac-md5' : $dhcpifconf['ddnsdomainkeyalgorithm'];
1221
		$dhcpdconf .= "key {$dhcpifconf['ddnsdomainkeyname']} {\n";
1222
		$dhcpdconf .= "	algorithm {$algorithm};\n";
1223
		$dhcpdconf .= "	secret {$dhcpifconf['ddnsdomainkey']};\n";
1224
		$dhcpdconf .= "}\n";
1225
	}
1226

    
1227
	return $dhcpdconf;
1228
}
1229

    
1230
function dhcpdzones($ddns_zones) {
1231
	$dhcpdconf = "";
1232

    
1233
	if (is_array($ddns_zones)) {
1234
		$added_zones = array();
1235
		foreach ($ddns_zones as $zone) {
1236
			if (!is_array($zone) || empty($zone) || !is_array($zone['dns-servers'])) {
1237
				continue;
1238
			}
1239
			$primary = $zone['dns-servers'][0];
1240
			$secondary = empty($zone['dns-servers'][1]) ? "" : $zone['dns-servers'][1];
1241

    
1242
			// Make sure we aren't using any invalid or IPv6 DNS servers.
1243
			if (!is_ipaddrv4($primary)) {
1244
				if (is_ipaddrv4($secondary)) {
1245
					$primary = $secondary;
1246
					$secondary = "";
1247
				} else {
1248
					continue;
1249
				}
1250
			}
1251

    
1252
			// We don't need to add zones multiple times.
1253
			if ($zone['domain-name'] && !in_array($zone['domain-name'], $added_zones)) {
1254
				$dhcpdconf .= "zone {$zone['domain-name']}. {\n";
1255
				$dhcpdconf .= "	primary {$primary};\n";
1256
				if (is_ipaddrv4($secondary)) {
1257
					$dhcpdconf .= "	secondary {$secondary};\n";
1258
				}
1259
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1260
					$dhcpdconf .= "	key {$zone['ddnsdomainkeyname']};\n";
1261
				}
1262
				$dhcpdconf .= "}\n";
1263
				$added_zones[] = $zone['domain-name'];
1264
			}
1265
			if ($zone['ptr-domain'] && !in_array($zone['ptr-domain'], $added_zones)) {
1266
				$dhcpdconf .= "zone {$zone['ptr-domain']} {\n";
1267
				$dhcpdconf .= "	primary {$primary};\n";
1268
				if (is_ipaddrv4($secondary)) {
1269
					$dhcpdconf .= "	secondary {$secondary};\n";
1270
				}
1271
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1272
					$dhcpdconf .= "	key {$zone['ddnsdomainkeyname']};\n";
1273
				}
1274
				$dhcpdconf .= "}\n";
1275
				$added_zones[] = $zone['ptr-domain'];
1276
			}
1277
		}
1278
	}
1279

    
1280
	return $dhcpdconf;
1281
}
1282

    
1283
function services_dhcpdv6_configure($blacklist = array()) {
1284
	global $config, $g;
1285

    
1286
	if ($g['services_dhcp_server_enable'] == false) {
1287
		return;
1288
	}
1289

    
1290
	if (isset($config['system']['developerspew'])) {
1291
		$mt = microtime();
1292
		echo "services_dhcpd_configure($if) being called $mt\n";
1293
	}
1294

    
1295
	/* kill any running dhcpd */
1296
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid")) {
1297
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid");
1298
	}
1299
	if (isvalidpid("{$g['varrun_path']}/dhcpleases6.pid")) {
1300
		killbypid("{$g['varrun_path']}/dhcpleases6.pid");
1301
	}
1302

    
1303
	/* DHCP enabled on any interfaces? */
1304
	if (!is_dhcpv6_server_enabled()) {
1305
		return 0;
1306
	}
1307

    
1308
	$syscfg = $config['system'];
1309
	if (!is_array($config['dhcpdv6'])) {
1310
		$config['dhcpdv6'] = array();
1311
	}
1312
	$dhcpdv6cfg = $config['dhcpdv6'];
1313
	$Iflist = get_configured_interface_list();
1314
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
1315

    
1316

    
1317
	if (platform_booting()) {
1318
		echo "Starting DHCPv6 service...";
1319
	} else {
1320
		sleep(1);
1321
	}
1322

    
1323
	$custoptionsv6 = "";
1324
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1325
		if (is_array($dhcpv6ifconf['numberoptions']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1326
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1327
				$custoptionsv6 .= "option custom-{$dhcpv6if}-{$itemv6idx} code {$itemv6['number']} = text;\n";
1328
			}
1329
		}
1330
	}
1331

    
1332
	if (isset($dhcpv6ifconf['netboot']) && !empty($dhcpv6ifconf['bootfile_url'])) {
1333
		$custoptionsv6 .= "option dhcp6.bootfile-url code 59 = string;\n";
1334
	}
1335

    
1336
	$dhcpdv6conf = <<<EOD
1337

    
1338
option domain-name "{$syscfg['domain']}";
1339
option ldap-server code 95 = text;
1340
option domain-search-list code 119 = text;
1341
{$custoptionsv6}
1342
default-lease-time 7200;
1343
max-lease-time 86400;
1344
log-facility local7;
1345
one-lease-per-client true;
1346
deny duplicates;
1347
ping-check true;
1348
update-conflict-detection false;
1349

    
1350
EOD;
1351

    
1352
	if (!isset($dhcpv6ifconf['disableauthoritative'])) {
1353
		$dhcpdv6conf .= "authoritative;\n";
1354
	}
1355

    
1356
	if (isset($dhcpv6ifconf['alwaysbroadcast'])) {
1357
		$dhcpdv6conf .= "always-broadcast on\n";
1358
	}
1359

    
1360
	$dhcpdv6ifs = array();
1361

    
1362
	$dhcpv6num = 0;
1363
	$nsupdate = false;
1364

    
1365
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1366

    
1367
		$ddns_zones = array();
1368

    
1369
		$ifcfgv6 = $config['interfaces'][$dhcpv6if];
1370

    
1371
		if (!isset($dhcpv6ifconf['enable']) || !isset($Iflist[$dhcpv6if]) || !isset($ifcfgv6['enable'])) {
1372
			continue;
1373
		}
1374
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1375
		if (!is_ipaddrv6($ifcfgipv6)) {
1376
			continue;
1377
		}
1378
		$ifcfgsnv6 = get_interface_subnetv6($dhcpv6if);
1379
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1380
		// We might have some prefix-delegation on WAN (e.g. /48),
1381
		// but then it is split and given out to individual interfaces
1382
		// (LAN, OPT1, OPT2...) as multiple /64 subnets. So the size
1383
		// of each subnet here is always /64.
1384
		$pdlen = 64;
1385

    
1386
		if ($is_olsr_enabled == true) {
1387
			if ($dhcpv6ifconf['netmask']) {
1388
				$subnetmask = gen_subnet_maskv6($dhcpv6ifconf['netmask']);
1389
			}
1390
		}
1391

    
1392
		$dnscfgv6 = "";
1393

    
1394
		if ($dhcpv6ifconf['domain']) {
1395
			$dnscfgv6 .= "	option domain-name \"{$dhcpv6ifconf['domain']}\";\n";
1396
		}
1397

    
1398
		if ($dhcpv6ifconf['domainsearchlist'] <> "") {
1399
			$dnscfgv6 .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpv6ifconf['domainsearchlist'])) . "\";\n";
1400
		}
1401

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

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

    
1433
		if (!is_ipaddrv6($ifcfgipv6)) {
1434
			$ifcfgsnv6 = "64";
1435
			$subnetv6 = gen_subnetv6($dhcpv6ifconf['range']['from'], $ifcfgsnv6);
1436
		}
1437

    
1438
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1439

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

    
1461
		$dhcpdv6conf .= " {\n";
1462

    
1463
		$range_from = $dhcpv6ifconf['range']['from'];
1464
		$range_to = $dhcpv6ifconf['range']['to'];
1465
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
1466
			$range_from = merge_ipv6_delegated_prefix($ifcfgipv6, $range_from, $pdlen);
1467
			$range_to = merge_ipv6_delegated_prefix($ifcfgipv6, $range_to, $pdlen);
1468
		}
1469

    
1470
		$dhcpdv6conf .= <<<EOD
1471
	range6 {$range_from} {$range_to};
1472
$dnscfgv6
1473

    
1474
EOD;
1475

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

    
1492
		// max-lease-time
1493
		if ($dhcpv6ifconf['maxleasetime']) {
1494
			$dhcpdv6conf .= "	max-lease-time {$dhcpv6ifconf['maxleasetime']};\n";
1495
		}
1496

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

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

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

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

    
1547
		$dhcpdv6conf .= "}\n";
1548

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

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

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

    
1580
				if ($sm['rootpath']) {
1581
					$dhcpdv6conf .= "	option root-path \"{$sm['rootpath']}\";\n";
1582
				}
1583

    
1584
				$dhcpdv6conf .= "}\n";
1585
				$i++;
1586
			}
1587
		}
1588

    
1589
		if ($dhcpv6ifconf['ddnsdomain']) {
1590
			$dhcpdv6conf .= dhcpdkey($dhcpv6ifconf);
1591
			$dhcpdv6conf .= dhcpdzones($ddns_zones);
1592
		}
1593

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

    
1612
	if ($nsupdate) {
1613
		$dhcpdv6conf .= "ddns-update-style interim;\n";
1614
	} else {
1615
		$dhcpdv6conf .= "ddns-update-style none;\n";
1616
	}
1617

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

    
1629
	/* create an empty leases v6 database */
1630
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases")) {
1631
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1632
	}
1633

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

    
1638
	/* fire up dhcpd in a chroot */
1639
	if (count($dhcpdv6ifs) > 0) {
1640
		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 " .
1641
			join(" ", $dhcpdv6ifs));
1642
		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");
1643
	}
1644
	if (platform_booting()) {
1645
		print gettext("done.") . "\n";
1646
	}
1647

    
1648
	return 0;
1649
}
1650

    
1651
function services_igmpproxy_configure() {
1652
	global $config, $g;
1653

    
1654
	/* kill any running igmpproxy */
1655
	killbyname("igmpproxy");
1656

    
1657
	if (!is_array($config['igmpproxy']['igmpentry']) || (count($config['igmpproxy']['igmpentry']) == 0)) {
1658
		return 1;
1659
	}
1660

    
1661
	$iflist = get_configured_interface_list();
1662

    
1663
	$igmpconf = <<<EOD
1664

    
1665
##------------------------------------------------------
1666
## Enable Quickleave mode (Sends Leave instantly)
1667
##------------------------------------------------------
1668
quickleave
1669

    
1670
EOD;
1671

    
1672
	foreach ($config['igmpproxy']['igmpentry'] as $igmpcf) {
1673
		unset($iflist[$igmpcf['ifname']]);
1674
		$realif = get_real_interface($igmpcf['ifname']);
1675
		if (empty($igmpcf['threshold'])) {
1676
			$threshld = 1;
1677
		} else {
1678
			$threshld = $igmpcf['threshold'];
1679
		}
1680
		$igmpconf .= "phyint {$realif} {$igmpcf['type']} ratelimit 0 threshold {$threshld}\n";
1681

    
1682
		if ($igmpcf['address'] <> "") {
1683
			$item = explode(" ", $igmpcf['address']);
1684
			foreach ($item as $iww) {
1685
				$igmpconf .= "altnet {$iww}\n";
1686
			}
1687
		}
1688
		$igmpconf .= "\n";
1689
	}
1690
	foreach ($iflist as $ifn) {
1691
		$realif = get_real_interface($ifn);
1692
		$igmpconf .= "phyint {$realif} disabled\n";
1693
	}
1694
	$igmpconf .= "\n";
1695

    
1696
	$igmpfl = fopen($g['varetc_path'] . "/igmpproxy.conf", "w");
1697
	if (!$igmpfl) {
1698
		log_error(gettext("Could not write Igmpproxy configuration file!"));
1699
		return;
1700
	}
1701
	fwrite($igmpfl, $igmpconf);
1702
	fclose($igmpfl);
1703
	unset($igmpconf);
1704

    
1705
	if (isset($config['syslog']['igmpxverbose'])) {
1706
		mwexec_bg("/usr/local/sbin/igmpproxy -v {$g['varetc_path']}/igmpproxy.conf");
1707
	} else {
1708
		mwexec_bg("/usr/local/sbin/igmpproxy {$g['varetc_path']}/igmpproxy.conf");
1709
	}
1710

    
1711
	log_error(gettext("Started IGMP proxy service."));
1712

    
1713
	return 0;
1714
}
1715

    
1716
function services_dhcrelay_configure() {
1717
	global $config, $g;
1718

    
1719
	if (isset($config['system']['developerspew'])) {
1720
		$mt = microtime();
1721
		echo "services_dhcrelay_configure() being called $mt\n";
1722
	}
1723

    
1724
	/* kill any running dhcrelay */
1725
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
1726

    
1727
	$dhcrelaycfg =& $config['dhcrelay'];
1728

    
1729
	/* DHCPRelay enabled on any interfaces? */
1730
	if (!isset($dhcrelaycfg['enable'])) {
1731
		return 0;
1732
	}
1733

    
1734
	if (platform_booting()) {
1735
		echo gettext("Starting DHCP relay service...");
1736
	} else {
1737
		sleep(1);
1738
	}
1739

    
1740
	$iflist = get_configured_interface_list();
1741

    
1742
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1743
	foreach ($dhcifaces as $dhcrelayif) {
1744
		if (!isset($iflist[$dhcrelayif]) ||
1745
		    link_interface_to_bridge($dhcrelayif)) {
1746
			continue;
1747
		}
1748

    
1749
		if (is_ipaddr(get_interface_ip($dhcrelayif))) {
1750
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1751
		}
1752
	}
1753

    
1754
	/*
1755
	 * In order for the relay to work, it needs to be active
1756
	 * on the interface in which the destination server sits.
1757
	 */
1758
	$srvips = explode(",", $dhcrelaycfg['server']);
1759
	if (!is_array($srvips)) {
1760
		log_error(gettext("No destination IP has been configured!"));
1761
		return;
1762
	}
1763

    
1764
	foreach ($srvips as $srcidx => $srvip) {
1765
		$destif = guess_interface_from_ip($srvip);
1766
		if (!empty($destif)) {
1767
			$dhcrelayifs[] = $destif;
1768
		}
1769
	}
1770
	$dhcrelayifs = array_unique($dhcrelayifs);
1771

    
1772
	/* fire up dhcrelay */
1773
	if (empty($dhcrelayifs)) {
1774
		log_error(gettext("No suitable interface found for running dhcrelay!"));
1775
		return; /* XXX */
1776
	}
1777

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

    
1780
	if (isset($dhcrelaycfg['agentoption'])) {
1781
		$cmd .= " -a -m replace";
1782
	}
1783

    
1784
	$cmd .= " " . implode(" ", $srvips);
1785
	mwexec($cmd);
1786
	unset($cmd);
1787

    
1788
	return 0;
1789
}
1790

    
1791
function services_dhcrelay6_configure() {
1792
	global $config, $g;
1793

    
1794
	if (isset($config['system']['developerspew'])) {
1795
		$mt = microtime();
1796
		echo "services_dhcrelay6_configure() being called $mt\n";
1797
	}
1798

    
1799
	/* kill any running dhcrelay */
1800
	killbypid("{$g['varrun_path']}/dhcrelay6.pid");
1801

    
1802
	$dhcrelaycfg =& $config['dhcrelay6'];
1803

    
1804
	/* DHCPv6 Relay enabled on any interfaces? */
1805
	if (!isset($dhcrelaycfg['enable'])) {
1806
		return 0;
1807
	}
1808

    
1809
	if (platform_booting()) {
1810
		echo gettext("Starting DHCPv6 relay service...");
1811
	} else {
1812
		sleep(1);
1813
	}
1814

    
1815
	$iflist = get_configured_interface_list();
1816

    
1817
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1818
	foreach ($dhcifaces as $dhcrelayif) {
1819
		if (!isset($iflist[$dhcrelayif]) ||
1820
		    link_interface_to_bridge($dhcrelayif)) {
1821
			continue;
1822
		}
1823

    
1824
		if (is_ipaddrv6(get_interface_ipv6($dhcrelayif))) {
1825
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1826
		}
1827
	}
1828
	$dhcrelayifs = array_unique($dhcrelayifs);
1829

    
1830
	/*
1831
	 * In order for the relay to work, it needs to be active
1832
	 * on the interface in which the destination server sits.
1833
	 */
1834
	$srvips = explode(",", $dhcrelaycfg['server']);
1835
	$srvifaces = array();
1836
	foreach ($srvips as $srcidx => $srvip) {
1837
		$destif = guess_interface_from_ip($srvip);
1838
		if (!empty($destif)) {
1839
			$srvifaces[] = "{$srvip}%{$destif}";
1840
		}
1841
	}
1842

    
1843
	/* fire up dhcrelay */
1844
	if (empty($dhcrelayifs) || empty($srvifaces)) {
1845
		log_error(gettext("No suitable interface found for running dhcrelay -6!"));
1846
		return; /* XXX */
1847
	}
1848

    
1849
	$cmd = "/usr/local/sbin/dhcrelay -6 -pf \"{$g['varrun_path']}/dhcrelay6.pid\"";
1850
	foreach ($dhcrelayifs as $dhcrelayif) {
1851
		$cmd .= " -l {$dhcrelayif}";
1852
	}
1853
	foreach ($srvifaces as $srviface) {
1854
		$cmd .= " -u \"{$srviface}\"";
1855
	}
1856
	mwexec($cmd);
1857
	unset($cmd);
1858

    
1859
	return 0;
1860
}
1861

    
1862
function services_dyndns_configure_client($conf) {
1863

    
1864
	if (!isset($conf['enable'])) {
1865
		return;
1866
	}
1867

    
1868
	/* load up the dyndns.class */
1869
	require_once("dyndns.class");
1870

    
1871
	$dns = new updatedns($dnsService = $conf['type'],
1872
		$dnsHost = $conf['host'],
1873
		$dnsDomain = $conf['domainname'],
1874
		$dnsUser = $conf['username'],
1875
		$dnsPass = $conf['password'],
1876
		$dnsWildcard = $conf['wildcard'],
1877
		$dnsProxied = $conf['proxied'],
1878
		$dnsMX = $conf['mx'],
1879
		$dnsIf = "{$conf['interface']}",
1880
		$dnsBackMX = NULL,
1881
		$dnsServer = NULL,
1882
		$dnsPort = NULL,
1883
		$dnsUpdateURL = "{$conf['updateurl']}",
1884
		$forceUpdate = $conf['force'],
1885
		$dnsZoneID = $conf['zoneid'],
1886
		$dnsTTL = $conf['ttl'],
1887
		$dnsResultMatch = "{$conf['resultmatch']}",
1888
		$dnsRequestIf = "{$conf['requestif']}",
1889
		$dnsID = "{$conf['id']}",
1890
		$dnsVerboseLog = $conf['verboselog'],
1891
		$curlIpresolveV4 = $conf['curl_ipresolve_v4'],
1892
		$curlSslVerifypeer = $conf['curl_ssl_verifypeer']);
1893
}
1894

    
1895
function services_dyndns_configure($int = "") {
1896
	global $config, $g;
1897
	if (isset($config['system']['developerspew'])) {
1898
		$mt = microtime();
1899
		echo "services_dyndns_configure() being called $mt\n";
1900
	}
1901

    
1902
	$dyndnscfg = $config['dyndnses']['dyndns'];
1903
	$gwgroups = return_gateway_groups_array();
1904
	if (is_array($dyndnscfg)) {
1905
		if (platform_booting()) {
1906
			echo gettext("Starting DynDNS clients...");
1907
		}
1908

    
1909
		foreach ($dyndnscfg as $dyndns) {
1910
			/*
1911
			 * If it's using a gateway group, check if interface is
1912
			 * the active gateway for that group
1913
			 */
1914
			$group_int = '';
1915
			$friendly_group_int = '';
1916
			if (is_array($gwgroups[$dyndns['interface']])) {
1917
				if (!empty($gwgroups[$dyndns['interface']][0]['vip'])) {
1918
					$group_int = $gwgroups[$dyndns['interface']][0]['vip'];
1919
				} else {
1920
					$group_int = $gwgroups[$dyndns['interface']][0]['int'];
1921
					$friendly_group_int =
1922
					    convert_real_interface_to_friendly_interface_name(
1923
						$group_int);
1924
				}
1925
			}
1926
			if ((empty($int)) || ($int == $dyndns['interface']) ||
1927
			    ($int == $group_int) || ($int == $friendly_group_int)) {
1928
				$dyndns['verboselog'] = isset($dyndns['verboselog']);
1929
				$dyndns['curl_ipresolve_v4'] = isset($dyndns['curl_ipresolve_v4']);
1930
				$dyndns['curl_ssl_verifypeer'] = isset($dyndns['curl_ssl_verifypeer']);
1931
				services_dyndns_configure_client($dyndns);
1932
				sleep(1);
1933
			}
1934
		}
1935

    
1936
		if (platform_booting()) {
1937
			echo gettext("done.") . "\n";
1938
		}
1939
	}
1940

    
1941
	return 0;
1942
}
1943

    
1944
function dyndnsCheckIP($int) {
1945
	global $config, $factory_default_checkipservice;
1946
	$ip_address = get_interface_ip($int);
1947
	if (is_private_ip($ip_address)) {
1948
		$gateways_status = return_gateways_status(true);
1949
		// If the gateway for this interface is down, then the external check cannot work.
1950
		// Avoid the long wait for the external check to timeout.
1951
		if (stristr($gateways_status[$config['interfaces'][$int]['gateway']]['status'], "down")) {
1952
			return "down";
1953
		}
1954

    
1955
		// Append the factory default check IP service to the list (if not disabled).
1956
		if (!isset($config['checkipservices']['disable_factory_default'])) {
1957
			$config['checkipservices']['checkipservice'][] = $factory_default_checkipservice;
1958
		}
1959

    
1960
		// Use the first enabled check IP service as the default.
1961
		if (is_array($config['checkipservices']['checkipservice'])) {
1962
			foreach ($config['checkipservices']['checkipservice'] as $i => $checkipservice) {
1963
				if (isset($checkipservice['enable'])) {
1964
					$url = $checkipservice['url'];
1965
					$username = $checkipservice['username'];
1966
					$password = $checkipservice['password'];
1967
					$verifysslpeer = isset($checkipservice['verifysslpeer']);
1968
					break;
1969
				}
1970
			}
1971
		}
1972

    
1973
		$hosttocheck = $url;
1974
		$ip_ch = curl_init($hosttocheck);
1975
		curl_setopt($ip_ch, CURLOPT_RETURNTRANSFER, 1);
1976
		curl_setopt($ip_ch, CURLOPT_SSL_VERIFYPEER, $verifysslpeer);
1977
		curl_setopt($ip_ch, CURLOPT_INTERFACE, 'host!' . $ip_address);
1978
		curl_setopt($ip_ch, CURLOPT_CONNECTTIMEOUT, '30');
1979
		curl_setopt($ip_ch, CURLOPT_TIMEOUT, 120);
1980
		curl_setopt($ip_ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
1981
		curl_setopt($ip_ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
1982
		curl_setopt($ip_ch, CURLOPT_USERPWD, "{$username}:{$password}");
1983
		$ip_result_page = curl_exec($ip_ch);
1984
		curl_close($ip_ch);
1985
		$ip_result_decoded = urldecode($ip_result_page);
1986
		preg_match('=Current IP Address: (.*)</body>=siU', $ip_result_decoded, $matches);
1987
		$ip_address = trim($matches[1]);
1988
	}
1989
	return $ip_address;
1990
}
1991

    
1992
function services_dnsmasq_configure($restart_dhcp = true) {
1993
	global $config, $g;
1994
	$return = 0;
1995

    
1996
	// hard coded args: will be removed to avoid duplication if specified in custom_options
1997
	$standard_args = array(
1998
		"dns-forward-max" => "--dns-forward-max=5000",
1999
		"cache-size" => "--cache-size=10000",
2000
		"local-ttl" => "--local-ttl=1"
2001
	);
2002

    
2003

    
2004
	if (isset($config['system']['developerspew'])) {
2005
		$mt = microtime();
2006
		echo "services_dnsmasq_configure() being called $mt\n";
2007
	}
2008

    
2009
	/* kill any running dnsmasq */
2010
	if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) {
2011
		sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
2012
	}
2013

    
2014
	if (isset($config['dnsmasq']['enable'])) {
2015

    
2016
		if (platform_booting()) {
2017
			echo gettext("Starting DNS forwarder...");
2018
		} else {
2019
			sleep(1);
2020
		}
2021

    
2022
		/* generate hosts file */
2023
		if (system_hosts_generate() != 0) {
2024
			$return = 1;
2025
		}
2026

    
2027
		$args = "";
2028

    
2029
		if (isset($config['dnsmasq']['regdhcp'])) {
2030
			$args .= " --dhcp-hostsfile={$g['etc_path']}/hosts ";
2031
		}
2032

    
2033
		/* Setup listen port, if non-default */
2034
		if (is_port($config['dnsmasq']['port'])) {
2035
			$args .= " --port={$config['dnsmasq']['port']} ";
2036
		}
2037

    
2038
		$listen_addresses = "";
2039
		if (isset($config['dnsmasq']['interface'])) {
2040
			$interfaces = explode(",", $config['dnsmasq']['interface']);
2041
			foreach ($interfaces as $interface) {
2042
				$if = get_real_interface($interface);
2043
				if (does_interface_exist($if)) {
2044
					$laddr = get_interface_ip($interface);
2045
					if (is_ipaddrv4($laddr)) {
2046
						$listen_addresses .= " --listen-address={$laddr} ";
2047
					}
2048
					$laddr6 = get_interface_ipv6($interface);
2049
					if (is_ipaddrv6($laddr6) && !isset($config['dnsmasq']['strictbind'])) {
2050
						/*
2051
						 * XXX: Since dnsmasq does not support link-local address
2052
						 * with scope specified. These checks are being done.
2053
						 */
2054
						if (is_linklocal($laddr6) && strstr($laddr6, "%")) {
2055
							$tmpaddrll6 = explode("%", $laddr6);
2056
							$listen_addresses .= " --listen-address={$tmpaddrll6[0]} ";
2057
						} else {
2058
							$listen_addresses .= " --listen-address={$laddr6} ";
2059
						}
2060
					}
2061
				}
2062
			}
2063
			if (!empty($listen_addresses)) {
2064
				$args .= " {$listen_addresses} ";
2065
				if (isset($config['dnsmasq']['strictbind'])) {
2066
					$args .= " --bind-interfaces ";
2067
				}
2068
			}
2069
		}
2070

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

    
2078
			// Build an array of domain overrides to help in checking for matches.
2079
			$override_a = array();
2080
			if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2081
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2082
					$override_a[$override['domain']] = "y";
2083
				}
2084
			}
2085

    
2086
			// Build an array of the private reverse lookup domain names
2087
			$reverse_domain_a = array("10.in-addr.arpa", "168.192.in-addr.arpa");
2088
			// Unfortunately the 172.16.0.0/12 range does not map nicely to the in-addr.arpa scheme.
2089
			for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) {
2090
				$reverse_domain_a[] = "$subnet_num.172.in-addr.arpa";
2091
			}
2092

    
2093
			// Set the --server parameter to nowhere for each reverse domain name that was not specifically specified in a domain override.
2094
			foreach ($reverse_domain_a as $reverse_domain) {
2095
				if (!isset($override_a[$reverse_domain])) {
2096
					$args .= " --server=/$reverse_domain/ ";
2097
				}
2098
			}
2099
			unset($override_a);
2100
			unset($reverse_domain_a);
2101
		}
2102

    
2103
		/* Setup forwarded domains */
2104
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2105
			foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2106
				if ($override['ip'] == "!") {
2107
					$override[ip] = "";
2108
				}
2109
				$args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
2110
			}
2111
		}
2112

    
2113
		/* Allow DNS Rebind for forwarded domains */
2114
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2115
			if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2116
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2117
					$args .= ' --rebind-domain-ok=/' . $override['domain'] . '/ ';
2118
				}
2119
			}
2120
		}
2121

    
2122
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2123
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2124
		}
2125

    
2126
		if (isset($config['dnsmasq']['strict_order'])) {
2127
			$args .= " --strict-order ";
2128
		}
2129

    
2130
		if (isset($config['dnsmasq']['domain_needed'])) {
2131
			$args .= " --domain-needed ";
2132
		}
2133

    
2134
		if ($config['dnsmasq']['custom_options']) {
2135
			foreach (preg_split('/\s+/', $config['dnsmasq']['custom_options']) as $c) {
2136
				$args .= " " . escapeshellarg("--{$c}");
2137
				$p = explode('=', $c);
2138
				if (array_key_exists($p[0], $standard_args)) {
2139
					unset($standard_args[$p[0]]);
2140
				}
2141
			}
2142
		}
2143
		$args .= ' ' . implode(' ', array_values($standard_args));
2144

    
2145
		/* run dnsmasq. Use "-C /dev/null" since we use command line args only (Issue #6730) */
2146
		$cmd = "/usr/local/sbin/dnsmasq --all-servers -C /dev/null {$dns_rebind} {$args}";
2147
		//log_error("dnsmasq command: {$cmd}");
2148
		mwexec_bg($cmd);
2149
		unset($args);
2150

    
2151
		system_dhcpleases_configure();
2152

    
2153
		if (platform_booting()) {
2154
			echo gettext("done.") . "\n";
2155
		}
2156
	}
2157

    
2158
	if (!platform_booting() && $restart_dhcp) {
2159
		if (services_dhcpd_configure() != 0) {
2160
			$return = 1;
2161
		}
2162
	}
2163

    
2164
	return $return;
2165
}
2166

    
2167
function services_unbound_configure($restart_dhcp = true) {
2168
	global $config, $g;
2169
	$return = 0;
2170

    
2171
	if (isset($config['system']['developerspew'])) {
2172
		$mt = microtime();
2173
		echo "services_unbound_configure() being called $mt\n";
2174
	}
2175

    
2176
	if (isset($config['unbound']['enable'])) {
2177
		require_once('/etc/inc/unbound.inc');
2178

    
2179
		/* Stop Unbound using TERM */
2180
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2181
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
2182
		}
2183

    
2184
		/* If unbound is still running, wait up to 30 seconds for it to terminate. */
2185
		for ($i=1; $i <= 30; $i++) {
2186
			if (is_process_running('unbound')) {
2187
				sleep(1);
2188
			}
2189
		}
2190

    
2191
		if (platform_booting()) {
2192
			echo gettext("Starting DNS Resolver...");
2193
		} else {
2194
			sleep(1);
2195
		}
2196

    
2197
		/* generate hosts file */
2198
		if (system_hosts_generate() != 0) {
2199
			$return = 1;
2200
		}
2201

    
2202
		/* Check here for dhcp6 complete - wait upto 10 seconds */
2203
		if($config['interfaces']["wan"]['ipaddrv6'] == 'dhcp6') {
2204
			$wanif = get_real_interface("wan", "inet6");
2205
			if (platform_booting()) {
2206
				for ($i=1; $i <= 10; $i++) {
2207
					if (!file_exists("/tmp/{$wanif}_dhcp6_complete")) { 
2208
						log_error(gettext("Unbound start waiting on dhcp6c."));
2209
						sleep(1);
2210
					} else {
2211
						unlink_if_exists("/tmp/{$wanif}_dhcp6_complete");
2212
						log_error(gettext("dhcp6 init complete. Continuing"));
2213
						break;
2214
					}						
2215
				}
2216
			}
2217
		}
2218
		
2219
		sync_unbound_service();
2220
		if (platform_booting()) {
2221
			log_error(gettext("sync unbound done."));
2222
			echo gettext("done.") . "\n";
2223
		}
2224

    
2225
		system_dhcpleases_configure();
2226
	} else {
2227
		/* kill Unbound since it should not be enabled */
2228
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2229
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "KILL");
2230
		}
2231
	}
2232

    
2233
	if (!platform_booting() && $restart_dhcp) {
2234
		if (services_dhcpd_configure() != 0) {
2235
			$return = 1;
2236
		}
2237
	}
2238

    
2239
	return $return;
2240
}
2241

    
2242
function services_snmpd_configure() {
2243
	global $config, $g;
2244
	if (isset($config['system']['developerspew'])) {
2245
		$mt = microtime();
2246
		echo "services_snmpd_configure() being called $mt\n";
2247
	}
2248

    
2249
	/* kill any running snmpd */
2250
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
2251
	sleep(2);
2252
	if (is_process_running("bsnmpd")) {
2253
		mwexec("/usr/bin/killall bsnmpd", true);
2254
	}
2255

    
2256
	if (isset($config['snmpd']['enable'])) {
2257

    
2258
		if (platform_booting()) {
2259
			echo gettext("Starting SNMP daemon... ");
2260
		}
2261

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

    
2267
		/* generate snmpd.conf */
2268
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
2269
		if (!$fd) {
2270
			printf(gettext("Error: cannot open snmpd.conf in services_snmpd_configure().%s"), "\n");
2271
			return 1;
2272
		}
2273

    
2274

    
2275
		$snmpdconf = <<<EOD
2276
location := "{$config['snmpd']['syslocation']}"
2277
contact := "{$config['snmpd']['syscontact']}"
2278
read := "{$config['snmpd']['rocommunity']}"
2279

    
2280
EOD;
2281

    
2282
/* No docs on what write strings do there so disable for now.
2283
		if (isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])) {
2284
			$snmpdconf .= <<<EOD
2285
# write string
2286
write := "{$config['snmpd']['rwcommunity']}"
2287

    
2288
EOD;
2289
		}
2290
*/
2291

    
2292

    
2293
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2294
			$snmpdconf .= <<<EOD
2295
# SNMP Trap support.
2296
traphost := {$config['snmpd']['trapserver']}
2297
trapport := {$config['snmpd']['trapserverport']}
2298
trap := "{$config['snmpd']['trapstring']}"
2299

    
2300

    
2301
EOD;
2302
		}
2303

    
2304
		$sysDescr = "{$g['product_name']} " . php_uname("n") .
2305
			" {$g['product_version']} {$g['platform']} " . php_uname("s") .
2306
			" " . php_uname("r") . " " . php_uname("m");
2307

    
2308
		$snmpdconf .= <<<EOD
2309
system := 1     # pfSense
2310
%snmpd
2311
sysDescr			= "{$sysDescr}"
2312
begemotSnmpdDebugDumpPdus       = 2
2313
begemotSnmpdDebugSyslogPri      = 7
2314
begemotSnmpdCommunityString.0.1 = $(read)
2315

    
2316
EOD;
2317

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

    
2323
EOD;
2324
		}
2325
*/
2326

    
2327

    
2328
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2329
			$snmpdconf .= <<<EOD
2330
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
2331
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
2332
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
2333

    
2334
EOD;
2335
		}
2336

    
2337

    
2338
		$snmpdconf .= <<<EOD
2339
begemotSnmpdCommunityDisable    = 1
2340

    
2341
EOD;
2342

    
2343
		$bind_to_ips = array();
2344
		if (isset($config['snmpd']['bindip'])) {
2345
			foreach (explode(",", $config['snmpd']['bindip']) as $bind_to_ip) {
2346
				if (is_ipaddr($bind_to_ip)) {
2347
					$bind_to_ips[] = $bind_to_ip;
2348
				} else {
2349
					$if = get_real_interface($bind_to_ip);
2350
					if (does_interface_exist($if)) {
2351
						$bindip = get_interface_ip($bind_to_ip);
2352
						if (is_ipaddr($bindip)) {
2353
							$bind_to_ips[] = $bindip;
2354
						}
2355
					}
2356
				}
2357
			}
2358
		}
2359
		if (!count($bind_to_ips)) {
2360
			$bind_to_ips = array("0.0.0.0");
2361
		}
2362

    
2363
		if (is_port($config['snmpd']['pollport'])) {
2364
			foreach ($bind_to_ips as $bind_to_ip) {
2365
				$snmpdconf .= <<<EOD
2366
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
2367

    
2368
EOD;
2369

    
2370
			}
2371
		}
2372

    
2373
		$snmpdconf .= <<<EOD
2374
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
2375
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
2376

    
2377
# These are bsnmp macros not php vars.
2378
sysContact      = $(contact)
2379
sysLocation     = $(location)
2380
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
2381

    
2382
snmpEnableAuthenTraps = 2
2383

    
2384
EOD;
2385

    
2386
		if (is_array($config['snmpd']['modules'])) {
2387
			if (isset($config['snmpd']['modules']['mibii'])) {
2388
			$snmpdconf .= <<<EOD
2389
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
2390

    
2391
EOD;
2392
			}
2393

    
2394
			if (isset($config['snmpd']['modules']['netgraph'])) {
2395
				$snmpdconf .= <<<EOD
2396
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
2397
%netgraph
2398
begemotNgControlNodeName = "snmpd"
2399

    
2400
EOD;
2401
			}
2402

    
2403
			if (isset($config['snmpd']['modules']['pf'])) {
2404
				$snmpdconf .= <<<EOD
2405
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
2406

    
2407
EOD;
2408
			}
2409

    
2410
			if (isset($config['snmpd']['modules']['hostres'])) {
2411
				$snmpdconf .= <<<EOD
2412
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
2413

    
2414
EOD;
2415
			}
2416

    
2417
			if (isset($config['snmpd']['modules']['bridge'])) {
2418
				$snmpdconf .= <<<EOD
2419
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
2420
# config must end with blank line
2421

    
2422
EOD;
2423
			}
2424
			if (isset($config['snmpd']['modules']['ucd'])) {
2425
				$snmpdconf .= <<<EOD
2426
begemotSnmpdModulePath."ucd"     = "/usr/local/lib/snmp_ucd.so"
2427

    
2428
EOD;
2429
			}
2430
			if (isset($config['snmpd']['modules']['regex'])) {
2431
				$snmpdconf .= <<<EOD
2432
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"
2433

    
2434
EOD;
2435
			}
2436
		}
2437

    
2438
		fwrite($fd, $snmpdconf);
2439
		fclose($fd);
2440
		unset($snmpdconf);
2441

    
2442
		/* run bsnmpd */
2443
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
2444
			" -p {$g['varrun_path']}/snmpd.pid");
2445

    
2446
		if (platform_booting()) {
2447
			echo gettext("done.") . "\n";
2448
		}
2449
	}
2450

    
2451
	return 0;
2452
}
2453

    
2454
function services_dnsupdate_process($int = "", $updatehost = "", $forced = false) {
2455
	global $config, $g;
2456
	if (isset($config['system']['developerspew'])) {
2457
		$mt = microtime();
2458
		echo "services_dnsupdate_process() being called $mt\n";
2459
	}
2460

    
2461
	/* Dynamic DNS updating active? */
2462
	if (!is_array($config['dnsupdates']['dnsupdate'])) {
2463
		return 0;
2464
	}
2465

    
2466
	$notify_text = "";
2467
	$gwgroups = return_gateway_groups_array();
2468
	foreach ($config['dnsupdates']['dnsupdate'] as $i => $dnsupdate) {
2469
		if (!isset($dnsupdate['enable'])) {
2470
			continue;
2471
		}
2472
		/*
2473
		 * If it's using a gateway group, check if interface is
2474
		 * the active gateway for that group
2475
		 */
2476
		$group_int = '';
2477
		$friendly_group_int = '';
2478
		if (is_array($gwgroups[$dnsupdate['interface']])) {
2479
			if (!empty($gwgroups[$dnsupdate['interface']][0]['vip'])) {
2480
				$group_int = $gwgroups[$dnsupdate['interface']][0]['vip'];
2481
			} else {
2482
				$group_int = $gwgroups[$dnsupdate['interface']][0]['int'];
2483
				$friendly_group_int =
2484
				    convert_real_interface_to_friendly_interface_name(
2485
					$group_int);
2486
			}
2487
		}
2488
		if (!empty($int) && ($int != $dnsupdate['interface']) &&
2489
		    ($int != $group_int) && ($int != $friendly_group_int)) {
2490
			continue;
2491
		}
2492
		if (!empty($updatehost) && ($updatehost != $dnsupdate['host'])) {
2493
			continue;
2494
		}
2495

    
2496
		/* determine interface name */
2497
		$if = get_failover_interface($dnsupdate['interface']);
2498

    
2499
		/* Determine address to update and default binding address */
2500
		if (isset($dnsupdate['usepublicip'])) {
2501
			$wanip = dyndnsCheckIP($if);
2502
			$bindipv4 = get_interface_ip($if);
2503
		} else {
2504
			$wanip = get_interface_ip($if);
2505
			$bindipv4 = $wanip;
2506
		}
2507
		$wanipv6 = get_interface_ipv6($if);
2508
		$bindipv6 = $wanipv6;
2509

    
2510
		/* Handle non-default interface bindings */
2511
		if ($dnsupdate['updatesource'] == "none") {
2512
			/* When empty, the directive will be omitted. */
2513
			$bindipv4 = "";
2514
			$bindipv6 = "";
2515
		} elseif (!empty($dnsupdate['updatesource'])) {
2516
			/* Find the alternate binding address */
2517
			$bindipv4 = get_interface_ip($dnsupdate['updatesource']);
2518
			$bindipv6 = get_interface_ipv6($dnsupdate['updatesource']);
2519
		}
2520

    
2521
		/* Handle IPv4/IPv6 selection for the update source interface/VIP */
2522
		switch ($dnsupdate['updatesourcefamily']) {
2523
			case "inet":
2524
				$bindip = $bindipv4;
2525
				break;
2526
			case "inet6":
2527
				$bindip = $bindipv6;
2528
				break;
2529
			case "":
2530
			default:
2531
				/* Try IPv4 first, if that is empty, try IPv6. */
2532
				/* Only specify the address if it's present, otherwise omit. */
2533
				if (!empty($bindipv4)) {
2534
					$bindip = $bindipv4;
2535
				} elseif (!empty($bindipv6)) {
2536
					$bindip = $bindipv6;
2537
				}
2538
				break;
2539
		}
2540

    
2541
		$cacheFile = $g['conf_path'] .
2542
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2543
		    escapeshellarg($dnsupdate['host']) .
2544
		    "_{$dnsupdate['server']}.cache";
2545
		$cacheFilev6 = $g['conf_path'] .
2546
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2547
		    escapeshellarg($dnsupdate['host']) .
2548
		    "_{$dnsupdate['server']}_v6.cache";
2549
		$currentTime = time();
2550

    
2551
		if (!$wanip && !$wanipv6) {
2552
			continue;
2553
		}
2554

    
2555
		$keyname = $dnsupdate['keyname'];
2556
		/* trailing dot */
2557
		if (substr($keyname, -1) != ".") {
2558
			$keyname .= ".";
2559
		}
2560

    
2561
		$hostname = $dnsupdate['host'];
2562
		/* trailing dot */
2563
		if (substr($hostname, -1) != ".") {
2564
			$hostname .= ".";
2565
		}
2566

    
2567
		/* write key file */
2568
		$algorithm = empty($dnsupdate['keyalgorithm']) ? 'hmac-md5' : $dnsupdate['keyalgorithm'];
2569
		$upkey = <<<EOD
2570
key "{$keyname}" {
2571
	algorithm {$algorithm};
2572
	secret "{$dnsupdate['keydata']}";
2573
};
2574

    
2575
EOD;
2576
		@file_put_contents("{$g['varetc_path']}/nsupdatekey{$i}", $upkey);
2577

    
2578
		/* generate update instructions */
2579
		$upinst = "";
2580
		if (!empty($dnsupdate['server'])) {
2581
			$upinst .= "server {$dnsupdate['server']}\n";
2582
		}
2583

    
2584
		$cachedipv4 = '';
2585
		$cacheTimev4 = 0;
2586
		if (file_exists($cacheFile)) {
2587
			list($cachedipv4, $cacheTimev4) = explode("|",
2588
			    file_get_contents($cacheFile));
2589
		}
2590
		$cachedipv6 = '';
2591
		$cacheTimev6 = 0;
2592
		if (file_exists($cacheFilev6)) {
2593
			list($cachedipv6, $cacheTimev6) = explode("|",
2594
			    file_get_contents($cacheFilev6));
2595
		}
2596

    
2597
		// 25 Days
2598
		$maxCacheAgeSecs = 25 * 24 * 60 * 60;
2599
		$need_update = false;
2600

    
2601
		/* Update IPv4 if we have it. */
2602
		if (is_ipaddrv4($wanip) && $dnsupdate['recordtype'] != "AAAA") {
2603
			if (($wanip != $cachedipv4) || $forced ||
2604
			    (($currentTime - $cacheTimev4) > $maxCacheAgeSecs)) {
2605
				$upinst .= "update delete " .
2606
				    "{$dnsupdate['host']}. A\n";
2607
				$upinst .= "update add {$dnsupdate['host']}. " .
2608
				    "{$dnsupdate['ttl']} A {$wanip}\n";
2609
				if (!empty($bindip)) {
2610
					$upinst .= "local {$bindip}\n";
2611
				}
2612
				$need_update = true;
2613
			} else {
2614
				log_error(sprintf(gettext(
2615
				    "phpDynDNS: Not updating %s A record because the IP address has not changed."),
2616
				    $dnsupdate['host']));
2617
			}
2618
		} else {
2619
			@unlink($cacheFile);
2620
			unset($cacheFile);
2621
		}
2622

    
2623
		/* Update IPv6 if we have it. */
2624
		if (is_ipaddrv6($wanipv6) && $dnsupdate['recordtype'] != "A") {
2625
			if (($wanipv6 != $cachedipv6) || $forced ||
2626
			    (($currentTime - $cacheTimev6) > $maxCacheAgeSecs)) {
2627
				$upinst .= "update delete " .
2628
				    "{$dnsupdate['host']}. AAAA\n";
2629
				$upinst .= "update add {$dnsupdate['host']}. " .
2630
				    "{$dnsupdate['ttl']} AAAA {$wanipv6}\n";
2631
				$need_update = true;
2632
			} else {
2633
				log_error(sprintf(gettext(
2634
				    "phpDynDNS: Not updating %s AAAA record because the IPv6 address has not changed."),
2635
				    $dnsupdate['host']));
2636
			}
2637
		} else {
2638
			@unlink($cacheFilev6);
2639
			unset($cacheFilev6);
2640
		}
2641

    
2642
		$upinst .= "\n";	/* mind that trailing newline! */
2643

    
2644
		if (!$need_update) {
2645
			continue;
2646
		}
2647

    
2648
		@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}", $upinst);
2649
		unset($upinst);
2650
		/* invoke nsupdate */
2651
		$cmd = "/usr/local/bin/nsupdate -k {$g['varetc_path']}/nsupdatekey{$i}";
2652

    
2653
		if (isset($dnsupdate['usetcp'])) {
2654
			$cmd .= " -v";
2655
		}
2656

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

    
2659
		if (mwexec($cmd) == 0) {
2660
			if (!empty($cacheFile)) {
2661
				@file_put_contents($cacheFile,
2662
				    "{$wanip}|{$currentTime}");
2663
				log_error(sprintf(gettext(
2664
				    'phpDynDNS: updating cache file %1$s: %2$s'),
2665
				    $cacheFile, $wanip));
2666
				$notify_text .= sprintf(gettext(
2667
				    'DynDNS updated IP Address (A) for %1$s on %2$s (%3$s) to %4$s'),
2668
				    $dnsupdate['host'],
2669
				    convert_real_interface_to_friendly_descr($if),
2670
				    $if, $wanip) . "\n";
2671
			}
2672
			if (!empty($cacheFilev6)) {
2673
				@file_put_contents($cacheFilev6,
2674
				    "{$wanipv6}|{$currentTime}");
2675
				log_error(sprintf(gettext(
2676
				    'phpDynDNS: updating cache file %1$s: %2$s'),
2677
				    $cacheFilev6, $wanipv6));
2678
				$notify_text .= sprintf(gettext(
2679
				    'DynDNS updated IPv6 Address (AAAA) for %1$s on %2$s (%3$s) to %4$s'),
2680
				    $dnsupdate['host'],
2681
				    convert_real_interface_to_friendly_descr($if),
2682
				    $if, $wanipv6) . "\n";
2683
			}
2684
		} else {
2685
			if (!empty($cacheFile)) {
2686
				log_error(sprintf(gettext(
2687
				    'phpDynDNS: ERROR while updating IP Address (A) for %1$s (%2$s)'),
2688
				    $dnsupdate['host'], $wanip));
2689
			}
2690
			if (!empty($cacheFilev6)) {
2691
				log_error(sprintf(gettext(
2692
				    'phpDynDNS: ERROR while updating IP Address (AAAA) for %1$s (%2$s)'),
2693
				    $dnsupdate['host'], $wanipv6));
2694
			}
2695
		}
2696
		unset($cmd);
2697
	}
2698

    
2699
	if (!empty($notify_text)) {
2700
		notify_all_remote($notify_text);
2701
	}
2702

    
2703
	return 0;
2704
}
2705

    
2706
/* configure cron service */
2707
function configure_cron() {
2708
	global $g, $config;
2709

    
2710
	/* preserve existing crontab entries */
2711
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2712

    
2713
	for ($i = 0; $i < count($crontab_contents); $i++) {
2714
		$cron_item =& $crontab_contents[$i];
2715
		if (strpos($cron_item, "# pfSense specific crontab entries") !== false) {
2716
			array_splice($crontab_contents, $i - 1);
2717
			break;
2718
		}
2719
	}
2720
	$crontab_contents = implode("\n", $crontab_contents) . "\n";
2721

    
2722

    
2723
	if (is_array($config['cron']['item'])) {
2724
		$crontab_contents .= "#\n";
2725
		$crontab_contents .= "# pfSense specific crontab entries\n";
2726
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
2727
		$crontab_contents .= "#\n";
2728

    
2729
		if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) {
2730
			$http_proxy = $config['system']['proxyurl'];
2731
			if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) {
2732
				$http_proxy .= ':' . $config['system']['proxyport'];
2733
			}
2734
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
2735

    
2736
			if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
2737
				$crontab_contents .= "HTTP_PROXY_AUTH=basic:*:{$config['system']['proxyuser']}:{$config['system']['proxypass']}";
2738
			}
2739
		}
2740

    
2741
		foreach ($config['cron']['item'] as $item) {
2742
			$crontab_contents .= "\n{$item['minute']}\t";
2743
			$crontab_contents .= "{$item['hour']}\t";
2744
			$crontab_contents .= "{$item['mday']}\t";
2745
			$crontab_contents .= "{$item['month']}\t";
2746
			$crontab_contents .= "{$item['wday']}\t";
2747
			$crontab_contents .= "{$item['who']}\t";
2748
			$crontab_contents .= "{$item['command']}";
2749
		}
2750

    
2751
		$crontab_contents .= "\n#\n";
2752
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
2753
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
2754
		$crontab_contents .= "#\n\n";
2755
	}
2756

    
2757
	/* please maintain the newline at the end of file */
2758
	file_put_contents("/etc/crontab", $crontab_contents);
2759
	unset($crontab_contents);
2760

    
2761
	/* make sure that cron is running and start it if it got killed somehow */
2762
	if (!is_process_running("cron")) {
2763
		exec("cd /tmp && /usr/sbin/cron -s 2>/dev/null");
2764
	} else {
2765
	/* do a HUP kill to force sync changes */
2766
		sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP");
2767
	}
2768

    
2769
}
2770

    
2771
function upnp_action ($action) {
2772
	global $g, $config;
2773
	switch ($action) {
2774
		case "start":
2775
			if (file_exists('/var/etc/miniupnpd.conf')) {
2776
				@unlink("{$g['varrun_path']}/miniupnpd.pid");
2777
				mwexec_bg("/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf -P {$g['varrun_path']}/miniupnpd.pid");
2778
			}
2779
			break;
2780
		case "stop":
2781
			killbypid("{$g['varrun_path']}/miniupnpd.pid");
2782
			while ((int)exec("/bin/pgrep -a miniupnpd | wc -l") > 0) {
2783
				mwexec('/usr/bin/killall miniupnpd 2>/dev/null', true);
2784
			}
2785
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
2786
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
2787
			break;
2788
		case "restart":
2789
			upnp_action('stop');
2790
			upnp_action('start');
2791
			break;
2792
	}
2793
}
2794

    
2795
function upnp_start() {
2796
	global $config;
2797

    
2798
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
2799
		return;
2800
	}
2801

    
2802
	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
2803
		echo gettext("Starting UPnP service... ");
2804
		require_once('/usr/local/pkg/miniupnpd.inc');
2805
		sync_package_miniupnpd();
2806
		echo "done.\n";
2807
	}
2808
}
2809

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

    
2813
	$is_installed = false;
2814
	$cron_changed = true;
2815
	$change_message = "";
2816

    
2817
	if (!is_array($config['cron'])) {
2818
		$config['cron'] = array();
2819
	}
2820
	if (!is_array($config['cron']['item'])) {
2821
		$config['cron']['item'] = array();
2822
	}
2823

    
2824
	$x = 0;
2825
	foreach ($config['cron']['item'] as $item) {
2826
		if (strstr($item['command'], $command)) {
2827
			$is_installed = true;
2828
			break;
2829
		}
2830
		$x++;
2831
	}
2832

    
2833
	if ($active) {
2834
		$cron_item = array();
2835
		$cron_item['minute'] = $minute;
2836
		$cron_item['hour'] = $hour;
2837
		$cron_item['mday'] = $monthday;
2838
		$cron_item['month'] = $month;
2839
		$cron_item['wday'] = $weekday;
2840
		$cron_item['who'] = $who;
2841
		$cron_item['command'] = $command;
2842
		if (!$is_installed) {
2843
			$config['cron']['item'][] = $cron_item;
2844
			$change_message = "Installed cron job for %s";
2845
		} else {
2846
			if ($config['cron']['item'][$x] == $cron_item) {
2847
				$cron_changed = false;
2848
			} else {
2849
				$config['cron']['item'][$x] = $cron_item;
2850
				$change_message = "Updated cron job for %s";
2851
			}
2852
		}
2853
	} else {
2854
		if ($is_installed == true) {
2855
			array_splice($config['cron']['item'], $x, 1);
2856
			$change_message = "Removed cron job for %s";
2857
		} else {
2858
			$cron_changed = false;
2859
		}
2860
	}
2861

    
2862
	if ($cron_changed) {
2863
		/* Optionally write the configuration if this function made changes.
2864
		 * Performing a write_config() in this way can have unintended side effects. See #7146
2865
		 * Base system instances of this function do not need to write, packages may.
2866
		 */
2867
		if ($write_config) {
2868
			write_config(sprintf(gettext($change_message), $command));
2869
		}
2870
		configure_cron();
2871
	}
2872
}
2873

    
2874
?>
(41-41/54)