Project

General

Profile

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

    
28

    
29
define('DYNDNS_PROVIDER_VALUES', 'all-inkl azure azurev6 citynetwork cloudflare cloudflare-v6 cloudns custom custom-v6 digitalocean digitalocean-v6 dnsexit dnsimple dnsmadeeasy dnsomatic domeneshop domeneshop-v6 dreamhost dreamhost-v6 duiadns duiadns-v6 dyndns dyndns-custom dyndns-static dyns dynv6 dynv6-v6 easydns easydns-v6 eurodns freedns freedns-v6 freedns2 freedns2-v6 glesys gandi-livedns gandi-livedns-v6 godaddy godaddy-v6 googledomains gratisdns he-net he-net-v6 he-net-tunnelbroker hover linode linode-v6 loopia mythicbeasts mythicbeasts-v6 namecheap noip noip-v6 noip-free noip-free-v6 ods opendns ovh-dynhost route53 route53-v6 selfhost spdyn spdyn-v6 zoneedit');
30
define('DYNDNS_PROVIDER_DESCRIPTIONS', 'All-Inkl.com,Azure DNS,Azure DNS (v6),City Network,Cloudflare,Cloudflare (v6),ClouDNS,Custom,Custom (v6),DigitalOcean,DigitalOcean (v6),DNSexit,DNSimple,DNS Made Easy,DNS-O-Matic,Domeneshop,Domeneshop (v6),DreamHost,Dreamhost (v6),DuiaDns.net,DuiaDns.net (v6),DynDNS (dynamic),DynDNS (custom),DynDNS (static),DyNS,Dynv6,Dynv6 (v6),easyDNS,easyDNS (v6),Euro Dns,freeDNS,freeDNS (v6),freeDNS API Version 2, freeDNS API Version 2 (v6),GleSYS,Gandi Live DNS,Gandi Live DNS (v6),GoDaddy,GoDaddy (v6),Google Domains,GratisDNS,HE.net,HE.net (v6),HE.net Tunnelbroker,Hover,Linode,Linode (v6),Loopia,Mythic Beasts,Mythic Beasts (v6),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
		$rasrcaddr = "";
81
		/* check if binding to CARP IP */
82
		if (!empty($dhcpv6ifconf['rainterface'])) {
83
			if (strstr($dhcpv6ifconf['rainterface'], "_vip")) {
84
				if (is_linklocal(get_configured_vip_ipv6($dhcpv6ifconf['rainterface']))) {
85
					$rasrcaddr = get_configured_vip_ipv6($dhcpv6ifconf['rainterface']);
86
				}
87
				elseif (get_carp_interface_status($dhcpv6ifconf['rainterface']) == "MASTER") {
88
					$dhcpv6if = $dhcpv6ifconf['rainterface'];
89
					$racarpif = true;
90
				} else {
91
					continue;
92
				}
93
			}
94
		}
95

    
96
		$realif = get_real_interface($dhcpv6if, "inet6");
97

    
98
		if (isset($radvdifs[$realif])) {
99
			continue;
100
		}
101

    
102
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
103
		if (!is_ipaddrv6($ifcfgipv6)) {
104
			continue;
105
		}
106

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

    
115
		$radvdconf .= "# Generated for DHCPv6 Server $dhcpv6if\n";
116
		$radvdconf .= "interface {$realif} {\n";
117
		if (strstr($realif, "ovpn")) {
118
			$radvdconf .= "\tUnicastOnly on;\n";
119
		}
120
		$radvdconf .= "\tAdvSendAdvert on;\n";
121

    
122
		if ($rasrcaddr) {
123
			$radvdconf .= "\tAdvRASrcAddress {\n";
124
			$radvdconf .= "\t\t{$rasrcaddr};\n";
125
			$radvdconf .= "\t};\n";
126
		}
127

    
128
		if (is_numericint($dhcpv6ifconf['raminrtradvinterval'])) {
129
			$radvdconf .= "\tMinRtrAdvInterval {$dhcpv6ifconf['raminrtradvinterval']};\n";
130
		} else {
131
			$radvdconf .= "\tMinRtrAdvInterval 5;\n";
132
		}
133

    
134
		if (is_numericint($dhcpv6ifconf['ramaxrtradvinterval'])) {
135
			$ramaxrtradvinterval = $dhcpv6ifconf['ramaxrtradvinterval'];
136
		} else {
137
			$ramaxrtradvinterval = 20;
138
		}
139
		$radvdconf .= "\tMaxRtrAdvInterval {$ramaxrtradvinterval};\n";
140
		if (is_numericint($dhcpv6ifconf['raadvdefaultlifetime'])) {
141
			$raadvdefaultlifetime = $dhcpv6ifconf['raadvdefaultlifetime'];
142
		} else {
143
			$raadvdefaultlifetime = $ramaxrtradvinterval * 3;
144
		}
145
		$radvdconf .= "\tAdvDefaultLifetime {$raadvdefaultlifetime};\n";
146

    
147
		$mtu = get_interface_mtu($realif);
148
		if (is_numeric($mtu)) {
149
			$radvdconf .= "\tAdvLinkMTU {$mtu};\n";
150
		} else {
151
			$radvdconf .= "\tAdvLinkMTU 1280;\n";
152
		}
153
		switch ($dhcpv6ifconf['rapriority']) {
154
			case "low":
155
				$radvdconf .= "\tAdvDefaultPreference low;\n";
156
				break;
157
			case "high":
158
				$radvdconf .= "\tAdvDefaultPreference high;\n";
159
				break;
160
			default:
161
				$radvdconf .= "\tAdvDefaultPreference medium;\n";
162
				break;
163
		}
164
		switch ($dhcpv6ifconf['ramode']) {
165
			case "managed":
166
			case "assist":
167
				$radvdconf .= "\tAdvManagedFlag on;\n";
168
				$radvdconf .= "\tAdvOtherConfigFlag on;\n";
169
				break;
170
			case "stateless_dhcp":
171
				$radvdconf .= "\tAdvManagedFlag off;\n";
172
				$radvdconf .= "\tAdvOtherConfigFlag on;\n";
173
				break;
174
		}
175
		$radvdconf .= "\tprefix {$subnetv6}/{$ifcfgsnv6} {\n";
176
		if ($racarpif == true) {
177
			$radvdconf .= "\t\tDeprecatePrefix off;\n";
178
		} else {
179
			$radvdconf .= "\t\tDeprecatePrefix on;\n";
180
		}
181
		switch ($dhcpv6ifconf['ramode']) {
182
			case "managed":
183
				$radvdconf .= "\t\tAdvOnLink on;\n";
184
				$radvdconf .= "\t\tAdvAutonomous off;\n";
185
				break;
186
			case "router":
187
				$radvdconf .= "\t\tAdvOnLink off;\n";
188
				$radvdconf .= "\t\tAdvAutonomous off;\n";
189
				break;
190
			case "stateless_dhcp":
191
			case "assist":
192
				$radvdconf .= "\t\tAdvOnLink on;\n";
193
				$radvdconf .= "\t\tAdvAutonomous on;\n";
194
				break;
195
			case "unmanaged":
196
				$radvdconf .= "\t\tAdvOnLink on;\n";
197
				$radvdconf .= "\t\tAdvAutonomous on;\n";
198
				break;
199
		}
200

    
201
		if (is_numericint($dhcpv6ifconf['ravalidlifetime'])) {
202
		  $radvdconf .= "\t\tAdvValidLifetime {$dhcpv6ifconf['ravalidlifetime']};\n";
203
		} else {
204
		  $radvdconf .= "\t\tAdvValidLifetime 86400;\n";
205
		}
206

    
207
		if (is_numericint($dhcpv6ifconf['rapreferredlifetime'])) {
208
		  $radvdconf .= "\t\tAdvPreferredLifetime {$dhcpv6ifconf['rapreferredlifetime']};\n";
209
		} else {
210
		  $radvdconf .= "\t\tAdvPreferredLifetime 14400;\n";
211
		}
212

    
213
		$radvdconf .= "\t};\n";
214

    
215
		if (is_array($dhcpv6ifconf['subnets']['item'])) {
216
			foreach ($dhcpv6ifconf['subnets']['item'] as $subnet) {
217
				if (is_subnetv6($subnet)) {
218
					$radvdconf .= "\tprefix {$subnet} {\n";
219
					$radvdconf .= "\t\tDeprecatePrefix on;\n";
220
					switch ($dhcpv6ifconf['ramode']) {
221
						case "managed":
222
							$radvdconf .= "\t\tAdvOnLink on;\n";
223
							$radvdconf .= "\t\tAdvAutonomous off;\n";
224
							break;
225
						case "router":
226
							$radvdconf .= "\t\tAdvOnLink off;\n";
227
							$radvdconf .= "\t\tAdvAutonomous off;\n";
228
							break;
229
						case "assist":
230
							$radvdconf .= "\t\tAdvOnLink on;\n";
231
							$radvdconf .= "\t\tAdvAutonomous on;\n";
232
							break;
233
						case "unmanaged":
234
							$radvdconf .= "\t\tAdvOnLink on;\n";
235
							$radvdconf .= "\t\tAdvAutonomous on;\n";
236
							break;
237
					}
238
					$radvdconf .= "\t};\n";
239
				}
240
			}
241
		}
242
		$radvdconf .= "\troute ::/0 {\n";
243
		switch ($dhcpv6ifconf['rapriority']) {
244
			case "low":
245
				$radvdconf .= "\t\tAdvRoutePreference low;\n";
246
				break;
247
			case "high":
248
				$radvdconf .= "\t\tAdvRoutePreference high;\n";
249
				break;
250
			default:
251
				$radvdconf .= "\t\tAdvRoutePreference medium;\n";
252
				break;
253
		}
254
		$radvdconf .= "\t\tRemoveRoute on;\n";
255
		$radvdconf .= "\t};\n";
256

    
257
		/* add DNS servers */
258
		if ($dhcpv6ifconf['radvd-dns'] != 'disabled') {
259
			$dnslist = array();
260
			if (isset($dhcpv6ifconf['rasamednsasdhcp6']) && is_array($dhcpv6ifconf['dnsserver']) && !empty($dhcpv6ifconf['dnsserver'])) {
261
				foreach ($dhcpv6ifconf['dnsserver'] as $server) {
262
					if (is_ipaddrv6($server)) {
263
						$dnslist[] = $server;
264
					}
265
				}
266
			} elseif (!isset($dhcpv6ifconf['rasamednsasdhcp6']) && isset($dhcpv6ifconf['radnsserver']) && is_array($dhcpv6ifconf['radnsserver'])) {
267
				foreach ($dhcpv6ifconf['radnsserver'] as $server) {
268
					if (is_ipaddrv6($server)) {
269
						$dnslist[] = $server;
270
					}
271
				}
272
			} elseif (isset($config['dnsmasq']['enable']) || isset($config['unbound']['enable'])) {
273
				$dnslist[] = get_interface_ipv6($realif);
274
			} elseif (is_array($config['system']['dnsserver']) && !empty($config['system']['dnsserver'])) {
275
				foreach ($config['system']['dnsserver'] as $server) {
276
					if (is_ipaddrv6($server)) {
277
						$dnslist[] = $server;
278
					}
279
				}
280
			}
281
			if (count($dnslist) > 0) {
282
				$dnsstring = implode(" ", $dnslist);
283
				if ($dnsstring <> "") {
284
					/* 
285
					 * The value of Lifetime SHOULD by default be at least
286
					 * 3 * MaxRtrAdvInterval, where MaxRtrAdvInterval is the
287
					 * maximum RA interval as defined in [RFC4861].
288
					 * see https://redmine.pfsense.org/issues/11105 
289
					 */
290
					$raadvrdnsslifetime = $ramaxrtradvinterval * 3;
291
					$radvdconf .= "\tRDNSS {$dnsstring} {\n";
292
					$radvdconf .= "\t\tAdvRDNSSLifetime {$raadvrdnsslifetime};\n";
293
					$radvdconf .= "\t};\n";
294
				}
295
			}
296

    
297
			$searchlist = array();
298
			$domainsearchlist = explode(';', $dhcpv6ifconf['radomainsearchlist']);
299
			foreach ($domainsearchlist as $sd) {
300
				$sd = trim($sd);
301
				if (is_hostname($sd)) {
302
					$searchlist[] = $sd;
303
				}
304
			}
305
			if (count($searchlist) > 0) {
306
				$searchliststring = trim(implode(" ", $searchlist));
307
			}
308
			if (!empty($dhcpv6ifconf['domain'])) {
309
				$radvdconf .= "\tDNSSL {$dhcpv6ifconf['domain']} {$searchliststring} { };\n";
310
			} elseif (!empty($config['system']['domain'])) {
311
				$radvdconf .= "\tDNSSL {$config['system']['domain']} {$searchliststring} { };\n";
312
			}
313
		}
314
		$radvdconf .= "};\n";
315
	}
316

    
317
	/* handle DHCP-PD prefixes and 6RD dynamic interfaces */
318
	foreach ($Iflist as $if => $ifdescr) {
319
		if (!isset($config['interfaces'][$if]['track6-interface']) ||
320
		    !isset($config['interfaces'][$if]['ipaddrv6']) ||
321
		    $config['interfaces'][$if]['ipaddrv6'] != 'track6') {
322
			continue;
323
		}
324
		if (!isset($config['interfaces'][$if]['enable'])) {
325
			continue;
326
		}
327
		if ($config['dhcpdv6'][$if]['ramode'] == "disabled") {
328
			continue;
329
		}
330
		/* Do not put in the config an interface which is down */
331
		if (isset($blacklist[$if])) {
332
			continue;
333
		}
334
		$trackif = $config['interfaces'][$if]['track6-interface'];
335
		if (empty($config['interfaces'][$trackif])) {
336
			continue;
337
		}
338

    
339
		$realif = get_real_interface($if, "inet6");
340

    
341
		/* prevent duplicate entries, manual overrides */
342
		if (isset($radvdifs[$realif])) {
343
			continue;
344
		}
345

    
346
		$ifcfgipv6 = get_interface_ipv6($if);
347
		if (!is_ipaddrv6($ifcfgipv6)) {
348
			$subnetv6 = "::";
349
			$ifcfgsnv6 = "64";
350
		} else {
351
			$ifcfgsnv6 = get_interface_subnetv6($if);
352
			$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
353
		}
354
		$radvdifs[$realif] = $realif;
355

    
356
		$autotype = $config['interfaces'][$trackif]['ipaddrv6'];
357

    
358
		if ($g['debug']) {
359
			log_error("configuring RA on {$if} for type {$autotype} radvd subnet {$subnetv6}/{$ifcfgsnv6}");
360
		}
361

    
362
		$radvdconf .= "# Generated config for {$autotype} delegation from {$trackif} on {$if}\n";
363
		$radvdconf .= "interface {$realif} {\n";
364
		$radvdconf .= "\tAdvSendAdvert on;\n";
365
		if (is_numericint($dhcpv6ifconf['raminrtradvinterval'])) {
366
			$radvdconf .= "\tMinRtrAdvInterval {$dhcpv6ifconf['raminrtradvinterval']};\n";
367
		} else {
368
			$radvdconf .= "\tMinRtrAdvInterval 5;\n";
369
                }
370
		if (is_numericint($dhcpv6ifconf['ramaxrtradvinterval'])) {
371
			$radvdconf .= "\tMaxRtrAdvInterval {$dhcpv6ifconf['ramaxrtradvinterval']};\n";
372
		} else {
373
			$radvdconf .= "\tMaxRtrAdvInterval 10;\n";
374
		}
375
		$mtu = get_interface_mtu($realif);
376
		if (is_numeric($mtu)) {
377
			$radvdconf .= "\tAdvLinkMTU {$mtu};\n";
378
		} else {
379
			$radvdconf .= "\tAdvLinkMTU 1280;\n";
380
		}
381
		$radvdconf .= "\tAdvOtherConfigFlag on;\n";
382
		$radvdconf .= "\tprefix {$subnetv6}/{$ifcfgsnv6} {\n";
383
		$radvdconf .= "\t\tAdvOnLink on;\n";
384
		$radvdconf .= "\t\tAdvAutonomous on;\n";
385
		$radvdconf .= "\t};\n";
386

    
387
		/* add DNS servers */
388
		if ($dhcpv6ifconf['radvd-dns'] != 'disabled') {
389
			$dnslist = array();
390
			if (isset($config['dnsmasq']['enable']) || isset($config['unbound']['enable'])) {
391
				$dnslist[] = $ifcfgipv6;
392
			} elseif (is_array($config['system']['dnsserver']) && !empty($config['system']['dnsserver'])) {
393
				foreach ($config['system']['dnsserver'] as $server) {
394
					if (is_ipaddrv6($server)) {
395
						$dnslist[] = $server;
396
					}
397
				}
398
			}
399
			if (count($dnslist) > 0) {
400
				$dnsstring = implode(" ", $dnslist);
401
				if (!empty($dnsstring)) {
402
					$radvdconf .= "\tRDNSS {$dnsstring} { };\n";
403
				}
404
			}
405
			if (!empty($config['system']['domain'])) {
406
				$radvdconf .= "\tDNSSL {$config['system']['domain']} { };\n";
407
			}
408
		}
409
		$radvdconf .= "};\n";
410
	}
