Project

General

Profile

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

    
1541
		$dnscfgv6 = "";
1542

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

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

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

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

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

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

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

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

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

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

    
1631
		$dhcpdv6conf .= $dnscfgv6;
1632

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1798
	/* fire up dhcpd in a chroot */
1799
	if (count($dhcpdv6ifs) > 0) {
1800
		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 " .
1801
			join(" ", $dhcpdv6ifs));
1802
		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");
1803
	}
1804
	if (platform_booting()) {
1805
		print gettext("done.") . "\n";
1806
	}
1807

    
1808
	return 0;
1809
}
1810

    
1811
function services_igmpproxy_configure() {
1812
	global $config, $g;
1813

    
1814
	/* kill any running igmpproxy */
1815
	killbyname("igmpproxy");
1816

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

    
1824
	$iflist = get_configured_interface_list();
1825

    
1826
	$igmpconf = <<<EOD
1827

    
1828
##------------------------------------------------------
1829
## Enable Quickleave mode (Sends Leave instantly)
1830
##------------------------------------------------------
1831
quickleave
1832

    
1833
EOD;
1834

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

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

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

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

    
1874
	log_error(gettext("Started IGMP proxy service."));
1875

    
1876
	return 0;
1877
}
1878

    
1879
function services_dhcrelay_configure() {
1880
	global $config, $g;
1881

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

    
1887
	/* kill any running dhcrelay */
1888
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
1889

    
1890
	init_config_arr(array('dhcrelay'));
1891
	$dhcrelaycfg = &$config['dhcrelay'];
1892

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

    
1898
	if (platform_booting()) {
1899
		echo gettext("Starting DHCP relay service...");
1900
	} else {
1901
		sleep(1);
1902
	}
1903

    
1904
	$iflist = get_configured_interface_list();
1905

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

    
1913
		if (get_interface_ip($dhcrelayif)) {
1914
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1915
		}
1916
	}
1917
	$dhcrelayifs = array_unique($dhcrelayifs);
1918

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

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

    
1941
	/* The server interface(s) should not be in this list */
1942
	$dhcrelayifs = array_diff($dhcrelayifs, $srvifaces);
1943

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

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

    
1958
	$cmd = "/usr/local/sbin/dhcrelay";
1959

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

    
1970
	if (isset($dhcrelaycfg['agentoption'])) {
1971
		$cmd .= " -a -m replace";
1972
	}
1973

    
1974
	$cmd .= " " . implode(" ", $srvips);
1975
	mwexec($cmd);
1976
	unset($cmd);
1977

    
1978
	return 0;
1979
}
1980

    
1981
function services_dhcrelay6_configure() {
1982
	global $config, $g;
1983

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

    
1989
	/* kill any running dhcrelay */
1990
	killbypid("{$g['varrun_path']}/dhcrelay6.pid");
1991

    
1992
	init_config_arr(array('dhcrelay6'));
1993
	$dhcrelaycfg = &$config['dhcrelay6'];
1994

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

    
2000
	if (platform_booting()) {
2001
		echo gettext("Starting DHCPv6 relay service...");
2002
	} else {
2003
		sleep(1);
2004
	}
2005

    
2006
	$iflist = get_configured_interface_list();
2007

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

    
2014
		if (get_interface_ipv6($dhcrelayif)) {
2015
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
2016
		}
2017
	}
2018
	$dhcrelayifs = array_unique($dhcrelayifs);
2019

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

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

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

    
2049
	return 0;
2050
}
2051

    
2052
function services_dyndns_configure_client($conf) {
2053

    
2054
	if (!isset($conf['enable'])) {
2055
		return;
2056
	}
2057

    
2058
	/* load up the dyndns.class */
2059
	require_once("dyndns.class");
2060

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

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

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

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

    
2137
		if (platform_booting()) {
2138
			echo gettext("done.") . "\n";
2139
		}
2140
	}
2141

    
2142
	return 0;
