Project

General

Profile

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

    
28

    
29
define('DYNDNS_PROVIDER_VALUES', 'all-inkl azure azurev6 citynetwork cloudflare cloudflare-v6 cloudns custom custom-v6 digitalocean digitalocean-v6 dnsexit dnsimple dnsmadeeasy dnsomatic domeneshop domeneshop-v6 dreamhost dreamhost-v6 duiadns duiadns-v6 dyndns dyndns-custom dyndns-static dyns dynv6 dynv6-v6 easydns 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,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
	if (!isset($dhcpifconf['disableauthoritative'])) {
563
		$dhcpdconf .= "authoritative;\n";
564
	}
565

    
566
	if (isset($dhcpifconf['alwaysbroadcast'])) {
567
		$dhcpdconf .= "always-broadcast on\n";
568
	}
569

    
570
	// OMAPI Settings
571
	if (isset($dhcpifconf['omapi_port']) && is_numeric($dhcpifconf['omapi_port'])) {
572
		$dhcpdconf .= <<<EOD
573

    
574
key omapi_key {
575
  algorithm {$dhcpifconf['omapi_key_algorithm']};
576
  secret "{$dhcpifconf['omapi_key']}";
577
};
578
omapi-port {$dhcpifconf['omapi_port']};
579
omapi-key omapi_key;
580

    
581
EOD;
582
	}
583

    
584
	$dhcpdifs = array();
585
	$enable_add_routers = false;
586
	$gateways_arr = return_gateways_array();
587
	/* only add a routers line if the system has any IPv4 gateway at all */
588
	/* a static route has a gateway, manually overriding this field always works */
589
	foreach ($gateways_arr as $gwitem) {
590
		if ($gwitem['ipprotocol'] == "inet") {
591
			$enable_add_routers = true;
592
			break;
593
		}
594
	}
595

    
596
	/*    loop through and determine if we need to setup
597
	 *    failover peer "bleh" entries
598
	 */
599
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
600

    
601
		if (!isset($config['interfaces'][$dhcpif]['enable'])) {
602
			continue;
603
		}
604

    
605
		interfaces_staticarp_configure($dhcpif);
606

    
607
		if (!isset($dhcpifconf['enable'])) {
608
			continue;
609
		}
610

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

    
652
			if (is_ipaddrv4($intip)) {
653
				$dhcpdconf .= <<<EOPP
654
failover peer "dhcp_{$dhcpif}" {
655
  {$type};
656
  address {$intip};
657
  port {$my_port};
658
  peer address {$dhcpifconf['failover_peerip']};
659
  peer port {$peer_port};
660
  max-response-delay 10;
661
  max-unacked-updates 10;
662
  {$dhcpdconf_pri}
663
  load balance max seconds 3;
664
}
665
\n
666
EOPP;
667
			}
668
		}
669
	}
670

    
671
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
672

    
673
		$newzone = array();
674
		$ifcfg = $config['interfaces'][$dhcpif];
675

    
676
		if (!isset($dhcpifconf['enable']) || !isset($Iflist[$dhcpif])) {
677
			continue;
678
		}
679
		$ifcfgip = get_interface_ip($dhcpif);
680
		$ifcfgsn = get_interface_subnet($dhcpif);
681
		$subnet = gen_subnet($ifcfgip, $ifcfgsn);
682
		$subnetmask = gen_subnet_mask($ifcfgsn);
683

    
684
		if (!is_ipaddr($subnet)) {
685
			continue;
686
		}
687

    
688
		$all_pools = array();
689
		$all_pools[] = $dhcpifconf;
690
		if (is_array($dhcpifconf['pool'])) {
691
			$all_pools = array_merge($all_pools, $dhcpifconf['pool']);
692
		}
693

    
694
		$dnscfg = "";
695

    
696
		if ($dhcpifconf['domain']) {
697
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
698
		}
699

    
700
		if ($dhcpifconf['domainsearchlist'] <> "") {
701
			$dnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpifconf['domainsearchlist'])) . "\";\n";
702
		}
703

    
704
		if (isset($dhcpifconf['ddnsupdate'])) {
705
			$need_ddns_updates = true;
706
			$newzone = array();
707
			if ($dhcpifconf['ddnsdomain'] <> "") {
708
				$newzone['domain-name'] = $dhcpifconf['ddnsdomain'];
709
				$dnscfg .= "	ddns-domainname \"{$dhcpifconf['ddnsdomain']}\";\n";
710
			} else {
711
				$newzone['domain-name'] = $config['system']['domain'];
712
			}
713

    
714
			if (empty($dhcpifconf['ddnsclientupdates'])) {
715
				$ddnsclientupdates = 'allow';
716
			} else {
717
				$ddnsclientupdates = $dhcpifconf['ddnsclientupdates'];
718
			}
719

    
720
			$dnscfg .= "	{$ddnsclientupdates} client-updates;\n";
721

    
722
			$revsubnet = array_reverse(explode('.',$subnet));
723

    
724
			$subnet_mask_bits = 32 - $ifcfgsn;
725
			$start_octet = $subnet_mask_bits >> 3;
726
			$octet_mask_bits = $subnet_mask_bits & ($subnet_mask_bits % 8);
727
			if ($octet_mask_bits) {
728
			    $octet_mask = (1 << $octet_mask_bits) - 1;
729
			    $octet_start = $revsubnet[$start_octet] & ~$octet_mask;
730
			    $revsubnet[$start_octet] = $octet_start . "-" . ($octet_start + $octet_mask);
731
			}
732

    
733
			$ptr_domain = '';
734
			for ($octet = 0; $octet <= 3; $octet++) {
735
				if ($octet < $start_octet) {
736
					continue;
737
				}
738
				$ptr_domain .= ((empty($ptr_domain) && $ptr_domain !== "0") ? '' : '.');
739
				$ptr_domain .= $revsubnet[$octet];
740
			}
741
			$ptr_domain .= ".in-addr.arpa";
742
			$newzone['ptr-domain'] = $ptr_domain;
743
			unset($ptr_domain, $revsubnet, $start_octet);
744
		}
745

    
746
		if (is_array($dhcpifconf['dnsserver']) && ($dhcpifconf['dnsserver'][0])) {
747
			$dnscfg .= "	option domain-name-servers " . join(",", $dhcpifconf['dnsserver']) . ";";
748
			if ($newzone['domain-name']) {
749
				$newzone['dns-servers'] = $dhcpifconf['dnsserver'];
750
			}
751
		} else if (isset($config['dnsmasq']['enable'])) {
752
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
753
			if ($newzone['domain-name'] && is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
754
				$newzone['dns-servers'] = $syscfg['dnsserver'];
755
			}
756
		} else if (isset($config['unbound']['enable'])) {
757
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
758
		} else if (!empty($dns_arrv4)) {
759
			$dnscfg .= "	option domain-name-servers " . join(",", $dns_arrv4) . ";";
760
			if ($newzone['domain-name']) {
761
				$newzone['dns-servers'] = $dns_arrv4;
762
			}
763
		}
764

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

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

    
792
		$dhcpdconf .= "subnet {$subnet} netmask {$subnetmask} {\n";
793

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

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

    
859
			if ($poolconf['failover_peerip'] <> "") {
860
				$dhcpdconf .= "		$deny_action dynamic bootp clients;\n";
861
			}
862

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

    
875
			if ($poolconf['gateway'] && $poolconf['gateway'] != "none" && ($poolconf['gateway'] != $dhcpifconf['gateway'])) {
876
				$dhcpdconf .= "		option routers {$poolconf['gateway']};\n";
877
			}
878

    
879
			if ($dhcpifconf['failover_peerip'] <> "") {
880
				$dhcpdconf .= "		failover peer \"dhcp_{$dhcpif}\";\n";
881
			}
882

    
883
			$pdnscfg = "";
884

    
885
			if ($poolconf['domain'] && ($poolconf['domain'] != $dhcpifconf['domain'])) {
886
				$pdnscfg .= "		option domain-name \"{$poolconf['domain']}\";\n";
887
			}
