Project

General

Profile

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

    
26

    
27
define('DYNDNS_PROVIDER_VALUES', 'all-inkl azure azurev6 citynetwork cloudflare cloudflare-v6 cloudns custom custom-v6 digitalocean dnsexit dnsimple dnsmadeeasy dnsomatic dreamhost dreamhost-v6 duiadns duiadns-v6 dyndns dyndns-custom dyndns-static dyns easydns eurodns freedns freedns-v6 glesys godaddy godaddy-v6 googledomains gratisdns he-net he-net-v6 he-net-tunnelbroker hover loopia namecheap noip noip-free ods opendns ovh-dynhost route53 route53-v6 selfhost spdyn spdyn-v6 zoneedit');
28
define('DYNDNS_PROVIDER_DESCRIPTIONS', 'All-Inkl.com,Azure DNS,Azure DNS (v6),City Network,Cloudflare,Cloudflare (v6),ClouDNS,Custom,Custom (v6),DigitalOcean,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,GoDaddy,GoDaddy (v6),Google Domains,GratisDNS,HE.net,HE.net (v6),HE.net Tunnelbroker,Hover,Loopia,Namecheap,No-IP,No-IP (free),ODS.org,OpenDNS,OVH DynHOST,Route 53,Route 53 (v6),SelfHost,SPDYN,SPDYN (v6),ZoneEdit');
29

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

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

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

    
43
	$Iflist = get_configured_interface_list();
44
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
45

    
46
	$radvdconf = "# Automatically Generated, do not edit\n";
47

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

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

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

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

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

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

    
90
		$realif = get_real_interface($dhcpv6if, "inet6");
91

    
92
		if (isset($radvdifs[$realif])) {
93
			continue;
94
		}
95

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

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

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

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

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

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

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

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

    
201
		$radvdconf .= "\t};\n";
202

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

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

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

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

    
320
		$realif = get_real_interface($if, "inet6");
321

    
322
		/* prevent duplicate entries, manual overrides */
323
		if (isset($radvdifs[$realif])) {
324
			continue;
325
		}
326

    
327
		$ifcfgipv6 = get_interface_ipv6($if);
328
		if (!is_ipaddrv6($ifcfgipv6)) {
329
			$subnetv6 = "::";
330
			$ifcfgsnv6 = "64";
331
		} else {
332
			$ifcfgsnv6 = get_interface_subnetv6($if);
333
			$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
334
		}
335
		$radvdifs[$realif] = $realif;
336

    
337
		$autotype = $config['interfaces'][$trackif]['ipaddrv6'];
338

    
339
		if ($g['debug']) {
340
			log_error("configuring RA on {$if} for type {$autotype} radvd subnet {$subnetv6}/{$ifcfgsnv6}");
341
		}
342

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

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

    
392
	/* write radvd.conf */
393
	if (!@file_put_contents("{$g['varetc_path']}/radvd.conf", $radvdconf)) {
394
		log_error(gettext("Error: cannot open radvd.conf in services_radvd_configure()."));
395
		if (platform_booting()) {
396
			printf("Error: cannot open radvd.conf in services_radvd_configure().\n");
397
		}
398
	}
399
	unset($radvdconf);
400

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

    
419
function services_dhcpd_configure($family = "all", $blacklist = array()) {
420
	global $config, $g;
421

    
422
	$dhcpdconfigurelck = lock("dhcpdconfigure", LOCK_EX);
423

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

    
440
	$status = `/sbin/mount | /usr/bin/grep -v grep | /usr/bin/grep "{$g['dhcpd_chroot_path']}/dev"`;
441
	if (!trim($status)) {
442
		fwrite($fd, "/sbin/mount -t devfs devfs {$g['dhcpd_chroot_path']}/dev\n");
443
	}
444
	fclose($fd);
445
	mwexec("/bin/sh {$g['tmp_path']}/dhcpd.sh");
446

    
447
	if ($family == "all" || $family == "inet") {
448
		services_dhcpdv4_configure();
449
	}
450
	if ($family == "all" || $family == "inet6") {
451
		services_dhcpdv6_configure($blacklist);
452
		services_radvd_configure($blacklist);
453
	}
454

    
455
	unlock($dhcpdconfigurelck);
456
}
457

    
458
function services_dhcpdv4_configure() {
459
	global $config, $g;
460
	$need_ddns_updates = false;
461
	$ddns_zones = array();
462

    
463
	if ($g['services_dhcp_server_enable'] == false) {
464
		return;
465
	}
466

    
467
	if (isset($config['system']['developerspew'])) {
468
		$mt = microtime();
469
		echo "services_dhcpdv4_configure($if) being called $mt\n";
470
	}
471

    
472
	/* kill any running dhcpd */
473
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid")) {
474
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid");
475
	}
476

    
477
	/* DHCP enabled on any interfaces? */
478
	if (!is_dhcp_server_enabled()) {
479
		return 0;
480
	}
481

    
482
	$syscfg = $config['system'];
483
	if (!is_array($config['dhcpd'])) {
484
		$config['dhcpd'] = array();
485
	}
486
	$dhcpdcfg = $config['dhcpd'];
487
	$Iflist = get_configured_interface_list();
488

    
489
	/* Only consider DNS servers with IPv4 addresses for the IPv4 DHCP server. */
490
	$dns_arrv4 = array();
491
	if (is_array($syscfg['dnsserver'])) {
492
		foreach ($syscfg['dnsserver'] as $dnsserver) {
493
			if (is_ipaddrv4($dnsserver)) {
494
				$dns_arrv4[] = $dnsserver;
495
			}
496
		}
497
	}
498

    
499
	if (platform_booting()) {
500
		echo gettext("Starting DHCP service...");
501
	} else {
502
		sleep(1);
503
	}
504

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

    
533
	$dhcpdconf = <<<EOD
534

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

    
547
EOD;
548

    
549
	if (!isset($dhcpifconf['pingcheck'])) {
550
		$dhcpdconf .= "ping-check true;\n";
551
	} else {
552
		$dhcpdconf .= "ping-check false;\n";
553
	}
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
	$dhcpdifs = array();
564
	$enable_add_routers = false;
565
	$gateways_arr = return_gateways_array();
566
	/* only add a routers line if the system has any IPv4 gateway at all */
567
	/* a static route has a gateway, manually overriding this field always works */
568
	foreach ($gateways_arr as $gwitem) {
569
		if ($gwitem['ipprotocol'] == "inet") {
570
			$enable_add_routers = true;
571
			break;
572
		}
573
	}
574

    
575
	/*    loop through and determine if we need to setup
576
	 *    failover peer "bleh" entries
577
	 */
578
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
579

    
580
		if (!isset($config['interfaces'][$dhcpif]['enable'])) {
581
			continue;
582
		}
583

    
584
		interfaces_staticarp_configure($dhcpif);
585

    
586
		if (!isset($dhcpifconf['enable'])) {
587
			continue;
588
		}
589

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

    
631
			if (is_ipaddrv4($intip)) {
632
				$dhcpdconf .= <<<EOPP
633
failover peer "dhcp_{$dhcpif}" {
634
  {$type};
635
  address {$intip};
636
  port {$my_port};
637
  peer address {$dhcpifconf['failover_peerip']};
638
  peer port {$peer_port};
639
  max-response-delay 10;
640
  max-unacked-updates 10;
641
  {$dhcpdconf_pri}
642
  load balance max seconds 3;
643
}
644
\n
645
EOPP;
646
			}
647
		}
648
	}
649

    
650
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
651

    
652
		$newzone = array();
653
		$ifcfg = $config['interfaces'][$dhcpif];
654

    
655
		if (!isset($dhcpifconf['enable']) || !isset($Iflist[$dhcpif])) {
656
			continue;
657
		}
658
		$ifcfgip = get_interface_ip($dhcpif);
659
		$ifcfgsn = get_interface_subnet($dhcpif);
660
		$subnet = gen_subnet($ifcfgip, $ifcfgsn);
661
		$subnetmask = gen_subnet_mask($ifcfgsn);
662

    
663
		if (!is_ipaddr($subnet)) {
664
			continue;
665
		}
666

    
667
		$all_pools = array();
668
		$all_pools[] = $dhcpifconf;
669
		if (is_array($dhcpifconf['pool'])) {
670
			$all_pools = array_merge($all_pools, $dhcpifconf['pool']);
671
		}
672

    
673
		$dnscfg = "";
674

    
675
		if ($dhcpifconf['domain']) {
676
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
677
		}
678

    
679
		if ($dhcpifconf['domainsearchlist'] <> "") {
680
			$dnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpifconf['domainsearchlist'])) . "\";\n";
681
		}
682

    
683
		if (isset($dhcpifconf['ddnsupdate'])) {
684
			$need_ddns_updates = true;
685
			$newzone = array();
686
			if ($dhcpifconf['ddnsdomain'] <> "") {
687
				$newzone['domain-name'] = $dhcpifconf['ddnsdomain'];
688
				$dnscfg .= "	ddns-domainname \"{$dhcpifconf['ddnsdomain']}\";\n";
689
			} else {
690
				$newzone['domain-name'] = $config['system']['domain'];
691
			}
692

    
693
			if (empty($dhcpifconf['ddnsclientupdates'])) {
694
				$ddnsclientupdates = 'allow';
695
			} else {
696
				$ddnsclientupdates = $dhcpifconf['ddnsclientupdates'];
697
			}
698

    
699
			$dnscfg .= "	{$ddnsclientupdates} client-updates;\n";
700

    
701
			$revsubnet = array_reverse(explode('.',$subnet));
702

    
703
			/* Take care of full classes first */
704
			switch ($ifcfgsn) {
705
				case 8:
706
					$start_octet = 3;
707
					break;
708
				case 16:
709
					$start_octet = 2;
710
					break;
711
				case 24:
712
					$start_octet = 1;
713
					break;
714
				default:
715
					$start_octet = 0;
716
					/* Add subnet bitmask to first octet */
717
					$revsubnet[0] .= '-' . $ifcfgsn;
718
					break;
719

    
720
			}
721

    
722
			$ptr_domain = '';
723
			for ($octet = 0; $octet <= 3; $octet++) {
724
				if ($octet < $start_octet) {
725
					continue;
726
				}
727
				$ptr_domain .= ((empty($ptr_domain) && $ptr_domain !== "0") ? '' : '.');
728
				$ptr_domain .= $revsubnet[$octet];
729
			}
730
			$ptr_domain .= ".in-addr.arpa";
731
			$newzone['ptr-domain'] = $ptr_domain;
732
			unset($ptr_domain, $revsubnet, $start_octet);
733
		}
734

    
735
		if (is_array($dhcpifconf['dnsserver']) && ($dhcpifconf['dnsserver'][0])) {
736
			$dnscfg .= "	option domain-name-servers " . join(",", $dhcpifconf['dnsserver']) . ";";
737
			if ($newzone['domain-name']) {
738
				$newzone['dns-servers'] = $dhcpifconf['dnsserver'];
739
			}
740
		} else if (isset($config['dnsmasq']['enable'])) {
741
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
742
			if ($newzone['domain-name'] && is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
743
				$newzone['dns-servers'] = $syscfg['dnsserver'];
744
			}
745
		} else if (isset($config['unbound']['enable'])) {
746
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
747
		} else if (!empty($dns_arrv4)) {
748
			$dnscfg .= "	option domain-name-servers " . join(",", $dns_arrv4) . ";";
749
			if ($newzone['domain-name']) {
750
				$newzone['dns-servers'] = $dns_arrv4;
751
			}
752
		}
753

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

    
778
		$dhcpdconf .= "subnet {$subnet} netmask {$subnetmask} {\n";
779

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

    
825
			/* allow/deny MACs */
826
			$mac_allow_list = array_unique(explode(',', $poolconf['mac_allow']));
827
			foreach ($mac_allow_list as $mac) {
828
				if (empty($mac)) {
829
					continue;
830
				}
831
				$dhcpdconf .= "		allow members of \"" . str_replace(':', '', $mac) . "\";\n";
832
			}
