Project

General

Profile

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

    
28

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

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

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

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

    
45
	$Iflist = get_configured_interface_list();
46
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
47

    
48
	$radvdconf = "# Automatically Generated, do not edit\n";
49

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

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

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

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

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

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

    
92
		$realif = get_real_interface($dhcpv6if, "inet6");
93

    
94
		if (isset($radvdifs[$realif])) {
95
			continue;
96
		}
97

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

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

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

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

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

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

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

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

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

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

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

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

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

    
316
		$realif = get_real_interface($if, "inet6");
317

    
318
		/* prevent duplicate entries, manual overrides */
319
		if (isset($radvdifs[$realif])) {
320
			continue;
321
		}
322

    
323
		$ifcfgipv6 = get_interface_ipv6($if);
324
		if (!is_ipaddrv6($ifcfgipv6)) {
325
			$subnetv6 = "::";
326
			$ifcfgsnv6 = "64";
327
		} else {
328
			$ifcfgsnv6 = get_interface_subnetv6($if);
329
			$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
330
		}
331
		$radvdifs[$realif] = $realif;
332

    
333
		$autotype = $config['interfaces'][$trackif]['ipaddrv6'];
334

    
335
		if ($g['debug']) {
336
			log_error("configuring RA on {$if} for type {$autotype} radvd subnet {$subnetv6}/{$ifcfgsnv6}");
337
		}
338

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

    
364
		/* add DNS servers */
365
		if ($dhcpv6ifconf['radvd-dns'] != 'disabled') {
366
			$dnslist = array();
367
			if (isset($config['dnsmasq']['enable']) || isset($config['unbound']['enable'])) {
368
				$dnslist[] = $ifcfgipv6;
369
			} elseif (is_array($config['system']['dnsserver']) && !empty($config['system']['dnsserver'])) {
370
				foreach ($config['system']['dnsserver'] as $server) {
371
					if (is_ipaddrv6($server)) {
372
						$dnslist[] = $server;
373
					}
374
				}
375
			}
376
			if (count($dnslist) > 0) {
377
				$dnsstring = implode(" ", $dnslist);
378
				if (!empty($dnsstring)) {
379
					$radvdconf .= "\tRDNSS {$dnsstring} { };\n";
380
				}
381
			}
382
			if (!empty($config['system']['domain'])) {
383
				$radvdconf .= "\tDNSSL {$config['system']['domain']} { };\n";
384
			}
385
		}
386
		$radvdconf .= "};\n";
387
	}
388

    
389
	/* write radvd.conf */
390
	if (!@file_put_contents("{$g['varetc_path']}/radvd.conf", $radvdconf)) {
391
		log_error(gettext("Error: cannot open radvd.conf in services_radvd_configure()."));
392
		if (platform_booting()) {
393
			printf("Error: cannot open radvd.conf in services_radvd_configure().\n");
394
		}
395
	}
396
	unset($radvdconf);
397

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

    
416
function services_dhcpd_configure($family = "all", $blacklist = array()) {
417
	global $config, $g;
418

    
419
	$dhcpdconfigurelck = lock("dhcpdconfigure", LOCK_EX);
420

    
421
	/* configure DHCPD chroot once */
422
	$fd = fopen("{$g['tmp_path']}/dhcpd.sh", "w");
423
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}\n");
424
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/dev\n");
425
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/etc\n");
426
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/usr/local/sbin\n");
427
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db\n");
428
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run\n");
429
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/usr\n");
430
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/lib\n");
431
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/run\n");
432
	fwrite($fd, "/usr/sbin/chown -R dhcpd:_dhcp {$g['dhcpd_chroot_path']}/*\n");
433
	fwrite($fd, "/bin/cp -n /lib/libc.so.* {$g['dhcpd_chroot_path']}/lib/\n");
434
	fwrite($fd, "/bin/cp -n /usr/local/sbin/dhcpd {$g['dhcpd_chroot_path']}/usr/local/sbin/\n");
435
	fwrite($fd, "/bin/chmod a+rx {$g['dhcpd_chroot_path']}/usr/local/sbin/dhcpd\n");
436

    
437
	$status = `/sbin/mount | /usr/bin/grep -v grep | /usr/bin/grep "{$g['dhcpd_chroot_path']}/dev"`;
438
	if (!trim($status)) {
439
		fwrite($fd, "/sbin/mount -t devfs devfs {$g['dhcpd_chroot_path']}/dev\n");
440
	}
441
	fclose($fd);
442
	mwexec("/bin/sh {$g['tmp_path']}/dhcpd.sh");
443

    
444
	if ($family == "all" || $family == "inet") {
445
		services_dhcpdv4_configure();
446
	}
447
	if ($family == "all" || $family == "inet6") {
448
		services_dhcpdv6_configure($blacklist);
449
		services_radvd_configure($blacklist);
450
	}
451

    
452
	unlock($dhcpdconfigurelck);
453
}
454

    
455
function services_dhcpdv4_configure() {
456
	global $config, $g;
457
	$need_ddns_updates = false;
458
	$ddns_zones = array();
459

    
460
	if ($g['services_dhcp_server_enable'] == false) {
461
		return;
462
	}
463

    
464
	if (isset($config['system']['developerspew'])) {
465
		$mt = microtime();
466
		echo "services_dhcpdv4_configure($if) being called $mt\n";
467
	}
468

    
469
	/* kill any running dhcpd */
470
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid")) {
471
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid");
472
	}
473

    
474
	/* DHCP enabled on any interfaces? */
475
	if (!is_dhcp_server_enabled()) {
476
		return 0;
477
	}
478

    
479
	$syscfg = $config['system'];
480
	if (!is_array($config['dhcpd'])) {
481
		$config['dhcpd'] = array();
482
	}
483
	$dhcpdcfg = $config['dhcpd'];
484
	$Iflist = get_configured_interface_list();
485

    
486
	/* Only consider DNS servers with IPv4 addresses for the IPv4 DHCP server. */
487
	$dns_arrv4 = array();
488
	if (is_array($syscfg['dnsserver'])) {
489
		foreach ($syscfg['dnsserver'] as $dnsserver) {
490
			if (is_ipaddrv4($dnsserver)) {
491
				$dns_arrv4[] = $dnsserver;
492
			}
493
		}
494
	}
495

    
496
	if (platform_booting()) {
497
		echo gettext("Starting DHCP service...");
498
	} else {
499
		sleep(1);
500
	}
501

    
502
	$custoptions = "";
503
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
504
		if (is_array($dhcpifconf['numberoptions']) && is_array($dhcpifconf['numberoptions']['item'])) {
505
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
506
				if (!empty($item['type'])) {
507
					$itemtype = $item['type'];
508
				} else {
509
					$itemtype = "text";
510
				}
511
				$custoptions .= "option custom-{$dhcpif}-{$itemidx} code {$item['number']} = {$itemtype};\n";
512
			}
513
		}
514
		if (is_array($dhcpifconf['pool'])) {
515
			foreach ($dhcpifconf['pool'] as $poolidx => $poolconf) {
516
				if (is_array($poolconf['numberoptions']) && is_array($poolconf['numberoptions']['item'])) {
517
					foreach ($poolconf['numberoptions']['item'] as $itemidx => $item) {
518
						if (!empty($item['type'])) {
519
							$itemtype = $item['type'];
520
						} else {
521
							$itemtype = "text";
522
						}
523
						$custoptions .= "option custom-{$dhcpif}-{$poolidx}-{$itemidx} code {$item['number']} = {$itemtype};\n";
524
					}
525
				}
526
			}
527
		}
528
		if (is_array($dhcpifconf['staticmap'])) {
529
			$i = 0;
530
			foreach ($dhcpifconf['staticmap'] as $sm) {
531
				if (is_array($sm['numberoptions']) && is_array($sm['numberoptions']['item'])) {
532
					foreach ($sm['numberoptions']['item'] as $itemidx => $item) {
533
						if (!empty($item['type'])) {
534
							$itemtype = $item['type'];
535
						} else {
536
							$itemtype = "text";
537
						}
538
						$custoptions .= "option custom-s_{$dhcpif}_{$i}-{$itemidx} code {$item['number']} = {$itemtype};\n";
539
					}
540
				}
541
				$i++;
542
			}
543
		}
544
	}
545

    
546
	$dhcpdconf = <<<EOD
547

    
548
option domain-name "{$syscfg['domain']}";
549
option ldap-server code 95 = text;
550
option domain-search-list code 119 = text;
551
option arch code 93 = unsigned integer 16; # RFC4578
552
{$custoptions}
553
default-lease-time 7200;
554
max-lease-time 86400;
555
log-facility local7;
556
one-lease-per-client true;
557
deny duplicates;
558
update-conflict-detection false;
559

    
560
EOD;
561

    
562
	/* take these settings from the first DHCP configured interface,
563
	 * see https://redmine.pfsense.org/issues/10270 
564
	 * TODO: Global Settings tab, see https://redmine.pfsense.org/issues/5080 */
565
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
566
		if (!isset($dhcpifconf['disableauthoritative'])) {
567
			$dhcpdconf .= "authoritative;\n";
568
		}
569

    
570
		if (isset($dhcpifconf['alwaysbroadcast'])) {
571
			$dhcpdconf .= "always-broadcast on\n";
572
		}
573

    
574
		// OMAPI Settings
575
		if (isset($dhcpifconf['omapi_port']) && is_numeric($dhcpifconf['omapi_port'])) {
576
			$dhcpdconf .= <<<EOD
577

    
578
key omapi_key {
579
  algorithm {$dhcpifconf['omapi_key_algorithm']};
580
  secret "{$dhcpifconf['omapi_key']}";
581
};
582
omapi-port {$dhcpifconf['omapi_port']};
583
omapi-key omapi_key;
584

    
585
EOD;
586

    
587
		}
588
		break;
589
	}
590

    
591
	$dhcpdifs = array();
592
	$enable_add_routers = false;
593
	$gateways_arr = return_gateways_array();
594
	/* only add a routers line if the system has any IPv4 gateway at all */
595
	/* a static route has a gateway, manually overriding this field always works */
596
	foreach ($gateways_arr as $gwitem) {
597
		if ($gwitem['ipprotocol'] == "inet") {
598
			$enable_add_routers = true;
599
			break;
600
		}
601
	}
602

    
603
	/*    loop through and determine if we need to setup
604
	 *    failover peer "bleh" entries
605
	 */
606
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
607

    
608
		if (!isset($config['interfaces'][$dhcpif]['enable'])) {
609
			continue;
610
		}
611

    
612
		interfaces_staticarp_configure($dhcpif);
613

    
614
		if (!isset($dhcpifconf['enable'])) {
615
			continue;
616
		}
617

    
618
		if ($dhcpifconf['failover_peerip'] <> "") {
619
			$intip = get_interface_ip($dhcpif);
620
			/*
621
			 *    yep, failover peer is defined.
622
			 *    does it match up to a defined vip?
623
			 */
624
			$skew = 110;
625
			if (is_array($config['virtualip']['vip'])) {
626
				foreach ($config['virtualip']['vip'] as $vipent) {
627
					if ($vipent['mode'] != 'carp') {
628
						continue;
629
					}
630
					if ($vipent['interface'] == $dhcpif) {
631
						$carp_nw = gen_subnet($config['interfaces'][$dhcpif]['ipaddr'],
632
						    $config['interfaces'][$dhcpif]['subnet']);
633
						$carp_nw .= "/{$config['interfaces'][$dhcpif]['subnet']}";
634
						if (ip_in_subnet($dhcpifconf['failover_peerip'], $carp_nw)) {
635
							/* this is the interface! */
636
							if (is_numeric($vipent['advskew']) && (intval($vipent['advskew']) < 20)) {
637
								$skew = 0;
638
								break;
639
							}
640
						}
641
					}
642
				}
643
			} else {
644
				log_error(gettext("Warning!  DHCP Failover setup and no CARP virtual IPs defined!"));
645
			}
646
			if ($skew > 10) {
647
				$type = "secondary";
648
				$my_port = "520";
649
				$peer_port = "519";
650
				$dhcpdconf_pri = '';
651
			} else {
652
				$my_port = "519";
653
				$peer_port = "520";
654
				$type = "primary";
655
				$dhcpdconf_pri = "split 128;\n";
656
				$dhcpdconf_pri .= "  mclt 600;\n";
657
			}
658

    
659
			if (is_ipaddrv4($intip)) {
660
				$dhcpdconf .= <<<EOPP
661
failover peer "dhcp_{$dhcpif}" {
662
  {$type};
663
  address {$intip};
664
  port {$my_port};
665
  peer address {$dhcpifconf['failover_peerip']};
666
  peer port {$peer_port};
667
  max-response-delay 10;
668
  max-unacked-updates 10;
669
  {$dhcpdconf_pri}
670
  load balance max seconds 3;
671
}
672
\n
673
EOPP;
674
			}
675
		}
676
	}
677

    
678
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
679

    
680
		$newzone = array();
681
		$ifcfg = $config['interfaces'][$dhcpif];
682

    
683
		if (!isset($dhcpifconf['enable']) || !isset($Iflist[$dhcpif])) {
684
			continue;
685
		}
686
		$ifcfgip = get_interface_ip($dhcpif);
687
		$ifcfgsn = get_interface_subnet($dhcpif);
688
		$subnet = gen_subnet($ifcfgip, $ifcfgsn);
689
		$subnetmask = gen_subnet_mask($ifcfgsn);
690

    
691
		if (!is_ipaddr($subnet)) {
692
			continue;
693
		}
694

    
695
		$all_pools = array();
696
		$all_pools[] = $dhcpifconf;
697
		if (is_array($dhcpifconf['pool'])) {
698
			$all_pools = array_merge($all_pools, $dhcpifconf['pool']);
699
		}
700

    
701
		$dnscfg = "";
702

    
703
		if ($dhcpifconf['domain']) {
704
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
705
		}
706

    
707
		if ($dhcpifconf['domainsearchlist'] <> "") {
708
			$dnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpifconf['domainsearchlist'])) . "\";\n";
709
		}
