Project

General

Profile

Download (85.9 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 Electric Sheep Fencing, LLC
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
define('DYNDNS_PROVIDER_VALUES', 'citynetwork cloudflare cloudflare-v6 custom custom-v6 dnsexit dnsimple dnsmadeeasy dnsomatic dyndns dyndns-custom dyndns-static dyns easydns eurodns freedns freedns-v6 glesys googledomains gratisdns he-net he-net-v6 he-net-tunnelbroker loopia namecheap noip noip-free ods opendns ovh-dynhost route53 selfhost spdyn spdyn-v6 zoneedit');
27
define('DYNDNS_PROVIDER_DESCRIPTIONS', 'City Network,CloudFlare,CloudFlare (v6),Custom,Custom (v6),DNSexit,DNSimple,DNS Made Easy,DNS-O-Matic,DynDNS (dynamic),DynDNS (custom),DynDNS (static),DyNS,easyDNS,Euro Dns,freeDNS,freeDNS (v6),GleSYS,Google Domains,GratisDNS,HE.net,HE.net (v6),HE.net Tunnelbroker,Loopia,Namecheap,No-IP,No-IP (free),ODS.org,OpenDNS,OVH DynHOST,Route 53,SelfHost,SPDYN,SPDYN (v6),ZoneEdit');
28

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
274
	/* handle DHCP-PD prefixes and 6RD dynamic interfaces */
275
	foreach ($Iflist as $if => $ifdescr) {
276
		if (!isset($config['interfaces'][$if]['track6-interface']) ||
277
		    !isset($config['interfaces'][$if]['ipaddrv6']) ||
278
		    $config['interfaces'][$if]['ipaddrv6'] != 'track6') {
279
			continue;
280
		}
281
		if (!isset($config['interfaces'][$if]['enable'])) {
282
			continue;
283
		}
284
		if ($config['dhcpdv6'][$if]['ramode'] == "disabled") {
285
			continue;
286
		}
287
		/* Do not put in the config an interface which is down */
288
		if (isset($blacklist[$if])) {
289
			continue;
290
		}
291
		$trackif = $config['interfaces'][$if]['track6-interface'];
292
		if (empty($config['interfaces'][$trackif])) {
293
			continue;
294
		}
295

    
296
		$realif = get_real_interface($if, "inet6");
297

    
298
		/* prevent duplicate entries, manual overrides */
299
		if (isset($radvdifs[$realif])) {
300
			continue;
301
		}
302

    
303
		$ifcfgipv6 = get_interface_ipv6($if);
304
		if (!is_ipaddrv6($ifcfgipv6)) {
305
			$subnetv6 = "::";
306
			$ifcfgsnv6 = "64";
307
		} else {
308
			$ifcfgsnv6 = get_interface_subnetv6($if);
309
			$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
310
		}
311
		$radvdifs[$realif] = $realif;
312

    
313
		$autotype = $config['interfaces'][$trackif]['ipaddrv6'];
314

    
315
		if ($g['debug']) {
316
			log_error("configuring RA on {$if} for type {$autotype} radvd subnet {$subnetv6}/{$ifcfgsnv6}");
317
		}
318

    
319
		$radvdconf .= "# Generated config for {$autotype} delegation from {$trackif} on {$if}\n";
320
		$radvdconf .= "interface {$realif} {\n";
321
		$radvdconf .= "\tAdvSendAdvert on;\n";
322
		if (is_numericint($dhcpv6ifconf['raminrtradvinterval'])) {
323
			$radvdconf .= "\tMinRtrAdvInterval {$dhcpv6ifconf['raminrtradvinterval']};\n";
324
		} else {
325
			$radvdconf .= "\tMinRtrAdvInterval 5;\n";
326
                }
327
		if (is_numericint($dhcpv6ifconf['ramaxrtradvinterval'])) {
328
			$radvdconf .= "\tMaxRtrAdvInterval {$dhcpv6ifconf['ramaxrtradvinterval']};\n";
329
		} else {
330
			$radvdconf .= "\tMaxRtrAdvInterval 10;\n";
331
		}
332
		$mtu = get_interface_mtu($realif);
333
		if (is_numeric($mtu)) {
334
			$radvdconf .= "\tAdvLinkMTU {$mtu};\n";
335
		} else {
336
			$radvdconf .= "\tAdvLinkMTU 1280;\n";
337
		}
338
		$radvdconf .= "\tAdvOtherConfigFlag on;\n";
339
		$radvdconf .= "\tprefix {$subnetv6}/{$ifcfgsnv6} {\n";
340
		$radvdconf .= "\t\tAdvOnLink on;\n";
341
		$radvdconf .= "\t\tAdvAutonomous on;\n";
342
		$radvdconf .= "\t\tAdvRouterAddr on;\n";
343
		$radvdconf .= "\t};\n";
344

    
345
		/* add DNS servers */
346
		$dnslist = array();
347
		if (isset($config['dnsmasq']['enable']) || isset($config['unbound']['enable'])) {
348
			$dnslist[] = $ifcfgipv6;
349
		} elseif (is_array($config['system']['dnsserver']) && !empty($config['system']['dnsserver'])) {
350
			foreach ($config['system']['dnsserver'] as $server) {
351
				if (is_ipaddrv6($server)) {
352
					$dnslist[] = $server;
353
				}
354
			}
355
		}
356
		if (count($dnslist) > 0) {
357
			$dnsstring = implode(" ", $dnslist);
358
			if (!empty($dnsstring)) {
359
				$radvdconf .= "\tRDNSS {$dnsstring} { };\n";
360
			}
361
		}
362
		if (!empty($config['system']['domain'])) {
363
			$radvdconf .= "\tDNSSL {$config['system']['domain']} { };\n";
364
		}
365
		$radvdconf .= "};\n";
366
	}
367

    
368
	/* write radvd.conf */
369
	if (!@file_put_contents("{$g['varetc_path']}/radvd.conf", $radvdconf)) {
370
		log_error(gettext("Error: cannot open radvd.conf in services_radvd_configure()."));
371
		if (platform_booting()) {
372
			printf("Error: cannot open radvd.conf in services_radvd_configure().\n");
373
		}
374
	}
375
	unset($radvdconf);
376

    
377
	if (count($radvdifs) > 0) {
378
		if (isvalidpid("{$g['varrun_path']}/radvd.pid")) {
379
			sigkillbypid("{$g['varrun_path']}/radvd.pid", "HUP");
380
		} else {
381
			mwexec("/usr/local/sbin/radvd -p {$g['varrun_path']}/radvd.pid -C {$g['varetc_path']}/radvd.conf -m syslog");
382
		}
383
	} else {
384
		/* we need to shut down the radvd cleanly, it will send out the prefix
385
		 * information with a lifetime of 0 to notify clients of a (possible) new prefix */
386
		if (isvalidpid("{$g['varrun_path']}/radvd.pid")) {
387
			log_error(gettext("Shutting down Router Advertisment daemon cleanly"));
388
			killbypid("{$g['varrun_path']}/radvd.pid");
389
			@unlink("{$g['varrun_path']}/radvd.pid");
390
		}
391
	}
392
	return 0;
393
}
394

    
395
function services_dhcpd_configure($family = "all", $blacklist = array()) {
396
	global $config, $g;
397

    
398
	$dhcpdconfigurelck = lock("dhcpdconfigure", LOCK_EX);
399

    
400
	/* configure DHCPD chroot once */
401
	$fd = fopen("{$g['tmp_path']}/dhcpd.sh", "w");
402
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}\n");
403
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/dev\n");
404
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/etc\n");
405
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/usr/local/sbin\n");
406
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db\n");
407
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run\n");
408
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/usr\n");
409
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/lib\n");
410
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/run\n");
411
	fwrite($fd, "/usr/sbin/chown -R dhcpd:_dhcp {$g['dhcpd_chroot_path']}/*\n");
412
	fwrite($fd, "/bin/cp -n /lib/libc.so.* {$g['dhcpd_chroot_path']}/lib/\n");
413
	fwrite($fd, "/bin/cp -n /usr/local/sbin/dhcpd {$g['dhcpd_chroot_path']}/usr/local/sbin/\n");
414
	fwrite($fd, "/bin/chmod a+rx {$g['dhcpd_chroot_path']}/usr/local/sbin/dhcpd\n");
415

    
416
	$status = `/sbin/mount | /usr/bin/grep -v grep | /usr/bin/grep "{$g['dhcpd_chroot_path']}/dev"`;
417
	if (!trim($status)) {
418
		fwrite($fd, "/sbin/mount -t devfs devfs {$g['dhcpd_chroot_path']}/dev\n");
419
	}
420
	fclose($fd);
421
	mwexec("/bin/sh {$g['tmp_path']}/dhcpd.sh");
422

    
423
	if ($family == "all" || $family == "inet") {
424
		services_dhcpdv4_configure();
425
	}
426
	if ($family == "all" || $family == "inet6") {
427
		services_dhcpdv6_configure($blacklist);
428
		services_radvd_configure($blacklist);
429
	}
430

    
431
	unlock($dhcpdconfigurelck);
432
}
433

    
434
function services_dhcpdv4_configure() {
435
	global $config, $g;
436
	$need_ddns_updates = false;
437
	$ddns_zones = array();
438

    
439
	if ($g['services_dhcp_server_enable'] == false) {
440
		return;
441
	}
442

    
443
	if (isset($config['system']['developerspew'])) {
444
		$mt = microtime();
445
		echo "services_dhcpdv4_configure($if) being called $mt\n";
446
	}
447

    
448
	/* kill any running dhcpd */
449
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid")) {
450
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid");
451
	}
452

    
453
	/* DHCP enabled on any interfaces? */
454
	if (!is_dhcp_server_enabled()) {
455
		return 0;
456
	}
457

    
458
	/* if OLSRD is enabled, allow WAN to house DHCP. */
459
	if (!function_exists('is_package_installed')) {
460
		require_once('pkg-utils.inc');
461
	}
462
	if (is_package_installed('olsrd') && isset($config['installedpackages']['olsrd'])) {
463
		foreach ($config['installedpackages']['olsrd']['config'] as $olsrd) {
464
			if (isset($olsrd['enable']) && $olsrd['enable'] == "on") {
465
				$is_olsr_enabled = true;
466
				break;
467
			}
468
		}
469
	}
