Project

General

Profile

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

    
26

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
444
	unlock($dhcpdconfigurelck);
445
}
446

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

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

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

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

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

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

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

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

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

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

    
535
	$dhcpdconf = <<<EOD
536

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

    
550
EOD;
551

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

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

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

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

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

    
581
		interfaces_staticarp_configure($dhcpif);
582

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

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

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

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

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

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

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

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

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

    
671
		$dnscfg = "";
672

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

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

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

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

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

    
710
			}
711

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

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

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

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

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

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

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

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

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

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

    
851
			$pdnscfg = "";
852

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1073
EOD;
1074

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

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

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

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

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

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

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

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

    
1114
				$smdnscfg = "";
1115

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1214
	return 0;
1215
}
1216

    
1217
function dhcpdkey($dhcpifconf) {
1218
	$dhcpdconf = "";
1219
	if ($dhcpifconf['ddnsdomainkeyname'] <> "" && $dhcpifconf['ddnsdomainkeyalgorithm'] <> "" && $dhcpifconf['ddnsdomainkey'] <> "") {
1220
		$dhcpdconf .= "key {$dhcpifconf['ddnsdomainkeyname']} {\n";
1221
		$dhcpdconf .= "	algorithm {$dhcpifconf['ddnsdomainkeyalgorithm']};\n";
1222
		$dhcpdconf .= "	secret {$dhcpifconf['ddnsdomainkey']};\n";
1223
		$dhcpdconf .= "}\n";
1224
	}
1225

    
1226
	return $dhcpdconf;
1227
}
1228

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

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

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

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

    
1279
	return $dhcpdconf;
1280
}
1281

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

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

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

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

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

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

    
1315

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

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

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

    
1335
	$dhcpdv6conf = <<<EOD
1336

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

    
1349
EOD;
1350

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

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

    
1359
	$dhcpdv6ifs = array();
1360

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

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

    
1366
		$ddns_zones = array();
1367

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

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

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

    
1391
		$dnscfgv6 = "";
1392

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

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

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

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

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

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

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

    
1459
		$dhcpdv6conf .= " {\n";
1460

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

    
1468
		$dhcpdv6conf .= <<<EOD
1469
	range6 {$range_from} {$range_to};
1470
$dnscfgv6
1471

    
1472
EOD;
1473

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

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

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

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

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

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

    
1545
		$dhcpdv6conf .= "}\n";
1546

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

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

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

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

    
1582
				$dhcpdv6conf .= "}\n";
1583
				$i++;
1584
			}
1585
		}
1586

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

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

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

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

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

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

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

    
1646
	return 0;
1647
}
1648

    
1649
function services_igmpproxy_configure() {
1650
	global $config, $g;
1651

    
1652
	/* kill any running igmpproxy */
1653
	killbyname("igmpproxy");
1654

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

    
1659
	$iflist = get_configured_interface_list();
1660

    
1661
	$igmpconf = <<<EOD
1662

    
1663
##------------------------------------------------------
1664
## Enable Quickleave mode (Sends Leave instantly)
1665
##------------------------------------------------------
1666
quickleave
1667

    
1668
EOD;
1669

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

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

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

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

    
1709
	log_error(gettext("Started IGMP proxy service."));
1710

    
1711
	return 0;
1712
}
1713

    
1714
function services_dhcrelay_configure() {
1715
	global $config, $g;
1716

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

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

    
1725
	$dhcrelaycfg =& $config['dhcrelay'];
1726

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

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

    
1738
	$iflist = get_configured_interface_list();
1739

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

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

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

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

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

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

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

    
1782
	$cmd .= " " . implode(" ", $srvips);
1783
	mwexec($cmd);
1784
	unset($cmd);
1785

    
1786
	return 0;
1787
}
1788

    
1789
function services_dhcrelay6_configure() {
1790
	global $config, $g;
1791

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

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

    
1800
	$dhcrelaycfg =& $config['dhcrelay6'];
1801

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

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

    
1813
	$iflist = get_configured_interface_list();
1814

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

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

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

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

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

    
1857
	return 0;
1858
}
1859

    
1860
function services_dyndns_configure_client($conf) {
1861

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

    
1866
	/* load up the dyndns.class */
1867
	require_once("dyndns.class");
1868

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

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

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

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

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

    
1939
	return 0;
1940
}
1941

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

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

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

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

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

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

    
2001

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

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

    
2012
	if (isset($config['dnsmasq']['enable'])) {
2013

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

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

    
2025
		$args = "";
2026

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2149
		system_dhcpleases_configure();
2150

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

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

    
2162
	return $return;
2163
}
2164

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

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

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

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

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

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

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

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

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

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

    
2237
	return $return;
