Project

General

Profile

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

    
26
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 (!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

    
554
EOD;
555

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

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

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

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

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

    
585
		interfaces_staticarp_configure($dhcpif);
586

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

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

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

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

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

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

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

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

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

    
674
		$dnscfg = "";
675

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

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

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

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

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

    
713
			}
714

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

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

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

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

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

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

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

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

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

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

    
854
			$pdnscfg = "";
855

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1030
EOD;
1031

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

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

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

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

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

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

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

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

    
1068
				$smdnscfg = "";
1069

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1167
	return 0;
1168
}
1169

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

    
1179
	return $dhcpdconf;
1180
}
1181

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

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

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

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

    
1232
	return $dhcpdconf;
1233
}
1234

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

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

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

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

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

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

    
1318
EOD;
1319

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

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

    
1328
	$dhcpdv6ifs = array();
1329

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

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

    
1335
		$ddns_zones = array();
1336

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

    
1339
		if (!isset($dhcpv6ifconf['enable']) || !isset($Iflist[$dhcpv6if]) || !isset($ifcfgv6['enable'])) {
1340
			continue;
1341
		}
1342
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1343
		if (!is_ipaddrv6($ifcfgipv6)) {
1344
			continue;
1345
		}
1346
		$ifcfgsnv6 = get_interface_subnetv6($dhcpv6if);
1347
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1348
		// We might have some prefix-delegation on WAN (e.g. /48),
1349
		// but then it is split and given out to individual interfaces
1350
		// (LAN, OPT1, OPT2...) as multiple /64 subnets. So the size
1351
		// of each subnet here is always /64.
1352
		$pdlen = 64;
1353

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

    
1360
		$dnscfgv6 = "";
1361

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

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

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

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

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

    
1406
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1407

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

    
1428
		$dhcpdv6conf .= " {\n";
1429

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

    
1437
		$dhcpdv6conf .= <<<EOD
1438
	range6 {$range_from} {$range_to};
1439
$dnscfgv6
1440

    
1441
EOD;
1442

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

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

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

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

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

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

    
1514
		$dhcpdv6conf .= "}\n";
1515

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

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

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

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

    
1547
				$dhcpdv6conf .= "}\n";
1548
				$i++;
1549
			}
1550
		}
1551

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

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

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

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

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

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

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

    
1611
	return 0;
1612
}
1613

    
1614
function services_igmpproxy_configure() {
1615
	global $config, $g;
1616

    
1617
	/* kill any running igmpproxy */
1618
	killbyname("igmpproxy");
1619

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

    
1624
	$iflist = get_configured_interface_list();
1625

    
1626
	$igmpconf = <<<EOD
1627

    
1628
##------------------------------------------------------
1629
## Enable Quickleave mode (Sends Leave instantly)
1630
##------------------------------------------------------
1631
quickleave
1632

    
1633
EOD;
1634

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

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

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

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

    
1674
	log_error(gettext("Started IGMP proxy service."));
1675

    
1676
	return 0;
1677
}
1678

    
1679
function services_dhcrelay_configure() {
1680
	global $config, $g;
1681

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

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

    
1690
	$dhcrelaycfg =& $config['dhcrelay'];
1691

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

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

    
1703
	$iflist = get_configured_interface_list();
1704

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

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

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

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

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

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

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

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

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

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

    
1806
	$cmd .= " " . implode(" ", $srvips);
1807
	mwexec($cmd);
1808
	unset($cmd);
1809

    
1810
	return 0;
1811
}
1812

    
1813
function services_dhcrelay6_configure() {
1814
	global $config, $g;
1815

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

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

    
1824
	$dhcrelaycfg =& $config['dhcrelay6'];
1825

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

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

    
1837
	$iflist = get_configured_interface_list();
1838

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

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

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

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

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

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

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

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

    
1934
	return 0;
1935
}
1936

    
1937
function services_dyndns_configure_client($conf) {
1938

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

    
1943
	/* load up the dyndns.class */
1944
	require_once("dyndns.class");
1945

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

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

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

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

    
2005
		if (platform_booting()) {
2006
			echo gettext("done.") . "\n";
2007
		}
2008
	}
