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 || $rasrcaddr) {
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

    
255
		if ($rasrcaddr) {
256
			$radvdconf .= "\t\tRemoveRoute off;\n";
257
		}
258
		else {
259
			$radvdconf .= "\t\tRemoveRoute on;\n";
260
		}
261
		$radvdconf .= "\t};\n";
262

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

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

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

    
345
		$realif = get_real_interface($if, "inet6");
346

    
347
		/* prevent duplicate entries, manual overrides */
348
		if (isset($radvdifs[$realif])) {
349
			continue;
350
		}
351

    
352
		$ifcfgipv6 = get_interface_ipv6($if);
353
		if (!is_ipaddrv6($ifcfgipv6)) {
354
			$subnetv6 = "::";
355
			$ifcfgsnv6 = "64";
356
		} else {
357
			$ifcfgsnv6 = get_interface_subnetv6($if);
358
			$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
359
		}
360
		$radvdifs[$realif] = $realif;
361

    
362
		$autotype = $config['interfaces'][$trackif]['ipaddrv6'];
363

    
364
		if ($g['debug']) {
365
			log_error("configuring RA on {$if} for type {$autotype} radvd subnet {$subnetv6}/{$ifcfgsnv6}");
366
		}
367

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

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

    
418
	/* write radvd.conf */
419
	if (!@file_put_contents("{$g['varetc_path']}/radvd.conf", $radvdconf)) {
420
		log_error(gettext("Error: cannot open radvd.conf in services_radvd_configure()."));
421
		if (platform_booting()) {
422
			printf("Error: cannot open radvd.conf in services_radvd_configure().\n");
423
		}
424
	}
425
	unset($radvdconf);
426

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

    
445
function services_dhcpd_configure($family = "all", $blacklist = array()) {
446
	global $config, $g;
447

    
448
	$dhcpdconfigurelck = lock("dhcpdconfigure", LOCK_EX);
449

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

    
466
	$status = `/sbin/mount | /usr/bin/grep -v grep | /usr/bin/grep "{$g['dhcpd_chroot_path']}/dev"`;
467
	if (!trim($status)) {
468
		fwrite($fd, "/sbin/mount -t devfs devfs {$g['dhcpd_chroot_path']}/dev\n");
469
	}
470
	fclose($fd);
471
	mwexec("/bin/sh {$g['tmp_path']}/dhcpd.sh");
472

    
473
	if ($family == "all" || $family == "inet") {
474
		services_dhcpdv4_configure();
475
	}
476
	if ($family == "all" || $family == "inet6") {
477
		services_dhcpdv6_configure($blacklist);
478
		services_radvd_configure($blacklist);
479
	}
480

    
481
	unlock($dhcpdconfigurelck);
482
}
483

    
484
function services_dhcpdv4_configure() {
485
	global $config, $g;
486
	$need_ddns_updates = false;
487
	$ddns_zones = array();
488

    
489
	if ($g['services_dhcp_server_enable'] == false) {
490
		return;
491
	}
492

    
493
	if (isset($config['system']['developerspew'])) {
494
		$mt = microtime();
495
		echo "services_dhcpdv4_configure($if) being called $mt\n";
496
	}
497

    
498
	/* kill any running dhcpd */
499
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid")) {
500
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid");
501
	}
502

    
503
	/* DHCP enabled on any interfaces? */
504
	if (!is_dhcp_server_enabled()) {
505
		return 0;
506
	}
507

    
508
	$syscfg = $config['system'];
509
	if (!is_array($config['dhcpd'])) {
510
		$config['dhcpd'] = array();
511
	}
512
	$dhcpdcfg = $config['dhcpd'];
513
	$Iflist = get_configured_interface_list();
514

    
515
	/* Only consider DNS servers with IPv4 addresses for the IPv4 DHCP server. */
516
	$dns_arrv4 = array();
517
	if (is_array($syscfg['dnsserver'])) {
518
		foreach ($syscfg['dnsserver'] as $dnsserver) {
519
			if (is_ipaddrv4($dnsserver)) {
520
				$dns_arrv4[] = $dnsserver;
521
			}
522
		}
523
	}
524

    
525
	if (platform_booting()) {
526
		echo gettext("Starting DHCP service...");
527
	} else {
528
		sleep(1);
529
	}
530

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

    
575
	$dhcpdconf = <<<EOD
576

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

    
589
EOD;
590

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

    
599
		if (isset($dhcpifconf['alwaysbroadcast'])) {
600
			$dhcpdconf .= "always-broadcast on\n";
601
		}
602

    
603
		// OMAPI Settings
604
		if (isset($dhcpifconf['omapi_port']) && is_numeric($dhcpifconf['omapi_port'])) {
605
			$dhcpdconf .= <<<EOD
606

    
607
key omapi_key {
608
  algorithm {$dhcpifconf['omapi_key_algorithm']};
609
  secret "{$dhcpifconf['omapi_key']}";
610
};
611
omapi-port {$dhcpifconf['omapi_port']};
612
omapi-key omapi_key;
613

    
614
EOD;
615

    
616
		}
617
		break;
618
	}
619

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

    
632
	/*    loop through and determine if we need to setup
633
	 *    failover peer "bleh" entries
634
	 */
635
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
636

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

    
641
		interfaces_staticarp_configure($dhcpif);
642

    
643
		if (!isset($dhcpifconf['enable'])) {
644
			continue;
645
		}
646

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

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

    
707
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
708

    
709
		$newzone = array();
710
		$ifcfg = $config['interfaces'][$dhcpif];
711

    
712
		if (!isset($dhcpifconf['enable']) || !isset($Iflist[$dhcpif])) {
713
			continue;
714
		}
715
		$ifcfgip = get_interface_ip($dhcpif);
716
		$ifcfgsn = get_interface_subnet($dhcpif);
717
		$subnet = gen_subnet($ifcfgip, $ifcfgsn);
718
		$subnetmask = gen_subnet_mask($ifcfgsn);
719

    
720
		if (!is_ipaddr($subnet)) {
721
			continue;
722
		}
723

    
724
		$all_pools = array();
725
		$all_pools[] = $dhcpifconf;
726
		if (is_array($dhcpifconf['pool'])) {
727
			$all_pools = array_merge($all_pools, $dhcpifconf['pool']);
728
		}
729

    
730
		$dnscfg = "";
731

    
732
		if ($dhcpifconf['domain']) {
733
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
734
		}
735

    
736
		if ($dhcpifconf['domainsearchlist'] <> "") {
737
			$dnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpifconf['domainsearchlist'])) . "\";\n";
738
		}
739

    
740
		if (isset($dhcpifconf['ddnsupdate'])) {
741
			$need_ddns_updates = true;
742
			$newzone = array();
743
			if ($dhcpifconf['ddnsdomain'] <> "") {
744
				$newzone['domain-name'] = $dhcpifconf['ddnsdomain'];
745
				$dnscfg .= "	ddns-domainname \"{$dhcpifconf['ddnsdomain']}\";\n";
746
			} else {
747
				$newzone['domain-name'] = $config['system']['domain'];
748
			}
749

    
750
			if (empty($dhcpifconf['ddnsclientupdates'])) {
751
				$ddnsclientupdates = 'allow';
752
			} else {
753
				$ddnsclientupdates = $dhcpifconf['ddnsclientupdates'];
754
			}
755

    
756
			$dnscfg .= "	{$ddnsclientupdates} client-updates;\n";
757

    
758
			$revsubnet = array_reverse(explode('.',$subnet));
759

    
760
			$subnet_mask_bits = 32 - $ifcfgsn;
761
			$start_octet = $subnet_mask_bits >> 3;
762
			$octet_mask_bits = $subnet_mask_bits & ($subnet_mask_bits % 8);
763
			if ($octet_mask_bits) {
764
			    $octet_mask = (1 << $octet_mask_bits) - 1;
765
			    $octet_start = $revsubnet[$start_octet] & ~$octet_mask;
766
			    $revsubnet[$start_octet] = $octet_start . "-" . ($octet_start + $octet_mask);
767
			}
768

    
769
			$ptr_domain = '';
770
			for ($octet = 0; $octet <= 3; $octet++) {
771
				if ($octet < $start_octet) {
772
					continue;
773
				}
774
				$ptr_domain .= ((empty($ptr_domain) && $ptr_domain !== "0") ? '' : '.');
775
				$ptr_domain .= $revsubnet[$octet];
776
			}
777
			$ptr_domain .= ".in-addr.arpa";
778
			$newzone['ptr-domain'] = $ptr_domain;
779
			unset($ptr_domain, $revsubnet, $start_octet);
780
		}
781

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

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

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

    
828
		$dhcpdconf .= "subnet {$subnet} netmask {$subnetmask} {\n";
829

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

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

    
895
			if ($poolconf['failover_peerip'] <> "") {
896
				$dhcpdconf .= "		$deny_action dynamic bootp clients;\n";
897
			}