2238
}
2239

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

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

    
2254
	if (isset($config['snmpd']['enable'])) {
2255

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

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

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

    
2272

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

    
2278
EOD;
2279

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

    
2286
EOD;
2287
		}
2288
*/
2289

    
2290

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

    
2298

    
2299
EOD;
2300
		}
2301

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

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

    
2314
EOD;
2315

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

    
2321
EOD;
2322
		}
2323
*/
2324

    
2325

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

    
2332
EOD;
2333
		}
2334

    
2335

    
2336
		$snmpdconf .= <<<EOD
2337
begemotSnmpdCommunityDisable    = 1
2338

    
2339
EOD;
2340

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

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

    
2366
EOD;
2367

    
2368
			}
2369
		}
2370

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

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

    
2380
snmpEnableAuthenTraps = 2
2381

    
2382
EOD;
2383

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

    
2389
EOD;
2390
			}
2391

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

    
2398
EOD;
2399
			}
2400

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

    
2405
EOD;
2406
			}
2407

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

    
2412
EOD;
2413
			}
2414

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

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

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

    
2432
EOD;
2433
			}
2434
		}
2435

    
2436
		fwrite($fd, $snmpdconf);
2437
		fclose($fd);
2438
		unset($snmpdconf);
2439

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

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

    
2449
	return 0;
2450
}
2451

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

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

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

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

    
2497
		if (isset($dnsupdate['usepublicip'])) {
2498
			$wanip = dyndnsCheckIP($if);
2499
			$bindip = get_interface_ip($if);
2500
		} else {
2501
			$wanip = get_interface_ip($if);
2502
			$bindip = $wanip;
2503
		}
2504

    
2505
		$wanipv6 = get_interface_ipv6($if);
2506
		$cacheFile = $g['conf_path'] .
2507
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2508
		    escapeshellarg($dnsupdate['host']) .
2509
		    "_{$dnsupdate['server']}.cache";
2510
		$cacheFilev6 = $g['conf_path'] .
2511
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2512
		    escapeshellarg($dnsupdate['host']) .
2513
		    "_{$dnsupdate['server']}_v6.cache";
2514
		$currentTime = time();
2515

    
2516
		if (!$wanip && !$wanipv6) {
2517
			continue;
2518
		}
2519

    
2520
		$keyname = $dnsupdate['keyname'];
2521
		/* trailing dot */
2522
		if (substr($keyname, -1) != ".") {
2523
			$keyname .= ".";
2524
		}
2525

    
2526
		$hostname = $dnsupdate['host'];
2527
		/* trailing dot */
2528
		if (substr($hostname, -1) != ".") {
2529
			$hostname .= ".";
2530
		}
2531

    
2532
		/*
2533
		 * write private key file
2534
		 * this is dumb - public and private keys are the same for
2535
		 * HMAC-MD5, but nsupdate insists on having both
2536
		 */
2537
		$fd = fopen($g['varetc_path'] .
2538
		    "/K{$i}{$keyname}+157+00000.private", "w");
2539
		$privkey = <<<EOD
2540
Private-key-format: v1.2
2541
Algorithm: 157 (HMAC)
2542
Key: {$dnsupdate['keydata']}
2543

    
2544
EOD;
2545
		fwrite($fd, $privkey);
2546
		fclose($fd);
2547

    
2548
		/* write public key file */