888

    
889
			if (!empty($poolconf['domainsearchlist']) && ($poolconf['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
890
				$pdnscfg .= "		option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $poolconf['domainsearchlist'])) . "\";\n";
891
			}
892

    
893
			if (isset($poolconf['ddnsupdate'])) {
894
				if (($poolconf['ddnsdomain'] <> "") && ($poolconf['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
895
					$pdnscfg .= "		ddns-domainname \"{$poolconf['ddnsdomain']}\";\n";
896
				}
897
				$pdnscfg .= "		ddns-update-style interim;\n";
898
			}
899

    
900
			$dhcpdconf .= "{$pdnscfg}";
901

    
902
			// default-lease-time
903
			if ($poolconf['defaultleasetime'] && ($poolconf['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
904
				$dhcpdconf .= "		default-lease-time {$poolconf['defaultleasetime']};\n";
905
			}
906

    
907
			// max-lease-time
908
			if ($poolconf['maxleasetime'] && ($poolconf['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
909
				$dhcpdconf .= "		max-lease-time {$poolconf['maxleasetime']};\n";
910
			}
911

    
912
			// ignore bootp
913
			if (isset($poolconf['ignorebootp'])) {
914
				$dhcpdconf .= "		ignore bootp;\n";
915
			}
916

    
917
			// ignore-client-uids
918
			if (isset($poolconf['ignoreclientuids'])) {
919
				$dhcpdconf .= "		ignore-client-uids true;\n";
920
			}
921

    
922
			// netbios-name*
923
			if (is_array($poolconf['winsserver']) && $poolconf['winsserver'][0] && ($poolconf['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
924
				$dhcpdconf .= "		option netbios-name-servers " . join(",", $poolconf['winsserver']) . ";\n";
925
				$dhcpdconf .= "		option netbios-node-type 8;\n";
926
			}
927

    
928
			// ntp-servers
929
			if (is_array($poolconf['ntpserver']) && $poolconf['ntpserver'][0] && ($poolconf['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
930
				$dhcpdconf .= "		option ntp-servers " . join(",", $poolconf['ntpserver']) . ";\n";
931
			}
932

    
933
			// tftp-server-name
934
			if (!empty($poolconf['tftp']) && ($poolconf['tftp'] != $dhcpifconf['tftp'])) {
935
				$dhcpdconf .= "		option tftp-server-name \"{$poolconf['tftp']}\";\n";
936
			}
937

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

    
955
			// ldap-server
956
			if (!empty($poolconf['ldap']) && ($poolconf['ldap'] != $dhcpifconf['ldap'])) {
957
				$dhcpdconf .= "		option ldap-server \"{$poolconf['ldap']}\";\n";
958
			}
959

    
960
			// net boot information
961
			if (isset($poolconf['netboot'])) {
962
				if (!empty($poolconf['nextserver']) && ($poolconf['nextserver'] != $dhcpifconf['nextserver'])) {
963
					$dhcpdconf .= "		next-server {$poolconf['nextserver']};\n";
964
				}
965

    
966
				if (!empty($poolconf['filename']) &&
967
				    (!isset($dhcpifconf['filename']) ||
968
				    ($poolconf['filename'] != $dhcpifconf['filename']))) {
969
					$filename = $poolconf['filename'];
970
				}
971
				if (!empty($poolconf['filename32']) &&
972
				    (!isset($dhcpifconf['filename32']) ||
973
				    ($poolconf['filename32'] != $dhcpifconf['filename32']))) {
974
					$filename32 = $poolconf['filename32'];
975
				}
976
				if (!empty($poolconf['filename64']) &&
977
				    (!isset($dhcpifconf['filename64']) ||
978
				    ($poolconf['filename64'] != $dhcpifconf['filename64']))) {
979
					$filename64 = $poolconf['filename64'];
980
				}
981
				if (!empty($poolconf['filename32arm']) &&
982
				    (!isset($dhcpifconf['filename32arm']) ||
983
				    ($poolconf['filename32arm'] != $dhcpifconf['filename32arm']))) {
984
					$filename32arm = $poolconf['filename32arm'];
985
				}
986
				if (!empty($poolconf['filename64arm']) &&
987
				    (!isset($dhcpifconf['filename64arm']) ||
988
				    ($poolconf['filename64arm'] != $dhcpifconf['filename64arm']))) {
989
					$filename64arm = $poolconf['filename64arm'];
990
				}
991

    
992
				if (!empty($filename32) || !empty($filename64) || !empty($filename32arm) || !empty($filename64arm)) {
993
					if (empty($filename) && !empty($dhcpifconf['filename'])) {
994
						$filename = $dhcpifconf['filename'];
995
					}
996
					if (empty($filename32) && !empty($dhcpifconf['filename32'])) {
997
						$filename32 = $dhcpifconf['filename32'];
998
					}
999
					if (empty($filename64) && !empty($dhcpifconf['filename64'])) {
1000
						$filename64 = $dhcpifconf['filename64'];
1001
					}
1002
					if (empty($filename32arm) && !empty($dhcpifconf['filename32arm'])) {
1003
						$filename32arm = $dhcpifconf['filename32arm'];
1004
					}
1005
					if (empty($filename64arm) && !empty($dhcpifconf['filename64arm'])) {
1006
						$filename64arm = $dhcpifconf['filename64arm'];
1007
					}
1008
				}
1009

    
1010
				if (!empty($filename) && !empty($filename32) && !empty($filename64) && !empty($filename32arm) && !empty($filename64arm)) {
1011
					$dhcpdconf .= "		if option arch = 00:06 {\n";
1012
					$dhcpdconf .= "			filename \"{$filename32}\";\n";
1013
					$dhcpdconf .= "		} else if option arch = 00:07 {\n";
1014
					$dhcpdconf .= "			filename \"{$filename64}\";\n";
1015
					$dhcpdconf .= "		} else if option arch = 00:09 {\n";
1016
					$dhcpdconf .= "			filename \"{$filename64}\";\n";
1017
					$dhcpdconf .= "		} else if option arch = 00:0a {\n";
1018
					$dhcpdconf .= "			filename \"{$filename32arm}\";\n";
1019
					$dhcpdconf .= "		} else if option arch = 00:0b {\n";
1020
					$dhcpdconf .= "			filename \"{$filename64arm}\";\n";
1021
					$dhcpdconf .= "		} else {\n";
1022
					$dhcpdconf .= "			filename \"{$filename}\";\n";
1023
					$dhcpdconf .= "		}\n\n";
1024
				} elseif (!empty($filename)) {
1025
					$dhcpdconf .= "		filename \"{$filename}\";\n";
1026
				}
1027
				unset($filename, $filename32, $filename64, $filename32arm, $filename64arm);
1028

    
1029
				if (!empty($poolconf['rootpath']) && ($poolconf['rootpath'] != $dhcpifconf['rootpath'])) {
1030
					$dhcpdconf .= "		option root-path \"{$poolconf['rootpath']}\";\n";
1031
				}
1032
			}
1033
			$dhcpdconf .= "		range {$poolconf['range']['from']} {$poolconf['range']['to']};\n";
1034
			$dhcpdconf .= "	}\n\n";
1035
		}
1036
// End of settings inside pools
1037

    
1038
		if ($dhcpifconf['gateway'] && $dhcpifconf['gateway'] != "none") {
1039
			$routers = $dhcpifconf['gateway'];
1040
			$add_routers = true;
1041
		} elseif ($dhcpifconf['gateway'] == "none") {
1042
			$add_routers = false;
1043
		} else {
1044
			$add_routers = $enable_add_routers;
1045
			$routers = $ifcfgip;
1046
		}
1047
		if ($add_routers) {
1048
			$dhcpdconf .= "	option routers {$routers};\n";
1049
		}
1050

    
1051
		$dhcpdconf .= <<<EOD
1052
$dnscfg
1053

    
1054
EOD;
1055
		// default-lease-time
1056
		if ($dhcpifconf['defaultleasetime']) {
1057
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
1058
		}
1059

    
1060
		// max-lease-time
1061
		if ($dhcpifconf['maxleasetime']) {
1062
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
1063
		}
1064

    
1065
		if (!isset($dhcpifconf['disablepingcheck'])) {
1066
			$dhcpdconf .= "	ping-check true;\n";
1067
		} else {
1068
			$dhcpdconf .= "	ping-check false;\n";
1069
		}
1070

    
1071
		// netbios-name*
1072
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
1073
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
1074
			$dhcpdconf .= "	option netbios-node-type 8;\n";
1075
		}
1076

    
1077
		// ntp-servers
1078
		if (is_array($dhcpifconf['ntpserver']) && $dhcpifconf['ntpserver'][0]) {
1079
			$dhcpdconf .= "	option ntp-servers " . join(",", $dhcpifconf['ntpserver']) . ";\n";
1080
		}
1081

    
1082
		// tftp-server-name
1083
		if ($dhcpifconf['tftp'] <> "") {
1084
			$dhcpdconf .= "	option tftp-server-name \"{$dhcpifconf['tftp']}\";\n";
1085
		}
1086

    
1087
		// Handle option, number rowhelper values
1088
		$dhcpdconf .= "\n";
1089
		if (isset($dhcpifconf['numberoptions']['item']) && is_array($dhcpifconf['numberoptions']['item'])) {
1090
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
1091
				$item_value = base64_decode($item['value']);
1092
				if (empty($item['type']) || $item['type'] == "text") {
1093
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} \"{$item_value}\";\n";
1094
				} else {
1095
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} {$item_value};\n";
1096
				}
1097
			}
1098
		}
1099

    
1100
		// ldap-server
1101
		if ($dhcpifconf['ldap'] <> "") {
1102
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
1103
		}
1104

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

    
1128
		$dhcpdconf .= <<<EOD
1129
}
1130

    
1131
EOD;
1132

    
1133
		/* add static mappings */
1134
		if (is_array($dhcpifconf['staticmap'])) {
1135

    
1136
			$i = 0;
1137
			$sm_newzone[] = array();
1138
			$need_sm_ddns_updates = false;
1139
			foreach ($dhcpifconf['staticmap'] as $sm) {
1140
				$cid = '';
1141
				$dhcpdconf .= "host s_{$dhcpif}_{$i} {\n";
1142

    
1143
				if ($sm['mac']) {
1144
					$dhcpdconf .= "	hardware ethernet {$sm['mac']};\n";
1145
				}
1146

    
1147
				if ($sm['cid']) {
1148
					$cid = str_replace('"', '\"', $sm['cid']);
1149
					$dhcpdconf .= "	option dhcp-client-identifier \"{$cid}\";\n";
1150
				}
1151

    
1152
				if ($sm['ipaddr']) {
1153
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
1154
				}
1155

    
1156
				if ($sm['hostname']) {
1157
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1158
					$dhhostname = str_replace(".", "_", $dhhostname);
1159
					$dhcpdconf .= "	option host-name \"{$dhhostname}\";\n";
1160
					if ((isset($dhcpifconf['ddnsupdate']) || isset($sm['ddnsupdate'])) && (isset($dhcpifconf['ddnsforcehostname']) || isset($sm['ddnsforcehostname']))) {
1161
						$dhcpdconf .= "	ddns-hostname \"{$dhhostname}\";\n";
1162
					}
1163
				}
1164
				if ($sm['filename']) {
1165
					$dhcpdconf .= "	filename \"{$sm['filename']}\";\n";
1166
				}
1167

    
1168
				if ($sm['rootpath']) {
1169
					$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1170
				}
1171

    
1172
				if ($sm['gateway'] && ($sm['gateway'] != $dhcpifconf['gateway'])) {
1173
					$dhcpdconf .= "	option routers {$sm['gateway']};\n";
1174
				}
1175

    
1176
				$smdnscfg = "";
1177

    
1178
				if ($sm['domain'] && ($sm['domain'] != $dhcpifconf['domain'])) {
1179
					$smdnscfg .= "	option domain-name \"{$sm['domain']}\";\n";
1180
				}
1181

    
1182
				if (!empty($sm['domainsearchlist']) && ($sm['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
1183
					$smdnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $sm['domainsearchlist'])) . "\";\n";
1184
				}
1185

    
1186
				if (isset($sm['ddnsupdate'])) {
1187
					if (($sm['ddnsdomain'] <> "") && ($sm['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
1188
						$smdnscfg .= "		ddns-domainname \"{$sm['ddnsdomain']}\";\n";
1189
				 		$need_sm_ddns_updates = true;	
1190
					}
1191
					$smdnscfg .= "		ddns-update-style interim;\n";
1192
				}
1193

    
1194
				if (is_array($sm['dnsserver']) && ($sm['dnsserver'][0]) && ($sm['dnsserver'][0] != $dhcpifconf['dnsserver'][0])) {
1195
					$smdnscfg .= "	option domain-name-servers " . join(",", $sm['dnsserver']) . ";\n";
1196
				}
1197
				$dhcpdconf .= "{$smdnscfg}";
1198

    
1199
				// default-lease-time
1200
				if ($sm['defaultleasetime'] && ($sm['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
1201
					$dhcpdconf .= "	default-lease-time {$sm['defaultleasetime']};\n";
1202
				}
1203

    
1204
				// max-lease-time
1205
				if ($sm['maxleasetime'] && ($sm['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
1206
					$dhcpdconf .= "	max-lease-time {$sm['maxleasetime']};\n";
1207
				}
1208

    
1209
				// netbios-name*
1210
				if (is_array($sm['winsserver']) && $sm['winsserver'][0] && ($sm['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
1211
					$dhcpdconf .= "	option netbios-name-servers " . join(",", $sm['winsserver']) . ";\n";
1212
					$dhcpdconf .= "	option netbios-node-type 8;\n";
1213
				}
1214

    
1215
				// ntp-servers
1216
				if (is_array($sm['ntpserver']) && $sm['ntpserver'][0] && ($sm['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
1217
					$dhcpdconf .= "	option ntp-servers " . join(",", $sm['ntpserver']) . ";\n";
1218
				}
1219

    
1220
				// tftp-server-name
1221
				if (!empty($sm['tftp']) && ($sm['tftp'] != $dhcpifconf['tftp'])) {
1222
					$dhcpdconf .= "	option tftp-server-name \"{$sm['tftp']}\";\n";
1223
				}
1224

    
1225
				// Handle option, number rowhelper values
1226
				$dhcpdconf .= "\n";
1227
				if (isset($sm['numberoptions']['item']) && is_array($sm['numberoptions']['item'])) {
1228
					foreach ($sm['numberoptions']['item'] as $itemidx => $item) {
1229
						$item_value = base64_decode($item['value']);
1230
						if (empty($item['type']) || $item['type'] == "text") {
1231
							$dhcpdconf .= "	option custom-s_{$dhcpif}_{$i}-{$itemidx} \"{$item_value}\";\n";
1232
						} else {
1233
							$dhcpdconf .= "	option custom-s_{$dhcpif}_{$i}-{$itemidx} {$item_value};\n";
1234
						}
1235
					}
1236
				}
1237

    
1238
				// ldap-server
1239
				if (!empty($sm['ldap']) && ($sm['ldap'] != $dhcpifconf['ldap'])) {
1240
					$dhcpdconf .= "	option ldap-server \"{$sm['ldap']}\";\n";
1241
				}
1242

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

    
1266
				$dhcpdconf .= "}\n";
1267

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

    
1288
				// subclass for DHCP limiting
1289
				if (!empty($sm['mac'])) {
1290
					// assuming ALL addresses are ethernet hardware type ("1:" prefix)
1291
					$dhcpdconf .= "subclass \"s_{$dhcpif}\" 1:{$sm['mac']};\n";
1292
				}
1293
				if (!empty($cid)) {
1294
					$dhcpdconf .= "subclass \"s_{$dhcpif}\" \"{$cid}\";\n";
1295
				}
1296

    
1297

    
1298
				$i++;
1299
			}
1300
		}
1301

    
1302
		$dhcpdifs[] = get_real_interface($dhcpif);
1303
		if ($newzone['domain-name']) {
1304
			if ($need_ddns_updates) {
1305
				$newzone['dns-servers'] = array($dhcpifconf['ddnsdomainprimary'], $dhcpifconf['ddnsdomainsecondary']);
1306
				$newzone['ddnsdomainkeyname'] = $dhcpifconf['ddnsdomainkeyname'];
1307
				$newzone['ddnsdomainkeyalgorithm'] = $dhcpifconf['ddnsdomainkeyalgorithm'];
1308
				$newzone['ddnsdomainkey'] = $dhcpifconf['ddnsdomainkey'];
1309
				$dhcpdconf .= dhcpdkey($dhcpifconf);
1310
			}
1311
			$ddns_zones[] = $newzone;
1312
		}
1313
	}
1314

    
1315
	if ($need_ddns_updates) {
1316
		$dhcpdconf .= "ddns-update-style interim;\n";
1317
		$dhcpdconf .= "update-static-leases on;\n";
1318

    
1319
		$dhcpdconf .= dhcpdzones($ddns_zones);
1320
	}
1321

    
1322
	/* write dhcpd.conf */
1323
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpd.conf", $dhcpdconf)) {
1324
		printf(gettext("Error: cannot open dhcpd.conf in services_dhcpdv4_configure().%s"), "\n");
1325
		unset($dhcpdconf);
1326
		return 1;
1327
	}
1328
	unset($dhcpdconf);
1329

    
1330
	/* create an empty leases database */
1331
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
1332
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
1333
	}
1334

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

    
1339
	/* fire up dhcpd in a chroot */
1340
	if (count($dhcpdifs) > 0) {
1341
		mwexec("/usr/local/sbin/dhcpd -user dhcpd -group _dhcp -chroot {$g['dhcpd_chroot_path']} -cf /etc/dhcpd.conf -pf {$g['varrun_path']}/dhcpd.pid " .
1342
			join(" ", $dhcpdifs));
1343
	}
1344

    
1345
	if (platform_booting()) {
1346
		print "done.\n";
1347
	}
1348

    
1349
	return 0;
1350
}
1351

    
1352
function dhcpdkey($dhcpifconf) {
1353
	$dhcpdconf = "";
1354
	if (!empty($dhcpifconf['ddnsdomainkeyname']) && !empty($dhcpifconf['ddnsdomainkey'])) {
1355
		$algorithm = empty($dhcpifconf['ddnsdomainkeyalgorithm']) ? 'hmac-md5' : $dhcpifconf['ddnsdomainkeyalgorithm'];
1356
		$dhcpdconf .= "key \"{$dhcpifconf['ddnsdomainkeyname']}\" {\n";
1357
		$dhcpdconf .= "	algorithm {$algorithm};\n";
1358
		$dhcpdconf .= "	secret {$dhcpifconf['ddnsdomainkey']};\n";
1359
		$dhcpdconf .= "}\n";
1360
	}
1361

    
1362
	return $dhcpdconf;
1363
}
1364

    
1365
function dhcpdzones($ddns_zones) {
1366
	$dhcpdconf = "";
1367

    
1368
	if (is_array($ddns_zones)) {
1369
		$added_zones = array();
1370
		foreach ($ddns_zones as $zone) {
1371
			if (!is_array($zone) || empty($zone) || !is_array($zone['dns-servers'])) {
1372
				continue;
1373
			}
1374
			$primary = $zone['dns-servers'][0];
1375
			$secondary = empty($zone['dns-servers'][1]) ? "" : $zone['dns-servers'][1];
1376

    
1377
			// Make sure we aren't using any invalid servers.
1378
			if (!is_ipaddr($primary)) {
1379
				if (is_ipaddr($secondary)) {
1380
					$primary = $secondary;
1381
					$secondary = "";
1382
				} else {
1383
					continue;
1384
				}
1385
			}
1386

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

    
1427
	return $dhcpdconf;
1428
}
1429

    
1430
function services_dhcpdv6_configure($blacklist = array()) {
1431
	global $config, $g;
1432

    
1433
	if ($g['services_dhcp_server_enable'] == false) {
1434
		return;
1435
	}
1436

    
1437
	if (isset($config['system']['developerspew'])) {
1438
		$mt = microtime();
1439
		echo "services_dhcpd_configure($if) being called $mt\n";
1440
	}
1441

    
1442
	/* kill any running dhcpd */
1443
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid")) {
1444
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid");
1445
	}
1446
	if (isvalidpid("{$g['varrun_path']}/dhcpleases6.pid")) {
1447
		killbypid("{$g['varrun_path']}/dhcpleases6.pid");
1448
	}
1449

    
1450
	/* DHCP enabled on any interfaces? */
1451
	if (!is_dhcpv6_server_enabled()) {
1452
		return 0;
1453
	}
1454

    
1455
	$syscfg = $config['system'];
1456
	if (!is_array($config['dhcpdv6'])) {
1457
		$config['dhcpdv6'] = array();
1458
	}
1459
	$dhcpdv6cfg = $config['dhcpdv6'];
1460
	$Iflist = get_configured_interface_list();
1461
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
1462

    
1463

    
1464
	if (platform_booting()) {
1465
		echo "Starting DHCPv6 service...";
1466
	} else {
1467
		sleep(1);
1468
	}
1469

    
1470
	$custoptionsv6 = "";
1471
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1472
		if (is_array($dhcpv6ifconf['numberoptions']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1473
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1474
				$custoptionsv6 .= "option custom-{$dhcpv6if}-{$itemv6idx} code {$itemv6['number']} = text;\n";
1475
			}
1476
		}
1477
	}
1478

    
1479
	if (isset($dhcpv6ifconf['netboot']) && !empty($dhcpv6ifconf['bootfile_url'])) {
1480
		$custoptionsv6 .= "option dhcp6.bootfile-url code 59 = string;\n";
1481
	}
1482

    
1483
	$dhcpdv6conf = <<<EOD
1484

    
1485
option domain-name "{$syscfg['domain']}";
1486
option ldap-server code 95 = text;
1487
option domain-search-list code 119 = text;
1488
{$custoptionsv6}
1489
default-lease-time 7200;
1490
max-lease-time 86400;
1491
log-facility local7;
1492
one-lease-per-client true;
1493
deny duplicates;
1494
ping-check true;
1495
update-conflict-detection false;
1496

    
1497
EOD;
1498

    
1499
	if (!isset($dhcpv6ifconf['disableauthoritative'])) {
1500
		$dhcpdv6conf .= "authoritative;\n";
1501
	}
1502

    
1503
	if (isset($dhcpv6ifconf['alwaysbroadcast'])) {
1504
		$dhcpdv6conf .= "always-broadcast on\n";
1505
	}
1506

    
1507
	$dhcpdv6ifs = array();
1508

    
1509
	$dhcpv6num = 0;
1510
	$nsupdate = false;
1511

    
1512
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1513

    
1514
		$ddns_zones = array();
1515

    
1516
		$ifcfgv6 = $config['interfaces'][$dhcpv6if];
1517

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

    
1533
		$dnscfgv6 = "";
1534

    
1535
		if ($dhcpv6ifconf['domain']) {
1536
			$dnscfgv6 .= "	option domain-name \"{$dhcpv6ifconf['domain']}\";\n";
1537
		}
1538

    
1539
		if ($dhcpv6ifconf['domainsearchlist'] <> "") {
1540
			$dnscfgv6 .= "	option dhcp6.domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpv6ifconf['domainsearchlist'])) . "\";\n";
1541
		}
1542

    
1543
		if (isset($dhcpv6ifconf['ddnsupdate'])) {
1544
			if ($dhcpv6ifconf['ddnsdomain'] <> "") {
1545
				$dnscfgv6 .= "	ddns-domainname \"{$dhcpv6ifconf['ddnsdomain']}\";\n";
1546
			}
1547
			if (empty($dhcpv6ifconf['ddnsclientupdates'])) {
1548
				$ddnsclientupdates = 'allow';
1549
			} else {
1550
				$ddnsclientupdates = $dhcpv6ifconf['ddnsclientupdates'];
1551
			}
1552
			$dnscfgv6 .= "	{$ddnsclientupdates} client-updates;\n";
1553
			$nsupdate = true;
1554
		} else {
1555
			$dnscfgv6 .= "	do-forward-updates false;\n";
1556
		}
1557

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

    
1582
		if (!is_ipaddrv6($ifcfgipv6)) {
1583
			$ifcfgsnv6 = "64";
1584
			$subnetv6 = gen_subnetv6($dhcpv6ifconf['range']['from'], $ifcfgsnv6);
1585
		}
1586

    
1587
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1588

    
1589
		if (isset($dhcpv6ifconf['ddnsupdate']) &&
1590
		    !empty($dhcpv6ifconf['ddnsdomain'])) {
1591
			$newzone = array();
1592
			$newzone['domain-name'] = $dhcpv6ifconf['ddnsdomain'];
1593
			$newzone['dns-servers'] = array($dhcpv6ifconf['ddnsdomainprimary'], $dhcpv6ifconf['ddnsdomainsecondary']);
1594
			$newzone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1595
			$newzone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1596
			$ddns_zones[] = $newzone;
1597
			if (isset($dhcpv6ifconf['ddnsreverse'])) {
1598
				$ptr_zones = get_v6_ptr_zones($subnetv6, $ifcfgsnv6);
1599
				foreach ($ptr_zones as $ptr_zone) {
1600
					$reversezone = array();
1601
					$reversezone['ptr-domain'] = $ptr_zone;
1602
					$reversezone['dns-servers'] = array($dhcpv6ifconf['ddnsdomainprimary'], $dhcpv6ifconf['ddnsdomainsecondary']);
1603
					$reversezone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1604
					$reversezone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1605
					$ddns_zones[] = $reversezone;
1606
				}
1607
			}
1608
		}
1609

    
1610
		$dhcpdv6conf .= " {\n";
1611

    
1612
		$range_from = $dhcpv6ifconf['range']['from'];
1613
		$range_to = $dhcpv6ifconf['range']['to'];
1614
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
1615
			$range_from = merge_ipv6_delegated_prefix($ifcfgipv6, $range_from, $pdlen);
1616
			$range_to = merge_ipv6_delegated_prefix($ifcfgipv6, $range_to, $pdlen);
1617
		}
1618

    
1619
		if (!empty($dhcpv6ifconf['range']['from']) && !empty($dhcpv6ifconf['range']['to'])) {
1620
			$dhcpdv6conf .= "	range6 {$range_from} {$range_to};\n";
1621
		}
1622

    
1623
		$dhcpdv6conf .= $dnscfgv6;
1624

    
1625
		if (is_ipaddrv6($dhcpv6ifconf['prefixrange']['from']) && is_ipaddrv6($dhcpv6ifconf['prefixrange']['to'])) {
1626
			$dhcpdv6conf .= "	prefix6 {$dhcpv6ifconf['prefixrange']['from']} {$dhcpv6ifconf['prefixrange']['to']} /{$dhcpv6ifconf['prefixrange']['prefixlength']};\n";
1627
		}
1628
		if (is_ipaddrv6($dhcpv6ifconf['dns6ip'])) {
1629
			$dns6ip = $dhcpv6ifconf['dns6ip'];
1630
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1631
			    Net_IPv6::isInNetmask($dns6ip, '::', $pdlen)) {
1632
				$dns6ip = merge_ipv6_delegated_prefix($ifcfgipv6, $dns6ip, $pdlen);
1633
			}
1634
			$dhcpdv6conf .= "	option dhcp6.name-servers {$dns6ip};\n";
1635
		}
1636
		// default-lease-time
1637
		if ($dhcpv6ifconf['defaultleasetime']) {
1638
			$dhcpdv6conf .= "	default-lease-time {$dhcpv6ifconf['defaultleasetime']};\n";
1639
		}
1640

    
1641
		// max-lease-time
1642
		if ($dhcpv6ifconf['maxleasetime']) {
1643
			$dhcpdv6conf .= "	max-lease-time {$dhcpv6ifconf['maxleasetime']};\n";
1644
		}
1645

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

    
1670
		// Handle option, number rowhelper values
1671
		$dhcpdv6conf .= "\n";
1672
		if (isset($dhcpv6ifconf['numberoptions']['item']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1673
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1674
				$itemv6_value = base64_decode($itemv6['value']);
1675
				$dhcpdv6conf .= "	option custom-{$dhcpv6if}-{$itemv6idx} \"{$itemv6_value}\";\n";
1676
			}
1677
		}
1678

    
1679
		// ldap-server
1680
		if ($dhcpv6ifconf['ldap'] <> "") {
1681
			$ldapserver = $dhcpv6ifconf['ldap'];
1682
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1683
			    Net_IPv6::isInNetmask($ldapserver, '::', $pdlen)) {
1684
				$ldapserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ldapserver, $pdlen);
1685
			}
1686
			$dhcpdv6conf .= "	option ldap-server \"{$ldapserver}\";\n";
1687
		}
1688

    
1689
		// net boot information
1690
		if (isset($dhcpv6ifconf['netboot'])) {
1691
			if (!empty($dhcpv6ifconf['bootfile_url'])) {
1692
				$dhcpdv6conf .= "	option dhcp6.bootfile-url \"{$dhcpv6ifconf['bootfile_url']}\";\n";
1693
			}
1694
		}
1695

    
1696
		$dhcpdv6conf .= "}\n";
1697

    
1698
		/* add static mappings */
1699
		/* Needs to use DUID */
1700
		if (is_array($dhcpv6ifconf['staticmap'])) {
1701
			$i = 0;
1702
			foreach ($dhcpv6ifconf['staticmap'] as $sm) {
1703
				$dhcpdv6conf .= <<<EOD
1704
host s_{$dhcpv6if}_{$i} {
1705
	host-identifier option dhcp6.client-id {$sm['duid']};
1706

    
1707
EOD;
1708
				if ($sm['ipaddrv6']) {
1709
					$ipaddrv6 = $sm['ipaddrv6'];
1710
					if ($ifcfgv6['ipaddrv6'] == 'track6') {
1711
						$ipaddrv6 = merge_ipv6_delegated_prefix($ifcfgipv6, $ipaddrv6, $pdlen);
1712
					}
1713
					$dhcpdv6conf .= "	fixed-address6 {$ipaddrv6};\n";
1714
				}
1715

    
1716
				if ($sm['hostname']) {
1717
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1718
					$dhhostname = str_replace(".", "_", $dhhostname);
1719
					$dhcpdv6conf .= "	option host-name {$dhhostname};\n";
1720
					if (isset($dhcpv6ifconf['ddnsupdate']) &&
1721
					    isset($dhcpv6ifconf['ddnsforcehostname'])) {
1722
						$dhcpdv6conf .= "	ddns-hostname \"{$dhhostname}\";\n";
1723
					}
1724
				}
1725
				if ($sm['filename']) {
1726
					$dhcpdv6conf .= "	filename \"{$sm['filename']}\";\n";
1727
				}
1728

    
1729
				if ($sm['rootpath']) {
1730
					$dhcpdv6conf .= "	option root-path \"{$sm['rootpath']}\";\n";
1731
				}
1732

    
1733
				$dhcpdv6conf .= "}\n";
1734
				$i++;
1735
			}
1736
		}
1737

    
1738
		if ($dhcpv6ifconf['ddnsdomain']) {
1739
			$dhcpdv6conf .= dhcpdkey($dhcpv6ifconf);
1740
			$dhcpdv6conf .= dhcpdzones($ddns_zones);
1741
		}
1742

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

    
1761
	if ($nsupdate) {
1762
		$dhcpdv6conf .= "ddns-update-style interim;\n";
1763
		$dhcpdv6conf .= "update-static-leases on;\n";
1764
	} else {
1765
		$dhcpdv6conf .= "ddns-update-style none;\n";
1766
	}
1767

    
1768
	/* write dhcpdv6.conf */
1769
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf", $dhcpdv6conf)) {
1770
		log_error("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1771
		if (platform_booting()) {
1772
			printf("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1773
		}
1774
		unset($dhcpdv6conf);
1775
		return 1;
1776
	}
1777
	unset($dhcpdv6conf);
1778

    
1779
	/* create an empty leases v6 database */
1780
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases")) {
1781
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1782
	}
1783

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

    
1788
	/* fire up dhcpd in a chroot */
1789
	if (count($dhcpdv6ifs) > 0) {
1790
		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 " .
1791
			join(" ", $dhcpdv6ifs));
1792
		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");
1793
	}
1794
	if (platform_booting()) {
1795
		print gettext("done.") . "\n";
1796
	}
1797

    
1798
	return 0;
1799
}
1800

    
1801
function services_igmpproxy_configure() {
1802
	global $config, $g;
1803

    
1804
	/* kill any running igmpproxy */
1805
	killbyname("igmpproxy");
1806

    
1807
	if (!isset($config['igmpproxy']['enable'])) {
1808
		return 0;
1809
	}
1810
	if (!is_array($config['igmpproxy']['igmpentry']) || (count($config['igmpproxy']['igmpentry']) == 0)) {
1811
		return 1;
1812
	}
1813

    
1814
	$iflist = get_configured_interface_list();
1815

    
1816
	$igmpconf = <<<EOD
1817

    
1818
##------------------------------------------------------
1819
## Enable Quickleave mode (Sends Leave instantly)
1820
##------------------------------------------------------
1821
quickleave
1822

    
1823
EOD;
1824

    
1825
	foreach ($config['igmpproxy']['igmpentry'] as $igmpcf) {
1826
		unset($iflist[$igmpcf['ifname']]);
1827
		$realif = get_real_interface($igmpcf['ifname']);
1828
		if (empty($igmpcf['threshold'])) {
1829
			$threshld = 1;
1830
		} else {
1831
			$threshld = $igmpcf['threshold'];
1832
		}
1833
		$igmpconf .= "phyint {$realif} {$igmpcf['type']} ratelimit 0 threshold {$threshld}\n";
1834

    
1835
		if ($igmpcf['address'] <> "") {
1836
			$item = explode(" ", $igmpcf['address']);
1837
			foreach ($item as $iww) {
1838
				$igmpconf .= "altnet {$iww}\n";
1839
			}
1840
		}
1841
		$igmpconf .= "\n";
1842
	}
1843
	foreach ($iflist as $ifn) {
1844
		$realif = get_real_interface($ifn);
1845
		$igmpconf .= "phyint {$realif} disabled\n";
1846
	}
1847
	$igmpconf .= "\n";
1848

    
1849
	$igmpfl = fopen($g['varetc_path'] . "/igmpproxy.conf", "w");
1850
	if (!$igmpfl) {
1851
		log_error(gettext("Could not write Igmpproxy configuration file!"));
1852
		return;
1853
	}
1854
	fwrite($igmpfl, $igmpconf);
1855
	fclose($igmpfl);
1856
	unset($igmpconf);
1857

    
1858
	if (isset($config['syslog']['igmpxverbose'])) {
1859
		mwexec_bg("/usr/local/sbin/igmpproxy -v {$g['varetc_path']}/igmpproxy.conf");
1860
	} else {
1861
		mwexec_bg("/usr/local/sbin/igmpproxy {$g['varetc_path']}/igmpproxy.conf");
1862
	}
1863

    
1864
	log_error(gettext("Started IGMP proxy service."));
1865

    
1866
	return 0;
1867
}
1868

    
1869
function services_dhcrelay_configure() {
1870
	global $config, $g;
1871

    
1872
	if (isset($config['system']['developerspew'])) {
1873
		$mt = microtime();
1874
		echo "services_dhcrelay_configure() being called $mt\n";
1875
	}
1876

    
1877
	/* kill any running dhcrelay */
1878
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
1879

    
1880
	init_config_arr(array('dhcrelay'));
1881
	$dhcrelaycfg = &$config['dhcrelay'];
1882

    
1883
	/* DHCPRelay enabled on any interfaces? */
1884
	if (!isset($dhcrelaycfg['enable'])) {
1885
		return 0;
1886
	}
1887

    
1888
	if (platform_booting()) {
1889
		echo gettext("Starting DHCP relay service...");
1890
	} else {
1891
		sleep(1);
1892
	}
1893

    
1894
	$iflist = get_configured_interface_list();
1895

    
1896
	$dhcrelayifs = array();
1897
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1898
	foreach ($dhcifaces as $dhcrelayif) {
1899
		if (!isset($iflist[$dhcrelayif])) {
1900
			continue;
1901
		}
1902

    
1903
		if (get_interface_ip($dhcrelayif)) {
1904
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1905
		}
1906
	}
1907
	$dhcrelayifs = array_unique($dhcrelayifs);
1908

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

    
1927
	/* Check for relays in the same subnet as clients so they can bind for
1928
	 * either direction (up or down) */
1929
	$srvrelayifs = array_intersect($dhcrelayifs, $srvifaces);
1930

    
1931
	/* The server interface(s) should not be in this list */
1932
	$dhcrelayifs = array_diff($dhcrelayifs, $srvifaces);
1933

    
1934
	/* Remove the dual-role interfaces from up and down lists */
1935
	$srvifaces = array_diff($srvifaces, $srvrelayifs);
1936
	$dhcrelayifs = array_diff($dhcrelayifs, $srvrelayifs);
1937

    
1938
	/* fire up dhcrelay */
1939
	if (empty($dhcrelayifs) && empty($srvrelayifs)) {
1940
		log_error(gettext("No suitable downstream interfaces found for running dhcrelay!"));
1941
		return; /* XXX */
1942
	}
1943
	if (empty($srvifaces) && empty($srvrelayifs)) {
1944
		log_error(gettext("No suitable upstream interfaces found for running dhcrelay!"));
1945
		return; /* XXX */
1946
	}
1947

    
1948
	$cmd = "/usr/local/sbin/dhcrelay";
1949

    
1950
	if (!empty($dhcrelayifs)) {
1951
		$cmd .= " -id " . implode(" -id ", $dhcrelayifs);
1952
	}
1953
	if (!empty($srvifaces)) {
1954
		$cmd .= " -iu " . implode(" -iu ", $srvifaces);
1955
	}
1956
	if (!empty($srvrelayifs)) {
1957
		$cmd .= " -i " . implode(" -i ", $srvrelayifs);
1958
	}
1959

    
1960
	if (isset($dhcrelaycfg['agentoption'])) {
1961
		$cmd .= " -a -m replace";
1962
	}
1963

    
1964
	$cmd .= " " . implode(" ", $srvips);
1965
	mwexec($cmd);
1966
	unset($cmd);
1967

    
1968
	return 0;
1969
}
1970

    
1971
function services_dhcrelay6_configure() {
1972
	global $config, $g;
1973

    
1974
	if (isset($config['system']['developerspew'])) {
1975
		$mt = microtime();
1976
		echo "services_dhcrelay6_configure() being called $mt\n";
1977
	}
1978

    
1979
	/* kill any running dhcrelay */
1980
	killbypid("{$g['varrun_path']}/dhcrelay6.pid");
1981

    
1982
	init_config_arr(array('dhcrelay6'));
1983
	$dhcrelaycfg = &$config['dhcrelay6'];
1984

    
1985
	/* DHCPv6 Relay enabled on any interfaces? */
1986
	if (!isset($dhcrelaycfg['enable'])) {
1987
		return 0;
1988
	}
1989

    
1990
	if (platform_booting()) {
1991
		echo gettext("Starting DHCPv6 relay service...");
1992
	} else {
1993
		sleep(1);
1994
	}
1995

    
1996
	$iflist = get_configured_interface_list();
1997

    
1998
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1999
	foreach ($dhcifaces as $dhcrelayif) {
2000
		if (!isset($iflist[$dhcrelayif])) {
2001
			continue;
2002
		}
2003

    
2004
		if (get_interface_ipv6($dhcrelayif)) {
2005
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
2006
		}
2007
	}
2008
	$dhcrelayifs = array_unique($dhcrelayifs);
2009

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

    
2023
	/* fire up dhcrelay */
2024
	if (empty($dhcrelayifs) || empty($srvifaces)) {
2025
		log_error(gettext("No suitable interface found for running dhcrelay -6!"));
2026
		return; /* XXX */
2027
	}
2028

    
2029
	$cmd = "/usr/local/sbin/dhcrelay -6 -pf \"{$g['varrun_path']}/dhcrelay6.pid\"";
2030
	foreach ($dhcrelayifs as $dhcrelayif) {
2031
		$cmd .= " -l {$dhcrelayif}";
2032
	}
2033
	foreach ($srvifaces as $srviface) {
2034
		$cmd .= " -u \"{$srviface}\"";
2035
	}
2036
	mwexec($cmd);
2037
	unset($cmd);
2038

    
2039
	return 0;
2040
}
2041

    
2042
function services_dyndns_configure_client($conf) {
2043

    
2044
	if (!isset($conf['enable'])) {
2045
		return;
2046
	}
2047

    
2048
	/* load up the dyndns.class */
2049
	require_once("dyndns.class");
2050

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

    
2075
function services_dyndns_configure($int = "") {
2076
	global $config, $g;
2077
	if (isset($config['system']['developerspew'])) {
2078
		$mt = microtime();
2079
		echo "services_dyndns_configure() being called $mt\n";
2080
	}
2081

    
2082
	if (isset($config['dyndnses']['dyndns']) && is_array($config['dyndnses']['dyndns'])) {
2083
		$dyndnscfg = $config['dyndnses']['dyndns'];
2084
	} else {
2085
		return 0;
2086
	}
2087
	$gwgroups = return_gateway_groups_array(true);
2088
	if (is_array($dyndnscfg)) {
2089
		if (platform_booting()) {
2090
			echo gettext("Starting DynDNS clients...");
2091
		}
2092

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

    
2127
		if (platform_booting()) {
2128
			echo gettext("done.") . "\n";
2129
		}
2130
	}
2131

    
2132
	return 0;
2133
}
2134

    
2135
function dyndnsCheckIP($int) {
2136
	global $config, $factory_default_checkipservice;
2137
	$ip_address = get_interface_ip($int);
2138
	if (is_private_ip($ip_address)) {
2139
		$gateways_status = return_gateways_status(true);
2140
		// If the gateway for this interface is down, then the external check cannot work.
2141
		// Avoid the long wait for the external check to timeout.
2142
		if (stristr($gateways_status[$config['interfaces'][$int]['gateway']]['status'], "down")) {
2143
			return "down";
2144
		}
2145

    
2146
		// Append the factory default check IP service to the list (if not disabled).
2147
		if (!isset($config['checkipservices']['disable_factory_default'])) {
2148
			if (!is_array($config['checkipservices'])) {
2149
				$config['checkipservices'] = array();
2150
			}
2151
			if (!is_array($config['checkipservices']['checkipservice'])) {
2152
				$config['checkipservices']['checkipservice'] = array();
2153
			}
2154
			$config['checkipservices']['checkipservice'][] = $factory_default_checkipservice;
2155
		}
2156

    
2157
		// Use the first enabled check IP service as the default.
2158
		if (is_array($config['checkipservices']['checkipservice'])) {
2159
			foreach ($config['checkipservices']['checkipservice'] as $i => $checkipservice) {
2160
				if (isset($checkipservice['enable'])) {
2161
					$url = $checkipservice['url'];
2162
					$username = $checkipservice['username'];
2163
					$password = $checkipservice['password'];
2164
					$verifysslpeer = isset($checkipservice['verifysslpeer']);
2165
					break;
2166
				}
2167
			}
2168
		}
2169

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

    
2189
function services_dnsmasq_configure($restart_dhcp = true) {
2190
	global $config, $g;
2191
	$return = 0;
2192

    
2193
	// hard coded args: will be removed to avoid duplication if specified in custom_options
2194
	$standard_args = array(
2195
		"dns-forward-max" => "--dns-forward-max=5000",
2196
		"cache-size" => "--cache-size=10000",
2197
		"local-ttl" => "--local-ttl=1"
2198
	);
2199

    
2200

    
2201
	if (isset($config['system']['developerspew'])) {
2202
		$mt = microtime();
2203
		echo "services_dnsmasq_configure() being called $mt\n";
2204
	}
2205

    
2206
	/* kill any running dnsmasq */
2207
	if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) {
2208
		sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
2209
	}
2210

    
2211
	if (isset($config['dnsmasq']['enable'])) {
2212

    
2213
		if (platform_booting()) {
2214
			echo gettext("Starting DNS forwarder...");
2215
		} else {
2216
			sleep(1);
2217
		}
2218

    
2219
		/* generate hosts file */
2220
		if (system_hosts_generate() != 0) {
2221
			$return = 1;
2222
		}
2223

    
2224
		$args = "";
2225

    
2226
		if (isset($config['dnsmasq']['regdhcp'])) {
2227
			$args .= " --dhcp-hostsfile={$g['etc_path']}/hosts ";
2228
		}
2229

    
2230
		/* Setup listen port, if non-default */
2231
		if (is_port($config['dnsmasq']['port'])) {
2232
			$args .= " --port={$config['dnsmasq']['port']} ";
2233
		}
2234

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

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

    
2275
			// Build an array of domain overrides to help in checking for matches.
2276
			$override_a = array();
2277
			if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2278
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2279
					$override_a[$override['domain']] = "y";
2280
				}
2281
			}
2282

    
2283
			// Build an array of the private reverse lookup domain names
2284
			$reverse_domain_a = array("10.in-addr.arpa", "168.192.in-addr.arpa");
2285
			// Unfortunately the 172.16.0.0/12 range does not map nicely to the in-addr.arpa scheme.
2286
			for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) {
2287
				$reverse_domain_a[] = "$subnet_num.172.in-addr.arpa";
2288
			}
2289

    
2290
			// Set the --server parameter to nowhere for each reverse domain name that was not specifically specified in a domain override.
2291
			foreach ($reverse_domain_a as $reverse_domain) {
2292
				if (!isset($override_a[$reverse_domain])) {
2293
					$args .= " --server=/$reverse_domain/ ";
2294
				}
2295
			}
2296
			unset($override_a);
2297
			unset($reverse_domain_a);
2298
		}
2299

    
2300
		/* Setup forwarded domains */
2301
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2302
			foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2303
				if ($override['ip'] == "!") {
2304
					$override[ip] = "";
2305
				}
2306
				$args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
2307
			}
2308
		}
2309

    
2310
		/* Allow DNS Rebind for forwarded domains */
2311
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2312
			if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2313
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2314
					$args .= ' --rebind-domain-ok=/' . $override['domain'] . '/ ';
2315
				}
2316
			}
2317
		}
2318

    
2319
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2320
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2321
		}
2322

    
2323
		if (isset($config['dnsmasq']['strict_order'])) {
2324
			$args .= " --strict-order ";
2325
		}
2326

    
2327
		if (isset($config['dnsmasq']['domain_needed'])) {
2328
			$args .= " --domain-needed ";
2329
		}
2330

    
2331
		if ($config['dnsmasq']['custom_options']) {
2332
			foreach (preg_split('/\s+/', $config['dnsmasq']['custom_options']) as $c) {
2333
				$args .= " " . escapeshellarg("--{$c}");
2334
				$p = explode('=', $c);
2335
				if (array_key_exists($p[0], $standard_args)) {
2336
					unset($standard_args[$p[0]]);
2337
				}
2338
			}
2339
		}
2340
		$args .= ' ' . implode(' ', array_values($standard_args));
2341

    
2342
		/* run dnsmasq. Use "-C /dev/null" since we use command line args only (Issue #6730) */
2343
		$cmd = "/usr/local/sbin/dnsmasq --all-servers -C /dev/null {$dns_rebind} {$args}";
2344
		//log_error("dnsmasq command: {$cmd}");
2345
		mwexec_bg($cmd);
2346
		unset($args);
2347

    
2348
		system_dhcpleases_configure();
2349

    
2350
		if (platform_booting()) {
2351
			echo gettext("done.") . "\n";
2352
		}
2353
	}
2354

    
2355
	if (!platform_booting() && $restart_dhcp) {
2356
		if (services_dhcpd_configure() != 0) {
2357
			$return = 1;
2358
		}
2359
	}
2360

    
2361
	return $return;
2362
}
2363

    
2364
function services_unbound_configure($restart_dhcp = true) {
2365
	global $config, $g;
2366
	$return = 0;
2367

    
2368
	if (isset($config['system']['developerspew'])) {
2369
		$mt = microtime();
2370
		echo "services_unbound_configure() being called $mt\n";
2371
	}
2372

    
2373
	if (isset($config['unbound']['enable'])) {
2374
		require_once('/etc/inc/unbound.inc');
2375

    
2376
		/* Stop Unbound using TERM */
2377
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2378
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
2379
		}
2380

    
2381
		/* If unbound is still running, wait up to 30 seconds for it to terminate. */
2382
		for ($i=1; $i <= 30; $i++) {
2383
			if (is_process_running('unbound')) {
2384
				sleep(1);
2385
			}
2386
		}
2387

    
2388
		$python_mode = false;
2389
		if (isset($config['unbound']['python']) && !empty($config['unbound']['python_script'])) {
2390
			$python_mode = true;
2391
		}
2392

    
2393
		/* Include any additional functions as defined by python script include file */
2394
		if (file_exists("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc")) {
2395
			exec("/usr/local/bin/php -l " . escapeshellarg("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc")
2396
				. " 2>&1", $py_output, $py_retval);
2397
			if ($py_retval == 0) {
2398
				require_once("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc");
2399
			}
2400
		}
2401

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

    
2418
				// Add DNS Resolver python integration
2419
				if (empty($validate)) {
2420
					if (!is_dir("{$g['unbound_chroot_path']}{$base_folder}{$dir}")) {
2421
						safe_mkdir("{$g['unbound_chroot_path']}{$base_folder}{$dir}");
2422
					}
2423
					$output = $retval = '';
2424
					exec("/sbin/mount_nullfs -o ro " . escapeshellarg("/usr/local{$dir}") . ' '
2425
					    . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir}") . " 2>&1", $output, $retval);
2426

    
2427
					// Disable Unbound python on mount failure
2428
					if ($retval != 0) {
2429
						$config['unbound']['python'] = '';
2430
						$log_msg = "[Unbound-pymod]: Disabling Unbound python due to failed mount";
2431
						write_config($log_msg);
2432
						log_error($log_msg);
2433
					}
2434
				}
2435
			}
