Project

General

Profile

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

    
28

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
191
		if (is_numericint($dhcpv6ifconf['ravalidlifetime'])) {
192
		  $radvdconf .= "\t\tAdvValidLifetime {$dhcpv6ifconf['ravalidlifetime']};\n";
193
		} else {
194
		  $radvdconf .= "\t\tAdvValidLifetime 86400;\n";
195
		}
196

    
197
		if (is_numericint($dhcpv6ifconf['rapreferredlifetime'])) {
198
		  $radvdconf .= "\t\tAdvPreferredLifetime {$dhcpv6ifconf['rapreferredlifetime']};\n";
199
		} else {
200
		  $radvdconf .= "\t\tAdvPreferredLifetime 14400;\n";
201
		}
202

    
203
		$radvdconf .= "\t};\n";
204

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

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

    
282
			$searchlist = array();
283
			$domainsearchlist = explode(';', $dhcpv6ifconf['radomainsearchlist']);
284
			foreach ($domainsearchlist as $sd) {
285
				$sd = trim($sd);
286
				if (is_hostname($sd)) {
287
					$searchlist[] = $sd;
288
				}
289
			}
290
			if (count($searchlist) > 0) {
291
				$searchliststring = trim(implode(" ", $searchlist));
292
			}
293
			if (!empty($dhcpv6ifconf['domain'])) {
294
				$radvdconf .= "\tDNSSL {$dhcpv6ifconf['domain']} {$searchliststring} { };\n";
295
			} elseif (!empty($config['system']['domain'])) {
296
				$radvdconf .= "\tDNSSL {$config['system']['domain']} {$searchliststring} { };\n";
297
			}
298
		}
299
		$radvdconf .= "};\n";
300
	}
301

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

    
324
		$realif = get_real_interface($if, "inet6");
325

    
326
		/* prevent duplicate entries, manual overrides */
327
		if (isset($radvdifs[$realif])) {
328
			continue;
329
		}
330

    
331
		$ifcfgipv6 = get_interface_ipv6($if);
332
		if (!is_ipaddrv6($ifcfgipv6)) {
333
			$subnetv6 = "::";
334
			$ifcfgsnv6 = "64";
335
		} else {
336
			$ifcfgsnv6 = get_interface_subnetv6($if);
337
			$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
338
		}
339
		$radvdifs[$realif] = $realif;
340

    
341
		$autotype = $config['interfaces'][$trackif]['ipaddrv6'];
342

    
343
		if ($g['debug']) {
344
			log_error("configuring RA on {$if} for type {$autotype} radvd subnet {$subnetv6}/{$ifcfgsnv6}");
345
		}
346

    
347
		$radvdconf .= "# Generated config for {$autotype} delegation from {$trackif} on {$if}\n";
348
		$radvdconf .= "interface {$realif} {\n";
349
		$radvdconf .= "\tAdvSendAdvert on;\n";
350
		if (is_numericint($dhcpv6ifconf['raminrtradvinterval'])) {
351
			$radvdconf .= "\tMinRtrAdvInterval {$dhcpv6ifconf['raminrtradvinterval']};\n";
352
		} else {
353
			$radvdconf .= "\tMinRtrAdvInterval 5;\n";
354
                }
355
		if (is_numericint($dhcpv6ifconf['ramaxrtradvinterval'])) {
356
			$radvdconf .= "\tMaxRtrAdvInterval {$dhcpv6ifconf['ramaxrtradvinterval']};\n";
357
		} else {
358
			$radvdconf .= "\tMaxRtrAdvInterval 10;\n";
359
		}
360
		$mtu = get_interface_mtu($realif);
361
		if (is_numeric($mtu)) {
362
			$radvdconf .= "\tAdvLinkMTU {$mtu};\n";
363
		} else {
364
			$radvdconf .= "\tAdvLinkMTU 1280;\n";
365
		}
366
		$radvdconf .= "\tAdvOtherConfigFlag on;\n";
367
		$radvdconf .= "\tprefix {$subnetv6}/{$ifcfgsnv6} {\n";
368
		$radvdconf .= "\t\tAdvOnLink on;\n";
369
		$radvdconf .= "\t\tAdvAutonomous on;\n";
370
		$radvdconf .= "\t\tAdvRouterAddr on;\n";
371
		$radvdconf .= "\t};\n";
372

    
373
		/* add DNS servers */
374
		if ($dhcpv6ifconf['radvd-dns'] != 'disabled') {
375
			$dnslist = array();
376
			if (isset($config['dnsmasq']['enable']) || isset($config['unbound']['enable'])) {
377
				$dnslist[] = $ifcfgipv6;
378
			} elseif (is_array($config['system']['dnsserver']) && !empty($config['system']['dnsserver'])) {
379
				foreach ($config['system']['dnsserver'] as $server) {
380
					if (is_ipaddrv6($server)) {
381
						$dnslist[] = $server;
382
					}
383
				}
384
			}
385
			if (count($dnslist) > 0) {
386
				$dnsstring = implode(" ", $dnslist);
387
				if (!empty($dnsstring)) {
388
					$radvdconf .= "\tRDNSS {$dnsstring} { };\n";
389
				}
390
			}
391
			if (!empty($config['system']['domain'])) {
392
				$radvdconf .= "\tDNSSL {$config['system']['domain']} { };\n";
393
			}
394
		}
395
		$radvdconf .= "};\n";
396
	}
397

    
398
	/* write radvd.conf */
399
	if (!@file_put_contents("{$g['varetc_path']}/radvd.conf", $radvdconf)) {
400
		log_error(gettext("Error: cannot open radvd.conf in services_radvd_configure()."));
401
		if (platform_booting()) {
402
			printf("Error: cannot open radvd.conf in services_radvd_configure().\n");
403
		}
404
	}
405
	unset($radvdconf);
406

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

    
425
function services_dhcpd_configure($family = "all", $blacklist = array()) {
426
	global $config, $g;
427

    
428
	$dhcpdconfigurelck = lock("dhcpdconfigure", LOCK_EX);
429

    
430
	/* configure DHCPD chroot once */
431
	$fd = fopen("{$g['tmp_path']}/dhcpd.sh", "w");
432
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}\n");
433
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/dev\n");
434
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/etc\n");
435
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/usr/local/sbin\n");
436
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db\n");
437
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run\n");
438
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/usr\n");
439
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/lib\n");
440
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/run\n");
441
	fwrite($fd, "/usr/sbin/chown -R dhcpd:_dhcp {$g['dhcpd_chroot_path']}/*\n");
442
	fwrite($fd, "/bin/cp -n /lib/libc.so.* {$g['dhcpd_chroot_path']}/lib/\n");
443
	fwrite($fd, "/bin/cp -n /usr/local/sbin/dhcpd {$g['dhcpd_chroot_path']}/usr/local/sbin/\n");
444
	fwrite($fd, "/bin/chmod a+rx {$g['dhcpd_chroot_path']}/usr/local/sbin/dhcpd\n");
445

    
446
	$status = `/sbin/mount | /usr/bin/grep -v grep | /usr/bin/grep "{$g['dhcpd_chroot_path']}/dev"`;
447
	if (!trim($status)) {
448
		fwrite($fd, "/sbin/mount -t devfs devfs {$g['dhcpd_chroot_path']}/dev\n");
449
	}
450
	fclose($fd);
451
	mwexec("/bin/sh {$g['tmp_path']}/dhcpd.sh");
452

    
453
	if ($family == "all" || $family == "inet") {
454
		services_dhcpdv4_configure();
455
	}
456
	if ($family == "all" || $family == "inet6") {
457
		services_dhcpdv6_configure($blacklist);
458
		services_radvd_configure($blacklist);
459
	}
460

    
461
	unlock($dhcpdconfigurelck);
462
}
463

    
464
function services_dhcpdv4_configure() {
465
	global $config, $g;
466
	$need_ddns_updates = false;
467
	$ddns_zones = array();
468

    
469
	if ($g['services_dhcp_server_enable'] == false) {
470
		return;
471
	}
472

    
473
	if (isset($config['system']['developerspew'])) {
474
		$mt = microtime();
475
		echo "services_dhcpdv4_configure($if) being called $mt\n";
476
	}
477

    
478
	/* kill any running dhcpd */
479
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid")) {
480
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid");
481
	}
482

    
483
	/* DHCP enabled on any interfaces? */
484
	if (!is_dhcp_server_enabled()) {
485
		return 0;
486
	}
487

    
488
	$syscfg = $config['system'];
489
	if (!is_array($config['dhcpd'])) {
490
		$config['dhcpd'] = array();
491
	}
492
	$dhcpdcfg = $config['dhcpd'];
493
	$Iflist = get_configured_interface_list();
494

    
495
	/* Only consider DNS servers with IPv4 addresses for the IPv4 DHCP server. */
496
	$dns_arrv4 = array();
497
	if (is_array($syscfg['dnsserver'])) {
498
		foreach ($syscfg['dnsserver'] as $dnsserver) {
499
			if (is_ipaddrv4($dnsserver)) {
500
				$dns_arrv4[] = $dnsserver;
501
			}
502
		}
503
	}
504

    
505
	if (platform_booting()) {
506
		echo gettext("Starting DHCP service...");
507
	} else {
508
		sleep(1);
509
	}
510

    
511
	$custoptions = "";
512
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
513
		if (is_array($dhcpifconf['numberoptions']) && is_array($dhcpifconf['numberoptions']['item'])) {
514
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
515
				if (!empty($item['type'])) {
516
					$itemtype = $item['type'];
517
				} else {
518
					$itemtype = "text";
519
				}
520
				$custoptions .= "option custom-{$dhcpif}-{$itemidx} code {$item['number']} = {$itemtype};\n";
521
			}
522
		}
523
		if (is_array($dhcpifconf['pool'])) {
524
			foreach ($dhcpifconf['pool'] as $poolidx => $poolconf) {
525
				if (is_array($poolconf['numberoptions']) && is_array($poolconf['numberoptions']['item'])) {
526
					foreach ($poolconf['numberoptions']['item'] as $itemidx => $item) {
527
						if (!empty($item['type'])) {
528
							$itemtype = $item['type'];
529
						} else {
530
							$itemtype = "text";
531
						}
532
						$custoptions .= "option custom-{$dhcpif}-{$poolidx}-{$itemidx} code {$item['number']} = {$itemtype};\n";
533
					}
534
				}
535
			}
536
		}
537
	}
538

    
539
	$dhcpdconf = <<<EOD
540

    
541
option domain-name "{$syscfg['domain']}";
542
option ldap-server code 95 = text;
543
option domain-search-list code 119 = text;
544
option arch code 93 = unsigned integer 16; # RFC4578
545
{$custoptions}
546
default-lease-time 7200;
547
max-lease-time 86400;
548
log-facility local7;
549
one-lease-per-client true;
550
deny duplicates;
551
update-conflict-detection false;
552

    
553
EOD;
554

    
555
	if (!isset($dhcpifconf['disableauthoritative'])) {
556
		$dhcpdconf .= "authoritative;\n";
557
	}
558

    
559
	if (isset($dhcpifconf['alwaysbroadcast'])) {
560
		$dhcpdconf .= "always-broadcast on\n";
561
	}
562

    
563
	// OMAPI Settings
564
	if (isset($dhcpifconf['omapi_port']) && is_numeric($dhcpifconf['omapi_port'])) {
565
		$dhcpdconf .= <<<EOD
566

    
567
key omapi_key {
568
  algorithm {$dhcpifconf['omapi_key_algorithm']};
569
  secret "{$dhcpifconf['omapi_key']}";
570
};
571
omapi-port {$dhcpifconf['omapi_port']};
572
omapi-key omapi_key;
573

    
574
EOD;
575
	}
576

    
577
	$dhcpdifs = array();
578
	$enable_add_routers = false;
579
	$gateways_arr = return_gateways_array();
580
	/* only add a routers line if the system has any IPv4 gateway at all */
581
	/* a static route has a gateway, manually overriding this field always works */
582
	foreach ($gateways_arr as $gwitem) {
583
		if ($gwitem['ipprotocol'] == "inet") {
584
			$enable_add_routers = true;
585
			break;
586
		}
587
	}
588

    
589
	/*    loop through and determine if we need to setup
590
	 *    failover peer "bleh" entries
591
	 */
592
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
593

    
594
		if (!isset($config['interfaces'][$dhcpif]['enable'])) {
595
			continue;
596
		}
597

    
598
		interfaces_staticarp_configure($dhcpif);
