Project

General

Profile

Download (90.1 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * services.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2004-2016 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
define('DYNDNS_PROVIDER_VALUES', 'all-inkl citynetwork cloudflare cloudflare-v6 cloudns custom custom-v6 dnsexit dnsimple dnsmadeeasy dnsomatic dreamhost dreamhost-v6 duiadns duiadns-v6 dyndns dyndns-custom dyndns-static dyns easydns eurodns freedns freedns-v6 glesys googledomains gratisdns he-net he-net-v6 he-net-tunnelbroker hover loopia namecheap noip noip-free ods opendns ovh-dynhost route53 selfhost spdyn spdyn-v6 zoneedit');
27
define('DYNDNS_PROVIDER_DESCRIPTIONS', 'All-Inkl.com,City Network,CloudFlare,CloudFlare (v6),ClouDNS,Custom,Custom (v6),DNSexit,DNSimple,DNS Made Easy,DNS-O-Matic,DreamHost,Dreamhost (v6),DuiaDns.net,DuiaDns.net (v6),DynDNS (dynamic),DynDNS (custom),DynDNS (static),DyNS,easyDNS,Euro Dns,freeDNS,freeDNS (v6),GleSYS,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,SelfHost,SPDYN,SPDYN (v6),ZoneEdit');
28

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
237
		/* add DNS servers */
238
		$dnslist = array();
239
		if (isset($dhcpv6ifconf['rasamednsasdhcp6']) && is_array($dhcpv6ifconf['dnsserver']) && !empty($dhcpv6ifconf['dnsserver'])) {
240
			foreach ($dhcpv6ifconf['dnsserver'] as $server) {
241
				if (is_ipaddrv6($server)) {
242
					$dnslist[] = $server;
243
				}
244
			}
245
		} elseif (!isset($dhcpv6ifconf['rasamednsasdhcp6']) && isset($dhcpv6ifconf['radnsserver']) && is_array($dhcpv6ifconf['radnsserver'])) {
246
			foreach ($dhcpv6ifconf['radnsserver'] as $server) {
247
				if (is_ipaddrv6($server)) {
248
					$dnslist[] = $server;
249
				}
250
			}
251
		} elseif (isset($config['dnsmasq']['enable']) || isset($config['unbound']['enable'])) {
252
			$dnslist[] = get_interface_ipv6($realif);
253
		} elseif (is_array($config['system']['dnsserver']) && !empty($config['system']['dnsserver'])) {
254
			foreach ($config['system']['dnsserver'] as $server) {
255
				if (is_ipaddrv6($server)) {
256
					$dnslist[] = $server;
257
				}
258
			}
259
		}
260
		if (count($dnslist) > 0) {
261
			$dnsstring = implode(" ", $dnslist);
262
			if ($dnsstring <> "") {
263
				$radvdconf .= "\tRDNSS {$dnsstring} { };\n";
264
			}
265
		}
266

    
267
		$searchlist = array();
268
		$domainsearchlist = explode(';', $dhcpv6ifconf['radomainsearchlist']);
269
		foreach ($domainsearchlist as $sd) {
270
			$sd = trim($sd);
271
			if (is_hostname($sd)) {
272
				$searchlist[] = $sd;
273
			}
274
		}
275
		if (count($searchlist) > 0) {
276
			$searchliststring = trim(implode(" ", $searchlist));
277
		}
278
		if (!empty($dhcpv6ifconf['domain'])) {
279
			$radvdconf .= "\tDNSSL {$dhcpv6ifconf['domain']} {$searchliststring} { };\n";
280
		} elseif (!empty($config['system']['domain'])) {
281
			$radvdconf .= "\tDNSSL {$config['system']['domain']} {$searchliststring} { };\n";
282
		}
283
		$radvdconf .= "};\n";
284
	}
285

    
286
	/* handle DHCP-PD prefixes and 6RD dynamic interfaces */
287
	foreach ($Iflist as $if => $ifdescr) {
288
		if (!isset($config['interfaces'][$if]['track6-interface']) ||
289
		    !isset($config['interfaces'][$if]['ipaddrv6']) ||
290
		    $config['interfaces'][$if]['ipaddrv6'] != 'track6') {
291
			continue;
292
		}
293
		if (!isset($config['interfaces'][$if]['enable'])) {
294
			continue;
295
		}
296
		if ($config['dhcpdv6'][$if]['ramode'] == "disabled") {
297
			continue;
298
		}
299
		/* Do not put in the config an interface which is down */
300
		if (isset($blacklist[$if])) {
301
			continue;
302
		}
303
		$trackif = $config['interfaces'][$if]['track6-interface'];
304
		if (empty($config['interfaces'][$trackif])) {
305
			continue;
306
		}
307

    
308
		$realif = get_real_interface($if, "inet6");
309

    
310
		/* prevent duplicate entries, manual overrides */
311
		if (isset($radvdifs[$realif])) {
312
			continue;
313
		}
314

    
315
		$ifcfgipv6 = get_interface_ipv6($if);
316
		if (!is_ipaddrv6($ifcfgipv6)) {
317
			$subnetv6 = "::";
318
			$ifcfgsnv6 = "64";
319
		} else {
320
			$ifcfgsnv6 = get_interface_subnetv6($if);
321
			$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
322
		}
323
		$radvdifs[$realif] = $realif;
324

    
325
		$autotype = $config['interfaces'][$trackif]['ipaddrv6'];
326

    
327
		if ($g['debug']) {
328
			log_error("configuring RA on {$if} for type {$autotype} radvd subnet {$subnetv6}/{$ifcfgsnv6}");
329
		}
330

    
331
		$radvdconf .= "# Generated config for {$autotype} delegation from {$trackif} on {$if}\n";
332
		$radvdconf .= "interface {$realif} {\n";
333
		$radvdconf .= "\tAdvSendAdvert on;\n";
334
		if (is_numericint($dhcpv6ifconf['raminrtradvinterval'])) {
335
			$radvdconf .= "\tMinRtrAdvInterval {$dhcpv6ifconf['raminrtradvinterval']};\n";
336
		} else {
337
			$radvdconf .= "\tMinRtrAdvInterval 5;\n";
338
                }
339
		if (is_numericint($dhcpv6ifconf['ramaxrtradvinterval'])) {
340
			$radvdconf .= "\tMaxRtrAdvInterval {$dhcpv6ifconf['ramaxrtradvinterval']};\n";
341
		} else {
342
			$radvdconf .= "\tMaxRtrAdvInterval 10;\n";
343
		}
344
		$mtu = get_interface_mtu($realif);
345
		if (is_numeric($mtu)) {
346
			$radvdconf .= "\tAdvLinkMTU {$mtu};\n";
347
		} else {
348
			$radvdconf .= "\tAdvLinkMTU 1280;\n";
349
		}
350
		$radvdconf .= "\tAdvOtherConfigFlag on;\n";
351
		$radvdconf .= "\tprefix {$subnetv6}/{$ifcfgsnv6} {\n";
352
		$radvdconf .= "\t\tAdvOnLink on;\n";
353
		$radvdconf .= "\t\tAdvAutonomous on;\n";
354
		$radvdconf .= "\t\tAdvRouterAddr on;\n";
355
		$radvdconf .= "\t};\n";
356

    
357
		/* add DNS servers */
358
		$dnslist = array();
359
		if (isset($config['dnsmasq']['enable']) || isset($config['unbound']['enable'])) {
360
			$dnslist[] = $ifcfgipv6;
361
		} elseif (is_array($config['system']['dnsserver']) && !empty($config['system']['dnsserver'])) {
362
			foreach ($config['system']['dnsserver'] as $server) {
363
				if (is_ipaddrv6($server)) {
364
					$dnslist[] = $server;
365
				}
366
			}
367
		}
368
		if (count($dnslist) > 0) {
369
			$dnsstring = implode(" ", $dnslist);
370
			if (!empty($dnsstring)) {
371
				$radvdconf .= "\tRDNSS {$dnsstring} { };\n";
372
			}
373
		}
374
		if (!empty($config['system']['domain'])) {
375
			$radvdconf .= "\tDNSSL {$config['system']['domain']} { };\n";
376
		}
377
		$radvdconf .= "};\n";
378
	}
379

    
380
	/* write radvd.conf */
381
	if (!@file_put_contents("{$g['varetc_path']}/radvd.conf", $radvdconf)) {
382
		log_error(gettext("Error: cannot open radvd.conf in services_radvd_configure()."));
383
		if (platform_booting()) {
384
			printf("Error: cannot open radvd.conf in services_radvd_configure().\n");
385
		}
386
	}
387
	unset($radvdconf);
388

    
389
	if (count($radvdifs) > 0) {
390
		if (isvalidpid("{$g['varrun_path']}/radvd.pid")) {
391
			sigkillbypid("{$g['varrun_path']}/radvd.pid", "HUP");
392
		} else {
393
			mwexec("/usr/local/sbin/radvd -p {$g['varrun_path']}/radvd.pid -C {$g['varetc_path']}/radvd.conf -m syslog");
394
		}
395
	} else {
396
		/* we need to shut down the radvd cleanly, it will send out the prefix
397
		 * information with a lifetime of 0 to notify clients of a (possible) new prefix */
398
		if (isvalidpid("{$g['varrun_path']}/radvd.pid")) {
399
			log_error(gettext("Shutting down Router Advertisment daemon cleanly"));
400
			killbypid("{$g['varrun_path']}/radvd.pid");
401
			@unlink("{$g['varrun_path']}/radvd.pid");
402
		}
403
	}
404
	return 0;
405
}
406

    
407
function services_dhcpd_configure($family = "all", $blacklist = array()) {
408
	global $config, $g;
409

    
410
	$dhcpdconfigurelck = lock("dhcpdconfigure", LOCK_EX);
411

    
412
	/* configure DHCPD chroot once */
413
	$fd = fopen("{$g['tmp_path']}/dhcpd.sh", "w");
414
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}\n");
415
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/dev\n");
416
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/etc\n");
417
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/usr/local/sbin\n");
418
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db\n");
419
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run\n");
420
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/usr\n");
421
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/lib\n");
422
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/run\n");
423
	fwrite($fd, "/usr/sbin/chown -R dhcpd:_dhcp {$g['dhcpd_chroot_path']}/*\n");
424
	fwrite($fd, "/bin/cp -n /lib/libc.so.* {$g['dhcpd_chroot_path']}/lib/\n");
425
	fwrite($fd, "/bin/cp -n /usr/local/sbin/dhcpd {$g['dhcpd_chroot_path']}/usr/local/sbin/\n");
426
	fwrite($fd, "/bin/chmod a+rx {$g['dhcpd_chroot_path']}/usr/local/sbin/dhcpd\n");
427

    
428
	$status = `/sbin/mount | /usr/bin/grep -v grep | /usr/bin/grep "{$g['dhcpd_chroot_path']}/dev"`;
429
	if (!trim($status)) {
430
		fwrite($fd, "/sbin/mount -t devfs devfs {$g['dhcpd_chroot_path']}/dev\n");
431
	}
432
	fclose($fd);
433
	mwexec("/bin/sh {$g['tmp_path']}/dhcpd.sh");
434

    
435
	if ($family == "all" || $family == "inet") {
436
		services_dhcpdv4_configure();
437
	}
438
	if ($family == "all" || $family == "inet6") {
439
		services_dhcpdv6_configure($blacklist);
440
		services_radvd_configure($blacklist);
441
	}
442

    
443
	unlock($dhcpdconfigurelck);
444
}
445

    
446
function services_dhcpdv4_configure() {
447
	global $config, $g;
448
	$need_ddns_updates = false;
449
	$ddns_zones = array();
450

    
451
	if ($g['services_dhcp_server_enable'] == false) {
452
		return;
453
	}
454

    
455
	if (isset($config['system']['developerspew'])) {
456
		$mt = microtime();
457
		echo "services_dhcpdv4_configure($if) being called $mt\n";
458
	}
459

    
460
	/* kill any running dhcpd */
461
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid")) {
462
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid");
463
	}
464

    
465
	/* DHCP enabled on any interfaces? */
466
	if (!is_dhcp_server_enabled()) {
467
		return 0;
468
	}
469

    
470
	/* if OLSRD is enabled, allow WAN to house DHCP. */
471
	if (!function_exists('is_package_installed')) {
472
		require_once('pkg-utils.inc');
473
	}
474
	if (is_package_installed('olsrd') && isset($config['installedpackages']['olsrd'])) {
475
		foreach ($config['installedpackages']['olsrd']['config'] as $olsrd) {
476
			if (isset($olsrd['enable']) && $olsrd['enable'] == "on") {
477
				$is_olsr_enabled = true;
478
				break;
479
			}
480
		}
481
	}
482

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

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

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

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

    
534
	$dhcpdconf = <<<EOD
535

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

    
549
EOD;
550

    
551
	if (!isset($dhcpifconf['disableauthoritative'])) {
552
		$dhcpdconf .= "authoritative;\n";
553
	}