833
			$deny_action = "deny";
834
			if (isset($poolconf['nonak']) && empty($poolconf['failover_peerip'])) {
835
				$deny_action = "ignore";
836
			}
837
			$mac_deny_list = array_unique(explode(',', $poolconf['mac_deny']));
838
			foreach ($mac_deny_list as $mac) {
839
				if (empty($mac)) {
840
					continue;
841
				}
842
				$dhcpdconf .= "		$deny_action members of \"" . str_replace(':', '', $mac) . "\";\n";
843
			}
844

    
845
			if ($poolconf['failover_peerip'] <> "") {
846
				$dhcpdconf .= "		$deny_action dynamic bootp clients;\n";
847
			}
848

    
849
			if (isset($poolconf['denyunknown'])) {
850
				$dhcpdconf .= "		$deny_action unknown-clients;\n";
851
			}
852

    
853
			if ($poolconf['gateway'] && $poolconf['gateway'] != "none" && ($poolconf['gateway'] != $dhcpifconf['gateway'])) {
854
				$dhcpdconf .= "		option routers {$poolconf['gateway']};\n";
855
			}
856

    
857
			if ($dhcpifconf['failover_peerip'] <> "") {
858
				$dhcpdconf .= "		failover peer \"dhcp_{$dhcpif}\";\n";
859
			}
860

    
861
			$pdnscfg = "";
862

    
863
			if ($poolconf['domain'] && ($poolconf['domain'] != $dhcpifconf['domain'])) {
864
				$pdnscfg .= "		option domain-name \"{$poolconf['domain']}\";\n";
865
			}