470

    
471
	if (platform_booting()) {
472
		/* restore the leases, if we have them */
473
		if (file_exists("{$g['cf_conf_path']}/dhcpleases.tgz")) {
474
			$dhcprestore = "";
475
			$dhcpreturn = "";
476
			exec("cd /;LANG=C /usr/bin/tar -xzf {$g['cf_conf_path']}/dhcpleases.tgz 2>&1", $dhcprestore, $dhcpreturn);
477
			$dhcprestore = implode(" ", $dhcprestore);
478
			if ($dhcpreturn <> 0) {
479
				log_error(sprintf(gettext('DHCP leases restore failed exited with %1$s, the error is: %2$s%3$s'), $dhcpreturn, $dhcprestore, "\n"));
480
			}
481
		}
482
		/* If this backup is still there on a full install, but we aren't going to use ram disks, remove the archive since this is a transition. */
483
		if (($g['platform'] == $g['product_name']) && !isset($config['system']['use_mfs_tmpvar'])) {
484
			unlink_if_exists("{$g['cf_conf_path']}/dhcpleases.tgz");
485
		}
486
	}
487

    
488
	$syscfg = $config['system'];
489
	if (!is_array($config['dhcpd'])) {
490
		$config['dhcpd'] = array();
491
	}
492
	$dhcpdcfg = $config['dhcpd'];
493
	$Iflist = get_configured_interface_list();
494

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

    
505
	if (platform_booting()) {
506
		echo gettext("Starting DHCP service...");
507
	} else {
508
		sleep(1);
509
	}
510

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

    
539
	$dhcpdconf = <<<EOD
540

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

    
555
EOD;
556

    
557
	if (!isset($dhcpifconf['disableauthoritative'])) {
558
		$dhcpdconf .= "authoritative;\n";
559
	}
560

    
561
	if (isset($dhcpifconf['alwaysbroadcast'])) {
562
		$dhcpdconf .= "always-broadcast on\n";
563
	}
564

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

    
577
	/*    loop through and determine if we need to setup
578
	 *    failover peer "bleh" entries
579
	 */
580
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
581

    
582
		if (!isset($config['interfaces'][$dhcpif]['enable'])) {
583
			continue;
584
		}
585

    
586
		interfaces_staticarp_configure($dhcpif);
587

    
588
		if (!isset($dhcpifconf['enable'])) {
589
			continue;
590
		}
591

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

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

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

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

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

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

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

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

    
675
		$dnscfg = "";
676

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

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

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

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

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

    
714
			}
715

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

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

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

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

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

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

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

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

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

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

    
855
			$pdnscfg = "";
856

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

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

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

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

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

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

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

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

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

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

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

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

    
927
			// net boot information
928
			if (isset($poolconf['netboot'])) {
929
				if (!empty($poolconf['nextserver']) && ($poolconf['nextserver'] != $dhcpifconf['nextserver'])) {
930
					$dhcpdconf .= "		next-server {$poolconf['nextserver']};\n";
931
				}
932
				if (!empty($poolconf['filename']) && ($poolconf['filename'] != $dhcpifconf['filename'])) {
933
					$dhcpdconf .= "		filename \"{$poolconf['filename']}\";\n";
934
				}
935
				if (!empty($poolconf['rootpath']) && ($poolconf['rootpath'] != $dhcpifconf['rootpath'])) {
936
					$dhcpdconf .= "		option root-path \"{$poolconf['rootpath']}\";\n";
937
				}
938
			}
939
			$dhcpdconf .= "		range {$poolconf['range']['from']} {$poolconf['range']['to']};\n";
940
			$dhcpdconf .= "	}\n\n";
941
		}
942
// End of settings inside pools
943

    
944
		if ($dhcpifconf['gateway'] && $dhcpifconf['gateway'] != "none") {
945
			$routers = $dhcpifconf['gateway'];
946
			$add_routers = true;
947
		} elseif ($dhcpifconf['gateway'] == "none") {
948
			$add_routers = false;
949
		} else {
950
			$add_routers = $enable_add_routers;
951
			$routers = $ifcfgip;
952
		}
953
		if ($add_routers) {
954
			$dhcpdconf .= "	option routers {$routers};\n";
955
		}
956

    
957
		$dhcpdconf .= <<<EOD
958
$dnscfg
959

    
960
EOD;
961
		// default-lease-time
962
		if ($dhcpifconf['defaultleasetime']) {
963
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
964
		}
965

    
966
		// max-lease-time
967
		if ($dhcpifconf['maxleasetime']) {
968
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
969
		}
970

    
971
		// netbios-name*
972
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
973
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
974
			$dhcpdconf .= "	option netbios-node-type 8;\n";
975
		}
976

    
977
		// ntp-servers
978
		if (is_array($dhcpifconf['ntpserver']) && $dhcpifconf['ntpserver'][0]) {
979
			$dhcpdconf .= "	option ntp-servers " . join(",", $dhcpifconf['ntpserver']) . ";\n";
980
		}
981

    
982
		// tftp-server-name
983
		if ($dhcpifconf['tftp'] <> "") {
984
			$dhcpdconf .= "	option tftp-server-name \"{$dhcpifconf['tftp']}\";\n";
985
		}
986

    
987
		// Handle option, number rowhelper values
988
		$dhcpdconf .= "\n";
989
		if ($dhcpifconf['numberoptions']['item']) {
990
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
991
				$item_value = base64_decode($item['value']);
992
				if (empty($item['type']) || $item['type'] == "text") {
993
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} \"{$item_value}\";\n";
994
				} else {
995
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} {$item_value};\n";
996
				}
997
			}
998
		}
999

    
1000
		// ldap-server
1001
		if ($dhcpifconf['ldap'] <> "") {
1002
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
1003
		}
1004

    
1005
		// net boot information
1006
		if (isset($dhcpifconf['netboot'])) {
1007
			if ($dhcpifconf['nextserver'] <> "") {
1008
				$dhcpdconf .= "	next-server {$dhcpifconf['nextserver']};\n";
1009
			}
1010
			if (!empty($dhcpifconf['filename']) && !empty($dhcpifconf['filename32']) && !empty($dhcpifconf['filename64'])) {
1011
				$dhcpdconf .= "	if option arch = 00:06 {\n";
1012
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename32']}\";\n";
1013
				$dhcpdconf .= "	} else if option arch = 00:07 {\n";
1014
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1015
				$dhcpdconf .= "	} else if option arch = 00:09 {\n";
1016
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1017
				$dhcpdconf .= "	} else {\n";
1018
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename']}\";\n";
1019
				$dhcpdconf .= "	}\n\n";
1020
			} elseif (!empty($dhcpifconf['filename'])) {
1021
				$dhcpdconf .= "	filename \"{$dhcpifconf['filename']}\";\n";
1022
			}
1023
			if (!empty($dhcpifconf['rootpath'])) {
1024
				$dhcpdconf .= "	option root-path \"{$dhcpifconf['rootpath']}\";\n";
1025
			}
1026
		}
1027

    
1028
		$dhcpdconf .= <<<EOD
1029
}
1030

    
1031
EOD;
1032

    
1033
		/* add static mappings */