710

    
711
		if (isset($dhcpifconf['ddnsupdate'])) {
712
			$need_ddns_updates = true;
713
			$newzone = array();
714
			if ($dhcpifconf['ddnsdomain'] <> "") {
715
				$newzone['domain-name'] = $dhcpifconf['ddnsdomain'];
716
				$dnscfg .= "	ddns-domainname \"{$dhcpifconf['ddnsdomain']}\";\n";
717
			} else {
718
				$newzone['domain-name'] = $config['system']['domain'];
719
			}
720

    
721
			if (empty($dhcpifconf['ddnsclientupdates'])) {
722
				$ddnsclientupdates = 'allow';
723
			} else {
724
				$ddnsclientupdates = $dhcpifconf['ddnsclientupdates'];
725
			}
726

    
727
			$dnscfg .= "	{$ddnsclientupdates} client-updates;\n";
728

    
729
			$revsubnet = array_reverse(explode('.',$subnet));
730

    
731
			$subnet_mask_bits = 32 - $ifcfgsn;
732
			$start_octet = $subnet_mask_bits >> 3;
733
			$octet_mask_bits = $subnet_mask_bits & ($subnet_mask_bits % 8);
734
			if ($octet_mask_bits) {
735
			    $octet_mask = (1 << $octet_mask_bits) - 1;
736
			    $octet_start = $revsubnet[$start_octet] & ~$octet_mask;
737
			    $revsubnet[$start_octet] = $octet_start . "-" . ($octet_start + $octet_mask);
738
			}
739

    
740
			$ptr_domain = '';
741
			for ($octet = 0; $octet <= 3; $octet++) {
742
				if ($octet < $start_octet) {
743
					continue;
744
				}
745
				$ptr_domain .= ((empty($ptr_domain) && $ptr_domain !== "0") ? '' : '.');
746
				$ptr_domain .= $revsubnet[$octet];
747
			}
748
			$ptr_domain .= ".in-addr.arpa";
749
			$newzone['ptr-domain'] = $ptr_domain;
750
			unset($ptr_domain, $revsubnet, $start_octet);
751
		}
752

    
753
		if (is_array($dhcpifconf['dnsserver']) && ($dhcpifconf['dnsserver'][0])) {
754
			$dnscfg .= "	option domain-name-servers " . join(",", $dhcpifconf['dnsserver']) . ";";
755
			if ($newzone['domain-name']) {
756
				$newzone['dns-servers'] = $dhcpifconf['dnsserver'];
757
			}
758
		} else if (isset($config['dnsmasq']['enable'])) {
759
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
760
			if ($newzone['domain-name'] && is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
761
				$newzone['dns-servers'] = $syscfg['dnsserver'];
762
			}
763
		} else if (isset($config['unbound']['enable'])) {
764
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
765
		} else if (!empty($dns_arrv4)) {
766
			$dnscfg .= "	option domain-name-servers " . join(",", $dns_arrv4) . ";";
767
			if ($newzone['domain-name']) {
768
				$newzone['dns-servers'] = $dns_arrv4;
769
			}
770
		}
771

    
772
		/* Create classes - These all contain comma separated lists. Join them into one
773
		   big comma separated string then split them all up. */
774
		$all_mac_strings = array();
775
		if (is_array($dhcpifconf['pool'])) {
776
			foreach ($all_pools as $poolconf) {
777
				$all_mac_strings[] = $poolconf['mac_allow'];
778
				$all_mac_strings[] = $poolconf['mac_deny'];
779
			}
780
		}
781
		$all_mac_strings[] = $dhcpifconf['mac_allow'];
782
		$all_mac_strings[] = $dhcpifconf['mac_deny'];
783
		if (!empty($all_mac_strings)) {
784
			$all_mac_list = array_unique(explode(',', implode(',', $all_mac_strings)));
785
			foreach ($all_mac_list as $mac) {
786
				if (empty($mac)) {
787
					continue;
788
				}
789
				$dhcpdconf .= 'class "' . str_replace(':', '', $mac) . '" {' . "\n";
790
				// Skip the first octet of the MAC address - for media type, typically Ethernet ("01") and match the rest.
791
				$dhcpdconf .= '	match if substring (hardware, 1, ' . (substr_count($mac, ':') + 1) . ') = ' . $mac . ';' . "\n";
792
				$dhcpdconf .= '}' . "\n";
793
			}
794
		}
795

    
796
		// instantiate class before pool definition
797
		$dhcpdconf .= "class \"s_{$dhcpif}\" {\n	match pick-first-value (option dhcp-client-identifier, hardware);\n}\n";
798

    
799
		$dhcpdconf .= "subnet {$subnet} netmask {$subnetmask} {\n";
800

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

    
846
			/* allow/deny MACs */
847
			$mac_allow_list = array_unique(explode(',', $poolconf['mac_allow']));
848
			foreach ($mac_allow_list as $mac) {
849
				if (empty($mac)) {
850
					continue;
851
				}
852
				$dhcpdconf .= "		allow members of \"" . str_replace(':', '', $mac) . "\";\n";
853
			}
854
			$deny_action = "deny";
855
			if (isset($poolconf['nonak']) && empty($poolconf['failover_peerip'])) {
856
				$deny_action = "ignore";
857
			}
858
			$mac_deny_list = array_unique(explode(',', $poolconf['mac_deny']));
859
			foreach ($mac_deny_list as $mac) {
860
				if (empty($mac)) {
861
					continue;
862
				}
863
				$dhcpdconf .= "		$deny_action members of \"" . str_replace(':', '', $mac) . "\";\n";
864
			}
865

    
866
			if ($poolconf['failover_peerip'] <> "") {
867
				$dhcpdconf .= "		$deny_action dynamic bootp clients;\n";
868
			}
869

    
870
			// set pool MAC limitations
871
			if (isset($poolconf['denyunknown'])) {
872
				if ($poolconf['denyunknown'] == "class") {
873
					$dhcpdconf .= "		allow members of \"s_{$dhcpif}\";\n";
874
					$dhcpdconf .= "		$deny_action unknown-clients;\n";
875
				} else if ($poolconf['denyunknown'] == "disabled") {
876
					// add nothing to $dhcpdconf; condition added to prevent next condition applying if ever engine changes such that: isset("disabled") == true
877
				} else {	// "catch-all" covering "enabled" value post-PR#4066, and covering non-upgraded boolean option (i.e. literal value "enabled")
878
					$dhcpdconf .= "		$deny_action unknown-clients;\n";
879
				}
880
			}
881

    
882
			if ($poolconf['gateway'] && $poolconf['gateway'] != "none" && ($poolconf['gateway'] != $dhcpifconf['gateway'])) {
883
				$dhcpdconf .= "		option routers {$poolconf['gateway']};\n";
884
			}
885

    
886
			if ($dhcpifconf['failover_peerip'] <> "") {
887
				$dhcpdconf .= "		failover peer \"dhcp_{$dhcpif}\";\n";
888
			}
889

    
890
			$pdnscfg = "";
891

    
892
			if ($poolconf['domain'] && ($poolconf['domain'] != $dhcpifconf['domain'])) {
893
				$pdnscfg .= "		option domain-name \"{$poolconf['domain']}\";\n";
894
			}