2436

    
2437
			// Remove DNS Resolver python integration
2438
			elseif (!empty($validate)) {
2439
				exec("/sbin/umount -t nullfs " . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir}") . " 2>&1", $output, $retval);
2440
				if ($retval == 0) {
2441
					foreach (array( "/usr/local{$dir}", '/usr/local', '/usr') as $folder) {
2442
						if (!empty($g['unbound_chroot_path']) && $g['unbound_chroot_path'] != '/' && is_dir("{$g['unbound_chroot_path']}{$folder}")) {
2443
							@rmdir(escapeshellarg("{$g['unbound_chroot_path']}{$folder}"));
2444
						}
2445

    
2446
						// Delete remaining subfolders on next loop
2447
						if ($dir == '/bin') {
2448
							break;
2449
						}
2450
					}
2451
				}
2452
				else {
2453
					log_error("[Unbound-pymod]: Failed to unmount!");
2454
				}
2455
			}
2456
		}
2457

    
2458
		if (platform_booting()) {
2459
			echo gettext("Starting DNS Resolver...");
2460
		} else {
2461
			sleep(1);
2462
		}
2463

    
2464
		/* generate hosts file */
2465
		if (system_hosts_generate() != 0) {
2466
			$return = 1;
2467
		}
2468

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

    
2486
		sync_unbound_service();
