Project

General

Profile

Download (93.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-free 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 (free),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
		$dhcpdconf .= "subnet {$subnet} netmask {$subnetmask} {\n";
793

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

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

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

    
863
			if (isset($poolconf['denyunknown'])) {
864
				$dhcpdconf .= "		$deny_action unknown-clients;\n";
865
			}
866

    
867
			if ($poolconf['gateway'] && $poolconf['gateway'] != "none" && ($poolconf['gateway'] != $dhcpifconf['gateway'])) {
868
				$dhcpdconf .= "		option routers {$poolconf['gateway']};\n";
869
			}
870

    
871
			if ($dhcpifconf['failover_peerip'] <> "") {
872
				$dhcpdconf .= "		failover peer \"dhcp_{$dhcpif}\";\n";
873
			}
874

    
875
			$pdnscfg = "";
876

    
877
			if ($poolconf['domain'] && ($poolconf['domain'] != $dhcpifconf['domain'])) {
878
				$pdnscfg .= "		option domain-name \"{$poolconf['domain']}\";\n";
879
			}
880

    
881
			if (!empty($poolconf['domainsearchlist']) && ($poolconf['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
882
				$pdnscfg .= "		option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $poolconf['domainsearchlist'])) . "\";\n";
883
			}
884

    
885
			if (isset($poolconf['ddnsupdate'])) {
886
				if (($poolconf['ddnsdomain'] <> "") && ($poolconf['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
887
					$pdnscfg .= "		ddns-domainname \"{$poolconf['ddnsdomain']}\";\n";
888
				}
889
				$pdnscfg .= "		ddns-update-style interim;\n";
890
			}
891

    
892
			$dhcpdconf .= "{$pdnscfg}";
893

    
894
			// default-lease-time
895
			if ($poolconf['defaultleasetime'] && ($poolconf['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
896
				$dhcpdconf .= "		default-lease-time {$poolconf['defaultleasetime']};\n";
897
			}
898

    
899
			// max-lease-time
900
			if ($poolconf['maxleasetime'] && ($poolconf['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
901
				$dhcpdconf .= "		max-lease-time {$poolconf['maxleasetime']};\n";
902
			}
903

    
904
			// ignore bootp
905
			if (isset($poolconf['ignorebootp'])) {
906
				$dhcpdconf .= "		ignore bootp;\n";
907
			}
908

    
909
			// ignore-client-uids
910
			if (isset($poolconf['ignoreclientuids'])) {
911
				$dhcpdconf .= "		ignore-client-uids true;\n";
912
			}
913

    
914
			// netbios-name*
915
			if (is_array($poolconf['winsserver']) && $poolconf['winsserver'][0] && ($poolconf['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
916
				$dhcpdconf .= "		option netbios-name-servers " . join(",", $poolconf['winsserver']) . ";\n";
917
				$dhcpdconf .= "		option netbios-node-type 8;\n";
918
			}
919

    
920
			// ntp-servers
921
			if (is_array($poolconf['ntpserver']) && $poolconf['ntpserver'][0] && ($poolconf['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
922
				$dhcpdconf .= "		option ntp-servers " . join(",", $poolconf['ntpserver']) . ";\n";
923
			}
924

    
925
			// tftp-server-name
926
			if (!empty($poolconf['tftp']) && ($poolconf['tftp'] != $dhcpifconf['tftp'])) {
927
				$dhcpdconf .= "		option tftp-server-name \"{$poolconf['tftp']}\";\n";
928
			}
929

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

    
947
			// ldap-server
948
			if (!empty($poolconf['ldap']) && ($poolconf['ldap'] != $dhcpifconf['ldap'])) {
949
				$dhcpdconf .= "		option ldap-server \"{$poolconf['ldap']}\";\n";
950
			}
951

    
952
			// net boot information
953
			if (isset($poolconf['netboot'])) {
954
				if (!empty($poolconf['nextserver']) && ($poolconf['nextserver'] != $dhcpifconf['nextserver'])) {
955
					$dhcpdconf .= "		next-server {$poolconf['nextserver']};\n";
956
				}
957

    
958
				if (!empty($poolconf['filename']) &&
959
				    (!isset($dhcpifconf['filename']) ||
960
				    ($poolconf['filename'] != $dhcpifconf['filename']))) {
961
					$filename = $poolconf['filename'];
962
				}
963
				if (!empty($poolconf['filename32']) &&
964
				    (!isset($dhcpifconf['filename32']) ||
965
				    ($poolconf['filename32'] != $dhcpifconf['filename32']))) {
966
					$filename32 = $poolconf['filename32'];
967
				}
968
				if (!empty($poolconf['filename64']) &&
969
				    (!isset($dhcpifconf['filename64']) ||
970
				    ($poolconf['filename64'] != $dhcpifconf['filename64']))) {
971
					$filename64 = $poolconf['filename64'];
972
				}
973

    
974
				if (!empty($filename32) || !empty($filename64)) {
975
					if (empty($filename) && !empty($dhcpifconf['filename'])) {
976
						$filename = $dhcpifconf['filename'];
977
					}
978
					if (empty($filename32) && !empty($dhcpifconf['filename32'])) {
979
						$filename32 = $dhcpifconf['filename32'];
980
					}
981
					if (empty($filename64) && !empty($dhcpifconf['filename64'])) {
982
						$filename64 = $dhcpifconf['filename64'];
983
					}
984
				}
985

    
986
				if (!empty($filename) && !empty($filename32) && !empty($filename64)) {
987
					$dhcpdconf .= "		if option arch = 00:06 {\n";
988
					$dhcpdconf .= "			filename \"{$filename32}\";\n";
989
					$dhcpdconf .= "		} else if option arch = 00:07 {\n";
990
					$dhcpdconf .= "			filename \"{$filename64}\";\n";
991
					$dhcpdconf .= "		} else if option arch = 00:09 {\n";
992
					$dhcpdconf .= "			filename \"{$filename64}\";\n";
993
					$dhcpdconf .= "		} else {\n";
994
					$dhcpdconf .= "			filename \"{$filename}\";\n";
995
					$dhcpdconf .= "		}\n\n";
996
				} elseif (!empty($filename)) {
997
					$dhcpdconf .= "		filename \"{$filename}\";\n";
998
				}
999
				unset($filename, $filename32, $filename64);
1000

    
1001
				if (!empty($poolconf['rootpath']) && ($poolconf['rootpath'] != $dhcpifconf['rootpath'])) {
1002
					$dhcpdconf .= "		option root-path \"{$poolconf['rootpath']}\";\n";
1003
				}
1004
			}
1005
			$dhcpdconf .= "		range {$poolconf['range']['from']} {$poolconf['range']['to']};\n";
1006
			$dhcpdconf .= "	}\n\n";
1007
		}
1008
// End of settings inside pools
1009

    
1010
		if ($dhcpifconf['gateway'] && $dhcpifconf['gateway'] != "none") {
1011
			$routers = $dhcpifconf['gateway'];
1012
			$add_routers = true;
1013
		} elseif ($dhcpifconf['gateway'] == "none") {
1014
			$add_routers = false;
1015
		} else {
1016
			$add_routers = $enable_add_routers;
1017
			$routers = $ifcfgip;
1018
		}
1019
		if ($add_routers) {
1020
			$dhcpdconf .= "	option routers {$routers};\n";
1021
		}
1022

    
1023
		$dhcpdconf .= <<<EOD
1024
$dnscfg
1025

    
1026
EOD;
1027
		// default-lease-time
1028
		if ($dhcpifconf['defaultleasetime']) {
1029
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
1030
		}
1031

    
1032
		// max-lease-time
1033
		if ($dhcpifconf['maxleasetime']) {
1034
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
1035
		}
1036

    
1037
		if (!isset($dhcpifconf['disablepingcheck'])) {
1038
			$dhcpdconf .= "	ping-check true;\n";
1039
		} else {
1040
			$dhcpdconf .= "	ping-check false;\n";
1041
		}
1042

    
1043
		// netbios-name*
1044
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
1045
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
1046
			$dhcpdconf .= "	option netbios-node-type 8;\n";
1047
		}
1048

    
1049
		// ntp-servers
1050
		if (is_array($dhcpifconf['ntpserver']) && $dhcpifconf['ntpserver'][0]) {
1051
			$dhcpdconf .= "	option ntp-servers " . join(",", $dhcpifconf['ntpserver']) . ";\n";
1052
		}
1053

    
1054
		// tftp-server-name
1055
		if ($dhcpifconf['tftp'] <> "") {
1056
			$dhcpdconf .= "	option tftp-server-name \"{$dhcpifconf['tftp']}\";\n";
1057
		}
1058

    
1059
		// Handle option, number rowhelper values
1060
		$dhcpdconf .= "\n";
1061
		if (isset($dhcpifconf['numberoptions']['item']) && is_array($dhcpifconf['numberoptions']['item'])) {
1062
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
1063
				$item_value = base64_decode($item['value']);
1064
				if (empty($item['type']) || $item['type'] == "text") {
1065
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} \"{$item_value}\";\n";
1066
				} else {
1067
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} {$item_value};\n";
1068
				}
1069
			}
1070
		}
1071

    
1072
		// ldap-server
1073
		if ($dhcpifconf['ldap'] <> "") {
1074
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
1075
		}
1076

    
1077
		// net boot information
1078
		if (isset($dhcpifconf['netboot'])) {
1079
			if ($dhcpifconf['nextserver'] <> "") {
1080
				$dhcpdconf .= "	next-server {$dhcpifconf['nextserver']};\n";
1081
			}
1082
			if (!empty($dhcpifconf['filename']) && !empty($dhcpifconf['filename32']) && !empty($dhcpifconf['filename64'])) {
1083
				$dhcpdconf .= "	if option arch = 00:06 {\n";
1084
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename32']}\";\n";
1085
				$dhcpdconf .= "	} else if option arch = 00:07 {\n";
1086
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1087
				$dhcpdconf .= "	} else if option arch = 00:09 {\n";
1088
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1089
				$dhcpdconf .= "	} else {\n";
1090
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename']}\";\n";
1091
				$dhcpdconf .= "	}\n\n";
1092
			} elseif (!empty($dhcpifconf['filename'])) {
1093
				$dhcpdconf .= "	filename \"{$dhcpifconf['filename']}\";\n";
1094
			}
1095
			if (!empty($dhcpifconf['rootpath'])) {
1096
				$dhcpdconf .= "	option root-path \"{$dhcpifconf['rootpath']}\";\n";
1097
			}
1098
		}
1099

    
1100
		$dhcpdconf .= <<<EOD
1101
}
1102

    
1103
EOD;
1104

    
1105
		/* add static mappings */
1106
		if (is_array($dhcpifconf['staticmap'])) {
1107

    
1108
			$i = 0;
1109
			foreach ($dhcpifconf['staticmap'] as $sm) {
1110
				$dhcpdconf .= "host s_{$dhcpif}_{$i} {\n";
1111

    
1112
				if ($sm['mac']) {
1113
					$dhcpdconf .= "        hardware ethernet {$sm['mac']};\n";
1114
				}
1115

    
1116
				if ($sm['cid']) {
1117
					$dhcpdconf .= "        option dhcp-client-identifier \"{$sm['cid']}\";\n";
1118
				}
1119

    
1120
				if ($sm['ipaddr']) {
1121
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
1122
				}
1123

    
1124
				if ($sm['hostname']) {
1125
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1126
					$dhhostname = str_replace(".", "_", $dhhostname);
1127
					$dhcpdconf .= "	option host-name \"{$dhhostname}\";\n";
1128
					if ((isset($dhcpifconf['ddnsupdate']) || isset($sm['ddnsupdate'])) && (isset($dhcpifconf['ddnsforcehostname']) || isset($sm['ddnsforcehostname']))) {
1129
						$dhcpdconf .= "	ddns-hostname \"{$dhhostname}\";\n";
1130
					}
1131
				}
1132
				if ($sm['filename']) {
1133
					$dhcpdconf .= "	filename \"{$sm['filename']}\";\n";
1134
				}
1135

    
1136
				if ($sm['rootpath']) {
1137
					$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1138
				}
1139

    
1140
				if ($sm['gateway'] && ($sm['gateway'] != $dhcpifconf['gateway'])) {
1141
					$dhcpdconf .= "	option routers {$sm['gateway']};\n";
1142
				}
1143

    
1144
				$smdnscfg = "";
1145

    
1146
				if ($sm['domain'] && ($sm['domain'] != $dhcpifconf['domain'])) {
1147
					$smdnscfg .= "	option domain-name \"{$sm['domain']}\";\n";
1148
				}
1149

    
1150
				if (!empty($sm['domainsearchlist']) && ($sm['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
1151
					$smdnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $sm['domainsearchlist'])) . "\";\n";
1152
				}
1153

    
1154
				if (isset($sm['ddnsupdate'])) {
1155
					if (($sm['ddnsdomain'] <> "") && ($sm['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
1156
						$smdnscfg .= "		ddns-domainname \"{$sm['ddnsdomain']}\";\n";
1157
					}
1158
					$smdnscfg .= "		ddns-update-style interim;\n";
1159
				}
1160

    
1161
				if (is_array($sm['dnsserver']) && ($sm['dnsserver'][0]) && ($sm['dnsserver'][0] != $dhcpifconf['dnsserver'][0])) {
1162
					$smdnscfg .= "	option domain-name-servers " . join(",", $sm['dnsserver']) . ";\n";
1163
				}
1164
				$dhcpdconf .= "{$smdnscfg}";
1165

    
1166
				// default-lease-time
1167
				if ($sm['defaultleasetime'] && ($sm['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
1168
					$dhcpdconf .= "	default-lease-time {$sm['defaultleasetime']};\n";
1169
				}
1170

    
1171
				// max-lease-time
1172
				if ($sm['maxleasetime'] && ($sm['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
1173
					$dhcpdconf .= "	max-lease-time {$sm['maxleasetime']};\n";
1174
				}
1175

    
1176
				// netbios-name*
1177
				if (is_array($sm['winsserver']) && $sm['winsserver'][0] && ($sm['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
1178
					$dhcpdconf .= "	option netbios-name-servers " . join(",", $sm['winsserver']) . ";\n";
1179
					$dhcpdconf .= "	option netbios-node-type 8;\n";
1180
				}
1181

    
1182
				// ntp-servers
1183
				if (is_array($sm['ntpserver']) && $sm['ntpserver'][0] && ($sm['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
1184
					$dhcpdconf .= "	option ntp-servers " . join(",", $sm['ntpserver']) . ";\n";
1185
				}
1186

    
1187
				// tftp-server-name
1188
				if (!empty($sm['tftp']) && ($sm['tftp'] != $dhcpifconf['tftp'])) {
1189
					$dhcpdconf .= "	option tftp-server-name \"{$sm['tftp']}\";\n";
1190
				}
1191

    
1192
				$dhcpdconf .= "}\n";
1193
				$i++;
1194
			}
1195
		}
1196

    
1197
		$dhcpdifs[] = get_real_interface($dhcpif);
1198
		if ($newzone['domain-name']) {
1199
			if ($need_ddns_updates) {
1200
				$newzone['dns-servers'] = array($dhcpifconf['ddnsdomainprimary']);
1201
				$newzone['ddnsdomainkeyname'] = $dhcpifconf['ddnsdomainkeyname'];
1202
				$newzone['ddnsdomainkeyalgorithm'] = $dhcpifconf['ddnsdomainkeyalgorithm'];
1203
				$newzone['ddnsdomainkey'] = $dhcpifconf['ddnsdomainkey'];
1204
				$dhcpdconf .= dhcpdkey($dhcpifconf);
1205
			}
1206
			$ddns_zones[] = $newzone;
1207
		}
1208
	}
1209

    
1210
	if ($need_ddns_updates) {
1211
		$dhcpdconf .= "ddns-update-style interim;\n";
1212
		$dhcpdconf .= "update-static-leases on;\n";
1213

    
1214
		$dhcpdconf .= dhcpdzones($ddns_zones);
1215
	}
1216

    
1217
	/* write dhcpd.conf */
1218
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpd.conf", $dhcpdconf)) {
1219
		printf(gettext("Error: cannot open dhcpd.conf in services_dhcpdv4_configure().%s"), "\n");
1220
		unset($dhcpdconf);
1221
		return 1;
1222
	}
1223
	unset($dhcpdconf);
1224

    
1225
	/* create an empty leases database */
1226
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
1227
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
1228
	}
1229

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

    
1234
	/* fire up dhcpd in a chroot */
1235
	if (count($dhcpdifs) > 0) {
1236
		mwexec("/usr/local/sbin/dhcpd -user dhcpd -group _dhcp -chroot {$g['dhcpd_chroot_path']} -cf /etc/dhcpd.conf -pf {$g['varrun_path']}/dhcpd.pid " .
1237
			join(" ", $dhcpdifs));
1238
	}
1239

    
1240
	if (platform_booting()) {
1241
		print "done.\n";
1242
	}
1243

    
1244
	return 0;
1245
}
1246

    
1247
function dhcpdkey($dhcpifconf) {
1248
	$dhcpdconf = "";
1249
	if (!empty($dhcpifconf['ddnsdomainkeyname']) && !empty($dhcpifconf['ddnsdomainkey'])) {
1250
		$algorithm = empty($dhcpifconf['ddnsdomainkeyalgorithm']) ? 'hmac-md5' : $dhcpifconf['ddnsdomainkeyalgorithm'];
1251
		$dhcpdconf .= "key {$dhcpifconf['ddnsdomainkeyname']} {\n";
1252
		$dhcpdconf .= "	algorithm {$algorithm};\n";
1253
		$dhcpdconf .= "	secret {$dhcpifconf['ddnsdomainkey']};\n";
1254
		$dhcpdconf .= "}\n";
1255
	}
1256

    
1257
	return $dhcpdconf;
1258
}
1259

    
1260
function dhcpdzones($ddns_zones) {
1261
	$dhcpdconf = "";
1262

    
1263
	if (is_array($ddns_zones)) {
1264
		$added_zones = array();
1265
		foreach ($ddns_zones as $zone) {
1266
			if (!is_array($zone) || empty($zone) || !is_array($zone['dns-servers'])) {
1267
				continue;
1268
			}
1269
			$primary = $zone['dns-servers'][0];
1270
			$secondary = empty($zone['dns-servers'][1]) ? "" : $zone['dns-servers'][1];
1271

    
1272
			// Make sure we aren't using any invalid or IPv6 DNS servers.
1273
			if (!is_ipaddrv4($primary)) {
1274
				if (is_ipaddrv4($secondary)) {
1275
					$primary = $secondary;
1276
					$secondary = "";
1277
				} else {
1278
					continue;
1279
				}
1280
			}
1281

    
1282
			// We don't need to add zones multiple times.
1283
			if ($zone['domain-name'] && !in_array($zone['domain-name'], $added_zones)) {
1284
				$dhcpdconf .= "zone {$zone['domain-name']}. {\n";
1285
				$dhcpdconf .= "	primary {$primary};\n";
1286
				if (is_ipaddrv4($secondary)) {
1287
					$dhcpdconf .= "	secondary {$secondary};\n";
1288
				}
1289
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1290
					$dhcpdconf .= "	key {$zone['ddnsdomainkeyname']};\n";
1291
				}
1292
				$dhcpdconf .= "}\n";
1293
				$added_zones[] = $zone['domain-name'];
1294
			}
1295
			if ($zone['ptr-domain'] && !in_array($zone['ptr-domain'], $added_zones)) {
1296
				$dhcpdconf .= "zone {$zone['ptr-domain']} {\n";
1297
				$dhcpdconf .= "	primary {$primary};\n";
1298
				if (is_ipaddrv4($secondary)) {
1299
					$dhcpdconf .= "	secondary {$secondary};\n";
1300
				}
1301
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1302
					$dhcpdconf .= "	key {$zone['ddnsdomainkeyname']};\n";
1303
				}
1304
				$dhcpdconf .= "}\n";
1305
				$added_zones[] = $zone['ptr-domain'];
1306
			}
1307
		}
1308
	}
1309

    
1310
	return $dhcpdconf;
1311
}
1312

    
1313
function services_dhcpdv6_configure($blacklist = array()) {
1314
	global $config, $g;
1315

    
1316
	if ($g['services_dhcp_server_enable'] == false) {
1317
		return;
1318
	}
1319

    
1320
	if (isset($config['system']['developerspew'])) {
1321
		$mt = microtime();
1322
		echo "services_dhcpd_configure($if) being called $mt\n";
1323
	}
1324

    
1325
	/* kill any running dhcpd */
1326
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid")) {
1327
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid");
1328
	}
1329
	if (isvalidpid("{$g['varrun_path']}/dhcpleases6.pid")) {
1330
		killbypid("{$g['varrun_path']}/dhcpleases6.pid");
1331
	}
1332

    
1333
	/* DHCP enabled on any interfaces? */
1334
	if (!is_dhcpv6_server_enabled()) {
1335
		return 0;
1336
	}
1337

    
1338
	$syscfg = $config['system'];
1339
	if (!is_array($config['dhcpdv6'])) {
1340
		$config['dhcpdv6'] = array();
1341
	}
1342
	$dhcpdv6cfg = $config['dhcpdv6'];
1343
	$Iflist = get_configured_interface_list();
1344
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
1345

    
1346

    
1347
	if (platform_booting()) {
1348
		echo "Starting DHCPv6 service...";
1349
	} else {
1350
		sleep(1);
1351
	}
1352

    
1353
	$custoptionsv6 = "";
1354
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1355
		if (is_array($dhcpv6ifconf['numberoptions']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1356
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1357
				$custoptionsv6 .= "option custom-{$dhcpv6if}-{$itemv6idx} code {$itemv6['number']} = text;\n";
1358
			}
1359
		}
1360
	}
1361

    
1362
	if (isset($dhcpv6ifconf['netboot']) && !empty($dhcpv6ifconf['bootfile_url'])) {
1363
		$custoptionsv6 .= "option dhcp6.bootfile-url code 59 = string;\n";
1364
	}
1365

    
1366
	$dhcpdv6conf = <<<EOD
1367

    
1368
option domain-name "{$syscfg['domain']}";
1369
option ldap-server code 95 = text;
1370
option domain-search-list code 119 = text;
1371
{$custoptionsv6}
1372
default-lease-time 7200;
1373
max-lease-time 86400;
1374
log-facility local7;
1375
one-lease-per-client true;
1376
deny duplicates;
1377
ping-check true;
1378
update-conflict-detection false;
1379

    
1380
EOD;
1381

    
1382
	if (!isset($dhcpv6ifconf['disableauthoritative'])) {
1383
		$dhcpdv6conf .= "authoritative;\n";
1384
	}
1385

    
1386
	if (isset($dhcpv6ifconf['alwaysbroadcast'])) {
1387
		$dhcpdv6conf .= "always-broadcast on\n";
1388
	}
1389

    
1390
	$dhcpdv6ifs = array();
1391

    
1392
	$dhcpv6num = 0;
1393
	$nsupdate = false;
1394

    
1395
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1396

    
1397
		$ddns_zones = array();
1398

    
1399
		$ifcfgv6 = $config['interfaces'][$dhcpv6if];
1400

    
1401
		if (!isset($dhcpv6ifconf['enable']) || !isset($Iflist[$dhcpv6if]) || !isset($ifcfgv6['enable'])) {
1402
			continue;
1403
		}
1404
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1405
		if (!is_ipaddrv6($ifcfgipv6)) {
1406
			continue;
1407
		}
1408
		$ifcfgsnv6 = get_interface_subnetv6($dhcpv6if);
1409
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1410
		// We might have some prefix-delegation on WAN (e.g. /48),
1411
		// but then it is split and given out to individual interfaces
1412
		// (LAN, OPT1, OPT2...) as multiple /64 subnets. So the size
1413
		// of each subnet here is always /64.
1414
		$pdlen = 64;
1415

    
1416
		$dnscfgv6 = "";
1417

    
1418
		if ($dhcpv6ifconf['domain']) {
1419
			$dnscfgv6 .= "	option domain-name \"{$dhcpv6ifconf['domain']}\";\n";
1420
		}
1421

    
1422
		if ($dhcpv6ifconf['domainsearchlist'] <> "") {
1423
			$dnscfgv6 .= "	option dhcp6.domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpv6ifconf['domainsearchlist'])) . "\";\n";
1424
		}
1425

    
1426
		if (isset($dhcpv6ifconf['ddnsupdate'])) {
1427
			if ($dhcpv6ifconf['ddnsdomain'] <> "") {
1428
				$dnscfgv6 .= "	ddns-domainname \"{$dhcpv6ifconf['ddnsdomain']}\";\n";
1429
			}
1430
			if (empty($dhcpv6ifconf['ddnsclientupdates'])) {
1431
				$ddnsclientupdates = 'allow';
1432
			} else {
1433
				$ddnsclientupdates = $dhcpv6ifconf['ddnsclientupdates'];
1434
			}
1435
			$dnscfgv6 .= "	{$ddnsclientupdates} client-updates;\n";
1436
			$nsupdate = true;
1437
		} else {
1438
			$dnscfgv6 .= "	do-forward-updates false;\n";
1439
		}
1440

    
1441
		if ($dhcpv6ifconf['dhcp6c-dns'] != 'disabled') {
1442
			if (is_array($dhcpv6ifconf['dnsserver']) && ($dhcpv6ifconf['dnsserver'][0])) {
1443
				$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dhcpv6ifconf['dnsserver']) . ";";
1444
			} else if (((isset($config['dnsmasq']['enable'])) || isset($config['unbound']['enable'])) && (is_ipaddrv6($ifcfgipv6))) {
1445
				$dnscfgv6 .= "	option dhcp6.name-servers {$ifcfgipv6};";
1446
			} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1447
				$dns_arrv6 = array();
1448
				foreach ($syscfg['dnsserver'] as $dnsserver) {
1449
					if (is_ipaddrv6($dnsserver)) {
1450
						$dns_arrv6[] = $dnsserver;
1451
					}
1452
				}
1453
				if (!empty($dns_arrv6)) {
1454
					$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dns_arrv6) . ";";
1455
				}
1456
			}
1457
		} else {
1458
			$dnscfgv6 .= "	#option dhcp6.name-servers --;";
1459
		}
1460

    
1461
		if (!is_ipaddrv6($ifcfgipv6)) {
1462
			$ifcfgsnv6 = "64";
1463
			$subnetv6 = gen_subnetv6($dhcpv6ifconf['range']['from'], $ifcfgsnv6);
1464
		}
1465

    
1466
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1467

    
1468
		if (isset($dhcpv6ifconf['ddnsupdate']) &&
1469
		    !empty($dhcpv6ifconf['ddnsdomain'])) {
1470
			$newzone = array();
1471
			$newzone['domain-name'] = $dhcpv6ifconf['ddnsdomain'];
1472
			$newzone['dns-servers'][] = $dhcpv6ifconf['ddnsdomainprimary'];
1473
			$newzone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1474
			$newzone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1475
			$ddns_zones[] = $newzone;
1476
			if (isset($dhcpv6ifconf['ddnsreverse'])) {
1477
				$ptr_zones = get_v6_ptr_zones($subnetv6, $ifcfgsnv6);
1478
				foreach ($ptr_zones as $ptr_zone) {
1479
					$reversezone = array();
1480
					$reversezone['ptr-domain'] = $ptr_zone;
1481
					$reversezone['dns-servers'][] = $dhcpv6ifconf['ddnsdomainprimary'];
1482
					$reversezone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1483
					$reversezone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1484
					$ddns_zones[] = $reversezone;
1485
				}
1486
			}
1487
		}
1488

    
1489
		$dhcpdv6conf .= " {\n";
1490

    
1491
		$range_from = $dhcpv6ifconf['range']['from'];
1492
		$range_to = $dhcpv6ifconf['range']['to'];
1493
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
1494
			$range_from = merge_ipv6_delegated_prefix($ifcfgipv6, $range_from, $pdlen);
1495
			$range_to = merge_ipv6_delegated_prefix($ifcfgipv6, $range_to, $pdlen);
1496
		}
1497

    
1498
		$dhcpdv6conf .= <<<EOD
1499
	range6 {$range_from} {$range_to};
1500
$dnscfgv6
1501

    
1502
EOD;
1503

    
1504
		if (is_ipaddrv6($dhcpv6ifconf['prefixrange']['from']) && is_ipaddrv6($dhcpv6ifconf['prefixrange']['to'])) {
1505
			$dhcpdv6conf .= "	prefix6 {$dhcpv6ifconf['prefixrange']['from']} {$dhcpv6ifconf['prefixrange']['to']} /{$dhcpv6ifconf['prefixrange']['prefixlength']};\n";
1506
		}
1507
		if (is_ipaddrv6($dhcpv6ifconf['dns6ip'])) {
1508
			$dns6ip = $dhcpv6ifconf['dns6ip'];
1509
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1510
			    Net_IPv6::isInNetmask($dns6ip, '::', $pdlen)) {
1511
				$dns6ip = merge_ipv6_delegated_prefix($ifcfgipv6, $dns6ip, $pdlen);
1512
			}
1513
			$dhcpdv6conf .= "	option dhcp6.name-servers {$dns6ip};\n";
1514
		}
1515
		// default-lease-time
1516
		if ($dhcpv6ifconf['defaultleasetime']) {
1517
			$dhcpdv6conf .= "	default-lease-time {$dhcpv6ifconf['defaultleasetime']};\n";
1518
		}
1519

    
1520
		// max-lease-time
1521
		if ($dhcpv6ifconf['maxleasetime']) {
1522
			$dhcpdv6conf .= "	max-lease-time {$dhcpv6ifconf['maxleasetime']};\n";
1523
		}
1524

    
1525
		// ntp-servers
1526
		if (is_array($dhcpv6ifconf['ntpserver']) && $dhcpv6ifconf['ntpserver'][0]) {
1527
			$ntpservers = array();
1528
			foreach ($dhcpv6ifconf['ntpserver'] as $ntpserver) {
1529
				if (!is_ipaddrv6($ntpserver)) {
1530
					continue;
1531
				}
1532
				if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1533
				    Net_IPv6::isInNetmask($ntpserver, '::', $pdlen)) {
1534
					$ntpserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ntpserver, $pdlen);
1535
				}
1536
				$ntpservers[] = $ntpserver;
1537
			}
1538
			if (count($ntpservers) > 0) {
1539
				$dhcpdv6conf .= "        option dhcp6.sntp-servers " . join(",", $dhcpv6ifconf['ntpserver']) . ";\n";
1540
			}
1541
		}
1542
		// tftp-server-name
1543
		/* Needs ISC DHCPD support
1544
		 if ($dhcpv6ifconf['tftp'] <> "") {
1545
			$dhcpdv6conf .= "	option tftp-server-name \"{$dhcpv6ifconf['tftp']}\";\n";
1546
		 }
1547
		*/
1548

    
1549
		// Handle option, number rowhelper values
1550
		$dhcpdv6conf .= "\n";
1551
		if (isset($dhcpv6ifconf['numberoptions']['item']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1552
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1553
				$itemv6_value = base64_decode($itemv6['value']);
1554
				$dhcpdv6conf .= "	option custom-{$dhcpv6if}-{$itemv6idx} \"{$itemv6_value}\";\n";
1555
			}
1556
		}
1557

    
1558
		// ldap-server
1559
		if ($dhcpv6ifconf['ldap'] <> "") {
1560
			$ldapserver = $dhcpv6ifconf['ldap'];
1561
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1562
			    Net_IPv6::isInNetmask($ldapserver, '::', $pdlen)) {
1563
				$ldapserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ldapserver, $pdlen);
1564
			}
1565
			$dhcpdv6conf .= "	option ldap-server \"{$ldapserver}\";\n";
1566
		}
1567

    
1568
		// net boot information
1569
		if (isset($dhcpv6ifconf['netboot'])) {
1570
			if (!empty($dhcpv6ifconf['bootfile_url'])) {
1571
				$dhcpdv6conf .= "	option dhcp6.bootfile-url \"{$dhcpv6ifconf['bootfile_url']}\";\n";
1572
			}
1573
		}
1574

    
1575
		$dhcpdv6conf .= "}\n";
1576

    
1577
		/* add static mappings */
1578
		/* Needs to use DUID */
1579
		if (is_array($dhcpv6ifconf['staticmap'])) {
1580
			$i = 0;
1581
			foreach ($dhcpv6ifconf['staticmap'] as $sm) {
1582
				$dhcpdv6conf .= <<<EOD
1583
host s_{$dhcpv6if}_{$i} {
1584
	host-identifier option dhcp6.client-id {$sm['duid']};
1585

    
1586
EOD;
1587
				if ($sm['ipaddrv6']) {
1588
					$ipaddrv6 = $sm['ipaddrv6'];
1589
					if ($ifcfgv6['ipaddrv6'] == 'track6') {
1590
						$ipaddrv6 = merge_ipv6_delegated_prefix($ifcfgipv6, $ipaddrv6, $pdlen);
1591
					}
1592
					$dhcpdv6conf .= "	fixed-address6 {$ipaddrv6};\n";
1593
				}
1594

    
1595
				if ($sm['hostname']) {
1596
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1597
					$dhhostname = str_replace(".", "_", $dhhostname);
1598
					$dhcpdv6conf .= "	option host-name {$dhhostname};\n";
1599
					if (isset($dhcpv6ifconf['ddnsupdate']) &&
1600
					    isset($dhcpv6ifconf['ddnsforcehostname'])) {
1601
						$dhcpdv6conf .= "	ddns-hostname \"{$dhhostname}\";\n";
1602
					}
1603
				}
1604
				if ($sm['filename']) {
1605
					$dhcpdv6conf .= "	filename \"{$sm['filename']}\";\n";
1606
				}
1607

    
1608
				if ($sm['rootpath']) {
1609
					$dhcpdv6conf .= "	option root-path \"{$sm['rootpath']}\";\n";
1610
				}
1611

    
1612
				$dhcpdv6conf .= "}\n";
1613
				$i++;
1614
			}
1615
		}
1616

    
1617
		if ($dhcpv6ifconf['ddnsdomain']) {
1618
			$dhcpdv6conf .= dhcpdkey($dhcpv6ifconf);
1619
			$dhcpdv6conf .= dhcpdzones($ddns_zones);
1620
		}
1621

    
1622
		if ($config['dhcpdv6'][$dhcpv6if]['ramode'] <> "unmanaged" && isset($config['interfaces'][$dhcpv6if]['enable'])) {
1623
			if (preg_match("/poes/si", $dhcpv6if)) {
1624
				/* magic here */
1625
				$dhcpdv6ifs = array_merge($dhcpdv6ifs, get_pppoes_child_interfaces($dhcpv6if));
1626
			} else {
1627
				$realif = get_real_interface($dhcpv6if, "inet6");
1628
				if (stristr("$realif", "bridge")) {
1629
					$mac = get_interface_mac($realif);
1630
					$v6address = generate_ipv6_from_mac($mac);
1631
					/* Create link local address for bridges */
1632
					mwexec("/sbin/ifconfig {$realif} inet6 {$v6address}");
1633
				}
1634
				$realif = escapeshellcmd($realif);
1635
				$dhcpdv6ifs[] = $realif;
1636
			}
1637
		}
1638
	}
1639

    
1640
	if ($nsupdate) {
1641
		$dhcpdv6conf .= "ddns-update-style interim;\n";
1642
	} else {
1643
		$dhcpdv6conf .= "ddns-update-style none;\n";
1644
	}
1645

    
1646
	/* write dhcpdv6.conf */
1647
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf", $dhcpdv6conf)) {
1648
		log_error("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1649
		if (platform_booting()) {
1650
			printf("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1651
		}
1652
		unset($dhcpdv6conf);
1653
		return 1;
1654
	}
1655
	unset($dhcpdv6conf);
1656

    
1657
	/* create an empty leases v6 database */
1658
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases")) {
1659
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1660
	}
1661

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

    
1666
	/* fire up dhcpd in a chroot */
1667
	if (count($dhcpdv6ifs) > 0) {
1668
		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 " .
1669
			join(" ", $dhcpdv6ifs));
1670
		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");
1671
	}