1034
		if (is_array($dhcpifconf['staticmap'])) {
1035

    
1036
			$i = 0;
1037
			foreach ($dhcpifconf['staticmap'] as $sm) {
1038
				$dhcpdconf .= "host s_{$dhcpif}_{$i} {\n";
1039

    
1040
				if ($sm['mac']) {
1041
					$dhcpdconf .= "        hardware ethernet {$sm['mac']};\n";
1042
				}
1043

    
1044
				if ($sm['cid']) {
1045
					$dhcpdconf .= "        option dhcp-client-identifier \"{$sm['cid']}\";\n";
1046
				}
1047

    
1048
				if ($sm['ipaddr']) {
1049
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
1050
				}
1051

    
1052
				if ($sm['hostname']) {
1053
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1054
					$dhhostname = str_replace(".", "_", $dhhostname);
1055
					$dhcpdconf .= "	option host-name \"{$dhhostname}\";\n";
1056
				}
1057
				if ($sm['filename']) {
1058
					$dhcpdconf .= "	filename \"{$sm['filename']}\";\n";
1059
				}
1060

    
1061
				if ($sm['rootpath']) {
1062
					$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1063
				}
1064

    
1065
				if ($sm['gateway'] && ($sm['gateway'] != $dhcpifconf['gateway'])) {
1066
					$dhcpdconf .= "	option routers {$sm['gateway']};\n";
1067
				}
1068

    
1069
				$smdnscfg = "";
1070

    
1071
				if ($sm['domain'] && ($sm['domain'] != $dhcpifconf['domain'])) {
1072
					$smdnscfg .= "	option domain-name \"{$sm['domain']}\";\n";
1073
				}
1074

    
1075
				if (!empty($sm['domainsearchlist']) && ($sm['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
1076
					$smdnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $sm['domainsearchlist'])) . "\";\n";
1077
				}
1078

    
1079
				if (isset($sm['ddnsupdate'])) {
1080
					if (($sm['ddnsdomain'] <> "") && ($sm['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
1081
						$smdnscfg .= "		ddns-domainname \"{$sm['ddnsdomain']}\";\n";
1082
					}
1083
					$smdnscfg .= "		ddns-update-style interim;\n";
1084
				}
1085

    
1086
				if (is_array($sm['dnsserver']) && ($sm['dnsserver'][0]) && ($sm['dnsserver'][0] != $dhcpifconf['dnsserver'][0])) {
1087
					$smdnscfg .= "	option domain-name-servers " . join(",", $sm['dnsserver']) . ";\n";
1088
				}
1089
				$dhcpdconf .= "{$smdnscfg}";
1090

    
1091
				// default-lease-time
1092
				if ($sm['defaultleasetime'] && ($sm['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
1093
					$dhcpdconf .= "	default-lease-time {$sm['defaultleasetime']};\n";
1094
				}
1095

    
1096
				// max-lease-time
1097
				if ($sm['maxleasetime'] && ($sm['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
1098
					$dhcpdconf .= "	max-lease-time {$sm['maxleasetime']};\n";
1099
				}
1100

    
1101
				// netbios-name*
1102
				if (is_array($sm['winsserver']) && $sm['winsserver'][0] && ($sm['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
1103
					$dhcpdconf .= "	option netbios-name-servers " . join(",", $sm['winsserver']) . ";\n";
1104
					$dhcpdconf .= "	option netbios-node-type 8;\n";
1105
				}
1106

    
1107
				// ntp-servers
1108
				if (is_array($sm['ntpserver']) && $sm['ntpserver'][0] && ($sm['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
1109
					$dhcpdconf .= "	option ntp-servers " . join(",", $sm['ntpserver']) . ";\n";
1110
				}
1111

    
1112
				// tftp-server-name
1113
				if (!empty($sm['tftp']) && ($sm['tftp'] != $dhcpifconf['tftp'])) {
1114
					$dhcpdconf .= "	option tftp-server-name \"{$sm['tftp']}\";\n";
1115
				}
1116

    
1117
				$dhcpdconf .= "}\n";
1118
				$i++;
1119
			}
1120
		}
1121

    
1122
		$dhcpdifs[] = get_real_interface($dhcpif);
1123
		if ($newzone['domain-name']) {
1124
			if ($need_ddns_updates) {
1125
				$newzone['dns-servers'] = array($dhcpifconf['ddnsdomainprimary']);
1126
				$newzone['ddnsdomainkeyname'] = $dhcpifconf['ddnsdomainkeyname'];
1127
				$newzone['ddnsdomainkey'] = $dhcpifconf['ddnsdomainkey'];
1128
				$dhcpdconf .= dhcpdkey($dhcpifconf);
1129
			}
1130
			$ddns_zones[] = $newzone;
1131
		}
1132
	}
1133

    
1134
	if ($need_ddns_updates) {
1135
		$dhcpdconf .= "ddns-update-style interim;\n";
1136
		$dhcpdconf .= "update-static-leases on;\n";
1137

    
1138
		$dhcpdconf .= dhcpdzones($ddns_zones);
1139
	}
1140

    
1141
	/* write dhcpd.conf */
1142
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpd.conf", $dhcpdconf)) {
1143
		printf(gettext("Error: cannot open dhcpd.conf in services_dhcpdv4_configure().%s"), "\n");
1144
		unset($dhcpdconf);
1145
		return 1;
1146
	}
1147
	unset($dhcpdconf);
1148

    
1149
	/* create an empty leases database */
1150
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
1151
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
1152
	}
1153

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

    
1158
	/* fire up dhcpd in a chroot */
1159
	if (count($dhcpdifs) > 0) {
1160
		mwexec("/usr/local/sbin/dhcpd -user dhcpd -group _dhcp -chroot {$g['dhcpd_chroot_path']} -cf /etc/dhcpd.conf -pf {$g['varrun_path']}/dhcpd.pid " .
1161
			join(" ", $dhcpdifs));
1162
	}
1163

    
1164
	if (platform_booting()) {
1165
		print "done.\n";
1166
	}
1167

    
1168
	return 0;
1169
}
1170

    
1171
function dhcpdkey($dhcpifconf) {
1172
	$dhcpdconf = "";
1173
	if ($dhcpifconf['ddnsdomainkeyname'] <> "" && $dhcpifconf['ddnsdomainkey'] <> "") {
1174
		$dhcpdconf .= "key {$dhcpifconf['ddnsdomainkeyname']} {\n";
1175
		$dhcpdconf .= "	algorithm hmac-md5;\n";
1176
		$dhcpdconf .= "	secret {$dhcpifconf['ddnsdomainkey']};\n";
1177
		$dhcpdconf .= "}\n";
1178
	}
1179

    
1180
	return $dhcpdconf;
1181
}
1182

    
1183
function dhcpdzones($ddns_zones) {
1184
	$dhcpdconf = "";
1185

    
1186
	if (is_array($ddns_zones)) {
1187
		$added_zones = array();
1188
		foreach ($ddns_zones as $zone) {
1189
			if (!is_array($zone) || empty($zone) || !is_array($zone['dns-servers'])) {
1190
				continue;
1191
			}
1192
			$primary = $zone['dns-servers'][0];
1193
			$secondary = empty($zone['dns-servers'][1]) ? "" : $zone['dns-servers'][1];
1194

    
1195
			// Make sure we aren't using any invalid or IPv6 DNS servers.
1196
			if (!is_ipaddrv4($primary)) {
1197
				if (is_ipaddrv4($secondary)) {
1198
					$primary = $secondary;
1199
					$secondary = "";
1200
				} else {
1201
					continue;
1202
				}
1203
			}
1204

    
1205
			// We don't need to add zones multiple times.
1206
			if ($zone['domain-name'] && !in_array($zone['domain-name'], $added_zones)) {
1207
				$dhcpdconf .= "zone {$zone['domain-name']}. {\n";
1208
				$dhcpdconf .= "	primary {$primary};\n";
1209
				if (is_ipaddrv4($secondary)) {
1210
					$dhcpdconf .= "	secondary {$secondary};\n";
1211
				}
1212
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1213
					$dhcpdconf .= "	key {$zone['ddnsdomainkeyname']};\n";
1214
				}
1215
				$dhcpdconf .= "}\n";
1216
				$added_zones[] = $zone['domain-name'];
1217
			}
1218
			if ($zone['ptr-domain'] && !in_array($zone['ptr-domain'], $added_zones)) {
1219
				$dhcpdconf .= "zone {$zone['ptr-domain']} {\n";
1220
				$dhcpdconf .= "	primary {$primary};\n";
1221
				if (is_ipaddrv4($secondary)) {
1222
					$dhcpdconf .= "	secondary {$secondary};\n";
1223
				}
1224
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1225
					$dhcpdconf .= "	key {$zone['ddnsdomainkeyname']};\n";
1226
				}
1227
				$dhcpdconf .= "}\n";
1228
				$added_zones[] = $zone['ptr-domain'];
1229
			}
1230
		}
1231
	}
1232

    
1233
	return $dhcpdconf;
1234
}
1235

    
1236
function services_dhcpdv6_configure($blacklist = array()) {
1237
	global $config, $g;
1238

    
1239
	if ($g['services_dhcp_server_enable'] == false) {
1240
		return;
1241
	}
1242

    
1243
	if (isset($config['system']['developerspew'])) {
1244
		$mt = microtime();
1245
		echo "services_dhcpd_configure($if) being called $mt\n";
1246
	}
1247

    
1248
	/* kill any running dhcpd */
1249
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid")) {
1250
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid");
1251
	}
1252
	if (isvalidpid("{$g['varrun_path']}/dhcpleases6.pid")) {
1253
		killbypid("{$g['varrun_path']}/dhcpleases6.pid");
1254
	}
1255

    
1256
	/* DHCP enabled on any interfaces? */
1257
	if (!is_dhcpv6_server_enabled()) {
1258
		return 0;
1259
	}
1260

    
1261
	if (platform_booting()) {
1262
		if ($g['platform'] != $g['product_name']) {
1263
			/* restore the leases, if we have them */
1264
			if (file_exists("{$g['cf_conf_path']}/dhcp6leases.tgz")) {
1265
				$dhcprestore = "";
1266
				$dhcpreturn = "";
1267
				exec("cd /;LANG=C /usr/bin/tar -xzf {$g['cf_conf_path']}/dhcp6leases.tgz 2>&1", $dhcprestore, $dhcpreturn);
1268
				$dhcprestore = implode(" ", $dhcprestore);
1269
				if ($dhcpreturn <> 0) {
1270
					log_error(sprintf(gettext('DHCP leases v6 restore failed exited with %1$s, the error is: %2$s'), $dhcpreturn, $dhcprestore));
1271
				}
1272
			}
1273
		}
1274
	}
1275

    
1276
	$syscfg = $config['system'];
1277
	if (!is_array($config['dhcpdv6'])) {
1278
		$config['dhcpdv6'] = array();
1279
	}
1280
	$dhcpdv6cfg = $config['dhcpdv6'];
1281
	$Iflist = get_configured_interface_list();
1282
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
1283

    
1284

    
1285
	if (platform_booting()) {
1286
		echo "Starting DHCPv6 service...";
1287
	} else {
1288
		sleep(1);
1289
	}
1290

    
1291
	$custoptionsv6 = "";
1292
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1293
		if (is_array($dhcpv6ifconf['numberoptions']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1294
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1295
				$custoptionsv6 .= "option custom-{$dhcpv6if}-{$itemv6idx} code {$itemv6['number']} = text;\n";
1296
			}
1297
		}
1298
	}
1299

    
1300
	if (isset($dhcpv6ifconf['netboot']) && !empty($dhcpv6ifconf['bootfile_url'])) {
1301
		$custoptionsv6 .= "option dhcp6.bootfile-url code 59 = string;\n";
1302
	}
1303

    
1304
	$dhcpdv6conf = <<<EOD
1305

    
1306
option domain-name "{$syscfg['domain']}";
1307
option ldap-server code 95 = text;
1308
option domain-search-list code 119 = text;
1309
{$custoptionsv6}
1310
default-lease-time 7200;
1311
max-lease-time 86400;
1312
log-facility local7;
1313
one-lease-per-client true;
1314
deny duplicates;
1315
ping-check true;
1316
update-conflict-detection false;
1317
dhcp-cache-threshold 0;
1318

    
1319
EOD;
1320

    
1321
	if (!isset($dhcpv6ifconf['disableauthoritative'])) {
1322
		$dhcpdv6conf .= "authoritative;\n";
1323
	}
1324

    
1325
	if (isset($dhcpv6ifconf['alwaysbroadcast'])) {
1326
		$dhcpdv6conf .= "always-broadcast on\n";
1327
	}
1328

    
1329
	$dhcpdv6ifs = array();
1330

    
1331
	$dhcpv6num = 0;
1332
	$nsupdate = false;
1333

    
1334
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1335

    
1336
		$ddns_zones = array();
1337

    
1338
		$ifcfgv6 = $config['interfaces'][$dhcpv6if];
1339

    
1340
		if (!isset($dhcpv6ifconf['enable']) || !isset($Iflist[$dhcpv6if]) || !isset($ifcfgv6['enable'])) {
1341
			continue;
1342
		}
1343
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1344
		if (!is_ipaddrv6($ifcfgipv6)) {
1345
			continue;
1346
		}
1347
		$ifcfgsnv6 = get_interface_subnetv6($dhcpv6if);
1348
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1349

    
1350
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
1351
			$trackifname = $config['interfaces'][$ifname]['track6-interface'];
1352
			$trackcfg = $config['interfaces'][$trackifname];
1353
			$pdlen = 64 - $trackcfg['dhcp6-ia-pd-len'];
1354
		}
1355

    
1356
		if ($is_olsr_enabled == true) {
1357
			if ($dhcpv6ifconf['netmask']) {
1358
				$subnetmask = gen_subnet_maskv6($dhcpv6ifconf['netmask']);
1359
			}
1360
		}
1361

    
1362
		$dnscfgv6 = "";
1363

    
1364
		if ($dhcpv6ifconf['domain']) {
1365
			$dnscfgv6 .= "	option domain-name \"{$dhcpv6ifconf['domain']}\";\n";
1366
		}
1367

    
1368
		if ($dhcpv6ifconf['domainsearchlist'] <> "") {
1369
			$dnscfgv6 .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpv6ifconf['domainsearchlist'])) . "\";\n";
1370
		}
1371

    
1372
		if (isset($dhcpv6ifconf['ddnsupdate'])) {
1373
			if ($dhcpv6ifconf['ddnsdomain'] <> "") {
1374
				$dnscfgv6 .= "	ddns-domainname \"{$dhcpv6ifconf['ddnsdomain']}\";\n";
1375
			}
1376
			if (empty($dhcpv6ifconf['ddnsclientupdates'])) {
1377
				$ddnsclientupdates = 'allow';
1378
			} else {
1379
				$ddnsclientupdates = $dhcpv6ifconf['ddnsclientupdates'];
1380
			}
1381
			$dnscfgv6 .= "	{$ddnsclientupdates} client-updates;\n";
1382
			$nsupdate = true;
1383
		} else {
1384
			$dnscfgv6 .= "	do-forward-updates false;\n";
1385
		}