2487
		if (platform_booting()) {
2488
			log_error(gettext("sync unbound done."));
2489
			echo gettext("done.") . "\n";
2490
		}
2491

    
2492
		system_dhcpleases_configure();
2493
	} else {
2494
		/* kill Unbound since it should not be enabled */
2495
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2496
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "KILL");
2497
		}
2498
	}
2499

    
2500
	if (!platform_booting() && $restart_dhcp) {
2501
		if (services_dhcpd_configure() != 0) {
2502
			$return = 1;
2503
		}
2504
	}
2505

    
2506
	return $return;
2507
}
2508

    
2509
function services_snmpd_configure() {
2510
	global $config, $g;
2511
	if (isset($config['system']['developerspew'])) {
2512
		$mt = microtime();
2513
		echo "services_snmpd_configure() being called $mt\n";
2514
	}
2515

    
2516
	/* kill any running snmpd */
2517
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
2518
	sleep(2);
2519
	if (is_process_running("bsnmpd")) {
2520
		mwexec("/usr/bin/killall bsnmpd", true);
2521
	}
2522

    
2523
	if (isset($config['snmpd']['enable'])) {
2524

    
2525
		if (platform_booting()) {
2526
			echo gettext("Starting SNMP daemon... ");
2527
		}
2528

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

    
2534
		/* generate snmpd.conf */
2535
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
2536
		if (!$fd) {
2537
			printf(gettext("Error: cannot open snmpd.conf in services_snmpd_configure().%s"), "\n");
2538
			return 1;
2539
		}
2540

    
2541

    
2542
		$snmpdconf = <<<EOD
2543
location := "{$config['snmpd']['syslocation']}"
2544
contact := "{$config['snmpd']['syscontact']}"
2545
read := "{$config['snmpd']['rocommunity']}"
2546

    
2547
EOD;
2548

    
2549
/* No docs on what write strings do there so disable for now.
2550
		if (isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])) {
2551
			$snmpdconf .= <<<EOD
2552
# write string
2553
write := "{$config['snmpd']['rwcommunity']}"
2554

    
2555
EOD;
2556
		}
2557
*/
2558

    
2559

    
2560
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2561
			$snmpdconf .= <<<EOD
2562
# SNMP Trap support.
2563
traphost := {$config['snmpd']['trapserver']}
2564
trapport := {$config['snmpd']['trapserverport']}
2565
trap := "{$config['snmpd']['trapstring']}"
2566

    
2567

    
2568
EOD;
2569
		}
2570

    
2571
		$sysDescr = "{$g['product_name']} {$config['system']['hostname']}.{$config['system']['domain']}" .
2572
			" {$g['product_version_string']} {$g['platform']} " . php_uname("s") .
2573
			" " . php_uname("r") . " " . php_uname("m");
2574

    
2575
		$snmpdconf .= <<<EOD
2576
system := 1     # pfSense
2577
%snmpd
2578
sysDescr			= "{$sysDescr}"
2579
begemotSnmpdDebugDumpPdus       = 2
2580
begemotSnmpdDebugSyslogPri      = 7
2581
begemotSnmpdCommunityString.0.1 = $(read)
2582

    
2583
EOD;
2584

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

    
2590
EOD;
2591
		}