1672
	if (platform_booting()) {
1673
		print gettext("done.") . "\n";
1674
	}
1675

    
1676
	return 0;
1677
}
1678

    
1679
function services_igmpproxy_configure() {
1680
	global $config, $g;
1681

    
1682
	/* kill any running igmpproxy */
1683
	killbyname("igmpproxy");
1684

    
1685
	if (!isset($config['igmpproxy']['enable'])) {
1686
		return 0;
1687
	}
1688
	if (!is_array($config['igmpproxy']['igmpentry']) || (count($config['igmpproxy']['igmpentry']) == 0)) {
1689
		return 1;
1690
	}
1691

    
1692
	$iflist = get_configured_interface_list();
1693

    
1694
	$igmpconf = <<<EOD
1695

    
1696
##------------------------------------------------------
1697
## Enable Quickleave mode (Sends Leave instantly)
1698
##------------------------------------------------------
1699
quickleave
1700

    
1701
EOD;
1702

    
1703
	foreach ($config['igmpproxy']['igmpentry'] as $igmpcf) {
1704
		unset($iflist[$igmpcf['ifname']]);
1705
		$realif = get_real_interface($igmpcf['ifname']);
1706
		if (empty($igmpcf['threshold'])) {
1707
			$threshld = 1;
1708
		} else {
1709
			$threshld = $igmpcf['threshold'];
1710
		}
1711
		$igmpconf .= "phyint {$realif} {$igmpcf['type']} ratelimit 0 threshold {$threshld}\n";
1712

    
1713
		if ($igmpcf['address'] <> "") {
1714
			$item = explode(" ", $igmpcf['address']);
1715
			foreach ($item as $iww) {
1716
				$igmpconf .= "altnet {$iww}\n";
1717
			}
1718
		}
1719
		$igmpconf .= "\n";
1720
	}
1721
	foreach ($iflist as $ifn) {
1722
		$realif = get_real_interface($ifn);
1723
		$igmpconf .= "phyint {$realif} disabled\n";
1724
	}
1725
	$igmpconf .= "\n";
1726

    
1727
	$igmpfl = fopen($g['varetc_path'] . "/igmpproxy.conf", "w");
1728
	if (!$igmpfl) {
1729
		log_error(gettext("Could not write Igmpproxy configuration file!"));
1730
		return;
1731
	}
1732
	fwrite($igmpfl, $igmpconf);
1733
	fclose($igmpfl);
1734
	unset($igmpconf);
1735

    
1736
	if (isset($config['syslog']['igmpxverbose'])) {
1737
		mwexec_bg("/usr/local/sbin/igmpproxy -v {$g['varetc_path']}/igmpproxy.conf");
1738
	} else {
1739
		mwexec_bg("/usr/local/sbin/igmpproxy {$g['varetc_path']}/igmpproxy.conf");
1740
	}
1741

    
1742
	log_error(gettext("Started IGMP proxy service."));
1743

    
1744
	return 0;
1745
}
1746

    
1747
function services_dhcrelay_configure() {
1748
	global $config, $g;
1749

    
1750
	if (isset($config['system']['developerspew'])) {
1751
		$mt = microtime();
1752
		echo "services_dhcrelay_configure() being called $mt\n";
1753
	}
1754

    
1755
	/* kill any running dhcrelay */
1756
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
1757

    
1758
	init_config_arr(array('dhcrelay'));
1759
	$dhcrelaycfg = &$config['dhcrelay'];
1760

    
1761
	/* DHCPRelay enabled on any interfaces? */
1762
	if (!isset($dhcrelaycfg['enable'])) {
1763
		return 0;
1764
	}
1765

    
1766
	if (platform_booting()) {
1767
		echo gettext("Starting DHCP relay service...");
1768
	} else {
1769
		sleep(1);
1770
	}
1771

    
1772
	$iflist = get_configured_interface_list();
1773

    
1774
	$dhcrelayifs = array();
1775
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1776
	foreach ($dhcifaces as $dhcrelayif) {
1777
		if (!isset($iflist[$dhcrelayif]) ||
1778
		    link_interface_to_bridge($dhcrelayif)) {
1779
			continue;
1780
		}
1781

    
1782
		if (is_ipaddr(get_interface_ip($dhcrelayif))) {
1783
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1784
		}
1785
	}
1786
	$dhcrelayifs = array_unique($dhcrelayifs);
1787

    
1788
	/*
1789
	 * In order for the relay to work, it needs to be active
1790
	 * on the interface in which the destination server sits.
1791
	 */
1792
	$srvips = explode(",", $dhcrelaycfg['server']);
1793
	if (!is_array($srvips)) {
1794
		log_error(gettext("No destination IP has been configured!"));
1795
		return;
1796
	}
1797
	$srvifaces = array();
1798
	foreach ($srvips as $srcidx => $srvip) {
1799
		$destif = guess_interface_from_ip($srvip);
1800
		if (!empty($destif)) {
1801
			$srvifaces[] = $destif;
1802
		}
1803
	}
1804
	$srvifaces = array_unique($srvifaces);
1805

    
1806
	/* The server interface(s) should not be in this list */
1807
	$dhcrelayifs = array_diff($dhcrelayifs, $srvifaces);
1808

    
1809
	/* fire up dhcrelay */
1810
	if (empty($dhcrelayifs)) {
1811
		log_error(gettext("No suitable downstream interfaces found for running dhcrelay!"));
1812
		return; /* XXX */
1813
	}
1814
	if (empty($srvifaces)) {
1815
		log_error(gettext("No suitable upstream interfaces found for running dhcrelay!"));
1816
		return; /* XXX */
1817
	}
1818

    
1819
	$cmd = "/usr/local/sbin/dhcrelay";
1820
	$cmd .= " -id " . implode(" -id ", $dhcrelayifs);
1821
	$cmd .= " -iu " . implode(" -iu ", $srvifaces);
1822

    
1823
	if (isset($dhcrelaycfg['agentoption'])) {
1824
		$cmd .= " -a -m replace";
1825
	}
1826

    
1827
	$cmd .= " " . implode(" ", $srvips);
1828
	mwexec($cmd);
1829
	unset($cmd);
1830

    
1831
	return 0;
1832
}
1833

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

    
1837
	if (isset($config['system']['developerspew'])) {
1838
		$mt = microtime();
1839
		echo "services_dhcrelay6_configure() being called $mt\n";
1840
	}