554

    
555
	if (isset($dhcpifconf['alwaysbroadcast'])) {
556
		$dhcpdconf .= "always-broadcast on\n";
557
	}
558

    
559
	$dhcpdifs = array();
560
	$enable_add_routers = false;
561
	$gateways_arr = return_gateways_array();
562
	/* only add a routers line if the system has any IPv4 gateway at all */
563
	/* a static route has a gateway, manually overriding this field always works */
564
	foreach ($gateways_arr as $gwitem) {
565
		if ($gwitem['ipprotocol'] == "inet") {
566
			$enable_add_routers = true;
567
			break;
568
		}
569
	}
570

    
571
	/*    loop through and determine if we need to setup
572
	 *    failover peer "bleh" entries
573
	 */
574
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
575

    
576
		if (!isset($config['interfaces'][$dhcpif]['enable'])) {
577
			continue;
578
		}
579

    
580
		interfaces_staticarp_configure($dhcpif);
581

    
582
		if (!isset($dhcpifconf['enable'])) {
583
			continue;
584
		}
585

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

    
622
			if (is_ipaddrv4($intip)) {
623
				$dhcpdconf .= <<<EOPP
624
failover peer "dhcp_{$dhcpif}" {
625
  {$type};
626
  address {$intip};
627
  port {$my_port};
628
  peer address {$dhcpifconf['failover_peerip']};
629
  peer port {$peer_port};
630
  max-response-delay 10;
631
  max-unacked-updates 10;
632
  {$dhcpdconf_pri}
633
  load balance max seconds 3;
634
}
635
\n
636
EOPP;
637
			}
638
		}
639
	}
640

    
641
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
642

    
643
		$newzone = array();
644
		$ifcfg = $config['interfaces'][$dhcpif];
645

    
646
		if (!isset($dhcpifconf['enable']) || !isset($Iflist[$dhcpif])) {
647
			continue;
648
		}
649
		$ifcfgip = get_interface_ip($dhcpif);
650
		$ifcfgsn = get_interface_subnet($dhcpif);
651
		$subnet = gen_subnet($ifcfgip, $ifcfgsn);
652
		$subnetmask = gen_subnet_mask($ifcfgsn);
653

    
654
		if (!is_ipaddr($subnet)) {
655
			continue;
656
		}
657

    
658
		if ($is_olsr_enabled == true) {
659
			if ($dhcpifconf['netmask']) {
660
				$subnetmask = gen_subnet_mask($dhcpifconf['netmask']);
661
			}
662
		}
663

    
664
		$all_pools = array();
665
		$all_pools[] = $dhcpifconf;
666
		if (is_array($dhcpifconf['pool'])) {
667
			$all_pools = array_merge($all_pools, $dhcpifconf['pool']);
668
		}
669

    
670
		$dnscfg = "";
671

    
672
		if ($dhcpifconf['domain']) {
673
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
674
		}
675

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

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

    
690
			$revsubnet = array_reverse(explode('.',$subnet));
691

    
692
			/* Take care of full classes first */
693
			switch ($ifcfgsn) {
694
				case 8:
695
					$start_octet = 3;
696
					break;
697
				case 16:
698
					$start_octet = 2;
699
					break;
700
				case 24:
701
					$start_octet = 1;
702
					break;
703
				default:
704
					$start_octet = 0;
705
					/* Add subnet bitmask to first octet */
706
					$revsubnet[0] .= '-' . $ifcfgsn;
707
					break;
708

    
709
			}
710

    
711
			$ptr_domain = '';
712
			for ($octet = 0; $octet <= 3; $octet++) {
713
				if ($octet < $start_octet) {
714
					continue;
715
				}
716
				$ptr_domain .= ((empty($ptr_domain) && $ptr_domain !== "0") ? '' : '.');
717
				$ptr_domain .= $revsubnet[$octet];
718
			}
719
			$ptr_domain .= ".in-addr.arpa";
720
			$newzone['ptr-domain'] = $ptr_domain;
721
			unset($ptr_domain, $revsubnet, $start_octet);
722
		}
723

    
724
		if (is_array($dhcpifconf['dnsserver']) && ($dhcpifconf['dnsserver'][0])) {
725
			$dnscfg .= "	option domain-name-servers " . join(",", $dhcpifconf['dnsserver']) . ";";
726
			if ($newzone['domain-name']) {
727
				$newzone['dns-servers'] = $dhcpifconf['dnsserver'];
728
			}
729
		} else if (isset($config['dnsmasq']['enable'])) {
730
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
731
			if ($newzone['domain-name'] && is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
732
				$newzone['dns-servers'] = $syscfg['dnsserver'];
733
			}
734
		} else if (isset($config['unbound']['enable'])) {
735
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
736
		} else if (!empty($dns_arrv4)) {
737
			$dnscfg .= "	option domain-name-servers " . join(",", $dns_arrv4) . ";";
738
			if ($newzone['domain-name']) {
739
				$newzone['dns-servers'] = $dns_arrv4;
740
			}
741
		}
742

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

    
767
		$dhcpdconf .= "subnet {$subnet} netmask {$subnetmask} {\n";
768

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

    
814
			/* allow/deny MACs */
815
			$mac_allow_list = array_unique(explode(',', $poolconf['mac_allow']));
816
			foreach ($mac_allow_list as $mac) {
817
				if (empty($mac)) {
818
					continue;
819
				}
820
				$dhcpdconf .= "		allow members of \"" . str_replace(':', '', $mac) . "\";\n";
821
			}
822
			$deny_action = "deny";
823
			if (isset($poolconf['nonak']) && empty($poolconf['failover_peerip'])) {
824
				$deny_action = "ignore";
825
			}
826
			$mac_deny_list = array_unique(explode(',', $poolconf['mac_deny']));
827
			foreach ($mac_deny_list as $mac) {
828
				if (empty($mac)) {
829
					continue;
830
				}
831
				$dhcpdconf .= "		$deny_action members of \"" . str_replace(':', '', $mac) . "\";\n";
832
			}
833

    
834
			if ($poolconf['failover_peerip'] <> "") {
835
				$dhcpdconf .= "		$deny_action dynamic bootp clients;\n";
836
			}
837

    
838
			if (isset($poolconf['denyunknown'])) {
839
				$dhcpdconf .= "		$deny_action unknown-clients;\n";
840
			}
841

    
842
			if ($poolconf['gateway'] && $poolconf['gateway'] != "none" && ($poolconf['gateway'] != $dhcpifconf['gateway'])) {
843
				$dhcpdconf .= "		option routers {$poolconf['gateway']};\n";
844
			}
845

    
846
			if ($dhcpifconf['failover_peerip'] <> "") {
847
				$dhcpdconf .= "		failover peer \"dhcp_{$dhcpif}\";\n";
848
			}
849

    
850
			$pdnscfg = "";
851

    
852
			if ($poolconf['domain'] && ($poolconf['domain'] != $dhcpifconf['domain'])) {
853
				$pdnscfg .= "		option domain-name \"{$poolconf['domain']}\";\n";
854
			}