2549
		if ($dnsupdate['keytype'] == "zone") {
2550
			$flags = 257;
2551
			$proto = 3;
2552
		} else if ($dnsupdate['keytype'] == "host") {
2553
			$flags = 513;
2554
			$proto = 3;
2555
		} else if ($dnsupdate['keytype'] == "user") {
2556
			$flags = 0;
2557
			$proto = 2;
2558
		}
2559

    
2560
		$fd = fopen($g['varetc_path'] .
2561
		    "/K{$i}{$keyname}+157+00000.key", "w");
2562
		fwrite($fd, "{$keyname} IN KEY {$flags} {$proto} 157 " .
2563
		    "{$dnsupdate['keydata']}\n");
2564
		fclose($fd);
2565

    
2566
		/* generate update instructions */
2567
		$upinst = "";
2568
		if (!empty($dnsupdate['server'])) {
2569
			$upinst .= "server {$dnsupdate['server']}\n";
2570
		}
2571

    
2572
		$cachedipv4 = '';
2573
		$cacheTimev4 = 0;
2574
		if (file_exists($cacheFile)) {
2575
			list($cachedipv4, $cacheTimev4) = explode("|",
2576
			    file_get_contents($cacheFile));
2577
		}
2578
		$cachedipv6 = '';
2579
		$cacheTimev6 = 0;
2580
		if (file_exists($cacheFilev6)) {
2581
			list($cachedipv6, $cacheTimev6) = explode("|",
2582
			    file_get_contents($cacheFilev6));
2583
		}
2584

    
2585
		// 25 Days
2586
		$maxCacheAgeSecs = 25 * 24 * 60 * 60;
2587
		$need_update = false;
2588

    
2589
		/* Update IPv4 if we have it. */
2590
		if (is_ipaddrv4($wanip) && $dnsupdate['recordtype'] != "AAAA") {
2591
			if (($wanip != $cachedipv4) || $forced ||
2592
			    (($currentTime - $cacheTimev4) > $maxCacheAgeSecs)) {
2593
				$upinst .= "update delete " .
2594
				    "{$dnsupdate['host']}. A\n";
2595
				$upinst .= "update add {$dnsupdate['host']}. " .
2596
				    "{$dnsupdate['ttl']} A {$wanip}\n";
2597
				$upinst .= "local {$bindip}\n";
2598
				$need_update = true;
2599
			} else {
2600
				log_error(sprintf(gettext(
2601
				    "phpDynDNS: Not updating %s A record because the IP address has not changed."),
2602
				    $dnsupdate['host']));
2603
			}
2604
		} else {
2605
			@unlink($cacheFile);
2606
			unset($cacheFile);
2607
		}
2608

    
2609
		/* Update IPv6 if we have it. */
2610
		if (is_ipaddrv6($wanipv6) && $dnsupdate['recordtype'] != "A") {
2611
			if (($wanipv6 != $cachedipv6) || $forced ||
2612
			    (($currentTime - $cacheTimev6) > $maxCacheAgeSecs)) {
2613
				$upinst .= "update delete " .
2614
				    "{$dnsupdate['host']}. AAAA\n";
2615
				$upinst .= "update add {$dnsupdate['host']}. " .
2616
				    "{$dnsupdate['ttl']} AAAA {$wanipv6}\n";
2617
				$need_update = true;
2618
			} else {
2619
				log_error(sprintf(gettext(
2620
				    "phpDynDNS: Not updating %s AAAA record because the IPv6 address has not changed."),
2621
				    $dnsupdate['host']));
2622
			}
2623
		} else {
2624
			@unlink($cacheFilev6);
2625
			unset($cacheFilev6);
2626
		}
2627

    
2628
		$upinst .= "\n";	/* mind that trailing newline! */
2629

    
2630
		if (!$need_update) {
2631
			continue;
2632
		}
2633

    
2634
		@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}",
2635
		    $upinst);
2636
		unset($upinst);
2637
		/* invoke nsupdate */
2638
		$cmd = "/usr/local/bin/nsupdate -k " .
2639
		    "{$g['varetc_path']}/K{$i}{$keyname}+157+00000.key";
2640

    
2641
		if (isset($dnsupdate['usetcp'])) {
2642
			$cmd .= " -v";
2643
		}