898

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

    
911
			if ($poolconf['gateway'] && $poolconf['gateway'] != "none" && ($poolconf['gateway'] != $dhcpifconf['gateway'])) {
912
				$dhcpdconf .= "		option routers {$poolconf['gateway']};\n";
913
			}
914

    
915
			if ($dhcpifconf['failover_peerip'] <> "") {
916
				$dhcpdconf .= "		failover peer \"dhcp_{$dhcpif}\";\n";
917
			}
918

    
919
			$pdnscfg = "";
920

    
921
			if ($poolconf['domain'] && ($poolconf['domain'] != $dhcpifconf['domain'])) {
922
				$pdnscfg .= "		option domain-name \"{$poolconf['domain']}\";\n";
923
			}
924

    
925
			if (!empty($poolconf['domainsearchlist']) && ($poolconf['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
926
				$pdnscfg .= "		option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $poolconf['domainsearchlist'])) . "\";\n";
927
			}
928

    
929
			if (isset($poolconf['ddnsupdate'])) {
930
				if (($poolconf['ddnsdomain'] <> "") && ($poolconf['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
931
					$pdnscfg .= "		ddns-domainname \"{$poolconf['ddnsdomain']}\";\n";
932
				}
933
				$pdnscfg .= "		ddns-update-style interim;\n";
934
			}
935

    
936
			$dhcpdconf .= "{$pdnscfg}";
937

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

    
943
			// max-lease-time
944
			if ($poolconf['maxleasetime'] && ($poolconf['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
945
				$dhcpdconf .= "		max-lease-time {$poolconf['maxleasetime']};\n";
946
			}
947

    
948
			// ignore bootp
949
			if (isset($poolconf['ignorebootp'])) {
950
				$dhcpdconf .= "		ignore bootp;\n";
951
			}
952

    
953
			// ignore-client-uids
954
			if (isset($poolconf['ignoreclientuids'])) {
955
				$dhcpdconf .= "		ignore-client-uids true;\n";
956
			}
957

    
958
			// netbios-name*
959
			if (is_array($poolconf['winsserver']) && $poolconf['winsserver'][0] && ($poolconf['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
960
				$dhcpdconf .= "		option netbios-name-servers " . join(",", $poolconf['winsserver']) . ";\n";
961
				$dhcpdconf .= "		option netbios-node-type 8;\n";
962
			}
963

    
964
			// ntp-servers
965
			if (is_array($poolconf['ntpserver']) && $poolconf['ntpserver'][0] && ($poolconf['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
966
				$dhcpdconf .= "		option ntp-servers " . join(",", $poolconf['ntpserver']) . ";\n";
967
			}
968

    
969
			// tftp-server-name
970
			if (!empty($poolconf['tftp']) && ($poolconf['tftp'] != $dhcpifconf['tftp'])) {
971
				$dhcpdconf .= "		option tftp-server-name \"{$poolconf['tftp']}\";\n";
972
			}
973

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

    
991
			// ldap-server
992
			if (!empty($poolconf['ldap']) && ($poolconf['ldap'] != $dhcpifconf['ldap'])) {
993
				$dhcpdconf .= "		option ldap-server \"{$poolconf['ldap']}\";\n";
994
			}
995

    
996
			// net boot information
997
			if (isset($poolconf['netboot'])) {
998
				if (!empty($poolconf['nextserver']) && ($poolconf['nextserver'] != $dhcpifconf['nextserver'])) {
999
					$dhcpdconf .= "		next-server {$poolconf['nextserver']};\n";
1000
				}
1001

    
1002
				if (!empty($poolconf['filename']) &&
1003
				    (!isset($dhcpifconf['filename']) ||
1004
				    ($poolconf['filename'] != $dhcpifconf['filename']))) {
1005
					$filename = $poolconf['filename'];
1006
				}
1007
				if (!empty($poolconf['filename32']) &&
1008
				    (!isset($dhcpifconf['filename32']) ||
1009
				    ($poolconf['filename32'] != $dhcpifconf['filename32']))) {
1010
					$filename32 = $poolconf['filename32'];
1011
				}
1012
				if (!empty($poolconf['filename64']) &&
1013
				    (!isset($dhcpifconf['filename64']) ||
1014
				    ($poolconf['filename64'] != $dhcpifconf['filename64']))) {
1015
					$filename64 = $poolconf['filename64'];
1016
				}
1017
				if (!empty($poolconf['filename32arm']) &&
1018
				    (!isset($dhcpifconf['filename32arm']) ||
1019
				    ($poolconf['filename32arm'] != $dhcpifconf['filename32arm']))) {
1020
					$filename32arm = $poolconf['filename32arm'];
1021
				}
1022
				if (!empty($poolconf['filename64arm']) &&
1023
				    (!isset($dhcpifconf['filename64arm']) ||
1024
				    ($poolconf['filename64arm'] != $dhcpifconf['filename64arm']))) {
1025
					$filename64arm = $poolconf['filename64arm'];
1026
				}
1027

    
1028
				if (!empty($filename32) || !empty($filename64) || !empty($filename32arm) || !empty($filename64arm)) {
1029
					if (empty($filename) && !empty($dhcpifconf['filename'])) {
1030
						$filename = $dhcpifconf['filename'];
1031
					}
1032
					if (empty($filename32) && !empty($dhcpifconf['filename32'])) {
1033
						$filename32 = $dhcpifconf['filename32'];
1034
					}
1035
					if (empty($filename64) && !empty($dhcpifconf['filename64'])) {
1036
						$filename64 = $dhcpifconf['filename64'];
1037
					}
1038
					if (empty($filename32arm) && !empty($dhcpifconf['filename32arm'])) {
1039
						$filename32arm = $dhcpifconf['filename32arm'];
1040
					}
1041
					if (empty($filename64arm) && !empty($dhcpifconf['filename64arm'])) {
1042
						$filename64arm = $dhcpifconf['filename64arm'];
1043
					}
1044
				}
1045

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

    
1065
				if (!empty($poolconf['rootpath']) && ($poolconf['rootpath'] != $dhcpifconf['rootpath'])) {
1066
					$dhcpdconf .= "		option root-path \"{$poolconf['rootpath']}\";\n";
1067
				}
1068
			}
1069
			$dhcpdconf .= "		range {$poolconf['range']['from']} {$poolconf['range']['to']};\n";
1070
			$dhcpdconf .= "	}\n\n";
1071
		}
1072
// End of settings inside pools
1073

    
1074
		if ($dhcpifconf['gateway'] && $dhcpifconf['gateway'] != "none") {
1075
			$routers = $dhcpifconf['gateway'];
1076
			$add_routers = true;
1077
		} elseif ($dhcpifconf['gateway'] == "none") {
1078
			$add_routers = false;
1079
		} else {
1080
			$add_routers = $enable_add_routers;
1081
			$routers = $ifcfgip;
1082
		}
1083
		if ($add_routers) {
1084
			$dhcpdconf .= "	option routers {$routers};\n";
1085
		}
1086

    
1087
		$dhcpdconf .= <<<EOD
1088
$dnscfg
1089

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

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

    
1101
		if (!isset($dhcpifconf['disablepingcheck'])) {
1102
			$dhcpdconf .= "	ping-check true;\n";
1103
		} else {
1104
			$dhcpdconf .= "	ping-check false;\n";
1105
		}
1106

    
1107
		// netbios-name*
1108
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
1109
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
1110
			$dhcpdconf .= "	option netbios-node-type 8;\n";
1111
		}
1112

    
1113
		// ntp-servers
1114
		if (is_array($dhcpifconf['ntpserver']) && $dhcpifconf['ntpserver'][0]) {
1115
			$dhcpdconf .= "	option ntp-servers " . join(",", $dhcpifconf['ntpserver']) . ";\n";
1116
		}
1117

    
1118
		// tftp-server-name
1119
		if ($dhcpifconf['tftp'] <> "") {
1120
			$dhcpdconf .= "	option tftp-server-name \"{$dhcpifconf['tftp']}\";\n";
1121
		}
1122

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

    
1136
		// ldap-server
1137
		if ($dhcpifconf['ldap'] <> "") {
1138
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
1139
		}
1140

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

    
1164
		$dhcpdconf .= <<<EOD
1165
}
1166

    
1167
EOD;
1168

    
1169
		/* add static mappings */
1170
		if (is_array($dhcpifconf['staticmap'])) {
1171

    
1172
			$i = 0;
1173
			$sm_newzone[] = array();
1174
			$need_sm_ddns_updates = false;
1175
			foreach ($dhcpifconf['staticmap'] as $sm) {
1176
				$cid = '';
1177
				$dhcpdconf .= "host s_{$dhcpif}_{$i} {\n";
1178

    
1179
				if ($sm['mac']) {
1180
					$dhcpdconf .= "	hardware ethernet {$sm['mac']};\n";
1181
				}
1182

    
1183
				if ($sm['cid']) {
1184
					$cid = str_replace('"', '\"', $sm['cid']);
1185
					$dhcpdconf .= "	option dhcp-client-identifier \"{$cid}\";\n";
1186
				}
1187

    
1188
				if ($sm['ipaddr']) {
1189
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
1190
				}
1191

    
1192
				if ($sm['hostname']) {
1193
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1194
					$dhhostname = str_replace(".", "_", $dhhostname);
1195
					$dhcpdconf .= "	option host-name \"{$dhhostname}\";\n";
1196
					if ((isset($dhcpifconf['ddnsupdate']) || isset($sm['ddnsupdate'])) && (isset($dhcpifconf['ddnsforcehostname']) || isset($sm['ddnsforcehostname']))) {
1197
						$dhcpdconf .= "	ddns-hostname \"{$dhhostname}\";\n";
1198
					}
1199
				}
1200
				if ($sm['filename']) {
1201
					$dhcpdconf .= "	filename \"{$sm['filename']}\";\n";
1202
				}
1203

    
1204
				if ($sm['rootpath']) {
1205
					$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1206
				}
1207

    
1208
				if ($sm['gateway'] && ($sm['gateway'] != $dhcpifconf['gateway'])) {
1209
					$dhcpdconf .= "	option routers {$sm['gateway']};\n";
1210
				}
1211

    
1212
				$smdnscfg = "";
1213

    
1214
				if ($sm['domain'] && ($sm['domain'] != $dhcpifconf['domain'])) {
1215
					$smdnscfg .= "	option domain-name \"{$sm['domain']}\";\n";
1216
				}
1217

    
1218
				if (!empty($sm['domainsearchlist']) && ($sm['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
1219
					$smdnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $sm['domainsearchlist'])) . "\";\n";
1220
				}
1221

    
1222
				if (isset($sm['ddnsupdate'])) {
1223
					if (($sm['ddnsdomain'] <> "") && ($sm['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
1224
						$smdnscfg .= "	ddns-domainname \"{$sm['ddnsdomain']}\";\n";
1225
				 		$need_sm_ddns_updates = true;	
1226
					}
1227
					$smdnscfg .= "	ddns-update-style interim;\n";
1228
				}
1229

    
1230
				if (is_array($sm['dnsserver']) && ($sm['dnsserver'][0]) && ($sm['dnsserver'][0] != $dhcpifconf['dnsserver'][0])) {
1231
					$smdnscfg .= "	option domain-name-servers " . join(",", $sm['dnsserver']) . ";\n";
1232
				}
1233
				$dhcpdconf .= "{$smdnscfg}";
1234

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

    
1240
				// max-lease-time
1241
				if ($sm['maxleasetime'] && ($sm['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
1242
					$dhcpdconf .= "	max-lease-time {$sm['maxleasetime']};\n";
1243
				}
1244

    
1245
				// netbios-name*
1246
				if (is_array($sm['winsserver']) && $sm['winsserver'][0] && ($sm['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
1247
					$dhcpdconf .= "	option netbios-name-servers " . join(",", $sm['winsserver']) . ";\n";
1248
					$dhcpdconf .= "	option netbios-node-type 8;\n";
1249
				}
1250

    
1251
				// ntp-servers
1252
				if (is_array($sm['ntpserver']) && $sm['ntpserver'][0] && ($sm['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
1253
					$dhcpdconf .= "	option ntp-servers " . join(",", $sm['ntpserver']) . ";\n";
1254
				}
1255

    
1256
				// tftp-server-name
1257
				if (!empty($sm['tftp']) && ($sm['tftp'] != $dhcpifconf['tftp'])) {
1258
					$dhcpdconf .= "	option tftp-server-name \"{$sm['tftp']}\";\n";
1259
				}
1260

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

    
1274
				// ldap-server
1275
				if (!empty($sm['ldap']) && ($sm['ldap'] != $dhcpifconf['ldap'])) {
1276
					$dhcpdconf .= "	option ldap-server \"{$sm['ldap']}\";\n";
1277
				}
1278

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

    
1302
				$dhcpdconf .= "}\n";
1303

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

    
1324
				// subclass for DHCP limiting
1325
				if (!empty($sm['mac'])) {
1326
					// assuming ALL addresses are ethernet hardware type ("1:" prefix)
1327
					$dhcpdconf .= "subclass \"s_{$dhcpif}\" 1:{$sm['mac']};\n";
1328
				}
1329
				if (!empty($cid)) {
1330
					$dhcpdconf .= "subclass \"s_{$dhcpif}\" \"{$cid}\";\n";
1331
				}
1332

    
1333

    
1334
				$i++;
1335
			}
1336
		}
1337

    
1338
		$dhcpdifs[] = get_real_interface($dhcpif);
1339
		if ($newzone['domain-name']) {
1340
			if ($need_ddns_updates) {
1341
				$newzone['dns-servers'] = array($dhcpifconf['ddnsdomainprimary'], $dhcpifconf['ddnsdomainsecondary']);
1342
				$newzone['ddnsdomainkeyname'] = $dhcpifconf['ddnsdomainkeyname'];
1343
				$newzone['ddnsdomainkeyalgorithm'] = $dhcpifconf['ddnsdomainkeyalgorithm'];
1344
				$newzone['ddnsdomainkey'] = $dhcpifconf['ddnsdomainkey'];
1345
				$dhcpdconf .= dhcpdkey($dhcpifconf);
1346
			}
1347
			$ddns_zones[] = $newzone;
1348
		}
1349
	}
1350

    
1351
	if ($need_ddns_updates) {
1352
		$dhcpdconf .= "ddns-update-style interim;\n";
1353
		$dhcpdconf .= "update-static-leases on;\n";
1354

    
1355
		$dhcpdconf .= dhcpdzones($ddns_zones);
1356
	}
1357

    
1358
	/* write dhcpd.conf */
1359
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpd.conf", $dhcpdconf)) {
1360
		printf(gettext("Error: cannot open dhcpd.conf in services_dhcpdv4_configure().%s"), "\n");
1361
		unset($dhcpdconf);
1362
		return 1;
1363
	}
1364
	unset($dhcpdconf);
1365

    
1366
	/* create an empty leases database */
1367
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
1368
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
1369
	}
1370

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

    
1375
	/* fire up dhcpd in a chroot */
1376
	if (count($dhcpdifs) > 0) {
1377
		mwexec("/usr/local/sbin/dhcpd -user dhcpd -group _dhcp -chroot {$g['dhcpd_chroot_path']} -cf /etc/dhcpd.conf -pf {$g['varrun_path']}/dhcpd.pid " .
1378
			join(" ", $dhcpdifs));
1379
	}
1380

    
1381
	if (platform_booting()) {
1382
		print "done.\n";
1383
	}
1384

    
1385
	return 0;
1386
}
1387

    
1388
function dhcpdkey($dhcpifconf) {
1389
	$dhcpdconf = "";
1390
	if (!empty($dhcpifconf['ddnsdomainkeyname']) && !empty($dhcpifconf['ddnsdomainkey'])) {
1391
		$algorithm = empty($dhcpifconf['ddnsdomainkeyalgorithm']) ? 'hmac-md5' : $dhcpifconf['ddnsdomainkeyalgorithm'];
1392
		$dhcpdconf .= "key \"{$dhcpifconf['ddnsdomainkeyname']}\" {\n";
1393
		$dhcpdconf .= "	algorithm {$algorithm};\n";
1394
		$dhcpdconf .= "	secret {$dhcpifconf['ddnsdomainkey']};\n";
1395
		$dhcpdconf .= "}\n";
1396
	}
1397

    
1398
	return $dhcpdconf;
1399
}
1400

    
1401
function dhcpdzones($ddns_zones) {
1402
	$dhcpdconf = "";
1403

    
1404
	if (is_array($ddns_zones)) {
1405
		$added_zones = array();
1406
		foreach ($ddns_zones as $zone) {
1407
			if (!is_array($zone) || empty($zone) || !is_array($zone['dns-servers'])) {
1408
				continue;
1409
			}
1410
			$primary = $zone['dns-servers'][0];
1411
			$secondary = empty($zone['dns-servers'][1]) ? "" : $zone['dns-servers'][1];
1412

    
1413
			// Make sure we aren't using any invalid servers.
1414
			if (!is_ipaddr($primary)) {
1415
				if (is_ipaddr($secondary)) {
1416
					$primary = $secondary;
1417
					$secondary = "";
1418
				} else {
1419
					continue;
1420
				}
1421
			}
1422

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

    
1463
	return $dhcpdconf;
1464
}
1465

    
1466
function services_dhcpdv6_configure($blacklist = array()) {
1467
	global $config, $g;
1468

    
1469
	if ($g['services_dhcp_server_enable'] == false) {
1470
		return;
1471
	}
1472

    
1473
	if (isset($config['system']['developerspew'])) {
1474
		$mt = microtime();
1475
		echo "services_dhcpd_configure($if) being called $mt\n";
1476
	}
1477

    
1478
	/* kill any running dhcpd */
1479
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid")) {
1480
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid");
1481
	}
1482
	if (isvalidpid("{$g['varrun_path']}/dhcpleases6.pid")) {
1483
		killbypid("{$g['varrun_path']}/dhcpleases6.pid");
1484
	}
1485

    
1486
	/* DHCP enabled on any interfaces? */
1487
	if (!is_dhcpv6_server_enabled()) {
1488
		return 0;
1489
	}
1490

    
1491
	$syscfg = $config['system'];
1492
	if (!is_array($config['dhcpdv6'])) {
1493
		$config['dhcpdv6'] = array();
1494
	}
1495
	$dhcpdv6cfg = $config['dhcpdv6'];
1496
	$Iflist = get_configured_interface_list();
1497
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
1498

    
1499

    
1500
	if (platform_booting()) {
1501
		echo "Starting DHCPv6 service...";
1502
	} else {
1503
		sleep(1);
1504
	}
1505

    
1506
	$custoptionsv6 = "";
1507
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1508
		if (is_array($dhcpv6ifconf['numberoptions']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1509
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1510
				$custoptionsv6 .= "option custom-{$dhcpv6if}-{$itemv6idx} code {$itemv6['number']} = text;\n";
1511
			}
1512
		}
1513
	}
1514

    
1515
	if (isset($dhcpv6ifconf['netboot']) && !empty($dhcpv6ifconf['bootfile_url'])) {
1516
		$custoptionsv6 .= "option dhcp6.bootfile-url code 59 = string;\n";
1517
	}
1518

    
1519
	$dhcpdv6conf = <<<EOD
1520

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

    
1533
EOD;
1534

    
1535
	if (!isset($dhcpv6ifconf['disableauthoritative'])) {
1536
		$dhcpdv6conf .= "authoritative;\n";
1537
	}
1538

    
1539
	if (isset($dhcpv6ifconf['alwaysbroadcast'])) {
1540
		$dhcpdv6conf .= "always-broadcast on\n";
1541
	}
1542

    
1543
	$dhcpdv6ifs = array();
1544

    
1545
	$dhcpv6num = 0;
1546
	$nsupdate = false;
1547

    
1548
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1549

    
1550
		$ddns_zones = array();
1551

    
1552
		$ifcfgv6 = $config['interfaces'][$dhcpv6if];
1553

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

    
1570
		$dnscfgv6 = "";
1571

    
1572
		if ($dhcpv6ifconf['domain']) {
1573
			$dnscfgv6 .= "	option domain-name \"{$dhcpv6ifconf['domain']}\";\n";
1574
		}
1575

    
1576
		if ($dhcpv6ifconf['domainsearchlist'] <> "") {
1577
			$dnscfgv6 .= "	option dhcp6.domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpv6ifconf['domainsearchlist'])) . "\";\n";
1578
		}
1579

    
1580
		if (isset($dhcpv6ifconf['ddnsupdate'])) {
1581
			if ($dhcpv6ifconf['ddnsdomain'] <> "") {
1582
				$dnscfgv6 .= "	ddns-domainname \"{$dhcpv6ifconf['ddnsdomain']}\";\n";
1583
			}
1584
			if (empty($dhcpv6ifconf['ddnsclientupdates'])) {
1585
				$ddnsclientupdates = 'allow';
1586
			} else {
1587
				$ddnsclientupdates = $dhcpv6ifconf['ddnsclientupdates'];
1588
			}
1589
			$dnscfgv6 .= "	{$ddnsclientupdates} client-updates;\n";
1590
			$nsupdate = true;
1591
		} else {
1592
			$dnscfgv6 .= "	do-forward-updates false;\n";
1593
		}
1594

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

    
1619
		if (!is_ipaddrv6($ifcfgipv6)) {
1620
			$ifcfgsnv6 = "64";
1621
			$subnetv6 = gen_subnetv6($dhcpv6ifconf['range']['from'], $ifcfgsnv6);
1622
		}
1623

    
1624
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1625

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

    
1647
		$dhcpdv6conf .= " {\n";
1648

    
1649
		$range_from = $dhcpv6ifconf['range']['from'];
1650
		$range_to = $dhcpv6ifconf['range']['to'];
1651
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
1652
			$range_from = merge_ipv6_delegated_prefix($ifcfgipv6, $range_from, $pdlen);
1653
			$range_to = merge_ipv6_delegated_prefix($ifcfgipv6, $range_to, $pdlen);
1654
		}
1655

    
1656
		if (!empty($dhcpv6ifconf['range']['from']) && !empty($dhcpv6ifconf['range']['to'])) {
1657
			$dhcpdv6conf .= "	range6 {$range_from} {$range_to};\n";
1658
		}
1659

    
1660
		$dhcpdv6conf .= $dnscfgv6;
1661

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

    
1678
		// max-lease-time
1679
		if ($dhcpv6ifconf['maxleasetime']) {
1680
			$dhcpdv6conf .= "	max-lease-time {$dhcpv6ifconf['maxleasetime']};\n";
1681
		}
1682

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

    
1707
		// Handle option, number rowhelper values
1708
		$dhcpdv6conf .= "\n";
1709
		if (isset($dhcpv6ifconf['numberoptions']['item']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1710
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1711
				$itemv6_value = base64_decode($itemv6['value']);
1712
				$dhcpdv6conf .= "	option custom-{$dhcpv6if}-{$itemv6idx} \"{$itemv6_value}\";\n";
1713
			}
1714
		}
1715

    
1716
		// ldap-server
1717
		if ($dhcpv6ifconf['ldap'] <> "") {
1718
			$ldapserver = $dhcpv6ifconf['ldap'];
1719
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1720
			    Net_IPv6::isInNetmask($ldapserver, '::', $pdlen)) {
1721
				$ldapserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ldapserver, $pdlen);
1722
			}
1723
			$dhcpdv6conf .= "	option ldap-server \"{$ldapserver}\";\n";
1724
		}
1725

    
1726
		// net boot information
1727
		if (isset($dhcpv6ifconf['netboot'])) {
1728
			if (!empty($dhcpv6ifconf['bootfile_url'])) {
1729
				$dhcpdv6conf .= "	option dhcp6.bootfile-url \"{$dhcpv6ifconf['bootfile_url']}\";\n";
1730
			}
1731
		}
1732

    
1733
		$dhcpdv6conf .= "}\n";
1734

    
1735
		/* add static mappings */
1736
		/* Needs to use DUID */
1737
		if (is_array($dhcpv6ifconf['staticmap'])) {
1738
			$i = 0;
1739
			foreach ($dhcpv6ifconf['staticmap'] as $sm) {
1740
				$dhcpdv6conf .= <<<EOD
1741
host s_{$dhcpv6if}_{$i} {
1742
	host-identifier option dhcp6.client-id {$sm['duid']};
1743

    
1744
EOD;
1745
				if ($sm['ipaddrv6']) {
1746
					$ipaddrv6 = $sm['ipaddrv6'];
1747
					if ($ifcfgv6['ipaddrv6'] == 'track6') {
1748
						$ipaddrv6 = merge_ipv6_delegated_prefix($ifcfgipv6, $ipaddrv6, $pdlen);
1749
					}
1750
					$dhcpdv6conf .= "	fixed-address6 {$ipaddrv6};\n";
1751
				}
1752

    
1753
				if ($sm['hostname']) {
1754
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1755
					$dhhostname = str_replace(".", "_", $dhhostname);
1756
					$dhcpdv6conf .= "	option host-name {$dhhostname};\n";
1757
					if (isset($dhcpv6ifconf['ddnsupdate']) &&
1758
					    isset($dhcpv6ifconf['ddnsforcehostname'])) {
1759
						$dhcpdv6conf .= "	ddns-hostname \"{$dhhostname}\";\n";
1760
					}
1761
				}
1762
				if ($sm['filename']) {
1763
					$dhcpdv6conf .= "	filename \"{$sm['filename']}\";\n";
1764
				}
1765

    
1766
				if ($sm['rootpath']) {
1767
					$dhcpdv6conf .= "	option root-path \"{$sm['rootpath']}\";\n";
1768
				}
1769

    
1770
				$dhcpdv6conf .= "}\n";
1771
				$i++;
1772
			}
1773
		}
1774

    
1775
		if ($dhcpv6ifconf['ddnsdomain']) {
1776
			$dhcpdv6conf .= dhcpdkey($dhcpv6ifconf);
1777
			$dhcpdv6conf .= dhcpdzones($ddns_zones);
1778
		}
1779

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

    
1800
	if ($nsupdate) {
1801
		$dhcpdv6conf .= "ddns-update-style interim;\n";
1802
		$dhcpdv6conf .= "update-static-leases on;\n";
1803
	} else {
1804
		$dhcpdv6conf .= "ddns-update-style none;\n";
1805
	}
1806

    
1807
	/* write dhcpdv6.conf */
1808
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf", $dhcpdv6conf)) {
1809
		log_error("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1810
		if (platform_booting()) {
1811
			printf("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1812
		}
1813
		unset($dhcpdv6conf);
1814
		return 1;
1815
	}
1816
	unset($dhcpdv6conf);
1817

    
1818
	/* create an empty leases v6 database */
1819
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases")) {
1820
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1821
	}
1822

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

    
1827
	/* fire up dhcpd in a chroot */
1828
	if (count($dhcpdv6ifs) > 0) {
1829
		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 " .
1830
			join(" ", $dhcpdv6ifs));
1831
		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");
1832
	}
1833
	if (platform_booting()) {
1834
		print gettext("done.") . "\n";
1835
	}
1836

    
1837
	return 0;
1838
}
1839

    
1840
function services_igmpproxy_configure() {
1841
	global $config, $g;
1842

    
1843
	/* kill any running igmpproxy */
1844
	killbyname("igmpproxy");
1845

    
1846
	if (!isset($config['igmpproxy']['enable'])) {
1847
		return 0;
1848
	}
1849
	if (!is_array($config['igmpproxy']['igmpentry']) || (count($config['igmpproxy']['igmpentry']) == 0)) {
1850
		return 1;
1851
	}
1852

    
1853
	$iflist = get_configured_interface_list();
1854

    
1855
	$igmpconf = <<<EOD
1856

    
1857
##------------------------------------------------------
1858
## Enable Quickleave mode (Sends Leave instantly)
1859
##------------------------------------------------------
1860
quickleave
1861

    
1862
EOD;
1863

    
1864
	foreach ($config['igmpproxy']['igmpentry'] as $igmpcf) {
1865
		unset($iflist[$igmpcf['ifname']]);
1866
		$realif = get_real_interface($igmpcf['ifname']);
1867
		if (empty($igmpcf['threshold'])) {
1868
			$threshld = 1;
1869
		} else {
1870
			$threshld = $igmpcf['threshold'];
1871
		}
1872
		$igmpconf .= "phyint {$realif} {$igmpcf['type']} ratelimit 0 threshold {$threshld}\n";
1873

    
1874
		if ($igmpcf['address'] <> "") {
1875
			$item = explode(" ", $igmpcf['address']);
1876
			foreach ($item as $iww) {
1877
				$igmpconf .= "altnet {$iww}\n";
1878
			}
1879
		}
1880
		$igmpconf .= "\n";
1881
	}
1882
	foreach ($iflist as $ifn) {
1883
		$realif = get_real_interface($ifn);
1884
		$igmpconf .= "phyint {$realif} disabled\n";
1885
	}
1886
	$igmpconf .= "\n";
1887

    
1888
	$igmpfl = fopen($g['varetc_path'] . "/igmpproxy.conf", "w");
1889
	if (!$igmpfl) {
1890
		log_error(gettext("Could not write Igmpproxy configuration file!"));
1891
		return;
1892
	}
1893
	fwrite($igmpfl, $igmpconf);
1894
	fclose($igmpfl);
1895
	unset($igmpconf);
1896

    
1897
	if (isset($config['syslog']['igmpxverbose'])) {
1898
		mwexec_bg("/usr/local/sbin/igmpproxy -v {$g['varetc_path']}/igmpproxy.conf");
1899
	} else {
1900
		mwexec_bg("/usr/local/sbin/igmpproxy {$g['varetc_path']}/igmpproxy.conf");
1901
	}
1902

    
1903
	log_error(gettext("Started IGMP proxy service."));
1904

    
1905
	return 0;
1906
}
1907

    
1908
function services_dhcrelay_configure() {
1909
	global $config, $g;
1910

    
1911
	if (isset($config['system']['developerspew'])) {
1912
		$mt = microtime();
1913
		echo "services_dhcrelay_configure() being called $mt\n";
1914
	}
1915

    
1916
	/* kill any running dhcrelay */
1917
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
1918

    
1919
	init_config_arr(array('dhcrelay'));
1920
	$dhcrelaycfg = &$config['dhcrelay'];
1921

    
1922
	/* DHCPRelay enabled on any interfaces? */
1923
	if (!isset($dhcrelaycfg['enable'])) {
1924
		return 0;
1925
	}
1926

    
1927
	if (platform_booting()) {
1928
		echo gettext("Starting DHCP relay service...");
1929
	} else {
1930
		sleep(1);
1931
	}
1932

    
1933
	$iflist = get_configured_interface_list();
1934

    
1935
	$dhcrelayifs = array();
1936
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1937
	foreach ($dhcifaces as $dhcrelayif) {
1938
		if (!isset($iflist[$dhcrelayif])) {
1939
			continue;
1940
		}
1941

    
1942
		if (get_interface_ip($dhcrelayif)) {
1943
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1944
		}
1945
	}
1946
	$dhcrelayifs = array_unique($dhcrelayifs);
1947

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

    
1966
	/* Check for relays in the same subnet as clients so they can bind for
1967
	 * either direction (up or down) */
1968
	$srvrelayifs = array_intersect($dhcrelayifs, $srvifaces);
1969

    
1970
	/* The server interface(s) should not be in this list */
1971
	$dhcrelayifs = array_diff($dhcrelayifs, $srvifaces);
1972

    
1973
	/* Remove the dual-role interfaces from up and down lists */
1974
	$srvifaces = array_diff($srvifaces, $srvrelayifs);
1975
	$dhcrelayifs = array_diff($dhcrelayifs, $srvrelayifs);
1976

    
1977
	/* fire up dhcrelay */
1978
	if (empty($dhcrelayifs) && empty($srvrelayifs)) {
1979
		log_error(gettext("No suitable downstream interfaces found for running dhcrelay!"));
1980
		return; /* XXX */
1981
	}
1982
	if (empty($srvifaces) && empty($srvrelayifs)) {
1983
		log_error(gettext("No suitable upstream interfaces found for running dhcrelay!"));
1984
		return; /* XXX */
1985
	}
1986

    
1987
	$cmd = "/usr/local/sbin/dhcrelay";
1988

    
1989
	if (!empty($dhcrelayifs)) {
1990
		$cmd .= " -id " . implode(" -id ", $dhcrelayifs);
1991
	}
1992
	if (!empty($srvifaces)) {
1993
		$cmd .= " -iu " . implode(" -iu ", $srvifaces);
1994
	}
1995
	if (!empty($srvrelayifs)) {
1996
		$cmd .= " -i " . implode(" -i ", $srvrelayifs);
1997
	}
1998

    
1999
	if (isset($dhcrelaycfg['agentoption'])) {
2000
		$cmd .= " -a -m replace";
2001
	}
2002

    
2003
	$cmd .= " " . implode(" ", $srvips);
2004
	mwexec($cmd);
2005
	unset($cmd);
2006

    
2007
	return 0;
2008
}
2009

    
2010
function services_dhcrelay6_configure() {
2011
	global $config, $g;
2012

    
2013
	if (isset($config['system']['developerspew'])) {
2014
		$mt = microtime();
2015
		echo "services_dhcrelay6_configure() being called $mt\n";
2016
	}
2017

    
2018
	/* kill any running dhcrelay */
2019
	killbypid("{$g['varrun_path']}/dhcrelay6.pid");
2020

    
2021
	init_config_arr(array('dhcrelay6'));
2022
	$dhcrelaycfg = &$config['dhcrelay6'];
2023

    
2024
	/* DHCPv6 Relay enabled on any interfaces? */
2025
	if (!isset($dhcrelaycfg['enable'])) {
2026
		return 0;
2027
	}
2028

    
2029
	if (platform_booting()) {
2030
		echo gettext("Starting DHCPv6 relay service...");
2031
	} else {
2032
		sleep(1);
2033
	}
2034

    
2035
	$iflist = get_configured_interface_list();
2036

    
2037
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
2038
	foreach ($dhcifaces as $dhcrelayif) {
2039
		if (!isset($iflist[$dhcrelayif])) {
2040
			continue;
2041
		}
2042

    
2043
		if (get_interface_ipv6($dhcrelayif)) {
2044
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
2045
		}
2046
	}
2047
	$dhcrelayifs = array_unique($dhcrelayifs);
2048

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

    
2062
	/* fire up dhcrelay */
2063
	if (empty($dhcrelayifs) || empty($srvifaces)) {
2064
		log_error(gettext("No suitable interface found for running dhcrelay -6!"));
2065
		return; /* XXX */
2066
	}
2067

    
2068
	$cmd = "/usr/local/sbin/dhcrelay -6 -pf \"{$g['varrun_path']}/dhcrelay6.pid\"";
2069
	foreach ($dhcrelayifs as $dhcrelayif) {
2070
		$cmd .= " -l {$dhcrelayif}";
2071
	}
2072
	foreach ($srvifaces as $srviface) {
2073
		$cmd .= " -u \"{$srviface}\"";
2074
	}
2075
	mwexec($cmd);
2076
	unset($cmd);
2077

    
2078
	return 0;
2079
}
2080

    
2081
function services_dyndns_configure_client($conf) {
2082

    
2083
	if (!isset($conf['enable'])) {
2084
		return;
2085
	}
2086

    
2087
	/* load up the dyndns.class */
2088
	require_once("dyndns.class");
2089

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

    
2114
function services_dyndns_configure($int = "") {
2115
	global $config, $g;
2116
	if (isset($config['system']['developerspew'])) {
2117
		$mt = microtime();
2118
		echo "services_dyndns_configure() being called $mt\n";
2119
	}
2120

    
2121
	if (isset($config['dyndnses']['dyndns']) && is_array($config['dyndnses']['dyndns'])) {
2122
		$dyndnscfg = $config['dyndnses']['dyndns'];
2123
	} else {
2124
		return 0;
2125
	}
2126
	$gwgroups = return_gateway_groups_array(true);
2127
	if (is_array($dyndnscfg)) {
2128
		if (platform_booting()) {
2129
			echo gettext("Starting DynDNS clients...");
2130
		}
2131

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

    
2167
		if (platform_booting()) {
2168
			echo gettext("done.") . "\n";
2169
		}
2170
	}
2171

    
2172
	return 0;
2173
}
2174

    
2175
function dyndnsCheckIP($int) {
2176
	global $config, $factory_default_checkipservice;
2177
	$ip_address = get_interface_ip($int);
2178
	if (is_private_ip($ip_address)) {
2179
		$gateways_status = return_gateways_status(true);
2180
		// If the gateway for this interface is down, then the external check cannot work.
2181
		// Avoid the long wait for the external check to timeout.
2182
		if (stristr($gateways_status[$config['interfaces'][$int]['gateway']]['status'], "down")) {
2183
			return "down";
2184
		}
2185

    
2186
		// Append the factory default check IP service to the list (if not disabled).
2187
		if (!isset($config['checkipservices']['disable_factory_default'])) {
2188
			if (!is_array($config['checkipservices'])) {
2189
				$config['checkipservices'] = array();
2190
			}
2191
			if (!is_array($config['checkipservices']['checkipservice'])) {
2192
				$config['checkipservices']['checkipservice'] = array();
2193
			}
2194
			$config['checkipservices']['checkipservice'][] = $factory_default_checkipservice;
2195
		}
2196

    
2197
		// Use the first enabled check IP service as the default.
2198
		if (is_array($config['checkipservices']['checkipservice'])) {
2199
			foreach ($config['checkipservices']['checkipservice'] as $i => $checkipservice) {
2200
				if (isset($checkipservice['enable'])) {
2201
					$url = $checkipservice['url'];
2202
					$username = $checkipservice['username'];
2203
					$password = $checkipservice['password'];
2204
					$verifysslpeer = isset($checkipservice['verifysslpeer']);
2205
					break;
2206
				}
2207
			}
2208
		}
2209

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

    
2229
function services_dnsmasq_configure($restart_dhcp = true) {
2230
	global $config, $g;
2231
	$return = 0;
2232

    
2233
	// hard coded args: will be removed to avoid duplication if specified in custom_options
2234
	$standard_args = array(
2235
		"dns-forward-max" => "--dns-forward-max=5000",
2236
		"cache-size" => "--cache-size=10000",
2237
		"local-ttl" => "--local-ttl=1"
2238
	);
2239

    
2240

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

    
2246
	/* kill any running dnsmasq */
2247
	if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) {
2248
		sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
2249
	}
2250

    
2251
	if (isset($config['dnsmasq']['enable'])) {
2252

    
2253
		if (platform_booting()) {
2254
			echo gettext("Starting DNS forwarder...");
2255
		} else {
2256
			sleep(1);
2257
		}
2258

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

    
2264
		$args = "";
2265

    
2266
		if (isset($config['dnsmasq']['regdhcp'])) {
2267
			$args .= " --dhcp-hostsfile={$g['etc_path']}/hosts ";
2268
		}
2269

    
2270
		/* Setup listen port, if non-default */
2271
		if (is_port($config['dnsmasq']['port'])) {
2272
			$args .= " --port={$config['dnsmasq']['port']} ";
2273
		}
2274

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

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

    
2315
			// Build an array of domain overrides to help in checking for matches.
2316
			$override_a = array();
2317
			if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2318
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2319
					$override_a[$override['domain']] = "y";
2320
				}
2321
			}
2322

    
2323
			// Build an array of the private reverse lookup domain names
2324
			$reverse_domain_a = array("10.in-addr.arpa", "168.192.in-addr.arpa");
2325
			// Unfortunately the 172.16.0.0/12 range does not map nicely to the in-addr.arpa scheme.
2326
			for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) {
2327
				$reverse_domain_a[] = "$subnet_num.172.in-addr.arpa";
2328
			}
2329

    
2330
			// Set the --server parameter to nowhere for each reverse domain name that was not specifically specified in a domain override.
2331
			foreach ($reverse_domain_a as $reverse_domain) {
2332
				if (!isset($override_a[$reverse_domain])) {
2333
					$args .= " --server=/$reverse_domain/ ";
2334
				}
2335
			}
2336
			unset($override_a);
2337
			unset($reverse_domain_a);
2338
		}
2339

    
2340
		/* Setup forwarded domains */
2341
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2342
			foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2343
				if ($override['ip'] == "!") {
2344
					$override[ip] = "";
2345
				}
2346
				$args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
2347
			}
2348
		}
2349

    
2350
		/* Allow DNS Rebind for forwarded domains */
2351
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2352
			if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2353
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2354
					$args .= ' --rebind-domain-ok=/' . $override['domain'] . '/ ';
2355
				}
2356
			}
2357
		}
2358

    
2359
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2360
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2361
		}
2362

    
2363
		if (isset($config['dnsmasq']['strict_order'])) {
2364
			$args .= " --strict-order ";
2365
		}
2366

    
2367
		if (isset($config['dnsmasq']['domain_needed'])) {
2368
			$args .= " --domain-needed ";
2369
		}
2370

    
2371
		if ($config['dnsmasq']['custom_options']) {
2372
			foreach (preg_split('/\s+/', $config['dnsmasq']['custom_options']) as $c) {
2373
				$args .= " " . escapeshellarg("--{$c}");
2374
				$p = explode('=', $c);
2375
				if (array_key_exists($p[0], $standard_args)) {
2376
					unset($standard_args[$p[0]]);
2377
				}
2378
			}
2379
		}
2380
		$args .= ' ' . implode(' ', array_values($standard_args));
2381

    
2382
		/* run dnsmasq. Use "-C /dev/null" since we use command line args only (Issue #6730) */
2383
		$cmd = "/usr/local/sbin/dnsmasq --all-servers -C /dev/null {$dns_rebind} {$args}";
2384
		//log_error("dnsmasq command: {$cmd}");
2385
		mwexec_bg($cmd);
2386
		unset($args);
2387

    
2388
		system_dhcpleases_configure();
2389

    
2390
		if (platform_booting()) {
2391
			echo gettext("done.") . "\n";
2392
		}
2393
	}
2394

    
2395
	if (!platform_booting() && $restart_dhcp) {
2396
		if (services_dhcpd_configure() != 0) {
2397
			$return = 1;
2398
		}
2399
	}
2400

    
2401
	return $return;
2402
}
2403

    
2404
function services_unbound_configure($restart_dhcp = true) {
2405
	global $config, $g;
2406
	$return = 0;
2407

    
2408
	if (isset($config['system']['developerspew'])) {
2409
		$mt = microtime();
2410
		echo "services_unbound_configure() being called $mt\n";
2411
	}
2412

    
2413
	if (isset($config['unbound']['enable'])) {
2414
		require_once('/etc/inc/unbound.inc');
2415

    
2416
		/* Stop Unbound using TERM */
2417
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2418
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
2419
		}
2420

    
2421
		/* If unbound is still running, wait up to 30 seconds for it to terminate. */
2422
		for ($i=1; $i <= 30; $i++) {
2423
			if (is_process_running('unbound')) {
2424
				sleep(1);
2425
			}
2426
		}
2427

    
2428
		$python_mode = false;
2429
		if (isset($config['unbound']['python']) && !empty($config['unbound']['python_script'])) {
2430
			$python_mode = true;
2431
		}
2432

    
2433
		/* Include any additional functions as defined by python script include file */
2434
		if (file_exists("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc")) {
2435
			exec("/usr/local/bin/php -l " . escapeshellarg("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc")
2436
				. " 2>&1", $py_output, $py_retval);
2437
			if ($py_retval == 0) {
2438
				require_once("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc");
2439
			}
2440
		}
2441

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

    
2458
				// Add DNS Resolver python integration
2459
				if (empty($validate)) {
2460
					if (!is_dir("{$g['unbound_chroot_path']}{$base_folder}{$dir}")) {
2461
						safe_mkdir("{$g['unbound_chroot_path']}{$base_folder}{$dir}");
2462
					}
2463
					$output = $retval = '';
2464
					exec("/sbin/mount_nullfs -o ro " . escapeshellarg("/usr/local{$dir}") . ' '
2465
					    . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir}") . " 2>&1", $output, $retval);
2466

    
2467
					// Disable Unbound python on mount failure
2468
					if ($retval != 0) {
2469
						$config['unbound']['python'] = '';
2470
						$log_msg = "[Unbound-pymod]: Disabling Unbound python due to failed mount";
2471
						write_config($log_msg);
2472
						log_error($log_msg);
2473
					}
2474
				}
2475
			}