2009

    
2010
	return 0;
2011
}
2012

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

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

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

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

    
2061
function services_dnsmasq_configure($restart_dhcp = true) {
2062
	global $config, $g;
2063
	$return = 0;
2064

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

    
2072

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

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

    
2083
	if (isset($config['dnsmasq']['enable'])) {
2084

    
2085
		if (platform_booting()) {
2086
			echo gettext("Starting DNS forwarder...");
2087
		} else {
2088
			sleep(1);
2089
		}
2090

    
2091
		/* generate hosts file */
2092
		if (system_hosts_generate() != 0) {
2093
			$return = 1;
2094
		}
2095

    
2096
		$args = "";
2097

    
2098
		if (isset($config['dnsmasq']['regdhcp'])) {
2099
			$args .= " --dhcp-hostsfile={$g['etc_path']}/hosts ";
2100
		}
2101

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

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

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

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

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

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

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

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

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

    
2195
		if (isset($config['dnsmasq']['strict_order'])) {
2196
			$args .= " --strict-order ";
2197
		}
2198

    
2199
		if (isset($config['dnsmasq']['domain_needed'])) {
2200
			$args .= " --domain-needed ";
2201
		}
2202

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

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

    
2220
		system_dhcpleases_configure();
2221

    
2222
		if (platform_booting()) {
2223
			echo gettext("done.") . "\n";
2224
		}
2225
	}
2226

    
2227
	if (!platform_booting() && $restart_dhcp) {
2228
		if (services_dhcpd_configure() != 0) {
2229
			$return = 1;
2230
		}
2231
	}
2232

    
2233
	return $return;
2234
}
2235

    
2236
function services_unbound_configure($restart_dhcp = true) {
2237
	global $config, $g;
2238
	$return = 0;
2239

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

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

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

    
2257
		/* generate hosts file */
2258
		if (system_hosts_generate() != 0) {
2259
			$return = 1;
2260
		}
2261

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

    
2268
		system_dhcpleases_configure();
2269
	}
2270

    
2271
	if (!platform_booting() && $restart_dhcp) {
2272
		if (services_dhcpd_configure() != 0) {
2273
			$return = 1;
2274
		}
2275
	}
2276

    
2277
	return $return;
2278
}
2279

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

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

    
2294
	if (isset($config['snmpd']['enable'])) {
2295

    
2296
		if (platform_booting()) {
2297
			echo gettext("Starting SNMP daemon... ");
2298
		}
2299

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

    
2307

    
2308
		$snmpdconf = <<<EOD
2309
location := "{$config['snmpd']['syslocation']}"
2310
contact := "{$config['snmpd']['syscontact']}"
2311
read := "{$config['snmpd']['rocommunity']}"
2312

    
2313
EOD;
2314

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

    
2321
EOD;
2322
		}
2323
*/
2324

    
2325

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

    
2333

    
2334
EOD;
2335
		}
2336

    
2337
		$sysDescr = "{$g['product_name']} " . php_uname("n") .
2338
			" {$g['product_version']} {$g['platform']} " . php_uname("s") .
2339
			" " . php_uname("r") . " " . php_uname("m");
2340

    
2341
		$snmpdconf .= <<<EOD
2342
system := 1     # pfSense
2343
%snmpd
2344
sysDescr			= "{$sysDescr}"
2345
begemotSnmpdDebugDumpPdus       = 2
2346
begemotSnmpdDebugSyslogPri      = 7
2347
begemotSnmpdCommunityString.0.1 = $(read)
2348

    
2349
EOD;
2350

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

    
2356
EOD;
2357
		}
2358
*/
2359

    
2360

    
2361
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2362
			$snmpdconf .= <<<EOD