1841

    
1842
	/* kill any running dhcrelay */
1843
	killbypid("{$g['varrun_path']}/dhcrelay6.pid");
1844

    
1845
	init_config_arr(array('dhcrelay6'));
1846
	$dhcrelaycfg = &$config['dhcrelay6'];
1847

    
1848
	/* DHCPv6 Relay enabled on any interfaces? */
1849
	if (!isset($dhcrelaycfg['enable'])) {
1850
		return 0;
1851
	}
1852

    
1853
	if (platform_booting()) {
1854
		echo gettext("Starting DHCPv6 relay service...");
1855
	} else {
1856
		sleep(1);
1857
	}
1858

    
1859
	$iflist = get_configured_interface_list();
1860

    
1861
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1862
	foreach ($dhcifaces as $dhcrelayif) {
1863
		if (!isset($iflist[$dhcrelayif]) ||
1864
		    link_interface_to_bridge($dhcrelayif)) {
1865
			continue;
1866
		}
1867

    
1868
		if (is_ipaddrv6(get_interface_ipv6($dhcrelayif))) {
1869
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1870
		}
1871
	}
1872
	$dhcrelayifs = array_unique($dhcrelayifs);
1873

    
1874
	/*
1875
	 * In order for the relay to work, it needs to be active
1876
	 * on the interface in which the destination server sits.
1877
	 */