599

    
600
		if (!isset($dhcpifconf['enable'])) {
601
			continue;
602
		}
603

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

    
645
			if (is_ipaddrv4($intip)) {
646
				$dhcpdconf .= <<<EOPP
647
failover peer "dhcp_{$dhcpif}" {
648
  {$type};
649
  address {$intip};
650
  port {$my_port};
651
  peer address {$dhcpifconf['failover_peerip']};
652
  peer port {$peer_port};
653
  max-response-delay 10;
654
  max-unacked-updates 10;
655
  {$dhcpdconf_pri}
656
  load balance max seconds 3;
657
}
658
\n
659
EOPP;
660
			}
661
		}
662
	}
663

    
664
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
665

    
666
		$newzone = array();
667
		$ifcfg = $config['interfaces'][$dhcpif];
668

    
669
		if (!isset($dhcpifconf['enable']) || !isset($Iflist[$dhcpif])) {
670
			continue;
671
		}
672
		$ifcfgip = get_interface_ip($dhcpif);
673
		$ifcfgsn = get_interface_subnet($dhcpif);
674
		$subnet = gen_subnet($ifcfgip, $ifcfgsn);
675
		$subnetmask = gen_subnet_mask($ifcfgsn);
676

    
677
		if (!is_ipaddr($subnet)) {
678
			continue;
679
		}
680

    
681
		$all_pools = array();
682
		$all_pools[] = $dhcpifconf;
683
		if (is_array($dhcpifconf['pool'])) {
684
			$all_pools = array_merge($all_pools, $dhcpifconf['pool']);
685
		}
686

    
687
		$dnscfg = "";
688

    
689
		if ($dhcpifconf['domain']) {
690
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
691
		}
692

    
693
		if ($dhcpifconf['domainsearchlist'] <> "") {
694
			$dnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpifconf['domainsearchlist'])) . "\";\n";
695
		}
696

    
697
		if (isset($dhcpifconf['ddnsupdate'])) {
698
			$need_ddns_updates = true;
699
			$newzone = array();
700
			if ($dhcpifconf['ddnsdomain'] <> "") {
701
				$newzone['domain-name'] = $dhcpifconf['ddnsdomain'];
702
				$dnscfg .= "	ddns-domainname \"{$dhcpifconf['ddnsdomain']}\";\n";
703
			} else {
704
				$newzone['domain-name'] = $config['system']['domain'];
705
			}
706

    
707
			if (empty($dhcpifconf['ddnsclientupdates'])) {
708
				$ddnsclientupdates = 'allow';
709
			} else {
710
				$ddnsclientupdates = $dhcpifconf['ddnsclientupdates'];
711
			}
712

    
713
			$dnscfg .= "	{$ddnsclientupdates} client-updates;\n";
714

    
715
			$revsubnet = array_reverse(explode('.',$subnet));
716

    
717
			/* Take care of full classes first */
718
			switch ($ifcfgsn) {
719
				case 8:
720
					$start_octet = 3;
721
					break;
722
				case 16:
723
					$start_octet = 2;
724
					break;
725
				case 24:
726
					$start_octet = 1;
727
					break;
728
				default:
729
					$start_octet = 0;
730
					/* Add subnet bitmask to first octet */
731
					$revsubnet[0] .= '-' . $ifcfgsn;
732
					break;
733

    
734
			}
735

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

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

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

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

    
795
		$dhcpdconf .= "subnet {$subnet} netmask {$subnetmask} {\n";
796

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

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

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

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

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

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

    
886
			$pdnscfg = "";
887

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

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

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

    
903
			$dhcpdconf .= "{$pdnscfg}";
904

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

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

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

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

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

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

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

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

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

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

    
969
				if (!empty($poolconf['filename']) &&
970
				    (!isset($dhcpifconf['filename']) ||
971
				    ($poolconf['filename'] != $dhcpifconf['filename']))) {
972
					$filename = $poolconf['filename'];
973
				}
974
				if (!empty($poolconf['filename32']) &&
975
				    (!isset($dhcpifconf['filename32']) ||
976
				    ($poolconf['filename32'] != $dhcpifconf['filename32']))) {
977
					$filename32 = $poolconf['filename32'];
978
				}
979
				if (!empty($poolconf['filename64']) &&
980
				    (!isset($dhcpifconf['filename64']) ||
981
				    ($poolconf['filename64'] != $dhcpifconf['filename64']))) {
982
					$filename64 = $poolconf['filename64'];
983
				}
984

    
985
				if (!empty($filename32) || !empty($filename64)) {
986
					if (empty($filename) && !empty($dhcpifconf['filename'])) {
987
						$filename = $dhcpifconf['filename'];
988
					}
989
					if (empty($filename32) && !empty($dhcpifconf['filename32'])) {
990
						$filename32 = $dhcpifconf['filename32'];
991
					}
992
					if (empty($filename64) && !empty($dhcpifconf['filename64'])) {
993
						$filename64 = $dhcpifconf['filename64'];
994
					}
995
				}
996

    
997
				if (!empty($filename) && !empty($filename32) && !empty($filename64)) {
998
					$dhcpdconf .= "		if option arch = 00:06 {\n";
999
					$dhcpdconf .= "			filename \"{$filename32}\";\n";
1000
					$dhcpdconf .= "		} else if option arch = 00:07 {\n";
1001
					$dhcpdconf .= "			filename \"{$filename64}\";\n";
1002
					$dhcpdconf .= "		} else if option arch = 00:09 {\n";
1003
					$dhcpdconf .= "			filename \"{$filename64}\";\n";
1004
					$dhcpdconf .= "		} else {\n";
1005
					$dhcpdconf .= "			filename \"{$filename}\";\n";
1006
					$dhcpdconf .= "		}\n\n";
1007
				} elseif (!empty($filename)) {
1008
					$dhcpdconf .= "		filename \"{$filename}\";\n";
1009
				}
1010
				unset($filename, $filename32, $filename64);
1011

    
1012
				if (!empty($poolconf['rootpath']) && ($poolconf['rootpath'] != $dhcpifconf['rootpath'])) {
1013
					$dhcpdconf .= "		option root-path \"{$poolconf['rootpath']}\";\n";
1014
				}
1015
			}
1016
			$dhcpdconf .= "		range {$poolconf['range']['from']} {$poolconf['range']['to']};\n";
1017
			$dhcpdconf .= "	}\n\n";
1018
		}
1019
// End of settings inside pools
1020

    
1021
		if ($dhcpifconf['gateway'] && $dhcpifconf['gateway'] != "none") {
1022
			$routers = $dhcpifconf['gateway'];
1023
			$add_routers = true;
1024
		} elseif ($dhcpifconf['gateway'] == "none") {
1025
			$add_routers = false;
1026
		} else {
1027
			$add_routers = $enable_add_routers;
1028
			$routers = $ifcfgip;
1029
		}
1030
		if ($add_routers) {
1031
			$dhcpdconf .= "	option routers {$routers};\n";
1032
		}
1033

    
1034
		$dhcpdconf .= <<<EOD
1035
$dnscfg
1036

    
1037
EOD;
1038
		// default-lease-time
1039
		if ($dhcpifconf['defaultleasetime']) {
1040
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
1041
		}
1042

    
1043
		// max-lease-time
1044
		if ($dhcpifconf['maxleasetime']) {
1045
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
1046
		}
1047

    
1048
		if (!isset($dhcpifconf['disablepingcheck'])) {
1049
			$dhcpdconf .= "	ping-check true;\n";
1050
		} else {
1051
			$dhcpdconf .= "	ping-check false;\n";
1052
		}
1053

    
1054
		// netbios-name*
1055
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
1056
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
1057
			$dhcpdconf .= "	option netbios-node-type 8;\n";
1058
		}
1059

    
1060
		// ntp-servers
1061
		if (is_array($dhcpifconf['ntpserver']) && $dhcpifconf['ntpserver'][0]) {
1062
			$dhcpdconf .= "	option ntp-servers " . join(",", $dhcpifconf['ntpserver']) . ";\n";
1063
		}
1064

    
1065
		// tftp-server-name
1066
		if ($dhcpifconf['tftp'] <> "") {
1067
			$dhcpdconf .= "	option tftp-server-name \"{$dhcpifconf['tftp']}\";\n";
1068
		}
1069

    
1070
		// Handle option, number rowhelper values
1071
		$dhcpdconf .= "\n";
1072
		if (isset($dhcpifconf['numberoptions']['item']) && is_array($dhcpifconf['numberoptions']['item'])) {
1073
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
1074
				$item_value = base64_decode($item['value']);
1075
				if (empty($item['type']) || $item['type'] == "text") {
1076
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} \"{$item_value}\";\n";
1077
				} else {
1078
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} {$item_value};\n";
1079
				}
1080
			}
1081
		}
1082

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

    
1088
		// net boot information
1089
		if (isset($dhcpifconf['netboot'])) {
1090
			if ($dhcpifconf['nextserver'] <> "") {
1091
				$dhcpdconf .= "	next-server {$dhcpifconf['nextserver']};\n";
1092
			}
1093
			if (!empty($dhcpifconf['filename']) && !empty($dhcpifconf['filename32']) && !empty($dhcpifconf['filename64'])) {
1094
				$dhcpdconf .= "	if option arch = 00:06 {\n";
1095
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename32']}\";\n";
1096
				$dhcpdconf .= "	} else if option arch = 00:07 {\n";
1097
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1098
				$dhcpdconf .= "	} else if option arch = 00:09 {\n";
1099
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1100
				$dhcpdconf .= "	} else {\n";
1101
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename']}\";\n";
1102
				$dhcpdconf .= "	}\n\n";
1103
			} elseif (!empty($dhcpifconf['filename'])) {
1104
				$dhcpdconf .= "	filename \"{$dhcpifconf['filename']}\";\n";
1105
			}
1106
			if (!empty($dhcpifconf['rootpath'])) {
1107
				$dhcpdconf .= "	option root-path \"{$dhcpifconf['rootpath']}\";\n";
1108
			}
1109
		}
1110

    
1111
		$dhcpdconf .= <<<EOD
1112
}
1113

    
1114
EOD;
1115

    
1116
		/* add static mappings */