855

    
856
			if (!empty($poolconf['domainsearchlist']) && ($poolconf['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
857
				$pdnscfg .= "		option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $poolconf['domainsearchlist'])) . "\";\n";
858
			}
859

    
860
			if (isset($poolconf['ddnsupdate'])) {
861
				if (($poolconf['ddnsdomain'] <> "") && ($poolconf['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
862
					$pdnscfg .= "		ddns-domainname \"{$poolconf['ddnsdomain']}\";\n";
863
				}
864
				$pdnscfg .= "		ddns-update-style interim;\n";
865
			}
866

    
867
			$dhcpdconf .= "{$pdnscfg}";
868

    
869
			// default-lease-time
870
			if ($poolconf['defaultleasetime'] && ($poolconf['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
871
				$dhcpdconf .= "		default-lease-time {$poolconf['defaultleasetime']};\n";
872
			}
873

    
874
			// max-lease-time
875
			if ($poolconf['maxleasetime'] && ($poolconf['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
876
				$dhcpdconf .= "		max-lease-time {$poolconf['maxleasetime']};\n";
877
			}
878

    
879
			// ignore bootp
880
			if (isset($poolconf['ignorebootp'])) {
881
				$dhcpdconf .= "		ignore bootp;\n";
882
			}
883

    
884
			// ignore-client-uids
885
			if (isset($poolconf['ignoreclientuids'])) {
886
				$dhcpdconf .= "		ignore-client-uids true;\n";
887
			}
888

    
889
			// netbios-name*
890
			if (is_array($poolconf['winsserver']) && $poolconf['winsserver'][0] && ($poolconf['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
891
				$dhcpdconf .= "		option netbios-name-servers " . join(",", $poolconf['winsserver']) . ";\n";
892
				$dhcpdconf .= "		option netbios-node-type 8;\n";
893
			}
894

    
895
			// ntp-servers
896
			if (is_array($poolconf['ntpserver']) && $poolconf['ntpserver'][0] && ($poolconf['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
897
				$dhcpdconf .= "		option ntp-servers " . join(",", $poolconf['ntpserver']) . ";\n";
898
			}
899

    
900
			// tftp-server-name
901
			if (!empty($poolconf['tftp']) && ($poolconf['tftp'] != $dhcpifconf['tftp'])) {
902
				$dhcpdconf .= "		option tftp-server-name \"{$poolconf['tftp']}\";\n";
903
			}
904

    
905
			// Handle pool-specific options
906
			$dhcpdconf .= "\n";
907
			// Ignore the first pool, which is the "overall" pool when $all_pools_idx is 0 - those are put outside the pool block later
908
			if ($poolconf['numberoptions']['item'] && ($all_pools_idx > 0)) {
909
				// Use the "real" pool index from the config, excluding the "overall" pool, and based from 0.
910
				// This matches the way $poolidx was used when generating the $custoptions string earlier.
911
				$poolidx = $all_pools_idx - 1;
912
				foreach ($poolconf['numberoptions']['item'] as $itemidx => $item) {
913
					$item_value = base64_decode($item['value']);
914
					if (empty($item['type']) || $item['type'] == "text") {
915
						$dhcpdconf .= "		option custom-{$dhcpif}-{$poolidx}-{$itemidx} \"{$item_value}\";\n";
916
					} else {
917
						$dhcpdconf .= "		option custom-{$dhcpif}-{$poolidx}-{$itemidx} {$item_value};\n";
918
					}
919
				}
920
			}
921

    
922
			// ldap-server
923
			if (!empty($poolconf['ldap']) && ($poolconf['ldap'] != $dhcpifconf['ldap'])) {
924
				$dhcpdconf .= "		option ldap-server \"{$poolconf['ldap']}\";\n";
925
			}
926

    
927
			// net boot information
928
			if (isset($poolconf['netboot'])) {
929
				if (!empty($poolconf['nextserver']) && ($poolconf['nextserver'] != $dhcpifconf['nextserver'])) {
930
					$dhcpdconf .= "		next-server {$poolconf['nextserver']};\n";
931
				}
932

    
933
				if (!empty($poolconf['filename']) &&
934
				    (!isset($dhcpifconf['filename']) ||
935
				    ($poolconf['filename'] != $dhcpifconf['filename']))) {
936
					$filename = $poolconf['filename'];
937
				}
938
				if (!empty($poolconf['filename32']) &&
939
				    (!isset($dhcpifconf['filename32']) ||
940
				    ($poolconf['filename32'] != $dhcpifconf['filename32']))) {
941
					$filename32 = $poolconf['filename32'];
942
				}
943
				if (!empty($poolconf['filename64']) &&
944
				    (!isset($dhcpifconf['filename64']) ||
945
				    ($poolconf['filename64'] != $dhcpifconf['filename64']))) {
946
					$filename64 = $poolconf['filename64'];
947
				}
948

    
949
				if (!empty($filename32) || !empty($filename64)) {
950
					if (empty($filename) && !empty($dhcpifconf['filename'])) {
951
						$filename = $dhcpifconf['filename'];
952
					}
953
					if (empty($filename32) && !empty($dhcpifconf['filename32'])) {
954
						$filename32 = $dhcpifconf['filename32'];
955
					}
956
					if (empty($filename64) && !empty($dhcpifconf['filename64'])) {
957
						$filename64 = $dhcpifconf['filename64'];
958
					}
959
				}
960

    
961
				if (!empty($filename) && !empty($filename32) && !empty($filename64)) {
962
					$dhcpdconf .= "		if option arch = 00:06 {\n";
963
					$dhcpdconf .= "			filename \"{$filename32}\";\n";
964
					$dhcpdconf .= "		} else if option arch = 00:07 {\n";
965
					$dhcpdconf .= "			filename \"{$filename64}\";\n";
966
					$dhcpdconf .= "		} else if option arch = 00:09 {\n";
967
					$dhcpdconf .= "			filename \"{$filename64}\";\n";
968
					$dhcpdconf .= "		} else {\n";
969
					$dhcpdconf .= "			filename \"{$filename}\";\n";
970
					$dhcpdconf .= "		}\n\n";
971
				} elseif (!empty($filename)) {
972
					$dhcpdconf .= "		filename \"{$filename}\";\n";
973
				}
974
				unset($filename, $filename32, $filename64);
975

    
976
				if (!empty($poolconf['rootpath']) && ($poolconf['rootpath'] != $dhcpifconf['rootpath'])) {
977
					$dhcpdconf .= "		option root-path \"{$poolconf['rootpath']}\";\n";
978
				}
979
			}
980
			$dhcpdconf .= "		range {$poolconf['range']['from']} {$poolconf['range']['to']};\n";
981
			$dhcpdconf .= "	}\n\n";
982
		}
983
// End of settings inside pools
984

    
985
		if ($dhcpifconf['gateway'] && $dhcpifconf['gateway'] != "none") {
986
			$routers = $dhcpifconf['gateway'];
987
			$add_routers = true;
988
		} elseif ($dhcpifconf['gateway'] == "none") {
989
			$add_routers = false;
990
		} else {
991
			$add_routers = $enable_add_routers;
992
			$routers = $ifcfgip;
993
		}
994
		if ($add_routers) {
995
			$dhcpdconf .= "	option routers {$routers};\n";
996
		}
997

    
998
		$dhcpdconf .= <<<EOD
999
$dnscfg
1000

    
1001
EOD;
1002
		// default-lease-time
1003
		if ($dhcpifconf['defaultleasetime']) {
1004
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
1005
		}
1006

    
1007
		// max-lease-time
1008
		if ($dhcpifconf['maxleasetime']) {
1009
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
1010
		}
1011

    
1012
		// netbios-name*
1013
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
1014
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
1015
			$dhcpdconf .= "	option netbios-node-type 8;\n";
1016
		}
1017

    
1018
		// ntp-servers
1019
		if (is_array($dhcpifconf['ntpserver']) && $dhcpifconf['ntpserver'][0]) {
1020
			$dhcpdconf .= "	option ntp-servers " . join(",", $dhcpifconf['ntpserver']) . ";\n";
1021
		}
1022

    
1023
		// tftp-server-name
1024
		if ($dhcpifconf['tftp'] <> "") {
1025
			$dhcpdconf .= "	option tftp-server-name \"{$dhcpifconf['tftp']}\";\n";
1026
		}
1027

    
1028
		// Handle option, number rowhelper values
1029
		$dhcpdconf .= "\n";
1030
		if ($dhcpifconf['numberoptions']['item']) {
1031
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
1032
				$item_value = base64_decode($item['value']);
1033
				if (empty($item['type']) || $item['type'] == "text") {
1034
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} \"{$item_value}\";\n";
1035
				} else {
1036
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} {$item_value};\n";
1037
				}
1038
			}
1039
		}
1040

    
1041
		// ldap-server
1042
		if ($dhcpifconf['ldap'] <> "") {
1043
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
1044
		}
1045

    
1046
		// net boot information
1047
		if (isset($dhcpifconf['netboot'])) {
1048
			if ($dhcpifconf['nextserver'] <> "") {
1049
				$dhcpdconf .= "	next-server {$dhcpifconf['nextserver']};\n";
1050
			}
1051
			if (!empty($dhcpifconf['filename']) && !empty($dhcpifconf['filename32']) && !empty($dhcpifconf['filename64'])) {
1052
				$dhcpdconf .= "	if option arch = 00:06 {\n";
1053
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename32']}\";\n";
1054
				$dhcpdconf .= "	} else if option arch = 00:07 {\n";
1055
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1056
				$dhcpdconf .= "	} else if option arch = 00:09 {\n";
1057
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1058
				$dhcpdconf .= "	} else {\n";
1059
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename']}\";\n";
1060
				$dhcpdconf .= "	}\n\n";
1061
			} elseif (!empty($dhcpifconf['filename'])) {
1062
				$dhcpdconf .= "	filename \"{$dhcpifconf['filename']}\";\n";
1063
			}
1064
			if (!empty($dhcpifconf['rootpath'])) {
1065
				$dhcpdconf .= "	option root-path \"{$dhcpifconf['rootpath']}\";\n";
1066
			}
1067
		}
1068

    
1069
		$dhcpdconf .= <<<EOD
1070
}
1071

    
1072
EOD;
1073

    
1074
		/* add static mappings */
1075
		if (is_array($dhcpifconf['staticmap'])) {
1076

    
1077
			$i = 0;
1078
			foreach ($dhcpifconf['staticmap'] as $sm) {
1079
				$dhcpdconf .= "host s_{$dhcpif}_{$i} {\n";
1080

    
1081
				if ($sm['mac']) {
1082
					$dhcpdconf .= "        hardware ethernet {$sm['mac']};\n";
1083
				}
1084

    
1085
				if ($sm['cid']) {
1086
					$dhcpdconf .= "        option dhcp-client-identifier \"{$sm['cid']}\";\n";
1087
				}
1088

    
1089
				if ($sm['ipaddr']) {
1090
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
1091
				}
1092

    
1093
				if ($sm['hostname']) {
1094
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1095
					$dhhostname = str_replace(".", "_", $dhhostname);
1096
					$dhcpdconf .= "	option host-name \"{$dhhostname}\";\n";
1097
					if ((isset($dhcpifconf['ddnsupdate']) || isset($sm['ddnsupdate'])) && (isset($dhcpifconf['ddnsforcehostname']) || isset($sm['ddnsforcehostname']))) {
1098
						$dhcpdconf .= "	ddns-hostname \"{$dhhostname}\";\n";
1099
					}
1100
				}
1101
				if ($sm['filename']) {
1102
					$dhcpdconf .= "	filename \"{$sm['filename']}\";\n";
1103
				}
1104

    
1105
				if ($sm['rootpath']) {
1106
					$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1107
				}
1108

    
1109
				if ($sm['gateway'] && ($sm['gateway'] != $dhcpifconf['gateway'])) {
1110
					$dhcpdconf .= "	option routers {$sm['gateway']};\n";
1111
				}
1112

    
1113
				$smdnscfg = "";
1114

    
1115
				if ($sm['domain'] && ($sm['domain'] != $dhcpifconf['domain'])) {
1116
					$smdnscfg .= "	option domain-name \"{$sm['domain']}\";\n";
1117
				}
1118

    
1119
				if (!empty($sm['domainsearchlist']) && ($sm['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
1120
					$smdnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $sm['domainsearchlist'])) . "\";\n";
1121
				}
1122

    
1123
				if (isset($sm['ddnsupdate'])) {
1124
					if (($sm['ddnsdomain'] <> "") && ($sm['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
1125
						$smdnscfg .= "		ddns-domainname \"{$sm['ddnsdomain']}\";\n";
1126
					}
1127
					$smdnscfg .= "		ddns-update-style interim;\n";
1128
				}
1129

    
1130
				if (is_array($sm['dnsserver']) && ($sm['dnsserver'][0]) && ($sm['dnsserver'][0] != $dhcpifconf['dnsserver'][0])) {
1131
					$smdnscfg .= "	option domain-name-servers " . join(",", $sm['dnsserver']) . ";\n";
1132
				}
1133
				$dhcpdconf .= "{$smdnscfg}";
1134

    
1135
				// default-lease-time
1136
				if ($sm['defaultleasetime'] && ($sm['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
1137
					$dhcpdconf .= "	default-lease-time {$sm['defaultleasetime']};\n";
1138
				}
1139

    
1140
				// max-lease-time
1141
				if ($sm['maxleasetime'] && ($sm['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
1142
					$dhcpdconf .= "	max-lease-time {$sm['maxleasetime']};\n";
1143
				}
1144

    
1145
				// netbios-name*
1146
				if (is_array($sm['winsserver']) && $sm['winsserver'][0] && ($sm['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
1147
					$dhcpdconf .= "	option netbios-name-servers " . join(",", $sm['winsserver']) . ";\n";
1148
					$dhcpdconf .= "	option netbios-node-type 8;\n";
1149
				}
1150

    
1151
				// ntp-servers
1152
				if (is_array($sm['ntpserver']) && $sm['ntpserver'][0] && ($sm['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
1153
					$dhcpdconf .= "	option ntp-servers " . join(",", $sm['ntpserver']) . ";\n";
1154
				}
1155

    
1156
				// tftp-server-name
1157
				if (!empty($sm['tftp']) && ($sm['tftp'] != $dhcpifconf['tftp'])) {
1158
					$dhcpdconf .= "	option tftp-server-name \"{$sm['tftp']}\";\n";
1159
				}
1160

    
1161
				$dhcpdconf .= "}\n";
1162
				$i++;
1163
			}
1164
		}
1165

    
1166
		$dhcpdifs[] = get_real_interface($dhcpif);
1167
		if ($newzone['domain-name']) {
1168
			if ($need_ddns_updates) {
1169
				$newzone['dns-servers'] = array($dhcpifconf['ddnsdomainprimary']);
1170
				$newzone['ddnsdomainkeyname'] = $dhcpifconf['ddnsdomainkeyname'];
1171
				$newzone['ddnsdomainkey'] = $dhcpifconf['ddnsdomainkey'];
1172
				$dhcpdconf .= dhcpdkey($dhcpifconf);
1173
			}
1174
			$ddns_zones[] = $newzone;
1175
		}
1176
	}
1177

    
1178
	if ($need_ddns_updates) {
1179
		$dhcpdconf .= "ddns-update-style interim;\n";
1180
		$dhcpdconf .= "update-static-leases on;\n";
1181

    
1182
		$dhcpdconf .= dhcpdzones($ddns_zones);
1183
	}
1184

    
1185
	/* write dhcpd.conf */
1186
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpd.conf", $dhcpdconf)) {
1187
		printf(gettext("Error: cannot open dhcpd.conf in services_dhcpdv4_configure().%s"), "\n");
1188
		unset($dhcpdconf);
1189
		return 1;
1190
	}
1191
	unset($dhcpdconf);
1192

    
1193
	/* create an empty leases database */
1194
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
1195
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
1196
	}
1197

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

    
1202
	/* fire up dhcpd in a chroot */
1203
	if (count($dhcpdifs) > 0) {
1204
		mwexec("/usr/local/sbin/dhcpd -user dhcpd -group _dhcp -chroot {$g['dhcpd_chroot_path']} -cf /etc/dhcpd.conf -pf {$g['varrun_path']}/dhcpd.pid " .
1205
			join(" ", $dhcpdifs));
1206
	}
1207

    
1208
	if (platform_booting()) {
1209
		print "done.\n";
1210
	}
1211

    
1212
	return 0;
1213
}
1214

    
1215
function dhcpdkey($dhcpifconf) {
1216
	$dhcpdconf = "";
1217
	if ($dhcpifconf['ddnsdomainkeyname'] <> "" && $dhcpifconf['ddnsdomainkey'] <> "") {
1218
		$dhcpdconf .= "key {$dhcpifconf['ddnsdomainkeyname']} {\n";
1219
		$dhcpdconf .= "	algorithm hmac-md5;\n";
1220
		$dhcpdconf .= "	secret {$dhcpifconf['ddnsdomainkey']};\n";
1221
		$dhcpdconf .= "}\n";
1222
	}
1223

    
1224
	return $dhcpdconf;
1225
}
1226

    
1227
function dhcpdzones($ddns_zones) {
1228
	$dhcpdconf = "";
1229

    
1230
	if (is_array($ddns_zones)) {
1231
		$added_zones = array();
1232
		foreach ($ddns_zones as $zone) {
1233
			if (!is_array($zone) || empty($zone) || !is_array($zone['dns-servers'])) {
1234
				continue;
1235
			}
1236
			$primary = $zone['dns-servers'][0];
1237
			$secondary = empty($zone['dns-servers'][1]) ? "" : $zone['dns-servers'][1];
1238

    
1239
			// Make sure we aren't using any invalid or IPv6 DNS servers.
1240
			if (!is_ipaddrv4($primary)) {
1241
				if (is_ipaddrv4($secondary)) {
1242
					$primary = $secondary;
1243
					$secondary = "";
1244
				} else {
1245
					continue;
1246
				}
1247
			}
1248

    
1249
			// We don't need to add zones multiple times.
1250
			if ($zone['domain-name'] && !in_array($zone['domain-name'], $added_zones)) {
1251
				$dhcpdconf .= "zone {$zone['domain-name']}. {\n";
1252
				$dhcpdconf .= "	primary {$primary};\n";
1253
				if (is_ipaddrv4($secondary)) {
1254
					$dhcpdconf .= "	secondary {$secondary};\n";
1255
				}
1256
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1257
					$dhcpdconf .= "	key {$zone['ddnsdomainkeyname']};\n";
1258
				}
1259
				$dhcpdconf .= "}\n";
1260
				$added_zones[] = $zone['domain-name'];
1261
			}
1262
			if ($zone['ptr-domain'] && !in_array($zone['ptr-domain'], $added_zones)) {
1263
				$dhcpdconf .= "zone {$zone['ptr-domain']} {\n";
1264
				$dhcpdconf .= "	primary {$primary};\n";
1265
				if (is_ipaddrv4($secondary)) {
1266
					$dhcpdconf .= "	secondary {$secondary};\n";
1267
				}
1268
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1269
					$dhcpdconf .= "	key {$zone['ddnsdomainkeyname']};\n";
1270
				}
1271
				$dhcpdconf .= "}\n";
1272
				$added_zones[] = $zone['ptr-domain'];
1273
			}
1274
		}
1275
	}
1276

    
1277
	return $dhcpdconf;
1278
}
1279

    
1280
function services_dhcpdv6_configure($blacklist = array()) {
1281
	global $config, $g;
1282

    
1283
	if ($g['services_dhcp_server_enable'] == false) {
1284
		return;
1285
	}
1286

    
1287
	if (isset($config['system']['developerspew'])) {
1288
		$mt = microtime();
1289
		echo "services_dhcpd_configure($if) being called $mt\n";
1290
	}
1291

    
1292
	/* kill any running dhcpd */
1293
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid")) {
1294
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid");
1295
	}
1296
	if (isvalidpid("{$g['varrun_path']}/dhcpleases6.pid")) {
1297
		killbypid("{$g['varrun_path']}/dhcpleases6.pid");
1298
	}
1299

    
1300
	/* DHCP enabled on any interfaces? */
1301
	if (!is_dhcpv6_server_enabled()) {
1302
		return 0;
1303
	}
1304

    
1305
	$syscfg = $config['system'];
1306
	if (!is_array($config['dhcpdv6'])) {
1307
		$config['dhcpdv6'] = array();
1308
	}
1309
	$dhcpdv6cfg = $config['dhcpdv6'];
1310
	$Iflist = get_configured_interface_list();
1311
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
1312

    
1313

    
1314
	if (platform_booting()) {
1315
		echo "Starting DHCPv6 service...";
1316
	} else {
1317
		sleep(1);
1318
	}
1319

    
1320
	$custoptionsv6 = "";
1321
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1322
		if (is_array($dhcpv6ifconf['numberoptions']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1323
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1324
				$custoptionsv6 .= "option custom-{$dhcpv6if}-{$itemv6idx} code {$itemv6['number']} = text;\n";
1325
			}
1326
		}
1327
	}
1328

    
1329
	if (isset($dhcpv6ifconf['netboot']) && !empty($dhcpv6ifconf['bootfile_url'])) {
1330
		$custoptionsv6 .= "option dhcp6.bootfile-url code 59 = string;\n";
1331
	}
1332

    
1333
	$dhcpdv6conf = <<<EOD
1334

    
1335
option domain-name "{$syscfg['domain']}";
1336
option ldap-server code 95 = text;
1337
option domain-search-list code 119 = text;
1338
{$custoptionsv6}
1339
default-lease-time 7200;
1340
max-lease-time 86400;
1341
log-facility local7;
1342
one-lease-per-client true;
1343
deny duplicates;
1344
ping-check true;
1345
update-conflict-detection false;
1346

    
1347
EOD;
1348

    
1349
	if (!isset($dhcpv6ifconf['disableauthoritative'])) {
1350
		$dhcpdv6conf .= "authoritative;\n";
1351
	}
1352

    
1353
	if (isset($dhcpv6ifconf['alwaysbroadcast'])) {
1354
		$dhcpdv6conf .= "always-broadcast on\n";
1355
	}
1356

    
1357
	$dhcpdv6ifs = array();
1358

    
1359
	$dhcpv6num = 0;
1360
	$nsupdate = false;
1361

    
1362
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1363

    
1364
		$ddns_zones = array();
1365

    
1366
		$ifcfgv6 = $config['interfaces'][$dhcpv6if];
1367

    
1368
		if (!isset($dhcpv6ifconf['enable']) || !isset($Iflist[$dhcpv6if]) || !isset($ifcfgv6['enable'])) {
1369
			continue;
1370
		}
1371
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1372
		if (!is_ipaddrv6($ifcfgipv6)) {
1373
			continue;
1374
		}
1375
		$ifcfgsnv6 = get_interface_subnetv6($dhcpv6if);
1376
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1377
		// We might have some prefix-delegation on WAN (e.g. /48),
1378
		// but then it is split and given out to individual interfaces
1379
		// (LAN, OPT1, OPT2...) as multiple /64 subnets. So the size
1380
		// of each subnet here is always /64.
1381
		$pdlen = 64;
1382

    
1383
		if ($is_olsr_enabled == true) {
1384
			if ($dhcpv6ifconf['netmask']) {
1385
				$subnetmask = gen_subnet_maskv6($dhcpv6ifconf['netmask']);
1386
			}
1387
		}
1388

    
1389
		$dnscfgv6 = "";
1390

    
1391
		if ($dhcpv6ifconf['domain']) {
1392
			$dnscfgv6 .= "	option domain-name \"{$dhcpv6ifconf['domain']}\";\n";
1393
		}
1394

    
1395
		if ($dhcpv6ifconf['domainsearchlist'] <> "") {
1396
			$dnscfgv6 .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpv6ifconf['domainsearchlist'])) . "\";\n";
1397
		}
1398

    
1399
		if (isset($dhcpv6ifconf['ddnsupdate'])) {
1400
			if ($dhcpv6ifconf['ddnsdomain'] <> "") {
1401
				$dnscfgv6 .= "	ddns-domainname \"{$dhcpv6ifconf['ddnsdomain']}\";\n";
1402
			}
1403
			if (empty($dhcpv6ifconf['ddnsclientupdates'])) {
1404
				$ddnsclientupdates = 'allow';
1405
			} else {
1406
				$ddnsclientupdates = $dhcpv6ifconf['ddnsclientupdates'];
1407
			}
1408
			$dnscfgv6 .= "	{$ddnsclientupdates} client-updates;\n";
1409
			$nsupdate = true;
1410
		} else {
1411
			$dnscfgv6 .= "	do-forward-updates false;\n";
1412
		}
1413

    
1414
		if (is_array($dhcpv6ifconf['dnsserver']) && ($dhcpv6ifconf['dnsserver'][0])) {
1415
			$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dhcpv6ifconf['dnsserver']) . ";";
1416
		} else if (((isset($config['dnsmasq']['enable'])) || isset($config['unbound']['enable'])) && (is_ipaddrv6($ifcfgipv6))) {
1417
			$dnscfgv6 .= "	option dhcp6.name-servers {$ifcfgipv6};";
1418
		} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1419
			$dns_arrv6 = array();
1420
			foreach ($syscfg['dnsserver'] as $dnsserver) {
1421
				if (is_ipaddrv6($dnsserver)) {
1422
					$dns_arrv6[] = $dnsserver;
1423
				}
1424
			}
1425
			if (!empty($dns_arrv6)) {
1426
				$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dns_arrv6) . ";";
1427
			}
1428
		}
1429

    
1430
		if (!is_ipaddrv6($ifcfgipv6)) {
1431
			$ifcfgsnv6 = "64";
1432
			$subnetv6 = gen_subnetv6($dhcpv6ifconf['range']['from'], $ifcfgsnv6);
1433
		}
1434

    
1435
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1436

    
1437
		if (isset($dhcpv6ifconf['ddnsupdate']) &&
1438
		    !empty($dhcpv6ifconf['ddnsdomain'])) {
1439
			$newzone = array();
1440
			$newzone['domain-name'] = $dhcpv6ifconf['ddnsdomain'];
1441
			$newzone['dns-servers'][] = $dhcpv6ifconf['ddnsdomainprimary'];
1442
			$newzone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1443
			$newzone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1444
			$ddns_zones[] = $newzone;
1445
			if (isset($dhcpv6ifconf['ddnsreverse'])) {
1446
				$ptr_zones = get_v6_ptr_zones($subnetv6, $ifcfgsnv6);
1447
				foreach ($ptr_zones as $ptr_zone) {
1448
					$reversezone = array();
1449
					$reversezone['domain-name'] = $ptr_zone;
1450
					$reversezone['dns-servers'][] =
1451
					    $dhcpv6ifconf['ddnsdomainprimary'];
1452
					$ddns_zones[] = $reversezone;
1453
				}
1454
			}
1455
		}
1456

    
1457
		$dhcpdv6conf .= " {\n";
1458

    
1459
		$range_from = $dhcpv6ifconf['range']['from'];
1460
		$range_to = $dhcpv6ifconf['range']['to'];
1461
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
1462
			$range_from = merge_ipv6_delegated_prefix($ifcfgipv6, $range_from, $pdlen);
1463
			$range_to = merge_ipv6_delegated_prefix($ifcfgipv6, $range_to, $pdlen);
1464
		}
1465

    
1466
		$dhcpdv6conf .= <<<EOD
1467
	range6 {$range_from} {$range_to};
1468
$dnscfgv6
1469

    
1470
EOD;
1471

    
1472
		if (is_ipaddrv6($dhcpv6ifconf['prefixrange']['from']) && is_ipaddrv6($dhcpv6ifconf['prefixrange']['to'])) {
1473
			$dhcpdv6conf .= "	prefix6 {$dhcpv6ifconf['prefixrange']['from']} {$dhcpv6ifconf['prefixrange']['to']} /{$dhcpv6ifconf['prefixrange']['prefixlength']};\n";
1474
		}
1475
		if (is_ipaddrv6($dhcpv6ifconf['dns6ip'])) {
1476
			$dns6ip = $dhcpv6ifconf['dns6ip'];
1477
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1478
			    Net_IPv6::isInNetmask($dns6ip, '::', $pdlen)) {
1479
				$dns6ip = merge_ipv6_delegated_prefix($ifcfgipv6, $dns6ip, $pdlen);
1480
			}
1481
			$dhcpdv6conf .= "	option dhcp6.name-servers {$dns6ip};\n";
1482
		}
1483
		// default-lease-time
1484
		if ($dhcpv6ifconf['defaultleasetime']) {
1485
			$dhcpdv6conf .= "	default-lease-time {$dhcpv6ifconf['defaultleasetime']};\n";
1486
		}
1487

    
1488
		// max-lease-time
1489
		if ($dhcpv6ifconf['maxleasetime']) {
1490
			$dhcpdv6conf .= "	max-lease-time {$dhcpv6ifconf['maxleasetime']};\n";
1491
		}
1492

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

    
1517
		// Handle option, number rowhelper values
1518
		$dhcpdv6conf .= "\n";
1519
		if ($dhcpv6ifconf['numberoptions']['item']) {
1520
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1521
				$itemv6_value = base64_decode($itemv6['value']);
1522
				$dhcpdv6conf .= "	option custom-{$dhcpv6if}-{$itemv6idx} \"{$itemv6_value}\";\n";
1523
			}
1524
		}
1525

    
1526
		// ldap-server
1527
		if ($dhcpv6ifconf['ldap'] <> "") {
1528
			$ldapserver = $dhcpv6ifconf['ldap'];
1529
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1530
			    Net_IPv6::isInNetmask($ldapserver, '::', $pdlen)) {
1531
				$ldapserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ldapserver, $pdlen);
1532
			}