2363
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
2364
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
2365
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
2366

    
2367
EOD;
2368
		}
2369

    
2370

    
2371
		$snmpdconf .= <<<EOD
2372
begemotSnmpdCommunityDisable    = 1
2373

    
2374
EOD;
2375

    
2376
		$bind_to_ip = "0.0.0.0";
2377
		if (isset($config['snmpd']['bindip'])) {
2378
			if (is_ipaddr($config['snmpd']['bindip'])) {
2379
				$bind_to_ip = $config['snmpd']['bindip'];
2380
			} else {
2381
				$if = get_real_interface($config['snmpd']['bindip']);
2382
				if (does_interface_exist($if)) {
2383
					$bind_to_ip = get_interface_ip($config['snmpd']['bindip']);
2384
				}
2385
			}
2386
		}
2387

    
2388
		if (is_port($config['snmpd']['pollport'])) {
2389
			$snmpdconf .= <<<EOD
2390
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
2391

    
2392
EOD;
2393

    
2394
		}
2395

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

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

    
2405
snmpEnableAuthenTraps = 2
2406

    
2407
EOD;
2408

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

    
2414
EOD;
2415
			}
2416

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

    
2423
EOD;
2424
			}
2425

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

    
2430
EOD;
2431
			}
2432

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

    
2437
EOD;
2438
			}
2439

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

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

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

    
2457
EOD;
2458
			}
2459
		}
2460

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

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

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

    
2474
	return 0;
2475
}
2476

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

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

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

    
2514
			if (isset($dnsupdate['usepublicip'])) {
2515
				$wanip = dyndnsCheckIP($if);
2516
			} else {
2517
				$wanip = get_interface_ip($if);
2518
			}
2519

    
2520
			$wanipv6 = get_interface_ipv6($if);
2521
			$cacheFile = "{$g['conf_path']}/dyndns_{$dnsupdate['interface']}_rfc2136_" . escapeshellarg($dnsupdate['host']) . "_{$dnsupdate['server']}.cache";
2522
			$currentTime = time();