2143
}
2144

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

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

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

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

    
2199
function services_dnsmasq_configure($restart_dhcp = true) {
2200
	global $config, $g;
2201
	$return = 0;
2202

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

    
2210

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

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

    
2221
	if (isset($config['dnsmasq']['enable'])) {
2222

    
2223
		if (platform_booting()) {
2224
			echo gettext("Starting DNS forwarder...");
2225
		} else {
2226
			sleep(1);
2227
		}
2228

    
2229
		/* generate hosts file */
2230
		if (system_hosts_generate() != 0) {
2231
			$return = 1;
2232
		}
2233

    
2234
		$args = "";
2235

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

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

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

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

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

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

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

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

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

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

    
2333
		if (isset($config['dnsmasq']['strict_order'])) {
2334
			$args .= " --strict-order ";
2335
		}
2336

    
2337
		if (isset($config['dnsmasq']['domain_needed'])) {
2338
			$args .= " --domain-needed ";
2339
		}
2340

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

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

    
2358
		system_dhcpleases_configure();
2359

    
2360
		if (platform_booting()) {
2361
			echo gettext("done.") . "\n";
2362
		}
2363
	}
2364

    
2365
	if (!platform_booting() && $restart_dhcp) {
2366
		if (services_dhcpd_configure() != 0) {
2367
			$return = 1;
2368
		}
2369
	}
2370

    
2371
	return $return;
2372
}
2373

    
2374
function services_unbound_configure($restart_dhcp = true) {
2375
	global $config, $g;
2376
	$return = 0;
2377

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

    
2383
	if (isset($config['unbound']['enable'])) {
2384
		require_once('/etc/inc/unbound.inc');
2385

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

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

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

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

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

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

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

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

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

    
2468
		if (platform_booting()) {
2469
			echo gettext("Starting DNS Resolver...");
2470
		} else {
2471
			sleep(1);
2472
		}
2473

    
2474
		/* generate hosts file */
2475
		if (system_hosts_generate() != 0) {
2476
			$return = 1;
2477
		}
2478

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

    
2496
		sync_unbound_service();
2497
		if (platform_booting()) {
2498
			log_error(gettext("sync unbound done."));
2499
			echo gettext("done.") . "\n";
2500
		}
2501

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

    
2510
	if (!platform_booting() && $restart_dhcp) {
2511
		if (services_dhcpd_configure() != 0) {
2512
			$return = 1;
2513
		}
2514
	}
2515

    
2516
	return $return;
2517
}
2518

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

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

    
2533
	if (isset($config['snmpd']['enable'])) {
2534

    
2535
		if (platform_booting()) {
2536
			echo gettext("Starting SNMP daemon... ");
2537
		}
2538

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

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

    
2551

    
2552
		$snmpdconf = <<<EOD
2553
location := "{$config['snmpd']['syslocation']}"
2554
contact := "{$config['snmpd']['syscontact']}"
2555
read := "{$config['snmpd']['rocommunity']}"
2556

    
2557
EOD;
2558

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

    
2565
EOD;
2566
		}
2567
*/
2568

    
2569

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

    
2577

    
2578
EOD;
2579
		}
2580

    
2581
		$sysDescr = "{$g['product_label']} {$config['system']['hostname']}.{$config['system']['domain']}" .
2582
			" {$g['product_version_string']} " . php_uname("s") .
2583
			" " . php_uname("r") . " " . php_uname("m");
2584

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

    
2593
EOD;
2594

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

    
2600
EOD;
2601
		}
2602
*/
2603

    
2604

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

    
2611
EOD;
2612
		}
2613

    
2614

    
2615
		$snmpdconf .= <<<EOD
2616
begemotSnmpdCommunityDisable    = 1
2617

    
2618
EOD;
2619

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

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

    
2645
EOD;
2646

    
2647
			}
2648
		}
2649

    
2650
		$snmpdconf .= <<<EOD
2651
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
2652
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
2653

    
2654
# These are bsnmp macros not php vars.
2655
sysContact      = $(contact)
2656
sysLocation     = $(location)
2657
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
2658

    
2659
snmpEnableAuthenTraps = 2
2660

    
2661
EOD;
2662

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

    
2668
EOD;
2669
			}
2670

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

    
2677
EOD;
2678
			}
2679

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

    
2684
EOD;
2685
			}
2686

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

    
2691
EOD;
2692
			}
2693

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

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

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

    
2711
EOD;
2712
			}
2713
		}
2714

    
2715
		fwrite($fd, $snmpdconf);
2716
		fclose($fd);
2717
		unset($snmpdconf);
2718

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

    
2723
		if (platform_booting()) {
2724
			echo gettext("done.") . "\n";
2725
		}
2726
	}
2727

    
2728
	return 0;
2729
}
2730

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

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

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

    
2779
		/* determine interface name */
2780
		$if = get_failover_interface($dnsupdate['interface']);
2781

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

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

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

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

    
2842
		if (!$wanip && !$wanipv6) {
2843
			continue;
2844
		}
2845

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

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

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

    
2866
EOD;
2867
		@file_put_contents("{$g['varetc_path']}/nsupdatekey{$i}", $upkey);
2868

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

    
2875
		if (!empty($dnsupdate['zone'])) {
2876
			$upinst .= "zone {$dnsupdate['zone']}\n";
2877
		}
2878

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

    
2892
		// 25 Days
2893
		$maxCacheAgeSecs = 25 * 24 * 60 * 60;
2894
		$need_update = false;
2895

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

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

    
2937
		$upinst .= "\n";	/* mind that trailing newline! */
2938

    
2939
		if (!$need_update) {
2940
			continue;
2941
		}
2942

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

    
2948
		if (isset($dnsupdate['usetcp'])) {
2949
			$cmd .= " -v";
2950
		}
2951

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

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

    
2994
	if (!empty($notify_text)) {
2995
		notify_all_remote($notify_text);
2996
	}
2997

    
2998
	return 0;
2999
}
3000

    
3001
/* configure cron service */
3002
function configure_cron() {
3003
	global $g, $config;
3004

    
3005
	/* preserve existing crontab entries */
3006
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
3007

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

    
3017

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

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

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

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

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

    
3052
	/* please maintain the newline at the end of file */
3053
	file_put_contents("/etc/crontab", $crontab_contents);
3054
	unset($crontab_contents);
3055

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

    
3064
}
3065

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

    
3090
function upnp_start() {
3091
	global $config;
3092

    
3093
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
3094
		return;
3095
	}
3096

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

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

    
3108
	$is_installed = false;
3109
	$cron_changed = true;
3110
	$change_message = "";
3111

    
3112
	if (!is_array($config['cron'])) {
3113
		$config['cron'] = array();
3114
	}
3115
	if (!is_array($config['cron']['item'])) {
3116
		$config['cron']['item'] = array();
3117
	}
3118

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

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

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

    
3169
?>
(46-46/61)