1533
			$dhcpdv6conf .= "	option ldap-server \"{$ldapserver}\";\n";
1534
		}
1535

    
1536
		// net boot information
1537
		if (isset($dhcpv6ifconf['netboot'])) {
1538
			if (!empty($dhcpv6ifconf['bootfile_url'])) {
1539
				$dhcpdv6conf .= "	option dhcp6.bootfile-url \"{$dhcpv6ifconf['bootfile_url']}\";\n";
1540
			}
1541
		}
1542

    
1543
		$dhcpdv6conf .= "}\n";
1544

    
1545
		/* add static mappings */
1546
		/* Needs to use DUID */
1547
		if (is_array($dhcpv6ifconf['staticmap'])) {
1548
			$i = 0;
1549
			foreach ($dhcpv6ifconf['staticmap'] as $sm) {
1550
				$dhcpdv6conf .= <<<EOD
1551
host s_{$dhcpv6if}_{$i} {
1552
	host-identifier option dhcp6.client-id {$sm['duid']};
1553

    
1554
EOD;
1555
				if ($sm['ipaddrv6']) {
1556
					$ipaddrv6 = $sm['ipaddrv6'];
1557
					if ($ifcfgv6['ipaddrv6'] == 'track6') {
1558
						$ipaddrv6 = merge_ipv6_delegated_prefix($ifcfgipv6, $ipaddrv6, $pdlen);
1559
					}
1560
					$dhcpdv6conf .= "	fixed-address6 {$ipaddrv6};\n";
1561
				}
1562

    
1563
				if ($sm['hostname']) {
1564
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1565
					$dhhostname = str_replace(".", "_", $dhhostname);
1566
					$dhcpdv6conf .= "	option host-name {$dhhostname};\n";
1567
					if (isset($dhcpv6ifconf['ddnsupdate']) &&
1568
					    isset($dhcpv6ifconf['ddnsforcehostname'])) {
1569
						$dhcpdv6conf .= "	ddns-hostname \"{$dhhostname}\";\n";
1570
					}
1571
				}
1572
				if ($sm['filename']) {
1573
					$dhcpdv6conf .= "	filename \"{$sm['filename']}\";\n";
1574
				}
1575

    
1576
				if ($sm['rootpath']) {
1577
					$dhcpdv6conf .= "	option root-path \"{$sm['rootpath']}\";\n";
1578
				}
1579

    
1580
				$dhcpdv6conf .= "}\n";
1581
				$i++;
1582
			}
1583
		}
1584

    
1585
		if ($dhcpv6ifconf['ddnsdomain']) {
1586
			$dhcpdv6conf .= dhcpdkey($dhcpv6ifconf);
1587
			$dhcpdv6conf .= dhcpdzones($ddns_zones);
1588
		}
1589

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

    
1608
	if ($nsupdate) {
1609
		$dhcpdv6conf .= "ddns-update-style interim;\n";
1610
	} else {
1611
		$dhcpdv6conf .= "ddns-update-style none;\n";
1612
	}
1613

    
1614
	/* write dhcpdv6.conf */
1615
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf", $dhcpdv6conf)) {
1616
		log_error("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1617
		if (platform_booting()) {
1618
			printf("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1619
		}
1620
		unset($dhcpdv6conf);
1621
		return 1;
1622
	}
1623
	unset($dhcpdv6conf);
1624

    
1625
	/* create an empty leases v6 database */
1626
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases")) {
1627
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1628
	}
1629

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

    
1634
	/* fire up dhcpd in a chroot */
1635
	if (count($dhcpdv6ifs) > 0) {
1636
		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 " .
1637
			join(" ", $dhcpdv6ifs));
1638
		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");
1639
	}