1878
	$srvips = explode(",", $dhcrelaycfg['server']);
1879
	$srvifaces = array();
1880
	foreach ($srvips as $srcidx => $srvip) {
1881
		$destif = guess_interface_from_ip($srvip);
1882
		if (!empty($destif)) {
1883
			$srvifaces[] = "{$srvip}%{$destif}";
1884
		}
1885
	}
1886

    
1887
	/* fire up dhcrelay */
1888
	if (empty($dhcrelayifs) || empty($srvifaces)) {
1889
		log_error(gettext("No suitable interface found for running dhcrelay -6!"));
1890
		return; /* XXX */
1891
	}
1892

    
1893
	$cmd = "/usr/local/sbin/dhcrelay -6 -pf \"{$g['varrun_path']}/dhcrelay6.pid\"";
1894
	foreach ($dhcrelayifs as $dhcrelayif) {
1895
		$cmd .= " -l {$dhcrelayif}";
1896
	}
1897
	foreach ($srvifaces as $srviface) {
1898
		$cmd .= " -u \"{$srviface}\"";
1899
	}
1900
	mwexec($cmd);
1901
	unset($cmd);
1902

    
1903
	return 0;
1904
}
1905

    
1906
function services_dyndns_configure_client($conf) {
1907

    
1908
	if (!isset($conf['enable'])) {
1909
		return;
1910
	}
1911

    
1912
	/* load up the dyndns.class */
1913
	require_once("dyndns.class");
1914

    
1915
	$dns = new updatedns($dnsService = $conf['type'],
1916
		$dnsHost = $conf['host'],
1917
		$dnsDomain = $conf['domainname'],
1918
		$dnsUser = $conf['username'],
1919
		$dnsPass = $conf['password'],
1920
		$dnsWildcard = $conf['wildcard'],
1921
		$dnsProxied = $conf['proxied'],
1922
		$dnsMX = $conf['mx'],
1923
		$dnsIf = "{$conf['interface']}",
1924
		$dnsBackMX = NULL,
1925
		$dnsServer = NULL,
1926
		$dnsPort = NULL,
1927
		$dnsUpdateURL = "{$conf['updateurl']}",
1928
		$forceUpdate = $conf['force'],
1929
		$dnsZoneID = $conf['zoneid'],
1930
		$dnsTTL = $conf['ttl'],
1931
		$dnsResultMatch = "{$conf['resultmatch']}",
1932
		$dnsRequestIf = "{$conf['requestif']}",
1933
		$dnsID = "{$conf['id']}",
1934
		$dnsVerboseLog = $conf['verboselog'],
1935
		$curlIpresolveV4 = $conf['curl_ipresolve_v4'],
1936
		$curlSslVerifypeer = $conf['curl_ssl_verifypeer']);
1937
}
1938

    
1939
function services_dyndns_configure($int = "") {
1940
	global $config, $g;
1941
	if (isset($config['system']['developerspew'])) {
1942
		$mt = microtime();
1943
		echo "services_dyndns_configure() being called $mt\n";
1944
	}
1945

    
1946
	if (isset($config['dyndnses']['dyndns']) && is_array($config['dyndnses']['dyndns'])) {
1947
		$dyndnscfg = $config['dyndnses']['dyndns'];
1948
	} else {
1949
		return 0;
1950
	}
1951
	$gwgroups = return_gateway_groups_array(true);
1952
	if (is_array($dyndnscfg)) {
1953
		if (platform_booting()) {
1954
			echo gettext("Starting DynDNS clients...");
1955
		}
1956

    
1957
		foreach ($dyndnscfg as $dyndns) {
1958
			/*
1959
			 * If it's using a gateway group, check if interface is
1960
			 * the active gateway for that group
1961
			 */
1962
			$group_int = '';
1963
			$friendly_group_int = '';
1964
			$gwgroup_member = false;
1965
			if (is_array($gwgroups[$dyndns['interface']])) {
1966
				if (!empty($gwgroups[$dyndns['interface']][0]['vip'])) {
1967
					$group_int = $gwgroups[$dyndns['interface']][0]['vip'];
1968
				} else {
1969
					$group_int = $gwgroups[$dyndns['interface']][0]['int'];
1970
					$friendly_group_int =
1971
					    convert_real_interface_to_friendly_interface_name(
1972
						$group_int);
1973
					if (!empty($int)) {
1974
						$gwgroup_member =
1975
						    interface_gateway_group_member(get_real_interface($int),
1976
						    $dyndns['interface']);
1977
					}
1978
				}
1979
			}
1980
			if ((empty($int)) || ($int == $dyndns['interface']) || $gwgroup_member ||
1981
			    ($int == $group_int) || ($int == $friendly_group_int)) {
1982
				$dyndns['verboselog'] = isset($dyndns['verboselog']);
1983
				$dyndns['curl_ipresolve_v4'] = isset($dyndns['curl_ipresolve_v4']);
1984
				$dyndns['curl_ssl_verifypeer'] = isset($dyndns['curl_ssl_verifypeer']);
1985
				$dyndns['proxied'] = isset($dyndns['proxied']);
1986
				services_dyndns_configure_client($dyndns);
1987
				sleep(1);
1988
			}
1989
		}
1990

    
1991
		if (platform_booting()) {
1992
			echo gettext("done.") . "\n";
1993
		}
1994
	}
1995

    
1996
	return 0;
1997
}
1998

    
1999
function dyndnsCheckIP($int) {
2000
	global $config, $factory_default_checkipservice;
2001
	$ip_address = get_interface_ip($int);
2002
	if (is_private_ip($ip_address)) {
2003
		$gateways_status = return_gateways_status(true);
2004
		// If the gateway for this interface is down, then the external check cannot work.
2005
		// Avoid the long wait for the external check to timeout.
2006
		if (stristr($gateways_status[$config['interfaces'][$int]['gateway']]['status'], "down")) {
2007
			return "down";
2008
		}
2009

    
2010
		// Append the factory default check IP service to the list (if not disabled).
2011
		if (!isset($config['checkipservices']['disable_factory_default'])) {
2012
			if (!is_array($config['checkipservices'])) {
2013
				$config['checkipservices'] = array();
2014
			}
2015
			if (!is_array($config['checkipservices']['checkipservice'])) {
2016
				$config['checkipservices']['checkipservice'] = array();
2017
			}
2018
			$config['checkipservices']['checkipservice'][] = $factory_default_checkipservice;
2019
		}
2020

    
2021
		// Use the first enabled check IP service as the default.
2022
		if (is_array($config['checkipservices']['checkipservice'])) {
2023
			foreach ($config['checkipservices']['checkipservice'] as $i => $checkipservice) {
2024
				if (isset($checkipservice['enable'])) {
2025
					$url = $checkipservice['url'];
2026
					$username = $checkipservice['username'];
2027
					$password = $checkipservice['password'];
2028
					$verifysslpeer = isset($checkipservice['verifysslpeer']);
2029
					break;
2030
				}
2031
			}
2032
		}
2033

    
2034
		$hosttocheck = $url;
2035
		$ip_ch = curl_init($hosttocheck);
2036
		curl_setopt($ip_ch, CURLOPT_RETURNTRANSFER, 1);
2037
		curl_setopt($ip_ch, CURLOPT_SSL_VERIFYPEER, $verifysslpeer);
2038
		curl_setopt($ip_ch, CURLOPT_INTERFACE, 'host!' . $ip_address);
2039
		curl_setopt($ip_ch, CURLOPT_CONNECTTIMEOUT, '30');
2040
		curl_setopt($ip_ch, CURLOPT_TIMEOUT, 120);
2041
		curl_setopt($ip_ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
2042
		curl_setopt($ip_ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
2043
		curl_setopt($ip_ch, CURLOPT_USERPWD, "{$username}:{$password}");
2044
		$ip_result_page = curl_exec($ip_ch);
2045
		curl_close($ip_ch);
2046
		$ip_result_decoded = urldecode($ip_result_page);
2047
		preg_match('=Current IP Address: (.*)</body>=siU', $ip_result_decoded, $matches);
2048
		$ip_address = trim($matches[1]);
2049
	}
2050
	return $ip_address;
2051
}
2052

    
2053
function services_dnsmasq_configure($restart_dhcp = true) {
2054
	global $config, $g;
2055
	$return = 0;
2056

    
2057
	// hard coded args: will be removed to avoid duplication if specified in custom_options
2058
	$standard_args = array(
2059
		"dns-forward-max" => "--dns-forward-max=5000",
2060
		"cache-size" => "--cache-size=10000",
2061
		"local-ttl" => "--local-ttl=1"
2062
	);
2063

    
2064

    
2065
	if (isset($config['system']['developerspew'])) {
2066
		$mt = microtime();
2067
		echo "services_dnsmasq_configure() being called $mt\n";
2068
	}
2069

    
2070
	/* kill any running dnsmasq */
2071
	if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) {
2072
		sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
2073
	}
2074

    
2075
	if (isset($config['dnsmasq']['enable'])) {
2076

    
2077
		if (platform_booting()) {
2078
			echo gettext("Starting DNS forwarder...");
2079
		} else {
2080
			sleep(1);
2081
		}
2082

    
2083
		/* generate hosts file */
2084
		if (system_hosts_generate() != 0) {
2085
			$return = 1;
2086
		}
2087

    
2088
		$args = "";
2089

    
2090
		if (isset($config['dnsmasq']['regdhcp'])) {
2091
			$args .= " --dhcp-hostsfile={$g['etc_path']}/hosts ";
2092
		}
2093

    
2094
		/* Setup listen port, if non-default */
2095
		if (is_port($config['dnsmasq']['port'])) {
2096
			$args .= " --port={$config['dnsmasq']['port']} ";
2097
		}
2098

    
2099
		$listen_addresses = "";
2100
		if (isset($config['dnsmasq']['interface'])) {
2101
			$interfaces = explode(",", $config['dnsmasq']['interface']);
2102
			foreach ($interfaces as $interface) {
2103
				$if = get_real_interface($interface);
2104
				if (does_interface_exist($if)) {
2105
					$laddr = get_interface_ip($interface);
2106
					if (is_ipaddrv4($laddr)) {
2107
						$listen_addresses .= " --listen-address={$laddr} ";
2108
					}
2109
					$laddr6 = get_interface_ipv6($interface);
2110
					if (is_ipaddrv6($laddr6) && !isset($config['dnsmasq']['strictbind'])) {
2111
						/*
2112
						 * XXX: Since dnsmasq does not support link-local address
2113
						 * with scope specified. These checks are being done.
2114
						 */
2115
						if (is_linklocal($laddr6) && strstr($laddr6, "%")) {
2116
							$tmpaddrll6 = explode("%", $laddr6);
2117
							$listen_addresses .= " --listen-address={$tmpaddrll6[0]} ";
2118
						} else {
2119
							$listen_addresses .= " --listen-address={$laddr6} ";
2120
						}
2121
					}
2122
				}
2123
			}
2124
			if (!empty($listen_addresses)) {
2125
				$args .= " {$listen_addresses} ";
2126
				if (isset($config['dnsmasq']['strictbind'])) {
2127
					$args .= " --bind-interfaces ";
2128
				}
2129
			}
2130
		}
2131

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

    
2139
			// Build an array of domain overrides to help in checking for matches.
2140
			$override_a = array();
2141
			if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2142
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2143
					$override_a[$override['domain']] = "y";
2144
				}
2145
			}
2146

    
2147
			// Build an array of the private reverse lookup domain names
2148
			$reverse_domain_a = array("10.in-addr.arpa", "168.192.in-addr.arpa");
2149
			// Unfortunately the 172.16.0.0/12 range does not map nicely to the in-addr.arpa scheme.
2150
			for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) {
2151
				$reverse_domain_a[] = "$subnet_num.172.in-addr.arpa";
2152
			}