1386

    
1387
		if (is_array($dhcpv6ifconf['dnsserver']) && ($dhcpv6ifconf['dnsserver'][0])) {
1388
			$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dhcpv6ifconf['dnsserver']) . ";";
1389
		} else if (((isset($config['dnsmasq']['enable'])) || isset($config['unbound']['enable'])) && (is_ipaddrv6($ifcfgipv6))) {
1390
			$dnscfgv6 .= "	option dhcp6.name-servers {$ifcfgipv6};";
1391
		} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1392
			$dns_arrv6 = array();
1393
			foreach ($syscfg['dnsserver'] as $dnsserver) {
1394
				if (is_ipaddrv6($dnsserver)) {
1395
					$dns_arrv6[] = $dnsserver;
1396
				}
1397
			}
1398
			if (!empty($dns_arrv6)) {
1399
				$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dns_arrv6) . ";";
1400
			}
1401
		}
1402

    
1403
		if (!is_ipaddrv6($ifcfgipv6)) {
1404
			$ifcfgsnv6 = "64";
1405
			$subnetv6 = gen_subnetv6($dhcpv6ifconf['range']['from'], $ifcfgsnv6);
1406
		}
1407

    
1408
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1409

    
1410
		if (isset($dhcpv6ifconf['ddnsupdate']) &&
1411
		    !empty($dhcpv6ifconf['ddnsdomain'])) {
1412
			$newzone = array();
1413
			$newzone['domain-name'] = $dhcpv6ifconf['ddnsdomain'];
1414
			$newzone['dns-servers'][] = $dhcpv6ifconf['ddnsdomainprimary'];
1415
			$newzone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1416
			$newzone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1417
			$ddns_zones[] = $newzone;
1418
			if (isset($dhcpv6ifconf['ddnsreverse'])) {
1419
				$ptr_zones = get_v6_ptr_zones($subnetv6, $ifcfgsnv6);
1420
				foreach ($ptr_zones as $ptr_zone) {
1421
					$reversezone = array();
1422
					$reversezone['domain-name'] = $ptr_zone;
1423
					$reversezone['dns-servers'][] =
1424
					    $dhcpv6ifconf['ddnsdomainprimary'];
1425
					$ddns_zones[] = $reversezone;
1426
				}
1427
			}
1428
		}
1429

    
1430
		$dhcpdv6conf .= " {\n";
1431

    
1432
		$range_from = $dhcpv6ifconf['range']['from'];
1433
		$range_to = $dhcpv6ifconf['range']['to'];
1434
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
1435
			$range_from = merge_ipv6_delegated_prefix($ifcfgipv6, $range_from, $pdlen);
1436
			$range_to = merge_ipv6_delegated_prefix($ifcfgipv6, $range_to, $pdlen);
1437
		}
1438

    
1439
		$dhcpdv6conf .= <<<EOD
1440
	range6 {$range_from} {$range_to};
1441
$dnscfgv6
1442

    
1443
EOD;
1444

    
1445
		if (is_ipaddrv6($dhcpv6ifconf['prefixrange']['from']) && is_ipaddrv6($dhcpv6ifconf['prefixrange']['to'])) {
1446
			$dhcpdv6conf .= "	prefix6 {$dhcpv6ifconf['prefixrange']['from']} {$dhcpv6ifconf['prefixrange']['to']} /{$dhcpv6ifconf['prefixrange']['prefixlength']};\n";
1447
		}
1448
		if (is_ipaddrv6($dhcpv6ifconf['dns6ip'])) {
1449
			$dns6ip = $dhcpv6ifconf['dns6ip'];
1450
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1451
			    Net_IPv6::isInNetmask($dns6ip, '::', $pdlen)) {
1452
				$dns6ip = merge_ipv6_delegated_prefix($ifcfgipv6, $dns6ip, $pdlen);
1453
			}
1454
			$dhcpdv6conf .= "	option dhcp6.name-servers {$dns6ip};\n";
1455
		}
1456
		// default-lease-time
1457
		if ($dhcpv6ifconf['defaultleasetime']) {
1458
			$dhcpdv6conf .= "	default-lease-time {$dhcpv6ifconf['defaultleasetime']};\n";
1459
		}
1460

    
1461
		// max-lease-time
1462
		if ($dhcpv6ifconf['maxleasetime']) {
1463
			$dhcpdv6conf .= "	max-lease-time {$dhcpv6ifconf['maxleasetime']};\n";
1464
		}
1465

    
1466
		// ntp-servers
1467
		if (is_array($dhcpv6ifconf['ntpserver']) && $dhcpv6ifconf['ntpserver'][0]) {
1468
			$ntpservers = array();
1469
			foreach ($dhcpv6ifconf['ntpserver'] as $ntpserver) {
1470
				if (!is_ipaddrv6($ntpserver)) {
1471
					continue;
1472
				}
1473
				if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1474
				    Net_IPv6::isInNetmask($ntpserver, '::', $pdlen)) {
1475
					$ntpserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ntpserver, $pdlen);
1476
				}
1477
				$ntpservers[] = $ntpserver;
1478
			}
1479
			if (count($ntpservers) > 0) {
1480
				$dhcpdv6conf .= "        option dhcp6.sntp-servers " . join(",", $dhcpv6ifconf['ntpserver']) . ";\n";
1481
			}
1482
		}
1483
		// tftp-server-name
1484
		/* Needs ISC DHCPD support
1485
		 if ($dhcpv6ifconf['tftp'] <> "") {
1486
			$dhcpdv6conf .= "	option tftp-server-name \"{$dhcpv6ifconf['tftp']}\";\n";
1487
		 }
1488
		*/
1489

    
1490
		// Handle option, number rowhelper values
1491
		$dhcpdv6conf .= "\n";
1492
		if ($dhcpv6ifconf['numberoptions']['item']) {
1493
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1494
				$itemv6_value = base64_decode($itemv6['value']);
1495
				$dhcpdv6conf .= "	option custom-{$dhcpv6if}-{$itemv6idx} \"{$itemv6_value}\";\n";
1496
			}
1497
		}
1498

    
1499
		// ldap-server
1500
		if ($dhcpv6ifconf['ldap'] <> "") {
1501
			$ldapserver = $dhcpv6ifconf['ldap'];
1502
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1503
			    Net_IPv6::isInNetmask($ldapserver, '::', $pdlen)) {
1504
				$ldapserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ldapserver, $pdlen);
1505
			}
1506
			$dhcpdv6conf .= "	option ldap-server \"{$ldapserver}\";\n";
1507
		}
1508

    
1509
		// net boot information
1510
		if (isset($dhcpv6ifconf['netboot'])) {
1511
			if (!empty($dhcpv6ifconf['bootfile_url'])) {
1512
				$dhcpdv6conf .= "	option dhcp6.bootfile-url \"{$dhcpv6ifconf['bootfile_url']}\";\n";
1513
			}
1514
		}
1515

    
1516
		$dhcpdv6conf .= "}\n";
1517

    
1518
		/* add static mappings */
1519
		/* Needs to use DUID */
1520
		if (is_array($dhcpv6ifconf['staticmap'])) {
1521
			$i = 0;
1522
			foreach ($dhcpv6ifconf['staticmap'] as $sm) {
1523
				$dhcpdv6conf .= <<<EOD
1524
host s_{$dhcpv6if}_{$i} {
1525
	host-identifier option dhcp6.client-id {$sm['duid']};
1526

    
1527
EOD;
1528
				if ($sm['ipaddrv6']) {
1529
					$ipaddrv6 = $sm['ipaddrv6'];
1530
					if ($ifcfgv6['ipaddrv6'] == 'track6') {
1531
						$ipaddrv6 = merge_ipv6_delegated_prefix($ifcfgipv6, $ipaddrv6, $pdlen);
1532
					}
1533
					$dhcpdv6conf .= "	fixed-address6 {$ipaddrv6};\n";
1534
				}
1535

    
1536
				if ($sm['hostname']) {
1537
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1538
					$dhhostname = str_replace(".", "_", $dhhostname);
1539
					$dhcpdv6conf .= "	option host-name {$dhhostname};\n";
1540
				}
1541
				if ($sm['filename']) {
1542
					$dhcpdv6conf .= "	filename \"{$sm['filename']}\";\n";
1543
				}
1544

    
1545
				if ($sm['rootpath']) {
1546
					$dhcpdv6conf .= "	option root-path \"{$sm['rootpath']}\";\n";
1547
				}
1548

    
1549
				$dhcpdv6conf .= "}\n";
1550
				$i++;
1551
			}
1552
		}
1553

    
1554
		if ($dhcpv6ifconf['ddnsdomain']) {
1555
			$dhcpdv6conf .= dhcpdkey($dhcpv6ifconf);
1556
			$dhcpdv6conf .= dhcpdzones($ddns_zones);
1557
		}
1558

    
1559
		if ($config['dhcpdv6'][$dhcpv6if]['ramode'] <> "unmanaged" && isset($config['interfaces'][$dhcpv6if]['enable'])) {
1560
			if (preg_match("/poes/si", $dhcpv6if)) {
1561
				/* magic here */
1562
				$dhcpdv6ifs = array_merge($dhcpdv6ifs, get_pppoes_child_interfaces($dhcpv6if));
1563
			} else {
1564
				$realif = get_real_interface($dhcpv6if, "inet6");
1565
				if (stristr("$realif", "bridge")) {
1566
					$mac = get_interface_mac($realif);
1567
					$v6address = generate_ipv6_from_mac($mac);
1568
					/* Create link local address for bridges */
1569
					mwexec("/sbin/ifconfig {$realif} inet6 {$v6address}");
1570
				}
1571
				$realif = escapeshellcmd($realif);
1572
				$dhcpdv6ifs[] = $realif;
1573
			}
1574
		}
1575
	}
1576

    
1577
	if ($nsupdate) {
1578
		$dhcpdv6conf .= "ddns-update-style interim;\n";
1579
	} else {
1580
		$dhcpdv6conf .= "ddns-update-style none;\n";
1581
	}
1582

    
1583
	/* write dhcpdv6.conf */
1584
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf", $dhcpdv6conf)) {
1585
		log_error("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1586
		if (platform_booting()) {
1587
			printf("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1588
		}
1589
		unset($dhcpdv6conf);
1590
		return 1;
1591
	}
1592
	unset($dhcpdv6conf);
1593

    
1594
	/* create an empty leases v6 database */
1595
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases")) {
1596
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1597
	}