2523

    
2524
			if ($wanip || $wanipv6) {
2525
				$keyname = $dnsupdate['keyname'];
2526
				/* trailing dot */
2527
				if (substr($keyname, -1) != ".") {
2528
					$keyname .= ".";
2529
				}
2530

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

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

    
2546
EOD;
2547
				fwrite($fd, $privkey);
2548
				fclose($fd);
2549

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

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

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

    
2572
				if (file_exists($cacheFile)) {
2573
					list($cachedipv4, $cacheTimev4) = explode("|", file_get_contents($cacheFile));
2574
				}
2575
				if (file_exists("{$cacheFile}.ipv6")) {
2576
					list($cachedipv6, $cacheTimev6) = explode("|", file_get_contents("{$cacheFile}.ipv6"));
2577
				}
2578

    
2579
				// 25 Days
2580
				$maxCacheAgeSecs = 25 * 24 * 60 * 60;
2581
				$need_update = false;
2582

    
2583
				/* Update IPv4 if we have it. */
2584
				if (is_ipaddrv4($wanip) && $dnsupdate['recordtype'] != "AAAA") {
2585
					if (($wanip != $cachedipv4) || (($currentTime - $cacheTimev4) > $maxCacheAgeSecs) || $forced) {
2586
						$upinst .= "update delete {$dnsupdate['host']}. A\n";
2587
						$upinst .= "update add {$dnsupdate['host']}. {$dnsupdate['ttl']} A {$wanip}\n";
2588
						$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";
2589
						@file_put_contents($cacheFile, "{$wanip}|{$currentTime}");
2590
						log_error(sprintf(gettext('phpDynDNS: updating cache file %1$s: %2$s'), $cacheFile, $wanip));
2591
						$need_update = true;
2592
					} else {
2593
						log_error(sprintf(gettext("phpDynDNS: Not updating %s A record because the IP address has not changed."), $dnsupdate['host']));
2594
					}
2595
				} else {
2596
					@unlink($cacheFile);
2597
				}
2598

    
2599
				/* Update IPv6 if we have it. */
2600
				if (is_ipaddrv6($wanipv6) && $dnsupdate['recordtype'] != "A") {
2601
					if (($wanipv6 != $cachedipv6) || (($currentTime - $cacheTimev6) > $maxCacheAgeSecs) || $forced) {
2602
						$upinst .= "update delete {$dnsupdate['host']}. AAAA\n";
2603
						$upinst .= "update add {$dnsupdate['host']}. {$dnsupdate['ttl']} AAAA {$wanipv6}\n";
2604
						$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";
2605
						@file_put_contents("{$cacheFile}.ipv6", "{$wanipv6}|{$currentTime}");
2606
						log_error(sprintf(gettext('phpDynDNS: updating cache file %1$s.ipv6: %2$s'), $cacheFile, $wanipv6));
2607
						$need_update = true;
2608
					} else {
2609
						log_error(sprintf(gettext("phpDynDNS: Not updating %s AAAA record because the IPv6 address has not changed."), $dnsupdate['host']));
2610
					}
2611
				} else {
2612
					@unlink("{$cacheFile}.ipv6");
2613
				}
2614

    
2615
				$upinst .= "\n";	/* mind that trailing newline! */
2616

    
2617
				if ($need_update) {
2618
					@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}", $upinst);
2619
					unset($upinst);
2620
					/* invoke nsupdate */
2621
					$cmd = "/usr/local/bin/nsupdate -k {$g['varetc_path']}/K{$i}{$keyname}+157+00000.key";
2622
					if (isset($dnsupdate['usetcp'])) {
2623
						$cmd .= " -v";
2624
					}
2625
					$cmd .= " {$g['varetc_path']}/nsupdatecmds{$i}";
2626
					mwexec_bg($cmd);
2627
					unset($cmd);
2628
				}
2629
			}
2630
		}
2631
		if (!empty($notify_text)) {
2632
			notify_all_remote($notify_text);
2633
		}
2634
	}
2635

    
2636
	return 0;
2637
}
2638

    
2639
/* configure cron service */
2640
function configure_cron() {
2641
	global $g, $config;
2642

    
2643
	/* preserve existing crontab entries */
2644
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2645

    
2646
	for ($i = 0; $i < count($crontab_contents); $i++) {
2647
		$cron_item =& $crontab_contents[$i];
2648
		if (strpos($cron_item, "# pfSense specific crontab entries") !== false) {
2649
			array_splice($crontab_contents, $i - 1);
2650
			break;
2651
		}
2652
	}
2653
	$crontab_contents = implode("\n", $crontab_contents) . "\n";
2654

    
2655

    
2656
	if (is_array($config['cron']['item'])) {
2657
		$crontab_contents .= "#\n";
2658
		$crontab_contents .= "# pfSense specific crontab entries\n";
2659
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
2660
		$crontab_contents .= "#\n";
2661

    
2662
		if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) {
2663
			$http_proxy = $config['system']['proxyurl'];
2664
			if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) {
2665
				$http_proxy .= ':' . $config['system']['proxyport'];
2666
			}
2667
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
2668
		}
2669

    
2670
		foreach ($config['cron']['item'] as $item) {
2671
			$crontab_contents .= "\n{$item['minute']}\t";
2672
			$crontab_contents .= "{$item['hour']}\t";
2673
			$crontab_contents .= "{$item['mday']}\t";
2674
			$crontab_contents .= "{$item['month']}\t";
2675
			$crontab_contents .= "{$item['wday']}\t";
2676
			$crontab_contents .= "{$item['who']}\t";
2677
			$crontab_contents .= "{$item['command']}";
2678
		}
2679

    
2680
		$crontab_contents .= "\n#\n";