895

    
896
			if (!empty($poolconf['domainsearchlist']) && ($poolconf['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
897
				$pdnscfg .= "		option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $poolconf['domainsearchlist'])) . "\";\n";
898
			}
899

    
900
			if (isset($poolconf['ddnsupdate'])) {
901
				if (($poolconf['ddnsdomain'] <> "") && ($poolconf['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
902
					$pdnscfg .= "		ddns-domainname \"{$poolconf['ddnsdomain']}\";\n";
903
				}
904
				$pdnscfg .= "		ddns-update-style interim;\n";
905
			}
906

    
907
			$dhcpdconf .= "{$pdnscfg}";
908

    
909
			// default-lease-time
910
			if ($poolconf['defaultleasetime'] && ($poolconf['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
911
				$dhcpdconf .= "		default-lease-time {$poolconf['defaultleasetime']};\n";
912
			}
913

    
914
			// max-lease-time
915
			if ($poolconf['maxleasetime'] && ($poolconf['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
916
				$dhcpdconf .= "		max-lease-time {$poolconf['maxleasetime']};\n";
917
			}
918

    
919
			// ignore bootp
920
			if (isset($poolconf['ignorebootp'])) {
921
				$dhcpdconf .= "		ignore bootp;\n";
922
			}
923

    
924
			// ignore-client-uids
925
			if (isset($poolconf['ignoreclientuids'])) {
926
				$dhcpdconf .= "		ignore-client-uids true;\n";
927
			}
928

    
929
			// netbios-name*
930
			if (is_array($poolconf['winsserver']) && $poolconf['winsserver'][0] && ($poolconf['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
931
				$dhcpdconf .= "		option netbios-name-servers " . join(",", $poolconf['winsserver']) . ";\n";
932
				$dhcpdconf .= "		option netbios-node-type 8;\n";
933
			}
934

    
935
			// ntp-servers
936
			if (is_array($poolconf['ntpserver']) && $poolconf['ntpserver'][0] && ($poolconf['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
937
				$dhcpdconf .= "		option ntp-servers " . join(",", $poolconf['ntpserver']) . ";\n";
938
			}
939

    
940
			// tftp-server-name
941
			if (!empty($poolconf['tftp']) && ($poolconf['tftp'] != $dhcpifconf['tftp'])) {
942
				$dhcpdconf .= "		option tftp-server-name \"{$poolconf['tftp']}\";\n";
943
			}
944

    
945
			// Handle pool-specific options
946
			$dhcpdconf .= "\n";
947
			// Ignore the first pool, which is the "overall" pool when $all_pools_idx is 0 - those are put outside the pool block later
948
			if (isset($poolconf['numberoptions']['item']) && is_array($poolconf['numberoptions']['item']) && ($all_pools_idx > 0)) {
949
				// Use the "real" pool index from the config, excluding the "overall" pool, and based from 0.
950
				// This matches the way $poolidx was used when generating the $custoptions string earlier.
951
				$poolidx = $all_pools_idx - 1;
952
				foreach ($poolconf['numberoptions']['item'] as $itemidx => $item) {
953
					$item_value = base64_decode($item['value']);
954
					if (empty($item['type']) || $item['type'] == "text") {
955
						$dhcpdconf .= "		option custom-{$dhcpif}-{$poolidx}-{$itemidx} \"{$item_value}\";\n";
956
					} else {
957
						$dhcpdconf .= "		option custom-{$dhcpif}-{$poolidx}-{$itemidx} {$item_value};\n";
958
					}
959
				}
960
			}
961

    
962
			// ldap-server
963
			if (!empty($poolconf['ldap']) && ($poolconf['ldap'] != $dhcpifconf['ldap'])) {
964
				$dhcpdconf .= "		option ldap-server \"{$poolconf['ldap']}\";\n";
965
			}
966

    
967
			// net boot information
968
			if (isset($poolconf['netboot'])) {
969
				if (!empty($poolconf['nextserver']) && ($poolconf['nextserver'] != $dhcpifconf['nextserver'])) {
970
					$dhcpdconf .= "		next-server {$poolconf['nextserver']};\n";
971
				}
972

    
973
				if (!empty($poolconf['filename']) &&
974
				    (!isset($dhcpifconf['filename']) ||
975
				    ($poolconf['filename'] != $dhcpifconf['filename']))) {
976
					$filename = $poolconf['filename'];
977
				}
978
				if (!empty($poolconf['filename32']) &&
979
				    (!isset($dhcpifconf['filename32']) ||
980
				    ($poolconf['filename32'] != $dhcpifconf['filename32']))) {
981
					$filename32 = $poolconf['filename32'];
982
				}
983
				if (!empty($poolconf['filename64']) &&
984
				    (!isset($dhcpifconf['filename64']) ||
985
				    ($poolconf['filename64'] != $dhcpifconf['filename64']))) {
986
					$filename64 = $poolconf['filename64'];
987
				}
988
				if (!empty($poolconf['filename32arm']) &&
989
				    (!isset($dhcpifconf['filename32arm']) ||
990
				    ($poolconf['filename32arm'] != $dhcpifconf['filename32arm']))) {
991
					$filename32arm = $poolconf['filename32arm'];
992
				}
993
				if (!empty($poolconf['filename64arm']) &&
994
				    (!isset($dhcpifconf['filename64arm']) ||
995
				    ($poolconf['filename64arm'] != $dhcpifconf['filename64arm']))) {
996
					$filename64arm = $poolconf['filename64arm'];
997
				}
998

    
999
				if (!empty($filename32) || !empty($filename64) || !empty($filename32arm) || !empty($filename64arm)) {
1000
					if (empty($filename) && !empty($dhcpifconf['filename'])) {
1001
						$filename = $dhcpifconf['filename'];
1002
					}
1003
					if (empty($filename32) && !empty($dhcpifconf['filename32'])) {
1004
						$filename32 = $dhcpifconf['filename32'];
1005
					}
1006
					if (empty($filename64) && !empty($dhcpifconf['filename64'])) {
1007
						$filename64 = $dhcpifconf['filename64'];
1008
					}
1009
					if (empty($filename32arm) && !empty($dhcpifconf['filename32arm'])) {
1010
						$filename32arm = $dhcpifconf['filename32arm'];
1011
					}
1012
					if (empty($filename64arm) && !empty($dhcpifconf['filename64arm'])) {
1013
						$filename64arm = $dhcpifconf['filename64arm'];
1014
					}
1015
				}
1016

    
1017
				if (!empty($filename) && !empty($filename32) && !empty($filename64) && !empty($filename32arm) && !empty($filename64arm)) {
1018
					$dhcpdconf .= "		if option arch = 00:06 {\n";
1019
					$dhcpdconf .= "			filename \"{$filename32}\";\n";
1020
					$dhcpdconf .= "		} else if option arch = 00:07 {\n";
1021
					$dhcpdconf .= "			filename \"{$filename64}\";\n";
1022
					$dhcpdconf .= "		} else if option arch = 00:09 {\n";
1023
					$dhcpdconf .= "			filename \"{$filename64}\";\n";
1024
					$dhcpdconf .= "		} else if option arch = 00:0a {\n";
1025
					$dhcpdconf .= "			filename \"{$filename32arm}\";\n";
1026
					$dhcpdconf .= "		} else if option arch = 00:0b {\n";
1027
					$dhcpdconf .= "			filename \"{$filename64arm}\";\n";
1028
					$dhcpdconf .= "		} else {\n";
1029
					$dhcpdconf .= "			filename \"{$filename}\";\n";
1030
					$dhcpdconf .= "		}\n\n";
1031
				} elseif (!empty($filename)) {
1032
					$dhcpdconf .= "		filename \"{$filename}\";\n";
1033
				}
1034
				unset($filename, $filename32, $filename64, $filename32arm, $filename64arm);
1035

    
1036
				if (!empty($poolconf['rootpath']) && ($poolconf['rootpath'] != $dhcpifconf['rootpath'])) {
1037
					$dhcpdconf .= "		option root-path \"{$poolconf['rootpath']}\";\n";
1038
				}
1039
			}
1040
			$dhcpdconf .= "		range {$poolconf['range']['from']} {$poolconf['range']['to']};\n";
1041
			$dhcpdconf .= "	}\n\n";
1042
		}
1043
// End of settings inside pools
1044

    
1045
		if ($dhcpifconf['gateway'] && $dhcpifconf['gateway'] != "none") {
1046
			$routers = $dhcpifconf['gateway'];
1047
			$add_routers = true;
1048
		} elseif ($dhcpifconf['gateway'] == "none") {
1049
			$add_routers = false;
1050
		} else {
1051
			$add_routers = $enable_add_routers;
1052
			$routers = $ifcfgip;
1053
		}
1054
		if ($add_routers) {
1055
			$dhcpdconf .= "	option routers {$routers};\n";
1056
		}
1057

    
1058
		$dhcpdconf .= <<<EOD
1059
$dnscfg
1060

    
1061
EOD;
1062
		// default-lease-time
1063
		if ($dhcpifconf['defaultleasetime']) {
1064
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
1065
		}
1066

    
1067
		// max-lease-time
1068
		if ($dhcpifconf['maxleasetime']) {
1069
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
1070
		}
1071

    
1072
		if (!isset($dhcpifconf['disablepingcheck'])) {
1073
			$dhcpdconf .= "	ping-check true;\n";
1074
		} else {
1075
			$dhcpdconf .= "	ping-check false;\n";
1076
		}
1077

    
1078
		// netbios-name*
1079
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
1080
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
1081
			$dhcpdconf .= "	option netbios-node-type 8;\n";
1082
		}
1083

    
1084
		// ntp-servers
1085
		if (is_array($dhcpifconf['ntpserver']) && $dhcpifconf['ntpserver'][0]) {
1086
			$dhcpdconf .= "	option ntp-servers " . join(",", $dhcpifconf['ntpserver']) . ";\n";
1087
		}
1088

    
1089
		// tftp-server-name
1090
		if ($dhcpifconf['tftp'] <> "") {
1091
			$dhcpdconf .= "	option tftp-server-name \"{$dhcpifconf['tftp']}\";\n";
1092
		}
1093

    
1094
		// Handle option, number rowhelper values
1095
		$dhcpdconf .= "\n";
1096
		if (isset($dhcpifconf['numberoptions']['item']) && is_array($dhcpifconf['numberoptions']['item'])) {
1097
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
1098
				$item_value = base64_decode($item['value']);
1099
				if (empty($item['type']) || $item['type'] == "text") {
1100
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} \"{$item_value}\";\n";
1101
				} else {
1102
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} {$item_value};\n";
1103
				}
1104
			}
1105
		}
1106

    
1107
		// ldap-server
1108
		if ($dhcpifconf['ldap'] <> "") {
1109
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
1110
		}
1111

    
1112
		// net boot information
1113
		if (isset($dhcpifconf['netboot'])) {
1114
			if ($dhcpifconf['nextserver'] <> "") {
1115
				$dhcpdconf .= "	next-server {$dhcpifconf['nextserver']};\n";
1116
			}
1117
			if (!empty($dhcpifconf['filename']) && !empty($dhcpifconf['filename32']) && !empty($dhcpifconf['filename64'])) {
1118
				$dhcpdconf .= "	if option arch = 00:06 {\n";
1119
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename32']}\";\n";
1120
				$dhcpdconf .= "	} else if option arch = 00:07 {\n";
1121
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1122
				$dhcpdconf .= "	} else if option arch = 00:09 {\n";
1123
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1124
				$dhcpdconf .= "	} else {\n";
1125
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename']}\";\n";
1126
				$dhcpdconf .= "	}\n\n";
1127
			} elseif (!empty($dhcpifconf['filename'])) {
1128
				$dhcpdconf .= "	filename \"{$dhcpifconf['filename']}\";\n";
1129
			}
1130
			if (!empty($dhcpifconf['rootpath'])) {
1131
				$dhcpdconf .= "	option root-path \"{$dhcpifconf['rootpath']}\";\n";
1132
			}
1133
		}
1134

    
1135
		$dhcpdconf .= <<<EOD
1136
}
1137

    
1138
EOD;
1139

    
1140
		/* add static mappings */
1141
		if (is_array($dhcpifconf['staticmap'])) {
1142

    
1143
			$i = 0;
1144
			$sm_newzone[] = array();
1145
			$need_sm_ddns_updates = false;
1146
			foreach ($dhcpifconf['staticmap'] as $sm) {
1147
				$cid = '';
1148
				$dhcpdconf .= "host s_{$dhcpif}_{$i} {\n";
1149

    
1150
				if ($sm['mac']) {
1151
					$dhcpdconf .= "	hardware ethernet {$sm['mac']};\n";
1152
				}
1153

    
1154
				if ($sm['cid']) {
1155
					$cid = str_replace('"', '\"', $sm['cid']);
1156
					$dhcpdconf .= "	option dhcp-client-identifier \"{$cid}\";\n";
1157
				}
1158

    
1159
				if ($sm['ipaddr']) {
1160
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
1161
				}
1162

    
1163
				if ($sm['hostname']) {
1164
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1165
					$dhhostname = str_replace(".", "_", $dhhostname);
1166
					$dhcpdconf .= "	option host-name \"{$dhhostname}\";\n";
1167
					if ((isset($dhcpifconf['ddnsupdate']) || isset($sm['ddnsupdate'])) && (isset($dhcpifconf['ddnsforcehostname']) || isset($sm['ddnsforcehostname']))) {
1168
						$dhcpdconf .= "	ddns-hostname \"{$dhhostname}\";\n";
1169
					}
1170
				}
1171
				if ($sm['filename']) {
1172
					$dhcpdconf .= "	filename \"{$sm['filename']}\";\n";
1173
				}
1174

    
1175
				if ($sm['rootpath']) {
1176
					$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1177
				}
1178

    
1179
				if ($sm['gateway'] && ($sm['gateway'] != $dhcpifconf['gateway'])) {
1180
					$dhcpdconf .= "	option routers {$sm['gateway']};\n";
1181
				}
1182

    
1183
				$smdnscfg = "";
1184

    
1185
				if ($sm['domain'] && ($sm['domain'] != $dhcpifconf['domain'])) {
1186
					$smdnscfg .= "	option domain-name \"{$sm['domain']}\";\n";
1187
				}
1188

    
1189
				if (!empty($sm['domainsearchlist']) && ($sm['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
1190
					$smdnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $sm['domainsearchlist'])) . "\";\n";
1191
				}
1192

    
1193
				if (isset($sm['ddnsupdate'])) {
1194
					if (($sm['ddnsdomain'] <> "") && ($sm['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
1195
						$smdnscfg .= "		ddns-domainname \"{$sm['ddnsdomain']}\";\n";
1196
				 		$need_sm_ddns_updates = true;	
1197
					}
1198
					$smdnscfg .= "		ddns-update-style interim;\n";
1199
				}
1200

    
1201
				if (is_array($sm['dnsserver']) && ($sm['dnsserver'][0]) && ($sm['dnsserver'][0] != $dhcpifconf['dnsserver'][0])) {
1202
					$smdnscfg .= "	option domain-name-servers " . join(",", $sm['dnsserver']) . ";\n";
1203
				}
1204
				$dhcpdconf .= "{$smdnscfg}";
1205

    
1206
				// default-lease-time
1207
				if ($sm['defaultleasetime'] && ($sm['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
1208
					$dhcpdconf .= "	default-lease-time {$sm['defaultleasetime']};\n";
1209
				}
1210

    
1211
				// max-lease-time
1212
				if ($sm['maxleasetime'] && ($sm['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
1213
					$dhcpdconf .= "	max-lease-time {$sm['maxleasetime']};\n";
1214
				}
1215

    
1216
				// netbios-name*
1217
				if (is_array($sm['winsserver']) && $sm['winsserver'][0] && ($sm['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
1218
					$dhcpdconf .= "	option netbios-name-servers " . join(",", $sm['winsserver']) . ";\n";
1219
					$dhcpdconf .= "	option netbios-node-type 8;\n";
1220
				}
1221

    
1222
				// ntp-servers
1223
				if (is_array($sm['ntpserver']) && $sm['ntpserver'][0] && ($sm['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
1224
					$dhcpdconf .= "	option ntp-servers " . join(",", $sm['ntpserver']) . ";\n";
1225
				}
1226

    
1227
				// tftp-server-name
1228
				if (!empty($sm['tftp']) && ($sm['tftp'] != $dhcpifconf['tftp'])) {
1229
					$dhcpdconf .= "	option tftp-server-name \"{$sm['tftp']}\";\n";
1230
				}
1231

    
1232
				// Handle option, number rowhelper values
1233
				$dhcpdconf .= "\n";
1234
				if (isset($sm['numberoptions']['item']) && is_array($sm['numberoptions']['item'])) {
1235
					foreach ($sm['numberoptions']['item'] as $itemidx => $item) {
1236
						$item_value = base64_decode($item['value']);
1237
						if (empty($item['type']) || $item['type'] == "text") {
1238
							$dhcpdconf .= "	option custom-s_{$dhcpif}_{$i}-{$itemidx} \"{$item_value}\";\n";
1239
						} else {
1240
							$dhcpdconf .= "	option custom-s_{$dhcpif}_{$i}-{$itemidx} {$item_value};\n";
1241
						}
1242
					}
1243
				}
1244

    
1245
				// ldap-server
1246
				if (!empty($sm['ldap']) && ($sm['ldap'] != $dhcpifconf['ldap'])) {
1247
					$dhcpdconf .= "	option ldap-server \"{$sm['ldap']}\";\n";
1248
				}
1249

    
1250
				// net boot information
1251
				if (isset($sm['netboot'])) {
1252
					if ($sm['nextserver'] <> "") {
1253
						$dhcpdconf .= "	next-server {$sm['nextserver']};\n";
1254
					}
1255
					if (!empty($sm['filename']) && !empty($sm['filename32']) && !empty($sm['filename64'])) {
1256
						$dhcpdconf .= "	if option arch = 00:06 {\n";
1257
						$dhcpdconf .= "		filename \"{$sm['filename32']}\";\n";
1258
						$dhcpdconf .= "	} else if option arch = 00:07 {\n";
1259
						$dhcpdconf .= "		filename \"{$sm['filename64']}\";\n";
1260
						$dhcpdconf .= "	} else if option arch = 00:09 {\n";
1261
						$dhcpdconf .= "		filename \"{$sm['filename64']}\";\n";
1262
						$dhcpdconf .= "	} else {\n";
1263
						$dhcpdconf .= "		filename \"{$sm['filename']}\";\n";
1264
						$dhcpdconf .= "	}\n\n";
1265
					} elseif (!empty($sm['filename'])) {
1266
						$dhcpdconf .= "	filename \"{$sm['filename']}\";\n";
1267
					}
1268
					if (!empty($dhcpifconf['rootpath'])) {
1269
						$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1270
					}
1271
				}
1272

    
1273
				$dhcpdconf .= "}\n";
1274

    
1275
				// add zone DDNS key/server to $ddns_zone[] if required
1276
				if ($need_sm_ddns_updates) {
1277
					$ddnsduplicate = false;
1278
					foreach ($ddns_zones as $ddnszone) {
1279
						if ($ddnszone['domain-name'] == $sm['ddnsdomain']) {
1280
							$ddnsduplicate = true;
1281
						}
1282
					}
1283
					if (!$ddnsduplicate) {
1284
						$sm_newzone['dns-servers'] = array($sm['ddnsdomainprimary']);
1285
						$sm_newzone['domain-name'] = $sm['ddnsdomain'];
1286
						$sm_newzone['ddnsdomainkeyname'] = $sm['ddnsdomainkeyname'];
1287
						$sm_newzone['ddnsdomainkeyalgorithm'] = $sm['ddnsdomainkeyalgorithm'];
1288
						$sm_newzone['ddnsdomainkey'] = $sm['ddnsdomainkey'];
1289
						$dhcpdconf .= dhcpdkey($sm_newzone);
1290
						$ddns_zones[] = $sm_newzone;
1291
						$need_ddns_updates = true;
1292
					}
1293
				}
1294

    
1295
				// subclass for DHCP limiting
1296
				if (!empty($sm['mac'])) {
1297
					// assuming ALL addresses are ethernet hardware type ("1:" prefix)
1298
					$dhcpdconf .= "subclass \"s_{$dhcpif}\" 1:{$sm['mac']};\n";
1299
				}
1300
				if (!empty($cid)) {
1301
					$dhcpdconf .= "subclass \"s_{$dhcpif}\" \"{$cid}\";\n";
1302
				}
1303

    
1304

    
1305
				$i++;
1306
			}
1307
		}
1308

    
1309
		$dhcpdifs[] = get_real_interface($dhcpif);
1310
		if ($newzone['domain-name']) {
1311
			if ($need_ddns_updates) {
1312
				$newzone['dns-servers'] = array($dhcpifconf['ddnsdomainprimary'], $dhcpifconf['ddnsdomainsecondary']);
1313
				$newzone['ddnsdomainkeyname'] = $dhcpifconf['ddnsdomainkeyname'];
1314
				$newzone['ddnsdomainkeyalgorithm'] = $dhcpifconf['ddnsdomainkeyalgorithm'];
1315
				$newzone['ddnsdomainkey'] = $dhcpifconf['ddnsdomainkey'];
1316
				$dhcpdconf .= dhcpdkey($dhcpifconf);
1317
			}
1318
			$ddns_zones[] = $newzone;
1319
		}
1320
	}
1321

    
1322
	if ($need_ddns_updates) {
1323
		$dhcpdconf .= "ddns-update-style interim;\n";
1324
		$dhcpdconf .= "update-static-leases on;\n";
1325

    
1326
		$dhcpdconf .= dhcpdzones($ddns_zones);
1327
	}
1328

    
1329
	/* write dhcpd.conf */
1330
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpd.conf", $dhcpdconf)) {
1331
		printf(gettext("Error: cannot open dhcpd.conf in services_dhcpdv4_configure().%s"), "\n");
1332
		unset($dhcpdconf);
1333
		return 1;
1334
	}
1335
	unset($dhcpdconf);
1336

    
1337
	/* create an empty leases database */
1338
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
1339
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
1340
	}
1341

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

    
1346
	/* fire up dhcpd in a chroot */
1347
	if (count($dhcpdifs) > 0) {
1348
		mwexec("/usr/local/sbin/dhcpd -user dhcpd -group _dhcp -chroot {$g['dhcpd_chroot_path']} -cf /etc/dhcpd.conf -pf {$g['varrun_path']}/dhcpd.pid " .
1349
			join(" ", $dhcpdifs));
1350
	}
1351

    
1352
	if (platform_booting()) {
1353
		print "done.\n";
1354
	}
1355

    
1356
	return 0;
1357
}
1358

    
1359
function dhcpdkey($dhcpifconf) {
1360
	$dhcpdconf = "";
1361
	if (!empty($dhcpifconf['ddnsdomainkeyname']) && !empty($dhcpifconf['ddnsdomainkey'])) {
1362
		$algorithm = empty($dhcpifconf['ddnsdomainkeyalgorithm']) ? 'hmac-md5' : $dhcpifconf['ddnsdomainkeyalgorithm'];
1363
		$dhcpdconf .= "key \"{$dhcpifconf['ddnsdomainkeyname']}\" {\n";
1364
		$dhcpdconf .= "	algorithm {$algorithm};\n";
1365
		$dhcpdconf .= "	secret {$dhcpifconf['ddnsdomainkey']};\n";
1366
		$dhcpdconf .= "}\n";
1367
	}
1368

    
1369
	return $dhcpdconf;
1370
}
1371

    
1372
function dhcpdzones($ddns_zones) {
1373
	$dhcpdconf = "";
1374

    
1375
	if (is_array($ddns_zones)) {
1376
		$added_zones = array();
1377
		foreach ($ddns_zones as $zone) {
1378
			if (!is_array($zone) || empty($zone) || !is_array($zone['dns-servers'])) {
1379
				continue;
1380
			}
1381
			$primary = $zone['dns-servers'][0];
1382
			$secondary = empty($zone['dns-servers'][1]) ? "" : $zone['dns-servers'][1];
1383

    
1384
			// Make sure we aren't using any invalid servers.
1385
			if (!is_ipaddr($primary)) {
1386
				if (is_ipaddr($secondary)) {
1387
					$primary = $secondary;
1388
					$secondary = "";
1389
				} else {
1390
					continue;
1391
				}
1392
			}
1393

    
1394
			// We don't need to add zones multiple times.
1395
			if ($zone['domain-name'] && !in_array($zone['domain-name'], $added_zones)) {
1396
				$dhcpdconf .= "zone {$zone['domain-name']}. {\n";
1397
				if (is_ipaddrv4($primary)) {
1398
					$dhcpdconf .= "	primary {$primary};\n";
1399
				} else {
1400
					$dhcpdconf .= "	primary6 {$primary};\n";
1401
				}
1402
				if (is_ipaddrv4($secondary)) {
1403
					$dhcpdconf .= "	secondary {$secondary};\n";
1404
				} elseif (is_ipaddrv6($secondary)) {
1405
					$dhcpdconf .= "	secondary6 {$secondary};\n";
1406
				}
1407
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1408
					$dhcpdconf .= "	key \"{$zone['ddnsdomainkeyname']}\";\n";
1409
				}
1410
				$dhcpdconf .= "}\n";
1411
				$added_zones[] = $zone['domain-name'];
1412
			}
1413
			if ($zone['ptr-domain'] && !in_array($zone['ptr-domain'], $added_zones)) {
1414
				$dhcpdconf .= "zone {$zone['ptr-domain']} {\n";
1415
				if (is_ipaddrv4($primary)) {
1416
					$dhcpdconf .= "	primary {$primary};\n";
1417
				} else {
1418
					$dhcpdconf .= "	primary6 {$primary};\n";
1419
				}
1420
				if (is_ipaddrv4($secondary)) {
1421
					$dhcpdconf .= "	secondary {$secondary};\n";
1422
				} elseif (is_ipaddrv6($secondary)) {
1423
					$dhcpdconf .= "	secondary6 {$secondary};\n";
1424
				}
1425
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1426
					$dhcpdconf .= "	key \"{$zone['ddnsdomainkeyname']}\";\n";
1427
				}
1428
				$dhcpdconf .= "}\n";
1429
				$added_zones[] = $zone['ptr-domain'];
1430
			}
1431
		}
1432
	}
1433

    
1434
	return $dhcpdconf;
1435
}
1436

    
1437
function services_dhcpdv6_configure($blacklist = array()) {
1438
	global $config, $g;
1439

    
1440
	if ($g['services_dhcp_server_enable'] == false) {
1441
		return;
1442
	}
1443

    
1444
	if (isset($config['system']['developerspew'])) {
1445
		$mt = microtime();
1446
		echo "services_dhcpd_configure($if) being called $mt\n";
1447
	}
1448

    
1449
	/* kill any running dhcpd */
1450
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid")) {
1451
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid");
1452
	}
1453
	if (isvalidpid("{$g['varrun_path']}/dhcpleases6.pid")) {
1454
		killbypid("{$g['varrun_path']}/dhcpleases6.pid");
1455
	}
1456

    
1457
	/* DHCP enabled on any interfaces? */
1458
	if (!is_dhcpv6_server_enabled()) {
1459
		return 0;
1460
	}
1461

    
1462
	$syscfg = $config['system'];
1463
	if (!is_array($config['dhcpdv6'])) {
1464
		$config['dhcpdv6'] = array();
1465
	}
1466
	$dhcpdv6cfg = $config['dhcpdv6'];
1467
	$Iflist = get_configured_interface_list();
1468
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
1469

    
1470

    
1471
	if (platform_booting()) {
1472
		echo "Starting DHCPv6 service...";
1473
	} else {
1474
		sleep(1);
1475
	}
1476

    
1477
	$custoptionsv6 = "";
1478
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1479
		if (is_array($dhcpv6ifconf['numberoptions']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1480
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1481
				$custoptionsv6 .= "option custom-{$dhcpv6if}-{$itemv6idx} code {$itemv6['number']} = text;\n";
1482
			}
1483
		}
1484
	}
1485

    
1486
	if (isset($dhcpv6ifconf['netboot']) && !empty($dhcpv6ifconf['bootfile_url'])) {
1487
		$custoptionsv6 .= "option dhcp6.bootfile-url code 59 = string;\n";
1488
	}
1489

    
1490
	$dhcpdv6conf = <<<EOD
1491

    
1492
option domain-name "{$syscfg['domain']}";
1493
option ldap-server code 95 = text;
1494
option domain-search-list code 119 = text;
1495
{$custoptionsv6}
1496
default-lease-time 7200;
1497
max-lease-time 86400;
1498
log-facility local7;
1499
one-lease-per-client true;
1500
deny duplicates;
1501
ping-check true;
1502
update-conflict-detection false;
1503

    
1504
EOD;
1505

    
1506
	if (!isset($dhcpv6ifconf['disableauthoritative'])) {
1507
		$dhcpdv6conf .= "authoritative;\n";
1508
	}
1509

    
1510
	if (isset($dhcpv6ifconf['alwaysbroadcast'])) {
1511
		$dhcpdv6conf .= "always-broadcast on\n";
1512
	}
1513

    
1514
	$dhcpdv6ifs = array();
1515

    
1516
	$dhcpv6num = 0;
1517
	$nsupdate = false;
1518

    
1519
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1520

    
1521
		$ddns_zones = array();
1522

    
1523
		$ifcfgv6 = $config['interfaces'][$dhcpv6if];
1524

    
1525
		if (!isset($dhcpv6ifconf['enable']) || !isset($Iflist[$dhcpv6if]) || !isset($ifcfgv6['enable'])) {
1526
			continue;
1527
		}
1528
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1529
		if (!is_ipaddrv6($ifcfgipv6)) {
1530
			continue;
1531
		}
1532
		$ifcfgsnv6 = get_interface_subnetv6($dhcpv6if);
1533
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1534
		// We might have some prefix-delegation on WAN (e.g. /48),
1535
		// but then it is split and given out to individual interfaces
1536
		// (LAN, OPT1, OPT2...) as multiple /64 subnets. So the size
1537
		// of each subnet here is always /64.
1538
		$pdlen = 64;
1539

    
1540
		$dnscfgv6 = "";
1541

    
1542
		if ($dhcpv6ifconf['domain']) {
1543
			$dnscfgv6 .= "	option domain-name \"{$dhcpv6ifconf['domain']}\";\n";
1544
		}
1545

    
1546
		if ($dhcpv6ifconf['domainsearchlist'] <> "") {
1547
			$dnscfgv6 .= "	option dhcp6.domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpv6ifconf['domainsearchlist'])) . "\";\n";
1548
		}
1549

    
1550
		if (isset($dhcpv6ifconf['ddnsupdate'])) {
1551
			if ($dhcpv6ifconf['ddnsdomain'] <> "") {
1552
				$dnscfgv6 .= "	ddns-domainname \"{$dhcpv6ifconf['ddnsdomain']}\";\n";
1553
			}
1554
			if (empty($dhcpv6ifconf['ddnsclientupdates'])) {
1555
				$ddnsclientupdates = 'allow';
1556
			} else {
1557
				$ddnsclientupdates = $dhcpv6ifconf['ddnsclientupdates'];
1558
			}
1559
			$dnscfgv6 .= "	{$ddnsclientupdates} client-updates;\n";
1560
			$nsupdate = true;
1561
		} else {
1562
			$dnscfgv6 .= "	do-forward-updates false;\n";
1563
		}
1564

    
1565
		if ($dhcpv6ifconf['dhcp6c-dns'] != 'disabled') {
1566
			if (is_array($dhcpv6ifconf['dnsserver']) && ($dhcpv6ifconf['dnsserver'][0])) {
1567
				$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dhcpv6ifconf['dnsserver']) . ";\n";
1568
			} else if (((isset($config['dnsmasq']['enable'])) || isset($config['unbound']['enable'])) && (is_ipaddrv6($ifcfgipv6))) {
1569
				$dnscfgv6 .= "	option dhcp6.name-servers {$ifcfgipv6};\n";
1570
			} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1571
				$dns_arrv6 = array();
1572
				foreach ($syscfg['dnsserver'] as $dnsserver) {
1573
					if (is_ipaddrv6($dnsserver)) {
1574
						if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1575
						    Net_IPv6::isInNetmask($dnsserver, '::', $pdlen)) {
1576
							$dnsserver = merge_ipv6_delegated_prefix($ifcfgipv6, $dnsserver, $pdlen);
1577
						}
1578
						$dns_arrv6[] = $dnsserver;
1579
					}
1580
				}
1581
				if (!empty($dns_arrv6)) {
1582
					$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dns_arrv6) . ";\n";
1583
				}
1584
			}
1585
		} else {
1586
			$dnscfgv6 .= "	#option dhcp6.name-servers --;\n";
1587
		}
1588

    
1589
		if (!is_ipaddrv6($ifcfgipv6)) {
1590
			$ifcfgsnv6 = "64";
1591
			$subnetv6 = gen_subnetv6($dhcpv6ifconf['range']['from'], $ifcfgsnv6);
1592
		}
1593

    
1594
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1595

    
1596
		if (isset($dhcpv6ifconf['ddnsupdate']) &&
1597
		    !empty($dhcpv6ifconf['ddnsdomain'])) {
1598
			$newzone = array();
1599
			$newzone['domain-name'] = $dhcpv6ifconf['ddnsdomain'];
1600
			$newzone['dns-servers'] = array($dhcpv6ifconf['ddnsdomainprimary'], $dhcpv6ifconf['ddnsdomainsecondary']);
1601
			$newzone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1602
			$newzone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1603
			$ddns_zones[] = $newzone;
1604
			if (isset($dhcpv6ifconf['ddnsreverse'])) {
1605
				$ptr_zones = get_v6_ptr_zones($subnetv6, $ifcfgsnv6);
1606
				foreach ($ptr_zones as $ptr_zone) {
1607
					$reversezone = array();
1608
					$reversezone['ptr-domain'] = $ptr_zone;
1609
					$reversezone['dns-servers'] = array($dhcpv6ifconf['ddnsdomainprimary'], $dhcpv6ifconf['ddnsdomainsecondary']);
1610
					$reversezone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1611
					$reversezone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1612
					$ddns_zones[] = $reversezone;
1613
				}
1614
			}
1615
		}
1616

    
1617
		$dhcpdv6conf .= " {\n";
1618

    
1619
		$range_from = $dhcpv6ifconf['range']['from'];
1620
		$range_to = $dhcpv6ifconf['range']['to'];
1621
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
1622
			$range_from = merge_ipv6_delegated_prefix($ifcfgipv6, $range_from, $pdlen);
1623
			$range_to = merge_ipv6_delegated_prefix($ifcfgipv6, $range_to, $pdlen);
1624
		}
1625

    
1626
		if (!empty($dhcpv6ifconf['range']['from']) && !empty($dhcpv6ifconf['range']['to'])) {
1627
			$dhcpdv6conf .= "	range6 {$range_from} {$range_to};\n";
1628
		}
1629

    
1630
		$dhcpdv6conf .= $dnscfgv6;
1631

    
1632
		if (is_ipaddrv6($dhcpv6ifconf['prefixrange']['from']) && is_ipaddrv6($dhcpv6ifconf['prefixrange']['to'])) {
1633
			$dhcpdv6conf .= "	prefix6 {$dhcpv6ifconf['prefixrange']['from']} {$dhcpv6ifconf['prefixrange']['to']} /{$dhcpv6ifconf['prefixrange']['prefixlength']};\n";
1634
		}
1635
		if (is_ipaddrv6($dhcpv6ifconf['dns6ip'])) {
1636
			$dns6ip = $dhcpv6ifconf['dns6ip'];
1637
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1638
			    Net_IPv6::isInNetmask($dns6ip, '::', $pdlen)) {
1639
				$dns6ip = merge_ipv6_delegated_prefix($ifcfgipv6, $dns6ip, $pdlen);
1640
			}
1641
			$dhcpdv6conf .= "	option dhcp6.name-servers {$dns6ip};\n";
1642
		}
1643
		// default-lease-time
1644
		if ($dhcpv6ifconf['defaultleasetime']) {
1645
			$dhcpdv6conf .= "	default-lease-time {$dhcpv6ifconf['defaultleasetime']};\n";
1646
		}
1647

    
1648
		// max-lease-time
1649
		if ($dhcpv6ifconf['maxleasetime']) {
1650
			$dhcpdv6conf .= "	max-lease-time {$dhcpv6ifconf['maxleasetime']};\n";
1651
		}
1652

    
1653
		// ntp-servers
1654
		if (is_array($dhcpv6ifconf['ntpserver']) && $dhcpv6ifconf['ntpserver'][0]) {
1655
			$ntpservers = array();
1656
			foreach ($dhcpv6ifconf['ntpserver'] as $ntpserver) {
1657
				if (!is_ipaddrv6($ntpserver)) {
1658
					continue;
1659
				}
1660
				if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1661
				    Net_IPv6::isInNetmask($ntpserver, '::', $pdlen)) {
1662
					$ntpserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ntpserver, $pdlen);
1663
				}
1664
				$ntpservers[] = $ntpserver;
1665
			}
1666
			if (count($ntpservers) > 0) {
1667
				$dhcpdv6conf .= "        option dhcp6.sntp-servers " . join(",", $dhcpv6ifconf['ntpserver']) . ";\n";
1668
			}
1669
		}
1670
		// tftp-server-name
1671
		/* Needs ISC DHCPD support
1672
		 if ($dhcpv6ifconf['tftp'] <> "") {
1673
			$dhcpdv6conf .= "	option tftp-server-name \"{$dhcpv6ifconf['tftp']}\";\n";
1674
		 }
1675
		*/
1676

    
1677
		// Handle option, number rowhelper values
1678
		$dhcpdv6conf .= "\n";
1679
		if (isset($dhcpv6ifconf['numberoptions']['item']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1680
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1681
				$itemv6_value = base64_decode($itemv6['value']);
1682
				$dhcpdv6conf .= "	option custom-{$dhcpv6if}-{$itemv6idx} \"{$itemv6_value}\";\n";
1683
			}
1684
		}
1685

    
1686
		// ldap-server
1687
		if ($dhcpv6ifconf['ldap'] <> "") {
1688
			$ldapserver = $dhcpv6ifconf['ldap'];
1689
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1690
			    Net_IPv6::isInNetmask($ldapserver, '::', $pdlen)) {
1691
				$ldapserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ldapserver, $pdlen);
1692
			}