1117
		if (is_array($dhcpifconf['staticmap'])) {
1118

    
1119
			$i = 0;
1120
			foreach ($dhcpifconf['staticmap'] as $sm) {
1121
				$dhcpdconf .= "host s_{$dhcpif}_{$i} {\n";
1122

    
1123
				if ($sm['mac']) {
1124
					$dhcpdconf .= "	hardware ethernet {$sm['mac']};\n";
1125
				}
1126

    
1127
				if ($sm['cid']) {
1128
					$dhcpdconf .= " option dhcp-client-identifier \"{$sm['cid']}\";\n";
1129
				}
1130

    
1131
				if ($sm['ipaddr']) {
1132
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
1133
				}
1134

    
1135
				if ($sm['hostname']) {
1136
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1137
					$dhhostname = str_replace(".", "_", $dhhostname);
1138
					$dhcpdconf .= "	option host-name \"{$dhhostname}\";\n";
1139
					if ((isset($dhcpifconf['ddnsupdate']) || isset($sm['ddnsupdate'])) && (isset($dhcpifconf['ddnsforcehostname']) || isset($sm['ddnsforcehostname']))) {
1140
						$dhcpdconf .= "	ddns-hostname \"{$dhhostname}\";\n";
1141
					}
1142
				}
1143
				if ($sm['filename']) {
1144
					$dhcpdconf .= "	filename \"{$sm['filename']}\";\n";
1145
				}
1146

    
1147
				if ($sm['rootpath']) {
1148
					$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1149
				}
1150

    
1151
				if ($sm['gateway'] && ($sm['gateway'] != $dhcpifconf['gateway'])) {
1152
					$dhcpdconf .= "	option routers {$sm['gateway']};\n";
1153
				}
1154

    
1155
				$smdnscfg = "";
1156

    
1157
				if ($sm['domain'] && ($sm['domain'] != $dhcpifconf['domain'])) {
1158
					$smdnscfg .= "	option domain-name \"{$sm['domain']}\";\n";
1159
				}
1160

    
1161
				if (!empty($sm['domainsearchlist']) && ($sm['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
1162
					$smdnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $sm['domainsearchlist'])) . "\";\n";
1163
				}
1164

    
1165
				if (isset($sm['ddnsupdate'])) {
1166
					if (($sm['ddnsdomain'] <> "") && ($sm['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
1167
						$smdnscfg .= "		ddns-domainname \"{$sm['ddnsdomain']}\";\n";
1168
					}
1169
					$smdnscfg .= "		ddns-update-style interim;\n";
1170
				}
1171

    
1172
				if (is_array($sm['dnsserver']) && ($sm['dnsserver'][0]) && ($sm['dnsserver'][0] != $dhcpifconf['dnsserver'][0])) {
1173
					$smdnscfg .= "	option domain-name-servers " . join(",", $sm['dnsserver']) . ";\n";
1174
				}
1175
				$dhcpdconf .= "{$smdnscfg}";
1176

    
1177
				// default-lease-time
1178
				if ($sm['defaultleasetime'] && ($sm['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
1179
					$dhcpdconf .= "	default-lease-time {$sm['defaultleasetime']};\n";
1180
				}
1181

    
1182
				// max-lease-time
1183
				if ($sm['maxleasetime'] && ($sm['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
1184
					$dhcpdconf .= "	max-lease-time {$sm['maxleasetime']};\n";
1185
				}
1186

    
1187
				// netbios-name*
1188
				if (is_array($sm['winsserver']) && $sm['winsserver'][0] && ($sm['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
1189
					$dhcpdconf .= "	option netbios-name-servers " . join(",", $sm['winsserver']) . ";\n";
1190
					$dhcpdconf .= "	option netbios-node-type 8;\n";
1191
				}
1192

    
1193
				// ntp-servers
1194
				if (is_array($sm['ntpserver']) && $sm['ntpserver'][0] && ($sm['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
1195
					$dhcpdconf .= "	option ntp-servers " . join(",", $sm['ntpserver']) . ";\n";
1196
				}
1197

    
1198
				// tftp-server-name
1199
				if (!empty($sm['tftp']) && ($sm['tftp'] != $dhcpifconf['tftp'])) {
1200
					$dhcpdconf .= "	option tftp-server-name \"{$sm['tftp']}\";\n";
1201
				}
1202

    
1203
				$dhcpdconf .= "}\n";
1204

    
1205
				// subclass for DHCP limiting
1206
				if (!empty($sm['mac'])) {
1207
					// assuming ALL addresses are ethernet hardware type ("1:" prefix)
1208
					$dhcpdconf .= "subclass \"s_{$dhcpif}\" 1:{$sm['mac']};\n";
1209
				}
1210
				if (!empty($sm['cid'])) {
1211
					$dhcpdconf .= "subclass \"s_{$dhcpif}\" \"{$sm['cid']}\";\n";
1212
				}
1213

    
1214

    
1215
				$i++;
1216
			}
1217
		}
1218

    
1219
		$dhcpdifs[] = get_real_interface($dhcpif);
1220
		if ($newzone['domain-name']) {
1221
			if ($need_ddns_updates) {
1222
				$newzone['dns-servers'] = array($dhcpifconf['ddnsdomainprimary']);
1223
				$newzone['ddnsdomainkeyname'] = $dhcpifconf['ddnsdomainkeyname'];
1224
				$newzone['ddnsdomainkeyalgorithm'] = $dhcpifconf['ddnsdomainkeyalgorithm'];
1225
				$newzone['ddnsdomainkey'] = $dhcpifconf['ddnsdomainkey'];
1226
				$dhcpdconf .= dhcpdkey($dhcpifconf);
1227
			}
1228
			$ddns_zones[] = $newzone;
1229
		}
1230
	}
1231

    
1232
	if ($need_ddns_updates) {
1233
		$dhcpdconf .= "ddns-update-style interim;\n";
1234
		$dhcpdconf .= "update-static-leases on;\n";
1235

    
1236
		$dhcpdconf .= dhcpdzones($ddns_zones);
1237
	}
1238

    
1239
	/* write dhcpd.conf */
1240
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpd.conf", $dhcpdconf)) {
1241
		printf(gettext("Error: cannot open dhcpd.conf in services_dhcpdv4_configure().%s"), "\n");
1242
		unset($dhcpdconf);
1243
		return 1;
1244
	}
1245
	unset($dhcpdconf);
1246

    
1247
	/* create an empty leases database */
1248
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
1249
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
1250
	}
1251

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

    
1256
	/* fire up dhcpd in a chroot */
1257
	if (count($dhcpdifs) > 0) {
1258
		mwexec("/usr/local/sbin/dhcpd -user dhcpd -group _dhcp -chroot {$g['dhcpd_chroot_path']} -cf /etc/dhcpd.conf -pf {$g['varrun_path']}/dhcpd.pid " .
1259
			join(" ", $dhcpdifs));
1260
	}
1261

    
1262
	if (platform_booting()) {
1263
		print "done.\n";
1264
	}
1265

    
1266
	return 0;
1267
}
1268

    
1269
function dhcpdkey($dhcpifconf) {
1270
	$dhcpdconf = "";
1271
	if (!empty($dhcpifconf['ddnsdomainkeyname']) && !empty($dhcpifconf['ddnsdomainkey'])) {
1272
		$algorithm = empty($dhcpifconf['ddnsdomainkeyalgorithm']) ? 'hmac-md5' : $dhcpifconf['ddnsdomainkeyalgorithm'];
1273
		$dhcpdconf .= "key {$dhcpifconf['ddnsdomainkeyname']} {\n";
1274
		$dhcpdconf .= "	algorithm {$algorithm};\n";
1275
		$dhcpdconf .= "	secret {$dhcpifconf['ddnsdomainkey']};\n";
1276
		$dhcpdconf .= "}\n";
1277
	}
1278

    
1279
	return $dhcpdconf;
1280
}
1281

    
1282
function dhcpdzones($ddns_zones) {
1283
	$dhcpdconf = "";
1284

    
1285
	if (is_array($ddns_zones)) {
1286
		$added_zones = array();
1287
		foreach ($ddns_zones as $zone) {
1288
			if (!is_array($zone) || empty($zone) || !is_array($zone['dns-servers'])) {
1289
				continue;
1290
			}
1291
			$primary = $zone['dns-servers'][0];
1292
			$secondary = empty($zone['dns-servers'][1]) ? "" : $zone['dns-servers'][1];
1293

    
1294
			// Make sure we aren't using any invalid or IPv6 DNS servers.
1295
			if (!is_ipaddrv4($primary)) {
1296
				if (is_ipaddrv4($secondary)) {
1297
					$primary = $secondary;
1298
					$secondary = "";
1299
				} else {
1300
					continue;
1301
				}
1302
			}
1303

    
1304
			// We don't need to add zones multiple times.
1305
			if ($zone['domain-name'] && !in_array($zone['domain-name'], $added_zones)) {
1306
				$dhcpdconf .= "zone {$zone['domain-name']}. {\n";
1307
				$dhcpdconf .= "	primary {$primary};\n";
1308
				if (is_ipaddrv4($secondary)) {
1309
					$dhcpdconf .= "	secondary {$secondary};\n";
1310
				}
1311
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1312
					$dhcpdconf .= "	key {$zone['ddnsdomainkeyname']};\n";
1313
				}
1314
				$dhcpdconf .= "}\n";
1315
				$added_zones[] = $zone['domain-name'];
1316
			}
1317
			if ($zone['ptr-domain'] && !in_array($zone['ptr-domain'], $added_zones)) {
1318
				$dhcpdconf .= "zone {$zone['ptr-domain']} {\n";
1319
				$dhcpdconf .= "	primary {$primary};\n";
1320
				if (is_ipaddrv4($secondary)) {
1321
					$dhcpdconf .= "	secondary {$secondary};\n";
1322
				}
1323
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1324
					$dhcpdconf .= "	key {$zone['ddnsdomainkeyname']};\n";
1325
				}
1326
				$dhcpdconf .= "}\n";
1327
				$added_zones[] = $zone['ptr-domain'];
1328
			}
1329
		}
1330
	}
1331

    
1332
	return $dhcpdconf;
1333
}
1334

    
1335
function services_dhcpdv6_configure($blacklist = array()) {
1336
	global $config, $g;
1337

    
1338
	if ($g['services_dhcp_server_enable'] == false) {
1339
		return;
1340
	}
1341

    
1342
	if (isset($config['system']['developerspew'])) {
1343
		$mt = microtime();
1344
		echo "services_dhcpd_configure($if) being called $mt\n";
1345
	}
1346

    
1347
	/* kill any running dhcpd */
1348
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid")) {
1349
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid");
1350
	}
1351
	if (isvalidpid("{$g['varrun_path']}/dhcpleases6.pid")) {
1352
		killbypid("{$g['varrun_path']}/dhcpleases6.pid");
1353
	}
1354

    
1355
	/* DHCP enabled on any interfaces? */
1356
	if (!is_dhcpv6_server_enabled()) {
1357
		return 0;
1358
	}
1359

    
1360
	$syscfg = $config['system'];
1361
	if (!is_array($config['dhcpdv6'])) {
1362
		$config['dhcpdv6'] = array();
1363
	}
1364
	$dhcpdv6cfg = $config['dhcpdv6'];
1365
	$Iflist = get_configured_interface_list();
1366
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
1367

    
1368

    
1369
	if (platform_booting()) {
1370
		echo "Starting DHCPv6 service...";
1371
	} else {
1372
		sleep(1);
1373
	}
1374

    
1375
	$custoptionsv6 = "";
1376
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1377
		if (is_array($dhcpv6ifconf['numberoptions']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1378
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1379
				$custoptionsv6 .= "option custom-{$dhcpv6if}-{$itemv6idx} code {$itemv6['number']} = text;\n";
1380
			}
1381
		}
1382
	}
1383

    
1384
	if (isset($dhcpv6ifconf['netboot']) && !empty($dhcpv6ifconf['bootfile_url'])) {
1385
		$custoptionsv6 .= "option dhcp6.bootfile-url code 59 = string;\n";
1386
	}
1387

    
1388
	$dhcpdv6conf = <<<EOD
1389

    
1390
option domain-name "{$syscfg['domain']}";
1391
option ldap-server code 95 = text;
1392
option domain-search-list code 119 = text;
1393
{$custoptionsv6}
1394
default-lease-time 7200;
1395
max-lease-time 86400;
1396
log-facility local7;
1397
one-lease-per-client true;
1398
deny duplicates;
1399
ping-check true;
1400
update-conflict-detection false;
1401

    
1402
EOD;
1403

    
1404
	if (!isset($dhcpv6ifconf['disableauthoritative'])) {
1405
		$dhcpdv6conf .= "authoritative;\n";
1406
	}
1407

    
1408
	if (isset($dhcpv6ifconf['alwaysbroadcast'])) {
1409
		$dhcpdv6conf .= "always-broadcast on\n";
1410
	}
1411

    
1412
	$dhcpdv6ifs = array();
1413

    
1414
	$dhcpv6num = 0;
1415
	$nsupdate = false;
1416

    
1417
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1418

    
1419
		$ddns_zones = array();
1420

    
1421
		$ifcfgv6 = $config['interfaces'][$dhcpv6if];
1422

    
1423
		if (!isset($dhcpv6ifconf['enable']) || !isset($Iflist[$dhcpv6if]) || !isset($ifcfgv6['enable'])) {
1424
			continue;
1425
		}
1426
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1427
		if (!is_ipaddrv6($ifcfgipv6)) {
1428
			continue;
1429
		}
1430
		$ifcfgsnv6 = get_interface_subnetv6($dhcpv6if);
1431
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1432
		// We might have some prefix-delegation on WAN (e.g. /48),
1433
		// but then it is split and given out to individual interfaces
1434
		// (LAN, OPT1, OPT2...) as multiple /64 subnets. So the size
1435
		// of each subnet here is always /64.
1436
		$pdlen = 64;
1437

    
1438
		$dnscfgv6 = "";
1439

    
1440
		if ($dhcpv6ifconf['domain']) {
1441
			$dnscfgv6 .= "	option domain-name \"{$dhcpv6ifconf['domain']}\";\n";
1442
		}
1443

    
1444
		if ($dhcpv6ifconf['domainsearchlist'] <> "") {
1445
			$dnscfgv6 .= "	option dhcp6.domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpv6ifconf['domainsearchlist'])) . "\";\n";
1446
		}
1447

    
1448
		if (isset($dhcpv6ifconf['ddnsupdate'])) {
1449
			if ($dhcpv6ifconf['ddnsdomain'] <> "") {
1450
				$dnscfgv6 .= "	ddns-domainname \"{$dhcpv6ifconf['ddnsdomain']}\";\n";
1451
			}
1452
			if (empty($dhcpv6ifconf['ddnsclientupdates'])) {
1453
				$ddnsclientupdates = 'allow';
1454
			} else {
1455
				$ddnsclientupdates = $dhcpv6ifconf['ddnsclientupdates'];
1456
			}
1457
			$dnscfgv6 .= "	{$ddnsclientupdates} client-updates;\n";
1458
			$nsupdate = true;
1459
		} else {
1460
			$dnscfgv6 .= "	do-forward-updates false;\n";
1461
		}
1462

    
1463
		if ($dhcpv6ifconf['dhcp6c-dns'] != 'disabled') {
1464
			if (is_array($dhcpv6ifconf['dnsserver']) && ($dhcpv6ifconf['dnsserver'][0])) {
1465
				$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dhcpv6ifconf['dnsserver']) . ";";
1466
			} else if (((isset($config['dnsmasq']['enable'])) || isset($config['unbound']['enable'])) && (is_ipaddrv6($ifcfgipv6))) {
1467
				$dnscfgv6 .= "	option dhcp6.name-servers {$ifcfgipv6};";
1468
			} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1469
				$dns_arrv6 = array();
1470
				foreach ($syscfg['dnsserver'] as $dnsserver) {
1471
					if (is_ipaddrv6($dnsserver)) {
1472
						$dns_arrv6[] = $dnsserver;
1473
					}
1474
				}
1475
				if (!empty($dns_arrv6)) {
1476
					$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dns_arrv6) . ";";
1477
				}
1478
			}
1479
		} else {
1480
			$dnscfgv6 .= "	#option dhcp6.name-servers --;";
1481
		}