1598

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

    
1603
	/* fire up dhcpd in a chroot */
1604
	if (count($dhcpdv6ifs) > 0) {
1605
		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 " .
1606
			join(" ", $dhcpdv6ifs));
1607
		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");
1608
	}
1609
	if (platform_booting()) {
1610
		print gettext("done.") . "\n";
1611
	}
1612

    
1613
	return 0;
1614
}
1615

    
1616
function services_igmpproxy_configure() {
1617
	global $config, $g;
1618

    
1619
	/* kill any running igmpproxy */
1620
	killbyname("igmpproxy");
1621

    
1622
	if (!is_array($config['igmpproxy']['igmpentry']) || (count($config['igmpproxy']['igmpentry']) == 0)) {
1623
		return 1;
1624
	}
1625

    
1626
	$iflist = get_configured_interface_list();
1627

    
1628
	$igmpconf = <<<EOD
1629

    
1630
##------------------------------------------------------
1631
## Enable Quickleave mode (Sends Leave instantly)
1632
##------------------------------------------------------
1633
quickleave
1634

    
1635
EOD;
1636

    
1637
	foreach ($config['igmpproxy']['igmpentry'] as $igmpcf) {
1638
		unset($iflist[$igmpcf['ifname']]);
1639
		$realif = get_real_interface($igmpcf['ifname']);
1640
		if (empty($igmpcf['threshold'])) {
1641
			$threshld = 1;
1642
		} else {
1643
			$threshld = $igmpcf['threshold'];
1644
		}
1645
		$igmpconf .= "phyint {$realif} {$igmpcf['type']} ratelimit 0 threshold {$threshld}\n";
1646

    
1647
		if ($igmpcf['address'] <> "") {
1648
			$item = explode(" ", $igmpcf['address']);
1649
			foreach ($item as $iww) {
1650
				$igmpconf .= "altnet {$iww}\n";
1651
			}
1652
		}
1653
		$igmpconf .= "\n";
1654
	}
1655
	foreach ($iflist as $ifn) {
1656
		$realif = get_real_interface($ifn);
1657
		$igmpconf .= "phyint {$realif} disabled\n";
1658
	}
1659
	$igmpconf .= "\n";
1660

    
1661
	$igmpfl = fopen($g['tmp_path'] . "/igmpproxy.conf", "w");
1662
	if (!$igmpfl) {
1663
		log_error(gettext("Could not write Igmpproxy configuration file!"));
1664
		return;
1665
	}
1666
	fwrite($igmpfl, $igmpconf);
1667
	fclose($igmpfl);
1668
	unset($igmpconf);
1669

    
1670
	if (isset($config['syslog']['igmpxverbose'])) {
1671
		mwexec_bg("/usr/local/sbin/igmpproxy -v {$g['tmp_path']}/igmpproxy.conf");
1672
	} else {
1673
		mwexec_bg("/usr/local/sbin/igmpproxy {$g['tmp_path']}/igmpproxy.conf");
1674
	}
1675

    
1676
	log_error(gettext("Started IGMP proxy service."));
1677

    
1678
	return 0;
1679
}
1680

    
1681
function services_dhcrelay_configure() {
1682
	global $config, $g;
1683

    
1684
	if (isset($config['system']['developerspew'])) {
1685
		$mt = microtime();
1686
		echo "services_dhcrelay_configure() being called $mt\n";
1687
	}
1688

    
1689
	/* kill any running dhcrelay */
1690
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
1691

    
1692
	$dhcrelaycfg =& $config['dhcrelay'];
1693

    
1694
	/* DHCPRelay enabled on any interfaces? */
1695
	if (!isset($dhcrelaycfg['enable'])) {
1696
		return 0;
1697
	}
1698

    
1699
	if (platform_booting()) {
1700
		echo gettext("Starting DHCP relay service...");
1701
	} else {
1702
		sleep(1);
1703
	}
1704

    
1705
	$iflist = get_configured_interface_list();
1706

    
1707
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1708
	foreach ($dhcifaces as $dhcrelayif) {
1709
		if (!isset($iflist[$dhcrelayif]) ||
1710
		    link_interface_to_bridge($dhcrelayif)) {
1711
			continue;
1712
		}
1713

    
1714
		if (is_ipaddr(get_interface_ip($dhcrelayif))) {
1715
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1716
		}
1717
	}
1718

    
1719
	/*
1720
	 * In order for the relay to work, it needs to be active
1721
	 * on the interface in which the destination server sits.
1722
	 */
1723
	$srvips = explode(",", $dhcrelaycfg['server']);
1724
	if (!is_array($srvips)) {
1725
		log_error(gettext("No destination IP has been configured!"));
1726
		return;
1727
	}
1728

    
1729
	foreach ($srvips as $srcidx => $srvip) {
1730
		unset($destif);
1731
		foreach ($iflist as $ifname) {
1732
			$subnet = get_interface_ip($ifname);
1733
			if (!is_ipaddr($subnet)) {
1734
				continue;
1735
			}
1736
			$subnet .= "/" . get_interface_subnet($ifname);
1737
			if (ip_in_subnet($srvip, $subnet)) {
1738
				$destif = get_real_interface($ifname);
1739
				break;
1740
			}
1741
		}
1742
		if (!isset($destif)) {
1743
			foreach (get_staticroutes() as $rtent) {
1744
				if (ip_in_subnet($srvip, $rtent['network'])) {
1745
					$a_gateways = return_gateways_array(true);
1746
					$destif = $a_gateways[$rtent['gateway']]['interface'];
1747
					break;
1748
				}
1749
			}
1750
		}
1751

    
1752
		if (!isset($destif)) {
1753
			/* Create a array from the existing route table */
1754
			exec("/usr/bin/netstat -rnWf inet", $route_str);
1755
			array_shift($route_str);
1756
			array_shift($route_str);
1757
			array_shift($route_str);
1758
			array_shift($route_str);
1759
			$route_arr = array();
1760
			foreach ($route_str as $routeline) {
1761
				$items = preg_split("/[ ]+/i", $routeline);
1762
				if (is_subnetv4($items[0])) {
1763
					$subnet = $items[0];
1764
				} elseif (is_ipaddrv4($items[0])) {
1765
					$subnet = "{$items[0]}/32";
1766
				} else {
1767
					// Not a subnet or IP address, skip to the next line.
1768
					continue;
1769
				}
1770
				if (ip_in_subnet($srvip, $subnet)) {
1771
					$destif = trim($items[6]);
1772
					break;
1773
				}
1774
			}
1775
		}
1776

    
1777
		if (!isset($destif)) {
1778
			if (is_array($config['gateways']['gateway_item'])) {
1779
				foreach ($config['gateways']['gateway_item'] as $gateway) {
1780
					if (isset($gateway['defaultgw'])) {
1781
						$destif = get_real_interface($gateway['interface']);
1782
						break;
1783
					}
1784
				}
1785
			} else {
1786
				$destif = get_real_interface("wan");
1787
			}
1788
		}
1789

    
1790
		if (!empty($destif)) {
1791
			$dhcrelayifs[] = $destif;
1792
		}
1793
	}
1794
	$dhcrelayifs = array_unique($dhcrelayifs);
1795

    
1796
	/* fire up dhcrelay */
1797
	if (empty($dhcrelayifs)) {
1798
		log_error(gettext("No suitable interface found for running dhcrelay!"));
1799
		return; /* XXX */
1800
	}
1801

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

    
1804
	if (isset($dhcrelaycfg['agentoption'])) {
1805
		$cmd .= " -a -m replace";
1806
	}
1807

    
1808
	$cmd .= " " . implode(" ", $srvips);
1809
	mwexec($cmd);
1810
	unset($cmd);
1811

    
1812
	return 0;
1813
}
1814

    
1815
function services_dhcrelay6_configure() {
1816
	global $config, $g;
1817

    
1818
	if (isset($config['system']['developerspew'])) {
1819
		$mt = microtime();
1820
		echo "services_dhcrelay6_configure() being called $mt\n";
1821
	}
1822

    
1823
	/* kill any running dhcrelay */
1824
	killbypid("{$g['varrun_path']}/dhcrelay6.pid");
1825

    
1826
	$dhcrelaycfg =& $config['dhcrelay6'];
1827

    
1828
	/* DHCPv6 Relay enabled on any interfaces? */
1829
	if (!isset($dhcrelaycfg['enable'])) {
1830
		return 0;
1831
	}
1832

    
1833
	if (platform_booting()) {
1834
		echo gettext("Starting DHCPv6 relay service...");
1835
	} else {
1836
		sleep(1);
1837
	}
1838

    
1839
	$iflist = get_configured_interface_list();
1840

    
1841
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1842
	foreach ($dhcifaces as $dhcrelayif) {
1843
		if (!isset($iflist[$dhcrelayif]) ||
1844
		    link_interface_to_bridge($dhcrelayif)) {
1845
			continue;
1846
		}
1847

    
1848
		if (is_ipaddrv6(get_interface_ipv6($dhcrelayif))) {
1849
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1850
		}
1851
	}
1852
	$dhcrelayifs = array_unique($dhcrelayifs);
1853

    
1854
	/*
1855
	 * In order for the relay to work, it needs to be active
1856
	 * on the interface in which the destination server sits.
1857
	 */
1858
	$srvips = explode(",", $dhcrelaycfg['server']);
1859
	$srvifaces = array();
1860
	foreach ($srvips as $srcidx => $srvip) {
1861
		unset($destif);
1862
		foreach ($iflist as $ifname) {
1863
			$subnet = get_interface_ipv6($ifname);
1864
			if (!is_ipaddrv6($subnet)) {
1865
				continue;
1866
			}
1867
			$subnet .= "/" . get_interface_subnetv6($ifname);
1868
			if (ip_in_subnet($srvip, $subnet)) {
1869
				$destif = get_real_interface($ifname);
1870
				break;
1871
			}
1872
		}
1873
		if (!isset($destif)) {
1874
			if (is_array($config['staticroutes']['route'])) {
1875
				foreach ($config['staticroutes']['route'] as $rtent) {
1876
					if (ip_in_subnet($srvip, $rtent['network'])) {
1877
						$a_gateways = return_gateways_array(true);
1878
						$destif = $a_gateways[$rtent['gateway']]['interface'];
1879
						break;
1880
					}
1881
				}
1882
			}
1883
		}
1884

    
1885
		if (!isset($destif)) {
1886
			/* Create a array from the existing route table */
1887
			exec("/usr/bin/netstat -rnWf inet6", $route_str);
1888
			array_shift($route_str);
1889
			array_shift($route_str);
1890
			array_shift($route_str);
1891
			array_shift($route_str);
1892
			$route_arr = array();
1893
			foreach ($route_str as $routeline) {
1894
				$items = preg_split("/[ ]+/i", $routeline);
1895
				if (ip_in_subnet($srvip, $items[0])) {
1896
					$destif = trim($items[6]);
1897
					break;
1898
				}
1899
			}
1900
		}
1901

    
1902
		if (!isset($destif)) {
1903
			if (is_array($config['gateways']['gateway_item'])) {
1904
				foreach ($config['gateways']['gateway_item'] as $gateway) {
1905
					if (isset($gateway['defaultgw'])) {
1906
						$destif = get_real_interface($gateway['interface']);
1907
						break;
1908
					}
1909
				}
1910
			} else {
1911
				$destif = get_real_interface("wan");
1912
			}
1913
		}
1914

    
1915
		if (!empty($destif)) {
1916
			$srvifaces[] = "{$srvip}%{$destif}";
1917
		}
1918
	}
1919

    
1920
	/* fire up dhcrelay */
1921
	if (empty($dhcrelayifs) || empty($srvifaces)) {
1922
		log_error(gettext("No suitable interface found for running dhcrelay -6!"));
1923
		return; /* XXX */
1924
	}
1925

    
1926
	$cmd = "/usr/local/sbin/dhcrelay -6 -pf \"{$g['varrun_path']}/dhcrelay6.pid\"";
1927
	foreach ($dhcrelayifs as $dhcrelayif) {
1928
		$cmd .= " -l {$dhcrelayif}";
1929
	}
1930
	foreach ($srvifaces as $srviface) {
1931
		$cmd .= " -u \"{$srviface}\"";
1932
	}
1933
	mwexec($cmd);
1934
	unset($cmd);
1935

    
1936
	return 0;
1937
}
1938

    
1939
function services_dyndns_configure_client($conf) {
1940

    
1941
	if (!isset($conf['enable'])) {
1942
		return;
1943
	}
1944

    
1945
	/* load up the dyndns.class */
1946
	require_once("dyndns.class");
1947

    
1948
	$dns = new updatedns($dnsService = $conf['type'],
1949
		$dnsHost = $conf['host'],
1950
		$dnsDomain = $conf['domainname'],
1951
		$dnsUser = $conf['username'],
1952
		$dnsPass = $conf['password'],
1953
		$dnsWildcard = $conf['wildcard'],
1954
		$dnsProxied = $conf['proxied'],
1955
		$dnsMX = $conf['mx'],
1956
		$dnsIf = "{$conf['interface']}",
1957
		$dnsBackMX = NULL,
1958
		$dnsServer = NULL,
1959
		$dnsPort = NULL,
1960
		$dnsUpdateURL = "{$conf['updateurl']}",
1961
		$forceUpdate = $conf['force'],
1962
		$dnsZoneID = $conf['zoneid'],
1963
		$dnsTTL = $conf['ttl'],
1964
		$dnsResultMatch = "{$conf['resultmatch']}",
1965
		$dnsRequestIf = "{$conf['requestif']}",
1966
		$dnsID = "{$conf['id']}",
1967
		$dnsVerboseLog = $conf['verboselog'],
1968
		$curlIpresolveV4 = $conf['curl_ipresolve_v4'],
1969
		$curlSslVerifypeer = $conf['curl_ssl_verifypeer']);
1970
}
1971

    
1972
function services_dyndns_configure($int = "") {
1973
	global $config, $g;
1974
	if (isset($config['system']['developerspew'])) {
1975
		$mt = microtime();
1976
		echo "services_dyndns_configure() being called $mt\n";
1977
	}
1978

    
1979
	$dyndnscfg = $config['dyndnses']['dyndns'];
1980
	$gwgroups = return_gateway_groups_array();
1981
	if (is_array($dyndnscfg)) {
1982
		if (platform_booting()) {
1983
			echo gettext("Starting DynDNS clients...");
1984
		}
1985

    
1986
		foreach ($dyndnscfg as $dyndns) {
1987
			/*
1988
			 * If it's using a gateway group, check if interface is
1989
			 * the active gateway for that group
1990
			 */
1991
			$group_int = '';
1992
			if (is_array($gwgroups[$dyndns['interface']])) {
1993
				if (!empty($gwgroups[$dyndns['interface']][0]['vip'])) {
1994
					$group_int = $gwgroups[$dyndns['interface']][0]['vip'];
1995
				} else {
1996
					$group_int = $gwgroups[$dyndns['interface']][0]['int'];
1997
				}
1998
			}
1999
			if ((empty($int)) || ($int == $dyndns['interface']) || ($int == $group_int)) {
2000
				$dyndns['verboselog'] = isset($dyndns['verboselog']);
2001
				$dyndns['curl_ipresolve_v4'] = isset($dyndns['curl_ipresolve_v4']);
2002
				$dyndns['curl_ssl_verifypeer'] = isset($dyndns['curl_ssl_verifypeer']);
2003
				services_dyndns_configure_client($dyndns);
2004
				sleep(1);
2005
			}
2006
		}
2007

    
2008
		if (platform_booting()) {
2009
			echo gettext("done.") . "\n";
2010
		}
2011
	}
2012

    
2013
	return 0;
2014
}
2015

    
2016
function dyndnsCheckIP($int) {
2017
	global $config, $factory_default_checkipservice;
2018
	$ip_address = get_interface_ip($int);
2019
	if (is_private_ip($ip_address)) {
2020
		$gateways_status = return_gateways_status(true);
2021
		// If the gateway for this interface is down, then the external check cannot work.
2022
		// Avoid the long wait for the external check to timeout.
2023
		if (stristr($gateways_status[$config['interfaces'][$int]['gateway']]['status'], "down")) {
2024
			return "down";
2025
		}
2026

    
2027
		// Append the factory default check IP service to the list (if not disabled).
2028
		if (!isset($config['checkipservices']['disable_factory_default'])) {
2029
			$config['checkipservices']['checkipservice'][] = $factory_default_checkipservice;
2030
		}
2031

    
2032
		// Use the first enabled check IP service as the default.
2033
		if (is_array($config['checkipservices']['checkipservice'])) {
2034
			foreach ($config['checkipservices']['checkipservice'] as $i => $checkipservice) {
2035
				if (isset($checkipservice['enable'])) {
2036
					$url = $checkipservice['url'];
2037
					$username = $checkipservice['username'];
2038
					$password = $checkipservice['password'];
2039
					$verifysslpeer = isset($checkipservice['verifysslpeer']);
2040
					break;
2041
				}
2042
			}
2043
		}
2044

    
2045
		$hosttocheck = $url;
2046
		$ip_ch = curl_init($hosttocheck);
2047
		curl_setopt($ip_ch, CURLOPT_RETURNTRANSFER, 1);
2048
		curl_setopt($ip_ch, CURLOPT_SSL_VERIFYPEER, $verifysslpeer);
2049
		curl_setopt($ip_ch, CURLOPT_INTERFACE, 'host!' . $ip_address);
2050
		curl_setopt($ip_ch, CURLOPT_CONNECTTIMEOUT, '30');
2051
		curl_setopt($ip_ch, CURLOPT_TIMEOUT, 120);
2052
		curl_setopt($ip_ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
2053
		curl_setopt($ip_ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
2054
		curl_setopt($ip_ch, CURLOPT_USERPWD, "{$username}:{$password}");
2055
		$ip_result_page = curl_exec($ip_ch);
2056
		curl_close($ip_ch);
2057
		$ip_result_decoded = urldecode($ip_result_page);
2058
		preg_match('=Current IP Address: (.*)</body>=siU', $ip_result_decoded, $matches);
2059
		$ip_address = trim($matches[1]);
2060
	}
2061
	return $ip_address;
2062
}
2063

    
2064
function services_dnsmasq_configure($restart_dhcp = true) {
2065
	global $config, $g;
2066
	$return = 0;
2067

    
2068
	// hard coded args: will be removed to avoid duplication if specified in custom_options
2069
	$standard_args = array(
2070
		"dns-forward-max" => "--dns-forward-max=5000",
2071
		"cache-size" => "--cache-size=10000",
2072
		"local-ttl" => "--local-ttl=1"
2073
	);
2074

    
2075

    
2076
	if (isset($config['system']['developerspew'])) {
2077
		$mt = microtime();
2078
		echo "services_dnsmasq_configure() being called $mt\n";
2079
	}
2080

    
2081
	/* kill any running dnsmasq */
2082
	if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) {
2083
		sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
2084
	}
2085

    
2086
	if (isset($config['dnsmasq']['enable'])) {
2087

    
2088
		if (platform_booting()) {
2089
			echo gettext("Starting DNS forwarder...");
2090
		} else {
2091
			sleep(1);
2092
		}
2093

    
2094
		/* generate hosts file */
2095
		if (system_hosts_generate() != 0) {
2096
			$return = 1;
2097
		}
2098

    
2099
		$args = "";
2100

    
2101
		if (isset($config['dnsmasq']['regdhcp'])) {
2102
			$args .= " --dhcp-hostsfile={$g['varetc_path']}/hosts ";
2103
		}
2104

    
2105
		/* Setup listen port, if non-default */
2106
		if (is_port($config['dnsmasq']['port'])) {
2107
			$args .= " --port={$config['dnsmasq']['port']} ";
2108
		}
2109

    
2110
		$listen_addresses = "";
2111
		if (isset($config['dnsmasq']['interface'])) {
2112
			$interfaces = explode(",", $config['dnsmasq']['interface']);
2113
			foreach ($interfaces as $interface) {
2114
				$if = get_real_interface($interface);
2115
				if (does_interface_exist($if)) {
2116
					$laddr = get_interface_ip($interface);
2117
					if (is_ipaddrv4($laddr)) {
2118
						$listen_addresses .= " --listen-address={$laddr} ";
2119
					}
2120
					$laddr6 = get_interface_ipv6($interface);
2121
					if (is_ipaddrv6($laddr6) && !isset($config['dnsmasq']['strictbind'])) {
2122
						/*
2123
						 * XXX: Since dnsmasq does not support link-local address
2124
						 * with scope specified. These checks are being done.
2125
						 */
2126
						if (is_linklocal($laddr6) && strstr($laddr6, "%")) {
2127
							$tmpaddrll6 = explode("%", $laddr6);
2128
							$listen_addresses .= " --listen-address={$tmpaddrll6[0]} ";
2129
						} else {
2130
							$listen_addresses .= " --listen-address={$laddr6} ";
2131
						}
2132
					}
2133
				}
2134
			}
2135
			if (!empty($listen_addresses)) {
2136
				$args .= " {$listen_addresses} ";
2137
				if (isset($config['dnsmasq']['strictbind'])) {
2138
					$args .= " --bind-interfaces ";
2139
				}
2140
			}
2141
		}
2142

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

    
2150
			// Build an array of domain overrides to help in checking for matches.
2151
			$override_a = array();
2152
			if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2153
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2154
					$override_a[$override['domain']] = "y";
2155
				}
2156
			}
2157

    
2158
			// Build an array of the private reverse lookup domain names
2159
			$reverse_domain_a = array("10.in-addr.arpa", "168.192.in-addr.arpa");
2160
			// Unfortunately the 172.16.0.0/12 range does not map nicely to the in-addr.arpa scheme.
2161
			for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) {
2162
				$reverse_domain_a[] = "$subnet_num.172.in-addr.arpa";
2163
			}