411

    
412
	/* write radvd.conf */
413
	if (!@file_put_contents("{$g['varetc_path']}/radvd.conf", $radvdconf)) {
414
		log_error(gettext("Error: cannot open radvd.conf in services_radvd_configure()."));
415
		if (platform_booting()) {
416
			printf("Error: cannot open radvd.conf in services_radvd_configure().\n");
417
		}
418
	}
419
	unset($radvdconf);
420

    
421
	if (count($radvdifs) > 0) {
422
		if (isvalidpid("{$g['varrun_path']}/radvd.pid")) {
423
			sigkillbypid("{$g['varrun_path']}/radvd.pid", "HUP");
424
		} else {
425
			mwexec("/usr/local/sbin/radvd -p {$g['varrun_path']}/radvd.pid -C {$g['varetc_path']}/radvd.conf -m syslog");
426
		}
427
	} else {
428
		/* we need to shut down the radvd cleanly, it will send out the prefix
429
		 * information with a lifetime of 0 to notify clients of a (possible) new prefix */
430
		if (isvalidpid("{$g['varrun_path']}/radvd.pid")) {
431
			log_error(gettext("Shutting down Router Advertisment daemon cleanly"));
432
			killbypid("{$g['varrun_path']}/radvd.pid");
433
			@unlink("{$g['varrun_path']}/radvd.pid");
434
		}
435
	}
436
	return 0;
437
}
438

    
439
function services_dhcpd_configure($family = "all", $blacklist = array()) {
440
	global $config, $g;
441

    
442
	$dhcpdconfigurelck = lock("dhcpdconfigure", LOCK_EX);
443

    
444
	/* configure DHCPD chroot once */
445
	$fd = fopen("{$g['tmp_path']}/dhcpd.sh", "w");
446
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}\n");
447
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/dev\n");
448
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/etc\n");
449
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/usr/local/sbin\n");
450
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db\n");
451
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run\n");
452
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/usr\n");
453
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/lib\n");
454
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/run\n");
455
	fwrite($fd, "/usr/sbin/chown -R dhcpd:_dhcp {$g['dhcpd_chroot_path']}/*\n");
456
	fwrite($fd, "/bin/cp -n /lib/libc.so.* {$g['dhcpd_chroot_path']}/lib/\n");
457
	fwrite($fd, "/bin/cp -n /usr/local/sbin/dhcpd {$g['dhcpd_chroot_path']}/usr/local/sbin/\n");
458
	fwrite($fd, "/bin/chmod a+rx {$g['dhcpd_chroot_path']}/usr/local/sbin/dhcpd\n");
459

    
460
	$status = `/sbin/mount | /usr/bin/grep -v grep | /usr/bin/grep "{$g['dhcpd_chroot_path']}/dev"`;
461
	if (!trim($status)) {
462
		fwrite($fd, "/sbin/mount -t devfs devfs {$g['dhcpd_chroot_path']}/dev\n");
463
	}
464
	fclose($fd);
465
	mwexec("/bin/sh {$g['tmp_path']}/dhcpd.sh");
466

    
467
	if ($family == "all" || $family == "inet") {
468
		services_dhcpdv4_configure();
469
	}
470
	if ($family == "all" || $family == "inet6") {
471
		services_dhcpdv6_configure($blacklist);
472
		services_radvd_configure($blacklist);
473
	}
474

    
475
	unlock($dhcpdconfigurelck);
476
}
477

    
478
function services_dhcpdv4_configure() {
479
	global $config, $g;
480
	$need_ddns_updates = false;
481
	$ddns_zones = array();
482

    
483
	if ($g['services_dhcp_server_enable'] == false) {
484
		return;
485
	}
486

    
487
	if (isset($config['system']['developerspew'])) {
488
		$mt = microtime();
489
		echo "services_dhcpdv4_configure($if) being called $mt\n";
490
	}
491

    
492
	/* kill any running dhcpd */
493
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid")) {
494
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid");
495
	}
496

    
497
	/* DHCP enabled on any interfaces? */
498
	if (!is_dhcp_server_enabled()) {
499
		return 0;
500
	}
501

    
502
	$syscfg = $config['system'];
503
	if (!is_array($config['dhcpd'])) {
504
		$config['dhcpd'] = array();
505
	}
506
	$dhcpdcfg = $config['dhcpd'];
507
	$Iflist = get_configured_interface_list();
508

    
509
	/* Only consider DNS servers with IPv4 addresses for the IPv4 DHCP server. */
510
	$dns_arrv4 = array();
511
	if (is_array($syscfg['dnsserver'])) {
512
		foreach ($syscfg['dnsserver'] as $dnsserver) {
513
			if (is_ipaddrv4($dnsserver)) {
514
				$dns_arrv4[] = $dnsserver;
515
			}
516
		}
517
	}
518

    
519
	if (platform_booting()) {
520
		echo gettext("Starting DHCP service...");
521
	} else {
522
		sleep(1);
523
	}
524

    
525
	$custoptions = "";
526
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
527
		if (is_array($dhcpifconf['numberoptions']) && is_array($dhcpifconf['numberoptions']['item'])) {
528
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
529
				if (!empty($item['type'])) {
530
					$itemtype = $item['type'];
531
				} else {
532
					$itemtype = "text";
533
				}
534
				$custoptions .= "option custom-{$dhcpif}-{$itemidx} code {$item['number']} = {$itemtype};\n";
535
			}
536
		}
537
		if (is_array($dhcpifconf['pool'])) {
538
			foreach ($dhcpifconf['pool'] as $poolidx => $poolconf) {
539
				if (is_array($poolconf['numberoptions']) && is_array($poolconf['numberoptions']['item'])) {
540
					foreach ($poolconf['numberoptions']['item'] as $itemidx => $item) {
541
						if (!empty($item['type'])) {
542
							$itemtype = $item['type'];
543
						} else {
544
							$itemtype = "text";
545
						}
546
						$custoptions .= "option custom-{$dhcpif}-{$poolidx}-{$itemidx} code {$item['number']} = {$itemtype};\n";
547
					}
548
				}
549
			}
550
		}
551
		if (is_array($dhcpifconf['staticmap'])) {
552
			$i = 0;
553
			foreach ($dhcpifconf['staticmap'] as $sm) {
554
				if (is_array($sm['numberoptions']) && is_array($sm['numberoptions']['item'])) {
555
					foreach ($sm['numberoptions']['item'] as $itemidx => $item) {
556
						if (!empty($item['type'])) {
557
							$itemtype = $item['type'];
558
						} else {
559
							$itemtype = "text";
560
						}
561
						$custoptions .= "option custom-s_{$dhcpif}_{$i}-{$itemidx} code {$item['number']} = {$itemtype};\n";
562
					}
563
				}
564
				$i++;
565
			}
566
		}
567
	}
568

    
569
	$dhcpdconf = <<<EOD
570

    
571
option domain-name "{$syscfg['domain']}";
572
option ldap-server code 95 = text;
573
option domain-search-list code 119 = text;
574
option arch code 93 = unsigned integer 16; # RFC4578
575
{$custoptions}
576
default-lease-time 7200;
577
max-lease-time 86400;
578
log-facility local7;
579
one-lease-per-client true;
580
deny duplicates;
581
update-conflict-detection false;
582

    
583
EOD;
584

    
585
	/* take these settings from the first DHCP configured interface,
586
	 * see https://redmine.pfsense.org/issues/10270 
587
	 * TODO: Global Settings tab, see https://redmine.pfsense.org/issues/5080 */
588
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
589
		if (!isset($dhcpifconf['disableauthoritative'])) {
590
			$dhcpdconf .= "authoritative;\n";
591
		}
592

    
593
		if (isset($dhcpifconf['alwaysbroadcast'])) {
594
			$dhcpdconf .= "always-broadcast on\n";
595
		}
596

    
597
		// OMAPI Settings
598
		if (isset($dhcpifconf['omapi_port']) && is_numeric($dhcpifconf['omapi_port'])) {
599
			$dhcpdconf .= <<<EOD
600

    
601
key omapi_key {
602
  algorithm {$dhcpifconf['omapi_key_algorithm']};
603
  secret "{$dhcpifconf['omapi_key']}";
604
};
605
omapi-port {$dhcpifconf['omapi_port']};
606
omapi-key omapi_key;
607

    
608
EOD;
609

    
610
		}
611
		break;
612
	}
613

    
614
	$dhcpdifs = array();
615
	$enable_add_routers = false;
616
	$gateways_arr = return_gateways_array();
617
	/* only add a routers line if the system has any IPv4 gateway at all */
618
	/* a static route has a gateway, manually overriding this field always works */
619
	foreach ($gateways_arr as $gwitem) {
620
		if ($gwitem['ipprotocol'] == "inet") {
621
			$enable_add_routers = true;
622
			break;
623
		}
624
	}
625

    
626
	/*    loop through and determine if we need to setup
627
	 *    failover peer "bleh" entries
628
	 */
629
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
630

    
631
		if (!isset($config['interfaces'][$dhcpif]['enable'])) {
632
			continue;
633
		}
634

    
635
		interfaces_staticarp_configure($dhcpif);
636

    
637
		if (!isset($dhcpifconf['enable'])) {
638
			continue;
639
		}
640

    
641
		if ($dhcpifconf['failover_peerip'] <> "") {
642
			$intip = get_interface_ip($dhcpif);
643
			/*
644
			 *    yep, failover peer is defined.
645
			 *    does it match up to a defined vip?
646
			 */
647
			$skew = 110;
648
			if (is_array($config['virtualip']['vip'])) {
649
				foreach ($config['virtualip']['vip'] as $vipent) {
650
					if ($vipent['mode'] != 'carp') {
651
						continue;
652
					}
653
					if ($vipent['interface'] == $dhcpif) {
654
						$carp_nw = gen_subnet($config['interfaces'][$dhcpif]['ipaddr'],
655
						    $config['interfaces'][$dhcpif]['subnet']);
656
						$carp_nw .= "/{$config['interfaces'][$dhcpif]['subnet']}";
657
						if (ip_in_subnet($dhcpifconf['failover_peerip'], $carp_nw)) {
658
							/* this is the interface! */
659
							if (is_numeric($vipent['advskew']) && (intval($vipent['advskew']) < 20)) {
660
								$skew = 0;
661
								break;
662
							}
663
						}
664
					}
665
				}
666
			} else {
667
				log_error(gettext("Warning!  DHCP Failover setup and no CARP virtual IPs defined!"));
668
			}
669
			if ($skew > 10) {
670
				$type = "secondary";
671
				$my_port = "520";
672
				$peer_port = "519";
673
				$dhcpdconf_pri = '';
674
			} else {
675
				$my_port = "519";
676
				$peer_port = "520";
677
				$type = "primary";
678
				$dhcpdconf_pri = "split 128;\n";
679
				$dhcpdconf_pri .= "  mclt 600;\n";
680
			}
681

    
682
			if (is_ipaddrv4($intip)) {
683
				$dhcpdconf .= <<<EOPP
684
failover peer "dhcp_{$dhcpif}" {
685
  {$type};
686
  address {$intip};
687
  port {$my_port};
688
  peer address {$dhcpifconf['failover_peerip']};
689
  peer port {$peer_port};
690
  max-response-delay 10;
691
  max-unacked-updates 10;
692
  {$dhcpdconf_pri}
693
  load balance max seconds 3;
694
}
695
\n
696
EOPP;
697
			}
698
		}
699
	}
700

    
701
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
702

    
703
		$newzone = array();
704
		$ifcfg = $config['interfaces'][$dhcpif];
705

    
706
		if (!isset($dhcpifconf['enable']) || !isset($Iflist[$dhcpif])) {
707
			continue;
708
		}
709
		$ifcfgip = get_interface_ip($dhcpif);
710
		$ifcfgsn = get_interface_subnet($dhcpif);
711
		$subnet = gen_subnet($ifcfgip, $ifcfgsn);
712
		$subnetmask = gen_subnet_mask($ifcfgsn);
713

    
714
		if (!is_ipaddr($subnet)) {
715
			continue;
716
		}
717

    
718
		$all_pools = array();
719
		$all_pools[] = $dhcpifconf;
720
		if (is_array($dhcpifconf['pool'])) {
721
			$all_pools = array_merge($all_pools, $dhcpifconf['pool']);
722
		}
723

    
724
		$dnscfg = "";
725

    
726
		if ($dhcpifconf['domain']) {
727
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
728
		}
729

    
730
		if ($dhcpifconf['domainsearchlist'] <> "") {
731
			$dnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpifconf['domainsearchlist'])) . "\";\n";
732
		}
733

    
734
		if (isset($dhcpifconf['ddnsupdate'])) {
735
			$need_ddns_updates = true;
736
			$newzone = array();
737
			if ($dhcpifconf['ddnsdomain'] <> "") {
738
				$newzone['domain-name'] = $dhcpifconf['ddnsdomain'];
739
				$dnscfg .= "	ddns-domainname \"{$dhcpifconf['ddnsdomain']}\";\n";
740
			} else {
741
				$newzone['domain-name'] = $config['system']['domain'];
742
			}
743

    
744
			if (empty($dhcpifconf['ddnsclientupdates'])) {
745
				$ddnsclientupdates = 'allow';
746
			} else {
747
				$ddnsclientupdates = $dhcpifconf['ddnsclientupdates'];
748
			}
749

    
750
			$dnscfg .= "	{$ddnsclientupdates} client-updates;\n";
751

    
752
			$revsubnet = array_reverse(explode('.',$subnet));
753

    
754
			$subnet_mask_bits = 32 - $ifcfgsn;
755
			$start_octet = $subnet_mask_bits >> 3;
756
			$octet_mask_bits = $subnet_mask_bits & ($subnet_mask_bits % 8);
757
			if ($octet_mask_bits) {
758
			    $octet_mask = (1 << $octet_mask_bits) - 1;
759
			    $octet_start = $revsubnet[$start_octet] & ~$octet_mask;
760
			    $revsubnet[$start_octet] = $octet_start . "-" . ($octet_start + $octet_mask);
761
			}
762

    
763
			$ptr_domain = '';
764
			for ($octet = 0; $octet <= 3; $octet++) {
765
				if ($octet < $start_octet) {
766
					continue;
767
				}
768
				$ptr_domain .= ((empty($ptr_domain) && $ptr_domain !== "0") ? '' : '.');
769
				$ptr_domain .= $revsubnet[$octet];
770
			}
771
			$ptr_domain .= ".in-addr.arpa";
772
			$newzone['ptr-domain'] = $ptr_domain;
773
			unset($ptr_domain, $revsubnet, $start_octet);
774
		}
775

    
776
		if (is_array($dhcpifconf['dnsserver']) && ($dhcpifconf['dnsserver'][0])) {
777
			$dnscfg .= "	option domain-name-servers " . join(",", $dhcpifconf['dnsserver']) . ";";
778
			if ($newzone['domain-name']) {
779
				$newzone['dns-servers'] = $dhcpifconf['dnsserver'];
780
			}
781
		} else if (isset($config['dnsmasq']['enable'])) {
782
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
783
			if ($newzone['domain-name'] && is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
784
				$newzone['dns-servers'] = $syscfg['dnsserver'];
785
			}
786
		} else if (isset($config['unbound']['enable'])) {
787
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
788
		} else if (!empty($dns_arrv4)) {
789
			$dnscfg .= "	option domain-name-servers " . join(",", $dns_arrv4) . ";";
790
			if ($newzone['domain-name']) {
791
				$newzone['dns-servers'] = $dns_arrv4;
792
			}
793
		}
794

    
795
		/* Create classes - These all contain comma separated lists. Join them into one
796
		   big comma separated string then split them all up. */
797
		$all_mac_strings = array();
798
		if (is_array($dhcpifconf['pool'])) {
799
			foreach ($all_pools as $poolconf) {
800
				$all_mac_strings[] = $poolconf['mac_allow'];
801
				$all_mac_strings[] = $poolconf['mac_deny'];
802
			}
803
		}
804
		$all_mac_strings[] = $dhcpifconf['mac_allow'];
805
		$all_mac_strings[] = $dhcpifconf['mac_deny'];
