Project

General

Profile

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

    
26

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
444
	unlock($dhcpdconfigurelck);
445
}
446

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

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

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

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

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

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

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

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

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

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

    
535
	$dhcpdconf = <<<EOD
536

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

    
550
EOD;
551

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

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

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

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

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

    
581
		interfaces_staticarp_configure($dhcpif);
582

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

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

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

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

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

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

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

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

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

    
676
		$dnscfg = "";
677

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

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

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

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

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

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

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

    
723
			}
724

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

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

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

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

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

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

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

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

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

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

    
864
			$pdnscfg = "";
865

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1086
EOD;
1087

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

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

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

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

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

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

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

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

    
1127
				$smdnscfg = "";
1128

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1227
	return 0;
1228
}
1229

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

    
1240
	return $dhcpdconf;
1241
}
1242

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

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

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

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

    
1293
	return $dhcpdconf;
1294
}
1295

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

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

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

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

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

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

    
1329

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

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

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

    
1349
	$dhcpdv6conf = <<<EOD
1350

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

    
1363
EOD;
1364

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

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

    
1373
	$dhcpdv6ifs = array();
1374

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

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

    
1380
		$ddns_zones = array();
1381

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

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

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

    
1405
		$dnscfgv6 = "";
1406

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

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

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

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

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

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

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

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

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

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

    
1487
EOD;
1488

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1651
	/* fire up dhcpd in a chroot */
1652
	if (count($dhcpdv6ifs) > 0) {
1653
		mwexec("/usr/local/sbin/dhcpd -6 -user dhcpd -group _dhcp -chroot {$g['dhcpd_chroot_path']} -cf /etc/dhcpdv6.conf -pf {$g['varrun_path']}/dhcpdv6.pid " .
1654
			join(" ", $dhcpdv6ifs));
1655
		mwexec("/usr/local/sbin/dhcpleases6 -c \"/usr/local/bin/php-cgi -f /usr/local/sbin/prefixes.php|/bin/sh\" -l {$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1656
	}
1657
	if (platform_booting()) {
1658
		print gettext("done.") . "\n";
1659
	}
1660

    
1661
	return 0;
1662
}
1663

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

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

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

    
1677
	$iflist = get_configured_interface_list();
1678

    
1679
	$igmpconf = <<<EOD
1680

    
1681
##------------------------------------------------------
1682
## Enable Quickleave mode (Sends Leave instantly)
1683
##------------------------------------------------------
1684
quickleave
1685

    
1686
EOD;
1687

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

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

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

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

    
1727
	log_error(gettext("Started IGMP proxy service."));
1728

    
1729
	return 0;
1730
}
1731

    
1732
function services_dhcrelay_configure() {
1733
	global $config, $g;
1734

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

    
1740
	/* kill any running dhcrelay */
1741
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
1742

    
1743
	$dhcrelaycfg =& $config['dhcrelay'];
1744

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

    
1750
	if (platform_booting()) {
1751
		echo gettext("Starting DHCP relay service...");
1752
	} else {
1753
		sleep(1);
1754
	}
1755

    
1756
	$iflist = get_configured_interface_list();
1757

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

    
1765
		if (is_ipaddr(get_interface_ip($dhcrelayif))) {
1766
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1767
		}
1768
	}
1769

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

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

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

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

    
1796
	if (isset($dhcrelaycfg['agentoption'])) {
1797
		$cmd .= " -a -m replace";
1798
	}
1799

    
1800
	$cmd .= " " . implode(" ", $srvips);
1801
	mwexec($cmd);
1802
	unset($cmd);
1803

    
1804
	return 0;
1805
}
1806

    
1807
function services_dhcrelay6_configure() {
1808
	global $config, $g;
1809

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

    
1815
	/* kill any running dhcrelay */
1816
	killbypid("{$g['varrun_path']}/dhcrelay6.pid");
1817

    
1818
	$dhcrelaycfg =& $config['dhcrelay6'];
1819

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

    
1825
	if (platform_booting()) {
1826
		echo gettext("Starting DHCPv6 relay service...");
1827
	} else {
1828
		sleep(1);
1829
	}
1830

    
1831
	$iflist = get_configured_interface_list();
1832

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

    
1840
		if (is_ipaddrv6(get_interface_ipv6($dhcrelayif))) {
1841
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1842
		}
1843
	}
1844
	$dhcrelayifs = array_unique($dhcrelayifs);
1845

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

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

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

    
1875
	return 0;
1876
}
1877

    
1878
function services_dyndns_configure_client($conf) {
1879

    
1880
	if (!isset($conf['enable'])) {
1881
		return;
1882
	}
1883

    
1884
	/* load up the dyndns.class */
1885
	require_once("dyndns.class");
1886

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

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

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

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

    
1958
		if (platform_booting()) {
1959
			echo gettext("done.") . "\n";
1960
		}
1961
	}