2164

    
2165
			// Set the --server parameter to nowhere for each reverse domain name that was not specifically specified in a domain override.
2166
			foreach ($reverse_domain_a as $reverse_domain) {
2167
				if (!isset($override_a[$reverse_domain])) {
2168
					$args .= " --server=/$reverse_domain/ ";
2169
				}
2170
			}
2171
			unset($override_a);
2172
			unset($reverse_domain_a);
2173
		}
2174

    
2175
		/* Setup forwarded domains */
2176
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2177
			foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2178
				if ($override['ip'] == "!") {
2179
					$override[ip] = "";
2180
				}
2181
				$args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
2182
			}
2183
		}
2184

    
2185
		/* Allow DNS Rebind for forwarded domains */
2186
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2187
			if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2188
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2189
					$args .= ' --rebind-domain-ok=/' . $override['domain'] . '/ ';
2190
				}
2191
			}
2192
		}
2193

    
2194
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2195
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2196
		}
2197

    
2198
		if (isset($config['dnsmasq']['strict_order'])) {
2199
			$args .= " --strict-order ";
2200
		}
2201

    
2202
		if (isset($config['dnsmasq']['domain_needed'])) {
2203
			$args .= " --domain-needed ";
2204
		}
2205

    
2206
		if ($config['dnsmasq']['custom_options']) {
2207
			foreach (preg_split('/\s+/', $config['dnsmasq']['custom_options']) as $c) {
2208
				$args .= " " . escapeshellarg("--{$c}");
2209
				$p = explode('=', $c);
2210
				if (array_key_exists($p[0], $standard_args)) {
2211
					unset($standard_args[$p[0]]);
2212
				}
2213
			}
2214
		}