1640
	if (platform_booting()) {
1641
		print gettext("done.") . "\n";
1642
	}
1643

    
1644
	return 0;
1645
}
1646

    
1647
function services_igmpproxy_configure() {
1648
	global $config, $g;
1649

    
1650
	/* kill any running igmpproxy */
1651
	killbyname("igmpproxy");
1652

    
1653
	if (!is_array($config['igmpproxy']['igmpentry']) || (count($config['igmpproxy']['igmpentry']) == 0)) {
1654
		return 1;
1655
	}
1656

    
1657
	$iflist = get_configured_interface_list();
1658

    
1659
	$igmpconf = <<<EOD
1660

    
1661
##------------------------------------------------------
1662
## Enable Quickleave mode (Sends Leave instantly)
1663
##------------------------------------------------------
1664
quickleave
1665

    
1666
EOD;
1667

    
1668
	foreach ($config['igmpproxy']['igmpentry'] as $igmpcf) {
1669
		unset($iflist[$igmpcf['ifname']]);
1670
		$realif = get_real_interface($igmpcf['ifname']);
1671
		if (empty($igmpcf['threshold'])) {
1672
			$threshld = 1;
1673
		} else {
1674
			$threshld = $igmpcf['threshold'];
1675
		}
1676
		$igmpconf .= "phyint {$realif} {$igmpcf['type']} ratelimit 0 threshold {$threshld}\n";
1677

    
1678
		if ($igmpcf['address'] <> "") {
1679
			$item = explode(" ", $igmpcf['address']);
1680
			foreach ($item as $iww) {
1681
				$igmpconf .= "altnet {$iww}\n";
1682
			}
1683
		}
1684
		$igmpconf .= "\n";
1685
	}
1686
	foreach ($iflist as $ifn) {
1687
		$realif = get_real_interface($ifn);
1688
		$igmpconf .= "phyint {$realif} disabled\n";
1689
	}
1690
	$igmpconf .= "\n";
1691

    
1692
	$igmpfl = fopen($g['varetc_path'] . "/igmpproxy.conf", "w");
1693
	if (!$igmpfl) {
1694
		log_error(gettext("Could not write Igmpproxy configuration file!"));
1695
		return;
1696
	}
1697
	fwrite($igmpfl, $igmpconf);
1698
	fclose($igmpfl);
1699
	unset($igmpconf);
1700

    
1701
	if (isset($config['syslog']['igmpxverbose'])) {
1702
		mwexec_bg("/usr/local/sbin/igmpproxy -v {$g['varetc_path']}/igmpproxy.conf");
1703
	} else {
1704
		mwexec_bg("/usr/local/sbin/igmpproxy {$g['varetc_path']}/igmpproxy.conf");
1705
	}
1706

    
1707
	log_error(gettext("Started IGMP proxy service."));
1708

    
1709
	return 0;
1710
}
1711

    
1712
function services_dhcrelay_configure() {
1713
	global $config, $g;
1714

    
1715
	if (isset($config['system']['developerspew'])) {
1716
		$mt = microtime();
1717
		echo "services_dhcrelay_configure() being called $mt\n";
1718
	}
1719

    
1720
	/* kill any running dhcrelay */
1721
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
1722

    
1723
	$dhcrelaycfg =& $config['dhcrelay'];
1724

    
1725
	/* DHCPRelay enabled on any interfaces? */
1726
	if (!isset($dhcrelaycfg['enable'])) {
1727
		return 0;
1728
	}
1729

    
1730
	if (platform_booting()) {
1731
		echo gettext("Starting DHCP relay service...");
1732
	} else {
1733
		sleep(1);
1734
	}
1735

    
1736
	$iflist = get_configured_interface_list();
1737

    
1738
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1739
	foreach ($dhcifaces as $dhcrelayif) {
1740
		if (!isset($iflist[$dhcrelayif]) ||
1741
		    link_interface_to_bridge($dhcrelayif)) {
1742
			continue;
1743
		}
1744

    
1745
		if (is_ipaddr(get_interface_ip($dhcrelayif))) {
1746
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1747
		}
1748
	}
1749

    
1750
	/*
1751
	 * In order for the relay to work, it needs to be active
1752
	 * on the interface in which the destination server sits.
1753
	 */
1754
	$srvips = explode(",", $dhcrelaycfg['server']);
1755
	if (!is_array($srvips)) {
1756
		log_error(gettext("No destination IP has been configured!"));
1757
		return;
1758
	}
1759

    
1760
	foreach ($srvips as $srcidx => $srvip) {
1761
		unset($destif);
1762
		foreach ($iflist as $ifname) {
1763
			$subnet = get_interface_ip($ifname);
1764
			if (!is_ipaddr($subnet)) {
1765
				continue;
1766
			}
1767
			$subnet .= "/" . get_interface_subnet($ifname);
1768
			if (ip_in_subnet($srvip, $subnet)) {
1769
				$destif = get_real_interface($ifname);
1770
				break;
1771
			}
1772
		}
1773
		if (!isset($destif)) {
1774
			// For each enabled static route
1775
			foreach (get_staticroutes(false, false, true) as $rtent) {
1776
				if (ip_in_subnet($srvip, $rtent['network'])) {
1777
					$a_gateways = return_gateways_array(true);
1778
					$destif = $a_gateways[$rtent['gateway']]['interface'];
1779
					break;
1780
				}
1781
			}
1782
		}
1783

    
1784
		if (!isset($destif)) {
1785
			/* Create a array from the existing route table */
1786
			exec("/usr/bin/netstat -rnWf inet", $route_str);
1787
			array_shift($route_str);
1788
			array_shift($route_str);
1789
			array_shift($route_str);
1790
			array_shift($route_str);
1791
			$route_arr = array();
1792
			foreach ($route_str as $routeline) {
1793
				$items = preg_split("/[ ]+/i", $routeline);
1794
				if (is_subnetv4($items[0])) {
1795
					$subnet = $items[0];
1796
				} elseif (is_ipaddrv4($items[0])) {
1797
					$subnet = "{$items[0]}/32";
1798
				} else {
1799
					// Not a subnet or IP address, skip to the next line.
1800
					continue;
1801
				}
1802
				if (ip_in_subnet($srvip, $subnet)) {
1803
					$destif = trim($items[6]);
1804
					break;
1805
				}
1806
			}
1807
		}
1808

    
1809
		if (!isset($destif)) {
1810
			if (is_array($config['gateways']['gateway_item'])) {
1811
				foreach ($config['gateways']['gateway_item'] as $gateway) {
1812
					if (isset($gateway['defaultgw'])) {
1813
						$destif = get_real_interface($gateway['interface']);
1814
						break;
1815
					}
1816
				}
1817
			} else {
1818
				$destif = get_real_interface("wan");
1819
			}
1820
		}
1821

    
1822
		if (!empty($destif)) {
1823
			$dhcrelayifs[] = $destif;
1824
		}
1825
	}
1826
	$dhcrelayifs = array_unique($dhcrelayifs);
1827

    
1828
	/* fire up dhcrelay */
1829
	if (empty($dhcrelayifs)) {
1830
		log_error(gettext("No suitable interface found for running dhcrelay!"));
1831
		return; /* XXX */
1832
	}
1833

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

    
1836
	if (isset($dhcrelaycfg['agentoption'])) {
1837
		$cmd .= " -a -m replace";
1838
	}
1839

    
1840
	$cmd .= " " . implode(" ", $srvips);
1841
	mwexec($cmd);
1842
	unset($cmd);
1843

    
1844
	return 0;
1845
}
1846

    
1847
function services_dhcrelay6_configure() {
1848
	global $config, $g;
1849

    
1850
	if (isset($config['system']['developerspew'])) {
1851
		$mt = microtime();
1852
		echo "services_dhcrelay6_configure() being called $mt\n";
1853
	}
1854

    
1855
	/* kill any running dhcrelay */
1856
	killbypid("{$g['varrun_path']}/dhcrelay6.pid");
1857

    
1858
	$dhcrelaycfg =& $config['dhcrelay6'];
1859

    
1860
	/* DHCPv6 Relay enabled on any interfaces? */
1861
	if (!isset($dhcrelaycfg['enable'])) {
1862
		return 0;
1863
	}
1864

    
1865
	if (platform_booting()) {
1866
		echo gettext("Starting DHCPv6 relay service...");
1867
	} else {
1868
		sleep(1);
1869
	}
1870

    
1871
	$iflist = get_configured_interface_list();
1872

    
1873
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1874
	foreach ($dhcifaces as $dhcrelayif) {
1875
		if (!isset($iflist[$dhcrelayif]) ||
1876
		    link_interface_to_bridge($dhcrelayif)) {
1877
			continue;
1878
		}
1879

    
1880
		if (is_ipaddrv6(get_interface_ipv6($dhcrelayif))) {
1881
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1882
		}
1883
	}
1884
	$dhcrelayifs = array_unique($dhcrelayifs);
1885

    
1886
	/*
1887
	 * In order for the relay to work, it needs to be active
1888
	 * on the interface in which the destination server sits.
1889
	 */
1890
	$srvips = explode(",", $dhcrelaycfg['server']);
1891
	$srvifaces = array();
1892
	foreach ($srvips as $srcidx => $srvip) {
1893
		unset($destif);
1894
		foreach ($iflist as $ifname) {
1895
			$subnet = get_interface_ipv6($ifname);
1896
			if (!is_ipaddrv6($subnet)) {
1897
				continue;
1898
			}
1899
			$subnet .= "/" . get_interface_subnetv6($ifname);
1900
			if (ip_in_subnet($srvip, $subnet)) {
1901
				$destif = get_real_interface($ifname);
1902
				break;
1903
			}
1904
		}
1905
		if (!isset($destif)) {
1906
			if (is_array($config['staticroutes']['route'])) {
1907
				foreach ($config['staticroutes']['route'] as $rtent) {
1908
					if (isset($rtent['disabled'])) {
1909
						continue;
1910
					}
1911
					if (ip_in_subnet($srvip, $rtent['network'])) {
1912
						$a_gateways = return_gateways_array(true);
1913
						$destif = $a_gateways[$rtent['gateway']]['interface'];
1914
						break;
1915
					}
1916
				}
1917
			}
1918
		}
1919

    
1920
		if (!isset($destif)) {
1921
			/* Create a array from the existing route table */
1922
			exec("/usr/bin/netstat -rnWf inet6", $route_str);
1923
			array_shift($route_str);
1924
			array_shift($route_str);
1925
			array_shift($route_str);
1926
			array_shift($route_str);
1927
			$route_arr = array();
1928
			foreach ($route_str as $routeline) {
1929
				$items = preg_split("/[ ]+/i", $routeline);
1930
				if (ip_in_subnet($srvip, $items[0])) {
1931
					$destif = trim($items[6]);
1932
					break;
1933
				}
1934
			}
1935
		}
1936

    
1937
		if (!isset($destif)) {
1938
			if (is_array($config['gateways']['gateway_item'])) {
1939
				foreach ($config['gateways']['gateway_item'] as $gateway) {
1940
					if (isset($gateway['defaultgw'])) {
1941
						$destif = get_real_interface($gateway['interface']);
1942
						break;
1943
					}
1944
				}
1945
			} else {
1946
				$destif = get_real_interface("wan");
1947
			}
1948
		}
1949

    
1950
		if (!empty($destif)) {
1951
			$srvifaces[] = "{$srvip}%{$destif}";
1952
		}
1953
	}
1954

    
1955
	/* fire up dhcrelay */
1956
	if (empty($dhcrelayifs) || empty($srvifaces)) {
1957
		log_error(gettext("No suitable interface found for running dhcrelay -6!"));
1958
		return; /* XXX */
1959
	}
1960

    
1961
	$cmd = "/usr/local/sbin/dhcrelay -6 -pf \"{$g['varrun_path']}/dhcrelay6.pid\"";
1962
	foreach ($dhcrelayifs as $dhcrelayif) {
1963
		$cmd .= " -l {$dhcrelayif}";
1964
	}
1965
	foreach ($srvifaces as $srviface) {
1966
		$cmd .= " -u \"{$srviface}\"";
1967
	}
1968
	mwexec($cmd);
1969
	unset($cmd);
1970

    
1971
	return 0;
1972
}
1973

    
1974
function services_dyndns_configure_client($conf) {
1975

    
1976
	if (!isset($conf['enable'])) {
1977
		return;
1978
	}
1979

    
1980
	/* load up the dyndns.class */
1981
	require_once("dyndns.class");
1982

    
1983
	$dns = new updatedns($dnsService = $conf['type'],
1984
		$dnsHost = $conf['host'],
1985
		$dnsDomain = $conf['domainname'],
1986
		$dnsUser = $conf['username'],
1987
		$dnsPass = $conf['password'],
1988
		$dnsWildcard = $conf['wildcard'],
1989
		$dnsProxied = $conf['proxied'],
1990
		$dnsMX = $conf['mx'],
1991
		$dnsIf = "{$conf['interface']}",
1992
		$dnsBackMX = NULL,
1993
		$dnsServer = NULL,
1994
		$dnsPort = NULL,
1995
		$dnsUpdateURL = "{$conf['updateurl']}",
1996
		$forceUpdate = $conf['force'],
1997
		$dnsZoneID = $conf['zoneid'],
1998
		$dnsTTL = $conf['ttl'],
1999
		$dnsResultMatch = "{$conf['resultmatch']}",
2000
		$dnsRequestIf = "{$conf['requestif']}",
2001
		$dnsID = "{$conf['id']}",
2002
		$dnsVerboseLog = $conf['verboselog'],
2003
		$curlIpresolveV4 = $conf['curl_ipresolve_v4'],
2004
		$curlSslVerifypeer = $conf['curl_ssl_verifypeer']);
2005
}
2006

    
2007
function services_dyndns_configure($int = "") {
2008
	global $config, $g;
2009
	if (isset($config['system']['developerspew'])) {
2010
		$mt = microtime();
2011
		echo "services_dyndns_configure() being called $mt\n";
2012
	}
2013

    
2014
	$dyndnscfg = $config['dyndnses']['dyndns'];
2015
	$gwgroups = return_gateway_groups_array();
2016
	if (is_array($dyndnscfg)) {
2017
		if (platform_booting()) {
2018
			echo gettext("Starting DynDNS clients...");
2019
		}
2020

    
2021
		foreach ($dyndnscfg as $dyndns) {
2022
			/*
2023
			 * If it's using a gateway group, check if interface is
2024
			 * the active gateway for that group
2025
			 */
2026
			$group_int = '';
2027
			$friendly_group_int = '';
2028
			if (is_array($gwgroups[$dyndns['interface']])) {
2029
				if (!empty($gwgroups[$dyndns['interface']][0]['vip'])) {
2030
					$group_int = $gwgroups[$dyndns['interface']][0]['vip'];
2031
				} else {
2032
					$group_int = $gwgroups[$dyndns['interface']][0]['int'];
2033
					$friendly_group_int =
2034
					    convert_real_interface_to_friendly_interface_name(
2035
						$group_int);
2036
				}
2037
			}
2038
			if ((empty($int)) || ($int == $dyndns['interface']) ||
2039
			    ($int == $group_int) || ($int == $friendly_group_int)) {
2040
				$dyndns['verboselog'] = isset($dyndns['verboselog']);
2041
				$dyndns['curl_ipresolve_v4'] = isset($dyndns['curl_ipresolve_v4']);
2042
				$dyndns['curl_ssl_verifypeer'] = isset($dyndns['curl_ssl_verifypeer']);
2043
				services_dyndns_configure_client($dyndns);
2044
				sleep(1);
2045
			}
2046
		}
2047

    
2048
		if (platform_booting()) {
2049
			echo gettext("done.") . "\n";
2050
		}
2051
	}
2052

    
2053
	return 0;
2054
}
2055

    
2056
function dyndnsCheckIP($int) {
2057
	global $config, $factory_default_checkipservice;
2058
	$ip_address = get_interface_ip($int);
2059
	if (is_private_ip($ip_address)) {
2060
		$gateways_status = return_gateways_status(true);
2061
		// If the gateway for this interface is down, then the external check cannot work.
2062
		// Avoid the long wait for the external check to timeout.
2063
		if (stristr($gateways_status[$config['interfaces'][$int]['gateway']]['status'], "down")) {
2064
			return "down";
2065
		}
2066

    
2067
		// Append the factory default check IP service to the list (if not disabled).
2068
		if (!isset($config['checkipservices']['disable_factory_default'])) {
2069
			$config['checkipservices']['checkipservice'][] = $factory_default_checkipservice;
2070
		}
2071

    
2072
		// Use the first enabled check IP service as the default.
2073
		if (is_array($config['checkipservices']['checkipservice'])) {
2074
			foreach ($config['checkipservices']['checkipservice'] as $i => $checkipservice) {
2075
				if (isset($checkipservice['enable'])) {
2076
					$url = $checkipservice['url'];
2077
					$username = $checkipservice['username'];
2078
					$password = $checkipservice['password'];
2079
					$verifysslpeer = isset($checkipservice['verifysslpeer']);
2080
					break;
2081
				}
2082
			}
2083
		}
2084

    
2085
		$hosttocheck = $url;
2086
		$ip_ch = curl_init($hosttocheck);
2087
		curl_setopt($ip_ch, CURLOPT_RETURNTRANSFER, 1);
2088
		curl_setopt($ip_ch, CURLOPT_SSL_VERIFYPEER, $verifysslpeer);
2089
		curl_setopt($ip_ch, CURLOPT_INTERFACE, 'host!' . $ip_address);
2090
		curl_setopt($ip_ch, CURLOPT_CONNECTTIMEOUT, '30');
2091
		curl_setopt($ip_ch, CURLOPT_TIMEOUT, 120);
2092
		curl_setopt($ip_ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
2093
		curl_setopt($ip_ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
2094
		curl_setopt($ip_ch, CURLOPT_USERPWD, "{$username}:{$password}");
2095
		$ip_result_page = curl_exec($ip_ch);
2096
		curl_close($ip_ch);
2097
		$ip_result_decoded = urldecode($ip_result_page);
2098
		preg_match('=Current IP Address: (.*)</body>=siU', $ip_result_decoded, $matches);
2099
		$ip_address = trim($matches[1]);
2100
	}
2101
	return $ip_address;
2102
}
2103

    
2104
function services_dnsmasq_configure($restart_dhcp = true) {
2105
	global $config, $g;
2106
	$return = 0;
2107

    
2108
	// hard coded args: will be removed to avoid duplication if specified in custom_options
2109
	$standard_args = array(
2110
		"dns-forward-max" => "--dns-forward-max=5000",
2111
		"cache-size" => "--cache-size=10000",
2112
		"local-ttl" => "--local-ttl=1"
2113
	);
2114

    
2115

    
2116
	if (isset($config['system']['developerspew'])) {
2117
		$mt = microtime();
2118
		echo "services_dnsmasq_configure() being called $mt\n";
2119
	}
2120

    
2121
	/* kill any running dnsmasq */
2122
	if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) {
2123
		sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
2124
	}
2125

    
2126
	if (isset($config['dnsmasq']['enable'])) {
2127

    
2128
		if (platform_booting()) {
2129
			echo gettext("Starting DNS forwarder...");
2130
		} else {
2131
			sleep(1);
2132
		}
2133

    
2134
		/* generate hosts file */
2135
		if (system_hosts_generate() != 0) {
2136
			$return = 1;
2137
		}
2138

    
2139
		$args = "";
2140

    
2141
		if (isset($config['dnsmasq']['regdhcp'])) {
2142
			$args .= " --dhcp-hostsfile={$g['etc_path']}/hosts ";
2143
		}
2144

    
2145
		/* Setup listen port, if non-default */
2146
		if (is_port($config['dnsmasq']['port'])) {
2147
			$args .= " --port={$config['dnsmasq']['port']} ";
2148
		}
2149

    
2150
		$listen_addresses = "";
2151
		if (isset($config['dnsmasq']['interface'])) {
2152
			$interfaces = explode(",", $config['dnsmasq']['interface']);
2153
			foreach ($interfaces as $interface) {
2154
				$if = get_real_interface($interface);
2155
				if (does_interface_exist($if)) {
2156
					$laddr = get_interface_ip($interface);
2157
					if (is_ipaddrv4($laddr)) {
2158
						$listen_addresses .= " --listen-address={$laddr} ";
2159
					}
2160
					$laddr6 = get_interface_ipv6($interface);
2161
					if (is_ipaddrv6($laddr6) && !isset($config['dnsmasq']['strictbind'])) {
2162
						/*
2163
						 * XXX: Since dnsmasq does not support link-local address
2164
						 * with scope specified. These checks are being done.
2165
						 */
2166
						if (is_linklocal($laddr6) && strstr($laddr6, "%")) {
2167
							$tmpaddrll6 = explode("%", $laddr6);
2168
							$listen_addresses .= " --listen-address={$tmpaddrll6[0]} ";
2169
						} else {
2170
							$listen_addresses .= " --listen-address={$laddr6} ";
2171
						}
2172
					}
2173
				}
2174
			}
2175
			if (!empty($listen_addresses)) {
2176
				$args .= " {$listen_addresses} ";
2177
				if (isset($config['dnsmasq']['strictbind'])) {
2178
					$args .= " --bind-interfaces ";
2179
				}
2180
			}
2181
		}
2182

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

    
2190
			// Build an array of domain overrides to help in checking for matches.
2191
			$override_a = array();
2192
			if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2193
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2194
					$override_a[$override['domain']] = "y";
2195
				}
2196
			}
2197

    
2198
			// Build an array of the private reverse lookup domain names
2199
			$reverse_domain_a = array("10.in-addr.arpa", "168.192.in-addr.arpa");
2200
			// Unfortunately the 172.16.0.0/12 range does not map nicely to the in-addr.arpa scheme.
2201
			for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) {
2202
				$reverse_domain_a[] = "$subnet_num.172.in-addr.arpa";
2203
			}