1962

    
1963
	return 0;
1964
}
1965

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

    
1977
		// Append the factory default check IP service to the list (if not disabled).
1978
		if (!isset($config['checkipservices']['disable_factory_default'])) {
1979
			$config['checkipservices']['checkipservice'][] = $factory_default_checkipservice;
1980
		}
1981

    
1982
		// Use the first enabled check IP service as the default.
1983
		if (is_array($config['checkipservices']['checkipservice'])) {
1984
			foreach ($config['checkipservices']['checkipservice'] as $i => $checkipservice) {
1985
				if (isset($checkipservice['enable'])) {
1986
					$url = $checkipservice['url'];
1987
					$username = $checkipservice['username'];
1988
					$password = $checkipservice['password'];
1989
					$verifysslpeer = isset($checkipservice['verifysslpeer']);
1990
					break;
1991
				}
1992
			}
1993
		}
1994

    
1995
		$hosttocheck = $url;
1996
		$ip_ch = curl_init($hosttocheck);
1997
		curl_setopt($ip_ch, CURLOPT_RETURNTRANSFER, 1);
1998
		curl_setopt($ip_ch, CURLOPT_SSL_VERIFYPEER, $verifysslpeer);
1999
		curl_setopt($ip_ch, CURLOPT_INTERFACE, 'host!' . $ip_address);
2000
		curl_setopt($ip_ch, CURLOPT_CONNECTTIMEOUT, '30');
2001
		curl_setopt($ip_ch, CURLOPT_TIMEOUT, 120);
2002
		curl_setopt($ip_ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
2003
		curl_setopt($ip_ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
2004
		curl_setopt($ip_ch, CURLOPT_USERPWD, "{$username}:{$password}");
2005
		$ip_result_page = curl_exec($ip_ch);
2006
		curl_close($ip_ch);
2007
		$ip_result_decoded = urldecode($ip_result_page);
2008
		preg_match('=Current IP Address: (.*)</body>=siU', $ip_result_decoded, $matches);
2009
		$ip_address = trim($matches[1]);
2010
	}
2011
	return $ip_address;
2012
}
2013

    
2014
function services_dnsmasq_configure($restart_dhcp = true) {
2015
	global $config, $g;
2016
	$return = 0;
2017

    
2018
	// hard coded args: will be removed to avoid duplication if specified in custom_options
2019
	$standard_args = array(
2020
		"dns-forward-max" => "--dns-forward-max=5000",
2021
		"cache-size" => "--cache-size=10000",
2022
		"local-ttl" => "--local-ttl=1"
2023
	);
2024

    
2025

    
2026
	if (isset($config['system']['developerspew'])) {
2027
		$mt = microtime();
2028
		echo "services_dnsmasq_configure() being called $mt\n";
2029
	}
2030

    
2031
	/* kill any running dnsmasq */
2032
	if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) {
2033
		sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
2034
	}
2035

    
2036
	if (isset($config['dnsmasq']['enable'])) {
2037

    
2038
		if (platform_booting()) {
2039
			echo gettext("Starting DNS forwarder...");
2040
		} else {
2041
			sleep(1);
2042
		}
2043

    
2044
		/* generate hosts file */
2045
		if (system_hosts_generate() != 0) {
2046
			$return = 1;
2047
		}
2048

    
2049
		$args = "";
2050

    
2051
		if (isset($config['dnsmasq']['regdhcp'])) {
2052
			$args .= " --dhcp-hostsfile={$g['etc_path']}/hosts ";
2053
		}
2054

    
2055
		/* Setup listen port, if non-default */
2056
		if (is_port($config['dnsmasq']['port'])) {
2057
			$args .= " --port={$config['dnsmasq']['port']} ";
2058
		}
2059

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

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

    
2100
			// Build an array of domain overrides to help in checking for matches.
2101
			$override_a = array();
2102
			if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2103
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2104
					$override_a[$override['domain']] = "y";
2105
				}
2106
			}
2107

    
2108
			// Build an array of the private reverse lookup domain names
2109
			$reverse_domain_a = array("10.in-addr.arpa", "168.192.in-addr.arpa");
2110
			// Unfortunately the 172.16.0.0/12 range does not map nicely to the in-addr.arpa scheme.
2111
			for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) {
2112
				$reverse_domain_a[] = "$subnet_num.172.in-addr.arpa";
2113
			}
2114

    
2115
			// Set the --server parameter to nowhere for each reverse domain name that was not specifically specified in a domain override.
2116
			foreach ($reverse_domain_a as $reverse_domain) {
2117
				if (!isset($override_a[$reverse_domain])) {
2118
					$args .= " --server=/$reverse_domain/ ";
2119
				}
2120
			}