1482

    
1483
		if (!is_ipaddrv6($ifcfgipv6)) {
1484
			$ifcfgsnv6 = "64";
1485
			$subnetv6 = gen_subnetv6($dhcpv6ifconf['range']['from'], $ifcfgsnv6);
1486
		}
1487

    
1488
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1489

    
1490
		if (isset($dhcpv6ifconf['ddnsupdate']) &&
1491
		    !empty($dhcpv6ifconf['ddnsdomain'])) {
1492
			$newzone = array();
1493
			$newzone['domain-name'] = $dhcpv6ifconf['ddnsdomain'];
1494
			$newzone['dns-servers'][] = $dhcpv6ifconf['ddnsdomainprimary'];
1495
			$newzone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1496
			$newzone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1497
			$ddns_zones[] = $newzone;
1498
			if (isset($dhcpv6ifconf['ddnsreverse'])) {
1499
				$ptr_zones = get_v6_ptr_zones($subnetv6, $ifcfgsnv6);
1500
				foreach ($ptr_zones as $ptr_zone) {
1501
					$reversezone = array();
1502
					$reversezone['ptr-domain'] = $ptr_zone;
1503
					$reversezone['dns-servers'][] = $dhcpv6ifconf['ddnsdomainprimary'];
1504
					$reversezone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1505
					$reversezone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1506
					$ddns_zones[] = $reversezone;
1507
				}
1508
			}
1509
		}
1510

    
1511
		$dhcpdv6conf .= " {\n";
1512

    
1513
		$range_from = $dhcpv6ifconf['range']['from'];
1514
		$range_to = $dhcpv6ifconf['range']['to'];
1515
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
1516
			$range_from = merge_ipv6_delegated_prefix($ifcfgipv6, $range_from, $pdlen);
1517
			$range_to = merge_ipv6_delegated_prefix($ifcfgipv6, $range_to, $pdlen);
1518
		}
1519

    
1520
		$dhcpdv6conf .= <<<EOD
1521
	range6 {$range_from} {$range_to};
1522
$dnscfgv6
1523

    
1524
EOD;
1525

    
1526
		if (is_ipaddrv6($dhcpv6ifconf['prefixrange']['from']) && is_ipaddrv6($dhcpv6ifconf['prefixrange']['to'])) {
1527
			$dhcpdv6conf .= "	prefix6 {$dhcpv6ifconf['prefixrange']['from']} {$dhcpv6ifconf['prefixrange']['to']} /{$dhcpv6ifconf['prefixrange']['prefixlength']};\n";
1528
		}
1529
		if (is_ipaddrv6($dhcpv6ifconf['dns6ip'])) {
1530
			$dns6ip = $dhcpv6ifconf['dns6ip'];
1531
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1532
			    Net_IPv6::isInNetmask($dns6ip, '::', $pdlen)) {
1533
				$dns6ip = merge_ipv6_delegated_prefix($ifcfgipv6, $dns6ip, $pdlen);
1534
			}
1535
			$dhcpdv6conf .= "	option dhcp6.name-servers {$dns6ip};\n";
1536
		}
1537
		// default-lease-time
1538
		if ($dhcpv6ifconf['defaultleasetime']) {
1539
			$dhcpdv6conf .= "	default-lease-time {$dhcpv6ifconf['defaultleasetime']};\n";
1540
		}
1541

    
1542
		// max-lease-time
1543
		if ($dhcpv6ifconf['maxleasetime']) {
1544
			$dhcpdv6conf .= "	max-lease-time {$dhcpv6ifconf['maxleasetime']};\n";
1545
		}
1546

    
1547
		// ntp-servers
1548
		if (is_array($dhcpv6ifconf['ntpserver']) && $dhcpv6ifconf['ntpserver'][0]) {
1549
			$ntpservers = array();
1550
			foreach ($dhcpv6ifconf['ntpserver'] as $ntpserver) {
1551
				if (!is_ipaddrv6($ntpserver)) {
1552
					continue;
1553
				}
1554
				if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1555
				    Net_IPv6::isInNetmask($ntpserver, '::', $pdlen)) {
1556
					$ntpserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ntpserver, $pdlen);
1557
				}
1558
				$ntpservers[] = $ntpserver;
1559
			}
1560
			if (count($ntpservers) > 0) {
1561
				$dhcpdv6conf .= "        option dhcp6.sntp-servers " . join(",", $dhcpv6ifconf['ntpserver']) . ";\n";
1562
			}
1563
		}
1564
		// tftp-server-name
1565
		/* Needs ISC DHCPD support
1566
		 if ($dhcpv6ifconf['tftp'] <> "") {
1567
			$dhcpdv6conf .= "	option tftp-server-name \"{$dhcpv6ifconf['tftp']}\";\n";
1568
		 }
1569
		*/
1570

    
1571
		// Handle option, number rowhelper values
1572
		$dhcpdv6conf .= "\n";
1573
		if (isset($dhcpv6ifconf['numberoptions']['item']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1574
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1575
				$itemv6_value = base64_decode($itemv6['value']);
1576
				$dhcpdv6conf .= "	option custom-{$dhcpv6if}-{$itemv6idx} \"{$itemv6_value}\";\n";
1577
			}
1578
		}
1579

    
1580
		// ldap-server
1581
		if ($dhcpv6ifconf['ldap'] <> "") {
1582
			$ldapserver = $dhcpv6ifconf['ldap'];
1583
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1584
			    Net_IPv6::isInNetmask($ldapserver, '::', $pdlen)) {
1585
				$ldapserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ldapserver, $pdlen);
1586
			}
1587
			$dhcpdv6conf .= "	option ldap-server \"{$ldapserver}\";\n";
1588
		}
1589

    
1590
		// net boot information
1591
		if (isset($dhcpv6ifconf['netboot'])) {
1592
			if (!empty($dhcpv6ifconf['bootfile_url'])) {
1593
				$dhcpdv6conf .= "	option dhcp6.bootfile-url \"{$dhcpv6ifconf['bootfile_url']}\";\n";
1594
			}
1595
		}
1596

    
1597
		$dhcpdv6conf .= "}\n";
1598

    
1599
		/* add static mappings */
1600
		/* Needs to use DUID */
1601
		if (is_array($dhcpv6ifconf['staticmap'])) {
1602
			$i = 0;
1603
			foreach ($dhcpv6ifconf['staticmap'] as $sm) {
1604
				$dhcpdv6conf .= <<<EOD
1605
host s_{$dhcpv6if}_{$i} {
1606
	host-identifier option dhcp6.client-id {$sm['duid']};
1607

    
1608
EOD;
1609
				if ($sm['ipaddrv6']) {
1610
					$ipaddrv6 = $sm['ipaddrv6'];
1611
					if ($ifcfgv6['ipaddrv6'] == 'track6') {
1612
						$ipaddrv6 = merge_ipv6_delegated_prefix($ifcfgipv6, $ipaddrv6, $pdlen);
1613
					}
1614
					$dhcpdv6conf .= "	fixed-address6 {$ipaddrv6};\n";
1615
				}
1616

    
1617
				if ($sm['hostname']) {
1618
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1619
					$dhhostname = str_replace(".", "_", $dhhostname);
1620
					$dhcpdv6conf .= "	option host-name {$dhhostname};\n";
1621
					if (isset($dhcpv6ifconf['ddnsupdate']) &&
1622
					    isset($dhcpv6ifconf['ddnsforcehostname'])) {
1623
						$dhcpdv6conf .= "	ddns-hostname \"{$dhhostname}\";\n";
1624
					}
1625
				}
1626
				if ($sm['filename']) {
1627
					$dhcpdv6conf .= "	filename \"{$sm['filename']}\";\n";
1628
				}
1629

    
1630
				if ($sm['rootpath']) {
1631
					$dhcpdv6conf .= "	option root-path \"{$sm['rootpath']}\";\n";
1632
				}
1633

    
1634
				$dhcpdv6conf .= "}\n";
1635
				$i++;
1636
			}
1637
		}
1638

    
1639
		if ($dhcpv6ifconf['ddnsdomain']) {
1640
			$dhcpdv6conf .= dhcpdkey($dhcpv6ifconf);
1641
			$dhcpdv6conf .= dhcpdzones($ddns_zones);
1642
		}
1643

    
1644
		if ($config['dhcpdv6'][$dhcpv6if]['ramode'] <> "unmanaged" && isset($config['interfaces'][$dhcpv6if]['enable'])) {
1645
			if (preg_match("/poes/si", $dhcpv6if)) {
1646
				/* magic here */
1647
				$dhcpdv6ifs = array_merge($dhcpdv6ifs, get_pppoes_child_interfaces($dhcpv6if));
1648
			} else {
1649
				$realif = get_real_interface($dhcpv6if, "inet6");
1650
				if (stristr("$realif", "bridge")) {
1651
					$mac = get_interface_mac($realif);
1652
					$v6address = generate_ipv6_from_mac($mac);
1653
					/* Create link local address for bridges */
1654
					mwexec("/sbin/ifconfig {$realif} inet6 {$v6address}");
1655
				}
1656
				$realif = escapeshellcmd($realif);
1657
				$dhcpdv6ifs[] = $realif;
1658
			}
1659
		}
1660
	}
1661

    
1662
	if ($nsupdate) {
1663
		$dhcpdv6conf .= "ddns-update-style interim;\n";
1664
	} else {
1665
		$dhcpdv6conf .= "ddns-update-style none;\n";
1666
	}
1667

    
1668
	/* write dhcpdv6.conf */
1669
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf", $dhcpdv6conf)) {
1670
		log_error("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1671
		if (platform_booting()) {
1672
			printf("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1673
		}
1674
		unset($dhcpdv6conf);
1675
		return 1;
1676
	}
1677
	unset($dhcpdv6conf);
1678

    
1679
	/* create an empty leases v6 database */
1680
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases")) {
1681
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1682
	}
1683

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

    
1688
	/* fire up dhcpd in a chroot */
1689
	if (count($dhcpdv6ifs) > 0) {
1690
		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 " .
1691
			join(" ", $dhcpdv6ifs));
1692
		mwexec("/usr/local/sbin/dhcpleases6 -c \"/usr/local/bin/php-cgi -f /usr/local/sbin/prefixes.php|/bin/sh\" -l {$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1693
	}
1694
	if (platform_booting()) {
1695
		print gettext("done.") . "\n";
1696
	}
1697

    
1698
	return 0;