866

    
867
			if (!empty($poolconf['domainsearchlist']) && ($poolconf['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
868
				$pdnscfg .= "		option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $poolconf['domainsearchlist'])) . "\";\n";
869
			}
870

    
871
			if (isset($poolconf['ddnsupdate'])) {
872
				if (($poolconf['ddnsdomain'] <> "") && ($poolconf['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
873
					$pdnscfg .= "		ddns-domainname \"{$poolconf['ddnsdomain']}\";\n";
874
				}
875
				$pdnscfg .= "		ddns-update-style interim;\n";
876
			}
877

    
878
			$dhcpdconf .= "{$pdnscfg}";
879

    
880
			// default-lease-time
881
			if ($poolconf['defaultleasetime'] && ($poolconf['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
882
				$dhcpdconf .= "		default-lease-time {$poolconf['defaultleasetime']};\n";
883
			}
884

    
885
			// max-lease-time
886
			if ($poolconf['maxleasetime'] && ($poolconf['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
887
				$dhcpdconf .= "		max-lease-time {$poolconf['maxleasetime']};\n";
888
			}
889

    
890
			// ignore bootp
891
			if (isset($poolconf['ignorebootp'])) {
892
				$dhcpdconf .= "		ignore bootp;\n";
893
			}
894

    
895
			// ignore-client-uids
896
			if (isset($poolconf['ignoreclientuids'])) {
897
				$dhcpdconf .= "		ignore-client-uids true;\n";
898
			}
899

    
900
			// netbios-name*
901
			if (is_array($poolconf['winsserver']) && $poolconf['winsserver'][0] && ($poolconf['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
902
				$dhcpdconf .= "		option netbios-name-servers " . join(",", $poolconf['winsserver']) . ";\n";
903
				$dhcpdconf .= "		option netbios-node-type 8;\n";
904
			}
905

    
906
			// ntp-servers
907
			if (is_array($poolconf['ntpserver']) && $poolconf['ntpserver'][0] && ($poolconf['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
908
				$dhcpdconf .= "		option ntp-servers " . join(",", $poolconf['ntpserver']) . ";\n";
909
			}
910

    
911
			// tftp-server-name
912
			if (!empty($poolconf['tftp']) && ($poolconf['tftp'] != $dhcpifconf['tftp'])) {
913
				$dhcpdconf .= "		option tftp-server-name \"{$poolconf['tftp']}\";\n";
914
			}
915

    
916
			// Handle pool-specific options
917
			$dhcpdconf .= "\n";
918
			// Ignore the first pool, which is the "overall" pool when $all_pools_idx is 0 - those are put outside the pool block later
919
			if ($poolconf['numberoptions']['item'] && ($all_pools_idx > 0)) {
920
				// Use the "real" pool index from the config, excluding the "overall" pool, and based from 0.
921
				// This matches the way $poolidx was used when generating the $custoptions string earlier.
922
				$poolidx = $all_pools_idx - 1;
923
				foreach ($poolconf['numberoptions']['item'] as $itemidx => $item) {
924
					$item_value = base64_decode($item['value']);
925
					if (empty($item['type']) || $item['type'] == "text") {
926
						$dhcpdconf .= "		option custom-{$dhcpif}-{$poolidx}-{$itemidx} \"{$item_value}\";\n";
927
					} else {
928
						$dhcpdconf .= "		option custom-{$dhcpif}-{$poolidx}-{$itemidx} {$item_value};\n";
929
					}
930
				}
931
			}
932

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

    
938
			// net boot information
939
			if (isset($poolconf['netboot'])) {
940
				if (!empty($poolconf['nextserver']) && ($poolconf['nextserver'] != $dhcpifconf['nextserver'])) {
941
					$dhcpdconf .= "		next-server {$poolconf['nextserver']};\n";
942
				}
943

    
944
				if (!empty($poolconf['filename']) &&
945
				    (!isset($dhcpifconf['filename']) ||
946
				    ($poolconf['filename'] != $dhcpifconf['filename']))) {
947
					$filename = $poolconf['filename'];
948
				}
949
				if (!empty($poolconf['filename32']) &&
950
				    (!isset($dhcpifconf['filename32']) ||
951
				    ($poolconf['filename32'] != $dhcpifconf['filename32']))) {
952
					$filename32 = $poolconf['filename32'];
953
				}
954
				if (!empty($poolconf['filename64']) &&
955
				    (!isset($dhcpifconf['filename64']) ||
956
				    ($poolconf['filename64'] != $dhcpifconf['filename64']))) {
957
					$filename64 = $poolconf['filename64'];
958
				}
959

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

    
972
				if (!empty($filename) && !empty($filename32) && !empty($filename64)) {
973
					$dhcpdconf .= "		if option arch = 00:06 {\n";
974
					$dhcpdconf .= "			filename \"{$filename32}\";\n";
975
					$dhcpdconf .= "		} else if option arch = 00:07 {\n";
976
					$dhcpdconf .= "			filename \"{$filename64}\";\n";
977
					$dhcpdconf .= "		} else if option arch = 00:09 {\n";
978
					$dhcpdconf .= "			filename \"{$filename64}\";\n";
979
					$dhcpdconf .= "		} else {\n";
980
					$dhcpdconf .= "			filename \"{$filename}\";\n";
981
					$dhcpdconf .= "		}\n\n";
982
				} elseif (!empty($filename)) {
983
					$dhcpdconf .= "		filename \"{$filename}\";\n";
984
				}
985
				unset($filename, $filename32, $filename64);
986

    
987
				if (!empty($poolconf['rootpath']) && ($poolconf['rootpath'] != $dhcpifconf['rootpath'])) {
988
					$dhcpdconf .= "		option root-path \"{$poolconf['rootpath']}\";\n";
989
				}
990
			}
991
			$dhcpdconf .= "		range {$poolconf['range']['from']} {$poolconf['range']['to']};\n";
992
			$dhcpdconf .= "	}\n\n";
993
		}
994
// End of settings inside pools
995

    
996
		if ($dhcpifconf['gateway'] && $dhcpifconf['gateway'] != "none") {
997
			$routers = $dhcpifconf['gateway'];
998
			$add_routers = true;
999
		} elseif ($dhcpifconf['gateway'] == "none") {
1000
			$add_routers = false;
1001
		} else {
1002
			$add_routers = $enable_add_routers;
1003
			$routers = $ifcfgip;
1004
		}
1005
		if ($add_routers) {
1006
			$dhcpdconf .= "	option routers {$routers};\n";
1007
		}
1008

    
1009
		$dhcpdconf .= <<<EOD
1010
$dnscfg
1011

    
1012
EOD;
1013
		// default-lease-time
1014
		if ($dhcpifconf['defaultleasetime']) {
1015
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
1016
		}
1017

    
1018
		// max-lease-time
1019
		if ($dhcpifconf['maxleasetime']) {
1020
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
1021
		}
1022

    
1023
		// netbios-name*
1024
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
1025
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
1026
			$dhcpdconf .= "	option netbios-node-type 8;\n";
1027
		}
1028

    
1029
		// ntp-servers
1030
		if (is_array($dhcpifconf['ntpserver']) && $dhcpifconf['ntpserver'][0]) {
1031
			$dhcpdconf .= "	option ntp-servers " . join(",", $dhcpifconf['ntpserver']) . ";\n";
1032
		}
1033

    
1034
		// tftp-server-name
1035
		if ($dhcpifconf['tftp'] <> "") {
1036
			$dhcpdconf .= "	option tftp-server-name \"{$dhcpifconf['tftp']}\";\n";
1037
		}
1038

    
1039
		// Handle option, number rowhelper values
1040
		$dhcpdconf .= "\n";
1041
		if ($dhcpifconf['numberoptions']['item']) {
1042
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
1043
				$item_value = base64_decode($item['value']);
1044
				if (empty($item['type']) || $item['type'] == "text") {
1045
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} \"{$item_value}\";\n";
1046
				} else {
1047
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} {$item_value};\n";
1048
				}
1049
			}
1050
		}
1051

    
1052
		// ldap-server
1053
		if ($dhcpifconf['ldap'] <> "") {
1054
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
1055
		}
1056

    
1057
		// net boot information
1058
		if (isset($dhcpifconf['netboot'])) {
1059
			if ($dhcpifconf['nextserver'] <> "") {
1060
				$dhcpdconf .= "	next-server {$dhcpifconf['nextserver']};\n";
1061
			}
1062
			if (!empty($dhcpifconf['filename']) && !empty($dhcpifconf['filename32']) && !empty($dhcpifconf['filename64'])) {
1063
				$dhcpdconf .= "	if option arch = 00:06 {\n";
1064
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename32']}\";\n";
1065
				$dhcpdconf .= "	} else if option arch = 00:07 {\n";
1066
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1067
				$dhcpdconf .= "	} else if option arch = 00:09 {\n";
1068
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1069
				$dhcpdconf .= "	} else {\n";
1070
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename']}\";\n";
1071
				$dhcpdconf .= "	}\n\n";
1072
			} elseif (!empty($dhcpifconf['filename'])) {
1073
				$dhcpdconf .= "	filename \"{$dhcpifconf['filename']}\";\n";
1074
			}
1075
			if (!empty($dhcpifconf['rootpath'])) {
1076
				$dhcpdconf .= "	option root-path \"{$dhcpifconf['rootpath']}\";\n";
1077
			}
1078
		}
1079

    
1080
		$dhcpdconf .= <<<EOD
1081
}
1082

    
1083
EOD;
1084

    
1085
		/* add static mappings */
1086
		if (is_array($dhcpifconf['staticmap'])) {
1087

    
1088
			$i = 0;
1089
			foreach ($dhcpifconf['staticmap'] as $sm) {
1090
				$dhcpdconf .= "host s_{$dhcpif}_{$i} {\n";
1091

    
1092
				if ($sm['mac']) {
1093
					$dhcpdconf .= "        hardware ethernet {$sm['mac']};\n";
1094
				}
1095

    
1096
				if ($sm['cid']) {
1097
					$dhcpdconf .= "        option dhcp-client-identifier \"{$sm['cid']}\";\n";
1098
				}
1099

    
1100
				if ($sm['ipaddr']) {
1101
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
1102
				}
1103

    
1104
				if ($sm['hostname']) {
1105
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1106
					$dhhostname = str_replace(".", "_", $dhhostname);
1107
					$dhcpdconf .= "	option host-name \"{$dhhostname}\";\n";
1108
					if ((isset($dhcpifconf['ddnsupdate']) || isset($sm['ddnsupdate'])) && (isset($dhcpifconf['ddnsforcehostname']) || isset($sm['ddnsforcehostname']))) {
1109
						$dhcpdconf .= "	ddns-hostname \"{$dhhostname}\";\n";
1110
					}
1111
				}
1112
				if ($sm['filename']) {
1113
					$dhcpdconf .= "	filename \"{$sm['filename']}\";\n";
1114
				}
1115

    
1116
				if ($sm['rootpath']) {
1117
					$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1118
				}
1119

    
1120
				if ($sm['gateway'] && ($sm['gateway'] != $dhcpifconf['gateway'])) {
1121
					$dhcpdconf .= "	option routers {$sm['gateway']};\n";
1122
				}
1123

    
1124
				$smdnscfg = "";
1125

    
1126
				if ($sm['domain'] && ($sm['domain'] != $dhcpifconf['domain'])) {
1127
					$smdnscfg .= "	option domain-name \"{$sm['domain']}\";\n";
1128
				}
1129

    
1130
				if (!empty($sm['domainsearchlist']) && ($sm['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
1131
					$smdnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $sm['domainsearchlist'])) . "\";\n";
1132
				}
1133

    
1134
				if (isset($sm['ddnsupdate'])) {
1135
					if (($sm['ddnsdomain'] <> "") && ($sm['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
1136
						$smdnscfg .= "		ddns-domainname \"{$sm['ddnsdomain']}\";\n";
1137
					}
1138
					$smdnscfg .= "		ddns-update-style interim;\n";
1139
				}
1140

    
1141
				if (is_array($sm['dnsserver']) && ($sm['dnsserver'][0]) && ($sm['dnsserver'][0] != $dhcpifconf['dnsserver'][0])) {
1142
					$smdnscfg .= "	option domain-name-servers " . join(",", $sm['dnsserver']) . ";\n";
1143
				}
1144
				$dhcpdconf .= "{$smdnscfg}";
1145

    
1146
				// default-lease-time
1147
				if ($sm['defaultleasetime'] && ($sm['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
1148
					$dhcpdconf .= "	default-lease-time {$sm['defaultleasetime']};\n";
1149
				}
1150

    
1151
				// max-lease-time
1152
				if ($sm['maxleasetime'] && ($sm['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
1153
					$dhcpdconf .= "	max-lease-time {$sm['maxleasetime']};\n";
1154
				}
1155

    
1156
				// netbios-name*
1157
				if (is_array($sm['winsserver']) && $sm['winsserver'][0] && ($sm['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
1158
					$dhcpdconf .= "	option netbios-name-servers " . join(",", $sm['winsserver']) . ";\n";
1159
					$dhcpdconf .= "	option netbios-node-type 8;\n";
1160
				}
1161

    
1162
				// ntp-servers
1163
				if (is_array($sm['ntpserver']) && $sm['ntpserver'][0] && ($sm['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
1164
					$dhcpdconf .= "	option ntp-servers " . join(",", $sm['ntpserver']) . ";\n";
1165
				}
1166

    
1167
				// tftp-server-name
1168
				if (!empty($sm['tftp']) && ($sm['tftp'] != $dhcpifconf['tftp'])) {
1169
					$dhcpdconf .= "	option tftp-server-name \"{$sm['tftp']}\";\n";
1170
				}
1171

    
1172
				$dhcpdconf .= "}\n";
1173
				$i++;
1174
			}
1175
		}
1176

    
1177
		$dhcpdifs[] = get_real_interface($dhcpif);
1178
		if ($newzone['domain-name']) {
1179
			if ($need_ddns_updates) {
1180
				$newzone['dns-servers'] = array($dhcpifconf['ddnsdomainprimary']);
1181
				$newzone['ddnsdomainkeyname'] = $dhcpifconf['ddnsdomainkeyname'];
1182
				$newzone['ddnsdomainkeyalgorithm'] = $dhcpifconf['ddnsdomainkeyalgorithm'];
1183
				$newzone['ddnsdomainkey'] = $dhcpifconf['ddnsdomainkey'];
1184
				$dhcpdconf .= dhcpdkey($dhcpifconf);
1185
			}
1186
			$ddns_zones[] = $newzone;
1187
		}
1188
	}
1189

    
1190
	if ($need_ddns_updates) {
1191
		$dhcpdconf .= "ddns-update-style interim;\n";
1192
		$dhcpdconf .= "update-static-leases on;\n";
1193

    
1194
		$dhcpdconf .= dhcpdzones($ddns_zones);
1195
	}
1196

    
1197
	/* write dhcpd.conf */
1198
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpd.conf", $dhcpdconf)) {
1199
		printf(gettext("Error: cannot open dhcpd.conf in services_dhcpdv4_configure().%s"), "\n");
1200
		unset($dhcpdconf);
1201
		return 1;
1202
	}
1203
	unset($dhcpdconf);
1204

    
1205
	/* create an empty leases database */
1206
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
1207
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
1208
	}
1209

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

    
1214
	/* fire up dhcpd in a chroot */
1215
	if (count($dhcpdifs) > 0) {
1216
		mwexec("/usr/local/sbin/dhcpd -user dhcpd -group _dhcp -chroot {$g['dhcpd_chroot_path']} -cf /etc/dhcpd.conf -pf {$g['varrun_path']}/dhcpd.pid " .
1217
			join(" ", $dhcpdifs));
1218
	}
1219

    
1220
	if (platform_booting()) {
1221
		print "done.\n";
1222
	}
1223

    
1224
	return 0;
1225
}
1226

    
1227
function dhcpdkey($dhcpifconf) {
1228
	$dhcpdconf = "";
1229
	if (!empty($dhcpifconf['ddnsdomainkeyname']) && !empty($dhcpifconf['ddnsdomainkey'])) {
1230
		$algorithm = empty($dhcpifconf['ddnsdomainkeyalgorithm']) ? 'hmac-md5' : $dhcpifconf['ddnsdomainkeyalgorithm'];
1231
		$dhcpdconf .= "key {$dhcpifconf['ddnsdomainkeyname']} {\n";
1232
		$dhcpdconf .= "	algorithm {$algorithm};\n";
1233
		$dhcpdconf .= "	secret {$dhcpifconf['ddnsdomainkey']};\n";
1234
		$dhcpdconf .= "}\n";
1235
	}
1236

    
1237
	return $dhcpdconf;
1238
}
1239

    
1240
function dhcpdzones($ddns_zones) {
1241
	$dhcpdconf = "";
1242

    
1243
	if (is_array($ddns_zones)) {
1244
		$added_zones = array();
1245
		foreach ($ddns_zones as $zone) {
1246
			if (!is_array($zone) || empty($zone) || !is_array($zone['dns-servers'])) {
1247
				continue;
1248
			}
1249
			$primary = $zone['dns-servers'][0];
1250
			$secondary = empty($zone['dns-servers'][1]) ? "" : $zone['dns-servers'][1];
1251

    
1252
			// Make sure we aren't using any invalid or IPv6 DNS servers.
1253
			if (!is_ipaddrv4($primary)) {
1254
				if (is_ipaddrv4($secondary)) {
1255
					$primary = $secondary;
1256
					$secondary = "";
1257
				} else {
1258
					continue;
1259
				}
1260
			}
1261

    
1262
			// We don't need to add zones multiple times.
1263
			if ($zone['domain-name'] && !in_array($zone['domain-name'], $added_zones)) {
1264
				$dhcpdconf .= "zone {$zone['domain-name']}. {\n";
1265
				$dhcpdconf .= "	primary {$primary};\n";
1266
				if (is_ipaddrv4($secondary)) {
1267
					$dhcpdconf .= "	secondary {$secondary};\n";
1268
				}
1269
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1270
					$dhcpdconf .= "	key {$zone['ddnsdomainkeyname']};\n";
1271
				}
1272
				$dhcpdconf .= "}\n";
1273
				$added_zones[] = $zone['domain-name'];
1274
			}
1275
			if ($zone['ptr-domain'] && !in_array($zone['ptr-domain'], $added_zones)) {
1276
				$dhcpdconf .= "zone {$zone['ptr-domain']} {\n";
1277
				$dhcpdconf .= "	primary {$primary};\n";
1278
				if (is_ipaddrv4($secondary)) {
1279
					$dhcpdconf .= "	secondary {$secondary};\n";
1280
				}
1281
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1282
					$dhcpdconf .= "	key {$zone['ddnsdomainkeyname']};\n";
1283
				}
1284
				$dhcpdconf .= "}\n";
1285
				$added_zones[] = $zone['ptr-domain'];
1286
			}
1287
		}
1288
	}
1289

    
1290
	return $dhcpdconf;
1291
}
1292

    
1293
function services_dhcpdv6_configure($blacklist = array()) {
1294
	global $config, $g;
1295

    
1296
	if ($g['services_dhcp_server_enable'] == false) {
1297
		return;
1298
	}
1299

    
1300
	if (isset($config['system']['developerspew'])) {
1301
		$mt = microtime();
1302
		echo "services_dhcpd_configure($if) being called $mt\n";
1303
	}
1304

    
1305
	/* kill any running dhcpd */
1306
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid")) {
1307
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid");
1308
	}
1309
	if (isvalidpid("{$g['varrun_path']}/dhcpleases6.pid")) {
1310
		killbypid("{$g['varrun_path']}/dhcpleases6.pid");
1311
	}
1312

    
1313
	/* DHCP enabled on any interfaces? */
1314
	if (!is_dhcpv6_server_enabled()) {
1315
		return 0;
1316
	}
1317

    
1318
	$syscfg = $config['system'];
1319
	if (!is_array($config['dhcpdv6'])) {
1320
		$config['dhcpdv6'] = array();
1321
	}
1322
	$dhcpdv6cfg = $config['dhcpdv6'];
1323
	$Iflist = get_configured_interface_list();
1324
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
1325

    
1326

    
1327
	if (platform_booting()) {
1328
		echo "Starting DHCPv6 service...";
1329
	} else {
1330
		sleep(1);
1331
	}
1332

    
1333
	$custoptionsv6 = "";
1334
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1335
		if (is_array($dhcpv6ifconf['numberoptions']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1336
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1337
				$custoptionsv6 .= "option custom-{$dhcpv6if}-{$itemv6idx} code {$itemv6['number']} = text;\n";
1338
			}
1339
		}
1340
	}
1341

    
1342
	if (isset($dhcpv6ifconf['netboot']) && !empty($dhcpv6ifconf['bootfile_url'])) {
1343
		$custoptionsv6 .= "option dhcp6.bootfile-url code 59 = string;\n";
1344
	}
1345

    
1346
	$dhcpdv6conf = <<<EOD
1347

    
1348
option domain-name "{$syscfg['domain']}";
1349
option ldap-server code 95 = text;
1350
option domain-search-list code 119 = text;
1351
{$custoptionsv6}
1352
default-lease-time 7200;
1353
max-lease-time 86400;
1354
log-facility local7;
1355
one-lease-per-client true;
1356
deny duplicates;
1357
ping-check true;
1358
update-conflict-detection false;
1359

    
1360
EOD;
1361

    
1362
	if (!isset($dhcpv6ifconf['disableauthoritative'])) {
1363
		$dhcpdv6conf .= "authoritative;\n";
1364
	}
1365

    
1366
	if (isset($dhcpv6ifconf['alwaysbroadcast'])) {
1367
		$dhcpdv6conf .= "always-broadcast on\n";
1368
	}
1369

    
1370
	$dhcpdv6ifs = array();
1371

    
1372
	$dhcpv6num = 0;
1373
	$nsupdate = false;
1374

    
1375
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1376

    
1377
		$ddns_zones = array();
1378

    
1379
		$ifcfgv6 = $config['interfaces'][$dhcpv6if];
1380

    
1381
		if (!isset($dhcpv6ifconf['enable']) || !isset($Iflist[$dhcpv6if]) || !isset($ifcfgv6['enable'])) {
1382
			continue;
1383
		}
1384
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1385
		if (!is_ipaddrv6($ifcfgipv6)) {
1386
			continue;
1387
		}
1388
		$ifcfgsnv6 = get_interface_subnetv6($dhcpv6if);
1389
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1390
		// We might have some prefix-delegation on WAN (e.g. /48),
1391
		// but then it is split and given out to individual interfaces
1392
		// (LAN, OPT1, OPT2...) as multiple /64 subnets. So the size
1393
		// of each subnet here is always /64.
1394
		$pdlen = 64;
1395

    
1396
		$dnscfgv6 = "";
1397

    
1398
		if ($dhcpv6ifconf['domain']) {
1399
			$dnscfgv6 .= "	option domain-name \"{$dhcpv6ifconf['domain']}\";\n";
1400
		}
1401

    
1402
		if ($dhcpv6ifconf['domainsearchlist'] <> "") {
1403
			$dnscfgv6 .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpv6ifconf['domainsearchlist'])) . "\";\n";
1404
		}
1405

    
1406
		if (isset($dhcpv6ifconf['ddnsupdate'])) {
1407
			if ($dhcpv6ifconf['ddnsdomain'] <> "") {
1408
				$dnscfgv6 .= "	ddns-domainname \"{$dhcpv6ifconf['ddnsdomain']}\";\n";
1409
			}
1410
			if (empty($dhcpv6ifconf['ddnsclientupdates'])) {
1411
				$ddnsclientupdates = 'allow';
1412
			} else {
1413
				$ddnsclientupdates = $dhcpv6ifconf['ddnsclientupdates'];
1414
			}
1415
			$dnscfgv6 .= "	{$ddnsclientupdates} client-updates;\n";
1416
			$nsupdate = true;
1417
		} else {
1418
			$dnscfgv6 .= "	do-forward-updates false;\n";
1419
		}
1420

    
1421
		if (is_array($dhcpv6ifconf['dnsserver']) && ($dhcpv6ifconf['dnsserver'][0])) {
1422
			$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dhcpv6ifconf['dnsserver']) . ";";
1423
		} else if (((isset($config['dnsmasq']['enable'])) || isset($config['unbound']['enable'])) && (is_ipaddrv6($ifcfgipv6))) {
1424
			$dnscfgv6 .= "	option dhcp6.name-servers {$ifcfgipv6};";
1425
		} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1426
			$dns_arrv6 = array();
1427
			foreach ($syscfg['dnsserver'] as $dnsserver) {
1428
				if (is_ipaddrv6($dnsserver)) {
1429
					$dns_arrv6[] = $dnsserver;
1430
				}
1431
			}
1432
			if (!empty($dns_arrv6)) {
1433
				$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dns_arrv6) . ";";
1434
			}
1435
		}
1436

    
1437
		if (!is_ipaddrv6($ifcfgipv6)) {
1438
			$ifcfgsnv6 = "64";
1439
			$subnetv6 = gen_subnetv6($dhcpv6ifconf['range']['from'], $ifcfgsnv6);
1440
		}
1441

    
1442
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1443

    
1444
		if (isset($dhcpv6ifconf['ddnsupdate']) &&
1445
		    !empty($dhcpv6ifconf['ddnsdomain'])) {
1446
			$newzone = array();
1447
			$newzone['domain-name'] = $dhcpv6ifconf['ddnsdomain'];
1448
			$newzone['dns-servers'][] = $dhcpv6ifconf['ddnsdomainprimary'];
1449
			$newzone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1450
			$newzone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1451
			$ddns_zones[] = $newzone;
1452
			if (isset($dhcpv6ifconf['ddnsreverse'])) {
1453
				$ptr_zones = get_v6_ptr_zones($subnetv6, $ifcfgsnv6);
1454
				foreach ($ptr_zones as $ptr_zone) {
1455
					$reversezone = array();
1456
					$reversezone['ptr-domain'] = $ptr_zone;
1457
					$reversezone['dns-servers'][] = $dhcpv6ifconf['ddnsdomainprimary'];
1458
					$reversezone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1459
					$reversezone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1460
					$ddns_zones[] = $reversezone;
1461
				}
1462
			}
1463
		}
1464

    
1465
		$dhcpdv6conf .= " {\n";
1466

    
1467
		$range_from = $dhcpv6ifconf['range']['from'];
1468
		$range_to = $dhcpv6ifconf['range']['to'];
1469
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
1470
			$range_from = merge_ipv6_delegated_prefix($ifcfgipv6, $range_from, $pdlen);
1471
			$range_to = merge_ipv6_delegated_prefix($ifcfgipv6, $range_to, $pdlen);
1472
		}
1473

    
1474
		$dhcpdv6conf .= <<<EOD
1475
	range6 {$range_from} {$range_to};
1476
$dnscfgv6
1477

    
1478
EOD;
1479

    
1480
		if (is_ipaddrv6($dhcpv6ifconf['prefixrange']['from']) && is_ipaddrv6($dhcpv6ifconf['prefixrange']['to'])) {
1481
			$dhcpdv6conf .= "	prefix6 {$dhcpv6ifconf['prefixrange']['from']} {$dhcpv6ifconf['prefixrange']['to']} /{$dhcpv6ifconf['prefixrange']['prefixlength']};\n";
1482
		}
1483
		if (is_ipaddrv6($dhcpv6ifconf['dns6ip'])) {
1484
			$dns6ip = $dhcpv6ifconf['dns6ip'];
1485
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1486
			    Net_IPv6::isInNetmask($dns6ip, '::', $pdlen)) {
1487
				$dns6ip = merge_ipv6_delegated_prefix($ifcfgipv6, $dns6ip, $pdlen);
1488
			}
1489
			$dhcpdv6conf .= "	option dhcp6.name-servers {$dns6ip};\n";
1490
		}
1491
		// default-lease-time
1492
		if ($dhcpv6ifconf['defaultleasetime']) {
1493
			$dhcpdv6conf .= "	default-lease-time {$dhcpv6ifconf['defaultleasetime']};\n";
1494
		}
1495

    
1496
		// max-lease-time
1497
		if ($dhcpv6ifconf['maxleasetime']) {
1498
			$dhcpdv6conf .= "	max-lease-time {$dhcpv6ifconf['maxleasetime']};\n";
1499
		}
1500

    
1501
		// ntp-servers
1502
		if (is_array($dhcpv6ifconf['ntpserver']) && $dhcpv6ifconf['ntpserver'][0]) {
1503
			$ntpservers = array();
1504
			foreach ($dhcpv6ifconf['ntpserver'] as $ntpserver) {
1505
				if (!is_ipaddrv6($ntpserver)) {
1506
					continue;
1507
				}
1508
				if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1509
				    Net_IPv6::isInNetmask($ntpserver, '::', $pdlen)) {
1510
					$ntpserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ntpserver, $pdlen);
1511
				}
1512
				$ntpservers[] = $ntpserver;
1513
			}
1514
			if (count($ntpservers) > 0) {
1515
				$dhcpdv6conf .= "        option dhcp6.sntp-servers " . join(",", $dhcpv6ifconf['ntpserver']) . ";\n";
1516
			}
1517
		}