806
		if (!empty($all_mac_strings)) {
807
			$all_mac_list = array_unique(explode(',', implode(',', $all_mac_strings)));
808
			foreach ($all_mac_list as $mac) {
809
				if (empty($mac)) {
810
					continue;
811
				}
812
				$dhcpdconf .= 'class "' . str_replace(':', '', $mac) . '" {' . "\n";
813
				// Skip the first octet of the MAC address - for media type, typically Ethernet ("01") and match the rest.
814
				$dhcpdconf .= '	match if substring (hardware, 1, ' . (substr_count($mac, ':') + 1) . ') = ' . $mac . ';' . "\n";
815
				$dhcpdconf .= '}' . "\n";
816
			}
817
		}
818

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

    
822
		$dhcpdconf .= "subnet {$subnet} netmask {$subnetmask} {\n";
823

    
824
		// Setup pool options
825
		foreach ($all_pools as $all_pools_idx => $poolconf) {
826
			if (!(ip_in_subnet($poolconf['range']['from'], "{$subnet}/{$ifcfgsn}") && ip_in_subnet($poolconf['range']['to'], "{$subnet}/{$ifcfgsn}"))) {
827
				// If the user has changed the subnet from the interfaces page and applied,
828
				// but has not updated the DHCP range, then the range to/from of the pool can be outside the subnet.
829
				// This can also happen when implementing the batch of changes when the setup wizard reloads the new settings.
830
				$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);
831
				$do_file_notice = true;
832
				$conf_ipv4_address = $ifcfg['ipaddr'];
833
				$conf_ipv4_subnetmask = $ifcfg['subnet'];
834
				if (is_ipaddrv4($conf_ipv4_address) && is_subnet("{$conf_ipv4_address}/{$conf_ipv4_subnetmask}")) {
835
					$conf_subnet_base = gen_subnet($conf_ipv4_address, $conf_ipv4_subnetmask);
836
					if (ip_in_subnet($poolconf['range']['from'], "{$conf_subnet_base}/{$conf_ipv4_subnetmask}") &&
837
					    ip_in_subnet($poolconf['range']['to'], "{$conf_subnet_base}/{$conf_ipv4_subnetmask}")) {
838
						// Even though the running interface subnet does not match the pool range,
839
						// the interface subnet in the config file contains the pool range.
840
						// We are somewhere part-way through a settings reload, e.g. after running the setup wizard.
841
						// services_dhcpdv4_configure will be called again later when the new interface settings from
842
						// the config are applied and at that time everything will match up.
843
						// Ignore this pool on this interface for now and just log the error to the system log.
844
						log_error($error_msg);
845
						$do_file_notice = false;
846
					}
847
				}
848
				if ($do_file_notice) {
849
					file_notice("DHCP", $error_msg);
850
				}
851
				continue;
852
			}
853
			$dhcpdconf .= "	pool {\n";
854
			/* is failover dns setup? */
855
			if (is_array($poolconf['dnsserver']) && $poolconf['dnsserver'][0] <> "") {
856
				$dhcpdconf .= "		option domain-name-servers {$poolconf['dnsserver'][0]}";
857
				if ($poolconf['dnsserver'][1] <> "") {
858
					$dhcpdconf .= ",{$poolconf['dnsserver'][1]}";
859
				}
860
				if ($poolconf['dnsserver'][2] <> "") {
861
					$dhcpdconf .= ",{$poolconf['dnsserver'][2]}";
862
				}
863
				if ($poolconf['dnsserver'][3] <> "") {
864
					$dhcpdconf .= ",{$poolconf['dnsserver'][3]}";
865
				}
866
				$dhcpdconf .= ";\n";
867
			}
868

    
869
			/* allow/deny MACs */
870
			$mac_allow_list = array_unique(explode(',', $poolconf['mac_allow']));
871
			foreach ($mac_allow_list as $mac) {
872
				if (empty($mac)) {
873
					continue;
874
				}
875
				$dhcpdconf .= "		allow members of \"" . str_replace(':', '', $mac) . "\";\n";
876
			}
877
			$deny_action = "deny";
878
			if (isset($poolconf['nonak']) && empty($poolconf['failover_peerip'])) {
879
				$deny_action = "ignore";
880
			}
881
			$mac_deny_list = array_unique(explode(',', $poolconf['mac_deny']));
882
			foreach ($mac_deny_list as $mac) {
883
				if (empty($mac)) {
884
					continue;
885
				}
886
				$dhcpdconf .= "		$deny_action members of \"" . str_replace(':', '', $mac) . "\";\n";
887
			}
888

    
889
			if ($poolconf['failover_peerip'] <> "") {
890
				$dhcpdconf .= "		$deny_action dynamic bootp clients;\n";
891
			}
892

    
893
			// set pool MAC limitations
894
			if (isset($poolconf['denyunknown'])) {
895
				if ($poolconf['denyunknown'] == "class") {
896
					$dhcpdconf .= "		allow members of \"s_{$dhcpif}\";\n";
897
					$dhcpdconf .= "		$deny_action unknown-clients;\n";
898
				} else if ($poolconf['denyunknown'] == "disabled") {
899
					// add nothing to $dhcpdconf; condition added to prevent next condition applying if ever engine changes such that: isset("disabled") == true
900
				} else {	// "catch-all" covering "enabled" value post-PR#4066, and covering non-upgraded boolean option (i.e. literal value "enabled")
901
					$dhcpdconf .= "		$deny_action unknown-clients;\n";
902
				}
903
			}
904

    
905
			if ($poolconf['gateway'] && $poolconf['gateway'] != "none" && ($poolconf['gateway'] != $dhcpifconf['gateway'])) {
906
				$dhcpdconf .= "		option routers {$poolconf['gateway']};\n";
907
			}
908

    
909
			if ($dhcpifconf['failover_peerip'] <> "") {
910
				$dhcpdconf .= "		failover peer \"dhcp_{$dhcpif}\";\n";
911
			}
912

    
913
			$pdnscfg = "";
914

    
915
			if ($poolconf['domain'] && ($poolconf['domain'] != $dhcpifconf['domain'])) {
916
				$pdnscfg .= "		option domain-name \"{$poolconf['domain']}\";\n";
917
			}