2121
			unset($override_a);
2122
			unset($reverse_domain_a);
2123
		}
2124

    
2125
		/* Setup forwarded domains */
2126
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2127
			foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2128
				if ($override['ip'] == "!") {
2129
					$override[ip] = "";
2130
				}
2131
				$args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
2132
			}
2133
		}
2134

    
2135
		/* Allow DNS Rebind for forwarded domains */
2136
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2137
			if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2138
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2139
					$args .= ' --rebind-domain-ok=/' . $override['domain'] . '/ ';
2140
				}
2141
			}
2142
		}
2143

    
2144
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2145
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2146
		}
2147

    
2148
		if (isset($config['dnsmasq']['strict_order'])) {
2149
			$args .= " --strict-order ";
2150
		}
2151

    
2152
		if (isset($config['dnsmasq']['domain_needed'])) {
2153
			$args .= " --domain-needed ";
2154
		}
2155

    
2156
		if ($config['dnsmasq']['custom_options']) {
2157
			foreach (preg_split('/\s+/', $config['dnsmasq']['custom_options']) as $c) {
2158
				$args .= " " . escapeshellarg("--{$c}");
2159
				$p = explode('=', $c);
2160
				if (array_key_exists($p[0], $standard_args)) {
2161
					unset($standard_args[$p[0]]);
2162
				}
2163
			}
2164
		}
2165
		$args .= ' ' . implode(' ', array_values($standard_args));
2166

    
2167
		/* run dnsmasq. Use "-C /dev/null" since we use command line args only (Issue #6730) */
2168
		$cmd = "/usr/local/sbin/dnsmasq --all-servers -C /dev/null {$dns_rebind} {$args}";
2169
		//log_error("dnsmasq command: {$cmd}");
2170
		mwexec_bg($cmd);
2171
		unset($args);
2172

    
2173
		system_dhcpleases_configure();
2174

    
2175
		if (platform_booting()) {
2176
			echo gettext("done.") . "\n";
2177
		}
2178
	}
2179

    
2180
	if (!platform_booting() && $restart_dhcp) {
2181
		if (services_dhcpd_configure() != 0) {
2182
			$return = 1;
2183
		}
2184
	}
2185

    
2186
	return $return;
2187
}
2188

    
2189
function services_unbound_configure($restart_dhcp = true) {
2190
	global $config, $g;
2191
	$return = 0;
2192

    
2193
	if (isset($config['system']['developerspew'])) {
2194
		$mt = microtime();
2195
		echo "services_unbound_configure() being called $mt\n";
2196
	}
2197

    
2198
	if (isset($config['unbound']['enable'])) {
2199
		require_once('/etc/inc/unbound.inc');
2200

    
2201
		/* Stop Unbound using TERM */
2202
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2203
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
2204
		}
2205

    
2206
		/* If unbound is still running, wait up to 30 seconds for it to terminate. */
2207
		for ($i=1; $i <= 30; $i++) {
2208
			if (is_process_running('unbound')) {
2209
				sleep(1);
2210
			}
2211
		}
2212

    
2213
		if (platform_booting()) {
2214
			echo gettext("Starting DNS Resolver...");
2215
		} else {
2216
			sleep(1);
2217
		}
2218

    
2219
		/* generate hosts file */
2220
		if (system_hosts_generate() != 0) {
2221
			$return = 1;
2222
		}
2223

    
2224
		/* Check here for dhcp6 complete - wait upto 10 seconds */
2225
		if($config['interfaces']["wan"]['ipaddrv6'] == 'dhcp6') {
2226
			$wanif = get_real_interface("wan", "inet6");
2227
			if (platform_booting()) {
2228
				for ($i=1; $i <= 10; $i++) {
2229
					if (!file_exists("/tmp/{$wanif}_dhcp6_complete")) {
2230
						log_error(gettext("Unbound start waiting on dhcp6c."));
2231
						sleep(1);
2232
					} else {
2233
						unlink_if_exists("/tmp/{$wanif}_dhcp6_complete");
2234
						log_error(gettext("dhcp6 init complete. Continuing"));
2235
						break;
2236
					}
2237
				}
2238
			}
2239
		}
2240

    
2241
		sync_unbound_service();
2242
		if (platform_booting()) {
2243
			log_error(gettext("sync unbound done."));
2244
			echo gettext("done.") . "\n";
2245
		}
2246

    
2247
		system_dhcpleases_configure();
2248
	} else {
2249
		/* kill Unbound since it should not be enabled */
2250
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2251
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "KILL");
2252
		}
2253
	}
2254

    
2255
	if (!platform_booting() && $restart_dhcp) {
2256
		if (services_dhcpd_configure() != 0) {
2257
			$return = 1;
2258
		}
2259
	}