1518
		// tftp-server-name
1519
		/* Needs ISC DHCPD support
1520
		 if ($dhcpv6ifconf['tftp'] <> "") {
1521
			$dhcpdv6conf .= "	option tftp-server-name \"{$dhcpv6ifconf['tftp']}\";\n";
1522
		 }
1523
		*/
1524

    
1525
		// Handle option, number rowhelper values
1526
		$dhcpdv6conf .= "\n";
1527
		if ($dhcpv6ifconf['numberoptions']['item']) {
1528
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1529
				$itemv6_value = base64_decode($itemv6['value']);
1530
				$dhcpdv6conf .= "	option custom-{$dhcpv6if}-{$itemv6idx} \"{$itemv6_value}\";\n";
1531
			}
1532
		}
1533

    
1534
		// ldap-server
1535
		if ($dhcpv6ifconf['ldap'] <> "") {
1536
			$ldapserver = $dhcpv6ifconf['ldap'];
1537
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1538
			    Net_IPv6::isInNetmask($ldapserver, '::', $pdlen)) {
1539
				$ldapserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ldapserver, $pdlen);
1540
			}
1541
			$dhcpdv6conf .= "	option ldap-server \"{$ldapserver}\";\n";
1542
		}
1543

    
1544
		// net boot information
1545
		if (isset($dhcpv6ifconf['netboot'])) {
1546
			if (!empty($dhcpv6ifconf['bootfile_url'])) {
1547
				$dhcpdv6conf .= "	option dhcp6.bootfile-url \"{$dhcpv6ifconf['bootfile_url']}\";\n";
1548
			}
1549
		}
1550

    
1551
		$dhcpdv6conf .= "}\n";
1552

    
1553
		/* add static mappings */
1554
		/* Needs to use DUID */
1555
		if (is_array($dhcpv6ifconf['staticmap'])) {
1556
			$i = 0;
1557
			foreach ($dhcpv6ifconf['staticmap'] as $sm) {
1558
				$dhcpdv6conf .= <<<EOD
1559
host s_{$dhcpv6if}_{$i} {
1560
	host-identifier option dhcp6.client-id {$sm['duid']};
1561

    
1562
EOD;
1563
				if ($sm['ipaddrv6']) {
1564
					$ipaddrv6 = $sm['ipaddrv6'];
1565
					if ($ifcfgv6['ipaddrv6'] == 'track6') {
1566
						$ipaddrv6 = merge_ipv6_delegated_prefix($ifcfgipv6, $ipaddrv6, $pdlen);
1567
					}
1568
					$dhcpdv6conf .= "	fixed-address6 {$ipaddrv6};\n";
1569
				}
1570

    
1571
				if ($sm['hostname']) {
1572
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1573
					$dhhostname = str_replace(".", "_", $dhhostname);
1574
					$dhcpdv6conf .= "	option host-name {$dhhostname};\n";
1575
					if (isset($dhcpv6ifconf['ddnsupdate']) &&
1576
					    isset($dhcpv6ifconf['ddnsforcehostname'])) {
1577
						$dhcpdv6conf .= "	ddns-hostname \"{$dhhostname}\";\n";
1578
					}
1579
				}
1580
				if ($sm['filename']) {
1581
					$dhcpdv6conf .= "	filename \"{$sm['filename']}\";\n";
1582
				}
1583

    
1584
				if ($sm['rootpath']) {
1585
					$dhcpdv6conf .= "	option root-path \"{$sm['rootpath']}\";\n";
1586
				}
1587

    
1588
				$dhcpdv6conf .= "}\n";
1589
				$i++;
1590
			}
1591
		}
1592

    
1593
		if ($dhcpv6ifconf['ddnsdomain']) {
1594
			$dhcpdv6conf .= dhcpdkey($dhcpv6ifconf);
1595
			$dhcpdv6conf .= dhcpdzones($ddns_zones);
1596
		}
1597

    
1598
		if ($config['dhcpdv6'][$dhcpv6if]['ramode'] <> "unmanaged" && isset($config['interfaces'][$dhcpv6if]['enable'])) {
1599
			if (preg_match("/poes/si", $dhcpv6if)) {
1600
				/* magic here */
1601
				$dhcpdv6ifs = array_merge($dhcpdv6ifs, get_pppoes_child_interfaces($dhcpv6if));
1602
			} else {
1603
				$realif = get_real_interface($dhcpv6if, "inet6");
1604
				if (stristr("$realif", "bridge")) {
1605
					$mac = get_interface_mac($realif);
1606
					$v6address = generate_ipv6_from_mac($mac);
1607
					/* Create link local address for bridges */
1608
					mwexec("/sbin/ifconfig {$realif} inet6 {$v6address}");
1609
				}
1610
				$realif = escapeshellcmd($realif);
1611
				$dhcpdv6ifs[] = $realif;
1612
			}
1613
		}
1614
	}