918

    
919
			if (!empty($poolconf['domainsearchlist']) && ($poolconf['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
920
				$pdnscfg .= "		option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $poolconf['domainsearchlist'])) . "\";\n";
921
			}
922

    
923
			if (isset($poolconf['ddnsupdate'])) {
924
				if (($poolconf['ddnsdomain'] <> "") && ($poolconf['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
925
					$pdnscfg .= "		ddns-domainname \"{$poolconf['ddnsdomain']}\";\n";
926
				}
927
				$pdnscfg .= "		ddns-update-style interim;\n";
928
			}
929

    
930
			$dhcpdconf .= "{$pdnscfg}";
931

    
932
			// default-lease-time
933
			if ($poolconf['defaultleasetime'] && ($poolconf['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
934
				$dhcpdconf .= "		default-lease-time {$poolconf['defaultleasetime']};\n";
935
			}
936

    
937
			// max-lease-time
938
			if ($poolconf['maxleasetime'] && ($poolconf['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
939
				$dhcpdconf .= "		max-lease-time {$poolconf['maxleasetime']};\n";
940
			}
941

    
942
			// ignore bootp
943
			if (isset($poolconf['ignorebootp'])) {
944
				$dhcpdconf .= "		ignore bootp;\n";
945
			}
946

    
947
			// ignore-client-uids
948
			if (isset($poolconf['ignoreclientuids'])) {
949
				$dhcpdconf .= "		ignore-client-uids true;\n";
950
			}
951

    
952
			// netbios-name*
953
			if (is_array($poolconf['winsserver']) && $poolconf['winsserver'][0] && ($poolconf['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
954
				$dhcpdconf .= "		option netbios-name-servers " . join(",", $poolconf['winsserver']) . ";\n";
955
				$dhcpdconf .= "		option netbios-node-type 8;\n";
956
			}
957

    
958
			// ntp-servers
959
			if (is_array($poolconf['ntpserver']) && $poolconf['ntpserver'][0] && ($poolconf['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
960
				$dhcpdconf .= "		option ntp-servers " . join(",", $poolconf['ntpserver']) . ";\n";
961
			}
962

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

    
968
			// Handle pool-specific options
969
			$dhcpdconf .= "\n";
970
			// Ignore the first pool, which is the "overall" pool when $all_pools_idx is 0 - those are put outside the pool block later
971
			if (isset($poolconf['numberoptions']['item']) && is_array($poolconf['numberoptions']['item']) && ($all_pools_idx > 0)) {
972
				// Use the "real" pool index from the config, excluding the "overall" pool, and based from 0.
973
				// This matches the way $poolidx was used when generating the $custoptions string earlier.
974
				$poolidx = $all_pools_idx - 1;
975
				foreach ($poolconf['numberoptions']['item'] as $itemidx => $item) {
976
					$item_value = base64_decode($item['value']);
977
					if (empty($item['type']) || $item['type'] == "text") {
978
						$dhcpdconf .= "		option custom-{$dhcpif}-{$poolidx}-{$itemidx} \"{$item_value}\";\n";
979
					} else {
980
						$dhcpdconf .= "		option custom-{$dhcpif}-{$poolidx}-{$itemidx} {$item_value};\n";
981
					}
982
				}
983
			}
984

    
985
			// ldap-server
986
			if (!empty($poolconf['ldap']) && ($poolconf['ldap'] != $dhcpifconf['ldap'])) {
987
				$dhcpdconf .= "		option ldap-server \"{$poolconf['ldap']}\";\n";
988
			}
989

    
990
			// net boot information
991
			if (isset($poolconf['netboot'])) {
992
				if (!empty($poolconf['nextserver']) && ($poolconf['nextserver'] != $dhcpifconf['nextserver'])) {
993
					$dhcpdconf .= "		next-server {$poolconf['nextserver']};\n";
994
				}
995

    
996
				if (!empty($poolconf['filename']) &&
997
				    (!isset($dhcpifconf['filename']) ||
998
				    ($poolconf['filename'] != $dhcpifconf['filename']))) {
999
					$filename = $poolconf['filename'];
1000
				}
1001
				if (!empty($poolconf['filename32']) &&
1002
				    (!isset($dhcpifconf['filename32']) ||
1003
				    ($poolconf['filename32'] != $dhcpifconf['filename32']))) {
1004
					$filename32 = $poolconf['filename32'];
1005
				}
1006
				if (!empty($poolconf['filename64']) &&
1007
				    (!isset($dhcpifconf['filename64']) ||
1008
				    ($poolconf['filename64'] != $dhcpifconf['filename64']))) {
1009
					$filename64 = $poolconf['filename64'];
1010
				}
1011
				if (!empty($poolconf['filename32arm']) &&
1012
				    (!isset($dhcpifconf['filename32arm']) ||
1013
				    ($poolconf['filename32arm'] != $dhcpifconf['filename32arm']))) {
1014
					$filename32arm = $poolconf['filename32arm'];
1015
				}
1016
				if (!empty($poolconf['filename64arm']) &&
1017
				    (!isset($dhcpifconf['filename64arm']) ||
1018
				    ($poolconf['filename64arm'] != $dhcpifconf['filename64arm']))) {
1019
					$filename64arm = $poolconf['filename64arm'];
1020
				}
1021

    
1022
				if (!empty($filename32) || !empty($filename64) || !empty($filename32arm) || !empty($filename64arm)) {
1023
					if (empty($filename) && !empty($dhcpifconf['filename'])) {
1024
						$filename = $dhcpifconf['filename'];
1025
					}
1026
					if (empty($filename32) && !empty($dhcpifconf['filename32'])) {
1027
						$filename32 = $dhcpifconf['filename32'];
1028
					}
1029
					if (empty($filename64) && !empty($dhcpifconf['filename64'])) {
1030
						$filename64 = $dhcpifconf['filename64'];
1031
					}
1032
					if (empty($filename32arm) && !empty($dhcpifconf['filename32arm'])) {
1033
						$filename32arm = $dhcpifconf['filename32arm'];
1034
					}
1035
					if (empty($filename64arm) && !empty($dhcpifconf['filename64arm'])) {
1036
						$filename64arm = $dhcpifconf['filename64arm'];
1037
					}
1038
				}
1039

    
1040
				if (!empty($filename) && !empty($filename32) && !empty($filename64) && !empty($filename32arm) && !empty($filename64arm)) {
1041
					$dhcpdconf .= "		if option arch = 00:06 {\n";
1042
					$dhcpdconf .= "			filename \"{$filename32}\";\n";
1043
					$dhcpdconf .= "		} else if option arch = 00:07 {\n";
1044
					$dhcpdconf .= "			filename \"{$filename64}\";\n";
1045
					$dhcpdconf .= "		} else if option arch = 00:09 {\n";
1046
					$dhcpdconf .= "			filename \"{$filename64}\";\n";
1047
					$dhcpdconf .= "		} else if option arch = 00:0a {\n";
1048
					$dhcpdconf .= "			filename \"{$filename32arm}\";\n";
1049
					$dhcpdconf .= "		} else if option arch = 00:0b {\n";
1050
					$dhcpdconf .= "			filename \"{$filename64arm}\";\n";
1051
					$dhcpdconf .= "		} else {\n";
1052
					$dhcpdconf .= "			filename \"{$filename}\";\n";
1053
					$dhcpdconf .= "		}\n\n";
1054
				} elseif (!empty($filename)) {
1055
					$dhcpdconf .= "		filename \"{$filename}\";\n";
1056
				}
1057
				unset($filename, $filename32, $filename64, $filename32arm, $filename64arm);
1058

    
1059
				if (!empty($poolconf['rootpath']) && ($poolconf['rootpath'] != $dhcpifconf['rootpath'])) {
1060
					$dhcpdconf .= "		option root-path \"{$poolconf['rootpath']}\";\n";
1061
				}
1062
			}
1063
			$dhcpdconf .= "		range {$poolconf['range']['from']} {$poolconf['range']['to']};\n";
1064
			$dhcpdconf .= "	}\n\n";
1065
		}
1066
// End of settings inside pools
1067

    
1068
		if ($dhcpifconf['gateway'] && $dhcpifconf['gateway'] != "none") {
1069
			$routers = $dhcpifconf['gateway'];
1070
			$add_routers = true;
1071
		} elseif ($dhcpifconf['gateway'] == "none") {
1072
			$add_routers = false;
1073
		} else {
1074
			$add_routers = $enable_add_routers;
1075
			$routers = $ifcfgip;
1076
		}
1077
		if ($add_routers) {
1078
			$dhcpdconf .= "	option routers {$routers};\n";
1079
		}
1080

    
1081
		$dhcpdconf .= <<<EOD
1082
$dnscfg
1083

    
1084
EOD;
1085
		// default-lease-time
1086
		if ($dhcpifconf['defaultleasetime']) {
1087
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
1088
		}
1089

    
1090
		// max-lease-time
1091
		if ($dhcpifconf['maxleasetime']) {
1092
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
1093
		}
1094

    
1095
		if (!isset($dhcpifconf['disablepingcheck'])) {
1096
			$dhcpdconf .= "	ping-check true;\n";
1097
		} else {
1098
			$dhcpdconf .= "	ping-check false;\n";
1099
		}
1100

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

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

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

    
1117
		// Handle option, number rowhelper values
1118
		$dhcpdconf .= "\n";
1119
		if (isset($dhcpifconf['numberoptions']['item']) && is_array($dhcpifconf['numberoptions']['item'])) {
1120
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
1121
				$item_value = base64_decode($item['value']);
1122
				if (empty($item['type']) || $item['type'] == "text") {
1123
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} \"{$item_value}\";\n";
1124
				} else {
1125
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} {$item_value};\n";
1126
				}
1127
			}
1128
		}
1129

    
1130
		// ldap-server
1131
		if ($dhcpifconf['ldap'] <> "") {
1132
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
1133
		}
1134

    
1135
		// net boot information
1136
		if (isset($dhcpifconf['netboot'])) {
1137
			if ($dhcpifconf['nextserver'] <> "") {
1138
				$dhcpdconf .= "	next-server {$dhcpifconf['nextserver']};\n";
1139
			}
1140
			if (!empty($dhcpifconf['filename']) && !empty($dhcpifconf['filename32']) && !empty($dhcpifconf['filename64'])) {
1141
				$dhcpdconf .= "	if option arch = 00:06 {\n";
1142
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename32']}\";\n";
1143
				$dhcpdconf .= "	} else if option arch = 00:07 {\n";
1144
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1145
				$dhcpdconf .= "	} else if option arch = 00:09 {\n";
1146
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1147
				$dhcpdconf .= "	} else {\n";
1148
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename']}\";\n";
1149
				$dhcpdconf .= "	}\n\n";
1150
			} elseif (!empty($dhcpifconf['filename'])) {
1151
				$dhcpdconf .= "	filename \"{$dhcpifconf['filename']}\";\n";
1152
			}
1153
			if (!empty($dhcpifconf['rootpath'])) {
1154
				$dhcpdconf .= "	option root-path \"{$dhcpifconf['rootpath']}\";\n";
1155
			}
1156
		}
1157

    
1158
		$dhcpdconf .= <<<EOD
1159
}
1160

    
1161
EOD;
1162

    
1163
		/* add static mappings */
1164
		if (is_array($dhcpifconf['staticmap'])) {
1165

    
1166
			$i = 0;
1167
			$sm_newzone[] = array();
1168
			$need_sm_ddns_updates = false;
1169
			foreach ($dhcpifconf['staticmap'] as $sm) {
1170
				$cid = '';
1171
				$dhcpdconf .= "host s_{$dhcpif}_{$i} {\n";
1172

    
1173
				if ($sm['mac']) {
1174
					$dhcpdconf .= "	hardware ethernet {$sm['mac']};\n";
1175
				}
1176

    
1177
				if ($sm['cid']) {
1178
					$cid = str_replace('"', '\"', $sm['cid']);
1179
					$dhcpdconf .= "	option dhcp-client-identifier \"{$cid}\";\n";
1180
				}
1181

    
1182
				if ($sm['ipaddr']) {
1183
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
1184
				}
1185

    
1186
				if ($sm['hostname']) {
1187
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1188
					$dhhostname = str_replace(".", "_", $dhhostname);
1189
					$dhcpdconf .= "	option host-name \"{$dhhostname}\";\n";
1190
					if ((isset($dhcpifconf['ddnsupdate']) || isset($sm['ddnsupdate'])) && (isset($dhcpifconf['ddnsforcehostname']) || isset($sm['ddnsforcehostname']))) {
1191
						$dhcpdconf .= "	ddns-hostname \"{$dhhostname}\";\n";
1192
					}
1193
				}
1194
				if ($sm['filename']) {
1195
					$dhcpdconf .= "	filename \"{$sm['filename']}\";\n";
1196
				}
1197

    
1198
				if ($sm['rootpath']) {
1199
					$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1200
				}
1201

    
1202
				if ($sm['gateway'] && ($sm['gateway'] != $dhcpifconf['gateway'])) {
1203
					$dhcpdconf .= "	option routers {$sm['gateway']};\n";
1204
				}
1205

    
1206
				$smdnscfg = "";
1207

    
1208
				if ($sm['domain'] && ($sm['domain'] != $dhcpifconf['domain'])) {
1209
					$smdnscfg .= "	option domain-name \"{$sm['domain']}\";\n";
1210
				}
1211

    
1212
				if (!empty($sm['domainsearchlist']) && ($sm['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
1213
					$smdnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $sm['domainsearchlist'])) . "\";\n";
1214
				}
1215

    
1216
				if (isset($sm['ddnsupdate'])) {
1217
					if (($sm['ddnsdomain'] <> "") && ($sm['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
1218
						$smdnscfg .= "	ddns-domainname \"{$sm['ddnsdomain']}\";\n";
1219
				 		$need_sm_ddns_updates = true;	
1220
					}
1221
					$smdnscfg .= "	ddns-update-style interim;\n";
1222
				}
1223

    
1224
				if (is_array($sm['dnsserver']) && ($sm['dnsserver'][0]) && ($sm['dnsserver'][0] != $dhcpifconf['dnsserver'][0])) {
1225
					$smdnscfg .= "	option domain-name-servers " . join(",", $sm['dnsserver']) . ";\n";
1226
				}
1227
				$dhcpdconf .= "{$smdnscfg}";
1228

    
1229
				// default-lease-time
1230
				if ($sm['defaultleasetime'] && ($sm['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
1231
					$dhcpdconf .= "	default-lease-time {$sm['defaultleasetime']};\n";
1232
				}
1233

    
1234
				// max-lease-time
1235
				if ($sm['maxleasetime'] && ($sm['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
1236
					$dhcpdconf .= "	max-lease-time {$sm['maxleasetime']};\n";
1237
				}
1238

    
1239
				// netbios-name*
1240
				if (is_array($sm['winsserver']) && $sm['winsserver'][0] && ($sm['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
1241
					$dhcpdconf .= "	option netbios-name-servers " . join(",", $sm['winsserver']) . ";\n";
1242
					$dhcpdconf .= "	option netbios-node-type 8;\n";
1243
				}
1244

    
1245
				// ntp-servers
1246
				if (is_array($sm['ntpserver']) && $sm['ntpserver'][0] && ($sm['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
1247
					$dhcpdconf .= "	option ntp-servers " . join(",", $sm['ntpserver']) . ";\n";
1248
				}
1249

    
1250
				// tftp-server-name
1251
				if (!empty($sm['tftp']) && ($sm['tftp'] != $dhcpifconf['tftp'])) {
1252
					$dhcpdconf .= "	option tftp-server-name \"{$sm['tftp']}\";\n";
1253
				}
1254

    
1255
				// Handle option, number rowhelper values
1256
				$dhcpdconf .= "\n";
1257
				if (isset($sm['numberoptions']['item']) && is_array($sm['numberoptions']['item'])) {
1258
					foreach ($sm['numberoptions']['item'] as $itemidx => $item) {
1259
						$item_value = base64_decode($item['value']);
1260
						if (empty($item['type']) || $item['type'] == "text") {
1261
							$dhcpdconf .= "	option custom-s_{$dhcpif}_{$i}-{$itemidx} \"{$item_value}\";\n";
1262
						} else {
1263
							$dhcpdconf .= "	option custom-s_{$dhcpif}_{$i}-{$itemidx} {$item_value};\n";
1264
						}
1265
					}
1266
				}
1267

    
1268
				// ldap-server
1269
				if (!empty($sm['ldap']) && ($sm['ldap'] != $dhcpifconf['ldap'])) {
1270
					$dhcpdconf .= "	option ldap-server \"{$sm['ldap']}\";\n";
1271
				}
1272

    
1273
				// net boot information
1274
				if (isset($sm['netboot'])) {
1275
					if ($sm['nextserver'] <> "") {
1276
						$dhcpdconf .= "	next-server {$sm['nextserver']};\n";
1277
					}
1278
					if (!empty($sm['filename']) && !empty($sm['filename32']) && !empty($sm['filename64'])) {
1279
						$dhcpdconf .= "	if option arch = 00:06 {\n";
1280
						$dhcpdconf .= "		filename \"{$sm['filename32']}\";\n";
1281
						$dhcpdconf .= "	} else if option arch = 00:07 {\n";
1282
						$dhcpdconf .= "		filename \"{$sm['filename64']}\";\n";
1283
						$dhcpdconf .= "	} else if option arch = 00:09 {\n";
1284
						$dhcpdconf .= "		filename \"{$sm['filename64']}\";\n";
1285
						$dhcpdconf .= "	} else {\n";
1286
						$dhcpdconf .= "		filename \"{$sm['filename']}\";\n";
1287
						$dhcpdconf .= "	}\n\n";
1288
					} elseif (!empty($sm['filename'])) {
1289
						$dhcpdconf .= "	filename \"{$sm['filename']}\";\n";
1290
					}
1291
					if (!empty($dhcpifconf['rootpath'])) {
1292
						$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1293
					}
1294
				}
1295

    
1296
				$dhcpdconf .= "}\n";
1297

    
1298
				// add zone DDNS key/server to $ddns_zone[] if required
1299
				if ($need_sm_ddns_updates) {
1300
					$ddnsduplicate = false;
1301
					foreach ($ddns_zones as $ddnszone) {
1302
						if ($ddnszone['domain-name'] == $sm['ddnsdomain']) {
1303
							$ddnsduplicate = true;
1304
						}
1305
					}
1306
					if (!$ddnsduplicate) {
1307
						$sm_newzone['dns-servers'] = array($sm['ddnsdomainprimary'], $sm['ddnsdomainsecondary']);
1308
						$sm_newzone['domain-name'] = $sm['ddnsdomain'];
1309
						$sm_newzone['ddnsdomainkeyname'] = $sm['ddnsdomainkeyname'];
1310
						$sm_newzone['ddnsdomainkeyalgorithm'] = $sm['ddnsdomainkeyalgorithm'];
1311
						$sm_newzone['ddnsdomainkey'] = $sm['ddnsdomainkey'];
1312
						$dhcpdconf .= dhcpdkey($sm_newzone);
1313
						$ddns_zones[] = $sm_newzone;
1314
						$need_ddns_updates = true;
1315
					}
1316
				}
1317

    
1318
				// subclass for DHCP limiting
1319
				if (!empty($sm['mac'])) {
1320
					// assuming ALL addresses are ethernet hardware type ("1:" prefix)
1321
					$dhcpdconf .= "subclass \"s_{$dhcpif}\" 1:{$sm['mac']};\n";
1322
				}
1323
				if (!empty($cid)) {
1324
					$dhcpdconf .= "subclass \"s_{$dhcpif}\" \"{$cid}\";\n";
1325
				}
1326

    
1327

    
1328
				$i++;
1329
			}
1330
		}
1331

    
1332
		$dhcpdifs[] = get_real_interface($dhcpif);
1333
		if ($newzone['domain-name']) {
1334
			if ($need_ddns_updates) {
1335
				$newzone['dns-servers'] = array($dhcpifconf['ddnsdomainprimary'], $dhcpifconf['ddnsdomainsecondary']);
1336
				$newzone['ddnsdomainkeyname'] = $dhcpifconf['ddnsdomainkeyname'];
1337
				$newzone['ddnsdomainkeyalgorithm'] = $dhcpifconf['ddnsdomainkeyalgorithm'];
1338
				$newzone['ddnsdomainkey'] = $dhcpifconf['ddnsdomainkey'];
1339
				$dhcpdconf .= dhcpdkey($dhcpifconf);
1340
			}
1341
			$ddns_zones[] = $newzone;
1342
		}
1343
	}
1344

    
1345
	if ($need_ddns_updates) {
1346
		$dhcpdconf .= "ddns-update-style interim;\n";
1347
		$dhcpdconf .= "update-static-leases on;\n";
1348

    
1349
		$dhcpdconf .= dhcpdzones($ddns_zones);
1350
	}
1351

    
1352
	/* write dhcpd.conf */
1353
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpd.conf", $dhcpdconf)) {
1354
		printf(gettext("Error: cannot open dhcpd.conf in services_dhcpdv4_configure().%s"), "\n");
1355
		unset($dhcpdconf);
1356
		return 1;
1357
	}
1358
	unset($dhcpdconf);
1359

    
1360
	/* create an empty leases database */
1361
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
1362
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
1363
	}
1364

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

    
1369
	/* fire up dhcpd in a chroot */
1370
	if (count($dhcpdifs) > 0) {
1371
		mwexec("/usr/local/sbin/dhcpd -user dhcpd -group _dhcp -chroot {$g['dhcpd_chroot_path']} -cf /etc/dhcpd.conf -pf {$g['varrun_path']}/dhcpd.pid " .
1372
			join(" ", $dhcpdifs));
1373
	}
1374

    
1375
	if (platform_booting()) {
1376
		print "done.\n";
1377
	}
1378

    
1379
	return 0;
1380
}
1381

    
1382
function dhcpdkey($dhcpifconf) {
1383
	$dhcpdconf = "";
1384
	if (!empty($dhcpifconf['ddnsdomainkeyname']) && !empty($dhcpifconf['ddnsdomainkey'])) {
1385
		$algorithm = empty($dhcpifconf['ddnsdomainkeyalgorithm']) ? 'hmac-md5' : $dhcpifconf['ddnsdomainkeyalgorithm'];
1386
		$dhcpdconf .= "key \"{$dhcpifconf['ddnsdomainkeyname']}\" {\n";
1387
		$dhcpdconf .= "	algorithm {$algorithm};\n";
1388
		$dhcpdconf .= "	secret {$dhcpifconf['ddnsdomainkey']};\n";
1389
		$dhcpdconf .= "}\n";
1390
	}
1391

    
1392
	return $dhcpdconf;
1393
}
1394

    
1395
function dhcpdzones($ddns_zones) {
1396
	$dhcpdconf = "";
1397

    
1398
	if (is_array($ddns_zones)) {
1399
		$added_zones = array();
1400
		foreach ($ddns_zones as $zone) {
1401
			if (!is_array($zone) || empty($zone) || !is_array($zone['dns-servers'])) {
1402
				continue;
1403
			}
1404
			$primary = $zone['dns-servers'][0];
1405
			$secondary = empty($zone['dns-servers'][1]) ? "" : $zone['dns-servers'][1];
1406

    
1407
			// Make sure we aren't using any invalid servers.
1408
			if (!is_ipaddr($primary)) {
1409
				if (is_ipaddr($secondary)) {
1410
					$primary = $secondary;
1411
					$secondary = "";
1412
				} else {
1413
					continue;
1414
				}
1415
			}
1416

    
1417
			// We don't need to add zones multiple times.
1418
			if ($zone['domain-name'] && !in_array($zone['domain-name'], $added_zones)) {
1419
				$dhcpdconf .= "zone {$zone['domain-name']}. {\n";
1420
				if (is_ipaddrv4($primary)) {
1421
					$dhcpdconf .= "	primary {$primary};\n";
1422
				} else {
1423
					$dhcpdconf .= "	primary6 {$primary};\n";
1424
				}
1425
				if (is_ipaddrv4($secondary)) {
1426
					$dhcpdconf .= "	secondary {$secondary};\n";
1427
				} elseif (is_ipaddrv6($secondary)) {
1428
					$dhcpdconf .= "	secondary6 {$secondary};\n";
1429
				}
1430
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1431
					$dhcpdconf .= "	key \"{$zone['ddnsdomainkeyname']}\";\n";
1432
				}
1433
				$dhcpdconf .= "}\n";
1434
				$added_zones[] = $zone['domain-name'];
1435
			}
1436
			if ($zone['ptr-domain'] && !in_array($zone['ptr-domain'], $added_zones)) {
1437
				$dhcpdconf .= "zone {$zone['ptr-domain']}. {\n";
1438
				if (is_ipaddrv4($primary)) {
1439
					$dhcpdconf .= "	primary {$primary};\n";
1440
				} else {
1441
					$dhcpdconf .= "	primary6 {$primary};\n";
1442
				}
1443
				if (is_ipaddrv4($secondary)) {
1444
					$dhcpdconf .= "	secondary {$secondary};\n";
1445
				} elseif (is_ipaddrv6($secondary)) {
1446
					$dhcpdconf .= "	secondary6 {$secondary};\n";
1447
				}
1448
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1449
					$dhcpdconf .= "	key \"{$zone['ddnsdomainkeyname']}\";\n";
1450
				}
1451
				$dhcpdconf .= "}\n";
1452
				$added_zones[] = $zone['ptr-domain'];
1453
			}
1454
		}
1455
	}
1456

    
1457
	return $dhcpdconf;
1458
}
1459

    
1460
function services_dhcpdv6_configure($blacklist = array()) {
1461
	global $config, $g;
1462

    
1463
	if ($g['services_dhcp_server_enable'] == false) {
1464
		return;
1465
	}
1466

    
1467
	if (isset($config['system']['developerspew'])) {
1468
		$mt = microtime();
1469
		echo "services_dhcpd_configure($if) being called $mt\n";
1470
	}
1471

    
1472
	/* kill any running dhcpd */
1473
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid")) {
1474
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid");
1475
	}
1476
	if (isvalidpid("{$g['varrun_path']}/dhcpleases6.pid")) {
1477
		killbypid("{$g['varrun_path']}/dhcpleases6.pid");
1478
	}
1479

    
1480
	/* DHCP enabled on any interfaces? */
1481
	if (!is_dhcpv6_server_enabled()) {
1482
		return 0;
1483
	}
1484

    
1485
	$syscfg = $config['system'];
1486
	if (!is_array($config['dhcpdv6'])) {
1487
		$config['dhcpdv6'] = array();
1488
	}
1489
	$dhcpdv6cfg = $config['dhcpdv6'];
1490
	$Iflist = get_configured_interface_list();
1491
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
1492

    
1493

    
1494
	if (platform_booting()) {
1495
		echo "Starting DHCPv6 service...";
1496
	} else {
1497
		sleep(1);
1498
	}
1499

    
1500
	$custoptionsv6 = "";
1501
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1502
		if (is_array($dhcpv6ifconf['numberoptions']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1503
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1504
				$custoptionsv6 .= "option custom-{$dhcpv6if}-{$itemv6idx} code {$itemv6['number']} = text;\n";
1505
			}
1506
		}
1507
	}
1508

    
1509
	if (isset($dhcpv6ifconf['netboot']) && !empty($dhcpv6ifconf['bootfile_url'])) {
1510
		$custoptionsv6 .= "option dhcp6.bootfile-url code 59 = string;\n";
1511
	}
1512

    
1513
	$dhcpdv6conf = <<<EOD
1514

    
1515
option domain-name "{$syscfg['domain']}";
1516
option ldap-server code 95 = text;
1517
option domain-search-list code 119 = text;
1518
{$custoptionsv6}
1519
default-lease-time 7200;
1520
max-lease-time 86400;
1521
log-facility local7;
1522
one-lease-per-client true;
1523
deny duplicates;
1524
ping-check true;
1525
update-conflict-detection false;
1526

    
1527
EOD;
1528

    
1529
	if (!isset($dhcpv6ifconf['disableauthoritative'])) {
1530
		$dhcpdv6conf .= "authoritative;\n";
1531
	}
1532

    
1533
	if (isset($dhcpv6ifconf['alwaysbroadcast'])) {
1534
		$dhcpdv6conf .= "always-broadcast on\n";
1535
	}
1536

    
1537
	$dhcpdv6ifs = array();
1538

    
1539
	$dhcpv6num = 0;
1540
	$nsupdate = false;
1541

    
1542
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1543

    
1544
		$ddns_zones = array();
1545

    
1546
		$ifcfgv6 = $config['interfaces'][$dhcpv6if];
1547

    
1548
		if (!isset($dhcpv6ifconf['enable']) || !isset($Iflist[$dhcpv6if]) ||
1549
		    (!isset($ifcfgv6['enable']) && !preg_match("/poes/", $dhcpv6if))) {
1550
			continue;
1551
		}
1552
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1553
		if (!is_ipaddrv6($ifcfgipv6) && !preg_match("/poes/", $dhcpv6if)) {
1554
			continue;
1555
		}
1556
		$ifcfgsnv6 = get_interface_subnetv6($dhcpv6if);
1557
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1558
		// We might have some prefix-delegation on WAN (e.g. /48),
1559
		// but then it is split and given out to individual interfaces
1560
		// (LAN, OPT1, OPT2...) as multiple /64 subnets. So the size
1561
		// of each subnet here is always /64.
1562
		$pdlen = 64;
1563

    
1564
		$dnscfgv6 = "";
1565

    
1566
		if ($dhcpv6ifconf['domain']) {
1567
			$dnscfgv6 .= "	option domain-name \"{$dhcpv6ifconf['domain']}\";\n";
1568
		}
1569

    
1570
		if ($dhcpv6ifconf['domainsearchlist'] <> "") {
1571
			$dnscfgv6 .= "	option dhcp6.domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpv6ifconf['domainsearchlist'])) . "\";\n";
1572
		}
1573

    
1574
		if (isset($dhcpv6ifconf['ddnsupdate'])) {
1575
			if ($dhcpv6ifconf['ddnsdomain'] <> "") {
1576
				$dnscfgv6 .= "	ddns-domainname \"{$dhcpv6ifconf['ddnsdomain']}\";\n";
1577
			}
1578
			if (empty($dhcpv6ifconf['ddnsclientupdates'])) {
1579
				$ddnsclientupdates = 'allow';
1580
			} else {
1581
				$ddnsclientupdates = $dhcpv6ifconf['ddnsclientupdates'];
1582
			}
1583
			$dnscfgv6 .= "	{$ddnsclientupdates} client-updates;\n";
1584
			$nsupdate = true;
1585
		} else {
1586
			$dnscfgv6 .= "	do-forward-updates false;\n";
1587
		}
1588

    
1589
		if ($dhcpv6ifconf['dhcp6c-dns'] != 'disabled') {
1590
			if (is_array($dhcpv6ifconf['dnsserver']) && ($dhcpv6ifconf['dnsserver'][0])) {
1591
				$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dhcpv6ifconf['dnsserver']) . ";\n";
1592
			} else if (((isset($config['dnsmasq']['enable'])) || isset($config['unbound']['enable'])) && (is_ipaddrv6($ifcfgipv6))) {
1593
				$dnscfgv6 .= "	option dhcp6.name-servers {$ifcfgipv6};\n";
1594
			} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1595
				$dns_arrv6 = array();
1596
				foreach ($syscfg['dnsserver'] as $dnsserver) {
1597
					if (is_ipaddrv6($dnsserver)) {
1598
						if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1599
						    Net_IPv6::isInNetmask($dnsserver, '::', $pdlen)) {
1600
							$dnsserver = merge_ipv6_delegated_prefix($ifcfgipv6, $dnsserver, $pdlen);
1601
						}
1602
						$dns_arrv6[] = $dnsserver;
1603
					}
1604
				}
1605
				if (!empty($dns_arrv6)) {
1606
					$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dns_arrv6) . ";\n";
1607
				}
1608
			}
1609
		} else {
1610
			$dnscfgv6 .= "	#option dhcp6.name-servers --;\n";
1611
		}
1612

    
1613
		if (!is_ipaddrv6($ifcfgipv6)) {
1614
			$ifcfgsnv6 = "64";
1615
			$subnetv6 = gen_subnetv6($dhcpv6ifconf['range']['from'], $ifcfgsnv6);
1616
		}
1617

    
1618
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1619

    
1620
		if (isset($dhcpv6ifconf['ddnsupdate']) &&
1621
		    !empty($dhcpv6ifconf['ddnsdomain'])) {
1622
			$newzone = array();
1623
			$newzone['domain-name'] = $dhcpv6ifconf['ddnsdomain'];
1624
			$newzone['dns-servers'] = array($dhcpv6ifconf['ddnsdomainprimary'], $dhcpv6ifconf['ddnsdomainsecondary']);
1625
			$newzone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1626
			$newzone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1627
			$ddns_zones[] = $newzone;
1628
			if (isset($dhcpv6ifconf['ddnsreverse'])) {
1629
				$ptr_zones = get_v6_ptr_zones($subnetv6, $ifcfgsnv6);
1630
				foreach ($ptr_zones as $ptr_zone) {
1631
					$reversezone = array();
1632
					$reversezone['ptr-domain'] = $ptr_zone;
1633
					$reversezone['dns-servers'] = array($dhcpv6ifconf['ddnsdomainprimary'], $dhcpv6ifconf['ddnsdomainsecondary']);
1634
					$reversezone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1635
					$reversezone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1636
					$ddns_zones[] = $reversezone;
1637
				}
1638
			}
1639
		}
1640

    
1641
		$dhcpdv6conf .= " {\n";
1642

    
1643
		$range_from = $dhcpv6ifconf['range']['from'];
1644
		$range_to = $dhcpv6ifconf['range']['to'];
1645
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
1646
			$range_from = merge_ipv6_delegated_prefix($ifcfgipv6, $range_from, $pdlen);
1647
			$range_to = merge_ipv6_delegated_prefix($ifcfgipv6, $range_to, $pdlen);
1648
		}
1649

    
1650
		if (!empty($dhcpv6ifconf['range']['from']) && !empty($dhcpv6ifconf['range']['to'])) {
1651
			$dhcpdv6conf .= "	range6 {$range_from} {$range_to};\n";
1652
		}
1653

    
1654
		$dhcpdv6conf .= $dnscfgv6;
1655

    
1656
		if (is_ipaddrv6($dhcpv6ifconf['prefixrange']['from']) && is_ipaddrv6($dhcpv6ifconf['prefixrange']['to'])) {
1657
			$dhcpdv6conf .= "	prefix6 {$dhcpv6ifconf['prefixrange']['from']} {$dhcpv6ifconf['prefixrange']['to']} /{$dhcpv6ifconf['prefixrange']['prefixlength']};\n";
1658
		}
1659
		if (is_ipaddrv6($dhcpv6ifconf['dns6ip'])) {
1660
			$dns6ip = $dhcpv6ifconf['dns6ip'];
1661
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1662
			    Net_IPv6::isInNetmask($dns6ip, '::', $pdlen)) {
1663
				$dns6ip = merge_ipv6_delegated_prefix($ifcfgipv6, $dns6ip, $pdlen);
1664
			}
1665
			$dhcpdv6conf .= "	option dhcp6.name-servers {$dns6ip};\n";
1666
		}
1667
		// default-lease-time
1668
		if ($dhcpv6ifconf['defaultleasetime']) {
1669
			$dhcpdv6conf .= "	default-lease-time {$dhcpv6ifconf['defaultleasetime']};\n";
1670
		}
1671

    
1672
		// max-lease-time
1673
		if ($dhcpv6ifconf['maxleasetime']) {
1674
			$dhcpdv6conf .= "	max-lease-time {$dhcpv6ifconf['maxleasetime']};\n";
1675
		}
1676

    
1677
		// ntp-servers
1678
		if (is_array($dhcpv6ifconf['ntpserver']) && $dhcpv6ifconf['ntpserver'][0]) {
1679
			$ntpservers = array();
1680
			foreach ($dhcpv6ifconf['ntpserver'] as $ntpserver) {
1681
				if (!is_ipaddrv6($ntpserver)) {
1682
					continue;
1683
				}
1684
				if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1685
				    Net_IPv6::isInNetmask($ntpserver, '::', $pdlen)) {
1686
					$ntpserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ntpserver, $pdlen);
1687
				}
1688
				$ntpservers[] = $ntpserver;
1689
			}
1690
			if (count($ntpservers) > 0) {
1691
				$dhcpdv6conf .= "        option dhcp6.sntp-servers " . join(",", $dhcpv6ifconf['ntpserver']) . ";\n";
1692
			}
1693
		}
1694
		// tftp-server-name
1695
		/* Needs ISC DHCPD support
1696
		 if ($dhcpv6ifconf['tftp'] <> "") {
1697
			$dhcpdv6conf .= "	option tftp-server-name \"{$dhcpv6ifconf['tftp']}\";\n";
1698
		 }
1699
		*/
1700

    
1701
		// Handle option, number rowhelper values
1702
		$dhcpdv6conf .= "\n";
1703
		if (isset($dhcpv6ifconf['numberoptions']['item']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1704
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1705
				$itemv6_value = base64_decode($itemv6['value']);
1706
				$dhcpdv6conf .= "	option custom-{$dhcpv6if}-{$itemv6idx} \"{$itemv6_value}\";\n";
1707
			}
1708
		}
1709

    
1710
		// ldap-server
1711
		if ($dhcpv6ifconf['ldap'] <> "") {
1712
			$ldapserver = $dhcpv6ifconf['ldap'];
1713
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1714
			    Net_IPv6::isInNetmask($ldapserver, '::', $pdlen)) {
1715
				$ldapserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ldapserver, $pdlen);
1716
			}
1717
			$dhcpdv6conf .= "	option ldap-server \"{$ldapserver}\";\n";
1718
		}