2476

    
2477
			// Remove DNS Resolver python integration
2478
			elseif (!empty($validate)) {
2479
				exec("/sbin/umount -t nullfs " . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir}") . " 2>&1", $output, $retval);
2480
				if ($retval == 0) {
2481
					foreach (array( "/usr/local{$dir}", '/usr/local', '/usr') as $folder) {
2482
						if (!empty($g['unbound_chroot_path']) && $g['unbound_chroot_path'] != '/' && is_dir("{$g['unbound_chroot_path']}{$folder}")) {
2483
							@rmdir(escapeshellarg("{$g['unbound_chroot_path']}{$folder}"));
2484
						}
2485

    
2486
						// Delete remaining subfolders on next loop
2487
						if ($dir == '/bin') {
2488
							break;
2489
						}
2490
					}
2491
				}
2492
				else {
2493
					log_error("[Unbound-pymod]: Failed to unmount!");
2494
				}
2495
			}
2496
		}
2497

    
2498
		if (platform_booting()) {
2499
			echo gettext("Starting DNS Resolver...");
2500
		} else {
2501
			sleep(1);
2502
		}
2503

    
2504
		/* generate hosts file */
2505
		if (system_hosts_generate() != 0) {
2506
			$return = 1;
2507
		}
2508

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

    
2526
		sync_unbound_service();