1693
			$dhcpdv6conf .= "	option ldap-server \"{$ldapserver}\";\n";
1694
		}
1695

    
1696
		// net boot information
1697
		if (isset($dhcpv6ifconf['netboot'])) {
1698
			if (!empty($dhcpv6ifconf['bootfile_url'])) {
1699
				$dhcpdv6conf .= "	option dhcp6.bootfile-url \"{$dhcpv6ifconf['bootfile_url']}\";\n";
1700
			}
1701
		}
1702

    
1703
		$dhcpdv6conf .= "}\n";
1704

    
1705
		/* add static mappings */
1706
		/* Needs to use DUID */
1707
		if (is_array($dhcpv6ifconf['staticmap'])) {
1708
			$i = 0;
1709
			foreach ($dhcpv6ifconf['staticmap'] as $sm) {
1710
				$dhcpdv6conf .= <<<EOD
1711
host s_{$dhcpv6if}_{$i} {
1712
	host-identifier option dhcp6.client-id {$sm['duid']};
1713

    
1714
EOD;
1715
				if ($sm['ipaddrv6']) {
1716
					$ipaddrv6 = $sm['ipaddrv6'];
1717
					if ($ifcfgv6['ipaddrv6'] == 'track6') {
1718
						$ipaddrv6 = merge_ipv6_delegated_prefix($ifcfgipv6, $ipaddrv6, $pdlen);
1719
					}
1720
					$dhcpdv6conf .= "	fixed-address6 {$ipaddrv6};\n";
1721
				}
1722

    
1723
				if ($sm['hostname']) {
1724
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1725
					$dhhostname = str_replace(".", "_", $dhhostname);
1726
					$dhcpdv6conf .= "	option host-name {$dhhostname};\n";
1727
					if (isset($dhcpv6ifconf['ddnsupdate']) &&
1728
					    isset($dhcpv6ifconf['ddnsforcehostname'])) {
1729
						$dhcpdv6conf .= "	ddns-hostname \"{$dhhostname}\";\n";
1730
					}
1731
				}
1732
				if ($sm['filename']) {
1733
					$dhcpdv6conf .= "	filename \"{$sm['filename']}\";\n";
1734
				}
1735

    
1736
				if ($sm['rootpath']) {
1737
					$dhcpdv6conf .= "	option root-path \"{$sm['rootpath']}\";\n";
1738
				}
1739

    
1740
				$dhcpdv6conf .= "}\n";
1741
				$i++;
1742
			}
1743
		}
1744

    
1745
		if ($dhcpv6ifconf['ddnsdomain']) {
1746
			$dhcpdv6conf .= dhcpdkey($dhcpv6ifconf);
1747
			$dhcpdv6conf .= dhcpdzones($ddns_zones);
1748
		}
1749

    
1750
		if ($config['dhcpdv6'][$dhcpv6if]['ramode'] <> "unmanaged" && isset($config['interfaces'][$dhcpv6if]['enable'])) {
1751
			if (preg_match("/poes/si", $dhcpv6if)) {
1752
				/* magic here */
1753
				$dhcpdv6ifs = array_merge($dhcpdv6ifs, get_pppoes_child_interfaces($dhcpv6if));
1754
			} else {
1755
				$realif = get_real_interface($dhcpv6if, "inet6");
1756
				if (stristr("$realif", "bridge")) {
1757
					$mac = get_interface_mac($realif);
1758
					$v6address = generate_ipv6_from_mac($mac);
1759
					/* Create link local address for bridges */
1760
					mwexec("/sbin/ifconfig {$realif} inet6 {$v6address}");
1761
				}
1762
				$realif = escapeshellcmd($realif);
1763
				$dhcpdv6ifs[] = $realif;
1764
			}
1765
		}
1766
	}