1699
}
1700

    
1701
function services_igmpproxy_configure() {
1702
	global $config, $g;
1703

    
1704
	/* kill any running igmpproxy */
1705
	killbyname("igmpproxy");
1706

    
1707
	if (!isset($config['igmpproxy']['enable'])) {
1708
		return 0;
1709
	}
1710
	if (!is_array($config['igmpproxy']['igmpentry']) || (count($config['igmpproxy']['igmpentry']) == 0)) {
1711
		return 1;
1712
	}
1713

    
1714
	$iflist = get_configured_interface_list();
1715

    
1716
	$igmpconf = <<<EOD
1717

    
1718
##------------------------------------------------------
1719
## Enable Quickleave mode (Sends Leave instantly)
1720
##------------------------------------------------------
1721
quickleave
1722

    
1723
EOD;
1724

    
1725
	foreach ($config['igmpproxy']['igmpentry'] as $igmpcf) {
1726
		unset($iflist[$igmpcf['ifname']]);
1727
		$realif = get_real_interface($igmpcf['ifname']);
1728
		if (empty($igmpcf['threshold'])) {
1729
			$threshld = 1;
1730
		} else {
1731
			$threshld = $igmpcf['threshold'];
1732
		}
1733
		$igmpconf .= "phyint {$realif} {$igmpcf['type']} ratelimit 0 threshold {$threshld}\n";
1734

    
1735
		if ($igmpcf['address'] <> "") {
1736
			$item = explode(" ", $igmpcf['address']);
1737
			foreach ($item as $iww) {
1738
				$igmpconf .= "altnet {$iww}\n";
1739
			}
1740
		}
1741
		$igmpconf .= "\n";
1742
	}
1743
	foreach ($iflist as $ifn) {
1744
		$realif = get_real_interface($ifn);
1745
		$igmpconf .= "phyint {$realif} disabled\n";
1746
	}
1747
	$igmpconf .= "\n";
1748

    
1749
	$igmpfl = fopen($g['varetc_path'] . "/igmpproxy.conf", "w");
1750
	if (!$igmpfl) {
1751
		log_error(gettext("Could not write Igmpproxy configuration file!"));
1752
		return;
1753
	}
1754
	fwrite($igmpfl, $igmpconf);
1755
	fclose($igmpfl);
1756
	unset($igmpconf);
1757

    
1758
	if (isset($config['syslog']['igmpxverbose'])) {
1759
		mwexec_bg("/usr/local/sbin/igmpproxy -v {$g['varetc_path']}/igmpproxy.conf");
1760
	} else {
1761
		mwexec_bg("/usr/local/sbin/igmpproxy {$g['varetc_path']}/igmpproxy.conf");
1762
	}
1763

    
1764
	log_error(gettext("Started IGMP proxy service."));
1765

    
1766
	return 0;
1767
}
1768

    
1769
function services_dhcrelay_configure() {
1770
	global $config, $g;
1771

    
1772
	if (isset($config['system']['developerspew'])) {
1773
		$mt = microtime();
1774
		echo "services_dhcrelay_configure() being called $mt\n";
1775
	}
1776

    
1777
	/* kill any running dhcrelay */
1778
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
1779

    
1780
	init_config_arr(array('dhcrelay'));
1781
	$dhcrelaycfg = &$config['dhcrelay'];
1782

    
1783
	/* DHCPRelay enabled on any interfaces? */
1784
	if (!isset($dhcrelaycfg['enable'])) {
1785
		return 0;
1786
	}
1787

    
1788
	if (platform_booting()) {
1789
		echo gettext("Starting DHCP relay service...");
1790
	} else {
1791
		sleep(1);
1792
	}
1793

    
1794
	$iflist = get_configured_interface_list();
1795

    
1796
	$dhcrelayifs = array();
1797
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1798
	foreach ($dhcifaces as $dhcrelayif) {
1799
		if (!isset($iflist[$dhcrelayif]) ||
1800
		    link_interface_to_bridge($dhcrelayif)) {
1801
			continue;
1802
		}
1803

    
1804
		if (is_ipaddr(get_interface_ip($dhcrelayif))) {
1805
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1806
		}
1807
	}
1808
	$dhcrelayifs = array_unique($dhcrelayifs);
1809

    
1810
	/*
1811
	 * In order for the relay to work, it needs to be active
1812
	 * on the interface in which the destination server sits.
1813
	 */
1814
	$srvips = explode(",", $dhcrelaycfg['server']);
1815
	if (!is_array($srvips)) {
1816
		log_error(gettext("No destination IP has been configured!"));
1817
		return;
1818
	}
1819
	$srvifaces = array();
1820
	foreach ($srvips as $srcidx => $srvip) {
1821
		$destif = guess_interface_from_ip($srvip);
1822
		if (!empty($destif)) {
1823
			$srvifaces[] = $destif;
1824
		}
1825
	}
1826
	$srvifaces = array_unique($srvifaces);
1827

    
1828
	/* The server interface(s) should not be in this list */
1829
	$dhcrelayifs = array_diff($dhcrelayifs, $srvifaces);
1830

    
1831
	/* fire up dhcrelay */
1832
	if (empty($dhcrelayifs)) {
1833
		log_error(gettext("No suitable downstream interfaces found for running dhcrelay!"));
1834
		return; /* XXX */
1835
	}
1836
	if (empty($srvifaces)) {
1837
		log_error(gettext("No suitable upstream interfaces found for running dhcrelay!"));
1838
		return; /* XXX */
1839
	}
1840

    
1841
	$cmd = "/usr/local/sbin/dhcrelay";
1842
	$cmd .= " -id " . implode(" -id ", $dhcrelayifs);
1843
	$cmd .= " -iu " . implode(" -iu ", $srvifaces);
1844

    
1845
	if (isset($dhcrelaycfg['agentoption'])) {
1846
		$cmd .= " -a -m replace";
1847
	}
1848

    
1849
	$cmd .= " " . implode(" ", $srvips);
1850
	mwexec($cmd);
1851
	unset($cmd);
1852

    
1853
	return 0;
1854
}
1855

    
1856
function services_dhcrelay6_configure() {
1857
	global $config, $g;
1858

    
1859
	if (isset($config['system']['developerspew'])) {
1860
		$mt = microtime();
1861
		echo "services_dhcrelay6_configure() being called $mt\n";
1862
	}
1863

    
1864
	/* kill any running dhcrelay */
1865
	killbypid("{$g['varrun_path']}/dhcrelay6.pid");
1866

    
1867
	init_config_arr(array('dhcrelay6'));
1868
	$dhcrelaycfg = &$config['dhcrelay6'];
1869

    
1870
	/* DHCPv6 Relay enabled on any interfaces? */
1871
	if (!isset($dhcrelaycfg['enable'])) {
1872
		return 0;
1873
	}
1874

    
1875
	if (platform_booting()) {
1876
		echo gettext("Starting DHCPv6 relay service...");
1877
	} else {
1878
		sleep(1);
1879
	}
1880

    
1881
	$iflist = get_configured_interface_list();
1882

    
1883
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1884
	foreach ($dhcifaces as $dhcrelayif) {
1885
		if (!isset($iflist[$dhcrelayif]) ||
1886
		    link_interface_to_bridge($dhcrelayif)) {
1887
			continue;
1888
		}
1889

    
1890
		if (is_ipaddrv6(get_interface_ipv6($dhcrelayif))) {
1891
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1892
		}
1893
	}
1894
	$dhcrelayifs = array_unique($dhcrelayifs);
1895

    
1896
	/*
1897
	 * In order for the relay to work, it needs to be active
1898
	 * on the interface in which the destination server sits.
1899
	 */
1900
	$srvips = explode(",", $dhcrelaycfg['server']);
1901
	$srvifaces = array();
1902
	foreach ($srvips as $srcidx => $srvip) {
1903
		$destif = guess_interface_from_ip($srvip);
1904
		if (!empty($destif)) {
1905
			$srvifaces[] = "{$srvip}%{$destif}";
1906
		}
1907
	}
1908

    
1909
	/* fire up dhcrelay */
1910
	if (empty($dhcrelayifs) || empty($srvifaces)) {
1911
		log_error(gettext("No suitable interface found for running dhcrelay -6!"));
1912
		return; /* XXX */
1913
	}
1914

    
1915
	$cmd = "/usr/local/sbin/dhcrelay -6 -pf \"{$g['varrun_path']}/dhcrelay6.pid\"";
1916
	foreach ($dhcrelayifs as $dhcrelayif) {
1917
		$cmd .= " -l {$dhcrelayif}";
1918
	}
1919
	foreach ($srvifaces as $srviface) {
1920
		$cmd .= " -u \"{$srviface}\"";
1921
	}
1922
	mwexec($cmd);
1923
	unset($cmd);
1924

    
1925
	return 0;
1926
}
1927

    
1928
function services_dyndns_configure_client($conf) {
1929

    
1930
	if (!isset($conf['enable'])) {
1931
		return;
1932
	}
1933

    
1934
	/* load up the dyndns.class */
1935
	require_once("dyndns.class");
1936

    
1937
	$dns = new updatedns($dnsService = $conf['type'],
1938
		$dnsHost = $conf['host'],
1939
		$dnsDomain = $conf['domainname'],
1940
		$dnsUser = $conf['username'],
1941
		$dnsPass = $conf['password'],
1942
		$dnsWildcard = $conf['wildcard'],
1943
		$dnsProxied = $conf['proxied'],
1944
		$dnsMX = $conf['mx'],
1945
		$dnsIf = "{$conf['interface']}",
1946
		$dnsBackMX = NULL,
1947
		$dnsServer = NULL,
1948
		$dnsPort = NULL,
1949
		$dnsUpdateURL = "{$conf['updateurl']}",
1950
		$forceUpdate = $conf['force'],
1951
		$dnsZoneID = $conf['zoneid'],
1952
		$dnsTTL = $conf['ttl'],
1953
		$dnsResultMatch = "{$conf['resultmatch']}",
1954
		$dnsRequestIf = "{$conf['requestif']}",
1955
		$dnsID = "{$conf['id']}",
1956
		$dnsVerboseLog = $conf['verboselog'],
1957
		$curlIpresolveV4 = $conf['curl_ipresolve_v4'],
1958
		$curlSslVerifypeer = $conf['curl_ssl_verifypeer']);
1959
}
1960

    
1961
function services_dyndns_configure($int = "") {
1962
	global $config, $g;
1963
	if (isset($config['system']['developerspew'])) {
1964
		$mt = microtime();
1965
		echo "services_dyndns_configure() being called $mt\n";
1966
	}
1967

    
1968
	if (isset($config['dyndnses']['dyndns']) && is_array($config['dyndnses']['dyndns'])) {
1969
		$dyndnscfg = $config['dyndnses']['dyndns'];
1970
	} else {
1971
		return 0;
1972
	}
1973
	$gwgroups = return_gateway_groups_array(true);
1974
	if (is_array($dyndnscfg)) {
1975
		if (platform_booting()) {
1976
			echo gettext("Starting DynDNS clients...");
1977
		}
1978

    
1979
		foreach ($dyndnscfg as $dyndns) {
1980
			/*
1981
			 * If it's using a gateway group, check if interface is
1982
			 * the active gateway for that group
1983
			 */
1984
			$group_int = '';
1985
			$friendly_group_int = '';
1986
			$gwgroup_member = false;
1987
			if (is_array($gwgroups[$dyndns['interface']])) {
1988
				if (!empty($gwgroups[$dyndns['interface']][0]['vip'])) {
1989
					$group_int = $gwgroups[$dyndns['interface']][0]['vip'];
1990
				} else {
1991
					$group_int = $gwgroups[$dyndns['interface']][0]['int'];
1992
					$friendly_group_int =
1993
					    convert_real_interface_to_friendly_interface_name(
1994
						$group_int);
1995
					if (!empty($int)) {
1996
						$gwgroup_member =
1997
						    interface_gateway_group_member(get_real_interface($int),
1998
						    $dyndns['interface']);
1999
					}
2000
				}
2001
			}
2002
			if ((empty($int)) || ($int == $dyndns['interface']) || $gwgroup_member ||
2003
			    ($int == $group_int) || ($int == $friendly_group_int)) {
2004
				$dyndns['verboselog'] = isset($dyndns['verboselog']);
2005
				$dyndns['curl_ipresolve_v4'] = isset($dyndns['curl_ipresolve_v4']);
2006
				$dyndns['curl_ssl_verifypeer'] = isset($dyndns['curl_ssl_verifypeer']);
2007
				$dyndns['proxied'] = isset($dyndns['proxied']);
2008
				services_dyndns_configure_client($dyndns);
2009
				sleep(1);
2010
			}
2011
		}
2012

    
2013
		if (platform_booting()) {
2014
			echo gettext("done.") . "\n";
2015
		}
2016
	}
2017

    
2018
	return 0;
2019
}
2020

    
2021
function dyndnsCheckIP($int) {
2022
	global $config, $factory_default_checkipservice;
2023
	$ip_address = get_interface_ip($int);
2024
	if (is_private_ip($ip_address)) {
2025
		$gateways_status = return_gateways_status(true);
2026
		// If the gateway for this interface is down, then the external check cannot work.
2027
		// Avoid the long wait for the external check to timeout.
2028
		if (stristr($gateways_status[$config['interfaces'][$int]['gateway']]['status'], "down")) {
2029
			return "down";
2030
		}
2031

    
2032
		// Append the factory default check IP service to the list (if not disabled).
2033
		if (!isset($config['checkipservices']['disable_factory_default'])) {
2034
			if (!is_array($config['checkipservices'])) {
2035
				$config['checkipservices'] = array();
2036
			}
2037
			if (!is_array($config['checkipservices']['checkipservice'])) {
2038
				$config['checkipservices']['checkipservice'] = array();
2039
			}
2040
			$config['checkipservices']['checkipservice'][] = $factory_default_checkipservice;
2041
		}
2042

    
2043
		// Use the first enabled check IP service as the default.
2044
		if (is_array($config['checkipservices']['checkipservice'])) {
2045
			foreach ($config['checkipservices']['checkipservice'] as $i => $checkipservice) {
2046
				if (isset($checkipservice['enable'])) {
2047
					$url = $checkipservice['url'];
2048
					$username = $checkipservice['username'];
2049
					$password = $checkipservice['password'];
2050
					$verifysslpeer = isset($checkipservice['verifysslpeer']);
2051
					break;
2052
				}
2053
			}
2054
		}
2055

    
2056
		$hosttocheck = $url;
2057
		$ip_ch = curl_init($hosttocheck);
2058
		curl_setopt($ip_ch, CURLOPT_RETURNTRANSFER, 1);
2059
		curl_setopt($ip_ch, CURLOPT_SSL_VERIFYPEER, $verifysslpeer);
2060
		curl_setopt($ip_ch, CURLOPT_INTERFACE, 'host!' . $ip_address);
2061
		curl_setopt($ip_ch, CURLOPT_CONNECTTIMEOUT, '30');
2062
		curl_setopt($ip_ch, CURLOPT_TIMEOUT, 120);
2063
		curl_setopt($ip_ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
2064
		curl_setopt($ip_ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
2065
		curl_setopt($ip_ch, CURLOPT_USERPWD, "{$username}:{$password}");
2066
		$ip_result_page = curl_exec($ip_ch);
2067
		curl_close($ip_ch);
2068
		$ip_result_decoded = urldecode($ip_result_page);
2069
		preg_match('=Current IP Address: (.*)</body>=siU', $ip_result_decoded, $matches);
2070
		$ip_address = trim($matches[1]);
2071
	}
2072
	return $ip_address;
2073
}
2074

    
2075
function services_dnsmasq_configure($restart_dhcp = true) {
2076
	global $config, $g;
2077
	$return = 0;
2078

    
2079
	// hard coded args: will be removed to avoid duplication if specified in custom_options
2080
	$standard_args = array(
2081
		"dns-forward-max" => "--dns-forward-max=5000",
2082
		"cache-size" => "--cache-size=10000",
2083
		"local-ttl" => "--local-ttl=1"
2084
	);
2085

    
2086

    
2087
	if (isset($config['system']['developerspew'])) {
2088
		$mt = microtime();
2089
		echo "services_dnsmasq_configure() being called $mt\n";
2090
	}
2091

    
2092
	/* kill any running dnsmasq */
2093
	if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) {
2094
		sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
2095
	}
2096

    
2097
	if (isset($config['dnsmasq']['enable'])) {
2098

    
2099
		if (platform_booting()) {
2100
			echo gettext("Starting DNS forwarder...");
2101
		} else {
2102
			sleep(1);
2103
		}
2104

    
2105
		/* generate hosts file */
2106
		if (system_hosts_generate() != 0) {
2107
			$return = 1;
2108
		}
2109

    
2110
		$args = "";
2111

    
2112
		if (isset($config['dnsmasq']['regdhcp'])) {
2113
			$args .= " --dhcp-hostsfile={$g['etc_path']}/hosts ";
2114
		}
2115

    
2116
		/* Setup listen port, if non-default */
2117
		if (is_port($config['dnsmasq']['port'])) {
2118
			$args .= " --port={$config['dnsmasq']['port']} ";
2119
		}
2120

    
2121
		$listen_addresses = "";
2122
		if (isset($config['dnsmasq']['interface'])) {
2123
			$interfaces = explode(",", $config['dnsmasq']['interface']);
2124
			foreach ($interfaces as $interface) {
2125
				$if = get_real_interface($interface);
2126
				if (does_interface_exist($if)) {
2127
					$laddr = get_interface_ip($interface);
2128
					if (is_ipaddrv4($laddr)) {
2129
						$listen_addresses .= " --listen-address={$laddr} ";
2130
					}
2131
					$laddr6 = get_interface_ipv6($interface);
2132
					if (is_ipaddrv6($laddr6) && !isset($config['dnsmasq']['strictbind'])) {
2133
						/*
2134
						 * XXX: Since dnsmasq does not support link-local address
2135
						 * with scope specified. These checks are being done.
2136
						 */
2137
						if (is_linklocal($laddr6) && strstr($laddr6, "%")) {
2138
							$tmpaddrll6 = explode("%", $laddr6);
2139
							$listen_addresses .= " --listen-address={$tmpaddrll6[0]} ";
2140
						} else {
2141
							$listen_addresses .= " --listen-address={$laddr6} ";
2142
						}
2143
					}
2144
				}
2145
			}
2146
			if (!empty($listen_addresses)) {
2147
				$args .= " {$listen_addresses} ";
2148
				if (isset($config['dnsmasq']['strictbind'])) {
2149
					$args .= " --bind-interfaces ";
2150
				}
2151
			}
2152
		}
2153

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

    
2161
			// Build an array of domain overrides to help in checking for matches.
2162
			$override_a = array();
2163
			if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2164
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2165
					$override_a[$override['domain']] = "y";
2166
				}
2167
			}
2168

    
2169
			// Build an array of the private reverse lookup domain names
2170
			$reverse_domain_a = array("10.in-addr.arpa", "168.192.in-addr.arpa");
2171
			// Unfortunately the 172.16.0.0/12 range does not map nicely to the in-addr.arpa scheme.
2172
			for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) {
2173
				$reverse_domain_a[] = "$subnet_num.172.in-addr.arpa";
2174
			}