1615

    
1616
	if ($nsupdate) {
1617
		$dhcpdv6conf .= "ddns-update-style interim;\n";
1618
	} else {
1619
		$dhcpdv6conf .= "ddns-update-style none;\n";
1620
	}
1621

    
1622
	/* write dhcpdv6.conf */
1623
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf", $dhcpdv6conf)) {
1624
		log_error("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1625
		if (platform_booting()) {
1626
			printf("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1627
		}
1628
		unset($dhcpdv6conf);
1629
		return 1;
1630
	}
1631
	unset($dhcpdv6conf);
1632

    
1633
	/* create an empty leases v6 database */
1634
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases")) {
1635
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1636
	}
1637

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

    
1642
	/* fire up dhcpd in a chroot */
1643
	if (count($dhcpdv6ifs) > 0) {
1644
		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 " .
1645
			join(" ", $dhcpdv6ifs));
1646
		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");
1647
	}
1648
	if (platform_booting()) {
1649
		print gettext("done.") . "\n";
1650
	}
1651

    
1652
	return 0;
1653
}
1654

    
1655
function services_igmpproxy_configure() {
1656
	global $config, $g;
1657

    
1658
	/* kill any running igmpproxy */
1659
	killbyname("igmpproxy");
1660

    
1661
	if (!isset($config['igmpproxy']['enable'])) {
1662
		return 0;
1663
	}
1664
	if (!is_array($config['igmpproxy']['igmpentry']) || (count($config['igmpproxy']['igmpentry']) == 0)) {
1665
		return 1;
1666
	}
1667

    
1668
	$iflist = get_configured_interface_list();
1669

    
1670
	$igmpconf = <<<EOD
1671

    
1672
##------------------------------------------------------
1673
## Enable Quickleave mode (Sends Leave instantly)
1674
##------------------------------------------------------
1675
quickleave
1676

    
1677
EOD;
1678

    
1679
	foreach ($config['igmpproxy']['igmpentry'] as $igmpcf) {
1680
		unset($iflist[$igmpcf['ifname']]);
1681
		$realif = get_real_interface($igmpcf['ifname']);
1682
		if (empty($igmpcf['threshold'])) {
1683
			$threshld = 1;
1684
		} else {
1685
			$threshld = $igmpcf['threshold'];
1686
		}
1687
		$igmpconf .= "phyint {$realif} {$igmpcf['type']} ratelimit 0 threshold {$threshld}\n";
1688

    
1689
		if ($igmpcf['address'] <> "") {
1690
			$item = explode(" ", $igmpcf['address']);
1691
			foreach ($item as $iww) {
1692
				$igmpconf .= "altnet {$iww}\n";
1693
			}
1694
		}
1695
		$igmpconf .= "\n";
1696
	}
1697
	foreach ($iflist as $ifn) {
1698
		$realif = get_real_interface($ifn);
1699
		$igmpconf .= "phyint {$realif} disabled\n";
1700
	}
1701
	$igmpconf .= "\n";
1702

    
1703
	$igmpfl = fopen($g['varetc_path'] . "/igmpproxy.conf", "w");
1704
	if (!$igmpfl) {
1705
		log_error(gettext("Could not write Igmpproxy configuration file!"));
1706
		return;
1707
	}
1708
	fwrite($igmpfl, $igmpconf);
1709
	fclose($igmpfl);
1710
	unset($igmpconf);
1711

    
1712
	if (isset($config['syslog']['igmpxverbose'])) {
1713
		mwexec_bg("/usr/local/sbin/igmpproxy -v {$g['varetc_path']}/igmpproxy.conf");
1714
	} else {
1715
		mwexec_bg("/usr/local/sbin/igmpproxy {$g['varetc_path']}/igmpproxy.conf");
1716
	}
1717

    
1718
	log_error(gettext("Started IGMP proxy service."));
1719

    
1720
	return 0;
1721
}
1722

    
1723
function services_dhcrelay_configure() {
1724
	global $config, $g;
1725

    
1726
	if (isset($config['system']['developerspew'])) {
1727
		$mt = microtime();
1728
		echo "services_dhcrelay_configure() being called $mt\n";
1729
	}
1730

    
1731
	/* kill any running dhcrelay */
1732
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
1733

    
1734
	init_config_arr(array('dhcrelay'));
1735
	$dhcrelaycfg = &$config['dhcrelay'];
1736

    
1737
	/* DHCPRelay enabled on any interfaces? */
1738
	if (!isset($dhcrelaycfg['enable'])) {
1739
		return 0;
1740
	}
1741

    
1742
	if (platform_booting()) {
1743
		echo gettext("Starting DHCP relay service...");
1744
	} else {
1745
		sleep(1);
1746
	}
1747

    
1748
	$iflist = get_configured_interface_list();
1749

    
1750
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1751
	foreach ($dhcifaces as $dhcrelayif) {
1752
		if (!isset($iflist[$dhcrelayif]) ||
1753
		    link_interface_to_bridge($dhcrelayif)) {
1754
			continue;
1755
		}
1756

    
1757
		if (is_ipaddr(get_interface_ip($dhcrelayif))) {
1758
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1759
		}
1760
	}
1761

    
1762
	/*
1763
	 * In order for the relay to work, it needs to be active
1764
	 * on the interface in which the destination server sits.
1765
	 */
1766
	$srvips = explode(",", $dhcrelaycfg['server']);
1767
	if (!is_array($srvips)) {
1768
		log_error(gettext("No destination IP has been configured!"));
1769
		return;
1770
	}
1771

    
1772
	foreach ($srvips as $srcidx => $srvip) {
1773
		$destif = guess_interface_from_ip($srvip);
1774
		if (!empty($destif)) {
1775
			$dhcrelayifs[] = $destif;
1776
		}
1777
	}
1778
	$dhcrelayifs = array_unique($dhcrelayifs);
1779

    
1780
	/* fire up dhcrelay */
1781
	if (empty($dhcrelayifs)) {
1782
		log_error(gettext("No suitable interface found for running dhcrelay!"));
1783
		return; /* XXX */
1784
	}
1785

    
1786
	$cmd = "/usr/local/sbin/dhcrelay -i " . implode(" -i ", $dhcrelayifs);
1787

    
1788
	if (isset($dhcrelaycfg['agentoption'])) {
1789
		$cmd .= " -a -m replace";
1790
	}
1791

    
1792
	$cmd .= " " . implode(" ", $srvips);
1793
	mwexec($cmd);
1794
	unset($cmd);
1795

    
1796
	return 0;
1797
}
1798

    
1799
function services_dhcrelay6_configure() {
1800
	global $config, $g;
1801

    
1802
	if (isset($config['system']['developerspew'])) {
1803
		$mt = microtime();
1804
		echo "services_dhcrelay6_configure() being called $mt\n";
1805
	}
1806

    
1807
	/* kill any running dhcrelay */
1808
	killbypid("{$g['varrun_path']}/dhcrelay6.pid");
1809

    
1810
	init_config_arr(array('dhcrelay6'));
1811
	$dhcrelaycfg = &$config['dhcrelay6'];
1812

    
1813
	/* DHCPv6 Relay enabled on any interfaces? */
1814
	if (!isset($dhcrelaycfg['enable'])) {
1815
		return 0;
1816
	}
1817

    
1818
	if (platform_booting()) {
1819
		echo gettext("Starting DHCPv6 relay service...");
1820
	} else {
1821
		sleep(1);
1822
	}
1823

    
1824
	$iflist = get_configured_interface_list();
1825

    
1826
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1827
	foreach ($dhcifaces as $dhcrelayif) {
1828
		if (!isset($iflist[$dhcrelayif]) ||
1829
		    link_interface_to_bridge($dhcrelayif)) {
1830
			continue;
1831
		}
1832

    
1833
		if (is_ipaddrv6(get_interface_ipv6($dhcrelayif))) {
1834
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1835
		}
1836
	}
1837
	$dhcrelayifs = array_unique($dhcrelayifs);
1838

    
1839
	/*
1840
	 * In order for the relay to work, it needs to be active
1841
	 * on the interface in which the destination server sits.
1842
	 */
1843
	$srvips = explode(",", $dhcrelaycfg['server']);
1844
	$srvifaces = array();
1845
	foreach ($srvips as $srcidx => $srvip) {
1846
		$destif = guess_interface_from_ip($srvip);
1847
		if (!empty($destif)) {
1848
			$srvifaces[] = "{$srvip}%{$destif}";
1849
		}
1850
	}
1851

    
1852
	/* fire up dhcrelay */
1853
	if (empty($dhcrelayifs) || empty($srvifaces)) {
1854
		log_error(gettext("No suitable interface found for running dhcrelay -6!"));
1855
		return; /* XXX */
1856
	}
1857

    
1858
	$cmd = "/usr/local/sbin/dhcrelay -6 -pf \"{$g['varrun_path']}/dhcrelay6.pid\"";
1859
	foreach ($dhcrelayifs as $dhcrelayif) {
1860
		$cmd .= " -l {$dhcrelayif}";
1861
	}
1862
	foreach ($srvifaces as $srviface) {
1863
		$cmd .= " -u \"{$srviface}\"";
1864
	}
1865
	mwexec($cmd);
1866
	unset($cmd);
1867

    
1868
	return 0;
1869
}
1870

    
1871
function services_dyndns_configure_client($conf) {
1872

    
1873
	if (!isset($conf['enable'])) {
1874
		return;
1875
	}
1876

    
1877
	/* load up the dyndns.class */
1878
	require_once("dyndns.class");
1879

    
1880
	$dns = new updatedns($dnsService = $conf['type'],
1881
		$dnsHost = $conf['host'],
1882
		$dnsDomain = $conf['domainname'],
1883
		$dnsUser = $conf['username'],
1884
		$dnsPass = $conf['password'],
1885
		$dnsWildcard = $conf['wildcard'],
1886
		$dnsProxied = $conf['proxied'],
1887
		$dnsMX = $conf['mx'],
1888
		$dnsIf = "{$conf['interface']}",
1889
		$dnsBackMX = NULL,
1890
		$dnsServer = NULL,
1891
		$dnsPort = NULL,
1892
		$dnsUpdateURL = "{$conf['updateurl']}",
1893
		$forceUpdate = $conf['force'],
1894
		$dnsZoneID = $conf['zoneid'],
1895
		$dnsTTL = $conf['ttl'],
1896
		$dnsResultMatch = "{$conf['resultmatch']}",
1897
		$dnsRequestIf = "{$conf['requestif']}",
1898
		$dnsID = "{$conf['id']}",
1899
		$dnsVerboseLog = $conf['verboselog'],
1900
		$curlIpresolveV4 = $conf['curl_ipresolve_v4'],
1901
		$curlSslVerifypeer = $conf['curl_ssl_verifypeer']);
1902
}
1903

    
1904
function services_dyndns_configure($int = "") {
1905
	global $config, $g;
1906
	if (isset($config['system']['developerspew'])) {
1907
		$mt = microtime();
1908
		echo "services_dyndns_configure() being called $mt\n";
1909
	}
1910

    
1911
	$dyndnscfg = $config['dyndnses']['dyndns'];
1912
	$gwgroups = return_gateway_groups_array(true);
1913
	if (is_array($dyndnscfg)) {
1914
		if (platform_booting()) {
1915
			echo gettext("Starting DynDNS clients...");
1916
		}
1917

    
1918
		foreach ($dyndnscfg as $dyndns) {
1919
			/*
1920
			 * If it's using a gateway group, check if interface is
1921
			 * the active gateway for that group
1922
			 */
1923
			$group_int = '';
1924
			$friendly_group_int = '';
1925
			$gwgroup_member = false;
1926
			if (is_array($gwgroups[$dyndns['interface']])) {
1927
				if (!empty($gwgroups[$dyndns['interface']][0]['vip'])) {
1928
					$group_int = $gwgroups[$dyndns['interface']][0]['vip'];
1929
				} else {
1930
					$group_int = $gwgroups[$dyndns['interface']][0]['int'];
1931
					$friendly_group_int =
1932
					    convert_real_interface_to_friendly_interface_name(
1933
						$group_int);
1934
					if (!empty($int)) {
1935
						$gwgroup_member =
1936
						    interface_gateway_group_member(get_real_interface($int),
1937
						    $dyndns['interface']);
1938
					}
1939
				}
1940
			}
1941
			if ((empty($int)) || ($int == $dyndns['interface']) || $gwgroup_member ||
1942
			    ($int == $group_int) || ($int == $friendly_group_int)) {
1943
				$dyndns['verboselog'] = isset($dyndns['verboselog']);
1944
				$dyndns['curl_ipresolve_v4'] = isset($dyndns['curl_ipresolve_v4']);
1945
				$dyndns['curl_ssl_verifypeer'] = isset($dyndns['curl_ssl_verifypeer']);
1946
				services_dyndns_configure_client($dyndns);
1947
				sleep(1);
1948
			}
1949
		}
1950

    
1951
		if (platform_booting()) {
1952
			echo gettext("done.") . "\n";
1953
		}
1954
	}
1955

    
1956
	return 0;
1957
}
1958

    
1959
function dyndnsCheckIP($int) {
1960
	global $config, $factory_default_checkipservice;
1961
	$ip_address = get_interface_ip($int);
1962
	if (is_private_ip($ip_address)) {
1963
		$gateways_status = return_gateways_status(true);
1964
		// If the gateway for this interface is down, then the external check cannot work.
1965
		// Avoid the long wait for the external check to timeout.
1966
		if (stristr($gateways_status[$config['interfaces'][$int]['gateway']]['status'], "down")) {
1967
			return "down";
1968
		}
1969

    
1970
		// Append the factory default check IP service to the list (if not disabled).
1971
		if (!isset($config['checkipservices']['disable_factory_default'])) {
1972
			if (!is_array($config['checkipservices'])) {
1973
				$config['checkipservices'] = array();
1974
			}
1975
			if (!is_array($config['checkipservices']['checkipservice'])) {
1976
				$config['checkipservices']['checkipservice'] = array();
1977
			}
1978
			$config['checkipservices']['checkipservice'][] = $factory_default_checkipservice;
1979
		}
1980

    
1981
		// Use the first enabled check IP service as the default.
1982
		if (is_array($config['checkipservices']['checkipservice'])) {
1983
			foreach ($config['checkipservices']['checkipservice'] as $i => $checkipservice) {
1984
				if (isset($checkipservice['enable'])) {
1985
					$url = $checkipservice['url'];
1986
					$username = $checkipservice['username'];
1987
					$password = $checkipservice['password'];
1988
					$verifysslpeer = isset($checkipservice['verifysslpeer']);
1989
					break;
1990
				}
1991
			}
1992
		}
1993

    
1994
		$hosttocheck = $url;
1995
		$ip_ch = curl_init($hosttocheck);
1996
		curl_setopt($ip_ch, CURLOPT_RETURNTRANSFER, 1);
1997
		curl_setopt($ip_ch, CURLOPT_SSL_VERIFYPEER, $verifysslpeer);
1998
		curl_setopt($ip_ch, CURLOPT_INTERFACE, 'host!' . $ip_address);
1999
		curl_setopt($ip_ch, CURLOPT_CONNECTTIMEOUT, '30');
2000
		curl_setopt($ip_ch, CURLOPT_TIMEOUT, 120);
2001
		curl_setopt($ip_ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
2002
		curl_setopt($ip_ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
2003
		curl_setopt($ip_ch, CURLOPT_USERPWD, "{$username}:{$password}");
2004
		$ip_result_page = curl_exec($ip_ch);
2005
		curl_close($ip_ch);
2006
		$ip_result_decoded = urldecode($ip_result_page);
2007
		preg_match('=Current IP Address: (.*)</body>=siU', $ip_result_decoded, $matches);
2008
		$ip_address = trim($matches[1]);
2009
	}
2010
	return $ip_address;
2011
}
2012

    
2013
function services_dnsmasq_configure($restart_dhcp = true) {
2014
	global $config, $g;
2015
	$return = 0;
2016

    
2017
	// hard coded args: will be removed to avoid duplication if specified in custom_options
2018
	$standard_args = array(
2019
		"dns-forward-max" => "--dns-forward-max=5000",
2020
		"cache-size" => "--cache-size=10000",
2021
		"local-ttl" => "--local-ttl=1"
2022
	);
2023

    
2024

    
2025
	if (isset($config['system']['developerspew'])) {
2026
		$mt = microtime();
2027
		echo "services_dnsmasq_configure() being called $mt\n";
2028
	}
2029

    
2030
	/* kill any running dnsmasq */
2031
	if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) {
2032
		sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
2033
	}
2034

    
2035
	if (isset($config['dnsmasq']['enable'])) {
2036

    
2037
		if (platform_booting()) {
2038
			echo gettext("Starting DNS forwarder...");
2039
		} else {
2040
			sleep(1);
2041
		}
2042

    
2043
		/* generate hosts file */
2044
		if (system_hosts_generate() != 0) {
2045
			$return = 1;
2046
		}
2047

    
2048
		$args = "";
2049

    
2050
		if (isset($config['dnsmasq']['regdhcp'])) {
2051
			$args .= " --dhcp-hostsfile={$g['etc_path']}/hosts ";
2052
		}
2053

    
2054
		/* Setup listen port, if non-default */
2055
		if (is_port($config['dnsmasq']['port'])) {
2056
			$args .= " --port={$config['dnsmasq']['port']} ";
2057
		}
2058

    
2059
		$listen_addresses = "";
2060
		if (isset($config['dnsmasq']['interface'])) {
2061
			$interfaces = explode(",", $config['dnsmasq']['interface']);
2062
			foreach ($interfaces as $interface) {
2063
				$if = get_real_interface($interface);
2064
				if (does_interface_exist($if)) {
2065
					$laddr = get_interface_ip($interface);
2066
					if (is_ipaddrv4($laddr)) {
2067
						$listen_addresses .= " --listen-address={$laddr} ";
2068
					}
2069
					$laddr6 = get_interface_ipv6($interface);
2070
					if (is_ipaddrv6($laddr6) && !isset($config['dnsmasq']['strictbind'])) {
2071
						/*
2072
						 * XXX: Since dnsmasq does not support link-local address
2073
						 * with scope specified. These checks are being done.
2074
						 */
2075
						if (is_linklocal($laddr6) && strstr($laddr6, "%")) {
2076
							$tmpaddrll6 = explode("%", $laddr6);
2077
							$listen_addresses .= " --listen-address={$tmpaddrll6[0]} ";
2078
						} else {
2079
							$listen_addresses .= " --listen-address={$laddr6} ";
2080
						}
2081
					}
2082
				}
2083
			}
2084
			if (!empty($listen_addresses)) {
2085
				$args .= " {$listen_addresses} ";
2086
				if (isset($config['dnsmasq']['strictbind'])) {
2087
					$args .= " --bind-interfaces ";
2088
				}
2089
			}
2090
		}
2091

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

    
2099
			// Build an array of domain overrides to help in checking for matches.
2100
			$override_a = array();
2101
			if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2102
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2103
					$override_a[$override['domain']] = "y";
2104
				}
2105
			}
2106

    
2107
			// Build an array of the private reverse lookup domain names
2108
			$reverse_domain_a = array("10.in-addr.arpa", "168.192.in-addr.arpa");
2109
			// Unfortunately the 172.16.0.0/12 range does not map nicely to the in-addr.arpa scheme.
2110
			for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) {
2111
				$reverse_domain_a[] = "$subnet_num.172.in-addr.arpa";
2112
			}