1767

    
1768
	if ($nsupdate) {
1769
		$dhcpdv6conf .= "ddns-update-style interim;\n";
1770
		$dhcpdv6conf .= "update-static-leases on;\n";
1771
	} else {
1772
		$dhcpdv6conf .= "ddns-update-style none;\n";
1773
	}
1774

    
1775
	/* write dhcpdv6.conf */
1776
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf", $dhcpdv6conf)) {
1777
		log_error("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1778
		if (platform_booting()) {
1779
			printf("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1780
		}
1781
		unset($dhcpdv6conf);
1782
		return 1;
1783
	}
1784
	unset($dhcpdv6conf);
1785

    
1786
	/* create an empty leases v6 database */
1787
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases")) {
1788
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1789
	}
1790

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

    
1795
	/* fire up dhcpd in a chroot */
1796
	if (count($dhcpdv6ifs) > 0) {
1797
		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 " .
1798
			join(" ", $dhcpdv6ifs));
1799
		mwexec("/usr/local/sbin/dhcpleases6 -c \"/usr/local/bin/php-cgi -f /usr/local/sbin/prefixes.php\" -l {$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1800
	}
1801
	if (platform_booting()) {
1802
		print gettext("done.") . "\n";
1803
	}
1804

    
1805
	return 0;