2527
		if (platform_booting()) {
2528
			log_error(gettext("sync unbound done."));
2529
			echo gettext("done.") . "\n";
2530
		}
2531

    
2532
		system_dhcpleases_configure();
2533
	} else {
2534
		/* kill Unbound since it should not be enabled */
2535
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2536
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "KILL");
2537
		}
2538
	}
2539

    
2540
	if (!platform_booting() && $restart_dhcp) {
2541
		if (services_dhcpd_configure() != 0) {
2542
			$return = 1;
2543
		}
2544
	}
2545

    
2546
	return $return;
2547
}
2548

    
2549
function services_snmpd_configure() {
2550
	global $config, $g;
2551
	if (isset($config['system']['developerspew'])) {
2552
		$mt = microtime();
2553
		echo "services_snmpd_configure() being called $mt\n";
2554
	}
2555

    
2556
	/* kill any running snmpd */
2557
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
2558
	sleep(2);
2559
	if (is_process_running("bsnmpd")) {
2560
		mwexec("/usr/bin/killall bsnmpd", true);
2561
	}
2562

    
2563
	if (isset($config['snmpd']['enable'])) {
2564

    
2565
		if (platform_booting()) {
2566
			echo gettext("Starting SNMP daemon... ");
2567
		}
2568

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

    
2574
		/* generate snmpd.conf */
2575
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
2576
		if (!$fd) {
2577
			printf(gettext("Error: cannot open snmpd.conf in services_snmpd_configure().%s"), "\n");
2578
			return 1;
2579
		}
2580

    
2581

    
2582
		$snmpdconf = <<<EOD
2583
location := "{$config['snmpd']['syslocation']}"
2584
contact := "{$config['snmpd']['syscontact']}"
2585
read := "{$config['snmpd']['rocommunity']}"
2586

    
2587
EOD;
2588

    
2589
/* No docs on what write strings do there so disable for now.
2590
		if (isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])) {
2591
			$snmpdconf .= <<<EOD
2592
# write string
2593
write := "{$config['snmpd']['rwcommunity']}"
2594

    
2595
EOD;
2596
		}
2597
*/
2598

    
2599

    
2600
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2601
			$snmpdconf .= <<<EOD
2602
# SNMP Trap support.
2603
traphost := {$config['snmpd']['trapserver']}
2604
trapport := {$config['snmpd']['trapserverport']}
2605
trap := "{$config['snmpd']['trapstring']}"
2606

    
2607

    
2608
EOD;
2609
		}
2610

    
2611
		$sysDescr = "{$g['product_label']} {$config['system']['hostname']}.{$config['system']['domain']}" .
2612
			" {$g['product_version_string']} " . php_uname("s") .
2613
			" " . php_uname("r") . " " . php_uname("m");
2614

    
2615
		$snmpdconf .= <<<EOD
2616
system := 1     # pfSense
2617
%snmpd
2618
sysDescr			= "{$sysDescr}"
2619
begemotSnmpdDebugDumpPdus       = 2
2620
begemotSnmpdDebugSyslogPri      = 7
2621
begemotSnmpdCommunityString.0.1 = $(read)
2622

    
2623
EOD;
2624

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

    
2630
EOD;
2631
		}