2592
*/
2593

    
2594

    
2595
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2596
			$snmpdconf .= <<<EOD
2597
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
2598
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
2599
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
2600

    
2601
EOD;
2602
		}
2603

    
2604

    
2605
		$snmpdconf .= <<<EOD
2606
begemotSnmpdCommunityDisable    = 1
2607

    
2608
EOD;
2609

    
2610
		$bind_to_ips = array();
2611
		if (isset($config['snmpd']['bindip'])) {
2612
			foreach (explode(",", $config['snmpd']['bindip']) as $bind_to_ip) {
2613
				if (is_ipaddr($bind_to_ip)) {
2614
					$bind_to_ips[] = $bind_to_ip;
2615
				} else {
2616
					$if = get_real_interface($bind_to_ip);
2617
					if (does_interface_exist($if)) {
2618
						$bindip = get_interface_ip($bind_to_ip);
2619
						if (is_ipaddr($bindip)) {
2620
							$bind_to_ips[] = $bindip;
2621
						}
2622
					}
2623
				}
2624
			}
2625
		}
2626
		if (!count($bind_to_ips)) {
2627
			$bind_to_ips = array("0.0.0.0");
2628
		}
2629

    
2630
		if (is_port($config['snmpd']['pollport'])) {
2631
			foreach ($bind_to_ips as $bind_to_ip) {
2632
				$snmpdconf .= <<<EOD
2633
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
2634

    
2635
EOD;
2636

    
2637
			}
2638
		}