1806
}
1807

    
1808
function services_igmpproxy_configure() {
1809
	global $config, $g;
1810

    
1811
	/* kill any running igmpproxy */
1812
	killbyname("igmpproxy");
1813

    
1814
	if (!isset($config['igmpproxy']['enable'])) {
1815
		return 0;
1816
	}
1817
	if (!is_array($config['igmpproxy']['igmpentry']) || (count($config['igmpproxy']['igmpentry']) == 0)) {
1818
		return 1;
1819
	}
1820

    
1821
	$iflist = get_configured_interface_list();
1822

    
1823
	$igmpconf = <<<EOD
1824

    
1825
##------------------------------------------------------
1826
## Enable Quickleave mode (Sends Leave instantly)
1827
##------------------------------------------------------
1828
quickleave
1829

    
1830
EOD;
1831

    
1832
	foreach ($config['igmpproxy']['igmpentry'] as $igmpcf) {
1833
		unset($iflist[$igmpcf['ifname']]);
1834
		$realif = get_real_interface($igmpcf['ifname']);
1835
		if (empty($igmpcf['threshold'])) {
1836
			$threshld = 1;
1837
		} else {
1838
			$threshld = $igmpcf['threshold'];
1839
		}
1840
		$igmpconf .= "phyint {$realif} {$igmpcf['type']} ratelimit 0 threshold {$threshld}\n";
1841

    
1842
		if ($igmpcf['address'] <> "") {
1843
			$item = explode(" ", $igmpcf['address']);
1844
			foreach ($item as $iww) {
1845
				$igmpconf .= "altnet {$iww}\n";
1846
			}
1847
		}
1848
		$igmpconf .= "\n";
1849
	}
1850
	foreach ($iflist as $ifn) {
1851
		$realif = get_real_interface($ifn);
1852
		$igmpconf .= "phyint {$realif} disabled\n";
1853
	}
1854
	$igmpconf .= "\n";
1855

    
1856
	$igmpfl = fopen($g['varetc_path'] . "/igmpproxy.conf", "w");
1857
	if (!$igmpfl) {
1858
		log_error(gettext("Could not write Igmpproxy configuration file!"));
1859
		return;
1860
	}
1861
	fwrite($igmpfl, $igmpconf);
1862
	fclose($igmpfl);
1863
	unset($igmpconf);
1864

    
1865
	if (isset($config['syslog']['igmpxverbose'])) {
1866
		mwexec_bg("/usr/local/sbin/igmpproxy -v {$g['varetc_path']}/igmpproxy.conf");
1867
	} else {
1868
		mwexec_bg("/usr/local/sbin/igmpproxy {$g['varetc_path']}/igmpproxy.conf");
1869
	}
1870

    
1871
	log_error(gettext("Started IGMP proxy service."));
1872

    
1873
	return 0;
1874
}
1875

    
1876
function services_dhcrelay_configure() {
1877
	global $config, $g;
1878

    
1879
	if (isset($config['system']['developerspew'])) {
1880
		$mt = microtime();
1881
		echo "services_dhcrelay_configure() being called $mt\n";
1882
	}
1883

    
1884
	/* kill any running dhcrelay */
1885
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
1886

    
1887
	init_config_arr(array('dhcrelay'));
1888
	$dhcrelaycfg = &$config['dhcrelay'];
1889

    
1890
	/* DHCPRelay enabled on any interfaces? */
1891
	if (!isset($dhcrelaycfg['enable'])) {
1892
		return 0;
1893
	}
1894

    
1895
	if (platform_booting()) {
1896
		echo gettext("Starting DHCP relay service...");
1897
	} else {
1898
		sleep(1);
1899
	}
1900

    
1901
	$iflist = get_configured_interface_list();
1902

    
1903
	$dhcrelayifs = array();
1904
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1905
	foreach ($dhcifaces as $dhcrelayif) {
1906
		if (!isset($iflist[$dhcrelayif])) {
1907
			continue;
1908
		}
1909

    
1910
		if (get_interface_ip($dhcrelayif)) {
1911
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1912
		}
1913
	}
1914
	$dhcrelayifs = array_unique($dhcrelayifs);
1915

    
1916
	/*
1917
	 * In order for the relay to work, it needs to be active
1918
	 * on the interface in which the destination server sits.
1919
	 */
1920
	$srvips = explode(",", $dhcrelaycfg['server']);
1921
	if (!is_array($srvips)) {
1922
		log_error(gettext("No destination IP has been configured!"));
1923
		return;
1924
	}
1925
	$srvifaces = array();
1926
	foreach ($srvips as $srcidx => $srvip) {
1927
		$destif = guess_interface_from_ip($srvip);
1928
		if (!empty($destif) && !is_pseudo_interface($destif)) {
1929
			$srvifaces[] = $destif;
1930
		}
1931
	}
1932
	$srvifaces = array_unique($srvifaces);
1933

    
1934
	/* Check for relays in the same subnet as clients so they can bind for
1935
	 * either direction (up or down) */
1936
	$srvrelayifs = array_intersect($dhcrelayifs, $srvifaces);
1937

    
1938
	/* The server interface(s) should not be in this list */
1939
	$dhcrelayifs = array_diff($dhcrelayifs, $srvifaces);
1940

    
1941
	/* Remove the dual-role interfaces from up and down lists */
1942
	$srvifaces = array_diff($srvifaces, $srvrelayifs);
1943
	$dhcrelayifs = array_diff($dhcrelayifs, $srvrelayifs);
1944

    
1945
	/* fire up dhcrelay */
1946
	if (empty($dhcrelayifs) && empty($srvrelayifs)) {
1947
		log_error(gettext("No suitable downstream interfaces found for running dhcrelay!"));
1948
		return; /* XXX */
1949
	}
1950
	if (empty($srvifaces) && empty($srvrelayifs)) {
1951
		log_error(gettext("No suitable upstream interfaces found for running dhcrelay!"));
1952
		return; /* XXX */
1953
	}
1954

    
1955
	$cmd = "/usr/local/sbin/dhcrelay";
1956

    
1957
	if (!empty($dhcrelayifs)) {
1958
		$cmd .= " -id " . implode(" -id ", $dhcrelayifs);
1959
	}
1960
	if (!empty($srvifaces)) {
1961
		$cmd .= " -iu " . implode(" -iu ", $srvifaces);
1962
	}
1963
	if (!empty($srvrelayifs)) {
1964
		$cmd .= " -i " . implode(" -i ", $srvrelayifs);
1965
	}
1966

    
1967
	if (isset($dhcrelaycfg['agentoption'])) {
1968
		$cmd .= " -a -m replace";
1969
	}
1970

    
1971
	$cmd .= " " . implode(" ", $srvips);
1972
	mwexec($cmd);
1973
	unset($cmd);
1974

    
1975
	return 0;
1976
}
1977

    
1978
function services_dhcrelay6_configure() {
1979
	global $config, $g;
1980

    
1981
	if (isset($config['system']['developerspew'])) {
1982
		$mt = microtime();
1983
		echo "services_dhcrelay6_configure() being called $mt\n";
1984
	}
1985

    
1986
	/* kill any running dhcrelay */
1987
	killbypid("{$g['varrun_path']}/dhcrelay6.pid");
1988

    
1989
	init_config_arr(array('dhcrelay6'));
1990
	$dhcrelaycfg = &$config['dhcrelay6'];
1991

    
1992
	/* DHCPv6 Relay enabled on any interfaces? */
1993
	if (!isset($dhcrelaycfg['enable'])) {
1994
		return 0;
1995
	}
1996

    
1997
	if (platform_booting()) {
1998
		echo gettext("Starting DHCPv6 relay service...");
1999
	} else {
2000
		sleep(1);
2001
	}
2002

    
2003
	$iflist = get_configured_interface_list();
2004

    
2005
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
2006
	foreach ($dhcifaces as $dhcrelayif) {
2007
		if (!isset($iflist[$dhcrelayif])) {
2008
			continue;
2009
		}
2010

    
2011
		if (get_interface_ipv6($dhcrelayif)) {
2012
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
2013
		}
2014
	}
2015
	$dhcrelayifs = array_unique($dhcrelayifs);
2016

    
2017
	/*
2018
	 * In order for the relay to work, it needs to be active
2019
	 * on the interface in which the destination server sits.
2020
	 */
2021
	$srvips = explode(",", $dhcrelaycfg['server']);
2022
	$srvifaces = array();
2023
	foreach ($srvips as $srcidx => $srvip) {
2024
		$destif = guess_interface_from_ip($srvip);
2025
		if (!empty($destif) && !is_pseudo_interface($destif)) {
2026
			$srvifaces[] = "{$srvip}%{$destif}";
2027
		}
2028
	}
2029

    
2030
	/* fire up dhcrelay */
2031
	if (empty($dhcrelayifs) || empty($srvifaces)) {
2032
		log_error(gettext("No suitable interface found for running dhcrelay -6!"));
2033
		return; /* XXX */
2034
	}
2035

    
2036
	$cmd = "/usr/local/sbin/dhcrelay -6 -pf \"{$g['varrun_path']}/dhcrelay6.pid\"";
2037
	foreach ($dhcrelayifs as $dhcrelayif) {
2038
		$cmd .= " -l {$dhcrelayif}";
2039
	}
2040
	foreach ($srvifaces as $srviface) {
2041
		$cmd .= " -u \"{$srviface}\"";
2042
	}
2043
	mwexec($cmd);
2044
	unset($cmd);
2045

    
2046
	return 0;
2047
}
2048

    
2049
function services_dyndns_configure_client($conf) {
2050

    
2051
	if (!isset($conf['enable'])) {
2052
		return;
2053
	}
2054

    
2055
	/* load up the dyndns.class */
2056
	require_once("dyndns.class");
2057

    
2058
	$dns = new updatedns($dnsService = $conf['type'],
2059
		$dnsHost = $conf['host'],
2060
		$dnsDomain = $conf['domainname'],
2061
		$dnsUser = $conf['username'],
2062
		$dnsPass = $conf['password'],
2063
		$dnsWildcard = $conf['wildcard'],
2064
		$dnsProxied = $conf['proxied'],
2065
		$dnsMX = $conf['mx'],
2066
		$dnsIf = "{$conf['interface']}",
2067
		$dnsBackMX = NULL,
2068
		$dnsServer = NULL,
2069
		$dnsPort = NULL,
2070
		$dnsUpdateURL = "{$conf['updateurl']}",
2071
		$forceUpdate = $conf['force'],
2072
		$dnsZoneID = $conf['zoneid'],
2073
		$dnsTTL = $conf['ttl'],
2074
		$dnsResultMatch = "{$conf['resultmatch']}",
2075
		$dnsRequestIf = "{$conf['requestif']}",
2076
		$dnsID = "{$conf['id']}",
2077
		$dnsVerboseLog = $conf['verboselog'],
2078
		$curlIpresolveV4 = $conf['curl_ipresolve_v4'],
2079
		$curlSslVerifypeer = $conf['curl_ssl_verifypeer']);
2080
}
2081

    
2082
function services_dyndns_configure($int = "") {
2083
	global $config, $g;
2084
	if (isset($config['system']['developerspew'])) {
2085
		$mt = microtime();
2086
		echo "services_dyndns_configure() being called $mt\n";
2087
	}
2088

    
2089
	if (isset($config['dyndnses']['dyndns']) && is_array($config['dyndnses']['dyndns'])) {
2090
		$dyndnscfg = $config['dyndnses']['dyndns'];
2091
	} else {
2092
		return 0;
2093
	}
2094
	$gwgroups = return_gateway_groups_array(true);
2095
	if (is_array($dyndnscfg)) {
2096
		if (platform_booting()) {
2097
			echo gettext("Starting DynDNS clients...");
2098
		}
2099

    
2100
		foreach ($dyndnscfg as $dyndns) {
2101
			/*
2102
			 * If it's using a gateway group, check if interface is
2103
			 * the active gateway for that group
2104
			 */
2105
			$group_int = '';
2106
			$friendly_group_int = '';
2107
			$gwgroup_member = false;
2108
			if (is_array($gwgroups[$dyndns['interface']])) {
2109
				if (!empty($gwgroups[$dyndns['interface']][0]['vip'])) {
2110
					$group_int = $gwgroups[$dyndns['interface']][0]['vip'];
2111
				} else {
2112
					$group_int = $gwgroups[$dyndns['interface']][0]['int'];
2113
					$friendly_group_int =
2114
					    convert_real_interface_to_friendly_interface_name(
2115
						$group_int);
2116
					if (!empty($int)) {
2117
						$gwgroup_member =
2118
						    interface_gateway_group_member(get_real_interface($int),
2119
						    $dyndns['interface']);
2120
					}
2121
				}
2122
			}
2123
			if ((empty($int)) || ($int == $dyndns['interface']) || $gwgroup_member ||
2124
			    ($int == $group_int) || ($int == $friendly_group_int)) {
2125
				$dyndns['verboselog'] = isset($dyndns['verboselog']);
2126
				$dyndns['curl_ipresolve_v4'] = isset($dyndns['curl_ipresolve_v4']);
2127
				$dyndns['curl_ssl_verifypeer'] = isset($dyndns['curl_ssl_verifypeer']);
2128
				$dyndns['proxied'] = isset($dyndns['proxied']);
2129
				services_dyndns_configure_client($dyndns);
2130
				sleep(1);
2131
			}
2132
		}
2133

    
2134
		if (platform_booting()) {
2135
			echo gettext("done.") . "\n";
2136
		}
2137
	}
2138

    
2139
	return 0;
2140
}
2141

    
2142
function dyndnsCheckIP($int) {
2143
	global $config, $factory_default_checkipservice;
2144
	$ip_address = get_interface_ip($int);
2145
	if (is_private_ip($ip_address)) {
2146
		$gateways_status = return_gateways_status(true);
2147
		// If the gateway for this interface is down, then the external check cannot work.
2148
		// Avoid the long wait for the external check to timeout.
2149
		if (stristr($gateways_status[$config['interfaces'][$int]['gateway']]['status'], "down")) {
2150
			return "down";
2151
		}
2152

    
2153
		// Append the factory default check IP service to the list (if not disabled).
2154
		if (!isset($config['checkipservices']['disable_factory_default'])) {
2155
			if (!is_array($config['checkipservices'])) {
2156
				$config['checkipservices'] = array();
2157
			}
2158
			if (!is_array($config['checkipservices']['checkipservice'])) {
2159
				$config['checkipservices']['checkipservice'] = array();
2160
			}
2161
			$config['checkipservices']['checkipservice'][] = $factory_default_checkipservice;
2162
		}
2163

    
2164
		// Use the first enabled check IP service as the default.
2165
		if (is_array($config['checkipservices']['checkipservice'])) {
2166
			foreach ($config['checkipservices']['checkipservice'] as $i => $checkipservice) {
2167
				if (isset($checkipservice['enable'])) {
2168
					$url = $checkipservice['url'];
2169
					$username = $checkipservice['username'];
2170
					$password = $checkipservice['password'];
2171
					$verifysslpeer = isset($checkipservice['verifysslpeer']);
2172
					break;
2173
				}
2174
			}
2175
		}
2176

    
2177
		$hosttocheck = $url;
2178
		$ip_ch = curl_init($hosttocheck);
2179
		curl_setopt($ip_ch, CURLOPT_RETURNTRANSFER, 1);
2180
		curl_setopt($ip_ch, CURLOPT_SSL_VERIFYPEER, $verifysslpeer);
2181
		curl_setopt($ip_ch, CURLOPT_INTERFACE, 'host!' . $ip_address);
2182
		curl_setopt($ip_ch, CURLOPT_CONNECTTIMEOUT, '30');
2183
		curl_setopt($ip_ch, CURLOPT_TIMEOUT, 120);
2184
		curl_setopt($ip_ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
2185
		curl_setopt($ip_ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
2186
		curl_setopt($ip_ch, CURLOPT_USERPWD, "{$username}:{$password}");
2187
		$ip_result_page = curl_exec($ip_ch);
2188
		curl_close($ip_ch);
2189
		$ip_result_decoded = urldecode($ip_result_page);
2190
		preg_match('=Current IP Address: (.*)</body>=siU', $ip_result_decoded, $matches);
2191
		$ip_address = trim($matches[1]);
2192
	}
2193
	return $ip_address;
2194
}
2195

    
2196
function services_dnsmasq_configure($restart_dhcp = true) {
2197
	global $config, $g;
2198
	$return = 0;
2199

    
2200
	// hard coded args: will be removed to avoid duplication if specified in custom_options
2201
	$standard_args = array(
2202
		"dns-forward-max" => "--dns-forward-max=5000",
2203
		"cache-size" => "--cache-size=10000",
2204
		"local-ttl" => "--local-ttl=1"
2205
	);
2206

    
2207

    
2208
	if (isset($config['system']['developerspew'])) {
2209
		$mt = microtime();
2210
		echo "services_dnsmasq_configure() being called $mt\n";
2211
	}
2212

    
2213
	/* kill any running dnsmasq */
2214
	if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) {
2215
		sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
2216
	}
2217

    
2218
	if (isset($config['dnsmasq']['enable'])) {
2219

    
2220
		if (platform_booting()) {
2221
			echo gettext("Starting DNS forwarder...");
2222
		} else {
2223
			sleep(1);
2224
		}
2225

    
2226
		/* generate hosts file */
2227
		if (system_hosts_generate() != 0) {
2228
			$return = 1;
2229
		}
2230

    
2231
		$args = "";
2232

    
2233
		if (isset($config['dnsmasq']['regdhcp'])) {
2234
			$args .= " --dhcp-hostsfile={$g['etc_path']}/hosts ";
2235
		}
2236

    
2237
		/* Setup listen port, if non-default */
2238
		if (is_port($config['dnsmasq']['port'])) {
2239
			$args .= " --port={$config['dnsmasq']['port']} ";
2240
		}
2241

    
2242
		$listen_addresses = "";
2243
		if (isset($config['dnsmasq']['interface'])) {
2244
			$interfaces = explode(",", $config['dnsmasq']['interface']);
2245
			foreach ($interfaces as $interface) {
2246
				$if = get_real_interface($interface);
2247
				if (does_interface_exist($if)) {
2248
					$laddr = get_interface_ip($interface);
2249
					if (is_ipaddrv4($laddr)) {
2250
						$listen_addresses .= " --listen-address={$laddr} ";
2251
					}
2252
					$laddr6 = get_interface_ipv6($interface);
2253
					if (is_ipaddrv6($laddr6) && !isset($config['dnsmasq']['strictbind'])) {
2254
						/*
2255
						 * XXX: Since dnsmasq does not support link-local address
2256
						 * with scope specified. These checks are being done.
2257
						 */
2258
						if (is_linklocal($laddr6) && strstr($laddr6, "%")) {
2259
							$tmpaddrll6 = explode("%", $laddr6);
2260
							$listen_addresses .= " --listen-address={$tmpaddrll6[0]} ";
2261
						} else {
2262
							$listen_addresses .= " --listen-address={$laddr6} ";
2263
						}
2264
					}
2265
				}
2266
			}
2267
			if (!empty($listen_addresses)) {
2268
				$args .= " {$listen_addresses} ";
2269
				if (isset($config['dnsmasq']['strictbind'])) {
2270
					$args .= " --bind-interfaces ";
2271
				}
2272
			}
2273
		}
2274

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

    
2282
			// Build an array of domain overrides to help in checking for matches.
2283
			$override_a = array();
2284
			if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2285
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2286
					$override_a[$override['domain']] = "y";
2287
				}
2288
			}
2289

    
2290
			// Build an array of the private reverse lookup domain names
2291
			$reverse_domain_a = array("10.in-addr.arpa", "168.192.in-addr.arpa");
2292
			// Unfortunately the 172.16.0.0/12 range does not map nicely to the in-addr.arpa scheme.
2293
			for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) {
2294
				$reverse_domain_a[] = "$subnet_num.172.in-addr.arpa";
2295
			}
2296

    
2297
			// Set the --server parameter to nowhere for each reverse domain name that was not specifically specified in a domain override.
2298
			foreach ($reverse_domain_a as $reverse_domain) {
2299
				if (!isset($override_a[$reverse_domain])) {
2300
					$args .= " --server=/$reverse_domain/ ";
2301
				}
2302
			}
2303
			unset($override_a);
2304
			unset($reverse_domain_a);
2305
		}
2306

    
2307
		/* Setup forwarded domains */
2308
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2309
			foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2310
				if ($override['ip'] == "!") {
2311
					$override[ip] = "";
2312
				}
2313
				$args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
2314
			}
2315
		}
2316

    
2317
		/* Allow DNS Rebind for forwarded domains */
2318
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2319
			if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2320
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2321
					$args .= ' --rebind-domain-ok=/' . $override['domain'] . '/ ';
2322
				}
2323
			}
2324
		}
2325

    
2326
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2327
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2328
		}
2329

    
2330
		if (isset($config['dnsmasq']['strict_order'])) {
2331
			$args .= " --strict-order ";
2332
		}
2333

    
2334
		if (isset($config['dnsmasq']['domain_needed'])) {
2335
			$args .= " --domain-needed ";
2336
		}
2337

    
2338
		if ($config['dnsmasq']['custom_options']) {
2339
			foreach (preg_split('/\s+/', $config['dnsmasq']['custom_options']) as $c) {
2340
				$args .= " " . escapeshellarg("--{$c}");
2341
				$p = explode('=', $c);
2342
				if (array_key_exists($p[0], $standard_args)) {
2343
					unset($standard_args[$p[0]]);
2344
				}
2345
			}
2346
		}
2347
		$args .= ' ' . implode(' ', array_values($standard_args));
2348

    
2349
		/* run dnsmasq. Use "-C /dev/null" since we use command line args only (Issue #6730) */
2350
		$cmd = "/usr/local/sbin/dnsmasq --all-servers -C /dev/null {$dns_rebind} {$args}";
2351
		//log_error("dnsmasq command: {$cmd}");
2352
		mwexec_bg($cmd);
2353
		unset($args);
2354

    
2355
		system_dhcpleases_configure();
2356

    
2357
		if (platform_booting()) {
2358
			echo gettext("done.") . "\n";
2359
		}
2360
	}
2361

    
2362
	if (!platform_booting() && $restart_dhcp) {
2363
		if (services_dhcpd_configure() != 0) {
2364
			$return = 1;
2365
		}
2366
	}
2367

    
2368
	return $return;