2153

    
2154
			// Set the --server parameter to nowhere for each reverse domain name that was not specifically specified in a domain override.
2155
			foreach ($reverse_domain_a as $reverse_domain) {
2156
				if (!isset($override_a[$reverse_domain])) {
2157
					$args .= " --server=/$reverse_domain/ ";
2158
				}
2159
			}
2160
			unset($override_a);
2161
			unset($reverse_domain_a);
2162
		}
2163

    
2164
		/* Setup forwarded domains */
2165
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2166
			foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2167
				if ($override['ip'] == "!") {
2168
					$override[ip] = "";
2169
				}
2170
				$args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
2171
			}
2172
		}
2173

    
2174
		/* Allow DNS Rebind for forwarded domains */
2175
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2176
			if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2177
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2178
					$args .= ' --rebind-domain-ok=/' . $override['domain'] . '/ ';
2179
				}
2180
			}
2181
		}
2182

    
2183
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2184
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2185
		}
2186

    
2187
		if (isset($config['dnsmasq']['strict_order'])) {
2188
			$args .= " --strict-order ";
2189
		}
2190

    
2191
		if (isset($config['dnsmasq']['domain_needed'])) {
2192
			$args .= " --domain-needed ";
2193
		}
2194

    
2195
		if ($config['dnsmasq']['custom_options']) {
2196
			foreach (preg_split('/\s+/', $config['dnsmasq']['custom_options']) as $c) {
2197
				$args .= " " . escapeshellarg("--{$c}");
2198
				$p = explode('=', $c);
2199
				if (array_key_exists($p[0], $standard_args)) {
2200
					unset($standard_args[$p[0]]);
2201
				}
2202
			}
2203
		}