2644

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

    
2647
		if (mwexec($cmd) == 0) {
2648
			if (!empty($cacheFile)) {
2649
				@file_put_contents($cacheFile,
2650
				    "{$wanip}|{$currentTime}");
2651
				log_error(sprintf(gettext(
2652
				    'phpDynDNS: updating cache file %1$s: %2$s'),
2653
				    $cacheFile, $wanip));
2654
				$notify_text .= sprintf(gettext(
2655
				    'DynDNS updated IP Address (A) for %1$s on %2$s (%3$s) to %4$s'),
2656
				    $dnsupdate['host'],
2657
				    convert_real_interface_to_friendly_descr($if),
2658
				    $if, $wanip) . "\n";
2659
			}
2660
			if (!empty($cacheFilev6)) {
2661
				@file_put_contents($cacheFilev6,
2662
				    "{$wanipv6}|{$currentTime}");
2663
				log_error(sprintf(gettext(
2664
				    'phpDynDNS: updating cache file %1$s: %2$s'),
2665
				    $cacheFilev6, $wanipv6));
2666
				$notify_text .= sprintf(gettext(
2667
				    'DynDNS updated IPv6 Address (AAAA) for %1$s on %2$s (%3$s) to %4$s'),
2668
				    $dnsupdate['host'],
2669
				    convert_real_interface_to_friendly_descr($if),
2670
				    $if, $wanipv6) . "\n";
2671
			}
2672
		} else {
2673
			if (!empty($cacheFile)) {
2674
				log_error(sprintf(gettext(
2675
				    'phpDynDNS: ERROR while updating IP Address (A) for %1$s (%2$s)'),
2676
				    $dnsupdate['host'], $wanip));
2677
			}
2678
			if (!empty($cacheFilev6)) {
2679
				log_error(sprintf(gettext(
2680
				    'phpDynDNS: ERROR while updating IP Address (AAAA) for %1$s (%2$s)'),
2681
				    $dnsupdate['host'], $wanipv6));
2682
			}
2683
		}
2684
		unset($cmd);
2685
	}
2686

    
2687
	if (!empty($notify_text)) {
2688
		notify_all_remote($notify_text);
2689
	}
2690

    
2691
	return 0;
2692
}
2693

    
2694
/* configure cron service */
2695
function configure_cron() {
2696
	global $g, $config;
2697

    
2698
	/* preserve existing crontab entries */
2699
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2700

    
2701
	for ($i = 0; $i < count($crontab_contents); $i++) {
2702
		$cron_item =& $crontab_contents[$i];
2703
		if (strpos($cron_item, "# pfSense specific crontab entries") !== false) {
2704
			array_splice($crontab_contents, $i - 1);
2705
			break;
2706
		}
2707
	}
2708
	$crontab_contents = implode("\n", $crontab_contents) . "\n";
2709

    
2710

    
2711
	if (is_array($config['cron']['item'])) {
2712
		$crontab_contents .= "#\n";
2713
		$crontab_contents .= "# pfSense specific crontab entries\n";
2714
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
2715
		$crontab_contents .= "#\n";
2716

    
2717
		if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) {
2718
			$http_proxy = $config['system']['proxyurl'];
2719
			if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) {
2720
				$http_proxy .= ':' . $config['system']['proxyport'];
2721
			}
2722
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
2723

    
2724
			if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
2725
				$crontab_contents .= "HTTP_PROXY_AUTH=basic:*:{$config['system']['proxyuser']}:{$config['system']['proxypass']}";
2726
			}
2727
		}
2728

    
2729
		foreach ($config['cron']['item'] as $item) {
2730
			$crontab_contents .= "\n{$item['minute']}\t";
2731
			$crontab_contents .= "{$item['hour']}\t";
2732
			$crontab_contents .= "{$item['mday']}\t";
2733
			$crontab_contents .= "{$item['month']}\t";
2734
			$crontab_contents .= "{$item['wday']}\t";
2735
			$crontab_contents .= "{$item['who']}\t";
2736
			$crontab_contents .= "{$item['command']}";
2737
		}
2738

    
2739
		$crontab_contents .= "\n#\n";