2113

    
2114
			// Set the --server parameter to nowhere for each reverse domain name that was not specifically specified in a domain override.
2115
			foreach ($reverse_domain_a as $reverse_domain) {
2116
				if (!isset($override_a[$reverse_domain])) {
2117
					$args .= " --server=/$reverse_domain/ ";
2118
				}
2119
			}
2120
			unset($override_a);
2121
			unset($reverse_domain_a);
2122
		}
2123

    
2124
		/* Setup forwarded domains */
2125
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2126
			foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2127
				if ($override['ip'] == "!") {
2128
					$override[ip] = "";
2129
				}
2130
				$args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
2131
			}
2132
		}
2133

    
2134
		/* Allow DNS Rebind for forwarded domains */
2135
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2136
			if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2137
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2138
					$args .= ' --rebind-domain-ok=/' . $override['domain'] . '/ ';
2139
				}
2140
			}
2141
		}
2142

    
2143
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2144
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2145
		}
2146

    
2147
		if (isset($config['dnsmasq']['strict_order'])) {
2148
			$args .= " --strict-order ";
2149
		}
2150

    
2151
		if (isset($config['dnsmasq']['domain_needed'])) {
2152
			$args .= " --domain-needed ";
2153
		}
2154

    
2155
		if ($config['dnsmasq']['custom_options']) {
2156
			foreach (preg_split('/\s+/', $config['dnsmasq']['custom_options']) as $c) {
2157
				$args .= " " . escapeshellarg("--{$c}");
2158
				$p = explode('=', $c);
2159
				if (array_key_exists($p[0], $standard_args)) {
2160
					unset($standard_args[$p[0]]);
2161
				}
2162
			}
2163
		}
2164
		$args .= ' ' . implode(' ', array_values($standard_args));
2165

    
2166
		/* run dnsmasq. Use "-C /dev/null" since we use command line args only (Issue #6730) */
2167
		$cmd = "/usr/local/sbin/dnsmasq --all-servers -C /dev/null {$dns_rebind} {$args}";
2168
		//log_error("dnsmasq command: {$cmd}");
2169
		mwexec_bg($cmd);
2170
		unset($args);
2171

    
2172
		system_dhcpleases_configure();
2173

    
2174
		if (platform_booting()) {
2175
			echo gettext("done.") . "\n";
2176
		}
2177
	}
2178

    
2179
	if (!platform_booting() && $restart_dhcp) {
2180
		if (services_dhcpd_configure() != 0) {
2181
			$return = 1;
2182
		}
2183
	}
2184

    
2185
	return $return;
2186
}
2187

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

    
2192
	if (isset($config['system']['developerspew'])) {
2193
		$mt = microtime();
2194
		echo "services_unbound_configure() being called $mt\n";
2195
	}
2196

    
2197
	if (isset($config['unbound']['enable'])) {
2198
		require_once('/etc/inc/unbound.inc');
2199

    
2200
		/* Stop Unbound using TERM */
2201
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2202
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
2203
		}
2204

    
2205
		/* If unbound is still running, wait up to 30 seconds for it to terminate. */
2206
		for ($i=1; $i <= 30; $i++) {
2207
			if (is_process_running('unbound')) {
2208
				sleep(1);
2209
			}
2210
		}
2211

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

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

    
2223
		/* Check here for dhcp6 complete - wait upto 10 seconds */
2224
		if($config['interfaces']["wan"]['ipaddrv6'] == 'dhcp6') {
2225
			$wanif = get_real_interface("wan", "inet6");
2226
			if (platform_booting()) {
2227
				for ($i=1; $i <= 10; $i++) {
2228
					if (!file_exists("/tmp/{$wanif}_dhcp6_complete")) {
2229
						log_error(gettext("Unbound start waiting on dhcp6c."));
2230
						sleep(1);
2231
					} else {
2232
						unlink_if_exists("/tmp/{$wanif}_dhcp6_complete");
2233
						log_error(gettext("dhcp6 init complete. Continuing"));
2234
						break;
2235
					}
2236
				}
2237
			}
2238
		}
2239

    
2240
		sync_unbound_service();