2204
		$args .= ' ' . implode(' ', array_values($standard_args));
2205

    
2206
		/* run dnsmasq. Use "-C /dev/null" since we use command line args only (Issue #6730) */
2207
		$cmd = "/usr/local/sbin/dnsmasq --all-servers -C /dev/null {$dns_rebind} {$args}";
2208
		//log_error("dnsmasq command: {$cmd}");
2209
		mwexec_bg($cmd);
2210
		unset($args);
2211

    
2212
		system_dhcpleases_configure();
2213

    
2214
		if (platform_booting()) {
2215
			echo gettext("done.") . "\n";
2216
		}
2217
	}
2218

    
2219
	if (!platform_booting() && $restart_dhcp) {
2220
		if (services_dhcpd_configure() != 0) {
2221
			$return = 1;
2222
		}
2223
	}
2224

    
2225
	return $return;
2226
}
2227

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

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

    
2237
	if (isset($config['unbound']['enable'])) {
2238
		require_once('/etc/inc/unbound.inc');
2239

    
2240
		/* Stop Unbound using TERM */
2241
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2242
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
2243
		}
2244

    
2245
		/* If unbound is still running, wait up to 30 seconds for it to terminate. */
2246
		for ($i=1; $i <= 30; $i++) {
2247
			if (is_process_running('unbound')) {
2248
				sleep(1);
2249
			}
2250
		}
2251

    
2252
		$python_mode = false;
2253
		if (isset($config['unbound']['python']) && !empty($config['unbound']['python_script'])) {
2254
			$python_mode = true;
2255
		}
2256

    
2257
		/* Include any additional functions as defined by python script include file */
2258
		if (file_exists("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc")) {
2259
			exec("/usr/local/bin/php -l " . escapeshellarg("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc")
2260
				. " 2>&1", $py_output, $py_retval);
2261
			if ($py_retval == 0) {
2262
				require_once("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc");
2263
			}
2264
		}
2265

    
2266
		/* DNS Resolver python integration */
2267
		if ($python_mode) {
2268
			if (!is_dir("{$g['unbound_chroot_path']}/dev")) {
2269
				safe_mkdir("{$g['unbound_chroot_path']}/dev");
2270
			}
2271
			exec("/sbin/mount -t devfs devfs " . escapeshellarg("{$g['unbound_chroot_path']}/dev"));
2272
		} else {
2273
			if (is_dir("{$g['unbound_chroot_path']}/dev")) {
2274
				exec("/sbin/umount -f " . escapeshellarg("{$g['unbound_chroot_path']}/dev"));
2275
			}
2276
		}
2277
		$base_folder = '/usr/local';
2278
		foreach (array('/bin', '/lib') as $dir) {
2279
			$validate = exec("/sbin/mount | /usr/bin/grep " . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir} (nullfs") . " 2>&1");
2280
			if ($python_mode) {
2281

    
2282
				// Add DNS Resolver python integration
2283
				if (empty($validate)) {
2284
					if (!is_dir("{$g['unbound_chroot_path']}{$base_folder}{$dir}")) {
2285
						safe_mkdir("{$g['unbound_chroot_path']}{$base_folder}{$dir}");
2286
					}
2287
					$output = $retval = '';
2288
					exec("/sbin/mount_nullfs -o ro " . escapeshellarg("/usr/local{$dir}") . ' '
2289
					    . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir}") . " 2>&1", $output, $retval);
2290

    
2291
					// Disable Unbound python on mount failure
2292
					if ($retval != 0) {
2293
						$config['unbound']['python'] = '';
2294
						$log_msg = "[Unbound-pymod]: Disabling Unbound python due to failed mount";
2295
						write_config($log_msg);
2296
						log_error($log_msg);
2297
					}
2298
				}
2299
			}
2300

    
2301
			// Remove DNS Resolver python integration
2302
			elseif (!empty($validate)) {
2303
				exec("/sbin/umount -t nullfs " . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir}") . " 2>&1", $output, $retval);
2304
				if ($retval == 0) {
2305
					foreach (array( "/usr/local{$dir}", '/usr/local', '/usr') as $folder) {
2306
						if (!empty($g['unbound_chroot_path']) && $g['unbound_chroot_path'] != '/' && is_dir("{$g['unbound_chroot_path']}{$folder}")) {
2307
							@rmdir(escapeshellarg("{$g['unbound_chroot_path']}{$folder}"));
2308
						}
2309

    
2310
						// Delete remaining subfolders on next loop
2311
						if ($dir == '/bin') {
2312
							break;
2313
						}
2314
					}
2315
				}
2316
				else {
2317
					log_error("[Unbound-pymod]: Failed to unmount!");
2318
				}
2319
			}
2320
		}
2321

    
2322
		if (platform_booting()) {
2323
			echo gettext("Starting DNS Resolver...");
2324
		} else {
2325
			sleep(1);
2326
		}
2327

    
2328
		/* generate hosts file */
2329
		if (system_hosts_generate() != 0) {
2330
			$return = 1;
2331
		}
2332

    
2333
		/* Check here for dhcp6 complete - wait upto 10 seconds */
2334
		if($config['interfaces']["wan"]['ipaddrv6'] == 'dhcp6') {
2335
			$wanif = get_real_interface("wan", "inet6");
2336
			if (platform_booting()) {
2337
				for ($i=1; $i <= 10; $i++) {
2338
					if (!file_exists("/tmp/{$wanif}_dhcp6_complete")) {
2339
						log_error(gettext("Unbound start waiting on dhcp6c."));
2340
						sleep(1);
2341
					} else {
2342
						unlink_if_exists("/tmp/{$wanif}_dhcp6_complete");
2343
						log_error(gettext("dhcp6 init complete. Continuing"));
2344
						break;
2345
					}
2346
				}
2347
			}
2348
		}
2349

    
2350
		sync_unbound_service();
2351
		if (platform_booting()) {
2352
			log_error(gettext("sync unbound done."));
2353
			echo gettext("done.") . "\n";
2354
		}
2355

    
2356
		system_dhcpleases_configure();
2357
	} else {
2358
		/* kill Unbound since it should not be enabled */
2359
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2360
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "KILL");
2361
		}
2362
	}
2363

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

    
2370
	return $return;