2204

    
2205
			// Set the --server parameter to nowhere for each reverse domain name that was not specifically specified in a domain override.
2206
			foreach ($reverse_domain_a as $reverse_domain) {
2207
				if (!isset($override_a[$reverse_domain])) {
2208
					$args .= " --server=/$reverse_domain/ ";
2209
				}
2210
			}
2211
			unset($override_a);
2212
			unset($reverse_domain_a);
2213
		}
2214

    
2215
		/* Setup forwarded domains */
2216
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2217
			foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2218
				if ($override['ip'] == "!") {
2219
					$override[ip] = "";
2220
				}
2221
				$args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
2222
			}
2223
		}
2224

    
2225
		/* Allow DNS Rebind for forwarded domains */
2226
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2227
			if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2228
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2229
					$args .= ' --rebind-domain-ok=/' . $override['domain'] . '/ ';
2230
				}
2231
			}
2232
		}
2233

    
2234
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2235
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2236
		}
2237

    
2238
		if (isset($config['dnsmasq']['strict_order'])) {
2239
			$args .= " --strict-order ";
2240
		}
2241

    
2242
		if (isset($config['dnsmasq']['domain_needed'])) {
2243
			$args .= " --domain-needed ";
2244
		}
2245

    
2246
		if ($config['dnsmasq']['custom_options']) {
2247
			foreach (preg_split('/\s+/', $config['dnsmasq']['custom_options']) as $c) {
2248
				$args .= " " . escapeshellarg("--{$c}");
2249
				$p = explode('=', $c);
2250
				if (array_key_exists($p[0], $standard_args)) {
2251
					unset($standard_args[$p[0]]);
2252
				}
2253
			}
2254
		}