2241
		if (platform_booting()) {
2242
			log_error(gettext("sync unbound done."));
2243
			echo gettext("done.") . "\n";
2244
		}
2245

    
2246
		system_dhcpleases_configure();
2247
	} else {
2248
		/* kill Unbound since it should not be enabled */
2249
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2250
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "KILL");
2251
		}
2252
	}
2253

    
2254
	if (!platform_booting() && $restart_dhcp) {
2255
		if (services_dhcpd_configure() != 0) {
2256
			$return = 1;
2257
		}
2258
	}
2259

    
2260
	return $return;
2261
}
2262

    
2263
function services_snmpd_configure() {
2264
	global $config, $g;
2265
	if (isset($config['system']['developerspew'])) {
2266
		$mt = microtime();
2267
		echo "services_snmpd_configure() being called $mt\n";
2268
	}
2269

    
2270
	/* kill any running snmpd */
2271
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
2272
	sleep(2);
2273
	if (is_process_running("bsnmpd")) {
2274
		mwexec("/usr/bin/killall bsnmpd", true);
2275
	}
2276

    
2277
	if (isset($config['snmpd']['enable'])) {
2278

    
2279
		if (platform_booting()) {
2280
			echo gettext("Starting SNMP daemon... ");
2281
		}
2282

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

    
2288
		/* generate snmpd.conf */
2289
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
2290
		if (!$fd) {
2291
			printf(gettext("Error: cannot open snmpd.conf in services_snmpd_configure().%s"), "\n");
2292
			return 1;
2293
		}
2294

    
2295

    
2296
		$snmpdconf = <<<EOD
2297
location := "{$config['snmpd']['syslocation']}"
2298
contact := "{$config['snmpd']['syscontact']}"
2299
read := "{$config['snmpd']['rocommunity']}"
2300

    
2301
EOD;
2302

    
2303
/* No docs on what write strings do there so disable for now.
2304
		if (isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])) {
2305
			$snmpdconf .= <<<EOD
2306
# write string
2307
write := "{$config['snmpd']['rwcommunity']}"
2308

    
2309
EOD;
2310
		}
2311
*/
2312

    
2313

    
2314
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2315
			$snmpdconf .= <<<EOD
2316
# SNMP Trap support.
2317
traphost := {$config['snmpd']['trapserver']}
2318
trapport := {$config['snmpd']['trapserverport']}
2319
trap := "{$config['snmpd']['trapstring']}"
2320

    
2321

    
2322
EOD;
2323
		}
2324

    
2325
		$sysDescr = "{$g['product_name']} " . php_uname("n") .
2326
			" {$g['product_version']} {$g['platform']} " . php_uname("s") .
2327
			" " . php_uname("r") . " " . php_uname("m");
2328

    
2329
		$snmpdconf .= <<<EOD
2330
system := 1     # pfSense
2331
%snmpd
2332
sysDescr			= "{$sysDescr}"
2333
begemotSnmpdDebugDumpPdus       = 2
2334
begemotSnmpdDebugSyslogPri      = 7
2335
begemotSnmpdCommunityString.0.1 = $(read)
2336

    
2337
EOD;
2338

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

    
2344
EOD;
2345
		}
2346
*/
2347

    
2348

    
2349
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2350
			$snmpdconf .= <<<EOD
2351
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
2352
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
2353
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
2354

    
2355
EOD;
2356
		}
2357

    
2358

    
2359
		$snmpdconf .= <<<EOD
2360
begemotSnmpdCommunityDisable    = 1
2361

    
2362
EOD;
2363

    
2364
		$bind_to_ips = array();
2365
		if (isset($config['snmpd']['bindip'])) {
2366
			foreach (explode(",", $config['snmpd']['bindip']) as $bind_to_ip) {
2367
				if (is_ipaddr($bind_to_ip)) {
2368
					$bind_to_ips[] = $bind_to_ip;
2369
				} else {
2370
					$if = get_real_interface($bind_to_ip);
2371
					if (does_interface_exist($if)) {
2372
						$bindip = get_interface_ip($bind_to_ip);
2373
						if (is_ipaddr($bindip)) {
2374
							$bind_to_ips[] = $bindip;
2375
						}
2376
					}
2377
				}
2378
			}
2379
		}
2380
		if (!count($bind_to_ips)) {
2381
			$bind_to_ips = array("0.0.0.0");
2382
		}
2383

    
2384
		if (is_port($config['snmpd']['pollport'])) {
2385
			foreach ($bind_to_ips as $bind_to_ip) {
2386
				$snmpdconf .= <<<EOD
2387
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
2388

    
2389
EOD;
2390

    
2391
			}
2392
		}
2393

    
2394
		$snmpdconf .= <<<EOD
2395
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
2396
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
2397

    
2398
# These are bsnmp macros not php vars.
2399
sysContact      = $(contact)
2400
sysLocation     = $(location)
2401
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
2402

    
2403
snmpEnableAuthenTraps = 2
2404

    
2405
EOD;
2406

    
2407
		if (is_array($config['snmpd']['modules'])) {
2408
			if (isset($config['snmpd']['modules']['mibii'])) {
2409
			$snmpdconf .= <<<EOD
2410
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
2411

    
2412
EOD;
2413
			}
2414

    
2415
			if (isset($config['snmpd']['modules']['netgraph'])) {
2416
				$snmpdconf .= <<<EOD
2417
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
2418
%netgraph
2419
begemotNgControlNodeName = "snmpd"
2420

    
2421
EOD;
2422
			}
2423

    
2424
			if (isset($config['snmpd']['modules']['pf'])) {
2425
				$snmpdconf .= <<<EOD
2426
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
2427

    
2428
EOD;
2429
			}
2430

    
2431
			if (isset($config['snmpd']['modules']['hostres'])) {
2432
				$snmpdconf .= <<<EOD
2433
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
2434

    
2435
EOD;
2436
			}
2437

    
2438
			if (isset($config['snmpd']['modules']['bridge'])) {
2439
				$snmpdconf .= <<<EOD
2440
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
2441
# config must end with blank line
2442

    
2443
EOD;
2444
			}
2445
			if (isset($config['snmpd']['modules']['ucd'])) {
2446
				$snmpdconf .= <<<EOD
2447
begemotSnmpdModulePath."ucd"     = "/usr/local/lib/snmp_ucd.so"
2448

    
2449
EOD;
2450
			}
2451
			if (isset($config['snmpd']['modules']['regex'])) {
2452
				$snmpdconf .= <<<EOD
2453
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"
2454

    
2455
EOD;
2456
			}
2457
		}
2458

    
2459
		fwrite($fd, $snmpdconf);
2460
		fclose($fd);
2461
		unset($snmpdconf);
2462

    
2463
		/* run bsnmpd */
2464
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
2465
			" -p {$g['varrun_path']}/snmpd.pid");
2466

    
2467
		if (platform_booting()) {
2468
			echo gettext("done.") . "\n";
2469
		}
2470
	}
2471

    
2472
	return 0;