2260

    
2261
	return $return;
2262
}
2263

    
2264
function services_snmpd_configure() {
2265
	global $config, $g;
2266
	if (isset($config['system']['developerspew'])) {
2267
		$mt = microtime();
2268
		echo "services_snmpd_configure() being called $mt\n";
2269
	}
2270

    
2271
	/* kill any running snmpd */
2272
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
2273
	sleep(2);
2274
	if (is_process_running("bsnmpd")) {
2275
		mwexec("/usr/bin/killall bsnmpd", true);
2276
	}
2277

    
2278
	if (isset($config['snmpd']['enable'])) {
2279

    
2280
		if (platform_booting()) {
2281
			echo gettext("Starting SNMP daemon... ");
2282
		}
2283

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

    
2289
		/* generate snmpd.conf */
2290
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
2291
		if (!$fd) {
2292
			printf(gettext("Error: cannot open snmpd.conf in services_snmpd_configure().%s"), "\n");
2293
			return 1;
2294
		}
2295

    
2296

    
2297
		$snmpdconf = <<<EOD
2298
location := "{$config['snmpd']['syslocation']}"
2299
contact := "{$config['snmpd']['syscontact']}"
2300
read := "{$config['snmpd']['rocommunity']}"
2301

    
2302
EOD;
2303

    
2304
/* No docs on what write strings do there so disable for now.
2305
		if (isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])) {
2306
			$snmpdconf .= <<<EOD
2307
# write string
2308
write := "{$config['snmpd']['rwcommunity']}"
2309

    
2310
EOD;
2311
		}
2312
*/
2313

    
2314

    
2315
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2316
			$snmpdconf .= <<<EOD
2317
# SNMP Trap support.
2318
traphost := {$config['snmpd']['trapserver']}
2319
trapport := {$config['snmpd']['trapserverport']}
2320
trap := "{$config['snmpd']['trapstring']}"
2321

    
2322

    
2323
EOD;
2324
		}
2325

    
2326
		$sysDescr = "{$g['product_name']} " . php_uname("n") .
2327
			" {$g['product_version']} {$g['platform']} " . php_uname("s") .
2328
			" " . php_uname("r") . " " . php_uname("m");
2329

    
2330
		$snmpdconf .= <<<EOD
2331
system := 1     # pfSense
2332
%snmpd
2333
sysDescr			= "{$sysDescr}"
2334
begemotSnmpdDebugDumpPdus       = 2
2335
begemotSnmpdDebugSyslogPri      = 7
2336
begemotSnmpdCommunityString.0.1 = $(read)
2337

    
2338
EOD;
2339

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

    
2345
EOD;
2346
		}
2347
*/
2348

    
2349

    
2350
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2351
			$snmpdconf .= <<<EOD
2352
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
2353
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
2354
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
2355

    
2356
EOD;
2357
		}
2358

    
2359

    
2360
		$snmpdconf .= <<<EOD
2361
begemotSnmpdCommunityDisable    = 1
2362

    
2363
EOD;
2364

    
2365
		$bind_to_ips = array();
2366
		if (isset($config['snmpd']['bindip'])) {
2367
			foreach (explode(",", $config['snmpd']['bindip']) as $bind_to_ip) {
2368
				if (is_ipaddr($bind_to_ip)) {
2369
					$bind_to_ips[] = $bind_to_ip;
2370
				} else {
2371
					$if = get_real_interface($bind_to_ip);
2372
					if (does_interface_exist($if)) {
2373
						$bindip = get_interface_ip($bind_to_ip);
2374
						if (is_ipaddr($bindip)) {
2375
							$bind_to_ips[] = $bindip;
2376
						}
2377
					}
2378
				}
2379
			}
2380
		}
2381
		if (!count($bind_to_ips)) {
2382
			$bind_to_ips = array("0.0.0.0");
2383
		}
2384

    
2385
		if (is_port($config['snmpd']['pollport'])) {
2386
			foreach ($bind_to_ips as $bind_to_ip) {
2387
				$snmpdconf .= <<<EOD
2388
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
2389

    
2390
EOD;
2391

    
2392
			}
2393
		}
2394

    
2395
		$snmpdconf .= <<<EOD