2175

    
2176
			// Set the --server parameter to nowhere for each reverse domain name that was not specifically specified in a domain override.
2177
			foreach ($reverse_domain_a as $reverse_domain) {
2178
				if (!isset($override_a[$reverse_domain])) {
2179
					$args .= " --server=/$reverse_domain/ ";
2180
				}
2181
			}
2182
			unset($override_a);
2183
			unset($reverse_domain_a);
2184
		}
2185

    
2186
		/* Setup forwarded domains */
2187
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2188
			foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2189
				if ($override['ip'] == "!") {
2190
					$override[ip] = "";
2191
				}
2192
				$args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
2193
			}
2194
		}
2195

    
2196
		/* Allow DNS Rebind for forwarded domains */
2197
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2198
			if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2199
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2200
					$args .= ' --rebind-domain-ok=/' . $override['domain'] . '/ ';
2201
				}
2202
			}
2203
		}
2204

    
2205
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2206
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2207
		}
2208

    
2209
		if (isset($config['dnsmasq']['strict_order'])) {
2210
			$args .= " --strict-order ";
2211
		}
2212

    
2213
		if (isset($config['dnsmasq']['domain_needed'])) {
2214
			$args .= " --domain-needed ";
2215
		}
2216

    
2217
		if ($config['dnsmasq']['custom_options']) {
2218
			foreach (preg_split('/\s+/', $config['dnsmasq']['custom_options']) as $c) {
2219
				$args .= " " . escapeshellarg("--{$c}");
2220
				$p = explode('=', $c);
2221
				if (array_key_exists($p[0], $standard_args)) {
2222
					unset($standard_args[$p[0]]);
2223
				}
2224
			}
2225
		}
2226
		$args .= ' ' . implode(' ', array_values($standard_args));
2227

    
2228
		/* run dnsmasq. Use "-C /dev/null" since we use command line args only (Issue #6730) */
2229
		$cmd = "/usr/local/sbin/dnsmasq --all-servers -C /dev/null {$dns_rebind} {$args}";
2230
		//log_error("dnsmasq command: {$cmd}");
2231
		mwexec_bg($cmd);
2232
		unset($args);
2233

    
2234
		system_dhcpleases_configure();
2235

    
2236
		if (platform_booting()) {
2237
			echo gettext("done.") . "\n";
2238
		}
2239
	}
2240

    
2241
	if (!platform_booting() && $restart_dhcp) {
2242
		if (services_dhcpd_configure() != 0) {
2243
			$return = 1;
2244
		}
2245
	}
2246

    
2247
	return $return;
2248
}
2249

    
2250
function services_unbound_configure($restart_dhcp = true) {
2251
	global $config, $g;
2252
	$return = 0;
2253

    
2254
	if (isset($config['system']['developerspew'])) {
2255
		$mt = microtime();
2256
		echo "services_unbound_configure() being called $mt\n";
2257
	}
2258

    
2259
	if (isset($config['unbound']['enable'])) {
2260
		require_once('/etc/inc/unbound.inc');
2261

    
2262
		/* Stop Unbound using TERM */
2263
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2264
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
2265
		}
2266

    
2267
		/* If unbound is still running, wait up to 30 seconds for it to terminate. */
2268
		for ($i=1; $i <= 30; $i++) {
2269
			if (is_process_running('unbound')) {
2270
				sleep(1);
2271
			}
2272
		}
2273

    
2274
		$python_mode = false;
2275
		if (isset($config['unbound']['python']) && !empty($config['unbound']['python_script'])) {
2276
			$python_mode = true;
2277
		}
2278

    
2279
		/* Include any additional functions as defined by python script include file */
2280
		if (file_exists("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc")) {
2281
			exec("/usr/local/bin/php -l " . escapeshellarg("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc")
2282
				. " 2>&1", $py_output, $py_retval);
2283
			if ($py_retval == 0) {
2284
				require_once("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc");
2285
			}
2286
		}
2287

    
2288
		/* DNS Resolver python integration */
2289
		if ($python_mode) {
2290
			if (!is_dir("{$g['unbound_chroot_path']}/dev")) {
2291
				safe_mkdir("{$g['unbound_chroot_path']}/dev");
2292
			}
2293
			exec("/sbin/mount -t devfs devfs " . escapeshellarg("{$g['unbound_chroot_path']}/dev"));
2294
		} else {
2295
			if (is_dir("{$g['unbound_chroot_path']}/dev")) {
2296
				exec("/sbin/umount -f " . escapeshellarg("{$g['unbound_chroot_path']}/dev"));
2297
			}
2298
		}
2299
		$base_folder = '/usr/local';
2300
		foreach (array('/bin', '/lib') as $dir) {
2301
			$validate = exec("/sbin/mount | /usr/bin/grep " . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir} (nullfs") . " 2>&1");
2302
			if ($python_mode) {
2303

    
2304
				// Add DNS Resolver python integration
2305
				if (empty($validate)) {
2306
					if (!is_dir("{$g['unbound_chroot_path']}{$base_folder}{$dir}")) {
2307
						safe_mkdir("{$g['unbound_chroot_path']}{$base_folder}{$dir}");
2308
					}
2309
					$output = $retval = '';
2310
					exec("/sbin/mount_nullfs -o ro " . escapeshellarg("/usr/local{$dir}") . ' '
2311
					    . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir}") . " 2>&1", $output, $retval);
2312

    
2313
					// Disable Unbound python on mount failure
2314
					if ($retval != 0) {
2315
						$config['unbound']['python'] = '';
2316
						$log_msg = "[Unbound-pymod]: Disabling Unbound python due to failed mount";
2317
						write_config($log_msg);
2318
						log_error($log_msg);
2319
					}
2320
				}
2321
			}
2322

    
2323
			// Remove DNS Resolver python integration
2324
			elseif (!empty($validate)) {
2325
				exec("/sbin/umount -t nullfs " . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir}") . " 2>&1", $output, $retval);
2326
				if ($retval == 0) {
2327
					foreach (array( "/usr/local{$dir}", '/usr/local', '/usr') as $folder) {
2328
						if (!empty($g['unbound_chroot_path']) && $g['unbound_chroot_path'] != '/' && is_dir("{$g['unbound_chroot_path']}{$folder}")) {
2329
							@rmdir(escapeshellarg("{$g['unbound_chroot_path']}{$folder}"));
2330
						}
2331

    
2332
						// Delete remaining subfolders on next loop
2333
						if ($dir == '/bin') {
2334
							break;
2335
						}
2336
					}
2337
				}
2338
				else {
2339
					log_error("[Unbound-pymod]: Failed to unmount!");
2340
				}
2341
			}
2342
		}
2343

    
2344
		if (platform_booting()) {
2345
			echo gettext("Starting DNS Resolver...");
2346
		} else {
2347
			sleep(1);
2348
		}
2349

    
2350
		/* generate hosts file */
2351
		if (system_hosts_generate() != 0) {
2352
			$return = 1;
2353
		}
2354

    
2355
		/* Check here for dhcp6 complete - wait upto 10 seconds */
2356
		if($config['interfaces']["wan"]['ipaddrv6'] == 'dhcp6') {
2357
			$wanif = get_real_interface("wan", "inet6");
2358
			if (platform_booting()) {
2359
				for ($i=1; $i <= 10; $i++) {
2360
					if (!file_exists("/tmp/{$wanif}_dhcp6_complete")) {
2361
						log_error(gettext("Unbound start waiting on dhcp6c."));
2362
						sleep(1);
2363
					} else {
2364
						unlink_if_exists("/tmp/{$wanif}_dhcp6_complete");
2365
						log_error(gettext("dhcp6 init complete. Continuing"));
2366
						break;
2367
					}
2368
				}
2369
			}
2370
		}
2371

    
2372
		sync_unbound_service();
2373
		if (platform_booting()) {
2374
			log_error(gettext("sync unbound done."));
2375
			echo gettext("done.") . "\n";
2376
		}
2377

    
2378
		system_dhcpleases_configure();
2379
	} else {
2380
		/* kill Unbound since it should not be enabled */
2381
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2382
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "KILL");
2383
		}