2371
}
2372

    
2373
function services_snmpd_configure() {
2374
	global $config, $g;
2375
	if (isset($config['system']['developerspew'])) {
2376
		$mt = microtime();
2377
		echo "services_snmpd_configure() being called $mt\n";
2378
	}
2379

    
2380
	/* kill any running snmpd */
2381
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
2382
	sleep(2);
2383
	if (is_process_running("bsnmpd")) {
2384
		mwexec("/usr/bin/killall bsnmpd", true);
2385
	}
2386

    
2387
	if (isset($config['snmpd']['enable'])) {
2388

    
2389
		if (platform_booting()) {
2390
			echo gettext("Starting SNMP daemon... ");
2391
		}
2392

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

    
2398
		/* generate snmpd.conf */
2399
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
2400
		if (!$fd) {
2401
			printf(gettext("Error: cannot open snmpd.conf in services_snmpd_configure().%s"), "\n");
2402
			return 1;
2403
		}
2404

    
2405

    
2406
		$snmpdconf = <<<EOD
2407
location := "{$config['snmpd']['syslocation']}"
2408
contact := "{$config['snmpd']['syscontact']}"
2409
read := "{$config['snmpd']['rocommunity']}"
2410

    
2411
EOD;
2412

    
2413
/* No docs on what write strings do there so disable for now.
2414
		if (isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])) {
2415
			$snmpdconf .= <<<EOD
2416
# write string
2417
write := "{$config['snmpd']['rwcommunity']}"
2418

    
2419
EOD;
2420
		}
2421
*/
2422

    
2423

    
2424
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2425
			$snmpdconf .= <<<EOD
2426
# SNMP Trap support.
2427
traphost := {$config['snmpd']['trapserver']}
2428
trapport := {$config['snmpd']['trapserverport']}
2429
trap := "{$config['snmpd']['trapstring']}"
2430

    
2431

    
2432
EOD;
2433
		}
2434

    
2435
		$sysDescr = "{$g['product_name']} {$config['system']['hostname']}.{$config['system']['domain']}" .
2436
			" {$g['product_version_string']} {$g['platform']} " . php_uname("s") .
2437
			" " . php_uname("r") . " " . php_uname("m");
2438

    
2439
		$snmpdconf .= <<<EOD
2440
system := 1     # pfSense
2441
%snmpd
2442
sysDescr			= "{$sysDescr}"
2443
begemotSnmpdDebugDumpPdus       = 2
2444
begemotSnmpdDebugSyslogPri      = 7
2445
begemotSnmpdCommunityString.0.1 = $(read)
2446

    
2447
EOD;
2448

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

    
2454
EOD;
2455
		}
2456
*/
2457

    
2458

    
2459
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2460
			$snmpdconf .= <<<EOD
2461
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
2462
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
2463
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
2464

    
2465
EOD;
2466
		}
2467

    
2468

    
2469
		$snmpdconf .= <<<EOD
2470
begemotSnmpdCommunityDisable    = 1
2471

    
2472
EOD;
2473

    
2474
		$bind_to_ips = array();
2475
		if (isset($config['snmpd']['bindip'])) {
2476
			foreach (explode(",", $config['snmpd']['bindip']) as $bind_to_ip) {
2477
				if (is_ipaddr($bind_to_ip)) {
2478
					$bind_to_ips[] = $bind_to_ip;
2479
				} else {
2480
					$if = get_real_interface($bind_to_ip);
2481
					if (does_interface_exist($if)) {
2482
						$bindip = get_interface_ip($bind_to_ip);
2483
						if (is_ipaddr($bindip)) {
2484
							$bind_to_ips[] = $bindip;
2485
						}
2486
					}
2487
				}
2488
			}
2489
		}
2490
		if (!count($bind_to_ips)) {
2491
			$bind_to_ips = array("0.0.0.0");
2492
		}
2493

    
2494
		if (is_port($config['snmpd']['pollport'])) {
2495
			foreach ($bind_to_ips as $bind_to_ip) {
2496
				$snmpdconf .= <<<EOD
2497
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
2498

    
2499
EOD;
2500

    
2501
			}
2502
		}
2503

    
2504
		$snmpdconf .= <<<EOD
2505
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
2506
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
2507

    
2508
# These are bsnmp macros not php vars.
2509
sysContact      = $(contact)
2510
sysLocation     = $(location)
2511
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
2512

    
2513
snmpEnableAuthenTraps = 2
2514

    
2515
EOD;
2516

    
2517
		if (is_array($config['snmpd']['modules'])) {
2518
			if (isset($config['snmpd']['modules']['mibii'])) {
2519
			$snmpdconf .= <<<EOD
2520
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
2521

    
2522
EOD;
2523
			}
2524

    
2525
			if (isset($config['snmpd']['modules']['netgraph'])) {
2526
				$snmpdconf .= <<<EOD
2527
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
2528
%netgraph
2529
begemotNgControlNodeName = "snmpd"
2530

    
2531
EOD;
2532
			}
2533

    
2534
			if (isset($config['snmpd']['modules']['pf'])) {
2535
				$snmpdconf .= <<<EOD
2536
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
2537

    
2538
EOD;
2539
			}
2540

    
2541
			if (isset($config['snmpd']['modules']['hostres'])) {
2542
				$snmpdconf .= <<<EOD
2543
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
2544

    
2545
EOD;
2546
			}
2547

    
2548
			if (isset($config['snmpd']['modules']['bridge'])) {
2549
				$snmpdconf .= <<<EOD
2550
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
2551
# config must end with blank line
2552

    
2553
EOD;
2554
			}
2555
			if (isset($config['snmpd']['modules']['ucd'])) {
2556
				$snmpdconf .= <<<EOD
2557
begemotSnmpdModulePath."ucd"     = "/usr/local/lib/snmp_ucd.so"
2558

    
2559
EOD;
2560
			}
2561
			if (isset($config['snmpd']['modules']['regex'])) {
2562
				$snmpdconf .= <<<EOD
2563
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"
2564

    
2565
EOD;
2566
			}
2567
		}
2568

    
2569
		fwrite($fd, $snmpdconf);
2570
		fclose($fd);
2571
		unset($snmpdconf);
2572

    
2573
		/* run bsnmpd */
2574
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
2575
			" -p {$g['varrun_path']}/snmpd.pid");
2576

    
2577
		if (platform_booting()) {
2578
			echo gettext("done.") . "\n";
2579
		}
2580
	}
2581

    
2582
	return 0;
2583
}
2584

    
2585
function services_dnsupdate_process($int = "", $updatehost = "", $forced = false) {
2586
	global $config, $g;
2587
	if (isset($config['system']['developerspew'])) {
2588
		$mt = microtime();
2589
		echo "services_dnsupdate_process() being called $mt\n";
2590
	}
2591

    
2592
	/* Dynamic DNS updating active? */
2593
	if (!is_array($config['dnsupdates']['dnsupdate'])) {
2594
		return 0;
2595
	}
2596

    
2597
	$notify_text = "";
2598
	$gwgroups = return_gateway_groups_array(true);
2599
	foreach ($config['dnsupdates']['dnsupdate'] as $i => $dnsupdate) {
2600
		if (!isset($dnsupdate['enable'])) {
2601
			continue;
2602
		}
2603
		/*
2604
		 * If it's using a gateway group, check if interface is
2605
		 * the active gateway for that group
2606
		 */
2607
		$group_int = '';
2608
		$friendly_group_int = '';
2609
		$gwgroup_member = false;
2610
		if (is_array($gwgroups[$dnsupdate['interface']])) {
2611
			if (!empty($gwgroups[$dnsupdate['interface']][0]['vip'])) {
2612
				$group_int = $gwgroups[$dnsupdate['interface']][0]['vip'];
2613
			} else {
2614
				$group_int = $gwgroups[$dnsupdate['interface']][0]['int'];
2615
				$friendly_group_int =
2616
				    convert_real_interface_to_friendly_interface_name(
2617
					$group_int);
2618
				if (!empty($int)) {
2619
					$gwgroup_member =
2620
					    interface_gateway_group_member(get_real_interface($int),
2621
					    $dnsupdate['interface']);
2622
				}
2623
			}
2624
		}
2625
		if (!empty($int) && ($int != $dnsupdate['interface']) && !$gwgroup_member &&
2626
		    ($int != $group_int) && ($int != $friendly_group_int)) {
2627
			continue;
2628
		}
2629
		if (!empty($updatehost) && ($updatehost != $dnsupdate['host'])) {
2630
			continue;
2631
		}
2632

    
2633
		/* determine interface name */
2634
		$if = get_failover_interface($dnsupdate['interface']);
2635

    
2636
		/* Determine address to update and default binding address */
2637
		if (isset($dnsupdate['usepublicip'])) {
2638
			$wanip = dyndnsCheckIP($if);
2639
			$bindipv4 = get_interface_ip($if);
2640
		} else {
2641
			$wanip = get_interface_ip($if);
2642
			$bindipv4 = $wanip;
2643
		}
2644
		$wanipv6 = get_interface_ipv6($if);
2645
		$bindipv6 = $wanipv6;
2646

    
2647
		/* Handle non-default interface bindings */
2648
		if ($dnsupdate['updatesource'] == "none") {
2649
			/* When empty, the directive will be omitted. */
2650
			$bindipv4 = "";
2651
			$bindipv6 = "";
2652
		} elseif (!empty($dnsupdate['updatesource'])) {
2653
			/* Find the alternate binding address */
2654
			$bindipv4 = get_interface_ip($dnsupdate['updatesource']);
2655
			$bindipv6 = get_interface_ipv6($dnsupdate['updatesource']);
2656
		}
2657

    
2658
		/* Handle IPv4/IPv6 selection for the update source interface/VIP */
2659
		switch ($dnsupdate['updatesourcefamily']) {
2660
			case "inet":
2661
				$bindip = $bindipv4;
2662
				break;
2663
			case "inet6":
2664
				$bindip = $bindipv6;
2665
				break;
2666
			case "":
2667
			default:
2668
				/* Try IPv4 first, if that is empty, try IPv6. */
2669
				/* Only specify the address if it's present, otherwise omit. */
2670
				if (!empty($bindipv4)) {
2671
					$bindip = $bindipv4;
2672
				} elseif (!empty($bindipv6)) {
2673
					$bindip = $bindipv6;
2674
				}
2675
				break;
2676
		}
2677

    
2678
		$cacheFile = $g['conf_path'] .
2679
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2680
		    escapeshellarg($dnsupdate['host']) .
2681
		    "_{$dnsupdate['server']}.cache";
2682
		$cacheFilev6 = $g['conf_path'] .
2683
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2684
		    escapeshellarg($dnsupdate['host']) .
2685
		    "_{$dnsupdate['server']}_v6.cache";
2686
		$currentTime = time();
2687

    
2688
		if (!$wanip && !$wanipv6) {
2689
			continue;
2690
		}
2691

    
2692
		$keyname = $dnsupdate['keyname'];
2693
		/* trailing dot */
2694
		if (substr($keyname, -1) != ".") {
2695
			$keyname .= ".";
2696
		}
2697

    
2698
		$hostname = $dnsupdate['host'];
2699
		/* trailing dot */
2700
		if (substr($hostname, -1) != ".") {
2701
			$hostname .= ".";
2702
		}
2703

    
2704
		/* write key file */
2705
		$algorithm = empty($dnsupdate['keyalgorithm']) ? 'hmac-md5' : $dnsupdate['keyalgorithm'];
2706
		$upkey = <<<EOD
2707
key "{$keyname}" {
2708
	algorithm {$algorithm};
2709
	secret "{$dnsupdate['keydata']}";
2710
};
2711

    
2712
EOD;
2713
		@file_put_contents("{$g['varetc_path']}/nsupdatekey{$i}", $upkey);
2714

    
2715
		/* generate update instructions */
2716
		$upinst = "";
2717
		if (!empty($dnsupdate['server'])) {
2718
			$upinst .= "server {$dnsupdate['server']}\n";
2719
		}
2720

    
2721
		$cachedipv4 = '';
2722
		$cacheTimev4 = 0;
2723
		if (file_exists($cacheFile)) {
2724
			list($cachedipv4, $cacheTimev4) = explode("|",
2725
			    file_get_contents($cacheFile));
2726
		}
2727
		$cachedipv6 = '';
2728
		$cacheTimev6 = 0;
2729
		if (file_exists($cacheFilev6)) {
2730
			list($cachedipv6, $cacheTimev6) = explode("|",
2731
			    file_get_contents($cacheFilev6));
2732
		}
2733

    
2734
		// 25 Days
2735
		$maxCacheAgeSecs = 25 * 24 * 60 * 60;
2736
		$need_update = false;
2737

    
2738
		/* Update IPv4 if we have it. */
2739
		if (is_ipaddrv4($wanip) && $dnsupdate['recordtype'] != "AAAA") {
2740
			if (($wanip != $cachedipv4) || $forced ||
2741
			    (($currentTime - $cacheTimev4) > $maxCacheAgeSecs)) {
2742
				$upinst .= "update delete " .
2743
				    "{$dnsupdate['host']}. A\n";
2744
				$upinst .= "update add {$dnsupdate['host']}. " .
2745
				    "{$dnsupdate['ttl']} A {$wanip}\n";
2746
				if (!empty($bindip)) {
2747
					$upinst .= "local {$bindip}\n";
2748
				}
2749
				$need_update = true;
2750
			} else {
2751
				log_error(sprintf(gettext(
2752
				    "phpDynDNS: Not updating %s A record because the IP address has not changed."),
2753
				    $dnsupdate['host']));
2754
			}
2755
		} else {
2756
			@unlink($cacheFile);
2757
			unset($cacheFile);
2758
		}
2759

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

    
2779
		$upinst .= "\n";	/* mind that trailing newline! */
2780

    
2781
		if (!$need_update) {
2782
			continue;
2783
		}
2784

    
2785
		@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}", $upinst);
2786
		unset($upinst);
2787
		/* invoke nsupdate */
2788
		$cmd = "/usr/local/bin/nsupdate -k {$g['varetc_path']}/nsupdatekey{$i}";
2789

    
2790
		if (isset($dnsupdate['usetcp'])) {
2791
			$cmd .= " -v";
2792
		}
2793

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

    
2796
		if (mwexec($cmd) == 0) {
2797
			if (!empty($cacheFile)) {
2798
				@file_put_contents($cacheFile,
2799
				    "{$wanip}|{$currentTime}");
2800
				log_error(sprintf(gettext(
2801
				    'phpDynDNS: updating cache file %1$s: %2$s'),
2802
				    $cacheFile, $wanip));
2803
				$notify_text .= sprintf(gettext(
2804
				    'DynDNS updated IP Address (A) for %1$s on %2$s (%3$s) to %4$s'),
2805
				    $dnsupdate['host'],
2806
				    convert_real_interface_to_friendly_descr($if),
2807
				    $if, $wanip) . "\n";
2808
			}
2809
			if (!empty($cacheFilev6)) {
2810
				@file_put_contents($cacheFilev6,
2811
				    "{$wanipv6}|{$currentTime}");
2812
				log_error(sprintf(gettext(
2813
				    'phpDynDNS: updating cache file %1$s: %2$s'),
2814
				    $cacheFilev6, $wanipv6));
2815
				$notify_text .= sprintf(gettext(
2816
				    'DynDNS updated IPv6 Address (AAAA) for %1$s on %2$s (%3$s) to %4$s'),
2817
				    $dnsupdate['host'],
2818
				    convert_real_interface_to_friendly_descr($if),
2819
				    $if, $wanipv6) . "\n";
2820
			}
2821
		} else {
2822
			if (!empty($cacheFile)) {
2823
				log_error(sprintf(gettext(
2824
				    'phpDynDNS: ERROR while updating IP Address (A) for %1$s (%2$s)'),
2825
				    $dnsupdate['host'], $wanip));
2826
			}
2827
			if (!empty($cacheFilev6)) {
2828
				log_error(sprintf(gettext(
2829
				    'phpDynDNS: ERROR while updating IP Address (AAAA) for %1$s (%2$s)'),
2830
				    $dnsupdate['host'], $wanipv6));
2831
			}
2832
		}
2833
		unset($cmd);
2834
	}