2639

    
2640
		$snmpdconf .= <<<EOD
2641
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
2642
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
2643

    
2644
# These are bsnmp macros not php vars.
2645
sysContact      = $(contact)
2646
sysLocation     = $(location)
2647
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
2648

    
2649
snmpEnableAuthenTraps = 2
2650

    
2651
EOD;
2652

    
2653
		if (is_array($config['snmpd']['modules'])) {
2654
			if (isset($config['snmpd']['modules']['mibii'])) {
2655
			$snmpdconf .= <<<EOD
2656
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
2657

    
2658
EOD;
2659
			}
2660

    
2661
			if (isset($config['snmpd']['modules']['netgraph'])) {
2662
				$snmpdconf .= <<<EOD
2663
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
2664
%netgraph
2665
begemotNgControlNodeName = "snmpd"
2666

    
2667
EOD;
2668
			}
2669

    
2670
			if (isset($config['snmpd']['modules']['pf'])) {
2671
				$snmpdconf .= <<<EOD
2672
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
2673

    
2674
EOD;
2675
			}
2676

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

    
2681
EOD;
2682
			}
2683

    
2684
			if (isset($config['snmpd']['modules']['bridge'])) {
2685
				$snmpdconf .= <<<EOD
2686
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
2687
# config must end with blank line
2688

    
2689
EOD;
2690
			}