2384
	}
2385

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

    
2392
	return $return;
2393
}
2394

    
2395
function services_snmpd_configure() {
2396
	global $config, $g;
2397
	if (isset($config['system']['developerspew'])) {
2398
		$mt = microtime();
2399
		echo "services_snmpd_configure() being called $mt\n";
2400
	}
2401

    
2402
	/* kill any running snmpd */
2403
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
2404
	sleep(2);
2405
	if (is_process_running("bsnmpd")) {
2406
		mwexec("/usr/bin/killall bsnmpd", true);
2407
	}
2408

    
2409
	if (isset($config['snmpd']['enable'])) {
2410

    
2411
		if (platform_booting()) {
2412
			echo gettext("Starting SNMP daemon... ");
2413
		}
2414

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

    
2420
		/* generate snmpd.conf */
2421
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
2422
		if (!$fd) {
2423
			printf(gettext("Error: cannot open snmpd.conf in services_snmpd_configure().%s"), "\n");
2424
			return 1;
2425
		}
2426

    
2427

    
2428
		$snmpdconf = <<<EOD
2429
location := "{$config['snmpd']['syslocation']}"
2430
contact := "{$config['snmpd']['syscontact']}"
2431
read := "{$config['snmpd']['rocommunity']}"
2432

    
2433
EOD;
2434

    
2435
/* No docs on what write strings do there so disable for now.
2436
		if (isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])) {
2437
			$snmpdconf .= <<<EOD
2438
# write string
2439
write := "{$config['snmpd']['rwcommunity']}"
2440

    
2441
EOD;
2442
		}
2443
*/
2444

    
2445

    
2446
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2447
			$snmpdconf .= <<<EOD
2448
# SNMP Trap support.
2449
traphost := {$config['snmpd']['trapserver']}
2450
trapport := {$config['snmpd']['trapserverport']}
2451
trap := "{$config['snmpd']['trapstring']}"
2452

    
2453

    
2454
EOD;
2455
		}
2456

    
2457
		$sysDescr = "{$g['product_name']} {$config['system']['hostname']}.{$config['system']['domain']}" .
2458
			" {$g['product_version_string']} {$g['platform']} " . php_uname("s") .
2459
			" " . php_uname("r") . " " . php_uname("m");
2460

    
2461
		$snmpdconf .= <<<EOD
2462
system := 1     # pfSense
2463
%snmpd
2464
sysDescr			= "{$sysDescr}"
2465
begemotSnmpdDebugDumpPdus       = 2
2466
begemotSnmpdDebugSyslogPri      = 7
2467
begemotSnmpdCommunityString.0.1 = $(read)
2468

    
2469
EOD;
2470

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

    
2476
EOD;
2477
		}
2478
*/
2479

    
2480

    
2481
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2482
			$snmpdconf .= <<<EOD
2483
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
2484
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
2485
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
2486

    
2487
EOD;
2488
		}
2489

    
2490

    
2491
		$snmpdconf .= <<<EOD
2492
begemotSnmpdCommunityDisable    = 1
2493

    
2494
EOD;
2495

    
2496
		$bind_to_ips = array();
2497
		if (isset($config['snmpd']['bindip'])) {
2498
			foreach (explode(",", $config['snmpd']['bindip']) as $bind_to_ip) {
2499
				if (is_ipaddr($bind_to_ip)) {
2500
					$bind_to_ips[] = $bind_to_ip;
2501
				} else {
2502
					$if = get_real_interface($bind_to_ip);
2503
					if (does_interface_exist($if)) {
2504
						$bindip = get_interface_ip($bind_to_ip);
2505
						if (is_ipaddr($bindip)) {
2506
							$bind_to_ips[] = $bindip;
2507
						}
2508
					}
2509
				}
2510
			}
2511
		}
2512
		if (!count($bind_to_ips)) {
2513
			$bind_to_ips = array("0.0.0.0");
2514
		}
2515

    
2516
		if (is_port($config['snmpd']['pollport'])) {
2517
			foreach ($bind_to_ips as $bind_to_ip) {
2518
				$snmpdconf .= <<<EOD
2519
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
2520

    
2521
EOD;
2522

    
2523
			}
2524
		}
2525

    
2526
		$snmpdconf .= <<<EOD
2527
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
2528
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
2529

    
2530
# These are bsnmp macros not php vars.
2531
sysContact      = $(contact)
2532
sysLocation     = $(location)
2533
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
2534

    
2535
snmpEnableAuthenTraps = 2
2536

    
2537
EOD;
2538

    
2539
		if (is_array($config['snmpd']['modules'])) {
2540
			if (isset($config['snmpd']['modules']['mibii'])) {
2541
			$snmpdconf .= <<<EOD
2542
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
2543

    
2544
EOD;
2545
			}
2546

    
2547
			if (isset($config['snmpd']['modules']['netgraph'])) {
2548
				$snmpdconf .= <<<EOD
2549
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
2550
%netgraph
2551
begemotNgControlNodeName = "snmpd"
2552

    
2553
EOD;
2554
			}
2555

    
2556
			if (isset($config['snmpd']['modules']['pf'])) {
2557
				$snmpdconf .= <<<EOD
2558
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
2559

    
2560
EOD;
2561
			}
2562

    
2563
			if (isset($config['snmpd']['modules']['hostres'])) {
2564
				$snmpdconf .= <<<EOD
2565
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
2566

    
2567
EOD;
2568
			}
2569

    
2570
			if (isset($config['snmpd']['modules']['bridge'])) {
2571
				$snmpdconf .= <<<EOD
2572
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
2573
# config must end with blank line
2574

    
2575
EOD;
2576
			}
2577
			if (isset($config['snmpd']['modules']['ucd'])) {
2578
				$snmpdconf .= <<<EOD
2579
begemotSnmpdModulePath."ucd"     = "/usr/local/lib/snmp_ucd.so"
2580

    
2581
EOD;
2582
			}
2583
			if (isset($config['snmpd']['modules']['regex'])) {
2584
				$snmpdconf .= <<<EOD
2585
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"
2586

    
2587
EOD;
2588
			}
2589
		}
2590

    
2591
		fwrite($fd, $snmpdconf);
2592
		fclose($fd);
2593
		unset($snmpdconf);
2594

    
2595
		/* run bsnmpd */
2596
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
2597
			" -p {$g['varrun_path']}/snmpd.pid");
2598

    
2599
		if (platform_booting()) {
2600
			echo gettext("done.") . "\n";
2601
		}
2602
	}
2603

    
2604
	return 0;