1719

    
1720
		// net boot information
1721
		if (isset($dhcpv6ifconf['netboot'])) {
1722
			if (!empty($dhcpv6ifconf['bootfile_url'])) {
1723
				$dhcpdv6conf .= "	option dhcp6.bootfile-url \"{$dhcpv6ifconf['bootfile_url']}\";\n";
1724
			}
1725
		}
1726

    
1727
		$dhcpdv6conf .= "}\n";
1728

    
1729
		/* add static mappings */
1730
		/* Needs to use DUID */
1731
		if (is_array($dhcpv6ifconf['staticmap'])) {
1732
			$i = 0;
1733
			foreach ($dhcpv6ifconf['staticmap'] as $sm) {
1734
				$dhcpdv6conf .= <<<EOD
1735
host s_{$dhcpv6if}_{$i} {
1736
	host-identifier option dhcp6.client-id {$sm['duid']};
1737

    
1738
EOD;
1739
				if ($sm['ipaddrv6']) {
1740
					$ipaddrv6 = $sm['ipaddrv6'];
1741
					if ($ifcfgv6['ipaddrv6'] == 'track6') {
1742
						$ipaddrv6 = merge_ipv6_delegated_prefix($ifcfgipv6, $ipaddrv6, $pdlen);
1743
					}
1744
					$dhcpdv6conf .= "	fixed-address6 {$ipaddrv6};\n";
1745
				}
1746

    
1747
				if ($sm['hostname']) {
1748
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1749
					$dhhostname = str_replace(".", "_", $dhhostname);
1750
					$dhcpdv6conf .= "	option host-name {$dhhostname};\n";
1751
					if (isset($dhcpv6ifconf['ddnsupdate']) &&
1752
					    isset($dhcpv6ifconf['ddnsforcehostname'])) {
1753
						$dhcpdv6conf .= "	ddns-hostname \"{$dhhostname}\";\n";
1754
					}
1755
				}
1756
				if ($sm['filename']) {
1757
					$dhcpdv6conf .= "	filename \"{$sm['filename']}\";\n";
1758
				}
1759

    
1760
				if ($sm['rootpath']) {
1761
					$dhcpdv6conf .= "	option root-path \"{$sm['rootpath']}\";\n";
1762
				}
1763

    
1764
				$dhcpdv6conf .= "}\n";
1765
				$i++;
1766
			}
1767
		}
1768

    
1769
		if ($dhcpv6ifconf['ddnsdomain']) {
1770
			$dhcpdv6conf .= dhcpdkey($dhcpv6ifconf);
1771
			$dhcpdv6conf .= dhcpdzones($ddns_zones);
1772
		}
1773

    
1774
		if (($config['dhcpdv6'][$dhcpv6if]['ramode'] != "unmanaged") &&
1775
		    (isset($config['interfaces'][$dhcpv6if]['enable']) ||
1776
		    preg_match("/poes/", $dhcpv6if))) {
1777
			if (preg_match("/poes/si", $dhcpv6if)) {
1778
				/* magic here */
1779
				$dhcpdv6ifs = array_merge($dhcpdv6ifs, get_pppoes_child_interfaces($dhcpv6if));
1780
			} else {
1781
				$realif = get_real_interface($dhcpv6if, "inet6");
1782
				if (stristr("$realif", "bridge")) {
1783
					$mac = get_interface_mac($realif);
1784
					$v6address = generate_ipv6_from_mac($mac);
1785
					/* Create link local address for bridges */
1786
					mwexec("/sbin/ifconfig {$realif} inet6 {$v6address}");
1787
				}
1788
				$realif = escapeshellcmd($realif);
1789
				$dhcpdv6ifs[] = $realif;
1790
			}
1791
		}
1792
	}
1793

    
1794
	if ($nsupdate) {
1795
		$dhcpdv6conf .= "ddns-update-style interim;\n";
1796
		$dhcpdv6conf .= "update-static-leases on;\n";
1797
	} else {
1798
		$dhcpdv6conf .= "ddns-update-style none;\n";
1799
	}
1800

    
1801
	/* write dhcpdv6.conf */
1802
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf", $dhcpdv6conf)) {
1803
		log_error("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1804
		if (platform_booting()) {
1805
			printf("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1806
		}
1807
		unset($dhcpdv6conf);
1808
		return 1;
1809
	}
1810
	unset($dhcpdv6conf);
1811

    
1812
	/* create an empty leases v6 database */
1813
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases")) {
1814
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1815
	}
1816

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

    
1821
	/* fire up dhcpd in a chroot */
1822
	if (count($dhcpdv6ifs) > 0) {
1823
		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 " .
1824
			join(" ", $dhcpdv6ifs));
1825
		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");
1826
	}
1827
	if (platform_booting()) {
1828
		print gettext("done.") . "\n";
1829
	}
1830

    
1831
	return 0;