2632
*/
2633

    
2634

    
2635
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2636
			$snmpdconf .= <<<EOD
2637
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
2638
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
2639
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
2640

    
2641
EOD;
2642
		}
2643

    
2644

    
2645
		$snmpdconf .= <<<EOD
2646
begemotSnmpdCommunityDisable    = 1
2647

    
2648
EOD;
2649

    
2650
		$bind_to_ips = array();
2651
		if (isset($config['snmpd']['bindip'])) {
2652
			foreach (explode(",", $config['snmpd']['bindip']) as $bind_to_ip) {
2653
				if (is_ipaddr($bind_to_ip)) {
2654
					$bind_to_ips[] = $bind_to_ip;
2655
				} else {
2656
					$if = get_real_interface($bind_to_ip);
2657
					if (does_interface_exist($if)) {
2658
						$bindip = get_interface_ip($bind_to_ip);
2659
						if (is_ipaddr($bindip)) {
2660
							$bind_to_ips[] = $bindip;
2661
						}
2662
					}
2663
				}
2664
			}
2665
		}
2666
		if (!count($bind_to_ips)) {
2667
			$bind_to_ips = array("0.0.0.0");
2668
		}
2669

    
2670
		if (is_port($config['snmpd']['pollport'])) {
2671
			foreach ($bind_to_ips as $bind_to_ip) {
2672
				$snmpdconf .= <<<EOD
2673
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
2674

    
2675
EOD;
2676

    
2677
			}
2678
		}