2473
}
2474

    
2475
function services_dnsupdate_process($int = "", $updatehost = "", $forced = false) {
2476
	global $config, $g;
2477
	if (isset($config['system']['developerspew'])) {
2478
		$mt = microtime();
2479
		echo "services_dnsupdate_process() being called $mt\n";
2480
	}
2481

    
2482
	/* Dynamic DNS updating active? */
2483
	if (!is_array($config['dnsupdates']['dnsupdate'])) {
2484
		return 0;
2485
	}
2486

    
2487
	$notify_text = "";
2488
	$gwgroups = return_gateway_groups_array(true);
2489
	foreach ($config['dnsupdates']['dnsupdate'] as $i => $dnsupdate) {
2490
		if (!isset($dnsupdate['enable'])) {
2491
			continue;
2492
		}
2493
		/*
2494
		 * If it's using a gateway group, check if interface is
2495
		 * the active gateway for that group
2496
		 */
2497
		$group_int = '';
2498
		$friendly_group_int = '';
2499
		$gwgroup_member = false;
2500
		if (is_array($gwgroups[$dnsupdate['interface']])) {
2501
			if (!empty($gwgroups[$dnsupdate['interface']][0]['vip'])) {
2502
				$group_int = $gwgroups[$dnsupdate['interface']][0]['vip'];
2503
			} else {
2504
				$group_int = $gwgroups[$dnsupdate['interface']][0]['int'];
2505
				$friendly_group_int =
2506
				    convert_real_interface_to_friendly_interface_name(
2507
					$group_int);
2508
				if (!empty($int)) {
2509
					$gwgroup_member =
2510
					    interface_gateway_group_member(get_real_interface($int),
2511
					    $dnsupdate['interface']);
2512
				}
2513
			}
2514
		}
2515
		if (!empty($int) && ($int != $dnsupdate['interface']) && !$gwgroup_member &&
2516
		    ($int != $group_int) && ($int != $friendly_group_int)) {
2517
			continue;
2518
		}
2519
		if (!empty($updatehost) && ($updatehost != $dnsupdate['host'])) {
2520
			continue;
2521
		}
2522

    
2523
		/* determine interface name */
2524
		$if = get_failover_interface($dnsupdate['interface']);
2525

    
2526
		/* Determine address to update and default binding address */
2527
		if (isset($dnsupdate['usepublicip'])) {
2528
			$wanip = dyndnsCheckIP($if);
2529
			$bindipv4 = get_interface_ip($if);
2530
		} else {
2531
			$wanip = get_interface_ip($if);
2532
			$bindipv4 = $wanip;
2533
		}
2534
		$wanipv6 = get_interface_ipv6($if);
2535
		$bindipv6 = $wanipv6;
2536

    
2537
		/* Handle non-default interface bindings */
2538
		if ($dnsupdate['updatesource'] == "none") {
2539
			/* When empty, the directive will be omitted. */
2540
			$bindipv4 = "";
2541
			$bindipv6 = "";
2542
		} elseif (!empty($dnsupdate['updatesource'])) {
2543
			/* Find the alternate binding address */
2544
			$bindipv4 = get_interface_ip($dnsupdate['updatesource']);
2545
			$bindipv6 = get_interface_ipv6($dnsupdate['updatesource']);
2546
		}
2547

    
2548
		/* Handle IPv4/IPv6 selection for the update source interface/VIP */
2549
		switch ($dnsupdate['updatesourcefamily']) {
2550
			case "inet":
2551
				$bindip = $bindipv4;
2552
				break;
2553
			case "inet6":
2554
				$bindip = $bindipv6;
2555
				break;
2556
			case "":
2557
			default:
2558
				/* Try IPv4 first, if that is empty, try IPv6. */
2559
				/* Only specify the address if it's present, otherwise omit. */
2560
				if (!empty($bindipv4)) {
2561
					$bindip = $bindipv4;
2562
				} elseif (!empty($bindipv6)) {
2563
					$bindip = $bindipv6;
2564
				}
2565
				break;
2566
		}
2567

    
2568
		$cacheFile = $g['conf_path'] .
2569
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2570
		    escapeshellarg($dnsupdate['host']) .
2571
		    "_{$dnsupdate['server']}.cache";
2572
		$cacheFilev6 = $g['conf_path'] .
2573
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2574
		    escapeshellarg($dnsupdate['host']) .
2575
		    "_{$dnsupdate['server']}_v6.cache";
2576
		$currentTime = time();
2577

    
2578
		if (!$wanip && !$wanipv6) {
2579
			continue;
2580
		}
2581

    
2582
		$keyname = $dnsupdate['keyname'];
2583
		/* trailing dot */
2584
		if (substr($keyname, -1) != ".") {
2585
			$keyname .= ".";
2586
		}
2587

    
2588
		$hostname = $dnsupdate['host'];
2589
		/* trailing dot */
2590
		if (substr($hostname, -1) != ".") {
2591
			$hostname .= ".";
2592
		}
2593

    
2594
		/* write key file */
2595
		$algorithm = empty($dnsupdate['keyalgorithm']) ? 'hmac-md5' : $dnsupdate['keyalgorithm'];
2596
		$upkey = <<<EOD
2597
key "{$keyname}" {
2598
	algorithm {$algorithm};
2599
	secret "{$dnsupdate['keydata']}";
2600
};
2601

    
2602
EOD;
2603
		@file_put_contents("{$g['varetc_path']}/nsupdatekey{$i}", $upkey);
2604

    
2605
		/* generate update instructions */
2606
		$upinst = "";
2607
		if (!empty($dnsupdate['server'])) {
2608
			$upinst .= "server {$dnsupdate['server']}\n";
2609
		}
2610

    
2611
		$cachedipv4 = '';
2612
		$cacheTimev4 = 0;
2613
		if (file_exists($cacheFile)) {
2614
			list($cachedipv4, $cacheTimev4) = explode("|",
2615
			    file_get_contents($cacheFile));
2616
		}
2617
		$cachedipv6 = '';
2618
		$cacheTimev6 = 0;
2619
		if (file_exists($cacheFilev6)) {
2620
			list($cachedipv6, $cacheTimev6) = explode("|",
2621
			    file_get_contents($cacheFilev6));
2622
		}
2623

    
2624
		// 25 Days
2625
		$maxCacheAgeSecs = 25 * 24 * 60 * 60;
2626
		$need_update = false;
2627

    
2628
		/* Update IPv4 if we have it. */
2629
		if (is_ipaddrv4($wanip) && $dnsupdate['recordtype'] != "AAAA") {
2630
			if (($wanip != $cachedipv4) || $forced ||
2631
			    (($currentTime - $cacheTimev4) > $maxCacheAgeSecs)) {
2632
				$upinst .= "update delete " .
2633
				    "{$dnsupdate['host']}. A\n";
2634
				$upinst .= "update add {$dnsupdate['host']}. " .
2635
				    "{$dnsupdate['ttl']} A {$wanip}\n";
2636
				if (!empty($bindip)) {
2637
					$upinst .= "local {$bindip}\n";
2638
				}
2639
				$need_update = true;
2640
			} else {
2641
				log_error(sprintf(gettext(
2642
				    "phpDynDNS: Not updating %s A record because the IP address has not changed."),
2643
				    $dnsupdate['host']));
2644
			}
2645
		} else {
2646
			@unlink($cacheFile);
2647
			unset($cacheFile);
2648
		}
2649

    
2650
		/* Update IPv6 if we have it. */
2651
		if (is_ipaddrv6($wanipv6) && $dnsupdate['recordtype'] != "A") {
2652
			if (($wanipv6 != $cachedipv6) || $forced ||
2653
			    (($currentTime - $cacheTimev6) > $maxCacheAgeSecs)) {
2654
				$upinst .= "update delete " .
2655
				    "{$dnsupdate['host']}. AAAA\n";
2656
				$upinst .= "update add {$dnsupdate['host']}. " .
2657
				    "{$dnsupdate['ttl']} AAAA {$wanipv6}\n";
2658
				$need_update = true;
2659
			} else {
2660
				log_error(sprintf(gettext(
2661
				    "phpDynDNS: Not updating %s AAAA record because the IPv6 address has not changed."),
2662
				    $dnsupdate['host']));
2663
			}
2664
		} else {
2665
			@unlink($cacheFilev6);
2666
			unset($cacheFilev6);
2667
		}
2668

    
2669
		$upinst .= "\n";	/* mind that trailing newline! */
2670

    
2671
		if (!$need_update) {
2672
			continue;
2673
		}
2674

    
2675
		@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}", $upinst);
2676
		unset($upinst);
2677
		/* invoke nsupdate */
2678
		$cmd = "/usr/local/bin/nsupdate -k {$g['varetc_path']}/nsupdatekey{$i}";
2679

    
2680
		if (isset($dnsupdate['usetcp'])) {
2681
			$cmd .= " -v";
2682
		}
2683

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

    
2686
		if (mwexec($cmd) == 0) {
2687
			if (!empty($cacheFile)) {
2688
				@file_put_contents($cacheFile,
2689
				    "{$wanip}|{$currentTime}");
2690
				log_error(sprintf(gettext(
2691
				    'phpDynDNS: updating cache file %1$s: %2$s'),
2692
				    $cacheFile, $wanip));
2693
				$notify_text .= sprintf(gettext(
2694
				    'DynDNS updated IP Address (A) for %1$s on %2$s (%3$s) to %4$s'),
2695
				    $dnsupdate['host'],
2696
				    convert_real_interface_to_friendly_descr($if),
2697
				    $if, $wanip) . "\n";
2698
			}
2699
			if (!empty($cacheFilev6)) {
2700
				@file_put_contents($cacheFilev6,
2701
				    "{$wanipv6}|{$currentTime}");
2702
				log_error(sprintf(gettext(
2703
				    'phpDynDNS: updating cache file %1$s: %2$s'),
2704
				    $cacheFilev6, $wanipv6));
2705
				$notify_text .= sprintf(gettext(
2706
				    'DynDNS updated IPv6 Address (AAAA) for %1$s on %2$s (%3$s) to %4$s'),
2707
				    $dnsupdate['host'],
2708
				    convert_real_interface_to_friendly_descr($if),
2709
				    $if, $wanipv6) . "\n";
2710
			}
2711
		} else {
2712
			if (!empty($cacheFile)) {
2713
				log_error(sprintf(gettext(
2714
				    'phpDynDNS: ERROR while updating IP Address (A) for %1$s (%2$s)'),
2715
				    $dnsupdate['host'], $wanip));
2716
			}
2717
			if (!empty($cacheFilev6)) {
2718
				log_error(sprintf(gettext(
2719
				    'phpDynDNS: ERROR while updating IP Address (AAAA) for %1$s (%2$s)'),
2720
				    $dnsupdate['host'], $wanipv6));
2721
			}
2722
		}
2723
		unset($cmd);
2724
	}
2725

    
2726
	if (!empty($notify_text)) {
2727
		notify_all_remote($notify_text);
2728
	}
2729

    
2730
	return 0;
2731
}
2732

    
2733
/* configure cron service */
2734
function configure_cron() {
2735
	global $g, $config;
2736

    
2737
	/* preserve existing crontab entries */
2738
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2739

    
2740
	for ($i = 0; $i < count($crontab_contents); $i++) {
2741
		$cron_item = &$crontab_contents[$i];
2742
		if (strpos($cron_item, "# pfSense specific crontab entries") !== false) {
2743
			array_splice($crontab_contents, $i - 1);
2744
			break;
2745
		}
2746
	}
2747
	$crontab_contents = implode("\n", $crontab_contents) . "\n";
2748

    
2749

    
2750
	if (is_array($config['cron']['item'])) {
2751
		$crontab_contents .= "#\n";
2752
		$crontab_contents .= "# pfSense specific crontab entries\n";
2753
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
2754
		$crontab_contents .= "#\n";
2755

    
2756
		if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) {
2757
			$http_proxy = $config['system']['proxyurl'];
2758
			if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) {
2759
				$http_proxy .= ':' . $config['system']['proxyport'];
2760
			}
2761
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
2762

    
2763
			if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
2764
				$crontab_contents .= "HTTP_PROXY_AUTH=basic:*:{$config['system']['proxyuser']}:{$config['system']['proxypass']}";
2765
			}
2766
		}
2767

    
2768
		foreach ($config['cron']['item'] as $item) {
2769
			$crontab_contents .= "\n{$item['minute']}\t";
2770
			$crontab_contents .= "{$item['hour']}\t";
2771
			$crontab_contents .= "{$item['mday']}\t";
2772
			$crontab_contents .= "{$item['month']}\t";
2773
			$crontab_contents .= "{$item['wday']}\t";
2774
			$crontab_contents .= "{$item['who']}\t";
2775
			$crontab_contents .= "{$item['command']}";
2776
		}
2777

    
2778
		$crontab_contents .= "\n#\n";
2779
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
2780
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
2781
		$crontab_contents .= "#\n\n";
2782
	}
2783

    
2784
	/* please maintain the newline at the end of file */
2785
	file_put_contents("/etc/crontab", $crontab_contents);
2786
	unset($crontab_contents);
2787

    
2788
	/* make sure that cron is running and start it if it got killed somehow */
2789
	if (!is_process_running("cron")) {
2790
		exec("cd /tmp && /usr/sbin/cron -s 2>/dev/null");
2791
	} else {
2792
	/* do a HUP kill to force sync changes */
2793
		sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP");
2794
	}
2795

    
2796
}
2797

    
2798
function upnp_action ($action) {
2799
	global $g, $config;
2800
	switch ($action) {
2801
		case "start":
2802
			if (file_exists('/var/etc/miniupnpd.conf')) {
2803
				@unlink("{$g['varrun_path']}/miniupnpd.pid");
2804
				mwexec_bg("/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf -P {$g['varrun_path']}/miniupnpd.pid");
2805
			}
2806
			break;
2807
		case "stop":
2808
			killbypid("{$g['varrun_path']}/miniupnpd.pid");
2809
			while ((int)exec("/bin/pgrep -a miniupnpd | wc -l") > 0) {
2810
				mwexec('/usr/bin/killall miniupnpd 2>/dev/null', true);
2811
			}
2812
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
2813
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
2814
			break;
2815
		case "restart":
2816
			upnp_action('stop');
2817
			upnp_action('start');
2818
			break;
2819
	}
2820
}
2821

    
2822
function upnp_start() {
2823
	global $config;
2824

    
2825
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
2826
		return;
2827
	}
2828

    
2829
	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
2830
		echo gettext("Starting UPnP service... ");
2831
		require_once('/usr/local/pkg/miniupnpd.inc');
2832
		sync_package_miniupnpd();
2833
		echo "done.\n";
2834
	}
2835
}
2836

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

    
2840
	$is_installed = false;
2841
	$cron_changed = true;
2842
	$change_message = "";
2843

    
2844
	if (!is_array($config['cron'])) {
2845
		$config['cron'] = array();
2846
	}
2847
	if (!is_array($config['cron']['item'])) {
2848
		$config['cron']['item'] = array();
2849
	}
2850

    
2851
	$x = 0;
2852
	foreach ($config['cron']['item'] as $item) {
2853
		if (strstr($item['command'], $command)) {
2854
			$is_installed = true;
2855
			break;
2856
		}
2857
		$x++;
2858
	}
2859

    
2860
	if ($active) {
2861
		$cron_item = array();
2862
		$cron_item['minute'] = $minute;
2863
		$cron_item['hour'] = $hour;
2864
		$cron_item['mday'] = $monthday;
2865
		$cron_item['month'] = $month;
2866
		$cron_item['wday'] = $weekday;
2867
		$cron_item['who'] = $who;
2868
		$cron_item['command'] = $command;
2869
		if (!$is_installed) {
2870
			$config['cron']['item'][] = $cron_item;
2871
			$change_message = "Installed cron job for %s";
2872
		} else {
2873
			if ($config['cron']['item'][$x] == $cron_item) {
2874
				$cron_changed = false;
2875
			} else {
2876
				$config['cron']['item'][$x] = $cron_item;
2877
				$change_message = "Updated cron job for %s";
2878
			}
2879
		}
2880
	} else {
2881
		if ($is_installed == true) {
2882
			array_splice($config['cron']['item'], $x, 1);
2883
			$change_message = "Removed cron job for %s";
2884
		} else {
2885
			$cron_changed = false;
2886
		}
2887
	}
2888

    
2889
	if ($cron_changed) {
2890
		/* Optionally write the configuration if this function made changes.
2891
		 * Performing a write_config() in this way can have unintended side effects. See #7146
2892
		 * Base system instances of this function do not need to write, packages may.
2893
		 */
2894
		if ($write_config) {
2895
			write_config(sprintf(gettext($change_message), $command));
2896
		}
2897
		configure_cron();
2898
	}
2899
}
2900

    
2901
?>
(46-46/60)