2255
		$args .= ' ' . implode(' ', array_values($standard_args));
2256

    
2257
		/* run dnsmasq. Use "-C /dev/null" since we use command line args only (Issue #6730) */
2258
		$cmd = "/usr/local/sbin/dnsmasq --all-servers -C /dev/null {$dns_rebind} {$args}";
2259
		//log_error("dnsmasq command: {$cmd}");
2260
		mwexec_bg($cmd);
2261
		unset($args);
2262

    
2263
		system_dhcpleases_configure();
2264

    
2265
		if (platform_booting()) {
2266
			echo gettext("done.") . "\n";
2267
		}
2268
	}
2269

    
2270
	if (!platform_booting() && $restart_dhcp) {
2271
		if (services_dhcpd_configure() != 0) {
2272
			$return = 1;
2273
		}
2274
	}
2275

    
2276
	return $return;
2277
}
2278

    
2279
function services_unbound_configure($restart_dhcp = true) {
2280
	global $config, $g;
2281
	$return = 0;
2282

    
2283
	if (isset($config['system']['developerspew'])) {
2284
		$mt = microtime();
2285
		echo "services_unbound_configure() being called $mt\n";
2286
	}
2287

    
2288
	if (isset($config['unbound']['enable'])) {
2289
		require_once('/etc/inc/unbound.inc');
2290

    
2291
		/* Stop Unbound using TERM */
2292
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2293
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
2294
		}
2295

    
2296
		/* If unbound is still running, wait up to 30 seconds for it to terminate. */
2297
		for ($i=1; $i <= 30; $i++) {
2298
			if (is_process_running('unbound')) {
2299
				sleep(1);
2300
			}
2301
		}
2302

    
2303
		if (platform_booting()) {
2304
			echo gettext("Starting DNS Resolver...");
2305
		} else {
2306
			sleep(1);
2307
		}
2308

    
2309
		/* generate hosts file */
2310
		if (system_hosts_generate() != 0) {
2311
			$return = 1;
2312
		}
2313

    
2314
		/* Check here for dhcp6 complete - wait upto 10 seconds */
2315
		if($config['interfaces']["wan"]['ipaddrv6'] == 'dhcp6') {
2316
			$wanif = get_real_interface("wan", "inet6");
2317
			if (platform_booting()) {
2318
				for ($i=1; $i <= 10; $i++) {
2319
					if (!file_exists("/tmp/{$wanif}_dhcp6_complete")) { 
2320
						log_error(gettext("Unbound start waiting on dhcp6c."));
2321
						sleep(1);
2322
					} else {
2323
						unlink_if_exists("/tmp/{$wanif}_dhcp6_complete");
2324
						log_error(gettext("dhcp6 init complete. Continuing"));
2325
						break;
2326
					}						
2327
				}
2328
			}
2329
		}
2330
		
2331
		sync_unbound_service();
2332
		if (platform_booting()) {
2333
			log_error(gettext("sync unbound done."));
2334
			echo gettext("done.") . "\n";
2335
		}
2336

    
2337
		system_dhcpleases_configure();
2338
	} else {
2339
		/* kill Unbound since it should not be enabled */
2340
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2341
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "KILL");
2342
		}
2343
	}
2344

    
2345
	if (!platform_booting() && $restart_dhcp) {
2346
		if (services_dhcpd_configure() != 0) {
2347
			$return = 1;
2348
		}
2349
	}
2350

    
2351
	return $return;
2352
}
2353

    
2354
function services_snmpd_configure() {
2355
	global $config, $g;
2356
	if (isset($config['system']['developerspew'])) {
2357
		$mt = microtime();
2358
		echo "services_snmpd_configure() being called $mt\n";
2359
	}
2360

    
2361
	/* kill any running snmpd */
2362
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
2363
	sleep(2);
2364
	if (is_process_running("bsnmpd")) {
2365
		mwexec("/usr/bin/killall bsnmpd", true);
2366
	}
2367

    
2368
	if (isset($config['snmpd']['enable'])) {
2369

    
2370
		if (platform_booting()) {
2371
			echo gettext("Starting SNMP daemon... ");
2372
		}
2373

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

    
2379
		/* generate snmpd.conf */
2380
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
2381
		if (!$fd) {
2382
			printf(gettext("Error: cannot open snmpd.conf in services_snmpd_configure().%s"), "\n");
2383
			return 1;
2384
		}
2385

    
2386

    
2387
		$snmpdconf = <<<EOD
2388
location := "{$config['snmpd']['syslocation']}"
2389
contact := "{$config['snmpd']['syscontact']}"
2390
read := "{$config['snmpd']['rocommunity']}"
2391

    
2392
EOD;
2393

    
2394
/* No docs on what write strings do there so disable for now.
2395
		if (isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])) {
2396
			$snmpdconf .= <<<EOD
2397
# write string
2398
write := "{$config['snmpd']['rwcommunity']}"
2399

    
2400
EOD;
2401
		}
2402
*/
2403

    
2404

    
2405
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2406
			$snmpdconf .= <<<EOD
2407
# SNMP Trap support.
2408
traphost := {$config['snmpd']['trapserver']}
2409
trapport := {$config['snmpd']['trapserverport']}
2410
trap := "{$config['snmpd']['trapstring']}"
2411

    
2412

    
2413
EOD;
2414
		}
2415

    
2416
		$sysDescr = "{$g['product_name']} " . php_uname("n") .
2417
			" {$g['product_version']} {$g['platform']} " . php_uname("s") .
2418
			" " . php_uname("r") . " " . php_uname("m");
2419

    
2420
		$snmpdconf .= <<<EOD
2421
system := 1     # pfSense
2422
%snmpd
2423
sysDescr			= "{$sysDescr}"
2424
begemotSnmpdDebugDumpPdus       = 2
2425
begemotSnmpdDebugSyslogPri      = 7
2426
begemotSnmpdCommunityString.0.1 = $(read)
2427

    
2428
EOD;
2429

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

    
2435
EOD;
2436
		}
2437
*/
2438

    
2439

    
2440
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2441
			$snmpdconf .= <<<EOD
2442
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
2443
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
2444
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
2445

    
2446
EOD;
2447
		}
2448

    
2449

    
2450
		$snmpdconf .= <<<EOD
2451
begemotSnmpdCommunityDisable    = 1
2452

    
2453
EOD;
2454

    
2455
		$bind_to_ips = array();
2456
		if (isset($config['snmpd']['bindip'])) {
2457
			foreach (explode(",", $config['snmpd']['bindip']) as $bind_to_ip) {
2458
				if (is_ipaddr($bind_to_ip)) {
2459
					$bind_to_ips[] = $bind_to_ip;
2460
				} else {
2461
					$if = get_real_interface($bind_to_ip);
2462
					if (does_interface_exist($if)) {
2463
						$bindip = get_interface_ip($bind_to_ip);
2464
						if (is_ipaddr($bindip)) {
2465
							$bind_to_ips[] = $bindip;
2466
						}
2467
					}
2468
				}
2469
			}
2470
		}
2471
		if (!count($bind_to_ips)) {
2472
			$bind_to_ips = array("0.0.0.0");
2473
		}
2474

    
2475
		if (is_port($config['snmpd']['pollport'])) {
2476
			foreach ($bind_to_ips as $bind_to_ip) {
2477
				$snmpdconf .= <<<EOD
2478
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
2479

    
2480
EOD;
2481

    
2482
			}
2483
		}
2484

    
2485
		$snmpdconf .= <<<EOD
2486
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
2487
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
2488

    
2489
# These are bsnmp macros not php vars.
2490
sysContact      = $(contact)
2491
sysLocation     = $(location)
2492
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
2493

    
2494
snmpEnableAuthenTraps = 2
2495

    
2496
EOD;
2497

    
2498
		if (is_array($config['snmpd']['modules'])) {
2499
			if (isset($config['snmpd']['modules']['mibii'])) {
2500
			$snmpdconf .= <<<EOD
2501
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
2502

    
2503
EOD;
2504
			}
2505

    
2506
			if (isset($config['snmpd']['modules']['netgraph'])) {
2507
				$snmpdconf .= <<<EOD
2508
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
2509
%netgraph
2510
begemotNgControlNodeName = "snmpd"
2511

    
2512
EOD;
2513
			}
2514

    
2515
			if (isset($config['snmpd']['modules']['pf'])) {
2516
				$snmpdconf .= <<<EOD
2517
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
2518

    
2519
EOD;
2520
			}
2521

    
2522
			if (isset($config['snmpd']['modules']['hostres'])) {
2523
				$snmpdconf .= <<<EOD
2524
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
2525

    
2526
EOD;
2527
			}
2528

    
2529
			if (isset($config['snmpd']['modules']['bridge'])) {
2530
				$snmpdconf .= <<<EOD
2531
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
2532
# config must end with blank line
2533

    
2534
EOD;
2535
			}
2536
			if (isset($config['snmpd']['modules']['ucd'])) {
2537
				$snmpdconf .= <<<EOD
2538
begemotSnmpdModulePath."ucd"     = "/usr/local/lib/snmp_ucd.so"
2539

    
2540
EOD;
2541
			}
2542
			if (isset($config['snmpd']['modules']['regex'])) {
2543
				$snmpdconf .= <<<EOD
2544
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"
2545

    
2546
EOD;
2547
			}
2548
		}
2549

    
2550
		fwrite($fd, $snmpdconf);
2551
		fclose($fd);
2552
		unset($snmpdconf);
2553

    
2554
		/* run bsnmpd */
2555
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
2556
			" -p {$g['varrun_path']}/snmpd.pid");
2557

    
2558
		if (platform_booting()) {
2559
			echo gettext("done.") . "\n";
2560
		}
2561
	}
2562

    
2563
	return 0;