2679

    
2680
		$snmpdconf .= <<<EOD
2681
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
2682
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
2683

    
2684
# These are bsnmp macros not php vars.
2685
sysContact      = $(contact)
2686
sysLocation     = $(location)
2687
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
2688

    
2689
snmpEnableAuthenTraps = 2
2690

    
2691
EOD;
2692

    
2693
		if (is_array($config['snmpd']['modules'])) {
2694
			if (isset($config['snmpd']['modules']['mibii'])) {
2695
			$snmpdconf .= <<<EOD
2696
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
2697

    
2698
EOD;
2699
			}
2700

    
2701
			if (isset($config['snmpd']['modules']['netgraph'])) {
2702
				$snmpdconf .= <<<EOD
2703
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
2704
%netgraph
2705
begemotNgControlNodeName = "snmpd"
2706

    
2707
EOD;
2708
			}
2709

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

    
2714
EOD;
2715
			}
2716

    
2717
			if (isset($config['snmpd']['modules']['hostres'])) {
2718
				$snmpdconf .= <<<EOD
2719
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
2720

    
2721
EOD;
2722
			}
2723

    
2724
			if (isset($config['snmpd']['modules']['bridge'])) {
2725
				$snmpdconf .= <<<EOD
2726
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
2727
# config must end with blank line
2728

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

    
2735
EOD;
2736
			}