2215
		$args .= ' ' . implode(' ', array_values($standard_args));
2216

    
2217
		/* run dnsmasq. Use "-C /dev/null" since we use command line args only (Issue #6730) */
2218
		$cmd = "/usr/local/sbin/dnsmasq --all-servers -C /dev/null {$dns_rebind} {$args}";
2219
		//log_error("dnsmasq command: {$cmd}");
2220
		mwexec_bg($cmd);
2221
		unset($args);
2222

    
2223
		system_dhcpleases_configure();
2224

    
2225
		if (platform_booting()) {
2226
			echo gettext("done.") . "\n";
2227
		}
2228
	}
2229

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

    
2236
	return $return;
2237
}
2238

    
2239
function services_unbound_configure($restart_dhcp = true) {
2240
	global $config, $g;
2241
	$return = 0;
2242

    
2243
	if (isset($config['system']['developerspew'])) {
2244
		$mt = microtime();
2245
		echo "services_unbound_configure() being called $mt\n";
2246
	}
2247

    
2248
	// kill any running Unbound instance
2249
	if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2250
		sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
2251
	}
2252

    
2253
	if (isset($config['unbound']['enable'])) {
2254
		if (platform_booting()) {
2255
			echo gettext("Starting DNS Resolver...");
2256
		} else {
2257
			sleep(1);
2258
		}
2259

    
2260
		/* generate hosts file */
2261
		if (system_hosts_generate() != 0) {
2262
			$return = 1;
2263
		}
2264

    
2265
		require_once('/etc/inc/unbound.inc');
2266
		sync_unbound_service();
2267
		if (platform_booting()) {
2268
			echo gettext("done.") . "\n";
2269
		}
2270

    
2271
		system_dhcpleases_configure();
2272
	}
2273

    
2274
	if (!platform_booting() && $restart_dhcp) {
2275
		if (services_dhcpd_configure() != 0) {
2276
			$return = 1;
2277
		}
2278
	}
2279

    
2280
	return $return;
2281
}
2282

    
2283
function services_snmpd_configure() {
2284
	global $config, $g;
2285
	if (isset($config['system']['developerspew'])) {
2286
		$mt = microtime();
2287
		echo "services_snmpd_configure() being called $mt\n";
2288
	}
2289

    
2290
	/* kill any running snmpd */
2291
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
2292
	sleep(2);
2293
	if (is_process_running("bsnmpd")) {
2294
		mwexec("/usr/bin/killall bsnmpd", true);
2295
	}
2296

    
2297
	if (isset($config['snmpd']['enable'])) {
2298

    
2299
		if (platform_booting()) {
2300
			echo gettext("Starting SNMP daemon... ");
2301
		}
2302

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

    
2310

    
2311
		$snmpdconf = <<<EOD
2312
location := "{$config['snmpd']['syslocation']}"
2313
contact := "{$config['snmpd']['syscontact']}"
2314
read := "{$config['snmpd']['rocommunity']}"
2315

    
2316
EOD;
2317

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

    
2324
EOD;
2325
		}
2326
*/
2327

    
2328

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

    
2336

    
2337
EOD;
2338
		}
2339

    
2340
		$platform = trim(file_get_contents('/etc/platform'));
2341
		if (($platform == "pfSense") && ($g['product_name'] != "pfSense")) {
2342
			$platform = $g['product_name'];
2343
		}
2344
		$sysDescr = "{$g['product_name']} " . php_uname("n") .
2345
			" {$g['product_version']} {$platform} " . php_uname("s") .
2346
			" " . php_uname("r") . " " . php_uname("m");
2347

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

    
2356
EOD;
2357

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

    
2363
EOD;
2364
		}
2365
*/
2366

    
2367

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

    
2374
EOD;
2375
		}
2376

    
2377

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

    
2381
EOD;
2382

    
2383
		$bind_to_ip = "0.0.0.0";
2384
		if (isset($config['snmpd']['bindip'])) {
2385
			if (is_ipaddr($config['snmpd']['bindip'])) {
2386
				$bind_to_ip = $config['snmpd']['bindip'];
2387
			} else {
2388
				$if = get_real_interface($config['snmpd']['bindip']);
2389
				if (does_interface_exist($if)) {
2390
					$bind_to_ip = get_interface_ip($config['snmpd']['bindip']);
2391
				}
2392
			}
2393
		}
2394

    
2395
		if (is_port($config['snmpd']['pollport'])) {
2396
			$snmpdconf .= <<<EOD
2397
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
2398

    
2399
EOD;
2400

    
2401
		}
2402

    
2403
		$snmpdconf .= <<<EOD
2404
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
2405
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
2406

    
2407
# These are bsnmp macros not php vars.
2408
sysContact      = $(contact)
2409
sysLocation     = $(location)
2410
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
2411

    
2412
snmpEnableAuthenTraps = 2
2413

    
2414
EOD;
2415

    
2416
		if (is_array($config['snmpd']['modules'])) {
2417
			if (isset($config['snmpd']['modules']['mibii'])) {
2418
			$snmpdconf .= <<<EOD
2419
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
2420

    
2421
EOD;
2422
			}
2423

    
2424
			if (isset($config['snmpd']['modules']['netgraph'])) {
2425
				$snmpdconf .= <<<EOD
2426
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
2427
%netgraph
2428
begemotNgControlNodeName = "snmpd"
2429

    
2430
EOD;
2431
			}
2432

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

    
2437
EOD;
2438
			}
2439

    
2440
			if (isset($config['snmpd']['modules']['hostres'])) {
2441
				$snmpdconf .= <<<EOD
2442
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
2443

    
2444
EOD;
2445
			}
2446

    
2447
			if (isset($config['snmpd']['modules']['bridge'])) {
2448
				$snmpdconf .= <<<EOD
2449
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
2450
# config must end with blank line
2451

    
2452
EOD;
2453
			}
2454
			if (isset($config['snmpd']['modules']['ucd'])) {
2455
				$snmpdconf .= <<<EOD
2456
begemotSnmpdModulePath."ucd"     = "/usr/local/lib/snmp_ucd.so"
2457

    
2458
EOD;
2459
			}
2460
			if (isset($config['snmpd']['modules']['regex'])) {
2461
				$snmpdconf .= <<<EOD
2462
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"
2463

    
2464
EOD;
2465
			}
2466
		}
2467

    
2468
		fwrite($fd, $snmpdconf);
2469
		fclose($fd);
2470
		unset($snmpdconf);
2471

    
2472
		/* run bsnmpd */
2473
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
2474
			" -p {$g['varrun_path']}/snmpd.pid");
2475

    
2476
		if (platform_booting()) {
2477
			echo gettext("done.") . "\n";
2478
		}
2479
	}
2480

    
2481
	return 0;