2396
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
2397
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
2398

    
2399
# These are bsnmp macros not php vars.
2400
sysContact      = $(contact)
2401
sysLocation     = $(location)
2402
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
2403

    
2404
snmpEnableAuthenTraps = 2
2405

    
2406
EOD;
2407

    
2408
		if (is_array($config['snmpd']['modules'])) {
2409
			if (isset($config['snmpd']['modules']['mibii'])) {
2410
			$snmpdconf .= <<<EOD
2411
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
2412

    
2413
EOD;
2414
			}
2415

    
2416
			if (isset($config['snmpd']['modules']['netgraph'])) {
2417
				$snmpdconf .= <<<EOD
2418
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
2419
%netgraph
2420
begemotNgControlNodeName = "snmpd"
2421

    
2422
EOD;
2423
			}
2424

    
2425
			if (isset($config['snmpd']['modules']['pf'])) {
2426
				$snmpdconf .= <<<EOD
2427
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
2428

    
2429
EOD;
2430
			}
2431

    
2432
			if (isset($config['snmpd']['modules']['hostres'])) {
2433
				$snmpdconf .= <<<EOD
2434
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
2435

    
2436
EOD;
2437
			}
2438

    
2439
			if (isset($config['snmpd']['modules']['bridge'])) {
2440
				$snmpdconf .= <<<EOD
2441
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
2442
# config must end with blank line
2443

    
2444
EOD;
2445
			}
2446
			if (isset($config['snmpd']['modules']['ucd'])) {
2447
				$snmpdconf .= <<<EOD
2448
begemotSnmpdModulePath."ucd"     = "/usr/local/lib/snmp_ucd.so"
2449

    
2450
EOD;
2451
			}
2452
			if (isset($config['snmpd']['modules']['regex'])) {
2453
				$snmpdconf .= <<<EOD
2454
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"
2455

    
2456
EOD;
2457
			}
2458
		}
2459

    
2460
		fwrite($fd, $snmpdconf);
2461
		fclose($fd);
2462
		unset($snmpdconf);
2463

    
2464
		/* run bsnmpd */
2465
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
2466
			" -p {$g['varrun_path']}/snmpd.pid");
2467

    
2468
		if (platform_booting()) {
2469
			echo gettext("done.") . "\n";
2470
		}
2471
	}
2472

    
2473
	return 0;