2737
			if (isset($config['snmpd']['modules']['regex'])) {
2738
				$snmpdconf .= <<<EOD
2739
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"
2740

    
2741
EOD;
2742
			}
2743
		}
2744

    
2745
		fwrite($fd, $snmpdconf);
2746
		fclose($fd);
2747
		unset($snmpdconf);
2748

    
2749
		/* run bsnmpd */
2750
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
2751
			" -p {$g['varrun_path']}/snmpd.pid");
2752

    
2753
		if (platform_booting()) {
2754
			echo gettext("done.") . "\n";
2755
		}
2756
	}
2757

    
2758
	return 0;
2759
}
2760

    
2761
function services_dnsupdate_process($int = "", $updatehost = "", $forced = false) {
2762
	global $config, $g;
2763
	if (isset($config['system']['developerspew'])) {
2764
		$mt = microtime();
2765
		echo "services_dnsupdate_process() being called $mt\n";
2766
	}
2767

    
2768
	/* Dynamic DNS updating active? */
2769
	if (!is_array($config['dnsupdates']['dnsupdate'])) {
2770
		return 0;
2771
	}
2772

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

    
2809
		/* determine interface name */
2810
		$if = get_failover_interface($dnsupdate['interface']);
2811

    
2812
		/* Determine address to update and default binding address */
2813
		if (isset($dnsupdate['usepublicip'])) {
2814
			$wanip = dyndnsCheckIP($if);
2815
			$bindipv4 = get_interface_ip($if);
2816
		} else {
2817
			$wanip = get_interface_ip($if);
2818
			$bindipv4 = $wanip;
2819
		}
2820
		if (is_stf_interface($dnsupdate['interface'])) { 
2821
			$wanipv6 = get_interface_ipv6($dnsupdate['interface'] . '_stf');
2822
		} else {
2823
			$wanipv6 = get_interface_ipv6($if);
2824
		}
2825
		$bindipv6 = $wanipv6;
2826

    
2827
		/* Handle non-default interface bindings */
2828
		if ($dnsupdate['updatesource'] == "none") {
2829
			/* When empty, the directive will be omitted. */
2830
			$bindipv4 = "";
2831
			$bindipv6 = "";
2832
		} elseif (!empty($dnsupdate['updatesource'])) {
2833
			/* Find the alternate binding address */
2834
			$bindipv4 = get_interface_ip($dnsupdate['updatesource']);
2835
			if (is_stf_interface($dnsupdate['interface'])) { 
2836
				$bindipv6 = get_interface_ipv6($dnsupdate['updatesource'] . '_stf');
2837
			} else {
2838
				$bindipv6 = get_interface_ipv6($dnsupdate['updatesource']);
2839
			}
2840
		}
2841

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

    
2862
		$cacheFile = $g['conf_path'] .
2863
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2864
		    escapeshellarg($dnsupdate['host']) .
2865
		    "_{$dnsupdate['server']}.cache";
2866
		$cacheFilev6 = $g['conf_path'] .
2867
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2868
		    escapeshellarg($dnsupdate['host']) .
2869
		    "_{$dnsupdate['server']}_v6.cache";
2870
		$currentTime = time();
2871

    
2872
		if (!$wanip && !$wanipv6) {
2873
			continue;
2874
		}
2875

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

    
2882
		$hostname = $dnsupdate['host'];
2883
		/* trailing dot */
2884
		if (substr($hostname, -1) != ".") {
2885
			$hostname .= ".";
2886
		}
2887

    
2888
		/* write key file */
2889
		$algorithm = empty($dnsupdate['keyalgorithm']) ? 'hmac-md5' : $dnsupdate['keyalgorithm'];
2890
		$upkey = <<<EOD
2891
key "{$keyname}" {
2892
	algorithm {$algorithm};
2893
	secret "{$dnsupdate['keydata']}";
2894
};
2895

    
2896
EOD;
2897
		@file_put_contents("{$g['varetc_path']}/nsupdatekey{$i}", $upkey);
2898

    
2899
		/* generate update instructions */
2900
		$upinst = "";
2901
		if (!empty($dnsupdate['server'])) {
2902
			$upinst .= "server {$dnsupdate['server']}\n";
2903
		}
2904

    
2905
		if (!empty($dnsupdate['zone'])) {
2906
			$upinst .= "zone {$dnsupdate['zone']}\n";
2907
		}
2908

    
2909
		$cachedipv4 = '';
2910
		$cacheTimev4 = 0;
2911
		if (file_exists($cacheFile)) {
2912
			list($cachedipv4, $cacheTimev4) = explode("|",
2913
			    file_get_contents($cacheFile));
2914
		}
2915
		$cachedipv6 = '';
2916
		$cacheTimev6 = 0;
2917
		if (file_exists($cacheFilev6)) {
2918
			list($cachedipv6, $cacheTimev6) = explode("|",
2919
			    file_get_contents($cacheFilev6));
2920
		}
2921

    
2922
		// 25 Days
2923
		$maxCacheAgeSecs = 25 * 24 * 60 * 60;
2924
		$need_update = false;
2925

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

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

    
2967
		$upinst .= "\n";	/* mind that trailing newline! */
2968

    
2969
		if (!$need_update) {
2970
			continue;
2971
		}
2972

    
2973
		@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}", $upinst);