2605
}
2606

    
2607
function services_dnsupdate_process($int = "", $updatehost = "", $forced = false) {
2608
	global $config, $g;
2609
	if (isset($config['system']['developerspew'])) {
2610
		$mt = microtime();
2611
		echo "services_dnsupdate_process() being called $mt\n";
2612
	}
2613

    
2614
	/* Dynamic DNS updating active? */
2615
	if (!is_array($config['dnsupdates']['dnsupdate'])) {
2616
		return 0;
2617
	}
2618

    
2619
	$notify_text = "";
2620
	$gwgroups = return_gateway_groups_array(true);
2621
	foreach ($config['dnsupdates']['dnsupdate'] as $i => $dnsupdate) {
2622
		if (!isset($dnsupdate['enable'])) {
2623
			continue;
2624
		}
2625
		/*
2626
		 * If it's using a gateway group, check if interface is
2627
		 * the active gateway for that group
2628
		 */
2629
		$group_int = '';
2630
		$friendly_group_int = '';
2631
		$gwgroup_member = false;
2632
		if (is_array($gwgroups[$dnsupdate['interface']])) {
2633
			if (!empty($gwgroups[$dnsupdate['interface']][0]['vip'])) {
2634
				$group_int = $gwgroups[$dnsupdate['interface']][0]['vip'];
2635
			} else {
2636
				$group_int = $gwgroups[$dnsupdate['interface']][0]['int'];
2637
				$friendly_group_int =
2638
				    convert_real_interface_to_friendly_interface_name(
2639
					$group_int);
2640
				if (!empty($int)) {
2641
					$gwgroup_member =
2642
					    interface_gateway_group_member(get_real_interface($int),
2643
					    $dnsupdate['interface']);
2644
				}
2645
			}
2646
		}
2647
		if (!empty($int) && ($int != $dnsupdate['interface']) && !$gwgroup_member &&
2648
		    ($int != $group_int) && ($int != $friendly_group_int)) {
2649
			continue;
2650
		}
2651
		if (!empty($updatehost) && ($updatehost != $dnsupdate['host'])) {
2652
			continue;
2653
		}
2654

    
2655
		/* determine interface name */
2656
		$if = get_failover_interface($dnsupdate['interface']);
2657

    
2658
		/* Determine address to update and default binding address */
2659
		if (isset($dnsupdate['usepublicip'])) {
2660
			$wanip = dyndnsCheckIP($if);
2661
			$bindipv4 = get_interface_ip($if);
2662
		} else {
2663
			$wanip = get_interface_ip($if);
2664
			$bindipv4 = $wanip;
2665
		}
2666
		$wanipv6 = get_interface_ipv6($if);
2667
		$bindipv6 = $wanipv6;
2668

    
2669
		/* Handle non-default interface bindings */
2670
		if ($dnsupdate['updatesource'] == "none") {
2671
			/* When empty, the directive will be omitted. */
2672
			$bindipv4 = "";
2673
			$bindipv6 = "";
2674
		} elseif (!empty($dnsupdate['updatesource'])) {
2675
			/* Find the alternate binding address */
2676
			$bindipv4 = get_interface_ip($dnsupdate['updatesource']);
2677
			$bindipv6 = get_interface_ipv6($dnsupdate['updatesource']);
2678
		}
2679

    
2680
		/* Handle IPv4/IPv6 selection for the update source interface/VIP */
2681
		switch ($dnsupdate['updatesourcefamily']) {
2682
			case "inet":
2683
				$bindip = $bindipv4;
2684
				break;
2685
			case "inet6":
2686
				$bindip = $bindipv6;
2687
				break;
2688
			case "":
2689
			default:
2690
				/* Try IPv4 first, if that is empty, try IPv6. */
2691
				/* Only specify the address if it's present, otherwise omit. */
2692
				if (!empty($bindipv4)) {
2693
					$bindip = $bindipv4;
2694
				} elseif (!empty($bindipv6)) {
2695
					$bindip = $bindipv6;
2696
				}
2697
				break;
2698
		}
2699

    
2700
		$cacheFile = $g['conf_path'] .
2701
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2702
		    escapeshellarg($dnsupdate['host']) .
2703
		    "_{$dnsupdate['server']}.cache";
2704
		$cacheFilev6 = $g['conf_path'] .
2705
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2706
		    escapeshellarg($dnsupdate['host']) .
2707
		    "_{$dnsupdate['server']}_v6.cache";
2708
		$currentTime = time();
2709

    
2710
		if (!$wanip && !$wanipv6) {
2711
			continue;
2712
		}
2713

    
2714
		$keyname = $dnsupdate['keyname'];
2715
		/* trailing dot */
2716
		if (substr($keyname, -1) != ".") {
2717
			$keyname .= ".";
2718
		}
2719

    
2720
		$hostname = $dnsupdate['host'];
2721
		/* trailing dot */
2722
		if (substr($hostname, -1) != ".") {
2723
			$hostname .= ".";
2724
		}
2725

    
2726
		/* write key file */
2727
		$algorithm = empty($dnsupdate['keyalgorithm']) ? 'hmac-md5' : $dnsupdate['keyalgorithm'];
2728
		$upkey = <<<EOD
2729
key "{$keyname}" {
2730
	algorithm {$algorithm};
2731
	secret "{$dnsupdate['keydata']}";
2732
};
2733

    
2734
EOD;
2735
		@file_put_contents("{$g['varetc_path']}/nsupdatekey{$i}", $upkey);
2736

    
2737
		/* generate update instructions */
2738
		$upinst = "";
2739
		if (!empty($dnsupdate['server'])) {
2740
			$upinst .= "server {$dnsupdate['server']}\n";
2741
		}
2742

    
2743
		$cachedipv4 = '';
2744
		$cacheTimev4 = 0;
2745
		if (file_exists($cacheFile)) {
2746
			list($cachedipv4, $cacheTimev4) = explode("|",
2747
			    file_get_contents($cacheFile));
2748
		}
2749
		$cachedipv6 = '';
2750
		$cacheTimev6 = 0;
2751
		if (file_exists($cacheFilev6)) {
2752
			list($cachedipv6, $cacheTimev6) = explode("|",
2753
			    file_get_contents($cacheFilev6));
2754
		}
2755

    
2756
		// 25 Days
2757
		$maxCacheAgeSecs = 25 * 24 * 60 * 60;
2758
		$need_update = false;
2759

    
2760
		/* Update IPv4 if we have it. */
2761
		if (is_ipaddrv4($wanip) && $dnsupdate['recordtype'] != "AAAA") {
2762
			if (($wanip != $cachedipv4) || $forced ||
2763
			    (($currentTime - $cacheTimev4) > $maxCacheAgeSecs)) {
2764
				$upinst .= "update delete " .
2765
				    "{$dnsupdate['host']}. A\n";
2766
				$upinst .= "update add {$dnsupdate['host']}. " .
2767
				    "{$dnsupdate['ttl']} A {$wanip}\n";
2768
				if (!empty($bindip)) {
2769
					$upinst .= "local {$bindip}\n";
2770
				}
2771
				$need_update = true;
2772
			} else {
2773
				log_error(sprintf(gettext(
2774
				    "phpDynDNS: Not updating %s A record because the IP address has not changed."),
2775
				    $dnsupdate['host']));
2776
			}
2777
		} else {
2778
			@unlink($cacheFile);
2779
			unset($cacheFile);
2780
		}
2781

    
2782
		/* Update IPv6 if we have it. */
2783
		if (is_ipaddrv6($wanipv6) && $dnsupdate['recordtype'] != "A") {
2784
			if (($wanipv6 != $cachedipv6) || $forced ||
2785
			    (($currentTime - $cacheTimev6) > $maxCacheAgeSecs)) {
2786
				$upinst .= "update delete " .
2787
				    "{$dnsupdate['host']}. AAAA\n";
2788
				$upinst .= "update add {$dnsupdate['host']}. " .
2789
				    "{$dnsupdate['ttl']} AAAA {$wanipv6}\n";
2790
				$need_update = true;
2791
			} else {
2792
				log_error(sprintf(gettext(
2793
				    "phpDynDNS: Not updating %s AAAA record because the IPv6 address has not changed."),
2794
				    $dnsupdate['host']));
2795
			}
2796
		} else {
2797
			@unlink($cacheFilev6);
2798
			unset($cacheFilev6);
2799
		}
2800

    
2801
		$upinst .= "\n";	/* mind that trailing newline! */
2802

    
2803
		if (!$need_update) {
2804
			continue;
2805
		}
2806

    
2807
		@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}", $upinst);
2808
		unset($upinst);
2809
		/* invoke nsupdate */
2810
		$cmd = "/usr/local/bin/nsupdate -k {$g['varetc_path']}/nsupdatekey{$i}";
2811

    
2812
		if (isset($dnsupdate['usetcp'])) {
2813
			$cmd .= " -v";
2814
		}
2815

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

    
2818
		if (mwexec($cmd) == 0) {
2819
			if (!empty($cacheFile)) {
2820
				@file_put_contents($cacheFile,
2821
				    "{$wanip}|{$currentTime}");
2822
				log_error(sprintf(gettext(
2823
				    'phpDynDNS: updating cache file %1$s: %2$s'),
2824
				    $cacheFile, $wanip));
2825
				$notify_text .= sprintf(gettext(
2826
				    'DynDNS updated IP Address (A) for %1$s on %2$s (%3$s) to %4$s'),
2827
				    $dnsupdate['host'],
2828
				    convert_real_interface_to_friendly_descr($if),
2829
				    $if, $wanip) . "\n";
2830
			}
2831
			if (!empty($cacheFilev6)) {
2832
				@file_put_contents($cacheFilev6,
2833
				    "{$wanipv6}|{$currentTime}");
2834
				log_error(sprintf(gettext(
2835
				    'phpDynDNS: updating cache file %1$s: %2$s'),
2836
				    $cacheFilev6, $wanipv6));
2837
				$notify_text .= sprintf(gettext(
2838
				    'DynDNS updated IPv6 Address (AAAA) for %1$s on %2$s (%3$s) to %4$s'),
2839
				    $dnsupdate['host'],
2840
				    convert_real_interface_to_friendly_descr($if),
2841
				    $if, $wanipv6) . "\n";
2842
			}
2843
		} else {
2844
			if (!empty($cacheFile)) {
2845
				log_error(sprintf(gettext(
2846
				    'phpDynDNS: ERROR while updating IP Address (A) for %1$s (%2$s)'),
2847
				    $dnsupdate['host'], $wanip));
2848
			}
2849
			if (!empty($cacheFilev6)) {
2850
				log_error(sprintf(gettext(
2851
				    'phpDynDNS: ERROR while updating IP Address (AAAA) for %1$s (%2$s)'),
2852
				    $dnsupdate['host'], $wanipv6));
2853
			}
2854
		}
2855
		unset($cmd);
2856
	}
2857

    
2858
	if (!empty($notify_text)) {
2859
		notify_all_remote($notify_text);
2860
	}
2861

    
2862
	return 0;
2863
}
2864

    
2865
/* configure cron service */
2866
function configure_cron() {
2867
	global $g, $config;
2868

    
2869
	/* preserve existing crontab entries */
2870
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2871

    
2872
	for ($i = 0; $i < count($crontab_contents); $i++) {
2873
		$cron_item = &$crontab_contents[$i];
2874
		if (strpos($cron_item, "# pfSense specific crontab entries") !== false) {
2875
			array_splice($crontab_contents, $i - 1);
2876
			break;
2877
		}
2878
	}
2879
	$crontab_contents = implode("\n", $crontab_contents) . "\n";
2880

    
2881

    
2882
	if (is_array($config['cron']['item'])) {
2883
		$crontab_contents .= "#\n";
2884
		$crontab_contents .= "# pfSense specific crontab entries\n";
2885
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
2886
		$crontab_contents .= "#\n";
2887

    
2888
		if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) {
2889
			$http_proxy = $config['system']['proxyurl'];
2890
			if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) {
2891
				$http_proxy .= ':' . $config['system']['proxyport'];
2892
			}
2893
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
2894

    
2895
			if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
2896
				$crontab_contents .= "HTTP_PROXY_AUTH=basic:*:{$config['system']['proxyuser']}:{$config['system']['proxypass']}";
2897
			}
2898
		}
2899

    
2900
		foreach ($config['cron']['item'] as $item) {
2901
			$crontab_contents .= "\n{$item['minute']}\t";
2902
			$crontab_contents .= "{$item['hour']}\t";
2903
			$crontab_contents .= "{$item['mday']}\t";
2904
			$crontab_contents .= "{$item['month']}\t";
2905
			$crontab_contents .= "{$item['wday']}\t";
2906
			$crontab_contents .= "{$item['who']}\t";
2907
			$crontab_contents .= "{$item['command']}";
2908
		}
2909

    
2910
		$crontab_contents .= "\n#\n";
2911
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
2912
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
2913
		$crontab_contents .= "#\n\n";
2914
	}
2915

    
2916
	/* please maintain the newline at the end of file */
2917
	file_put_contents("/etc/crontab", $crontab_contents);
2918
	unset($crontab_contents);
2919

    
2920
	/* make sure that cron is running and start it if it got killed somehow */
2921
	if (!is_process_running("cron")) {
2922
		exec("cd /tmp && /usr/sbin/cron -s 2>/dev/null");
2923
	} else {
2924
	/* do a HUP kill to force sync changes */
2925
		sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP");
2926
	}
2927

    
2928
}
2929

    
2930
function upnp_action ($action) {
2931
	global $g, $config;
2932
	switch ($action) {
2933
		case "start":
2934
			if (file_exists('/var/etc/miniupnpd.conf')) {
2935
				@unlink("{$g['varrun_path']}/miniupnpd.pid");
2936
				mwexec_bg("/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf -P {$g['varrun_path']}/miniupnpd.pid");
2937
			}
2938
			break;
2939
		case "stop":
2940
			killbypid("{$g['varrun_path']}/miniupnpd.pid");
2941
			while ((int)exec("/bin/pgrep -a miniupnpd | wc -l") > 0) {
2942
				mwexec('/usr/bin/killall miniupnpd 2>/dev/null', true);
2943
			}
2944
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
2945
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
2946
			break;
2947
		case "restart":
2948
			upnp_action('stop');
2949
			upnp_action('start');
2950
			break;
2951
	}
2952
}
2953

    
2954
function upnp_start() {
2955
	global $config;
2956

    
2957
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
2958
		return;
2959
	}
2960

    
2961
	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
2962
		echo gettext("Starting UPnP service... ");
2963
		require_once('/usr/local/pkg/miniupnpd.inc');
2964
		sync_package_miniupnpd();
2965
		echo "done.\n";
2966
	}
2967
}
2968

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

    
2972
	$is_installed = false;
2973
	$cron_changed = true;
2974
	$change_message = "";
2975

    
2976
	if (!is_array($config['cron'])) {
2977
		$config['cron'] = array();
2978
	}
2979
	if (!is_array($config['cron']['item'])) {
2980
		$config['cron']['item'] = array();
2981
	}
2982

    
2983
	$x = 0;
2984
	foreach ($config['cron']['item'] as $item) {
2985
		if (strstr($item['command'], $command)) {
2986
			$is_installed = true;
2987
			break;
2988
		}
2989
		$x++;
2990
	}
2991

    
2992
	if ($active) {
2993
		$cron_item = array();
2994
		$cron_item['minute'] = $minute;
2995
		$cron_item['hour'] = $hour;
2996
		$cron_item['mday'] = $monthday;
2997
		$cron_item['month'] = $month;
2998
		$cron_item['wday'] = $weekday;
2999
		$cron_item['who'] = $who;
3000
		$cron_item['command'] = $command;
3001
		if (!$is_installed) {
3002
			$config['cron']['item'][] = $cron_item;
3003
			$change_message = "Installed cron job for %s";
3004
		} else {
3005
			if ($config['cron']['item'][$x] == $cron_item) {
3006
				$cron_changed = false;
3007
			} else {
3008
				$config['cron']['item'][$x] = $cron_item;
3009
				$change_message = "Updated cron job for %s";
3010
			}
3011
		}
3012
	} else {
3013
		if ($is_installed == true) {
3014
			array_splice($config['cron']['item'], $x, 1);
3015
			$change_message = "Removed cron job for %s";
3016
		} else {
3017
			$cron_changed = false;
3018
		}
3019
	}
3020

    
3021
	if ($cron_changed) {
3022
		/* Optionally write the configuration if this function made changes.
3023
		 * Performing a write_config() in this way can have unintended side effects. See #7146
3024
		 * Base system instances of this function do not need to write, packages may.
3025
		 */
3026
		if ($write_config) {
3027
			write_config(sprintf(gettext($change_message), $command));
3028
		}
3029
		configure_cron();
3030
	}
3031
}
3032

    
3033
?>
(46-46/60)