2369
}
2370

    
2371
function services_unbound_configure($restart_dhcp = true) {
2372
	global $config, $g;
2373
	$return = 0;
2374

    
2375
	if (isset($config['system']['developerspew'])) {
2376
		$mt = microtime();
2377
		echo "services_unbound_configure() being called $mt\n";
2378
	}
2379

    
2380
	if (isset($config['unbound']['enable'])) {
2381
		require_once('/etc/inc/unbound.inc');
2382

    
2383
		/* Stop Unbound using TERM */
2384
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2385
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
2386
		}
2387

    
2388
		/* If unbound is still running, wait up to 30 seconds for it to terminate. */
2389
		for ($i=1; $i <= 30; $i++) {
2390
			if (is_process_running('unbound')) {
2391
				sleep(1);
2392
			}
2393
		}
2394

    
2395
		$python_mode = false;
2396
		if (isset($config['unbound']['python']) && !empty($config['unbound']['python_script'])) {
2397
			$python_mode = true;
2398
		}
2399

    
2400
		/* Include any additional functions as defined by python script include file */
2401
		if (file_exists("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc")) {
2402
			exec("/usr/local/bin/php -l " . escapeshellarg("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc")
2403
				. " 2>&1", $py_output, $py_retval);
2404
			if ($py_retval == 0) {
2405
				require_once("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc");
2406
			}
2407
		}
2408

    
2409
		/* DNS Resolver python integration */
2410
		if ($python_mode) {
2411
			if (!is_dir("{$g['unbound_chroot_path']}/dev")) {
2412
				safe_mkdir("{$g['unbound_chroot_path']}/dev");
2413
			}
2414
			exec("/sbin/mount -t devfs devfs " . escapeshellarg("{$g['unbound_chroot_path']}/dev"));
2415
		} else {
2416
			if (is_dir("{$g['unbound_chroot_path']}/dev")) {
2417
				exec("/sbin/umount -f " . escapeshellarg("{$g['unbound_chroot_path']}/dev"));
2418
			}
2419
		}
2420
		$base_folder = '/usr/local';
2421
		foreach (array('/bin', '/lib') as $dir) {
2422
			$validate = exec("/sbin/mount | /usr/bin/grep " . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir} (nullfs") . " 2>&1");
2423
			if ($python_mode) {
2424

    
2425
				// Add DNS Resolver python integration
2426
				if (empty($validate)) {
2427
					if (!is_dir("{$g['unbound_chroot_path']}{$base_folder}{$dir}")) {
2428
						safe_mkdir("{$g['unbound_chroot_path']}{$base_folder}{$dir}");
2429
					}
2430
					$output = $retval = '';
2431
					exec("/sbin/mount_nullfs -o ro " . escapeshellarg("/usr/local{$dir}") . ' '
2432
					    . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir}") . " 2>&1", $output, $retval);
2433

    
2434
					// Disable Unbound python on mount failure
2435
					if ($retval != 0) {
2436
						$config['unbound']['python'] = '';
2437
						$log_msg = "[Unbound-pymod]: Disabling Unbound python due to failed mount";
2438
						write_config($log_msg);
2439
						log_error($log_msg);
2440
					}
2441
				}
2442
			}
2443

    
2444
			// Remove DNS Resolver python integration
2445
			elseif (!empty($validate)) {
2446
				exec("/sbin/umount -t nullfs " . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir}") . " 2>&1", $output, $retval);
2447
				if ($retval == 0) {
2448
					foreach (array( "/usr/local{$dir}", '/usr/local', '/usr') as $folder) {
2449
						if (!empty($g['unbound_chroot_path']) && $g['unbound_chroot_path'] != '/' && is_dir("{$g['unbound_chroot_path']}{$folder}")) {
2450
							@rmdir(escapeshellarg("{$g['unbound_chroot_path']}{$folder}"));
2451
						}
2452

    
2453
						// Delete remaining subfolders on next loop
2454
						if ($dir == '/bin') {
2455
							break;
2456
						}
2457
					}
2458
				}
2459
				else {
2460
					log_error("[Unbound-pymod]: Failed to unmount!");
2461
				}
2462
			}
2463
		}
2464

    
2465
		if (platform_booting()) {
2466
			echo gettext("Starting DNS Resolver...");
2467
		} else {
2468
			sleep(1);
2469
		}
2470

    
2471
		/* generate hosts file */
2472
		if (system_hosts_generate() != 0) {
2473
			$return = 1;
2474
		}
2475

    
2476
		/* Check here for dhcp6 complete - wait upto 10 seconds */
2477
		if($config['interfaces']["wan"]['ipaddrv6'] == 'dhcp6') {
2478
			$wanif = get_real_interface("wan", "inet6");
2479
			if (platform_booting()) {
2480
				for ($i=1; $i <= 10; $i++) {
2481
					if (!file_exists("/tmp/{$wanif}_dhcp6_complete")) {
2482
						log_error(gettext("Unbound start waiting on dhcp6c."));
2483
						sleep(1);
2484
					} else {
2485
						unlink_if_exists("/tmp/{$wanif}_dhcp6_complete");
2486
						log_error(gettext("dhcp6 init complete. Continuing"));
2487
						break;
2488
					}
2489
				}
2490
			}
2491
		}
2492

    
2493
		sync_unbound_service();
2494
		if (platform_booting()) {
2495
			log_error(gettext("sync unbound done."));
2496
			echo gettext("done.") . "\n";
2497
		}
2498

    
2499
		system_dhcpleases_configure();
2500
	} else {
2501
		/* kill Unbound since it should not be enabled */
2502
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2503
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "KILL");
2504
		}
2505
	}
2506

    
2507
	if (!platform_booting() && $restart_dhcp) {
2508
		if (services_dhcpd_configure() != 0) {
2509
			$return = 1;
2510
		}
2511
	}
2512

    
2513
	return $return;
2514
}
2515

    
2516
function services_snmpd_configure() {
2517
	global $config, $g;
2518
	if (isset($config['system']['developerspew'])) {
2519
		$mt = microtime();
2520
		echo "services_snmpd_configure() being called $mt\n";
2521
	}
2522

    
2523
	/* kill any running snmpd */
2524
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
2525
	sleep(2);
2526
	if (is_process_running("bsnmpd")) {
2527
		mwexec("/usr/bin/killall bsnmpd", true);
2528
	}
2529

    
2530
	if (isset($config['snmpd']['enable'])) {
2531

    
2532
		if (platform_booting()) {
2533
			echo gettext("Starting SNMP daemon... ");
2534
		}
2535

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

    
2541
		/* generate snmpd.conf */
2542
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
2543
		if (!$fd) {
2544
			printf(gettext("Error: cannot open snmpd.conf in services_snmpd_configure().%s"), "\n");
2545
			return 1;
2546
		}
2547

    
2548

    
2549
		$snmpdconf = <<<EOD
2550
location := "{$config['snmpd']['syslocation']}"
2551
contact := "{$config['snmpd']['syscontact']}"
2552
read := "{$config['snmpd']['rocommunity']}"
2553

    
2554
EOD;
2555

    
2556
/* No docs on what write strings do there so disable for now.
2557
		if (isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])) {
2558
			$snmpdconf .= <<<EOD
2559
# write string
2560
write := "{$config['snmpd']['rwcommunity']}"
2561

    
2562
EOD;
2563
		}
2564
*/
2565

    
2566

    
2567
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2568
			$snmpdconf .= <<<EOD
2569
# SNMP Trap support.
2570
traphost := {$config['snmpd']['trapserver']}
2571
trapport := {$config['snmpd']['trapserverport']}
2572
trap := "{$config['snmpd']['trapstring']}"
2573

    
2574

    
2575
EOD;
2576
		}
2577

    
2578
		$sysDescr = "{$g['product_name']} {$config['system']['hostname']}.{$config['system']['domain']}" .
2579
			" {$g['product_version_string']} {$g['platform']} " . php_uname("s") .
2580
			" " . php_uname("r") . " " . php_uname("m");
2581

    
2582
		$snmpdconf .= <<<EOD
2583
system := 1     # pfSense
2584
%snmpd
2585
sysDescr			= "{$sysDescr}"
2586
begemotSnmpdDebugDumpPdus       = 2
2587
begemotSnmpdDebugSyslogPri      = 7
2588
begemotSnmpdCommunityString.0.1 = $(read)
2589

    
2590
EOD;
2591

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

    
2597
EOD;
2598
		}
2599
*/
2600

    
2601

    
2602
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2603
			$snmpdconf .= <<<EOD
2604
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
2605
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
2606
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
2607

    
2608
EOD;
2609
		}
2610

    
2611

    
2612
		$snmpdconf .= <<<EOD
2613
begemotSnmpdCommunityDisable    = 1
2614

    
2615
EOD;
2616

    
2617
		$bind_to_ips = array();
2618
		if (isset($config['snmpd']['bindip'])) {
2619
			foreach (explode(",", $config['snmpd']['bindip']) as $bind_to_ip) {
2620
				if (is_ipaddr($bind_to_ip)) {
2621
					$bind_to_ips[] = $bind_to_ip;
2622
				} else {
2623
					$if = get_real_interface($bind_to_ip);
2624
					if (does_interface_exist($if)) {
2625
						$bindip = get_interface_ip($bind_to_ip);
2626
						if (is_ipaddr($bindip)) {
2627
							$bind_to_ips[] = $bindip;
2628
						}
2629
					}
2630
				}
2631
			}
2632
		}
2633
		if (!count($bind_to_ips)) {
2634
			$bind_to_ips = array("0.0.0.0");
2635
		}
2636

    
2637
		if (is_port($config['snmpd']['pollport'])) {
2638
			foreach ($bind_to_ips as $bind_to_ip) {
2639
				$snmpdconf .= <<<EOD
2640
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
2641

    
2642
EOD;
2643

    
2644
			}
2645
		}
2646

    
2647
		$snmpdconf .= <<<EOD
2648
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
2649
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
2650

    
2651
# These are bsnmp macros not php vars.
2652
sysContact      = $(contact)
2653
sysLocation     = $(location)
2654
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
2655

    
2656
snmpEnableAuthenTraps = 2
2657

    
2658
EOD;
2659

    
2660
		if (is_array($config['snmpd']['modules'])) {
2661
			if (isset($config['snmpd']['modules']['mibii'])) {
2662
			$snmpdconf .= <<<EOD
2663
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
2664

    
2665
EOD;
2666
			}
2667

    
2668
			if (isset($config['snmpd']['modules']['netgraph'])) {
2669
				$snmpdconf .= <<<EOD
2670
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
2671
%netgraph
2672
begemotNgControlNodeName = "snmpd"
2673

    
2674
EOD;
2675
			}
2676

    
2677
			if (isset($config['snmpd']['modules']['pf'])) {
2678
				$snmpdconf .= <<<EOD
2679
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
2680

    
2681
EOD;
2682
			}
2683

    
2684
			if (isset($config['snmpd']['modules']['hostres'])) {
2685
				$snmpdconf .= <<<EOD
2686
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
2687

    
2688
EOD;
2689
			}
2690

    
2691
			if (isset($config['snmpd']['modules']['bridge'])) {
2692
				$snmpdconf .= <<<EOD
2693
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
2694
# config must end with blank line
2695

    
2696
EOD;
2697
			}
2698
			if (isset($config['snmpd']['modules']['ucd'])) {
2699
				$snmpdconf .= <<<EOD
2700
begemotSnmpdModulePath."ucd"     = "/usr/local/lib/snmp_ucd.so"
2701

    
2702
EOD;
2703
			}
2704
			if (isset($config['snmpd']['modules']['regex'])) {
2705
				$snmpdconf .= <<<EOD
2706
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"
2707

    
2708
EOD;
2709
			}
2710
		}
2711

    
2712
		fwrite($fd, $snmpdconf);
2713
		fclose($fd);
2714
		unset($snmpdconf);
2715

    
2716
		/* run bsnmpd */
2717
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
2718
			" -p {$g['varrun_path']}/snmpd.pid");
2719

    
2720
		if (platform_booting()) {
2721
			echo gettext("done.") . "\n";
2722
		}
2723
	}
2724

    
2725
	return 0;