1832
}
1833

    
1834
function services_igmpproxy_configure() {
1835
	global $config, $g;
1836

    
1837
	/* kill any running igmpproxy */
1838
	killbyname("igmpproxy");
1839

    
1840
	if (!isset($config['igmpproxy']['enable'])) {
1841
		return 0;
1842
	}
1843
	if (!is_array($config['igmpproxy']['igmpentry']) || (count($config['igmpproxy']['igmpentry']) == 0)) {
1844
		return 1;
1845
	}
1846

    
1847
	$iflist = get_configured_interface_list();
1848

    
1849
	$igmpconf = <<<EOD
1850

    
1851
##------------------------------------------------------
1852
## Enable Quickleave mode (Sends Leave instantly)
1853
##------------------------------------------------------
1854
quickleave
1855

    
1856
EOD;
1857

    
1858
	foreach ($config['igmpproxy']['igmpentry'] as $igmpcf) {
1859
		unset($iflist[$igmpcf['ifname']]);
1860
		$realif = get_real_interface($igmpcf['ifname']);
1861
		if (empty($igmpcf['threshold'])) {
1862
			$threshld = 1;
1863
		} else {
1864
			$threshld = $igmpcf['threshold'];
1865
		}
1866
		$igmpconf .= "phyint {$realif} {$igmpcf['type']} ratelimit 0 threshold {$threshld}\n";
1867

    
1868
		if ($igmpcf['address'] <> "") {
1869
			$item = explode(" ", $igmpcf['address']);
1870
			foreach ($item as $iww) {
1871
				$igmpconf .= "altnet {$iww}\n";
1872
			}
1873
		}
1874
		$igmpconf .= "\n";
1875
	}
1876
	foreach ($iflist as $ifn) {
1877
		$realif = get_real_interface($ifn);
1878
		$igmpconf .= "phyint {$realif} disabled\n";
1879
	}
1880
	$igmpconf .= "\n";
1881

    
1882
	$igmpfl = fopen($g['varetc_path'] . "/igmpproxy.conf", "w");
1883
	if (!$igmpfl) {
1884
		log_error(gettext("Could not write Igmpproxy configuration file!"));
1885
		return;
1886
	}
1887
	fwrite($igmpfl, $igmpconf);
1888
	fclose($igmpfl);
1889
	unset($igmpconf);
1890

    
1891
	if (isset($config['syslog']['igmpxverbose'])) {
1892
		mwexec_bg("/usr/local/sbin/igmpproxy -v {$g['varetc_path']}/igmpproxy.conf");
1893
	} else {
1894
		mwexec_bg("/usr/local/sbin/igmpproxy {$g['varetc_path']}/igmpproxy.conf");
1895
	}
1896

    
1897
	log_error(gettext("Started IGMP proxy service."));
1898

    
1899
	return 0;
1900
}
1901

    
1902
function services_dhcrelay_configure() {
1903
	global $config, $g;
1904

    
1905
	if (isset($config['system']['developerspew'])) {
1906
		$mt = microtime();
1907
		echo "services_dhcrelay_configure() being called $mt\n";
1908
	}
1909

    
1910
	/* kill any running dhcrelay */
1911
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
1912

    
1913
	init_config_arr(array('dhcrelay'));
1914
	$dhcrelaycfg = &$config['dhcrelay'];
1915

    
1916
	/* DHCPRelay enabled on any interfaces? */
1917
	if (!isset($dhcrelaycfg['enable'])) {
1918
		return 0;
1919
	}
1920

    
1921
	if (platform_booting()) {
1922
		echo gettext("Starting DHCP relay service...");
1923
	} else {
1924
		sleep(1);
1925
	}
1926

    
1927
	$iflist = get_configured_interface_list();
1928

    
1929
	$dhcrelayifs = array();
1930
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1931
	foreach ($dhcifaces as $dhcrelayif) {
1932
		if (!isset($iflist[$dhcrelayif])) {
1933
			continue;
1934
		}
1935

    
1936
		if (get_interface_ip($dhcrelayif)) {
1937
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1938
		}
1939
	}
1940
	$dhcrelayifs = array_unique($dhcrelayifs);
1941

    
1942
	/*
1943
	 * In order for the relay to work, it needs to be active
1944
	 * on the interface in which the destination server sits.
1945
	 */
1946
	$srvips = explode(",", $dhcrelaycfg['server']);
1947
	if (!is_array($srvips)) {
1948
		log_error(gettext("No destination IP has been configured!"));
1949
		return;
1950
	}
1951
	$srvifaces = array();
1952
	foreach ($srvips as $srcidx => $srvip) {
1953
		$destif = guess_interface_from_ip($srvip);
1954
		if (!empty($destif) && !is_pseudo_interface($destif)) {
1955
			$srvifaces[] = $destif;
1956
		}
1957
	}
1958
	$srvifaces = array_unique($srvifaces);
1959

    
1960
	/* Check for relays in the same subnet as clients so they can bind for
1961
	 * either direction (up or down) */
1962
	$srvrelayifs = array_intersect($dhcrelayifs, $srvifaces);
1963

    
1964
	/* The server interface(s) should not be in this list */
1965
	$dhcrelayifs = array_diff($dhcrelayifs, $srvifaces);
1966

    
1967
	/* Remove the dual-role interfaces from up and down lists */
1968
	$srvifaces = array_diff($srvifaces, $srvrelayifs);
1969
	$dhcrelayifs = array_diff($dhcrelayifs, $srvrelayifs);
1970

    
1971
	/* fire up dhcrelay */
1972
	if (empty($dhcrelayifs) && empty($srvrelayifs)) {
1973
		log_error(gettext("No suitable downstream interfaces found for running dhcrelay!"));
1974
		return; /* XXX */
1975
	}
1976
	if (empty($srvifaces) && empty($srvrelayifs)) {
1977
		log_error(gettext("No suitable upstream interfaces found for running dhcrelay!"));
1978
		return; /* XXX */
1979
	}
1980

    
1981
	$cmd = "/usr/local/sbin/dhcrelay";
1982

    
1983
	if (!empty($dhcrelayifs)) {
1984
		$cmd .= " -id " . implode(" -id ", $dhcrelayifs);
1985
	}
1986
	if (!empty($srvifaces)) {
1987
		$cmd .= " -iu " . implode(" -iu ", $srvifaces);
1988
	}
1989
	if (!empty($srvrelayifs)) {
1990
		$cmd .= " -i " . implode(" -i ", $srvrelayifs);
1991
	}
1992

    
1993
	if (isset($dhcrelaycfg['agentoption'])) {
1994
		$cmd .= " -a -m replace";
1995
	}
1996

    
1997
	$cmd .= " " . implode(" ", $srvips);
1998
	mwexec($cmd);
1999
	unset($cmd);
2000

    
2001
	return 0;
2002
}
2003

    
2004
function services_dhcrelay6_configure() {
2005
	global $config, $g;
2006

    
2007
	if (isset($config['system']['developerspew'])) {
2008
		$mt = microtime();
2009
		echo "services_dhcrelay6_configure() being called $mt\n";
2010
	}
2011

    
2012
	/* kill any running dhcrelay */
2013
	killbypid("{$g['varrun_path']}/dhcrelay6.pid");
2014

    
2015
	init_config_arr(array('dhcrelay6'));
2016
	$dhcrelaycfg = &$config['dhcrelay6'];
2017

    
2018
	/* DHCPv6 Relay enabled on any interfaces? */
2019
	if (!isset($dhcrelaycfg['enable'])) {
2020
		return 0;
2021
	}
2022

    
2023
	if (platform_booting()) {
2024
		echo gettext("Starting DHCPv6 relay service...");
2025
	} else {
2026
		sleep(1);
2027
	}
2028

    
2029
	$iflist = get_configured_interface_list();
2030

    
2031
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
2032
	foreach ($dhcifaces as $dhcrelayif) {
2033
		if (!isset($iflist[$dhcrelayif])) {
2034
			continue;
2035
		}
2036

    
2037
		if (get_interface_ipv6($dhcrelayif)) {
2038
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
2039
		}
2040
	}
2041
	$dhcrelayifs = array_unique($dhcrelayifs);
2042

    
2043
	/*
2044
	 * In order for the relay to work, it needs to be active
2045
	 * on the interface in which the destination server sits.
2046
	 */
2047
	$srvips = explode(",", $dhcrelaycfg['server']);
2048
	$srvifaces = array();
2049
	foreach ($srvips as $srcidx => $srvip) {
2050
		$destif = guess_interface_from_ip($srvip);
2051
		if (!empty($destif) && !is_pseudo_interface($destif)) {
2052
			$srvifaces[] = "{$srvip}%{$destif}";
2053
		}
2054
	}
2055

    
2056
	/* fire up dhcrelay */
2057
	if (empty($dhcrelayifs) || empty($srvifaces)) {
2058
		log_error(gettext("No suitable interface found for running dhcrelay -6!"));
2059
		return; /* XXX */
2060
	}
2061

    
2062
	$cmd = "/usr/local/sbin/dhcrelay -6 -pf \"{$g['varrun_path']}/dhcrelay6.pid\"";
2063
	foreach ($dhcrelayifs as $dhcrelayif) {
2064
		$cmd .= " -l {$dhcrelayif}";
2065
	}
2066
	foreach ($srvifaces as $srviface) {
2067
		$cmd .= " -u \"{$srviface}\"";
2068
	}
2069
	mwexec($cmd);
2070
	unset($cmd);
2071

    
2072
	return 0;
2073
}
2074

    
2075
function services_dyndns_configure_client($conf) {
2076

    
2077
	if (!isset($conf['enable'])) {
2078
		return;
2079
	}
2080

    
2081
	/* load up the dyndns.class */
2082
	require_once("dyndns.class");
2083

    
2084
	$dns = new updatedns($dnsService = $conf['type'],
2085
		$dnsHost = $conf['host'],
2086
		$dnsDomain = $conf['domainname'],
2087
		$dnsUser = $conf['username'],
2088
		$dnsPass = $conf['password'],
2089
		$dnsWildcard = $conf['wildcard'],
2090
		$dnsProxied = $conf['proxied'],
2091
		$dnsMX = $conf['mx'],
2092
		$dnsIf = "{$conf['interface']}",
2093
		$dnsBackMX = NULL,
2094
		$dnsServer = NULL,
2095
		$dnsPort = NULL,
2096
		$dnsUpdateURL = "{$conf['updateurl']}",
2097
		$forceUpdate = $conf['force'],
2098
		$dnsZoneID = $conf['zoneid'],
2099
		$dnsTTL = $conf['ttl'],
2100
		$dnsResultMatch = "{$conf['resultmatch']}",
2101
		$dnsRequestIf = "{$conf['requestif']}",
2102
		$dnsID = "{$conf['id']}",
2103
		$dnsVerboseLog = $conf['verboselog'],
2104
		$curlIpresolveV4 = $conf['curl_ipresolve_v4'],
2105
		$curlSslVerifypeer = $conf['curl_ssl_verifypeer']);
2106
}
2107

    
2108
function services_dyndns_configure($int = "") {
2109
	global $config, $g;
2110
	if (isset($config['system']['developerspew'])) {
2111
		$mt = microtime();
2112
		echo "services_dyndns_configure() being called $mt\n";
2113
	}
2114

    
2115
	if (isset($config['dyndnses']['dyndns']) && is_array($config['dyndnses']['dyndns'])) {
2116
		$dyndnscfg = $config['dyndnses']['dyndns'];
2117
	} else {
2118
		return 0;
2119
	}
2120
	$gwgroups = return_gateway_groups_array(true);
2121
	if (is_array($dyndnscfg)) {
2122
		if (platform_booting()) {
2123
			echo gettext("Starting DynDNS clients...");
2124
		}
2125

    
2126
		foreach ($dyndnscfg as $dyndns) {
2127
			/*
2128
			 * If it's using a gateway group, check if interface is
2129
			 * the active gateway for that group
2130
			 */
2131
			$group_int = '';
2132
			$friendly_group_int = '';
2133
			$gwgroup_member = false;
2134
			if (is_array($gwgroups[$dyndns['interface']])) {
2135
				if (!empty($gwgroups[$dyndns['interface']][0]['vip'])) {
2136
					$group_int = $gwgroups[$dyndns['interface']][0]['vip'];
2137
				} else {
2138
					$group_int = $gwgroups[$dyndns['interface']][0]['int'];
2139
					$friendly_group_int =
2140
					    convert_real_interface_to_friendly_interface_name(
2141
						$group_int);
2142
					if (!empty($int)) {
2143
						$gwgroup_member =
2144
						    interface_gateway_group_member(get_real_interface($int),
2145
						    $dyndns['interface']);
2146
					}
2147
				}
2148
			}
2149
			if ((empty($int)) || ($int == $dyndns['interface']) || $gwgroup_member ||
2150
			    ($int == $group_int) || ($int == $friendly_group_int)) {
2151
				$dyndns['verboselog'] = isset($dyndns['verboselog']);
2152
				$dyndns['curl_ipresolve_v4'] = isset($dyndns['curl_ipresolve_v4']);
2153
				$dyndns['curl_ssl_verifypeer'] = isset($dyndns['curl_ssl_verifypeer']);
2154
				$dyndns['proxied'] = isset($dyndns['proxied']);
2155
				services_dyndns_configure_client($dyndns);
2156
				sleep(1);
2157
			}
2158
		}
2159

    
2160
		if (platform_booting()) {
2161
			echo gettext("done.") . "\n";
2162
		}
2163
	}
2164

    
2165
	return 0;
2166
}
2167

    
2168
function dyndnsCheckIP($int) {
2169
	global $config, $factory_default_checkipservice;
2170
	$ip_address = get_interface_ip($int);
2171
	if (is_private_ip($ip_address)) {
2172
		$gateways_status = return_gateways_status(true);
2173
		// If the gateway for this interface is down, then the external check cannot work.
2174
		// Avoid the long wait for the external check to timeout.
2175
		if (stristr($gateways_status[$config['interfaces'][$int]['gateway']]['status'], "down")) {
2176
			return "down";
2177
		}
2178

    
2179
		// Append the factory default check IP service to the list (if not disabled).
2180
		if (!isset($config['checkipservices']['disable_factory_default'])) {
2181
			if (!is_array($config['checkipservices'])) {
2182
				$config['checkipservices'] = array();
2183
			}
2184
			if (!is_array($config['checkipservices']['checkipservice'])) {
2185
				$config['checkipservices']['checkipservice'] = array();
2186
			}
2187
			$config['checkipservices']['checkipservice'][] = $factory_default_checkipservice;
2188
		}
2189

    
2190
		// Use the first enabled check IP service as the default.
2191
		if (is_array($config['checkipservices']['checkipservice'])) {
2192
			foreach ($config['checkipservices']['checkipservice'] as $i => $checkipservice) {
2193
				if (isset($checkipservice['enable'])) {
2194
					$url = $checkipservice['url'];
2195
					$username = $checkipservice['username'];
2196
					$password = $checkipservice['password'];
2197
					$verifysslpeer = isset($checkipservice['verifysslpeer']);
2198
					break;
2199
				}
2200
			}
2201
		}
2202

    
2203
		$hosttocheck = $url;
2204
		$ip_ch = curl_init($hosttocheck);
2205
		curl_setopt($ip_ch, CURLOPT_RETURNTRANSFER, 1);
2206
		curl_setopt($ip_ch, CURLOPT_SSL_VERIFYPEER, $verifysslpeer);
2207
		curl_setopt($ip_ch, CURLOPT_INTERFACE, 'host!' . $ip_address);
2208
		curl_setopt($ip_ch, CURLOPT_CONNECTTIMEOUT, '30');
2209
		curl_setopt($ip_ch, CURLOPT_TIMEOUT, 120);
2210
		curl_setopt($ip_ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
2211
		curl_setopt($ip_ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
2212
		curl_setopt($ip_ch, CURLOPT_USERPWD, "{$username}:{$password}");
2213
		$ip_result_page = curl_exec($ip_ch);
2214
		curl_close($ip_ch);
2215
		$ip_result_decoded = urldecode($ip_result_page);
2216
		preg_match('=Current IP Address: (.*)</body>=siU', $ip_result_decoded, $matches);
2217
		$ip_address = trim($matches[1]);
2218
	}
2219
	return $ip_address;
2220
}
2221

    
2222
function services_dnsmasq_configure($restart_dhcp = true) {
2223
	global $config, $g;
2224
	$return = 0;
2225

    
2226
	// hard coded args: will be removed to avoid duplication if specified in custom_options
2227
	$standard_args = array(
2228
		"dns-forward-max" => "--dns-forward-max=5000",
2229
		"cache-size" => "--cache-size=10000",
2230
		"local-ttl" => "--local-ttl=1"
2231
	);
2232

    
2233

    
2234
	if (isset($config['system']['developerspew'])) {
2235
		$mt = microtime();
2236
		echo "services_dnsmasq_configure() being called $mt\n";
2237
	}
2238

    
2239
	/* kill any running dnsmasq */
2240
	if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) {
2241
		sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
2242
	}
2243

    
2244
	if (isset($config['dnsmasq']['enable'])) {
2245

    
2246
		if (platform_booting()) {
2247
			echo gettext("Starting DNS forwarder...");
2248
		} else {
2249
			sleep(1);
2250
		}
2251

    
2252
		/* generate hosts file */
2253
		if (system_hosts_generate() != 0) {
2254
			$return = 1;
2255
		}
2256

    
2257
		$args = "";
2258

    
2259
		if (isset($config['dnsmasq']['regdhcp'])) {
2260
			$args .= " --dhcp-hostsfile={$g['etc_path']}/hosts ";
2261
		}
2262

    
2263
		/* Setup listen port, if non-default */
2264
		if (is_port($config['dnsmasq']['port'])) {
2265
			$args .= " --port={$config['dnsmasq']['port']} ";
2266
		}
2267

    
2268
		$listen_addresses = "";
2269
		if (isset($config['dnsmasq']['interface'])) {
2270
			$interfaces = explode(",", $config['dnsmasq']['interface']);
2271
			foreach ($interfaces as $interface) {
2272
				$if = get_real_interface($interface);
2273
				if (does_interface_exist($if)) {
2274
					$laddr = get_interface_ip($interface);
2275
					if (is_ipaddrv4($laddr)) {
2276
						$listen_addresses .= " --listen-address={$laddr} ";
2277
					}
2278
					$laddr6 = get_interface_ipv6($interface);
2279
					if (is_ipaddrv6($laddr6) && !isset($config['dnsmasq']['strictbind'])) {
2280
						/*
2281
						 * XXX: Since dnsmasq does not support link-local address
2282
						 * with scope specified. These checks are being done.
2283
						 */
2284
						if (is_linklocal($laddr6) && strstr($laddr6, "%")) {
2285
							$tmpaddrll6 = explode("%", $laddr6);
2286
							$listen_addresses .= " --listen-address={$tmpaddrll6[0]} ";
2287
						} else {
2288
							$listen_addresses .= " --listen-address={$laddr6} ";
2289
						}
2290
					}
2291
				}
2292
			}
2293
			if (!empty($listen_addresses)) {
2294
				$args .= " {$listen_addresses} ";
2295
				if (isset($config['dnsmasq']['strictbind'])) {
2296
					$args .= " --bind-interfaces ";
2297
				}
2298
			}
2299
		}
2300

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

    
2308
			// Build an array of domain overrides to help in checking for matches.
2309
			$override_a = array();
2310
			if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2311
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2312
					$override_a[$override['domain']] = "y";
2313
				}
2314
			}
2315

    
2316
			// Build an array of the private reverse lookup domain names
2317
			$reverse_domain_a = array("10.in-addr.arpa", "168.192.in-addr.arpa");
2318
			// Unfortunately the 172.16.0.0/12 range does not map nicely to the in-addr.arpa scheme.
2319
			for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) {
2320
				$reverse_domain_a[] = "$subnet_num.172.in-addr.arpa";
2321
			}