2691
			if (isset($config['snmpd']['modules']['ucd'])) {
2692
				$snmpdconf .= <<<EOD
2693
begemotSnmpdModulePath."ucd"     = "/usr/local/lib/snmp_ucd.so"
2694

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

    
2701
EOD;
2702
			}
2703
		}
2704

    
2705
		fwrite($fd, $snmpdconf);
2706
		fclose($fd);
2707
		unset($snmpdconf);
2708

    
2709
		/* run bsnmpd */
2710
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
2711
			" -p {$g['varrun_path']}/snmpd.pid");
2712

    
2713
		if (platform_booting()) {
2714
			echo gettext("done.") . "\n";
2715
		}
2716
	}
2717

    
2718
	return 0;
2719
}
2720

    
2721
function services_dnsupdate_process($int = "", $updatehost = "", $forced = false) {
2722
	global $config, $g;
2723
	if (isset($config['system']['developerspew'])) {
2724
		$mt = microtime();
2725
		echo "services_dnsupdate_process() being called $mt\n";
2726
	}
2727

    
2728
	/* Dynamic DNS updating active? */
2729
	if (!is_array($config['dnsupdates']['dnsupdate'])) {
2730
		return 0;
2731
	}
2732

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

    
2769
		/* determine interface name */
2770
		$if = get_failover_interface($dnsupdate['interface']);
2771

    
2772
		/* Determine address to update and default binding address */
2773
		if (isset($dnsupdate['usepublicip'])) {
2774
			$wanip = dyndnsCheckIP($if);
2775
			$bindipv4 = get_interface_ip($if);
2776
		} else {
2777
			$wanip = get_interface_ip($if);
2778
			$bindipv4 = $wanip;
2779
		}
2780
		if (is_stf_interface($dnsupdate['interface'])) { 
2781
			$wanipv6 = get_interface_ipv6($dnsupdate['interface'] . '_stf');
2782
		} else {
2783
			$wanipv6 = get_interface_ipv6($if);
2784
		}
2785
		$bindipv6 = $wanipv6;
2786

    
2787
		/* Handle non-default interface bindings */
2788
		if ($dnsupdate['updatesource'] == "none") {
2789
			/* When empty, the directive will be omitted. */
2790
			$bindipv4 = "";
2791
			$bindipv6 = "";
2792
		} elseif (!empty($dnsupdate['updatesource'])) {
2793
			/* Find the alternate binding address */
2794
			$bindipv4 = get_interface_ip($dnsupdate['updatesource']);
2795
			if (is_stf_interface($dnsupdate['interface'])) { 
2796
				$bindipv6 = get_interface_ipv6($dnsupdate['updatesource'] . '_stf');
2797
			} else {
2798
				$bindipv6 = get_interface_ipv6($dnsupdate['updatesource']);
2799
			}
2800
		}
2801

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

    
2822
		$cacheFile = $g['conf_path'] .
2823
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2824
		    escapeshellarg($dnsupdate['host']) .
2825
		    "_{$dnsupdate['server']}.cache";
2826
		$cacheFilev6 = $g['conf_path'] .
2827
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2828
		    escapeshellarg($dnsupdate['host']) .
2829
		    "_{$dnsupdate['server']}_v6.cache";
2830
		$currentTime = time();
2831

    
2832
		if (!$wanip && !$wanipv6) {
2833
			continue;
2834
		}
2835

    
2836
		$keyname = $dnsupdate['keyname'];
2837
		/* trailing dot */
2838
		if (substr($keyname, -1) != ".") {
2839
			$keyname .= ".";
2840
		}
2841

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

    
2848
		/* write key file */
2849
		$algorithm = empty($dnsupdate['keyalgorithm']) ? 'hmac-md5' : $dnsupdate['keyalgorithm'];
2850
		$upkey = <<<EOD
2851
key "{$keyname}" {
2852
	algorithm {$algorithm};
2853
	secret "{$dnsupdate['keydata']}";
2854
};
2855

    
2856
EOD;
2857
		@file_put_contents("{$g['varetc_path']}/nsupdatekey{$i}", $upkey);
2858

    
2859
		/* generate update instructions */
2860
		$upinst = "";
2861
		if (!empty($dnsupdate['server'])) {
2862
			$upinst .= "server {$dnsupdate['server']}\n";
2863
		}
2864

    
2865
		if (!empty($dnsupdate['zone'])) {
2866
			$upinst .= "zone {$dnsupdate['zone']}\n";
2867
		}
2868

    
2869
		$cachedipv4 = '';
2870
		$cacheTimev4 = 0;
2871
		if (file_exists($cacheFile)) {
2872
			list($cachedipv4, $cacheTimev4) = explode("|",
2873
			    file_get_contents($cacheFile));
2874
		}
2875
		$cachedipv6 = '';
2876
		$cacheTimev6 = 0;
2877
		if (file_exists($cacheFilev6)) {
2878
			list($cachedipv6, $cacheTimev6) = explode("|",
2879
			    file_get_contents($cacheFilev6));
2880
		}
2881

    
2882
		// 25 Days
2883
		$maxCacheAgeSecs = 25 * 24 * 60 * 60;
2884
		$need_update = false;
2885

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

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

    
2927
		$upinst .= "\n";	/* mind that trailing newline! */
2928

    
2929
		if (!$need_update) {
2930
			continue;
2931
		}
2932

    
2933
		@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}", $upinst);