2564
}
2565

    
2566
function services_dnsupdate_process($int = "", $updatehost = "", $forced = false) {
2567
	global $config, $g;
2568
	if (isset($config['system']['developerspew'])) {
2569
		$mt = microtime();
2570
		echo "services_dnsupdate_process() being called $mt\n";
2571
	}
2572

    
2573
	/* Dynamic DNS updating active? */
2574
	if (!is_array($config['dnsupdates']['dnsupdate'])) {
2575
		return 0;
2576
	}
2577

    
2578
	$notify_text = "";
2579
	$gwgroups = return_gateway_groups_array();
2580
	foreach ($config['dnsupdates']['dnsupdate'] as $i => $dnsupdate) {
2581
		if (!isset($dnsupdate['enable'])) {
2582
			continue;
2583
		}
2584
		/*
2585
		 * If it's using a gateway group, check if interface is
2586
		 * the active gateway for that group
2587
		 */
2588
		$group_int = '';
2589
		$friendly_group_int = '';
2590
		if (is_array($gwgroups[$dnsupdate['interface']])) {
2591
			if (!empty($gwgroups[$dnsupdate['interface']][0]['vip'])) {
2592
				$group_int = $gwgroups[$dnsupdate['interface']][0]['vip'];
2593
			} else {
2594
				$group_int = $gwgroups[$dnsupdate['interface']][0]['int'];
2595
				$friendly_group_int =
2596
				    convert_real_interface_to_friendly_interface_name(
2597
					$group_int);
2598
			}
2599
		}
2600
		if (!empty($int) && ($int != $dnsupdate['interface']) &&
2601
		    ($int != $group_int) && ($int != $friendly_group_int)) {
2602
			continue;
2603
		}
2604
		if (!empty($updatehost) && ($updatehost != $dnsupdate['host'])) {
2605
			continue;
2606
		}
2607

    
2608
		/* determine interface name */
2609
		$if = get_failover_interface($dnsupdate['interface']);
2610

    
2611
		if (isset($dnsupdate['usepublicip'])) {
2612
			$wanip = dyndnsCheckIP($if);
2613
			$bindip = get_interface_ip($if);
2614
		} else {
2615
			$wanip = get_interface_ip($if);
2616
			$bindip = $wanip;
2617
		}
2618

    
2619
		$wanipv6 = get_interface_ipv6($if);
2620
		$cacheFile = $g['conf_path'] .
2621
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2622
		    escapeshellarg($dnsupdate['host']) .
2623
		    "_{$dnsupdate['server']}.cache";
2624
		$cacheFilev6 = $g['conf_path'] .
2625
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2626
		    escapeshellarg($dnsupdate['host']) .
2627
		    "_{$dnsupdate['server']}_v6.cache";
2628
		$currentTime = time();
2629

    
2630
		if (!$wanip && !$wanipv6) {
2631
			continue;
2632
		}
2633

    
2634
		$keyname = $dnsupdate['keyname'];
2635
		/* trailing dot */
2636
		if (substr($keyname, -1) != ".") {
2637
			$keyname .= ".";
2638
		}
2639

    
2640
		$hostname = $dnsupdate['host'];
2641
		/* trailing dot */
2642
		if (substr($hostname, -1) != ".") {
2643
			$hostname .= ".";
2644
		}
2645

    
2646
		/*
2647
		 * write private key file
2648
		 * this is dumb - public and private keys are the same for
2649
		 * HMAC-MD5, but nsupdate insists on having both
2650
		 */
2651
		$fd = fopen($g['varetc_path'] .
2652
		    "/K{$i}{$keyname}+157+00000.private", "w");
2653
		$privkey = <<<EOD
2654
Private-key-format: v1.2
2655
Algorithm: 157 (HMAC)
2656
Key: {$dnsupdate['keydata']}
2657

    
2658
EOD;
2659
		fwrite($fd, $privkey);
2660
		fclose($fd);
2661

    
2662
		/* write public key file */
2663
		if ($dnsupdate['keytype'] == "zone") {
2664
			$flags = 257;
2665
			$proto = 3;
2666
		} else if ($dnsupdate['keytype'] == "host") {
2667
			$flags = 513;
2668
			$proto = 3;
2669
		} else if ($dnsupdate['keytype'] == "user") {
2670
			$flags = 0;
2671
			$proto = 2;
2672
		}
2673

    
2674
		$fd = fopen($g['varetc_path'] .
2675
		    "/K{$i}{$keyname}+157+00000.key", "w");
2676
		fwrite($fd, "{$keyname} IN KEY {$flags} {$proto} 157 " .
2677
		    "{$dnsupdate['keydata']}\n");
2678
		fclose($fd);
2679

    
2680
		/* generate update instructions */
2681
		$upinst = "";
2682
		if (!empty($dnsupdate['server'])) {
2683
			$upinst .= "server {$dnsupdate['server']}\n";
2684
		}
2685

    
2686
		$cachedipv4 = '';
2687
		$cacheTimev4 = 0;
2688
		if (file_exists($cacheFile)) {
2689
			list($cachedipv4, $cacheTimev4) = explode("|",
2690
			    file_get_contents($cacheFile));
2691
		}
2692
		$cachedipv6 = '';
2693
		$cacheTimev6 = 0;
2694
		if (file_exists($cacheFilev6)) {
2695
			list($cachedipv6, $cacheTimev6) = explode("|",
2696
			    file_get_contents($cacheFilev6));
2697
		}
2698

    
2699
		// 25 Days
2700
		$maxCacheAgeSecs = 25 * 24 * 60 * 60;
2701
		$need_update = false;
2702

    
2703
		/* Update IPv4 if we have it. */
2704
		if (is_ipaddrv4($wanip) && $dnsupdate['recordtype'] != "AAAA") {
2705
			if (($wanip != $cachedipv4) || $forced ||
2706
			    (($currentTime - $cacheTimev4) > $maxCacheAgeSecs)) {
2707
				$upinst .= "update delete " .
2708
				    "{$dnsupdate['host']}. A\n";
2709
				$upinst .= "update add {$dnsupdate['host']}. " .
2710
				    "{$dnsupdate['ttl']} A {$wanip}\n";
2711
				$upinst .= "local {$bindip}\n";
2712
				$need_update = true;
2713
			} else {
2714
				log_error(sprintf(gettext(
2715
				    "phpDynDNS: Not updating %s A record because the IP address has not changed."),
2716
				    $dnsupdate['host']));
2717
			}
2718
		} else {
2719
			@unlink($cacheFile);
2720
			unset($cacheFile);
2721
		}
2722

    
2723
		/* Update IPv6 if we have it. */
2724
		if (is_ipaddrv6($wanipv6) && $dnsupdate['recordtype'] != "A") {
2725
			if (($wanipv6 != $cachedipv6) || $forced ||
2726
			    (($currentTime - $cacheTimev6) > $maxCacheAgeSecs)) {
2727
				$upinst .= "update delete " .
2728
				    "{$dnsupdate['host']}. AAAA\n";
2729
				$upinst .= "update add {$dnsupdate['host']}. " .
2730
				    "{$dnsupdate['ttl']} AAAA {$wanipv6}\n";
2731
				$need_update = true;
2732
			} else {
2733
				log_error(sprintf(gettext(
2734
				    "phpDynDNS: Not updating %s AAAA record because the IPv6 address has not changed."),
2735
				    $dnsupdate['host']));
2736
			}
2737
		} else {
2738
			@unlink($cacheFilev6);
2739
			unset($cacheFilev6);
2740
		}
2741

    
2742
		$upinst .= "\n";	/* mind that trailing newline! */
2743

    
2744
		if (!$need_update) {
2745
			continue;
2746
		}
2747

    
2748
		@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}",
2749
		    $upinst);
2750
		unset($upinst);
2751
		/* invoke nsupdate */
2752
		$cmd = "/usr/local/bin/nsupdate -k " .
2753
		    "{$g['varetc_path']}/K{$i}{$keyname}+157+00000.key";
2754

    
2755
		if (isset($dnsupdate['usetcp'])) {
2756
			$cmd .= " -v";
2757
		}
2758

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

    
2761
		if (mwexec($cmd) == 0) {
2762
			if (!empty($cacheFile)) {
2763
				@file_put_contents($cacheFile,
2764
				    "{$wanip}|{$currentTime}");
2765
				log_error(sprintf(gettext(
2766
				    'phpDynDNS: updating cache file %1$s: %2$s'),
2767
				    $cacheFile, $wanip));
2768
				$notify_text .= sprintf(gettext(
2769
				    'DynDNS updated IP Address (A) for %1$s on %2$s (%3$s) to %4$s'),
2770
				    $dnsupdate['host'],
2771
				    convert_real_interface_to_friendly_descr($if),
2772
				    $if, $wanip) . "\n";
2773
			}
2774
			if (!empty($cacheFilev6)) {
2775
				@file_put_contents($cacheFilev6,
2776
				    "{$wanipv6}|{$currentTime}");
2777
				log_error(sprintf(gettext(
2778
				    'phpDynDNS: updating cache file %1$s: %2$s'),
2779
				    $cacheFilev6, $wanipv6));
2780
				$notify_text .= sprintf(gettext(
2781
				    'DynDNS updated IPv6 Address (AAAA) for %1$s on %2$s (%3$s) to %4$s'),
2782
				    $dnsupdate['host'],
2783
				    convert_real_interface_to_friendly_descr($if),
2784
				    $if, $wanipv6) . "\n";
2785
			}
2786
		} else {
2787
			if (!empty($cacheFile)) {
2788
				log_error(sprintf(gettext(
2789
				    'phpDynDNS: ERROR while updating IP Address (A) for %1$s (%2$s)'),
2790
				    $dnsupdate['host'], $wanip));
2791
			}
2792
			if (!empty($cacheFilev6)) {
2793
				log_error(sprintf(gettext(
2794
				    'phpDynDNS: ERROR while updating IP Address (AAAA) for %1$s (%2$s)'),
2795
				    $dnsupdate['host'], $wanipv6));
2796
			}
2797
		}
2798
		unset($cmd);
2799
	}
2800

    
2801
	if (!empty($notify_text)) {
2802
		notify_all_remote($notify_text);
2803
	}
2804

    
2805
	return 0;
2806
}
2807

    
2808
/* configure cron service */
2809
function configure_cron() {
2810
	global $g, $config;
2811

    
2812
	/* preserve existing crontab entries */
2813
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2814

    
2815
	for ($i = 0; $i < count($crontab_contents); $i++) {
2816
		$cron_item =& $crontab_contents[$i];
2817
		if (strpos($cron_item, "# pfSense specific crontab entries") !== false) {
2818
			array_splice($crontab_contents, $i - 1);
2819
			break;
2820
		}
2821
	}
2822
	$crontab_contents = implode("\n", $crontab_contents) . "\n";
2823

    
2824

    
2825
	if (is_array($config['cron']['item'])) {
2826
		$crontab_contents .= "#\n";
2827
		$crontab_contents .= "# pfSense specific crontab entries\n";
2828
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
2829
		$crontab_contents .= "#\n";
2830

    
2831
		if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) {
2832
			$http_proxy = $config['system']['proxyurl'];
2833
			if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) {
2834
				$http_proxy .= ':' . $config['system']['proxyport'];
2835
			}
2836
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
2837

    
2838
			if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
2839
				$crontab_contents .= "HTTP_PROXY_AUTH=basic:*:{$config['system']['proxyuser']}:{$config['system']['proxypass']}";
2840
			}
2841
		}
2842

    
2843
		foreach ($config['cron']['item'] as $item) {
2844
			$crontab_contents .= "\n{$item['minute']}\t";
2845
			$crontab_contents .= "{$item['hour']}\t";
2846
			$crontab_contents .= "{$item['mday']}\t";
2847
			$crontab_contents .= "{$item['month']}\t";
2848
			$crontab_contents .= "{$item['wday']}\t";
2849
			$crontab_contents .= "{$item['who']}\t";
2850
			$crontab_contents .= "{$item['command']}";
2851
		}
2852

    
2853
		$crontab_contents .= "\n#\n";
2854
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
2855
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
2856
		$crontab_contents .= "#\n\n";
2857
	}
2858

    
2859
	/* please maintain the newline at the end of file */
2860
	file_put_contents("/etc/crontab", $crontab_contents);
2861
	unset($crontab_contents);
2862

    
2863
	/* make sure that cron is running and start it if it got killed somehow */
2864
	if (!is_process_running("cron")) {
2865
		exec("cd /tmp && /usr/sbin/cron -s 2>/dev/null");
2866
	} else {
2867
	/* do a HUP kill to force sync changes */
2868
		sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP");
2869
	}
2870

    
2871
}
2872

    
2873
function upnp_action ($action) {
2874
	global $g, $config;
2875
	switch ($action) {
2876
		case "start":
2877
			if (file_exists('/var/etc/miniupnpd.conf')) {
2878
				@unlink("{$g['varrun_path']}/miniupnpd.pid");
2879
				mwexec_bg("/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf -P {$g['varrun_path']}/miniupnpd.pid");
2880
			}
2881
			break;
2882
		case "stop":
2883
			killbypid("{$g['varrun_path']}/miniupnpd.pid");
2884
			while ((int)exec("/bin/pgrep -a miniupnpd | wc -l") > 0) {
2885
				mwexec('/usr/bin/killall miniupnpd 2>/dev/null', true);
2886
			}
2887
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
2888
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
2889
			break;
2890
		case "restart":
2891
			upnp_action('stop');
2892
			upnp_action('start');
2893
			break;
2894
	}
2895
}
2896

    
2897
function upnp_start() {
2898
	global $config;
2899

    
2900
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
2901
		return;
2902
	}
2903

    
2904
	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
2905
		echo gettext("Starting UPnP service... ");
2906
		require_once('/usr/local/pkg/miniupnpd.inc');
2907
		sync_package_miniupnpd();
2908
		echo "done.\n";
2909
	}
2910
}
2911

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

    
2915
	$is_installed = false;
2916
	$cron_changed = true;
2917
	$change_message = "";
2918

    
2919
	if (!is_array($config['cron'])) {
2920
		$config['cron'] = array();
2921
	}
2922
	if (!is_array($config['cron']['item'])) {
2923
		$config['cron']['item'] = array();
2924
	}
2925

    
2926
	$x = 0;
2927
	foreach ($config['cron']['item'] as $item) {
2928
		if (strstr($item['command'], $command)) {
2929
			$is_installed = true;
2930
			break;
2931
		}
2932
		$x++;
2933
	}
2934

    
2935
	if ($active) {
2936
		$cron_item = array();
2937
		$cron_item['minute'] = $minute;
2938
		$cron_item['hour'] = $hour;
2939
		$cron_item['mday'] = $monthday;
2940
		$cron_item['month'] = $month;
2941
		$cron_item['wday'] = $weekday;
2942
		$cron_item['who'] = $who;
2943
		$cron_item['command'] = $command;
2944
		if (!$is_installed) {
2945
			$config['cron']['item'][] = $cron_item;
2946
			$change_message = "Installed cron job for %s";
2947
		} else {
2948
			if ($config['cron']['item'][$x] == $cron_item) {
2949
				$cron_changed = false;
2950
			} else {
2951
				$config['cron']['item'][$x] = $cron_item;
2952
				$change_message = "Updated cron job for %s";
2953
			}
2954
		}
2955
	} else {
2956
		if ($is_installed == true) {
2957
			array_splice($config['cron']['item'], $x, 1);
2958
			$change_message = "Removed cron job for %s";
2959
		} else {
2960
			$cron_changed = false;
2961
		}
2962
	}
2963

    
2964
	if ($cron_changed) {
2965
		/* Optionally write the configuration if this function made changes.
2966
		 * Performing a write_config() in this way can have unintended side effects. See #7146
2967
		 * Base system instances of this function do not need to write, packages may.
2968
		 */
2969
		if ($write_config) {
2970
			write_config(sprintf(gettext($change_message), $command));
2971
		}
2972
		configure_cron();
2973
	}
2974
}
2975

    
2976
?>
(41-41/54)