2322

    
2323
			// Set the --server parameter to nowhere for each reverse domain name that was not specifically specified in a domain override.
2324
			foreach ($reverse_domain_a as $reverse_domain) {
2325
				if (!isset($override_a[$reverse_domain])) {
2326
					$args .= " --server=/$reverse_domain/ ";
2327
				}
2328
			}
2329
			unset($override_a);
2330
			unset($reverse_domain_a);
2331
		}
2332

    
2333
		/* Setup forwarded domains */
2334
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2335
			foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2336
				if ($override['ip'] == "!") {
2337
					$override[ip] = "";
2338
				}
2339
				$args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
2340
			}
2341
		}
2342

    
2343
		/* Allow DNS Rebind for forwarded domains */
2344
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2345
			if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2346
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2347
					$args .= ' --rebind-domain-ok=/' . $override['domain'] . '/ ';
2348
				}
2349
			}
2350
		}
2351

    
2352
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2353
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2354
		}
2355

    
2356
		if (isset($config['dnsmasq']['strict_order'])) {
2357
			$args .= " --strict-order ";
2358
		}
2359

    
2360
		if (isset($config['dnsmasq']['domain_needed'])) {
2361
			$args .= " --domain-needed ";
2362
		}
2363

    
2364
		if ($config['dnsmasq']['custom_options']) {
2365
			foreach (preg_split('/\s+/', $config['dnsmasq']['custom_options']) as $c) {
2366
				$args .= " " . escapeshellarg("--{$c}");
2367
				$p = explode('=', $c);
2368
				if (array_key_exists($p[0], $standard_args)) {
2369
					unset($standard_args[$p[0]]);
2370
				}
2371
			}
2372
		}
2373
		$args .= ' ' . implode(' ', array_values($standard_args));
2374

    
2375
		/* run dnsmasq. Use "-C /dev/null" since we use command line args only (Issue #6730) */
2376
		$cmd = "/usr/local/sbin/dnsmasq --all-servers -C /dev/null {$dns_rebind} {$args}";
2377
		//log_error("dnsmasq command: {$cmd}");
2378
		mwexec_bg($cmd);
2379
		unset($args);
2380

    
2381
		system_dhcpleases_configure();
2382

    
2383
		if (platform_booting()) {
2384
			echo gettext("done.") . "\n";
2385
		}
2386
	}
2387

    
2388
	if (!platform_booting() && $restart_dhcp) {
2389
		if (services_dhcpd_configure() != 0) {
2390
			$return = 1;
2391
		}
2392
	}
2393

    
2394
	return $return;
2395
}
2396

    
2397
function services_unbound_configure($restart_dhcp = true) {
2398
	global $config, $g;
2399
	$return = 0;
2400

    
2401
	if (isset($config['system']['developerspew'])) {
2402
		$mt = microtime();
2403
		echo "services_unbound_configure() being called $mt\n";
2404
	}
2405

    
2406
	if (isset($config['unbound']['enable'])) {
2407
		require_once('/etc/inc/unbound.inc');
2408

    
2409
		/* Stop Unbound using TERM */
2410
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2411
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
2412
		}
2413

    
2414
		/* If unbound is still running, wait up to 30 seconds for it to terminate. */
2415
		for ($i=1; $i <= 30; $i++) {
2416
			if (is_process_running('unbound')) {
2417
				sleep(1);
2418
			}
2419
		}
2420

    
2421
		$python_mode = false;
2422
		if (isset($config['unbound']['python']) && !empty($config['unbound']['python_script'])) {
2423
			$python_mode = true;
2424
		}
2425

    
2426
		/* Include any additional functions as defined by python script include file */
2427
		if (file_exists("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc")) {
2428
			exec("/usr/local/bin/php -l " . escapeshellarg("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc")
2429
				. " 2>&1", $py_output, $py_retval);
2430
			if ($py_retval == 0) {
2431
				require_once("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc");
2432
			}
2433
		}
2434

    
2435
		/* DNS Resolver python integration */
2436
		if ($python_mode) {
2437
			if (!is_dir("{$g['unbound_chroot_path']}/dev")) {
2438
				safe_mkdir("{$g['unbound_chroot_path']}/dev");
2439
			}
2440
			exec("/sbin/mount -t devfs devfs " . escapeshellarg("{$g['unbound_chroot_path']}/dev"));
2441
		} else {
2442
			if (is_dir("{$g['unbound_chroot_path']}/dev")) {
2443
				exec("/sbin/umount -f " . escapeshellarg("{$g['unbound_chroot_path']}/dev"));
2444
			}
2445
		}
2446
		$base_folder = '/usr/local';
2447
		foreach (array('/bin', '/lib') as $dir) {
2448
			$validate = exec("/sbin/mount | /usr/bin/grep " . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir} (nullfs") . " 2>&1");
2449
			if ($python_mode) {
2450

    
2451
				// Add DNS Resolver python integration
2452
				if (empty($validate)) {
2453
					if (!is_dir("{$g['unbound_chroot_path']}{$base_folder}{$dir}")) {
2454
						safe_mkdir("{$g['unbound_chroot_path']}{$base_folder}{$dir}");
2455
					}
2456
					$output = $retval = '';
2457
					exec("/sbin/mount_nullfs -o ro " . escapeshellarg("/usr/local{$dir}") . ' '
2458
					    . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir}") . " 2>&1", $output, $retval);
2459

    
2460
					// Disable Unbound python on mount failure
2461
					if ($retval != 0) {
2462
						$config['unbound']['python'] = '';
2463
						$log_msg = "[Unbound-pymod]: Disabling Unbound python due to failed mount";
2464
						write_config($log_msg);
2465
						log_error($log_msg);
2466
					}
2467
				}
2468
			}
2469

    
2470
			// Remove DNS Resolver python integration
2471
			elseif (!empty($validate)) {
2472
				exec("/sbin/umount -t nullfs " . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir}") . " 2>&1", $output, $retval);
2473
				if ($retval == 0) {
2474
					foreach (array( "/usr/local{$dir}", '/usr/local', '/usr') as $folder) {
2475
						if (!empty($g['unbound_chroot_path']) && $g['unbound_chroot_path'] != '/' && is_dir("{$g['unbound_chroot_path']}{$folder}")) {
2476
							@rmdir(escapeshellarg("{$g['unbound_chroot_path']}{$folder}"));
2477
						}
2478

    
2479
						// Delete remaining subfolders on next loop
2480
						if ($dir == '/bin') {
2481
							break;
2482
						}
2483
					}
2484
				}
2485
				else {
2486
					log_error("[Unbound-pymod]: Failed to unmount!");
2487
				}
2488
			}
2489
		}
2490

    
2491
		if (platform_booting()) {
2492
			echo gettext("Starting DNS Resolver...");
2493
		} else {
2494
			sleep(1);
2495
		}
2496

    
2497
		/* generate hosts file */
2498
		if (system_hosts_generate() != 0) {
2499
			$return = 1;
2500
		}
2501

    
2502
		/* Check here for dhcp6 complete - wait upto 10 seconds */
2503
		if($config['interfaces']["wan"]['ipaddrv6'] == 'dhcp6') {
2504
			$wanif = get_real_interface("wan", "inet6");
2505
			if (platform_booting()) {
2506
				for ($i=1; $i <= 10; $i++) {
2507
					if (!file_exists("/tmp/{$wanif}_dhcp6_complete")) {
2508
						log_error(gettext("Unbound start waiting on dhcp6c."));
2509
						sleep(1);
2510
					} else {
2511
						unlink_if_exists("/tmp/{$wanif}_dhcp6_complete");
2512
						log_error(gettext("dhcp6 init complete. Continuing"));
2513
						break;
2514
					}
2515
				}
2516
			}
2517
		}
2518

    
2519
		sync_unbound_service();
2520
		if (platform_booting()) {
2521
			log_error(gettext("sync unbound done."));
2522
			echo gettext("done.") . "\n";
2523
		}
2524

    
2525
		system_dhcpleases_configure();
2526
	} else {
2527
		/* kill Unbound since it should not be enabled */
2528
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2529
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "KILL");
2530
		}
2531
	}
2532

    
2533
	if (!platform_booting() && $restart_dhcp) {
2534
		if (services_dhcpd_configure() != 0) {
2535
			$return = 1;
2536
		}
2537
	}
2538

    
2539
	return $return;
2540
}
2541

    
2542
function services_snmpd_configure() {
2543
	global $config, $g;
2544
	if (isset($config['system']['developerspew'])) {
2545
		$mt = microtime();
2546
		echo "services_snmpd_configure() being called $mt\n";
2547
	}
2548

    
2549
	/* kill any running snmpd */
2550
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
2551
	sleep(2);
2552
	if (is_process_running("bsnmpd")) {
2553
		mwexec("/usr/bin/killall bsnmpd", true);
2554
	}
2555

    
2556
	if (isset($config['snmpd']['enable'])) {
2557

    
2558
		if (platform_booting()) {
2559
			echo gettext("Starting SNMP daemon... ");
2560
		}
2561

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

    
2567
		/* generate snmpd.conf */
2568
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
2569
		if (!$fd) {
2570
			printf(gettext("Error: cannot open snmpd.conf in services_snmpd_configure().%s"), "\n");
2571
			return 1;
2572
		}
2573

    
2574

    
2575
		$snmpdconf = <<<EOD
2576
location := "{$config['snmpd']['syslocation']}"
2577
contact := "{$config['snmpd']['syscontact']}"
2578
read := "{$config['snmpd']['rocommunity']}"
2579

    
2580
EOD;
2581

    
2582
/* No docs on what write strings do there so disable for now.
2583
		if (isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])) {
2584
			$snmpdconf .= <<<EOD
2585
# write string
2586
write := "{$config['snmpd']['rwcommunity']}"
2587

    
2588
EOD;
2589
		}
2590
*/
2591

    
2592

    
2593
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2594
			$snmpdconf .= <<<EOD
2595
# SNMP Trap support.
2596
traphost := {$config['snmpd']['trapserver']}
2597
trapport := {$config['snmpd']['trapserverport']}
2598
trap := "{$config['snmpd']['trapstring']}"
2599

    
2600

    
2601
EOD;
2602
		}
2603

    
2604
		$sysDescr = "{$g['product_label']} {$config['system']['hostname']}.{$config['system']['domain']}" .
2605
			" {$g['product_version_string']} " . php_uname("s") .
2606
			" " . php_uname("r") . " " . php_uname("m");
2607

    
2608
		$snmpdconf .= <<<EOD
2609
system := 1     # pfSense
2610
%snmpd
2611
sysDescr			= "{$sysDescr}"
2612
begemotSnmpdDebugDumpPdus       = 2
2613
begemotSnmpdDebugSyslogPri      = 7
2614
begemotSnmpdCommunityString.0.1 = $(read)
2615

    
2616
EOD;
2617

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

    
2623
EOD;
2624
		}
2625
*/
2626

    
2627

    
2628
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2629
			$snmpdconf .= <<<EOD
2630
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
2631
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
2632
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
2633

    
2634
EOD;
2635
		}
2636

    
2637

    
2638
		$snmpdconf .= <<<EOD
2639
begemotSnmpdCommunityDisable    = 1
2640

    
2641
EOD;
2642

    
2643
		$bind_to_ips = array();
2644
		if (isset($config['snmpd']['bindip'])) {
2645
			foreach (explode(",", $config['snmpd']['bindip']) as $bind_to_ip) {
2646
				if (is_ipaddr($bind_to_ip)) {
2647
					$bind_to_ips[] = $bind_to_ip;
2648
				} else {
2649
					$if = get_real_interface($bind_to_ip);
2650
					if (does_interface_exist($if)) {
2651
						$bindip = get_interface_ip($bind_to_ip);
2652
						if (is_ipaddr($bindip)) {
2653
							$bind_to_ips[] = $bindip;
2654
						}
2655
					}
2656
				}
2657
			}
2658
		}
2659
		if (!count($bind_to_ips)) {
2660
			$bind_to_ips = array("0.0.0.0");
2661
		}
2662

    
2663
		if (is_port($config['snmpd']['pollport'])) {
2664
			foreach ($bind_to_ips as $bind_to_ip) {
2665
				$snmpdconf .= <<<EOD
2666
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
2667

    
2668
EOD;
2669

    
2670
			}
2671
		}
2672

    
2673
		$snmpdconf .= <<<EOD
2674
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
2675
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
2676

    
2677
# These are bsnmp macros not php vars.
2678
sysContact      = $(contact)
2679
sysLocation     = $(location)
2680
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
2681

    
2682
snmpEnableAuthenTraps = 2
2683

    
2684
EOD;
2685

    
2686
		if (is_array($config['snmpd']['modules'])) {
2687
			if (isset($config['snmpd']['modules']['mibii'])) {
2688
			$snmpdconf .= <<<EOD
2689
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
2690

    
2691
EOD;
2692
			}
2693

    
2694
			if (isset($config['snmpd']['modules']['netgraph'])) {
2695
				$snmpdconf .= <<<EOD
2696
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
2697
%netgraph
2698
begemotNgControlNodeName = "snmpd"
2699

    
2700
EOD;
2701
			}
2702

    
2703
			if (isset($config['snmpd']['modules']['pf'])) {
2704
				$snmpdconf .= <<<EOD
2705
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
2706

    
2707
EOD;
2708
			}
2709

    
2710
			if (isset($config['snmpd']['modules']['hostres'])) {
2711
				$snmpdconf .= <<<EOD
2712
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
2713

    
2714
EOD;
2715
			}
2716

    
2717
			if (isset($config['snmpd']['modules']['bridge'])) {
2718
				$snmpdconf .= <<<EOD
2719
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
2720
# config must end with blank line
2721

    
2722
EOD;
2723
			}
2724
			if (isset($config['snmpd']['modules']['ucd'])) {
2725
				$snmpdconf .= <<<EOD
2726
begemotSnmpdModulePath."ucd"     = "/usr/local/lib/snmp_ucd.so"
2727

    
2728
EOD;
2729
			}
2730
			if (isset($config['snmpd']['modules']['regex'])) {
2731
				$snmpdconf .= <<<EOD
2732
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"
2733

    
2734
EOD;
2735
			}
2736
		}
2737

    
2738
		fwrite($fd, $snmpdconf);
2739
		fclose($fd);
2740
		unset($snmpdconf);
2741

    
2742
		/* run bsnmpd */
2743
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
2744
			" -p {$g['varrun_path']}/snmpd.pid");
2745

    
2746
		if (platform_booting()) {
2747
			echo gettext("done.") . "\n";
2748
		}
2749
	}
2750

    
2751
	return 0;