2740
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
2741
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
2742
		$crontab_contents .= "#\n\n";
2743
	}
2744

    
2745
	/* please maintain the newline at the end of file */
2746
	file_put_contents("/etc/crontab", $crontab_contents);
2747
	unset($crontab_contents);
2748

    
2749
	/* make sure that cron is running and start it if it got killed somehow */
2750
	if (!is_process_running("cron")) {
2751
		exec("cd /tmp && /usr/sbin/cron -s 2>/dev/null");
2752
	} else {
2753
	/* do a HUP kill to force sync changes */
2754
		sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP");
2755
	}
2756

    
2757
}
2758

    
2759
function upnp_action ($action) {
2760
	global $g, $config;
2761
	switch ($action) {
2762
		case "start":
2763
			if (file_exists('/var/etc/miniupnpd.conf')) {
2764
				@unlink("{$g['varrun_path']}/miniupnpd.pid");
2765
				mwexec_bg("/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf -P {$g['varrun_path']}/miniupnpd.pid");
2766
			}
2767
			break;
2768
		case "stop":
2769
			killbypid("{$g['varrun_path']}/miniupnpd.pid");
2770
			while ((int)exec("/bin/pgrep -a miniupnpd | wc -l") > 0) {
2771
				mwexec('/usr/bin/killall miniupnpd 2>/dev/null', true);
2772
			}
2773
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
2774
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
2775
			break;
2776
		case "restart":
2777
			upnp_action('stop');
2778
			upnp_action('start');
2779
			break;
2780
	}
2781
}
2782

    
2783
function upnp_start() {
2784
	global $config;
2785

    
2786
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
2787
		return;
2788
	}
2789

    
2790
	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
2791
		echo gettext("Starting UPnP service... ");
2792
		require_once('/usr/local/pkg/miniupnpd.inc');
2793
		sync_package_miniupnpd();
2794
		echo "done.\n";
2795
	}
2796
}
2797

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

    
2801
	$is_installed = false;
2802
	$cron_changed = true;
2803
	$change_message = "";
2804

    
2805
	if (!is_array($config['cron'])) {
2806
		$config['cron'] = array();
2807
	}
2808
	if (!is_array($config['cron']['item'])) {
2809
		$config['cron']['item'] = array();
2810
	}
2811

    
2812
	$x = 0;
2813
	foreach ($config['cron']['item'] as $item) {
2814
		if (strstr($item['command'], $command)) {
2815
			$is_installed = true;
2816
			break;
2817
		}
2818
		$x++;
2819
	}
2820

    
2821
	if ($active) {
2822
		$cron_item = array();
2823
		$cron_item['minute'] = $minute;
2824
		$cron_item['hour'] = $hour;
2825
		$cron_item['mday'] = $monthday;
2826
		$cron_item['month'] = $month;
2827
		$cron_item['wday'] = $weekday;
2828
		$cron_item['who'] = $who;
2829
		$cron_item['command'] = $command;
2830
		if (!$is_installed) {
2831
			$config['cron']['item'][] = $cron_item;
2832
			$change_message = "Installed cron job for %s";
2833
		} else {
2834
			if ($config['cron']['item'][$x] == $cron_item) {
2835
				$cron_changed = false;
2836
			} else {
2837
				$config['cron']['item'][$x] = $cron_item;
2838
				$change_message = "Updated cron job for %s";
2839
			}
2840
		}
2841
	} else {
2842
		if ($is_installed == true) {
2843
			array_splice($config['cron']['item'], $x, 1);
2844
			$change_message = "Removed cron job for %s";
2845
		} else {
2846
			$cron_changed = false;
2847
		}
2848
	}
2849

    
2850
	if ($cron_changed) {
2851
		/* Optionally write the configuration if this function made changes.
2852
		 * Performing a write_config() in this way can have unintended side effects. See #7146
2853
		 * Base system instances of this function do not need to write, packages may.
2854
		 */
2855
		if ($write_config) {
2856
			write_config(sprintf(gettext($change_message), $command));
2857
		}
2858
		configure_cron();
2859
	}
2860
}
2861

    
2862
?>
(42-42/55)