2835

    
2836
	if (!empty($notify_text)) {
2837
		notify_all_remote($notify_text);
2838
	}
2839

    
2840
	return 0;
2841
}
2842

    
2843
/* configure cron service */
2844
function configure_cron() {
2845
	global $g, $config;
2846

    
2847
	/* preserve existing crontab entries */
2848
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2849

    
2850
	for ($i = 0; $i < count($crontab_contents); $i++) {
2851
		$cron_item = &$crontab_contents[$i];
2852
		if (strpos($cron_item, "# pfSense specific crontab entries") !== false) {
2853
			array_splice($crontab_contents, $i - 1);
2854
			break;
2855
		}
2856
	}
2857
	$crontab_contents = implode("\n", $crontab_contents) . "\n";
2858

    
2859

    
2860
	if (is_array($config['cron']['item'])) {
2861
		$crontab_contents .= "#\n";
2862
		$crontab_contents .= "# pfSense specific crontab entries\n";
2863
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
2864
		$crontab_contents .= "#\n";
2865

    
2866
		if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) {
2867
			$http_proxy = $config['system']['proxyurl'];
2868
			if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) {
2869
				$http_proxy .= ':' . $config['system']['proxyport'];
2870
			}
2871
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
2872

    
2873
			if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
2874
				$crontab_contents .= "HTTP_PROXY_AUTH=basic:*:{$config['system']['proxyuser']}:{$config['system']['proxypass']}";
2875
			}
2876
		}
2877

    
2878
		foreach ($config['cron']['item'] as $item) {
2879
			$crontab_contents .= "\n{$item['minute']}\t";
2880
			$crontab_contents .= "{$item['hour']}\t";
2881
			$crontab_contents .= "{$item['mday']}\t";
2882
			$crontab_contents .= "{$item['month']}\t";
2883
			$crontab_contents .= "{$item['wday']}\t";
2884
			$crontab_contents .= "{$item['who']}\t";
2885
			$crontab_contents .= "{$item['command']}";
2886
		}
2887

    
2888
		$crontab_contents .= "\n#\n";
2889
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
2890
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
2891
		$crontab_contents .= "#\n\n";
2892
	}
2893

    
2894
	/* please maintain the newline at the end of file */
2895
	file_put_contents("/etc/crontab", $crontab_contents);
2896
	unset($crontab_contents);
2897

    
2898
	/* make sure that cron is running and start it if it got killed somehow */
2899
	if (!is_process_running("cron")) {
2900
		exec("cd /tmp && /usr/sbin/cron -s 2>/dev/null");
2901
	} else {
2902
	/* do a HUP kill to force sync changes */
2903
		sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP");
2904
	}
2905

    
2906
}
2907

    
2908
function upnp_action ($action) {
2909
	global $g, $config;
2910
	switch ($action) {
2911
		case "start":
2912
			if (file_exists('/var/etc/miniupnpd.conf')) {
2913
				@unlink("{$g['varrun_path']}/miniupnpd.pid");
2914
				mwexec_bg("/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf -P {$g['varrun_path']}/miniupnpd.pid");
2915
			}
2916
			break;
2917
		case "stop":
2918
			killbypid("{$g['varrun_path']}/miniupnpd.pid");
2919
			while ((int)exec("/bin/pgrep -a miniupnpd | wc -l") > 0) {
2920
				mwexec('/usr/bin/killall miniupnpd 2>/dev/null', true);
2921
			}
2922
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
2923
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
2924
			break;
2925
		case "restart":
2926
			upnp_action('stop');
2927
			upnp_action('start');
2928
			break;
2929
	}
2930
}
2931

    
2932
function upnp_start() {
2933
	global $config;
2934

    
2935
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
2936
		return;
2937
	}
2938

    
2939
	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
2940
		echo gettext("Starting UPnP service... ");
2941
		require_once('/usr/local/pkg/miniupnpd.inc');
2942
		sync_package_miniupnpd();
2943
		echo "done.\n";
2944
	}
2945
}
2946

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

    
2950
	$is_installed = false;
2951
	$cron_changed = true;
2952
	$change_message = "";
2953

    
2954
	if (!is_array($config['cron'])) {
2955
		$config['cron'] = array();
2956
	}
2957
	if (!is_array($config['cron']['item'])) {
2958
		$config['cron']['item'] = array();
2959
	}
2960

    
2961
	$x = 0;
2962
	foreach ($config['cron']['item'] as $item) {
2963
		if (strstr($item['command'], $command)) {
2964
			$is_installed = true;
2965
			break;
2966
		}
2967
		$x++;
2968
	}
2969

    
2970
	if ($active) {
2971
		$cron_item = array();
2972
		$cron_item['minute'] = $minute;
2973
		$cron_item['hour'] = $hour;
2974
		$cron_item['mday'] = $monthday;
2975
		$cron_item['month'] = $month;
2976
		$cron_item['wday'] = $weekday;
2977
		$cron_item['who'] = $who;
2978
		$cron_item['command'] = $command;
2979
		if (!$is_installed) {
2980
			$config['cron']['item'][] = $cron_item;
2981
			$change_message = "Installed cron job for %s";
2982
		} else {
2983
			if ($config['cron']['item'][$x] == $cron_item) {
2984
				$cron_changed = false;
2985
			} else {
2986
				$config['cron']['item'][$x] = $cron_item;
2987
				$change_message = "Updated cron job for %s";
2988
			}
2989
		}
2990
	} else {
2991
		if ($is_installed == true) {
2992
			array_splice($config['cron']['item'], $x, 1);
2993
			$change_message = "Removed cron job for %s";
2994
		} else {
2995
			$cron_changed = false;
2996
		}
2997
	}
2998

    
2999
	if ($cron_changed) {
3000
		/* Optionally write the configuration if this function made changes.
3001
		 * Performing a write_config() in this way can have unintended side effects. See #7146
3002
		 * Base system instances of this function do not need to write, packages may.
3003
		 */
3004
		if ($write_config) {
3005
			write_config(sprintf(gettext($change_message), $command));
3006
		}
3007
		configure_cron();
3008
	}
3009
}
3010

    
3011
?>
(46-46/60)