2474
}
2475

    
2476
function services_dnsupdate_process($int = "", $updatehost = "", $forced = false) {
2477
	global $config, $g;
2478
	if (isset($config['system']['developerspew'])) {
2479
		$mt = microtime();
2480
		echo "services_dnsupdate_process() being called $mt\n";
2481
	}
2482

    
2483
	/* Dynamic DNS updating active? */
2484
	if (!is_array($config['dnsupdates']['dnsupdate'])) {
2485
		return 0;
2486
	}
2487

    
2488
	$notify_text = "";
2489
	$gwgroups = return_gateway_groups_array();
2490
	foreach ($config['dnsupdates']['dnsupdate'] as $i => $dnsupdate) {
2491
		if (!isset($dnsupdate['enable'])) {
2492
			continue;
2493
		}
2494
		/*
2495
		 * If it's using a gateway group, check if interface is
2496
		 * the active gateway for that group
2497
		 */
2498
		$group_int = '';
2499
		$friendly_group_int = '';
2500
		$gwgroup_member = false;
2501
		if (is_array($gwgroups[$dnsupdate['interface']])) {
2502
			if (!empty($gwgroups[$dnsupdate['interface']][0]['vip'])) {
2503
				$group_int = $gwgroups[$dnsupdate['interface']][0]['vip'];
2504
			} else {
2505
				$group_int = $gwgroups[$dnsupdate['interface']][0]['int'];
2506
				$friendly_group_int =
2507
				    convert_real_interface_to_friendly_interface_name(
2508
					$group_int);
2509
				if (!empty($int)) {
2510
					$gwgroup_member =
2511
					    interface_gateway_group_member(get_real_interface($int),
2512
					    $dnsupdate['interface']);
2513
				}
2514
			}
2515
		}
2516
		if (!empty($int) && ($int != $dnsupdate['interface']) && !$gwgroup_member &&
2517
		    ($int != $group_int) && ($int != $friendly_group_int)) {
2518
			continue;
2519
		}
2520
		if (!empty($updatehost) && ($updatehost != $dnsupdate['host'])) {
2521
			continue;
2522
		}
2523

    
2524
		/* determine interface name */
2525
		$if = get_failover_interface($dnsupdate['interface']);
2526

    
2527
		/* Determine address to update and default binding address */
2528
		if (isset($dnsupdate['usepublicip'])) {
2529
			$wanip = dyndnsCheckIP($if);
2530
			$bindipv4 = get_interface_ip($if);
2531
		} else {
2532
			$wanip = get_interface_ip($if);
2533
			$bindipv4 = $wanip;
2534
		}
2535
		$wanipv6 = get_interface_ipv6($if);
2536
		$bindipv6 = $wanipv6;
2537

    
2538
		/* Handle non-default interface bindings */
2539
		if ($dnsupdate['updatesource'] == "none") {
2540
			/* When empty, the directive will be omitted. */
2541
			$bindipv4 = "";
2542
			$bindipv6 = "";
2543
		} elseif (!empty($dnsupdate['updatesource'])) {
2544
			/* Find the alternate binding address */
2545
			$bindipv4 = get_interface_ip($dnsupdate['updatesource']);
2546
			$bindipv6 = get_interface_ipv6($dnsupdate['updatesource']);
2547
		}
2548

    
2549
		/* Handle IPv4/IPv6 selection for the update source interface/VIP */
2550
		switch ($dnsupdate['updatesourcefamily']) {
2551
			case "inet":
2552
				$bindip = $bindipv4;
2553
				break;
2554
			case "inet6":
2555
				$bindip = $bindipv6;
2556
				break;
2557
			case "":
2558
			default:
2559
				/* Try IPv4 first, if that is empty, try IPv6. */
2560
				/* Only specify the address if it's present, otherwise omit. */
2561
				if (!empty($bindipv4)) {
2562
					$bindip = $bindipv4;
2563
				} elseif (!empty($bindipv6)) {
2564
					$bindip = $bindipv6;
2565
				}
2566
				break;
2567
		}
2568

    
2569
		$cacheFile = $g['conf_path'] .
2570
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2571
		    escapeshellarg($dnsupdate['host']) .
2572
		    "_{$dnsupdate['server']}.cache";
2573
		$cacheFilev6 = $g['conf_path'] .
2574
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2575
		    escapeshellarg($dnsupdate['host']) .
2576
		    "_{$dnsupdate['server']}_v6.cache";
2577
		$currentTime = time();
2578

    
2579
		if (!$wanip && !$wanipv6) {
2580
			continue;
2581
		}
2582

    
2583
		$keyname = $dnsupdate['keyname'];
2584
		/* trailing dot */
2585
		if (substr($keyname, -1) != ".") {
2586
			$keyname .= ".";
2587
		}
2588

    
2589
		$hostname = $dnsupdate['host'];
2590
		/* trailing dot */
2591
		if (substr($hostname, -1) != ".") {
2592
			$hostname .= ".";
2593
		}
2594

    
2595
		/* write key file */
2596
		$algorithm = empty($dnsupdate['keyalgorithm']) ? 'hmac-md5' : $dnsupdate['keyalgorithm'];
2597
		$upkey = <<<EOD
2598
key "{$keyname}" {
2599
	algorithm {$algorithm};
2600
	secret "{$dnsupdate['keydata']}";
2601
};
2602

    
2603
EOD;
2604
		@file_put_contents("{$g['varetc_path']}/nsupdatekey{$i}", $upkey);
2605

    
2606
		/* generate update instructions */
2607
		$upinst = "";
2608
		if (!empty($dnsupdate['server'])) {
2609
			$upinst .= "server {$dnsupdate['server']}\n";
2610
		}
2611

    
2612
		$cachedipv4 = '';
2613
		$cacheTimev4 = 0;
2614
		if (file_exists($cacheFile)) {
2615
			list($cachedipv4, $cacheTimev4) = explode("|",
2616
			    file_get_contents($cacheFile));
2617
		}
2618
		$cachedipv6 = '';
2619
		$cacheTimev6 = 0;
2620
		if (file_exists($cacheFilev6)) {
2621
			list($cachedipv6, $cacheTimev6) = explode("|",
2622
			    file_get_contents($cacheFilev6));
2623
		}
2624

    
2625
		// 25 Days
2626
		$maxCacheAgeSecs = 25 * 24 * 60 * 60;
2627
		$need_update = false;
2628

    
2629
		/* Update IPv4 if we have it. */
2630
		if (is_ipaddrv4($wanip) && $dnsupdate['recordtype'] != "AAAA") {
2631
			if (($wanip != $cachedipv4) || $forced ||
2632
			    (($currentTime - $cacheTimev4) > $maxCacheAgeSecs)) {
2633
				$upinst .= "update delete " .
2634
				    "{$dnsupdate['host']}. A\n";
2635
				$upinst .= "update add {$dnsupdate['host']}. " .
2636
				    "{$dnsupdate['ttl']} A {$wanip}\n";
2637
				if (!empty($bindip)) {
2638
					$upinst .= "local {$bindip}\n";
2639
				}
2640
				$need_update = true;
2641
			} else {
2642
				log_error(sprintf(gettext(
2643
				    "phpDynDNS: Not updating %s A record because the IP address has not changed."),
2644
				    $dnsupdate['host']));
2645
			}
2646
		} else {
2647
			@unlink($cacheFile);
2648
			unset($cacheFile);
2649
		}
2650

    
2651
		/* Update IPv6 if we have it. */
2652
		if (is_ipaddrv6($wanipv6) && $dnsupdate['recordtype'] != "A") {
2653
			if (($wanipv6 != $cachedipv6) || $forced ||
2654
			    (($currentTime - $cacheTimev6) > $maxCacheAgeSecs)) {
2655
				$upinst .= "update delete " .
2656
				    "{$dnsupdate['host']}. AAAA\n";
2657
				$upinst .= "update add {$dnsupdate['host']}. " .
2658
				    "{$dnsupdate['ttl']} AAAA {$wanipv6}\n";
2659
				$need_update = true;
2660
			} else {
2661
				log_error(sprintf(gettext(
2662
				    "phpDynDNS: Not updating %s AAAA record because the IPv6 address has not changed."),
2663
				    $dnsupdate['host']));
2664
			}
2665
		} else {
2666
			@unlink($cacheFilev6);
2667
			unset($cacheFilev6);
2668
		}
2669

    
2670
		$upinst .= "\n";	/* mind that trailing newline! */
2671

    
2672
		if (!$need_update) {
2673
			continue;
2674
		}
2675

    
2676
		@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}", $upinst);
2677
		unset($upinst);
2678
		/* invoke nsupdate */
2679
		$cmd = "/usr/local/bin/nsupdate -k {$g['varetc_path']}/nsupdatekey{$i}";
2680

    
2681
		if (isset($dnsupdate['usetcp'])) {
2682
			$cmd .= " -v";
2683
		}
2684

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

    
2687
		if (mwexec($cmd) == 0) {
2688
			if (!empty($cacheFile)) {
2689
				@file_put_contents($cacheFile,
2690
				    "{$wanip}|{$currentTime}");
2691
				log_error(sprintf(gettext(
2692
				    'phpDynDNS: updating cache file %1$s: %2$s'),
2693
				    $cacheFile, $wanip));
2694
				$notify_text .= sprintf(gettext(
2695
				    'DynDNS updated IP Address (A) for %1$s on %2$s (%3$s) to %4$s'),
2696
				    $dnsupdate['host'],
2697
				    convert_real_interface_to_friendly_descr($if),
2698
				    $if, $wanip) . "\n";
2699
			}
2700
			if (!empty($cacheFilev6)) {
2701
				@file_put_contents($cacheFilev6,
2702
				    "{$wanipv6}|{$currentTime}");
2703
				log_error(sprintf(gettext(
2704
				    'phpDynDNS: updating cache file %1$s: %2$s'),
2705
				    $cacheFilev6, $wanipv6));
2706
				$notify_text .= sprintf(gettext(
2707
				    'DynDNS updated IPv6 Address (AAAA) for %1$s on %2$s (%3$s) to %4$s'),
2708
				    $dnsupdate['host'],
2709
				    convert_real_interface_to_friendly_descr($if),
2710
				    $if, $wanipv6) . "\n";
2711
			}
2712
		} else {
2713
			if (!empty($cacheFile)) {
2714
				log_error(sprintf(gettext(
2715
				    'phpDynDNS: ERROR while updating IP Address (A) for %1$s (%2$s)'),
2716
				    $dnsupdate['host'], $wanip));
2717
			}
2718
			if (!empty($cacheFilev6)) {
2719
				log_error(sprintf(gettext(
2720
				    'phpDynDNS: ERROR while updating IP Address (AAAA) for %1$s (%2$s)'),
2721
				    $dnsupdate['host'], $wanipv6));
2722
			}
2723
		}
2724
		unset($cmd);
2725
	}