2681
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
2682
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
2683
		$crontab_contents .= "#\n\n";
2684
	}
2685

    
2686
	/* please maintain the newline at the end of file */
2687
	file_put_contents("/etc/crontab", $crontab_contents);
2688
	unset($crontab_contents);
2689

    
2690
	/* make sure that cron is running and start it if it got killed somehow */
2691
	if (!is_process_running("cron")) {
2692
		exec("cd /tmp && /usr/sbin/cron -s 2>/dev/null");
2693
	} else {
2694
	/* do a HUP kill to force sync changes */
2695
		sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP");
2696
	}
2697

    
2698
}
2699

    
2700
function upnp_action ($action) {
2701
	global $g, $config;
2702
	switch ($action) {
2703
		case "start":
2704
			if (file_exists('/var/etc/miniupnpd.conf')) {
2705
				@unlink("{$g['varrun_path']}/miniupnpd.pid");
2706
				mwexec_bg("/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf -P {$g['varrun_path']}/miniupnpd.pid");
2707
			}
2708
			break;
2709
		case "stop":
2710
			killbypid("{$g['varrun_path']}/miniupnpd.pid");
2711
			while ((int)exec("/bin/pgrep -a miniupnpd | wc -l") > 0) {
2712
				mwexec('/usr/bin/killall miniupnpd 2>/dev/null', true);
2713
			}
2714
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
2715
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
2716
			break;
2717
		case "restart":
2718
			upnp_action('stop');
2719
			upnp_action('start');
2720
			break;
2721
	}
2722
}
2723

    
2724
function upnp_start() {
2725
	global $config;
2726

    
2727
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
2728
		return;
2729
	}
2730

    
2731
	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
2732
		echo gettext("Starting UPnP service... ");
2733
		require_once('/usr/local/pkg/miniupnpd.inc');
2734
		sync_package_miniupnpd();
2735
		echo "done.\n";
2736
	}
2737
}
2738

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

    
2742
	$is_installed = false;
2743
	$cron_changed = true;
2744

    
2745
	if (!is_array($config['cron'])) {
2746
		$config['cron'] = array();
2747
	}
2748
	if (!is_array($config['cron']['item'])) {
2749
		$config['cron']['item'] = array();
2750
	}
2751

    
2752
	$x = 0;
2753
	foreach ($config['cron']['item'] as $item) {
2754
		if (strstr($item['command'], $command)) {
2755
			$is_installed = true;
2756
			break;
2757
		}
2758
		$x++;
2759
	}
2760

    
2761
	if ($active) {
2762
		$cron_item = array();
2763
		$cron_item['minute'] = $minute;
2764
		$cron_item['hour'] = $hour;
2765
		$cron_item['mday'] = $monthday;
2766
		$cron_item['month'] = $month;
2767
		$cron_item['wday'] = $weekday;
2768
		$cron_item['who'] = $who;
2769
		$cron_item['command'] = $command;
2770
		if (!$is_installed) {
2771
			$config['cron']['item'][] = $cron_item;
2772
			write_config(sprintf(gettext("Installed cron job for %s"), $command));
2773
		} else {
2774
			if ($config['cron']['item'][$x] == $cron_item) {
2775
				$cron_changed = false;
2776
				log_error(sprintf(gettext("Checked cron job for %s, no change needed"), $command));
2777
			} else {
2778
				$config['cron']['item'][$x] = $cron_item;
2779
				write_config(sprintf(gettext("Updated cron job for %s"), $command));
2780
			}
2781
		}
2782
	} else {
2783
		if ($is_installed == true) {
2784
			unset($config['cron']['item'][$x]);
2785
			write_config(sprintf(gettext("Removed cron job for %s"), $command));
2786
		}
2787
	}
2788

    
2789
	if ($cron_changed) {
2790
		configure_cron();
2791
	}
2792
}
2793

    
2794
?>
(38-38/51)