2726
}
2727

    
2728
function services_dnsupdate_process($int = "", $updatehost = "", $forced = false) {
2729
	global $config, $g;
2730
	if (isset($config['system']['developerspew'])) {
2731
		$mt = microtime();
2732
		echo "services_dnsupdate_process() being called $mt\n";
2733
	}
2734

    
2735
	/* Dynamic DNS updating active? */
2736
	if (!is_array($config['dnsupdates']['dnsupdate'])) {
2737
		return 0;
2738
	}
2739

    
2740
	$notify_text = "";
2741
	$gwgroups = return_gateway_groups_array(true);
2742
	foreach ($config['dnsupdates']['dnsupdate'] as $i => $dnsupdate) {
2743
		if (!isset($dnsupdate['enable'])) {
2744
			continue;
2745
		}
2746
		/*
2747
		 * If it's using a gateway group, check if interface is
2748
		 * the active gateway for that group
2749
		 */
2750
		$group_int = '';
2751
		$friendly_group_int = '';
2752
		$gwgroup_member = false;
2753
		if (is_array($gwgroups[$dnsupdate['interface']])) {
2754
			if (!empty($gwgroups[$dnsupdate['interface']][0]['vip'])) {
2755
				$group_int = $gwgroups[$dnsupdate['interface']][0]['vip'];
2756
			} else {
2757
				$group_int = $gwgroups[$dnsupdate['interface']][0]['int'];
2758
				$friendly_group_int =
2759
				    convert_real_interface_to_friendly_interface_name(
2760
					$group_int);
2761
				if (!empty($int)) {
2762
					$gwgroup_member =
2763
					    interface_gateway_group_member(get_real_interface($int),
2764
					    $dnsupdate['interface']);
2765
				}
2766
			}
2767
		}
2768
		if (!empty($int) && ($int != $dnsupdate['interface']) && !$gwgroup_member &&
2769
		    ($int != $group_int) && ($int != $friendly_group_int)) {
2770
			continue;
2771
		}
2772
		if (!empty($updatehost) && ($updatehost != $dnsupdate['host'])) {
2773
			continue;
2774
		}
2775

    
2776
		/* determine interface name */
2777
		$if = get_failover_interface($dnsupdate['interface']);
2778

    
2779
		/* Determine address to update and default binding address */
2780
		if (isset($dnsupdate['usepublicip'])) {
2781
			$wanip = dyndnsCheckIP($if);
2782
			$bindipv4 = get_interface_ip($if);
2783
		} else {
2784
			$wanip = get_interface_ip($if);
2785
			$bindipv4 = $wanip;
2786
		}
2787
		if (is_stf_interface($dnsupdate['interface'])) { 
2788
			$wanipv6 = get_interface_ipv6($dnsupdate['interface'] . '_stf');
2789
		} else {
2790
			$wanipv6 = get_interface_ipv6($if);
2791
		}
2792
		$bindipv6 = $wanipv6;
2793

    
2794
		/* Handle non-default interface bindings */
2795
		if ($dnsupdate['updatesource'] == "none") {
2796
			/* When empty, the directive will be omitted. */
2797
			$bindipv4 = "";
2798
			$bindipv6 = "";
2799
		} elseif (!empty($dnsupdate['updatesource'])) {
2800
			/* Find the alternate binding address */
2801
			$bindipv4 = get_interface_ip($dnsupdate['updatesource']);
2802
			if (is_stf_interface($dnsupdate['interface'])) { 
2803
				$bindipv6 = get_interface_ipv6($dnsupdate['updatesource'] . '_stf');
2804
			} else {
2805
				$bindipv6 = get_interface_ipv6($dnsupdate['updatesource']);
2806
			}
2807
		}
2808

    
2809
		/* Handle IPv4/IPv6 selection for the update source interface/VIP */
2810
		switch ($dnsupdate['updatesourcefamily']) {
2811
			case "inet":
2812
				$bindip = $bindipv4;
2813
				break;
2814
			case "inet6":
2815
				$bindip = $bindipv6;
2816
				break;
2817
			case "":
2818
			default:
2819
				/* Try IPv4 first, if that is empty, try IPv6. */
2820
				/* Only specify the address if it's present, otherwise omit. */
2821
				if (!empty($bindipv4)) {
2822
					$bindip = $bindipv4;
2823
				} elseif (!empty($bindipv6)) {
2824
					$bindip = $bindipv6;
2825
				}
2826
				break;
2827
		}
2828

    
2829
		$cacheFile = $g['conf_path'] .
2830
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2831
		    escapeshellarg($dnsupdate['host']) .
2832
		    "_{$dnsupdate['server']}.cache";
2833
		$cacheFilev6 = $g['conf_path'] .
2834
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2835
		    escapeshellarg($dnsupdate['host']) .
2836
		    "_{$dnsupdate['server']}_v6.cache";
2837
		$currentTime = time();
2838

    
2839
		if (!$wanip && !$wanipv6) {
2840
			continue;
2841
		}
2842

    
2843
		$keyname = $dnsupdate['keyname'];
2844
		/* trailing dot */
2845
		if (substr($keyname, -1) != ".") {
2846
			$keyname .= ".";
2847
		}
2848

    
2849
		$hostname = $dnsupdate['host'];
2850
		/* trailing dot */
2851
		if (substr($hostname, -1) != ".") {
2852
			$hostname .= ".";
2853
		}
2854

    
2855
		/* write key file */
2856
		$algorithm = empty($dnsupdate['keyalgorithm']) ? 'hmac-md5' : $dnsupdate['keyalgorithm'];
2857
		$upkey = <<<EOD
2858
key "{$keyname}" {
2859
	algorithm {$algorithm};
2860
	secret "{$dnsupdate['keydata']}";
2861
};
2862

    
2863
EOD;
2864
		@file_put_contents("{$g['varetc_path']}/nsupdatekey{$i}", $upkey);
2865

    
2866
		/* generate update instructions */
2867
		$upinst = "";
2868
		if (!empty($dnsupdate['server'])) {
2869
			$upinst .= "server {$dnsupdate['server']}\n";
2870
		}
2871

    
2872
		if (!empty($dnsupdate['zone'])) {
2873
			$upinst .= "zone {$dnsupdate['zone']}\n";
2874
		}
2875

    
2876
		$cachedipv4 = '';
2877
		$cacheTimev4 = 0;
2878
		if (file_exists($cacheFile)) {
2879
			list($cachedipv4, $cacheTimev4) = explode("|",
2880
			    file_get_contents($cacheFile));
2881
		}
2882
		$cachedipv6 = '';
2883
		$cacheTimev6 = 0;
2884
		if (file_exists($cacheFilev6)) {
2885
			list($cachedipv6, $cacheTimev6) = explode("|",
2886
			    file_get_contents($cacheFilev6));
2887
		}
2888

    
2889
		// 25 Days
2890
		$maxCacheAgeSecs = 25 * 24 * 60 * 60;
2891
		$need_update = false;
2892

    
2893
		/* Update IPv4 if we have it. */
2894
		if (is_ipaddrv4($wanip) && $dnsupdate['recordtype'] != "AAAA") {
2895
			if (($wanip != $cachedipv4) || $forced ||
2896
			    (($currentTime - $cacheTimev4) > $maxCacheAgeSecs)) {
2897
				$upinst .= "update delete " .
2898
				    "{$dnsupdate['host']}. A\n";
2899
				$upinst .= "update add {$dnsupdate['host']}. " .
2900
				    "{$dnsupdate['ttl']} A {$wanip}\n";
2901
				if (!empty($bindip)) {
2902
					$upinst .= "local {$bindip}\n";
2903
				}
2904
				$need_update = true;
2905
			} else {
2906
				log_error(sprintf(gettext(
2907
				    "phpDynDNS: Not updating %s A record because the IP address has not changed."),
2908
				    $dnsupdate['host']));
2909
			}
2910
		} else {
2911
			@unlink($cacheFile);
2912
			unset($cacheFile);
2913
		}
2914

    
2915
		/* Update IPv6 if we have it. */
2916
		if (is_ipaddrv6($wanipv6) && $dnsupdate['recordtype'] != "A") {
2917
			if (($wanipv6 != $cachedipv6) || $forced ||
2918
			    (($currentTime - $cacheTimev6) > $maxCacheAgeSecs)) {
2919
				$upinst .= "update delete " .
2920
				    "{$dnsupdate['host']}. AAAA\n";
2921
				$upinst .= "update add {$dnsupdate['host']}. " .
2922
				    "{$dnsupdate['ttl']} AAAA {$wanipv6}\n";
2923
				$need_update = true;
2924
			} else {
2925
				log_error(sprintf(gettext(
2926
				    "phpDynDNS: Not updating %s AAAA record because the IPv6 address has not changed."),
2927
				    $dnsupdate['host']));
2928
			}
2929
		} else {
2930
			@unlink($cacheFilev6);
2931
			unset($cacheFilev6);
2932
		}
2933

    
2934
		$upinst .= "\n";	/* mind that trailing newline! */
2935

    
2936
		if (!$need_update) {
2937
			continue;
2938
		}
2939

    
2940
		@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}", $upinst);
2941
		unset($upinst);
2942
		/* invoke nsupdate */
2943
		$cmd = "/usr/local/bin/nsupdate -k {$g['varetc_path']}/nsupdatekey{$i}";
2944

    
2945
		if (isset($dnsupdate['usetcp'])) {
2946
			$cmd .= " -v";
2947
		}
2948

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

    
2951
		if (mwexec($cmd) == 0) {
2952
			if (!empty($cacheFile)) {
2953
				@file_put_contents($cacheFile,
2954
				    "{$wanip}|{$currentTime}");
2955
				log_error(sprintf(gettext(
2956
				    'phpDynDNS: updating cache file %1$s: %2$s'),
2957
				    $cacheFile, $wanip));
2958
				$notify_text .= sprintf(gettext(
2959
				    'DynDNS updated IP Address (A) for %1$s on %2$s (%3$s) to %4$s'),
2960
				    $dnsupdate['host'],
2961
				    convert_real_interface_to_friendly_descr($if),
2962
				    $if, $wanip) . "\n";
2963
			}
2964
			if (!empty($cacheFilev6)) {
2965
				@file_put_contents($cacheFilev6,
2966
				    "{$wanipv6}|{$currentTime}");
2967
				log_error(sprintf(gettext(
2968
				    'phpDynDNS: updating cache file %1$s: %2$s'),
2969
				    $cacheFilev6, $wanipv6));
2970
				$notify_text .= sprintf(gettext(
2971
				    'DynDNS updated IPv6 Address (AAAA) for %1$s on %2$s (%3$s) to %4$s'),
2972
				    $dnsupdate['host'],
2973
				    convert_real_interface_to_friendly_descr($if),
2974
				    $if, $wanipv6) . "\n";
2975
			}
2976
		} else {
2977
			if (!empty($cacheFile)) {
2978
				log_error(sprintf(gettext(
2979
				    'phpDynDNS: ERROR while updating IP Address (A) for %1$s (%2$s)'),
2980
				    $dnsupdate['host'], $wanip));
2981
			}
2982
			if (!empty($cacheFilev6)) {
2983
				log_error(sprintf(gettext(
2984
				    'phpDynDNS: ERROR while updating IP Address (AAAA) for %1$s (%2$s)'),
2985
				    $dnsupdate['host'], $wanipv6));
2986
			}
2987
		}
2988
		unset($cmd);
2989
	}
2990

    
2991
	if (!empty($notify_text)) {
2992
		notify_all_remote($notify_text);
2993
	}
2994

    
2995
	return 0;
2996
}
2997

    
2998
/* configure cron service */
2999
function configure_cron() {
3000
	global $g, $config;
3001

    
3002
	/* preserve existing crontab entries */
3003
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
3004

    
3005
	for ($i = 0; $i < count($crontab_contents); $i++) {
3006
		$cron_item = &$crontab_contents[$i];
3007
		if (strpos($cron_item, "# pfSense specific crontab entries") !== false) {
3008
			array_splice($crontab_contents, $i - 1);
3009
			break;
3010
		}
3011
	}
3012
	$crontab_contents = implode("\n", $crontab_contents) . "\n";
3013

    
3014

    
3015
	if (is_array($config['cron']['item'])) {
3016
		$crontab_contents .= "#\n";
3017
		$crontab_contents .= "# pfSense specific crontab entries\n";
3018
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
3019
		$crontab_contents .= "#\n";
3020

    
3021
		if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) {
3022
			$http_proxy = $config['system']['proxyurl'];
3023
			if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) {
3024
				$http_proxy .= ':' . $config['system']['proxyport'];
3025
			}
3026
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
3027

    
3028
			if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
3029
				$crontab_contents .= "HTTP_PROXY_AUTH=basic:*:{$config['system']['proxyuser']}:{$config['system']['proxypass']}";
3030
			}
3031
		}
3032

    
3033
		foreach ($config['cron']['item'] as $item) {
3034
			$crontab_contents .= "\n{$item['minute']}\t";
3035
			$crontab_contents .= "{$item['hour']}\t";
3036
			$crontab_contents .= "{$item['mday']}\t";
3037
			$crontab_contents .= "{$item['month']}\t";
3038
			$crontab_contents .= "{$item['wday']}\t";
3039
			$crontab_contents .= "{$item['who']}\t";
3040
			$crontab_contents .= "{$item['command']}";
3041
		}
3042

    
3043
		$crontab_contents .= "\n#\n";
3044
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
3045
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
3046
		$crontab_contents .= "#\n\n";
3047
	}
3048

    
3049
	/* please maintain the newline at the end of file */
3050
	file_put_contents("/etc/crontab", $crontab_contents);
3051
	unset($crontab_contents);
3052

    
3053
	/* make sure that cron is running and start it if it got killed somehow */
3054
	if (!is_process_running("cron")) {
3055
		exec("cd /tmp && /usr/sbin/cron -s 2>/dev/null");
3056
	} else {
3057
	/* do a HUP kill to force sync changes */
3058
		sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP");
3059
	}
3060

    
3061
}
3062

    
3063
function upnp_action ($action) {
3064
	global $g, $config;
3065
	switch ($action) {
3066
		case "start":
3067
			if (file_exists('/var/etc/miniupnpd.conf')) {
3068
				@unlink("{$g['varrun_path']}/miniupnpd.pid");
3069
				mwexec_bg("/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf -P {$g['varrun_path']}/miniupnpd.pid");
3070
			}
3071
			break;
3072
		case "stop":
3073
			killbypid("{$g['varrun_path']}/miniupnpd.pid");
3074
			while ((int)exec("/bin/pgrep -a miniupnpd | wc -l") > 0) {
3075
				mwexec('/usr/bin/killall miniupnpd 2>/dev/null', true);
3076
			}
3077
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
3078
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
3079
			break;
3080
		case "restart":
3081
			upnp_action('stop');
3082
			upnp_action('start');
3083
			break;
3084
	}
3085
}
3086

    
3087
function upnp_start() {
3088
	global $config;
3089

    
3090
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
3091
		return;
3092
	}
3093

    
3094
	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
3095
		echo gettext("Starting UPnP service... ");
3096
		require_once('/usr/local/pkg/miniupnpd.inc');
3097
		sync_package_miniupnpd();
3098
		echo "done.\n";
3099
	}
3100
}
3101

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

    
3105
	$is_installed = false;
3106
	$cron_changed = true;
3107
	$change_message = "";
3108

    
3109
	if (!is_array($config['cron'])) {
3110
		$config['cron'] = array();
3111
	}
3112
	if (!is_array($config['cron']['item'])) {
3113
		$config['cron']['item'] = array();
3114
	}
3115

    
3116
	$x = 0;
3117
	foreach ($config['cron']['item'] as $item) {
3118
		if (strstr($item['command'], $command)) {
3119
			$is_installed = true;
3120
			break;
3121
		}
3122
		$x++;
3123
	}
3124

    
3125
	if ($active) {
3126
		$cron_item = array();
3127
		$cron_item['minute'] = $minute;
3128
		$cron_item['hour'] = $hour;
3129
		$cron_item['mday'] = $monthday;
3130
		$cron_item['month'] = $month;
3131
		$cron_item['wday'] = $weekday;
3132
		$cron_item['who'] = $who;
3133
		$cron_item['command'] = $command;
3134
		if (!$is_installed) {
3135
			$config['cron']['item'][] = $cron_item;
3136
			$change_message = "Installed cron job for %s";
3137
		} else {
3138
			if ($config['cron']['item'][$x] == $cron_item) {
3139
				$cron_changed = false;
3140
			} else {
3141
				$config['cron']['item'][$x] = $cron_item;
3142
				$change_message = "Updated cron job for %s";
3143
			}
3144
		}
3145
	} else {
3146
		if ($is_installed == true) {
3147
			array_splice($config['cron']['item'], $x, 1);
3148
			$change_message = "Removed cron job for %s";
3149
		} else {
3150
			$cron_changed = false;
3151
		}
3152
	}
3153

    
3154
	if ($cron_changed) {
3155
		/* Optionally write the configuration if this function made changes.
3156
		 * Performing a write_config() in this way can have unintended side effects. See #7146
3157
		 * Base system instances of this function do not need to write, packages may.
3158
		 */
3159
		if ($write_config) {
3160
			write_config(sprintf(gettext($change_message), $command));
3161
		}
3162
		configure_cron();
3163
	}
3164
}
3165

    
3166
?>
(46-46/61)