2752
}
2753

    
2754
function services_dnsupdate_process($int = "", $updatehost = "", $forced = false) {
2755
	global $config, $g;
2756
	if (isset($config['system']['developerspew'])) {
2757
		$mt = microtime();
2758
		echo "services_dnsupdate_process() being called $mt\n";
2759
	}
2760

    
2761
	/* Dynamic DNS updating active? */
2762
	if (!is_array($config['dnsupdates']['dnsupdate'])) {
2763
		return 0;
2764
	}
2765

    
2766
	$notify_text = "";
2767
	$gwgroups = return_gateway_groups_array(true);
2768
	foreach ($config['dnsupdates']['dnsupdate'] as $i => $dnsupdate) {
2769
		if (!isset($dnsupdate['enable'])) {
2770
			continue;
2771
		}
2772
		/*
2773
		 * If it's using a gateway group, check if interface is
2774
		 * the active gateway for that group
2775
		 */
2776
		$group_int = '';
2777
		$friendly_group_int = '';
2778
		$gwgroup_member = false;
2779
		if (is_array($gwgroups[$dnsupdate['interface']])) {
2780
			if (!empty($gwgroups[$dnsupdate['interface']][0]['vip'])) {
2781
				$group_int = $gwgroups[$dnsupdate['interface']][0]['vip'];
2782
			} else {
2783
				$group_int = $gwgroups[$dnsupdate['interface']][0]['int'];
2784
				$friendly_group_int =
2785
				    convert_real_interface_to_friendly_interface_name(
2786
					$group_int);
2787
				if (!empty($int)) {
2788
					$gwgroup_member =
2789
					    interface_gateway_group_member(get_real_interface($int),
2790
					    $dnsupdate['interface']);
2791
				}
2792
			}
2793
		}
2794
		if (!empty($int) && ($int != $dnsupdate['interface']) && !$gwgroup_member &&
2795
		    ($int != $group_int) && ($int != $friendly_group_int)) {
2796
			continue;
2797
		}
2798
		if (!empty($updatehost) && ($updatehost != $dnsupdate['host'])) {
2799
			continue;
2800
		}
2801

    
2802
		/* determine interface name */
2803
		$if = get_failover_interface($dnsupdate['interface']);
2804

    
2805
		/* Determine address to update and default binding address */
2806
		if (isset($dnsupdate['usepublicip'])) {
2807
			$wanip = dyndnsCheckIP($if);
2808
			$bindipv4 = get_interface_ip($if);
2809
		} else {
2810
			$wanip = get_interface_ip($if);
2811
			$bindipv4 = $wanip;
2812
		}
2813
		if (is_stf_interface($dnsupdate['interface'])) { 
2814
			$wanipv6 = get_interface_ipv6($dnsupdate['interface'] . '_stf');
2815
		} else {
2816
			$wanipv6 = get_interface_ipv6($if);
2817
		}
2818
		$bindipv6 = $wanipv6;
2819

    
2820
		/* Handle non-default interface bindings */
2821
		if ($dnsupdate['updatesource'] == "none") {
2822
			/* When empty, the directive will be omitted. */
2823
			$bindipv4 = "";
2824
			$bindipv6 = "";
2825
		} elseif (!empty($dnsupdate['updatesource'])) {
2826
			/* Find the alternate binding address */
2827
			$bindipv4 = get_interface_ip($dnsupdate['updatesource']);
2828
			if (is_stf_interface($dnsupdate['interface'])) { 
2829
				$bindipv6 = get_interface_ipv6($dnsupdate['updatesource'] . '_stf');
2830
			} else {
2831
				$bindipv6 = get_interface_ipv6($dnsupdate['updatesource']);
2832
			}
2833
		}
2834

    
2835
		/* Handle IPv4/IPv6 selection for the update source interface/VIP */
2836
		switch ($dnsupdate['updatesourcefamily']) {
2837
			case "inet":
2838
				$bindip = $bindipv4;
2839
				break;
2840
			case "inet6":
2841
				$bindip = $bindipv6;
2842
				break;
2843
			case "":
2844
			default:
2845
				/* Try IPv4 first, if that is empty, try IPv6. */
2846
				/* Only specify the address if it's present, otherwise omit. */
2847
				if (!empty($bindipv4)) {
2848
					$bindip = $bindipv4;
2849
				} elseif (!empty($bindipv6)) {
2850
					$bindip = $bindipv6;
2851
				}
2852
				break;
2853
		}
2854

    
2855
		$cacheFile = $g['conf_path'] .
2856
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2857
		    escapeshellarg($dnsupdate['host']) .
2858
		    "_{$dnsupdate['server']}.cache";
2859
		$cacheFilev6 = $g['conf_path'] .
2860
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2861
		    escapeshellarg($dnsupdate['host']) .
2862
		    "_{$dnsupdate['server']}_v6.cache";
2863
		$currentTime = time();
2864

    
2865
		if (!$wanip && !$wanipv6) {
2866
			continue;
2867
		}
2868

    
2869
		$keyname = $dnsupdate['keyname'];
2870
		/* trailing dot */
2871
		if (substr($keyname, -1) != ".") {
2872
			$keyname .= ".";
2873
		}
2874

    
2875
		$hostname = $dnsupdate['host'];
2876
		/* trailing dot */
2877
		if (substr($hostname, -1) != ".") {
2878
			$hostname .= ".";
2879
		}
2880

    
2881
		/* write key file */
2882
		$algorithm = empty($dnsupdate['keyalgorithm']) ? 'hmac-md5' : $dnsupdate['keyalgorithm'];
2883
		$upkey = <<<EOD
2884
key "{$keyname}" {
2885
	algorithm {$algorithm};
2886
	secret "{$dnsupdate['keydata']}";
2887
};
2888

    
2889
EOD;
2890
		@file_put_contents("{$g['varetc_path']}/nsupdatekey{$i}", $upkey);
2891

    
2892
		/* generate update instructions */
2893
		$upinst = "";
2894
		if (!empty($dnsupdate['server'])) {
2895
			$upinst .= "server {$dnsupdate['server']}\n";
2896
		}
2897

    
2898
		if (!empty($dnsupdate['zone'])) {
2899
			$upinst .= "zone {$dnsupdate['zone']}\n";
2900
		}
2901

    
2902
		$cachedipv4 = '';
2903
		$cacheTimev4 = 0;
2904
		if (file_exists($cacheFile)) {
2905
			list($cachedipv4, $cacheTimev4) = explode("|",
2906
			    file_get_contents($cacheFile));
2907
		}
2908
		$cachedipv6 = '';
2909
		$cacheTimev6 = 0;
2910
		if (file_exists($cacheFilev6)) {
2911
			list($cachedipv6, $cacheTimev6) = explode("|",
2912
			    file_get_contents($cacheFilev6));
2913
		}
2914

    
2915
		// 25 Days
2916
		$maxCacheAgeSecs = 25 * 24 * 60 * 60;
2917
		$need_update = false;
2918

    
2919
		/* Update IPv4 if we have it. */
2920
		if (is_ipaddrv4($wanip) && $dnsupdate['recordtype'] != "AAAA") {
2921
			if (($wanip != $cachedipv4) || $forced ||
2922
			    (($currentTime - $cacheTimev4) > $maxCacheAgeSecs)) {
2923
				$upinst .= "update delete " .
2924
				    "{$dnsupdate['host']}. A\n";
2925
				$upinst .= "update add {$dnsupdate['host']}. " .
2926
				    "{$dnsupdate['ttl']} A {$wanip}\n";
2927
				if (!empty($bindip)) {
2928
					$upinst .= "local {$bindip}\n";
2929
				}
2930
				$need_update = true;
2931
			} else {
2932
				log_error(sprintf(gettext(
2933
				    "phpDynDNS: Not updating %s A record because the IP address has not changed."),
2934
				    $dnsupdate['host']));
2935
			}
2936
		} else {
2937
			@unlink($cacheFile);
2938
			unset($cacheFile);
2939
		}
2940

    
2941
		/* Update IPv6 if we have it. */
2942
		if (is_ipaddrv6($wanipv6) && $dnsupdate['recordtype'] != "A") {
2943
			if (($wanipv6 != $cachedipv6) || $forced ||
2944
			    (($currentTime - $cacheTimev6) > $maxCacheAgeSecs)) {
2945
				$upinst .= "update delete " .
2946
				    "{$dnsupdate['host']}. AAAA\n";
2947
				$upinst .= "update add {$dnsupdate['host']}. " .
2948
				    "{$dnsupdate['ttl']} AAAA {$wanipv6}\n";
2949
				$need_update = true;
2950
			} else {
2951
				log_error(sprintf(gettext(
2952
				    "phpDynDNS: Not updating %s AAAA record because the IPv6 address has not changed."),
2953
				    $dnsupdate['host']));
2954
			}
2955
		} else {
2956
			@unlink($cacheFilev6);
2957
			unset($cacheFilev6);
2958
		}
2959

    
2960
		$upinst .= "\n";	/* mind that trailing newline! */
2961

    
2962
		if (!$need_update) {
2963
			continue;
2964
		}
2965

    
2966
		@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}", $upinst);
2967
		unset($upinst);
2968
		/* invoke nsupdate */
2969
		$cmd = "/usr/local/bin/nsupdate -k {$g['varetc_path']}/nsupdatekey{$i}";
2970

    
2971
		if (isset($dnsupdate['usetcp'])) {
2972
			$cmd .= " -v";
2973
		}
2974

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

    
2977
		if (mwexec($cmd) == 0) {
2978
			if (!empty($cacheFile)) {
2979
				@file_put_contents($cacheFile,
2980
				    "{$wanip}|{$currentTime}");
2981
				log_error(sprintf(gettext(
2982
				    'phpDynDNS: updating cache file %1$s: %2$s'),
2983
				    $cacheFile, $wanip));
2984
				$notify_text .= sprintf(gettext(
2985
				    'DynDNS updated IP Address (A) for %1$s on %2$s (%3$s) to %4$s'),
2986
				    $dnsupdate['host'],
2987
				    convert_real_interface_to_friendly_descr($if),
2988
				    $if, $wanip) . "\n";
2989
			}
2990
			if (!empty($cacheFilev6)) {
2991
				@file_put_contents($cacheFilev6,
2992
				    "{$wanipv6}|{$currentTime}");
2993
				log_error(sprintf(gettext(
2994
				    'phpDynDNS: updating cache file %1$s: %2$s'),
2995
				    $cacheFilev6, $wanipv6));
2996
				$notify_text .= sprintf(gettext(
2997
				    'DynDNS updated IPv6 Address (AAAA) for %1$s on %2$s (%3$s) to %4$s'),
2998
				    $dnsupdate['host'],
2999
				    convert_real_interface_to_friendly_descr($if),
3000
				    $if, $wanipv6) . "\n";
3001
			}
3002
		} else {
3003
			if (!empty($cacheFile)) {
3004
				log_error(sprintf(gettext(
3005
				    'phpDynDNS: ERROR while updating IP Address (A) for %1$s (%2$s)'),
3006
				    $dnsupdate['host'], $wanip));
3007
			}
3008
			if (!empty($cacheFilev6)) {
3009
				log_error(sprintf(gettext(
3010
				    'phpDynDNS: ERROR while updating IP Address (AAAA) for %1$s (%2$s)'),
3011
				    $dnsupdate['host'], $wanipv6));
3012
			}
3013
		}
3014
		unset($cmd);
3015
	}
3016

    
3017
	if (!empty($notify_text)) {
3018
		notify_all_remote($notify_text);
3019
	}
3020

    
3021
	return 0;
3022
}
3023

    
3024
/* configure cron service */
3025
function configure_cron() {
3026
	global $g, $config;
3027

    
3028
	/* preserve existing crontab entries */
3029
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
3030

    
3031
	for ($i = 0; $i < count($crontab_contents); $i++) {
3032
		$cron_item = &$crontab_contents[$i];
3033
		if (strpos($cron_item, "# pfSense specific crontab entries") !== false) {
3034
			array_splice($crontab_contents, $i - 1);
3035
			break;
3036
		}
3037
	}
3038
	$crontab_contents = implode("\n", $crontab_contents) . "\n";
3039

    
3040

    
3041
	if (is_array($config['cron']['item'])) {
3042
		$crontab_contents .= "#\n";
3043
		$crontab_contents .= "# pfSense specific crontab entries\n";
3044
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
3045
		$crontab_contents .= "#\n";
3046

    
3047
		if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) {
3048
			$http_proxy = $config['system']['proxyurl'];
3049
			if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) {
3050
				$http_proxy .= ':' . $config['system']['proxyport'];
3051
			}
3052
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
3053

    
3054
			if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
3055
				$crontab_contents .= "HTTP_PROXY_AUTH=basic:*:{$config['system']['proxyuser']}:{$config['system']['proxypass']}";
3056
			}
3057
		}
3058

    
3059
		foreach ($config['cron']['item'] as $item) {
3060
			$crontab_contents .= "\n{$item['minute']}\t";
3061
			$crontab_contents .= "{$item['hour']}\t";
3062
			$crontab_contents .= "{$item['mday']}\t";
3063
			$crontab_contents .= "{$item['month']}\t";
3064
			$crontab_contents .= "{$item['wday']}\t";
3065
			$crontab_contents .= "{$item['who']}\t";
3066
			$crontab_contents .= "{$item['command']}";
3067
		}
3068

    
3069
		$crontab_contents .= "\n#\n";
3070
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
3071
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
3072
		$crontab_contents .= "#\n\n";
3073
	}
3074

    
3075
	/* please maintain the newline at the end of file */
3076
	file_put_contents("/etc/crontab", $crontab_contents);
3077
	unset($crontab_contents);
3078

    
3079
	/* make sure that cron is running and start it if it got killed somehow */
3080
	if (!is_process_running("cron")) {
3081
		exec("cd /tmp && /usr/sbin/cron -s 2>/dev/null");
3082
	} else {
3083
	/* do a HUP kill to force sync changes */
3084
		sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP");
3085
	}
3086

    
3087
}
3088

    
3089
function upnp_action ($action) {
3090
	global $g, $config;
3091
	switch ($action) {
3092
		case "start":
3093
			if (file_exists('/var/etc/miniupnpd.conf')) {
3094
				@unlink("{$g['varrun_path']}/miniupnpd.pid");
3095
				mwexec_bg("/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf -P {$g['varrun_path']}/miniupnpd.pid");
3096
			}
3097
			break;
3098
		case "stop":
3099
			killbypid("{$g['varrun_path']}/miniupnpd.pid");
3100
			while ((int)exec("/bin/pgrep -a miniupnpd | wc -l") > 0) {
3101
				mwexec('/usr/bin/killall miniupnpd 2>/dev/null', true);
3102
			}
3103
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
3104
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
3105
			break;
3106
		case "restart":
3107
			upnp_action('stop');
3108
			upnp_action('start');
3109
			break;
3110
	}
3111
}
3112

    
3113
function upnp_start() {
3114
	global $config;
3115

    
3116
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
3117
		return;
3118
	}
3119

    
3120
	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
3121
		echo gettext("Starting UPnP service... ");
3122
		require_once('/usr/local/pkg/miniupnpd.inc');
3123
		sync_package_miniupnpd();
3124
		echo "done.\n";
3125
	}
3126
}
3127

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

    
3131
	$is_installed = false;
3132
	$cron_changed = true;
3133
	$change_message = "";
3134

    
3135
	if (!is_array($config['cron'])) {
3136
		$config['cron'] = array();
3137
	}
3138
	if (!is_array($config['cron']['item'])) {
3139
		$config['cron']['item'] = array();
3140
	}
3141

    
3142
	$x = 0;
3143
	foreach ($config['cron']['item'] as $item) {
3144
		if (strstr($item['command'], $command)) {
3145
			$is_installed = true;
3146
			break;
3147
		}
3148
		$x++;
3149
	}
3150

    
3151
	if ($active) {
3152
		$cron_item = array();
3153
		$cron_item['minute'] = $minute;
3154
		$cron_item['hour'] = $hour;
3155
		$cron_item['mday'] = $monthday;
3156
		$cron_item['month'] = $month;
3157
		$cron_item['wday'] = $weekday;
3158
		$cron_item['who'] = $who;
3159
		$cron_item['command'] = $command;
3160
		if (!$is_installed) {
3161
			$config['cron']['item'][] = $cron_item;
3162
			$change_message = "Installed cron job for %s";
3163
		} else {
3164
			if ($config['cron']['item'][$x] == $cron_item) {
3165
				$cron_changed = false;
3166
			} else {
3167
				$config['cron']['item'][$x] = $cron_item;
3168
				$change_message = "Updated cron job for %s";
3169
			}
3170
		}
3171
	} else {
3172
		if ($is_installed == true) {
3173
			array_splice($config['cron']['item'], $x, 1);
3174
			$change_message = "Removed cron job for %s";
3175
		} else {
3176
			$cron_changed = false;
3177
		}
3178
	}
3179

    
3180
	if ($cron_changed) {
3181
		/* Optionally write the configuration if this function made changes.
3182
		 * Performing a write_config() in this way can have unintended side effects. See #7146
3183
		 * Base system instances of this function do not need to write, packages may.
3184
		 */
3185
		if ($write_config) {
3186
			write_config(sprintf(gettext($change_message), $command));
3187
		}
3188
		configure_cron();
3189
	}
3190
}
3191

    
3192
?>
(46-46/61)