2726

    
2727
	if (!empty($notify_text)) {
2728
		notify_all_remote($notify_text);
2729
	}
2730

    
2731
	return 0;
2732
}
2733

    
2734
/* configure cron service */
2735
function configure_cron() {
2736
	global $g, $config;
2737

    
2738
	/* preserve existing crontab entries */
2739
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2740

    
2741
	for ($i = 0; $i < count($crontab_contents); $i++) {
2742
		$cron_item =& $crontab_contents[$i];
2743
		if (strpos($cron_item, "# pfSense specific crontab entries") !== false) {
2744
			array_splice($crontab_contents, $i - 1);
2745
			break;
2746
		}
2747
	}
2748
	$crontab_contents = implode("\n", $crontab_contents) . "\n";
2749

    
2750

    
2751
	if (is_array($config['cron']['item'])) {
2752
		$crontab_contents .= "#\n";
2753
		$crontab_contents .= "# pfSense specific crontab entries\n";
2754
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
2755
		$crontab_contents .= "#\n";
2756

    
2757
		if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) {
2758
			$http_proxy = $config['system']['proxyurl'];
2759
			if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) {
2760
				$http_proxy .= ':' . $config['system']['proxyport'];
2761
			}
2762
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
2763

    
2764
			if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
2765
				$crontab_contents .= "HTTP_PROXY_AUTH=basic:*:{$config['system']['proxyuser']}:{$config['system']['proxypass']}";
2766
			}