2482
}
2483

    
2484
function services_dnsupdate_process($int = "", $updatehost = "", $forced = false) {
2485
	global $config, $g;
2486
	if (isset($config['system']['developerspew'])) {
2487
		$mt = microtime();
2488
		echo "services_dnsupdate_process() being called $mt\n";
2489
	}
2490

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

    
2518
			/* determine interface name */
2519
			$if = get_failover_interface($dnsupdate['interface']);
2520

    
2521
			if (isset($dnsupdate['usepublicip'])) {
2522
				$wanip = dyndnsCheckIP($if);
2523
			} else {
2524
				$wanip = get_interface_ip($if);
2525
			}
2526

    
2527
			$wanipv6 = get_interface_ipv6($if);
2528
			$cacheFile = "{$g['conf_path']}/dyndns_{$dnsupdate['interface']}_rfc2136_" . escapeshellarg($dnsupdate['host']) . "_{$dnsupdate['server']}.cache";
2529
			$currentTime = time();
2530

    
2531
			if ($wanip || $wanipv6) {
2532
				$keyname = $dnsupdate['keyname'];
2533
				/* trailing dot */
2534
				if (substr($keyname, -1) != ".") {
2535
					$keyname .= ".";
2536
				}
2537

    
2538
				$hostname = $dnsupdate['host'];
2539
				/* trailing dot */
2540
				if (substr($hostname, -1) != ".") {
2541
					$hostname .= ".";
2542
				}
2543

    
2544
				/* write private key file
2545
				   this is dumb - public and private keys are the same for HMAC-MD5,
2546
				   but nsupdate insists on having both */
2547
				$fd = fopen("{$g['varetc_path']}/K{$i}{$keyname}+157+00000.private", "w");
2548
				$privkey = <<<EOD
2549
Private-key-format: v1.2
2550
Algorithm: 157 (HMAC)
2551
Key: {$dnsupdate['keydata']}
2552

    
2553
EOD;
2554
				fwrite($fd, $privkey);
2555
				fclose($fd);
2556

    
2557
				/* write public key file */
2558
				if ($dnsupdate['keytype'] == "zone") {
2559
					$flags = 257;
2560
					$proto = 3;
2561
				} else if ($dnsupdate['keytype'] == "host") {
2562
					$flags = 513;
2563
					$proto = 3;
2564
				} else if ($dnsupdate['keytype'] == "user") {
2565
					$flags = 0;
2566
					$proto = 2;
2567
				}
2568

    
2569
				$fd = fopen("{$g['varetc_path']}/K{$i}{$keyname}+157+00000.key", "w");
2570
				fwrite($fd, "{$keyname} IN KEY {$flags} {$proto} 157 {$dnsupdate['keydata']}\n");
2571
				fclose($fd);
2572

    
2573
				/* generate update instructions */
2574
				$upinst = "";
2575
				if (!empty($dnsupdate['server'])) {
2576
					$upinst .= "server {$dnsupdate['server']}\n";
2577
				}
2578

    
2579
				if (file_exists($cacheFile)) {
2580
					list($cachedipv4, $cacheTimev4) = explode("|", file_get_contents($cacheFile));
2581
				}
2582
				if (file_exists("{$cacheFile}.ipv6")) {
2583
					list($cachedipv6, $cacheTimev6) = explode("|", file_get_contents("{$cacheFile}.ipv6"));
2584
				}
2585

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

    
2590
				conf_mount_rw();
2591
				/* Update IPv4 if we have it. */
2592
				if (is_ipaddrv4($wanip) && $dnsupdate['recordtype'] != "AAAA") {
2593
					if (($wanip != $cachedipv4) || (($currentTime - $cacheTimev4) > $maxCacheAgeSecs) || $forced) {
2594
						$upinst .= "update delete {$dnsupdate['host']}. A\n";
2595
						$upinst .= "update add {$dnsupdate['host']}. {$dnsupdate['ttl']} A {$wanip}\n";
2596
						$notify_text .= sprintf(gettext('DynDNS updated IP Address (A) for %1$s on %2$s (%3$s) to %4$s'), $dnsupdate['host'], convert_real_interface_to_friendly_descr($if), $if, $wanip) . "\n";
2597
						@file_put_contents($cacheFile, "{$wanip}|{$currentTime}");
2598
						log_error(sprintf(gettext('phpDynDNS: updating cache file %1$s: %2$s'), $cacheFile, $wanip));
2599
						$need_update = true;
2600
					} else {
2601
						log_error(sprintf(gettext("phpDynDNS: Not updating %s A record because the IP address has not changed."), $dnsupdate['host']));
2602
					}
2603
				} else {
2604
					@unlink($cacheFile);
2605
				}
2606

    
2607
				/* Update IPv6 if we have it. */
2608
				if (is_ipaddrv6($wanipv6) && $dnsupdate['recordtype'] != "A") {
2609
					if (($wanipv6 != $cachedipv6) || (($currentTime - $cacheTimev6) > $maxCacheAgeSecs) || $forced) {
2610
						$upinst .= "update delete {$dnsupdate['host']}. AAAA\n";
2611
						$upinst .= "update add {$dnsupdate['host']}. {$dnsupdate['ttl']} AAAA {$wanipv6}\n";
2612
						$notify_text .= sprintf(gettext('DynDNS updated IPv6 Address (AAAA) for %1$s on %2$s (%3$s) to %4$s'), $dnsupdate['host'], convert_real_interface_to_friendly_descr($if), $if, $wanipv6) . "\n";
2613
						@file_put_contents("{$cacheFile}.ipv6", "{$wanipv6}|{$currentTime}");
2614
						log_error(sprintf(gettext('phpDynDNS: updating cache file %1$s.ipv6: %2$s'), $cacheFile, $wanipv6));
2615
						$need_update = true;
2616
					} else {
2617
						log_error(sprintf(gettext("phpDynDNS: Not updating %s AAAA record because the IPv6 address has not changed."), $dnsupdate['host']));
2618
					}
2619
				} else {
2620
					@unlink("{$cacheFile}.ipv6");
2621
				}
2622
				conf_mount_ro();
2623

    
2624
				$upinst .= "\n";	/* mind that trailing newline! */
2625

    
2626
				if ($need_update) {
2627
					@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}", $upinst);
2628
					unset($upinst);
2629
					/* invoke nsupdate */
2630
					$cmd = "/usr/local/bin/nsupdate -k {$g['varetc_path']}/K{$i}{$keyname}+157+00000.key";
2631
					if (isset($dnsupdate['usetcp'])) {
2632
						$cmd .= " -v";
2633
					}
2634
					$cmd .= " {$g['varetc_path']}/nsupdatecmds{$i}";
2635
					mwexec_bg($cmd);
2636
					unset($cmd);
2637
				}
2638
			}
2639
		}
2640
		if (!empty($notify_text)) {
2641
			notify_all_remote($notify_text);
2642
		}
2643
	}
2644

    
2645
	return 0;
2646
}
2647

    
2648
/* configure cron service */
2649
function configure_cron() {
2650
	global $g, $config;
2651

    
2652
	conf_mount_rw();
2653
	/* preserve existing crontab entries */
2654
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2655

    
2656
	for ($i = 0; $i < count($crontab_contents); $i++) {
2657
		$cron_item =& $crontab_contents[$i];
2658
		if (strpos($cron_item, "# pfSense specific crontab entries") !== false) {
2659
			array_splice($crontab_contents, $i - 1);
2660
			break;
2661
		}
2662
	}
2663
	$crontab_contents = implode("\n", $crontab_contents) . "\n";
2664

    
2665

    
2666
	if (is_array($config['cron']['item'])) {
2667
		$crontab_contents .= "#\n";
2668
		$crontab_contents .= "# pfSense specific crontab entries\n";
2669
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
2670
		$crontab_contents .= "#\n";
2671

    
2672
		if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) {
2673
			$http_proxy = $config['system']['proxyurl'];
2674
			if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) {
2675
				$http_proxy .= ':' . $config['system']['proxyport'];
2676
			}
2677
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
2678
		}
2679

    
2680
		foreach ($config['cron']['item'] as $item) {
2681
			$crontab_contents .= "\n{$item['minute']}\t";
2682
			$crontab_contents .= "{$item['hour']}\t";
2683
			$crontab_contents .= "{$item['mday']}\t";
2684
			$crontab_contents .= "{$item['month']}\t";
2685
			$crontab_contents .= "{$item['wday']}\t";
2686
			$crontab_contents .= "{$item['who']}\t";
2687
			$crontab_contents .= "{$item['command']}";
2688
		}
2689

    
2690
		$crontab_contents .= "\n#\n";
2691
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
2692
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
2693
		$crontab_contents .= "#\n\n";
2694
	}
2695

    
2696
	/* please maintain the newline at the end of file */
2697
	file_put_contents("/etc/crontab", $crontab_contents);
2698
	unset($crontab_contents);
2699

    
2700
	/* make sure that cron is running and start it if it got killed somehow */
2701
	if (!is_process_running("cron")) {
2702
		exec("cd /tmp && /usr/sbin/cron -s 2>/dev/null");
2703
	} else {
2704
	/* do a HUP kill to force sync changes */
2705
		sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP");
2706
	}
2707

    
2708
	conf_mount_ro();
2709
}
2710

    
2711
function upnp_action ($action) {
2712
	global $g, $config;
2713
	switch ($action) {
2714
		case "start":
2715
			if (file_exists('/var/etc/miniupnpd.conf')) {
2716
				@unlink("{$g['varrun_path']}/miniupnpd.pid");
2717
				mwexec_bg("/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf -P {$g['varrun_path']}/miniupnpd.pid");
2718
			}
2719
			break;
2720
		case "stop":
2721
			killbypid("{$g['varrun_path']}/miniupnpd.pid");
2722
			while ((int)exec("/bin/pgrep -a miniupnpd | wc -l") > 0) {
2723
				mwexec('/usr/bin/killall miniupnpd 2>/dev/null', true);
2724
			}
2725
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
2726
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
2727
			break;
2728
		case "restart":
2729
			upnp_action('stop');
2730
			upnp_action('start');
2731
			break;
2732
	}
2733
}
2734

    
2735
function upnp_start() {
2736
	global $config;
2737

    
2738
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
2739
		return;
2740
	}
2741

    
2742
	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
2743
		echo gettext("Starting UPnP service... ");
2744
		require_once('/usr/local/pkg/miniupnpd.inc');
2745
		sync_package_miniupnpd();
2746
		echo "done.\n";
2747
	}
2748
}
2749

    
2750
function install_cron_job($command, $active = false, $minute = "0", $hour = "*", $monthday = "*", $month = "*", $weekday = "*", $who = "root") {
2751
	global $config, $g;
2752

    
2753
	$is_installed = false;
2754
	$cron_changed = true;
2755

    
2756
	if (!is_array($config['cron'])) {
2757
		$config['cron'] = array();
2758
	}
2759
	if (!is_array($config['cron']['item'])) {
2760
		$config['cron']['item'] = array();
2761
	}
2762

    
2763
	$x = 0;
2764
	foreach ($config['cron']['item'] as $item) {
2765
		if (strstr($item['command'], $command)) {
2766
			$is_installed = true;
2767
			break;
2768
		}
2769
		$x++;
2770
	}
2771

    
2772
	if ($active) {
2773
		$cron_item = array();
2774
		$cron_item['minute'] = $minute;
2775
		$cron_item['hour'] = $hour;
2776
		$cron_item['mday'] = $monthday;
2777
		$cron_item['month'] = $month;
2778
		$cron_item['wday'] = $weekday;
2779
		$cron_item['who'] = $who;
2780
		$cron_item['command'] = $command;
2781
		if (!$is_installed) {
2782
			$config['cron']['item'][] = $cron_item;
2783
			write_config(sprintf(gettext("Installed cron job for %s"), $command));
2784
		} else {
2785
			if ($config['cron']['item'][$x] == $cron_item) {
2786
				$cron_changed = false;
2787
				log_error(sprintf(gettext("Checked cron job for %s, no change needed"), $command));
2788
			} else {
2789
				$config['cron']['item'][$x] = $cron_item;
2790
				write_config(sprintf(gettext("Updated cron job for %s"), $command));
2791
			}
2792
		}
2793
	} else {
2794
		if ($is_installed == true) {
2795
			unset($config['cron']['item'][$x]);
2796
			write_config(sprintf(gettext("Removed cron job for %s"), $command));
2797
		}
2798
	}
2799

    
2800
	if ($cron_changed) {
2801
		configure_cron();
2802
	}
2803
}
2804

    
2805
?>
(38-38/50)