2974
		unset($upinst);
2975
		/* invoke nsupdate */
2976
		$cmd = "/usr/local/bin/nsupdate -k {$g['varetc_path']}/nsupdatekey{$i}";
2977

    
2978
		if (isset($dnsupdate['usetcp'])) {
2979
			$cmd .= " -v";
2980
		}
2981

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

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

    
3024
	if (!empty($notify_text)) {
3025
		notify_all_remote($notify_text);
3026
	}
3027

    
3028
	return 0;
3029
}
3030

    
3031
/* configure cron service */
3032
function configure_cron() {
3033
	global $g, $config;
3034

    
3035
	/* preserve existing crontab entries */
3036
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
3037

    
3038
	for ($i = 0; $i < count($crontab_contents); $i++) {
3039
		$cron_item = &$crontab_contents[$i];
3040
		if (strpos($cron_item, "# pfSense specific crontab entries") !== false) {
3041
			array_splice($crontab_contents, $i - 1);
3042
			break;
3043
		}
3044
	}
3045
	$crontab_contents = implode("\n", $crontab_contents) . "\n";
3046

    
3047

    
3048
	if (is_array($config['cron']['item'])) {
3049
		$crontab_contents .= "#\n";
3050
		$crontab_contents .= "# pfSense specific crontab entries\n";
3051
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
3052
		$crontab_contents .= "#\n";
3053

    
3054
		if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) {
3055
			$http_proxy = $config['system']['proxyurl'];
3056
			if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) {
3057
				$http_proxy .= ':' . $config['system']['proxyport'];
3058
			}
3059
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
3060

    
3061
			if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
3062
				$crontab_contents .= "HTTP_PROXY_AUTH=basic:*:{$config['system']['proxyuser']}:{$config['system']['proxypass']}";
3063
			}
3064
		}
3065

    
3066
		foreach ($config['cron']['item'] as $item) {
3067
			$crontab_contents .= "\n{$item['minute']}\t";
3068
			$crontab_contents .= "{$item['hour']}\t";
3069
			$crontab_contents .= "{$item['mday']}\t";
3070
			$crontab_contents .= "{$item['month']}\t";
3071
			$crontab_contents .= "{$item['wday']}\t";
3072
			$crontab_contents .= "{$item['who']}\t";
3073
			$crontab_contents .= "{$item['command']}";
3074
		}
3075

    
3076
		$crontab_contents .= "\n#\n";
3077
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
3078
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
3079
		$crontab_contents .= "#\n\n";
3080
	}
3081

    
3082
	/* please maintain the newline at the end of file */
3083
	file_put_contents("/etc/crontab", $crontab_contents);
3084
	unset($crontab_contents);
3085

    
3086
	/* make sure that cron is running and start it if it got killed somehow */
3087
	if (!is_process_running("cron")) {
3088
		exec("cd /tmp && /usr/sbin/cron -s 2>/dev/null");
3089
	} else {
3090
	/* do a HUP kill to force sync changes */
3091
		sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP");
3092
	}
3093

    
3094
}
3095

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

    
3120
function upnp_start() {
3121
	global $config;
3122

    
3123
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
3124
		return;
3125
	}
3126

    
3127
	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
3128
		echo gettext("Starting UPnP service... ");
3129
		require_once('/usr/local/pkg/miniupnpd.inc');
3130
		sync_package_miniupnpd();
3131
		echo "done.\n";
3132
	}
3133
}
3134

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

    
3138
	$is_installed = false;
3139
	$cron_changed = true;
3140
	$change_message = "";
3141

    
3142
	if (!is_array($config['cron'])) {
3143
		$config['cron'] = array();
3144
	}
3145
	if (!is_array($config['cron']['item'])) {
3146
		$config['cron']['item'] = array();
3147
	}
3148

    
3149
	$x = 0;
3150
	foreach ($config['cron']['item'] as $item) {
3151
		if (strstr($item['command'], $command)) {
3152
			$is_installed = true;
3153
			break;
3154
		}
3155
		$x++;
3156
	}
3157

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

    
3187
	if ($cron_changed) {
3188
		/* Optionally write the configuration if this function made changes.
3189
		 * Performing a write_config() in this way can have unintended side effects. See #7146
3190
		 * Base system instances of this function do not need to write, packages may.
3191
		 */
3192
		if ($write_config) {
3193
			write_config(sprintf(gettext($change_message), $command));
3194
		}
3195
		configure_cron();
3196
	}
3197
}
3198

    
3199
?>
(46-46/61)