2934
		unset($upinst);
2935
		/* invoke nsupdate */
2936
		$cmd = "/usr/local/bin/nsupdate -k {$g['varetc_path']}/nsupdatekey{$i}";
2937

    
2938
		if (isset($dnsupdate['usetcp'])) {
2939
			$cmd .= " -v";
2940
		}
2941

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

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

    
2984
	if (!empty($notify_text)) {
2985
		notify_all_remote($notify_text);
2986
	}
2987

    
2988
	return 0;
2989
}
2990

    
2991
/* configure cron service */
2992
function configure_cron() {
2993
	global $g, $config;
2994

    
2995
	/* preserve existing crontab entries */
2996
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2997

    
2998
	for ($i = 0; $i < count($crontab_contents); $i++) {
2999
		$cron_item = &$crontab_contents[$i];
3000
		if (strpos($cron_item, "# pfSense specific crontab entries") !== false) {
3001
			array_splice($crontab_contents, $i - 1);
3002
			break;
3003
		}
3004
	}
3005
	$crontab_contents = implode("\n", $crontab_contents) . "\n";
3006

    
3007

    
3008
	if (is_array($config['cron']['item'])) {
3009
		$crontab_contents .= "#\n";
3010
		$crontab_contents .= "# pfSense specific crontab entries\n";
3011
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
3012
		$crontab_contents .= "#\n";
3013

    
3014
		if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) {
3015
			$http_proxy = $config['system']['proxyurl'];
3016
			if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) {
3017
				$http_proxy .= ':' . $config['system']['proxyport'];
3018
			}
3019
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
3020

    
3021
			if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
3022
				$crontab_contents .= "HTTP_PROXY_AUTH=basic:*:{$config['system']['proxyuser']}:{$config['system']['proxypass']}";
3023
			}
3024
		}
3025

    
3026
		foreach ($config['cron']['item'] as $item) {
3027
			$crontab_contents .= "\n{$item['minute']}\t";
3028
			$crontab_contents .= "{$item['hour']}\t";
3029
			$crontab_contents .= "{$item['mday']}\t";
3030
			$crontab_contents .= "{$item['month']}\t";
3031
			$crontab_contents .= "{$item['wday']}\t";
3032
			$crontab_contents .= "{$item['who']}\t";
3033
			$crontab_contents .= "{$item['command']}";
3034
		}
3035

    
3036
		$crontab_contents .= "\n#\n";
3037
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
3038
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
3039
		$crontab_contents .= "#\n\n";
3040
	}
3041

    
3042
	/* please maintain the newline at the end of file */
3043
	file_put_contents("/etc/crontab", $crontab_contents);
3044
	unset($crontab_contents);
3045

    
3046
	/* make sure that cron is running and start it if it got killed somehow */
3047
	if (!is_process_running("cron")) {
3048
		exec("cd /tmp && /usr/sbin/cron -s 2>/dev/null");
3049
	} else {
3050
	/* do a HUP kill to force sync changes */
3051
		sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP");
3052
	}
3053

    
3054
}
3055

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

    
3080
function upnp_start() {
3081
	global $config;
3082

    
3083
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
3084
		return;
3085
	}
3086

    
3087
	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
3088
		echo gettext("Starting UPnP service... ");
3089
		require_once('/usr/local/pkg/miniupnpd.inc');
3090
		sync_package_miniupnpd();
3091
		echo "done.\n";
3092
	}
3093
}
3094

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

    
3098
	$is_installed = false;
3099
	$cron_changed = true;
3100
	$change_message = "";
3101

    
3102
	if (!is_array($config['cron'])) {
3103
		$config['cron'] = array();
3104
	}
3105
	if (!is_array($config['cron']['item'])) {
3106
		$config['cron']['item'] = array();
3107
	}
3108

    
3109
	$x = 0;
3110
	foreach ($config['cron']['item'] as $item) {
3111
		if (strstr($item['command'], $command)) {
3112
			$is_installed = true;
3113
			break;
3114
		}
3115
		$x++;
3116
	}
3117

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

    
3147
	if ($cron_changed) {
3148
		/* Optionally write the configuration if this function made changes.
3149
		 * Performing a write_config() in this way can have unintended side effects. See #7146
3150
		 * Base system instances of this function do not need to write, packages may.
3151
		 */
3152
		if ($write_config) {
3153
			write_config(sprintf(gettext($change_message), $command));
3154
		}
3155
		configure_cron();
3156
	}
3157
}
3158

    
3159
?>
(46-46/61)