2767
		}
2768

    
2769
		foreach ($config['cron']['item'] as $item) {
2770
			$crontab_contents .= "\n{$item['minute']}\t";
2771
			$crontab_contents .= "{$item['hour']}\t";
2772
			$crontab_contents .= "{$item['mday']}\t";
2773
			$crontab_contents .= "{$item['month']}\t";
2774
			$crontab_contents .= "{$item['wday']}\t";
2775
			$crontab_contents .= "{$item['who']}\t";
2776
			$crontab_contents .= "{$item['command']}";
2777
		}
2778

    
2779
		$crontab_contents .= "\n#\n";
2780
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
2781
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
2782
		$crontab_contents .= "#\n\n";
2783
	}
2784

    
2785
	/* please maintain the newline at the end of file */
2786
	file_put_contents("/etc/crontab", $crontab_contents);
2787
	unset($crontab_contents);
2788

    
2789
	/* make sure that cron is running and start it if it got killed somehow */
2790
	if (!is_process_running("cron")) {
2791
		exec("cd /tmp && /usr/sbin/cron -s 2>/dev/null");
2792
	} else {
2793
	/* do a HUP kill to force sync changes */
2794
		sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP");
2795
	}
2796

    
2797
}
2798

    
2799
function upnp_action ($action) {
2800
	global $g, $config;
2801
	switch ($action) {
2802
		case "start":
2803
			if (file_exists('/var/etc/miniupnpd.conf')) {
2804
				@unlink("{$g['varrun_path']}/miniupnpd.pid");
2805
				mwexec_bg("/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf -P {$g['varrun_path']}/miniupnpd.pid");
2806
			}
2807
			break;
2808
		case "stop":
2809
			killbypid("{$g['varrun_path']}/miniupnpd.pid");
2810
			while ((int)exec("/bin/pgrep -a miniupnpd | wc -l") > 0) {
2811
				mwexec('/usr/bin/killall miniupnpd 2>/dev/null', true);
2812
			}
2813
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
2814
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
2815
			break;
2816
		case "restart":
2817
			upnp_action('stop');
2818
			upnp_action('start');
2819
			break;
2820
	}
2821
}
2822

    
2823
function upnp_start() {
2824
	global $config;
2825

    
2826
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
2827
		return;
2828
	}
2829

    
2830
	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
2831
		echo gettext("Starting UPnP service... ");
2832
		require_once('/usr/local/pkg/miniupnpd.inc');
2833
		sync_package_miniupnpd();
2834
		echo "done.\n";
2835
	}
2836
}
2837

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

    
2841
	$is_installed = false;
2842
	$cron_changed = true;
2843
	$change_message = "";
2844

    
2845
	if (!is_array($config['cron'])) {
2846
		$config['cron'] = array();
2847
	}
2848
	if (!is_array($config['cron']['item'])) {
2849
		$config['cron']['item'] = array();
2850
	}
2851

    
2852
	$x = 0;
2853
	foreach ($config['cron']['item'] as $item) {
2854
		if (strstr($item['command'], $command)) {
2855
			$is_installed = true;
2856
			break;
2857
		}
2858
		$x++;
2859
	}
2860

    
2861
	if ($active) {
2862
		$cron_item = array();
2863
		$cron_item['minute'] = $minute;
2864
		$cron_item['hour'] = $hour;
2865
		$cron_item['mday'] = $monthday;
2866
		$cron_item['month'] = $month;
2867
		$cron_item['wday'] = $weekday;
2868
		$cron_item['who'] = $who;
2869
		$cron_item['command'] = $command;
2870
		if (!$is_installed) {
2871
			$config['cron']['item'][] = $cron_item;
2872
			$change_message = "Installed cron job for %s";
2873
		} else {
2874
			if ($config['cron']['item'][$x] == $cron_item) {
2875
				$cron_changed = false;
2876
			} else {
2877
				$config['cron']['item'][$x] = $cron_item;
2878
				$change_message = "Updated cron job for %s";
2879
			}
2880
		}
2881
	} else {
2882
		if ($is_installed == true) {
2883
			array_splice($config['cron']['item'], $x, 1);
2884
			$change_message = "Removed cron job for %s";
2885
		} else {
2886
			$cron_changed = false;
2887
		}
2888
	}
2889

    
2890
	if ($cron_changed) {
2891
		/* Optionally write the configuration if this function made changes.
2892
		 * Performing a write_config() in this way can have unintended side effects. See #7146
2893
		 * Base system instances of this function do not need to write, packages may.
2894
		 */
2895
		if ($write_config) {
2896
			write_config(sprintf(gettext($change_message), $command));
2897
		}
2898
		configure_cron();
2899
	}
2900
}
2901

    
2902
?>
(44-44/58)