Project

General

Profile

Download (87.7 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
 * Redistribution and use in source and binary forms, with or without
14
 * modification, are permitted provided that the following conditions are met:
15
 *
16
 * 1. Redistributions of source code must retain the above copyright notice,
17
 *    this list of conditions and the following disclaimer.
18
 *
19
 * 2. Redistributions in binary form must reproduce the above copyright
20
 *    notice, this list of conditions and the following disclaimer in
21
 *    the documentation and/or other materials provided with the
22
 *    distribution.
23
 *
24
 * 3. All advertising materials mentioning features or use of this software
25
 *    must display the following acknowledgment:
26
 *    "This product includes software developed by the pfSense Project
27
 *    for use in the pfSense® software distribution. (http://www.pfsense.org/).
28
 *
29
 * 4. The names "pfSense" and "pfSense Project" must not be used to
30
 *    endorse or promote products derived from this software without
31
 *    prior written permission. For written permission, please contact
32
 *    coreteam@pfsense.org.
33
 *
34
 * 5. Products derived from this software may not be called "pfSense"
35
 *    nor may "pfSense" appear in their names without prior written
36
 *    permission of the Electric Sheep Fencing, LLC.
37
 *
38
 * 6. Redistributions of any form whatsoever must retain the following
39
 *    acknowledgment:
40
 *
41
 * "This product includes software developed by the pfSense Project
42
 * for use in the pfSense software distribution (http://www.pfsense.org/).
43
 *
44
 * THIS SOFTWARE IS PROVIDED BY THE pfSense PROJECT ``AS IS'' AND ANY
45
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
46
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
47
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE pfSense PROJECT OR
48
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
49
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
50
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
51
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
53
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
54
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
55
 * OF THE POSSIBILITY OF SUCH DAMAGE.
56
 */
57

    
58
define('DYNDNS_PROVIDER_VALUES', 'all-inkl citynetwork cloudflare cloudflare-v6 custom custom-v6 dnsexit dnsimple dnsmadeeasy dnsomatic 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 loopia namecheap noip noip-free ods opendns ovh-dynhost route53 selfhost spdyn spdyn-v6 zoneedit');
59
define('DYNDNS_PROVIDER_DESCRIPTIONS', 'All-Inkl.com,City Network,CloudFlare,CloudFlare (v6),Custom,Custom (v6),DNSexit,DNSimple,DNS Made Easy,DNS-O-Matic,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,Loopia,Namecheap,No-IP,No-IP (free),ODS.org,OpenDNS,OVH DynHOST,Route 53,SelfHost,SPDYN,SPDYN (v6),ZoneEdit');
60

    
61
/* implement ipv6 route advertising daemon */
62
function services_radvd_configure($blacklist = array()) {
63
	global $config, $g;
64

    
65
	if (isset($config['system']['developerspew'])) {
66
		$mt = microtime();
67
		echo "services_radvd_configure() being called $mt\n";
68
	}
69

    
70
	if (!is_array($config['dhcpdv6'])) {
71
		$config['dhcpdv6'] = array();
72
	}
73

    
74
	$Iflist = get_configured_interface_list();
75
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
76

    
77
	$radvdconf = "# Automatically Generated, do not edit\n";
78

    
79
	/* Process all links which need the router advertise daemon */
80
	$radvdifs = array();
81

    
82
	/* handle manually configured DHCP6 server settings first */
83
	foreach ($config['dhcpdv6'] as $dhcpv6if => $dhcpv6ifconf) {
84
		if (!is_array($config['interfaces'][$dhcpv6if])) {
85
			continue;
86
		}
87
		if (!isset($config['interfaces'][$dhcpv6if]['enable'])) {
88
			continue;
89
		}
90

    
91
		/* Do not put in the config an interface which is down */
92
		if (isset($blacklist[$dhcpv6if])) {
93
			continue;
94
		}
95
		if (!isset($dhcpv6ifconf['ramode'])) {
96
			$dhcpv6ifconf['ramode'] = $dhcpv6ifconf['mode'];
97
		}
98

    
99
		/* are router advertisements enabled? */
100
		if ($dhcpv6ifconf['ramode'] == "disabled") {
101
			continue;
102
		}
103

    
104
		if (!isset($dhcpv6ifconf['rapriority'])) {
105
			$dhcpv6ifconf['rapriority'] = "medium";
106
		}
107

    
108
		$racarpif = false;
109
		/* check if binding to CARP IP */
110
		if (!empty($dhcpv6ifconf['rainterface'])) {
111
			if (strstr($dhcpv6ifconf['rainterface'], "_vip")) {
112
				if (get_carp_interface_status($dhcpv6ifconf['rainterface']) == "MASTER") {
113
					$dhcpv6if = $dhcpv6ifconf['rainterface'];
114
					$racarpif = true;
115
				} else {
116
					continue;
117
				}
118
			}
119
		}
120

    
121
		$realif = get_real_interface($dhcpv6if, "inet6");
122

    
123
		if (isset($radvdifs[$realif])) {
124
			continue;
125
		}
126

    
127
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
128
		if (!is_ipaddrv6($ifcfgipv6)) {
129
			continue;
130
		}
131

    
132
		$ifcfgsnv6 = get_interface_subnetv6($dhcpv6if);
133
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
134
		if (!is_subnetv6($subnetv6 . "/" . $ifcfgsnv6)) {
135
			log_error("radvd: skipping configuration for interface $dhcpv6if because its subnet or prefix length is invalid.");
136
			continue;
137
		}
138
		$radvdifs[$realif] = $realif;
139

    
140
		$radvdconf .= "# Generated for DHCPv6 Server $dhcpv6if\n";
141
		$radvdconf .= "interface {$realif} {\n";
142
		if (strstr($realif, "ovpn")) {
143
			$radvdconf .= "\tUnicastOnly on;\n";
144
		}
145
		$radvdconf .= "\tAdvSendAdvert on;\n";
146

    
147
		if (is_numericint($dhcpv6ifconf['raminrtradvinterval'])) {
148
			$radvdconf .= "\tMinRtrAdvInterval {$dhcpv6ifconf['raminrtradvinterval']};\n";
149
		} else {
150
			$radvdconf .= "\tMinRtrAdvInterval 5;\n";
151
		}
152

    
153
		if (is_numericint($dhcpv6ifconf['ramaxrtradvinterval'])) {
154
			$radvdconf .= "\tMaxRtrAdvInterval {$dhcpv6ifconf['ramaxrtradvinterval']};\n";
155
		} else {
156
			$radvdconf .= "\tMaxRtrAdvInterval 20;\n";
157
		}
158
		if (is_numericint($dhcpv6ifconf['raadvdefaultlifetime'])) {
159
			$radvdconf .= "\tAdvDefaultLifetime {$dhcpv6ifconf['raadvdefaultlifetime']};\n";
160
		}
161

    
162
		$mtu = get_interface_mtu($realif);
163
		if (is_numeric($mtu)) {
164
			$radvdconf .= "\tAdvLinkMTU {$mtu};\n";
165
		} else {
166
			$radvdconf .= "\tAdvLinkMTU 1280;\n";
167
		}
168
		switch ($dhcpv6ifconf['rapriority']) {
169
			case "low":
170
				$radvdconf .= "\tAdvDefaultPreference low;\n";
171
				break;
172
			case "high":
173
				$radvdconf .= "\tAdvDefaultPreference high;\n";
174
				break;
175
			default:
176
				$radvdconf .= "\tAdvDefaultPreference medium;\n";
177
				break;
178
		}
179
		switch ($dhcpv6ifconf['ramode']) {
180
			case "managed":
181
			case "assist":
182
				$radvdconf .= "\tAdvManagedFlag on;\n";
183
				$radvdconf .= "\tAdvOtherConfigFlag on;\n";
184
				break;
185
			case "stateless_dhcp":
186
				$radvdconf .= "\tAdvManagedFlag off;\n";
187
				$radvdconf .= "\tAdvOtherConfigFlag on;\n";
188
				break;
189
		}
190
		$radvdconf .= "\tprefix {$subnetv6}/{$ifcfgsnv6} {\n";
191
		if ($racarpif == true) {
192
			$radvdconf .= "\t\tDeprecatePrefix off;\n";
193
		} else {
194
			$radvdconf .= "\t\tDeprecatePrefix on;\n";
195
		}
196
		switch ($dhcpv6ifconf['ramode']) {
197
			case "managed":
198
				$radvdconf .= "\t\tAdvOnLink on;\n";
199
				$radvdconf .= "\t\tAdvAutonomous off;\n";
200
				$radvdconf .= "\t\tAdvRouterAddr on;\n";
201
				break;
202
			case "router":
203
				$radvdconf .= "\t\tAdvOnLink off;\n";
204
				$radvdconf .= "\t\tAdvAutonomous off;\n";
205
				$radvdconf .= "\t\tAdvRouterAddr on;\n";
206
				break;
207
			case "stateless_dhcp":
208
			case "assist":
209
				$radvdconf .= "\t\tAdvOnLink on;\n";
210
				$radvdconf .= "\t\tAdvAutonomous on;\n";
211
				$radvdconf .= "\t\tAdvRouterAddr on;\n";
212
				break;
213
			case "unmanaged":
214
				$radvdconf .= "\t\tAdvOnLink on;\n";
215
				$radvdconf .= "\t\tAdvAutonomous on;\n";
216
				$radvdconf .= "\t\tAdvRouterAddr on;\n";
217
				break;
218
		}
219

    
220
		if (is_numericint($dhcpv6ifconf['ravalidlifetime'])) {
221
		  $radvdconf .= "\t\tAdvValidLifetime {$dhcpv6ifconf['ravalidlifetime']};\n";
222
		} else {
223
		  $radvdconf .= "\t\tAdvValidLifetime 86400;\n";
224
		}
225

    
226
		if (is_numericint($dhcpv6ifconf['rapreferredlifetime'])) {
227
		  $radvdconf .= "\t\tAdvPreferredLifetime {$dhcpv6ifconf['rapreferredlifetime']};\n";
228
		} else {
229
		  $radvdconf .= "\t\tAdvPreferredLifetime 14400;\n";
230
		}
231

    
232
		$radvdconf .= "\t};\n";
233

    
234
		if (is_array($dhcpv6ifconf['subnets']['item'])) {
235
			foreach ($dhcpv6ifconf['subnets']['item'] as $subnet) {
236
				if (is_subnetv6($subnet)) {
237
					$radvdconf .= "\tprefix {$subnet} {\n";
238
					$radvdconf .= "\t\tDeprecatePrefix on;\n";
239
					switch ($dhcpv6ifconf['ramode']) {
240
						case "managed":
241
							$radvdconf .= "\t\tAdvOnLink on;\n";
242
							$radvdconf .= "\t\tAdvAutonomous off;\n";
243
							$radvdconf .= "\t\tAdvRouterAddr on;\n";
244
							break;
245
						case "router":
246
							$radvdconf .= "\t\tAdvOnLink off;\n";
247
							$radvdconf .= "\t\tAdvAutonomous off;\n";
248
							$radvdconf .= "\t\tAdvRouterAddr on;\n";
249
							break;
250
						case "assist":
251
							$radvdconf .= "\t\tAdvOnLink on;\n";
252
							$radvdconf .= "\t\tAdvAutonomous on;\n";
253
							$radvdconf .= "\t\tAdvRouterAddr on;\n";
254
							break;
255
						case "unmanaged":
256
							$radvdconf .= "\t\tAdvOnLink on;\n";
257
							$radvdconf .= "\t\tAdvAutonomous on;\n";
258
							$radvdconf .= "\t\tAdvRouterAddr on;\n";
259
							break;
260
					}
261
					$radvdconf .= "\t};\n";
262
				}
263
			}
264
		}
265
		$radvdconf .= "\troute ::/0 {\n";
266
		$radvdconf .= "\t\tRemoveRoute on;\n";
267
		$radvdconf .= "\t};\n";
268

    
269
		/* add DNS servers */
270
		$dnslist = array();
271
		if (isset($dhcpv6ifconf['rasamednsasdhcp6']) && is_array($dhcpv6ifconf['dnsserver']) && !empty($dhcpv6ifconf['dnsserver'])) {
272
			foreach ($dhcpv6ifconf['dnsserver'] as $server) {
273
				if (is_ipaddrv6($server)) {
274
					$dnslist[] = $server;
275
				}
276
			}
277
		} elseif (!isset($dhcpv6ifconf['rasamednsasdhcp6']) && isset($dhcpv6ifconf['radnsserver']) && is_array($dhcpv6ifconf['radnsserver'])) {
278
			foreach ($dhcpv6ifconf['radnsserver'] as $server) {
279
				if (is_ipaddrv6($server)) {
280
					$dnslist[] = $server;
281
				}
282
			}
283
		} elseif (isset($config['dnsmasq']['enable']) || isset($config['unbound']['enable'])) {
284
			$dnslist[] = get_interface_ipv6($realif);
285
		} elseif (is_array($config['system']['dnsserver']) && !empty($config['system']['dnsserver'])) {
286
			foreach ($config['system']['dnsserver'] as $server) {
287
				if (is_ipaddrv6($server)) {
288
					$dnslist[] = $server;
289
				}
290
			}
291
		}
292
		if (count($dnslist) > 0) {
293
			$dnsstring = implode(" ", $dnslist);
294
			if ($dnsstring <> "") {
295
				$radvdconf .= "\tRDNSS {$dnsstring} { };\n";
296
			}
297
		}
298
		if (!empty($dhcpv6ifconf['domain'])) {
299
			$radvdconf .= "\tDNSSL {$dhcpv6ifconf['domain']} { };\n";
300
		} elseif (!empty($config['system']['domain'])) {
301
			$radvdconf .= "\tDNSSL {$config['system']['domain']} { };\n";
302
		}
303
		$radvdconf .= "};\n";
304
	}
305

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

    
328
		$realif = get_real_interface($if, "inet6");
329

    
330
		/* prevent duplicate entries, manual overrides */
331
		if (isset($radvdifs[$realif])) {
332
			continue;
333
		}
334

    
335
		$ifcfgipv6 = get_interface_ipv6($if);
336
		if (!is_ipaddrv6($ifcfgipv6)) {
337
			$subnetv6 = "::";
338
			$ifcfgsnv6 = "64";
339
		} else {
340
			$ifcfgsnv6 = get_interface_subnetv6($if);
341
			$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
342
		}
343
		$radvdifs[$realif] = $realif;
344

    
345
		$autotype = $config['interfaces'][$trackif]['ipaddrv6'];
346

    
347
		if ($g['debug']) {
348
			log_error("configuring RA on {$if} for type {$autotype} radvd subnet {$subnetv6}/{$ifcfgsnv6}");
349
		}
350

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

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

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

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

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

    
430
	$dhcpdconfigurelck = lock("dhcpdconfigure", LOCK_EX);
431

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

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

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

    
463
	unlock($dhcpdconfigurelck);
464
}
465

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

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

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

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

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

    
490
	/* if OLSRD is enabled, allow WAN to house DHCP. */
491
	if (!function_exists('is_package_installed')) {
492
		require_once('pkg-utils.inc');
493
	}
494
	if (is_package_installed('olsrd') && isset($config['installedpackages']['olsrd'])) {
495
		foreach ($config['installedpackages']['olsrd']['config'] as $olsrd) {
496
			if (isset($olsrd['enable']) && $olsrd['enable'] == "on") {
497
				$is_olsr_enabled = true;
498
				break;
499
			}
500
		}
501
	}
502

    
503
	if (platform_booting()) {
504
		/* restore the leases, if we have them */
505
		if (file_exists("{$g['cf_conf_path']}/dhcpleases.tgz")) {
506
			$dhcprestore = "";
507
			$dhcpreturn = "";
508
			exec("cd /;LANG=C /usr/bin/tar -xzf {$g['cf_conf_path']}/dhcpleases.tgz 2>&1", $dhcprestore, $dhcpreturn);
509
			$dhcprestore = implode(" ", $dhcprestore);
510
			if ($dhcpreturn <> 0) {
511
				log_error(sprintf(gettext('DHCP leases restore failed exited with %1$s, the error is: %2$s%3$s'), $dhcpreturn, $dhcprestore, "\n"));
512
			}
513
		}
514
		/* If this backup is still there on a full install, but we aren't going to use ram disks, remove the archive since this is a transition. */
515
		if (($g['platform'] == $g['product_name']) && !isset($config['system']['use_mfs_tmpvar'])) {
516
			unlink_if_exists("{$g['cf_conf_path']}/dhcpleases.tgz");
517
		}
518
	}
519

    
520
	$syscfg = $config['system'];
521
	if (!is_array($config['dhcpd'])) {
522
		$config['dhcpd'] = array();
523
	}
524
	$dhcpdcfg = $config['dhcpd'];
525
	$Iflist = get_configured_interface_list();
526

    
527
	/* Only consider DNS servers with IPv4 addresses for the IPv4 DHCP server. */
528
	$dns_arrv4 = array();
529
	if (is_array($syscfg['dnsserver'])) {
530
		foreach ($syscfg['dnsserver'] as $dnsserver) {
531
			if (is_ipaddrv4($dnsserver)) {
532
				$dns_arrv4[] = $dnsserver;
533
			}
534
		}
535
	}
536

    
537
	if (platform_booting()) {
538
		echo gettext("Starting DHCP service...");
539
	} else {
540
		sleep(1);
541
	}
542

    
543
	$custoptions = "";
544
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
545
		if (is_array($dhcpifconf['numberoptions']) && is_array($dhcpifconf['numberoptions']['item'])) {
546
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
547
				if (!empty($item['type'])) {
548
					$itemtype = $item['type'];
549
				} else {
550
					$itemtype = "text";
551
				}
552
				$custoptions .= "option custom-{$dhcpif}-{$itemidx} code {$item['number']} = {$itemtype};\n";
553
			}
554
		}
555
		if (is_array($dhcpifconf['pool'])) {
556
			foreach ($dhcpifconf['pool'] as $poolidx => $poolconf) {
557
				if (is_array($poolconf['numberoptions']) && is_array($poolconf['numberoptions']['item'])) {
558
					foreach ($poolconf['numberoptions']['item'] as $itemidx => $item) {
559
						if (!empty($item['type'])) {
560
							$itemtype = $item['type'];
561
						} else {
562
							$itemtype = "text";
563
						}
564
						$custoptions .= "option custom-{$dhcpif}-{$poolidx}-{$itemidx} code {$item['number']} = {$itemtype};\n";
565
					}
566
				}
567
			}
568
		}
569
	}
570

    
571
	$dhcpdconf = <<<EOD
572

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

    
586
EOD;
587

    
588
	if (!isset($dhcpifconf['disableauthoritative'])) {
589
		$dhcpdconf .= "authoritative;\n";
590
	}
591

    
592
	if (isset($dhcpifconf['alwaysbroadcast'])) {
593
		$dhcpdconf .= "always-broadcast on\n";
594
	}
595

    
596
	$dhcpdifs = array();
597
	$enable_add_routers = false;
598
	$gateways_arr = return_gateways_array();
599
	/* only add a routers line if the system has any IPv4 gateway at all */
600
	/* a static route has a gateway, manually overriding this field always works */
601
	foreach ($gateways_arr as $gwitem) {
602
		if ($gwitem['ipprotocol'] == "inet") {
603
			$enable_add_routers = true;
604
			break;
605
		}
606
	}
607

    
608
	/*    loop through and determine if we need to setup
609
	 *    failover peer "bleh" entries
610
	 */
611
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
612

    
613
		if (!isset($config['interfaces'][$dhcpif]['enable'])) {
614
			continue;
615
		}
616

    
617
		interfaces_staticarp_configure($dhcpif);
618

    
619
		if (!isset($dhcpifconf['enable'])) {
620
			continue;
621
		}
622

    
623
		if ($dhcpifconf['failover_peerip'] <> "") {
624
			$intip = get_interface_ip($dhcpif);
625
			/*
626
			 *    yep, failover peer is defined.
627
			 *    does it match up to a defined vip?
628
			 */
629
			$skew = 110;
630
			if (is_array($config['virtualip']['vip'])) {
631
				foreach ($config['virtualip']['vip'] as $vipent) {
632
					if ($vipent['interface'] == $dhcpif) {
633
						$carp_nw = gen_subnet($vipent['subnet'], $vipent['subnet_bits']);
634
						if (ip_in_subnet($dhcpifconf['failover_peerip'], "{$carp_nw}/{$vipent['subnet_bits']}")) {
635
							/* this is the interface! */
636
							if (is_numeric($vipent['advskew']) && (intval($vipent['advskew']) < 20)) {
637
								$skew = 0;
638
								break;
639
							}
640
						}
641
					}
642
				}
643
			} else {
644
				log_error(gettext("Warning!  DHCP Failover setup and no CARP virtual IPs defined!"));
645
			}
646
			if ($skew > 10) {
647
				$type = "secondary";
648
				$my_port = "520";
649
				$peer_port = "519";
650
			} else {
651
				$my_port = "519";
652
				$peer_port = "520";
653
				$type = "primary";
654
				$dhcpdconf_pri = "split 128;\n";
655
				$dhcpdconf_pri .= "  mclt 600;\n";
656
			}
657

    
658
			if (is_ipaddrv4($intip)) {
659
				$dhcpdconf .= <<<EOPP
660
failover peer "dhcp_{$dhcpif}" {
661
  {$type};
662
  address {$intip};
663
  port {$my_port};
664
  peer address {$dhcpifconf['failover_peerip']};
665
  peer port {$peer_port};
666
  max-response-delay 10;
667
  max-unacked-updates 10;
668
  {$dhcpdconf_pri}
669
  load balance max seconds 3;
670
}
671
\n
672
EOPP;
673
			}
674
		}
675
	}
676

    
677
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
678

    
679
		$newzone = array();
680
		$ifcfg = $config['interfaces'][$dhcpif];
681

    
682
		if (!isset($dhcpifconf['enable']) || !isset($Iflist[$dhcpif])) {
683
			continue;
684
		}
685
		$ifcfgip = get_interface_ip($dhcpif);
686
		$ifcfgsn = get_interface_subnet($dhcpif);
687
		$subnet = gen_subnet($ifcfgip, $ifcfgsn);
688
		$subnetmask = gen_subnet_mask($ifcfgsn);
689

    
690
		if (!is_ipaddr($subnet)) {
691
			continue;
692
		}
693

    
694
		if ($is_olsr_enabled == true) {
695
			if ($dhcpifconf['netmask']) {
696
				$subnetmask = gen_subnet_mask($dhcpifconf['netmask']);
697
			}
698
		}
699

    
700
		$all_pools = array();
701
		$all_pools[] = $dhcpifconf;
702
		if (is_array($dhcpifconf['pool'])) {
703
			$all_pools = array_merge($all_pools, $dhcpifconf['pool']);
704
		}
705

    
706
		$dnscfg = "";
707

    
708
		if ($dhcpifconf['domain']) {
709
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
710
		}
711

    
712
		if ($dhcpifconf['domainsearchlist'] <> "") {
713
			$dnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpifconf['domainsearchlist'])) . "\";\n";
714
		}
715

    
716
		if (isset($dhcpifconf['ddnsupdate'])) {
717
			$need_ddns_updates = true;
718
			$newzone = array();
719
			if ($dhcpifconf['ddnsdomain'] <> "") {
720
				$newzone['domain-name'] = $dhcpifconf['ddnsdomain'];
721
				$dnscfg .= "	ddns-domainname \"{$dhcpifconf['ddnsdomain']}\";\n";
722
			} else {
723
				$newzone['domain-name'] = $config['system']['domain'];
724
			}
725

    
726
			$revsubnet = array_reverse(explode('.',$subnet));
727

    
728
			/* Take care of full classes first */
729
			switch ($ifcfgsn) {
730
				case 8:
731
					$start_octet = 3;
732
					break;
733
				case 16:
734
					$start_octet = 2;
735
					break;
736
				case 24:
737
					$start_octet = 1;
738
					break;
739
				default:
740
					$start_octet = 0;
741
					/* Add subnet bitmask to first octet */
742
					$revsubnet[0] .= '-' . $ifcfgsn;
743
					break;
744

    
745
			}
746

    
747
			$ptr_domain = '';
748
			for ($octet = 0; $octet <= 3; $octet++) {
749
				if ($octet < $start_octet) {
750
					continue;
751
				}
752
				$ptr_domain .= ((empty($ptr_domain) && $ptr_domain !== "0") ? '' : '.');
753
				$ptr_domain .= $revsubnet[$octet];
754
			}
755
			$ptr_domain .= ".in-addr.arpa";
756
			$newzone['ptr-domain'] = $ptr_domain;
757
			unset($ptr_domain, $revsubnet, $start_octet);
758
		}
759

    
760
		if (is_array($dhcpifconf['dnsserver']) && ($dhcpifconf['dnsserver'][0])) {
761
			$dnscfg .= "	option domain-name-servers " . join(",", $dhcpifconf['dnsserver']) . ";";
762
			if ($newzone['domain-name']) {
763
				$newzone['dns-servers'] = $dhcpifconf['dnsserver'];
764
			}
765
		} else if (isset($config['dnsmasq']['enable'])) {
766
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
767
			if ($newzone['domain-name'] && is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
768
				$newzone['dns-servers'] = $syscfg['dnsserver'];
769
			}
770
		} else if (isset($config['unbound']['enable'])) {
771
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
772
		} else if (!empty($dns_arrv4)) {
773
			$dnscfg .= "	option domain-name-servers " . join(",", $dns_arrv4) . ";";
774
			if ($newzone['domain-name']) {
775
				$newzone['dns-servers'] = $dns_arrv4;
776
			}
777
		}
778

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

    
803
		$dhcpdconf .= "subnet {$subnet} netmask {$subnetmask} {\n";
804

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

    
850
			/* allow/deny MACs */
851
			$mac_allow_list = array_unique(explode(',', $poolconf['mac_allow']));
852
			foreach ($mac_allow_list as $mac) {
853
				if (empty($mac)) {
854
					continue;
855
				}
856
				$dhcpdconf .= "		allow members of \"" . str_replace(':', '', $mac) . "\";\n";
857
			}
858
			$deny_action = "deny";
859
			if (isset($poolconf['nonak']) && empty($poolconf['failover_peerip'])) {
860
				$deny_action = "ignore";
861
			}
862
			$mac_deny_list = array_unique(explode(',', $poolconf['mac_deny']));
863
			foreach ($mac_deny_list as $mac) {
864
				if (empty($mac)) {
865
					continue;
866
				}
867
				$dhcpdconf .= "		$deny_action members of \"" . str_replace(':', '', $mac) . "\";\n";
868
			}
869

    
870
			if ($poolconf['failover_peerip'] <> "") {
871
				$dhcpdconf .= "		$deny_action dynamic bootp clients;\n";
872
			}
873

    
874
			if (isset($poolconf['denyunknown'])) {
875
				$dhcpdconf .= "		$deny_action unknown-clients;\n";
876
			}
877

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

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

    
886
			$pdnscfg = "";
887

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

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

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

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

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

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

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

    
920
			// netbios-name*
921
			if (is_array($poolconf['winsserver']) && $poolconf['winsserver'][0] && ($poolconf['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
922
				$dhcpdconf .= "		option netbios-name-servers " . join(",", $poolconf['winsserver']) . ";\n";
923
				$dhcpdconf .= "		option netbios-node-type 8;\n";
924
			}
925

    
926
			// ntp-servers
927
			if (is_array($poolconf['ntpserver']) && $poolconf['ntpserver'][0] && ($poolconf['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
928
				$dhcpdconf .= "		option ntp-servers " . join(",", $poolconf['ntpserver']) . ";\n";
929
			}
930

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

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

    
953
			// ldap-server
954
			if (!empty($poolconf['ldap']) && ($poolconf['ldap'] != $dhcpifconf['ldap'])) {
955
				$dhcpdconf .= "		option ldap-server \"{$poolconf['ldap']}\";\n";
956
			}
957

    
958
			// net boot information
959
			if (isset($poolconf['netboot'])) {
960
				if (!empty($poolconf['nextserver']) && ($poolconf['nextserver'] != $dhcpifconf['nextserver'])) {
961
					$dhcpdconf .= "		next-server {$poolconf['nextserver']};\n";
962
				}
963
				if (!empty($poolconf['filename']) && ($poolconf['filename'] != $dhcpifconf['filename'])) {
964
					$dhcpdconf .= "		filename \"{$poolconf['filename']}\";\n";
965
				}
966
				if (!empty($poolconf['rootpath']) && ($poolconf['rootpath'] != $dhcpifconf['rootpath'])) {
967
					$dhcpdconf .= "		option root-path \"{$poolconf['rootpath']}\";\n";
968
				}
969
			}
970
			$dhcpdconf .= "		range {$poolconf['range']['from']} {$poolconf['range']['to']};\n";
971
			$dhcpdconf .= "	}\n\n";
972
		}
973
// End of settings inside pools
974

    
975
		if ($dhcpifconf['gateway'] && $dhcpifconf['gateway'] != "none") {
976
			$routers = $dhcpifconf['gateway'];
977
			$add_routers = true;
978
		} elseif ($dhcpifconf['gateway'] == "none") {
979
			$add_routers = false;
980
		} else {
981
			$add_routers = $enable_add_routers;
982
			$routers = $ifcfgip;
983
		}
984
		if ($add_routers) {
985
			$dhcpdconf .= "	option routers {$routers};\n";
986
		}
987

    
988
		$dhcpdconf .= <<<EOD
989
$dnscfg
990

    
991
EOD;
992
		// default-lease-time
993
		if ($dhcpifconf['defaultleasetime']) {
994
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
995
		}
996

    
997
		// max-lease-time
998
		if ($dhcpifconf['maxleasetime']) {
999
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
1000
		}
1001

    
1002
		// netbios-name*
1003
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
1004
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
1005
			$dhcpdconf .= "	option netbios-node-type 8;\n";
1006
		}
1007

    
1008
		// ntp-servers
1009
		if (is_array($dhcpifconf['ntpserver']) && $dhcpifconf['ntpserver'][0]) {
1010
			$dhcpdconf .= "	option ntp-servers " . join(",", $dhcpifconf['ntpserver']) . ";\n";
1011
		}
1012

    
1013
		// tftp-server-name
1014
		if ($dhcpifconf['tftp'] <> "") {
1015
			$dhcpdconf .= "	option tftp-server-name \"{$dhcpifconf['tftp']}\";\n";
1016
		}
1017

    
1018
		// Handle option, number rowhelper values
1019
		$dhcpdconf .= "\n";
1020
		if ($dhcpifconf['numberoptions']['item']) {
1021
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
1022
				$item_value = base64_decode($item['value']);
1023
				if (empty($item['type']) || $item['type'] == "text") {
1024
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} \"{$item_value}\";\n";
1025
				} else {
1026
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} {$item_value};\n";
1027
				}
1028
			}
1029
		}
1030

    
1031
		// ldap-server
1032
		if ($dhcpifconf['ldap'] <> "") {
1033
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
1034
		}
1035

    
1036
		// net boot information
1037
		if (isset($dhcpifconf['netboot'])) {
1038
			if ($dhcpifconf['nextserver'] <> "") {
1039
				$dhcpdconf .= "	next-server {$dhcpifconf['nextserver']};\n";
1040
			}
1041
			if (!empty($dhcpifconf['filename']) && !empty($dhcpifconf['filename32']) && !empty($dhcpifconf['filename64'])) {
1042
				$dhcpdconf .= "	if option arch = 00:06 {\n";
1043
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename32']}\";\n";
1044
				$dhcpdconf .= "	} else if option arch = 00:07 {\n";
1045
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1046
				$dhcpdconf .= "	} else if option arch = 00:09 {\n";
1047
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1048
				$dhcpdconf .= "	} else {\n";
1049
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename']}\";\n";
1050
				$dhcpdconf .= "	}\n\n";
1051
			} elseif (!empty($dhcpifconf['filename'])) {
1052
				$dhcpdconf .= "	filename \"{$dhcpifconf['filename']}\";\n";
1053
			}
1054
			if (!empty($dhcpifconf['rootpath'])) {
1055
				$dhcpdconf .= "	option root-path \"{$dhcpifconf['rootpath']}\";\n";
1056
			}
1057
		}
1058

    
1059
		$dhcpdconf .= <<<EOD
1060
}
1061

    
1062
EOD;
1063

    
1064
		/* add static mappings */
1065
		if (is_array($dhcpifconf['staticmap'])) {
1066

    
1067
			$i = 0;
1068
			foreach ($dhcpifconf['staticmap'] as $sm) {
1069
				$dhcpdconf .= "host s_{$dhcpif}_{$i} {\n";
1070

    
1071
				if ($sm['mac']) {
1072
					$dhcpdconf .= "        hardware ethernet {$sm['mac']};\n";
1073
				}
1074

    
1075
				if ($sm['cid']) {
1076
					$dhcpdconf .= "        option dhcp-client-identifier \"{$sm['cid']}\";\n";
1077
				}
1078

    
1079
				if ($sm['ipaddr']) {
1080
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
1081
				}
1082

    
1083
				if ($sm['hostname']) {
1084
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1085
					$dhhostname = str_replace(".", "_", $dhhostname);
1086
					$dhcpdconf .= "	option host-name \"{$dhhostname}\";\n";
1087
				}
1088
				if ($sm['filename']) {
1089
					$dhcpdconf .= "	filename \"{$sm['filename']}\";\n";
1090
				}
1091

    
1092
				if ($sm['rootpath']) {
1093
					$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1094
				}
1095

    
1096
				if ($sm['gateway'] && ($sm['gateway'] != $dhcpifconf['gateway'])) {
1097
					$dhcpdconf .= "	option routers {$sm['gateway']};\n";
1098
				}
1099

    
1100
				$smdnscfg = "";
1101

    
1102
				if ($sm['domain'] && ($sm['domain'] != $dhcpifconf['domain'])) {
1103
					$smdnscfg .= "	option domain-name \"{$sm['domain']}\";\n";
1104
				}
1105

    
1106
				if (!empty($sm['domainsearchlist']) && ($sm['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
1107
					$smdnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $sm['domainsearchlist'])) . "\";\n";
1108
				}
1109

    
1110
				if (isset($sm['ddnsupdate'])) {
1111
					if (($sm['ddnsdomain'] <> "") && ($sm['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
1112
						$smdnscfg .= "		ddns-domainname \"{$sm['ddnsdomain']}\";\n";
1113
					}
1114
					$smdnscfg .= "		ddns-update-style interim;\n";
1115
				}
1116

    
1117
				if (is_array($sm['dnsserver']) && ($sm['dnsserver'][0]) && ($sm['dnsserver'][0] != $dhcpifconf['dnsserver'][0])) {
1118
					$smdnscfg .= "	option domain-name-servers " . join(",", $sm['dnsserver']) . ";\n";
1119
				}
1120
				$dhcpdconf .= "{$smdnscfg}";
1121

    
1122
				// default-lease-time
1123
				if ($sm['defaultleasetime'] && ($sm['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
1124
					$dhcpdconf .= "	default-lease-time {$sm['defaultleasetime']};\n";
1125
				}
1126

    
1127
				// max-lease-time
1128
				if ($sm['maxleasetime'] && ($sm['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
1129
					$dhcpdconf .= "	max-lease-time {$sm['maxleasetime']};\n";
1130
				}
1131

    
1132
				// netbios-name*
1133
				if (is_array($sm['winsserver']) && $sm['winsserver'][0] && ($sm['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
1134
					$dhcpdconf .= "	option netbios-name-servers " . join(",", $sm['winsserver']) . ";\n";
1135
					$dhcpdconf .= "	option netbios-node-type 8;\n";
1136
				}
1137

    
1138
				// ntp-servers
1139
				if (is_array($sm['ntpserver']) && $sm['ntpserver'][0] && ($sm['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
1140
					$dhcpdconf .= "	option ntp-servers " . join(",", $sm['ntpserver']) . ";\n";
1141
				}
1142

    
1143
				// tftp-server-name
1144
				if (!empty($sm['tftp']) && ($sm['tftp'] != $dhcpifconf['tftp'])) {
1145
					$dhcpdconf .= "	option tftp-server-name \"{$sm['tftp']}\";\n";
1146
				}
1147

    
1148
				$dhcpdconf .= "}\n";
1149
				$i++;
1150
			}
1151
		}
1152

    
1153
		$dhcpdifs[] = get_real_interface($dhcpif);
1154
		if ($newzone['domain-name']) {
1155
			if ($need_ddns_updates) {
1156
				$newzone['dns-servers'] = array($dhcpifconf['ddnsdomainprimary']);
1157
				$newzone['ddnsdomainkeyname'] = $dhcpifconf['ddnsdomainkeyname'];
1158
				$newzone['ddnsdomainkey'] = $dhcpifconf['ddnsdomainkey'];
1159
				$dhcpdconf .= dhcpdkey($dhcpifconf);
1160
			}
1161
			$ddns_zones[] = $newzone;
1162
		}
1163
	}
1164

    
1165
	if ($need_ddns_updates) {
1166
		$dhcpdconf .= "ddns-update-style interim;\n";
1167
		$dhcpdconf .= "update-static-leases on;\n";
1168

    
1169
		$dhcpdconf .= dhcpdzones($ddns_zones);
1170
	}
1171

    
1172
	/* write dhcpd.conf */
1173
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpd.conf", $dhcpdconf)) {
1174
		printf(gettext("Error: cannot open dhcpd.conf in services_dhcpdv4_configure().%s"), "\n");
1175
		unset($dhcpdconf);
1176
		return 1;
1177
	}
1178
	unset($dhcpdconf);
1179

    
1180
	/* create an empty leases database */
1181
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
1182
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
1183
	}
1184

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

    
1189
	/* fire up dhcpd in a chroot */
1190
	if (count($dhcpdifs) > 0) {
1191
		mwexec("/usr/local/sbin/dhcpd -user dhcpd -group _dhcp -chroot {$g['dhcpd_chroot_path']} -cf /etc/dhcpd.conf -pf {$g['varrun_path']}/dhcpd.pid " .
1192
			join(" ", $dhcpdifs));
1193
	}
1194

    
1195
	if (platform_booting()) {
1196
		print "done.\n";
1197
	}
1198

    
1199
	return 0;
1200
}
1201

    
1202
function dhcpdkey($dhcpifconf) {
1203
	$dhcpdconf = "";
1204
	if ($dhcpifconf['ddnsdomainkeyname'] <> "" && $dhcpifconf['ddnsdomainkey'] <> "") {
1205
		$dhcpdconf .= "key {$dhcpifconf['ddnsdomainkeyname']} {\n";
1206
		$dhcpdconf .= "	algorithm hmac-md5;\n";
1207
		$dhcpdconf .= "	secret {$dhcpifconf['ddnsdomainkey']};\n";
1208
		$dhcpdconf .= "}\n";
1209
	}
1210

    
1211
	return $dhcpdconf;
1212
}
1213

    
1214
function dhcpdzones($ddns_zones) {
1215
	$dhcpdconf = "";
1216

    
1217
	if (is_array($ddns_zones)) {
1218
		$added_zones = array();
1219
		foreach ($ddns_zones as $zone) {
1220
			if (!is_array($zone) || empty($zone) || !is_array($zone['dns-servers'])) {
1221
				continue;
1222
			}
1223
			$primary = $zone['dns-servers'][0];
1224
			$secondary = empty($zone['dns-servers'][1]) ? "" : $zone['dns-servers'][1];
1225

    
1226
			// Make sure we aren't using any invalid or IPv6 DNS servers.
1227
			if (!is_ipaddrv4($primary)) {
1228
				if (is_ipaddrv4($secondary)) {
1229
					$primary = $secondary;
1230
					$secondary = "";
1231
				} else {
1232
					continue;
1233
				}
1234
			}
1235

    
1236
			// We don't need to add zones multiple times.
1237
			if ($zone['domain-name'] && !in_array($zone['domain-name'], $added_zones)) {
1238
				$dhcpdconf .= "zone {$zone['domain-name']}. {\n";
1239
				$dhcpdconf .= "	primary {$primary};\n";
1240
				if (is_ipaddrv4($secondary)) {
1241
					$dhcpdconf .= "	secondary {$secondary};\n";
1242
				}
1243
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1244
					$dhcpdconf .= "	key {$zone['ddnsdomainkeyname']};\n";
1245
				}
1246
				$dhcpdconf .= "}\n";
1247
				$added_zones[] = $zone['domain-name'];
1248
			}
1249
			if ($zone['ptr-domain'] && !in_array($zone['ptr-domain'], $added_zones)) {
1250
				$dhcpdconf .= "zone {$zone['ptr-domain']} {\n";
1251
				$dhcpdconf .= "	primary {$primary};\n";
1252
				if (is_ipaddrv4($secondary)) {
1253
					$dhcpdconf .= "	secondary {$secondary};\n";
1254
				}
1255
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1256
					$dhcpdconf .= "	key {$zone['ddnsdomainkeyname']};\n";
1257
				}
1258
				$dhcpdconf .= "}\n";
1259
				$added_zones[] = $zone['ptr-domain'];
1260
			}
1261
		}
1262
	}
1263

    
1264
	return $dhcpdconf;
1265
}
1266

    
1267
function services_dhcpdv6_configure($blacklist = array()) {
1268
	global $config, $g;
1269

    
1270
	if ($g['services_dhcp_server_enable'] == false) {
1271
		return;
1272
	}
1273

    
1274
	if (isset($config['system']['developerspew'])) {
1275
		$mt = microtime();
1276
		echo "services_dhcpd_configure($if) being called $mt\n";
1277
	}
1278

    
1279
	/* kill any running dhcpd */
1280
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid")) {
1281
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid");
1282
	}
1283
	if (isvalidpid("{$g['varrun_path']}/dhcpleases6.pid")) {
1284
		killbypid("{$g['varrun_path']}/dhcpleases6.pid");
1285
	}
1286

    
1287
	/* DHCP enabled on any interfaces? */
1288
	if (!is_dhcpv6_server_enabled()) {
1289
		return 0;
1290
	}
1291

    
1292
	if (platform_booting() &&
1293
	    ($g['platform'] != $g['product_name'] ||
1294
	    isset($config['system']['use_mfs_tmpvar'])) &&
1295
	    file_exists("{$g['cf_conf_path']}/dhcp6leases.tgz")) {
1296
		/* restore the leases, if we have them */
1297
		$dhcprestore = "";
1298
		$dhcpreturn = "";
1299
		exec("cd /;LANG=C /usr/bin/tar -xzf {$g['cf_conf_path']}/dhcp6leases.tgz 2>&1",
1300
		    $dhcprestore, $dhcpreturn);
1301
		$dhcprestore = implode(" ", $dhcprestore);
1302
		if ($dhcpreturn <> 0) {
1303
			log_error(sprintf(gettext(
1304
			    'DHCP leases v6 restore failed exited with %1$s, the error is: %2$s'),
1305
			    $dhcpreturn, $dhcprestore));
1306
		}
1307
	}
1308

    
1309
	$syscfg = $config['system'];
1310
	if (!is_array($config['dhcpdv6'])) {
1311
		$config['dhcpdv6'] = array();
1312
	}
1313
	$dhcpdv6cfg = $config['dhcpdv6'];
1314
	$Iflist = get_configured_interface_list();
1315
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
1316

    
1317

    
1318
	if (platform_booting()) {
1319
		echo "Starting DHCPv6 service...";
1320
	} else {
1321
		sleep(1);
1322
	}
1323

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

    
1333
	if (isset($dhcpv6ifconf['netboot']) && !empty($dhcpv6ifconf['bootfile_url'])) {
1334
		$custoptionsv6 .= "option dhcp6.bootfile-url code 59 = string;\n";
1335
	}
1336

    
1337
	$dhcpdv6conf = <<<EOD
1338

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

    
1351
EOD;
1352

    
1353
	if (!isset($dhcpv6ifconf['disableauthoritative'])) {
1354
		$dhcpdv6conf .= "authoritative;\n";
1355
	}
1356

    
1357
	if (isset($dhcpv6ifconf['alwaysbroadcast'])) {
1358
		$dhcpdv6conf .= "always-broadcast on\n";
1359
	}
1360

    
1361
	$dhcpdv6ifs = array();
1362

    
1363
	$dhcpv6num = 0;
1364
	$nsupdate = false;
1365

    
1366
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1367

    
1368
		$ddns_zones = array();
1369

    
1370
		$ifcfgv6 = $config['interfaces'][$dhcpv6if];
1371

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

    
1387
		if ($is_olsr_enabled == true) {
1388
			if ($dhcpv6ifconf['netmask']) {
1389
				$subnetmask = gen_subnet_maskv6($dhcpv6ifconf['netmask']);
1390
			}
1391
		}
1392

    
1393
		$dnscfgv6 = "";
1394

    
1395
		if ($dhcpv6ifconf['domain']) {
1396
			$dnscfgv6 .= "	option domain-name \"{$dhcpv6ifconf['domain']}\";\n";
1397
		}
1398

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

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

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

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

    
1439
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1440

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

    
1461
		$dhcpdv6conf .= " {\n";
1462

    
1463
		$range_from = $dhcpv6ifconf['range']['from'];
1464
		$range_to = $dhcpv6ifconf['range']['to'];
1465
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
1466
			$range_from = merge_ipv6_delegated_prefix($ifcfgipv6, $range_from, $pdlen);
1467
			$range_to = merge_ipv6_delegated_prefix($ifcfgipv6, $range_to, $pdlen);
1468
		}
1469

    
1470
		$dhcpdv6conf .= <<<EOD
1471
	range6 {$range_from} {$range_to};
1472
$dnscfgv6
1473

    
1474
EOD;
1475

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

    
1492
		// max-lease-time
1493
		if ($dhcpv6ifconf['maxleasetime']) {
1494
			$dhcpdv6conf .= "	max-lease-time {$dhcpv6ifconf['maxleasetime']};\n";
1495
		}
1496

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

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

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

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

    
1547
		$dhcpdv6conf .= "}\n";
1548

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

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

    
1567
				if ($sm['hostname']) {
1568
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1569
					$dhhostname = str_replace(".", "_", $dhhostname);
1570
					$dhcpdv6conf .= "	option host-name {$dhhostname};\n";
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['tmp_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['tmp_path']}/igmpproxy.conf");
1703
	} else {
1704
		mwexec_bg("/usr/local/sbin/igmpproxy {$g['tmp_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
			foreach (get_staticroutes() as $rtent) {
1775
				if (ip_in_subnet($srvip, $rtent['network'])) {
1776
					$a_gateways = return_gateways_array(true);
1777
					$destif = $a_gateways[$rtent['gateway']]['interface'];
1778
					break;
1779
				}
1780
			}
1781
		}
1782

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

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

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

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

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

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

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

    
1843
	return 0;
1844
}
1845

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

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

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

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

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

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

    
1870
	$iflist = get_configured_interface_list();
1871

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

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

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

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

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

    
1946
		if (!empty($destif)) {
1947
			$srvifaces[] = "{$srvip}%{$destif}";
1948
		}
1949
	}
1950

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

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

    
1967
	return 0;
1968
}
1969

    
1970
function services_dyndns_configure_client($conf) {
1971

    
1972
	if (!isset($conf['enable'])) {
1973
		return;
1974
	}
1975

    
1976
	/* load up the dyndns.class */
1977
	require_once("dyndns.class");
1978

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

    
2002
function services_dyndns_configure($int = "") {
2003
	global $config, $g;
2004
	if (isset($config['system']['developerspew'])) {
2005
		$mt = microtime();
2006
		echo "services_dyndns_configure() being called $mt\n";
2007
	}
2008

    
2009
	$dyndnscfg = $config['dyndnses']['dyndns'];
2010
	$gwgroups = return_gateway_groups_array();
2011
	if (is_array($dyndnscfg)) {
2012
		if (platform_booting()) {
2013
			echo gettext("Starting DynDNS clients...");
2014
		}
2015

    
2016
		foreach ($dyndnscfg as $dyndns) {
2017
			/*
2018
			 * If it's using a gateway group, check if interface is
2019
			 * the active gateway for that group
2020
			 */
2021
			$group_int = '';
2022
			if (is_array($gwgroups[$dyndns['interface']])) {
2023
				if (!empty($gwgroups[$dyndns['interface']][0]['vip'])) {
2024
					$group_int = $gwgroups[$dyndns['interface']][0]['vip'];
2025
				} else {
2026
					$group_int = $gwgroups[$dyndns['interface']][0]['int'];
2027
				}
2028
			}
2029
			if ((empty($int)) || ($int == $dyndns['interface']) || ($int == $group_int)) {
2030
				$dyndns['verboselog'] = isset($dyndns['verboselog']);
2031
				$dyndns['curl_ipresolve_v4'] = isset($dyndns['curl_ipresolve_v4']);
2032
				$dyndns['curl_ssl_verifypeer'] = isset($dyndns['curl_ssl_verifypeer']);
2033
				services_dyndns_configure_client($dyndns);
2034
				sleep(1);
2035
			}
2036
		}
2037

    
2038
		if (platform_booting()) {
2039
			echo gettext("done.") . "\n";
2040
		}
2041
	}
2042

    
2043
	return 0;
2044
}
2045

    
2046
function dyndnsCheckIP($int) {
2047
	global $config, $factory_default_checkipservice;
2048
	$ip_address = get_interface_ip($int);
2049
	if (is_private_ip($ip_address)) {
2050
		$gateways_status = return_gateways_status(true);
2051
		// If the gateway for this interface is down, then the external check cannot work.
2052
		// Avoid the long wait for the external check to timeout.
2053
		if (stristr($gateways_status[$config['interfaces'][$int]['gateway']]['status'], "down")) {
2054
			return "down";
2055
		}
2056

    
2057
		// Append the factory default check IP service to the list (if not disabled).
2058
		if (!isset($config['checkipservices']['disable_factory_default'])) {
2059
			$config['checkipservices']['checkipservice'][] = $factory_default_checkipservice;
2060
		}
2061

    
2062
		// Use the first enabled check IP service as the default.
2063
		if (is_array($config['checkipservices']['checkipservice'])) {
2064
			foreach ($config['checkipservices']['checkipservice'] as $i => $checkipservice) {
2065
				if (isset($checkipservice['enable'])) {
2066
					$url = $checkipservice['url'];
2067
					$username = $checkipservice['username'];
2068
					$password = $checkipservice['password'];
2069
					$verifysslpeer = isset($checkipservice['verifysslpeer']);
2070
					break;
2071
				}
2072
			}
2073
		}
2074

    
2075
		$hosttocheck = $url;
2076
		$ip_ch = curl_init($hosttocheck);
2077
		curl_setopt($ip_ch, CURLOPT_RETURNTRANSFER, 1);
2078
		curl_setopt($ip_ch, CURLOPT_SSL_VERIFYPEER, $verifysslpeer);
2079
		curl_setopt($ip_ch, CURLOPT_INTERFACE, 'host!' . $ip_address);
2080
		curl_setopt($ip_ch, CURLOPT_CONNECTTIMEOUT, '30');
2081
		curl_setopt($ip_ch, CURLOPT_TIMEOUT, 120);
2082
		curl_setopt($ip_ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
2083
		curl_setopt($ip_ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
2084
		curl_setopt($ip_ch, CURLOPT_USERPWD, "{$username}:{$password}");
2085
		$ip_result_page = curl_exec($ip_ch);
2086
		curl_close($ip_ch);
2087
		$ip_result_decoded = urldecode($ip_result_page);
2088
		preg_match('=Current IP Address: (.*)</body>=siU', $ip_result_decoded, $matches);
2089
		$ip_address = trim($matches[1]);
2090
	}
2091
	return $ip_address;
2092
}
2093

    
2094
function services_dnsmasq_configure($restart_dhcp = true) {
2095
	global $config, $g;
2096
	$return = 0;
2097

    
2098
	// hard coded args: will be removed to avoid duplication if specified in custom_options
2099
	$standard_args = array(
2100
		"dns-forward-max" => "--dns-forward-max=5000",
2101
		"cache-size" => "--cache-size=10000",
2102
		"local-ttl" => "--local-ttl=1"
2103
	);
2104

    
2105

    
2106
	if (isset($config['system']['developerspew'])) {
2107
		$mt = microtime();
2108
		echo "services_dnsmasq_configure() being called $mt\n";
2109
	}
2110

    
2111
	/* kill any running dnsmasq */
2112
	if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) {
2113
		sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
2114
	}
2115

    
2116
	if (isset($config['dnsmasq']['enable'])) {
2117

    
2118
		if (platform_booting()) {
2119
			echo gettext("Starting DNS forwarder...");
2120
		} else {
2121
			sleep(1);
2122
		}
2123

    
2124
		/* generate hosts file */
2125
		if (system_hosts_generate() != 0) {
2126
			$return = 1;
2127
		}
2128

    
2129
		$args = "";
2130

    
2131
		if (isset($config['dnsmasq']['regdhcp'])) {
2132
			$args .= " --dhcp-hostsfile={$g['varetc_path']}/hosts ";
2133
		}
2134

    
2135
		/* Setup listen port, if non-default */
2136
		if (is_port($config['dnsmasq']['port'])) {
2137
			$args .= " --port={$config['dnsmasq']['port']} ";
2138
		}
2139

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

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

    
2180
			// Build an array of domain overrides to help in checking for matches.
2181
			$override_a = array();
2182
			if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2183
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2184
					$override_a[$override['domain']] = "y";
2185
				}
2186
			}
2187

    
2188
			// Build an array of the private reverse lookup domain names
2189
			$reverse_domain_a = array("10.in-addr.arpa", "168.192.in-addr.arpa");
2190
			// Unfortunately the 172.16.0.0/12 range does not map nicely to the in-addr.arpa scheme.
2191
			for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) {
2192
				$reverse_domain_a[] = "$subnet_num.172.in-addr.arpa";
2193
			}
2194

    
2195
			// Set the --server parameter to nowhere for each reverse domain name that was not specifically specified in a domain override.
2196
			foreach ($reverse_domain_a as $reverse_domain) {
2197
				if (!isset($override_a[$reverse_domain])) {
2198
					$args .= " --server=/$reverse_domain/ ";
2199
				}
2200
			}
2201
			unset($override_a);
2202
			unset($reverse_domain_a);
2203
		}
2204

    
2205
		/* Setup forwarded domains */
2206
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2207
			foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2208
				if ($override['ip'] == "!") {
2209
					$override[ip] = "";
2210
				}
2211
				$args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
2212
			}
2213
		}
2214

    
2215
		/* Allow DNS Rebind for forwarded domains */
2216
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2217
			if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2218
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2219
					$args .= ' --rebind-domain-ok=/' . $override['domain'] . '/ ';
2220
				}
2221
			}
2222
		}
2223

    
2224
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2225
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2226
		}
2227

    
2228
		if (isset($config['dnsmasq']['strict_order'])) {
2229
			$args .= " --strict-order ";
2230
		}
2231

    
2232
		if (isset($config['dnsmasq']['domain_needed'])) {
2233
			$args .= " --domain-needed ";
2234
		}
2235

    
2236
		if ($config['dnsmasq']['custom_options']) {
2237
			foreach (preg_split('/\s+/', $config['dnsmasq']['custom_options']) as $c) {
2238
				$args .= " " . escapeshellarg("--{$c}");
2239
				$p = explode('=', $c);
2240
				if (array_key_exists($p[0], $standard_args)) {
2241
					unset($standard_args[$p[0]]);
2242
				}
2243
			}
2244
		}
2245
		$args .= ' ' . implode(' ', array_values($standard_args));
2246

    
2247
		/* run dnsmasq. Use "-C /dev/null" since we use command line args only (Issue #6730) */
2248
		$cmd = "/usr/local/sbin/dnsmasq --all-servers -C /dev/null {$dns_rebind} {$args}";
2249
		//log_error("dnsmasq command: {$cmd}");
2250
		mwexec_bg($cmd);
2251
		unset($args);
2252

    
2253
		system_dhcpleases_configure();
2254

    
2255
		if (platform_booting()) {
2256
			echo gettext("done.") . "\n";
2257
		}
2258
	}
2259

    
2260
	if (!platform_booting() && $restart_dhcp) {
2261
		if (services_dhcpd_configure() != 0) {
2262
			$return = 1;
2263
		}
2264
	}
2265

    
2266
	return $return;
2267
}
2268

    
2269
function services_unbound_configure($restart_dhcp = true) {
2270
	global $config, $g;
2271
	$return = 0;
2272

    
2273
	if (isset($config['system']['developerspew'])) {
2274
		$mt = microtime();
2275
		echo "services_unbound_configure() being called $mt\n";
2276
	}
2277

    
2278
	// kill any running Unbound instance
2279
	if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2280
		sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
2281
	}
2282

    
2283
	if (isset($config['unbound']['enable'])) {
2284
		if (platform_booting()) {
2285
			echo gettext("Starting DNS Resolver...");
2286
		} else {
2287
			sleep(1);
2288
		}
2289

    
2290
		/* generate hosts file */
2291
		if (system_hosts_generate() != 0) {
2292
			$return = 1;
2293
		}
2294

    
2295
		require_once('/etc/inc/unbound.inc');
2296
		sync_unbound_service();
2297
		if (platform_booting()) {
2298
			echo gettext("done.") . "\n";
2299
		}
2300

    
2301
		system_dhcpleases_configure();
2302
	}
2303

    
2304
	if (!platform_booting() && $restart_dhcp) {
2305
		if (services_dhcpd_configure() != 0) {
2306
			$return = 1;
2307
		}
2308
	}
2309

    
2310
	return $return;
2311
}
2312

    
2313
function services_snmpd_configure() {
2314
	global $config, $g;
2315
	if (isset($config['system']['developerspew'])) {
2316
		$mt = microtime();
2317
		echo "services_snmpd_configure() being called $mt\n";
2318
	}
2319

    
2320
	/* kill any running snmpd */
2321
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
2322
	sleep(2);
2323
	if (is_process_running("bsnmpd")) {
2324
		mwexec("/usr/bin/killall bsnmpd", true);
2325
	}
2326

    
2327
	if (isset($config['snmpd']['enable'])) {
2328

    
2329
		if (platform_booting()) {
2330
			echo gettext("Starting SNMP daemon... ");
2331
		}
2332

    
2333
		/* generate snmpd.conf */
2334
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
2335
		if (!$fd) {
2336
			printf(gettext("Error: cannot open snmpd.conf in services_snmpd_configure().%s"), "\n");
2337
			return 1;
2338
		}
2339

    
2340

    
2341
		$snmpdconf = <<<EOD
2342
location := "{$config['snmpd']['syslocation']}"
2343
contact := "{$config['snmpd']['syscontact']}"
2344
read := "{$config['snmpd']['rocommunity']}"
2345

    
2346
EOD;
2347

    
2348
/* No docs on what write strings do there so disable for now.
2349
		if (isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])) {
2350
			$snmpdconf .= <<<EOD
2351
# write string
2352
write := "{$config['snmpd']['rwcommunity']}"
2353

    
2354
EOD;
2355
		}
2356
*/
2357

    
2358

    
2359
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2360
			$snmpdconf .= <<<EOD
2361
# SNMP Trap support.
2362
traphost := {$config['snmpd']['trapserver']}
2363
trapport := {$config['snmpd']['trapserverport']}
2364
trap := "{$config['snmpd']['trapstring']}"
2365

    
2366

    
2367
EOD;
2368
		}
2369

    
2370
		$platform = trim(file_get_contents('/etc/platform'));
2371
		if (($platform == "pfSense") && ($g['product_name'] != "pfSense")) {
2372
			$platform = $g['product_name'];
2373
		}
2374
		$sysDescr = "{$g['product_name']} " . php_uname("n") .
2375
			" {$g['product_version']} {$platform} " . php_uname("s") .
2376
			" " . php_uname("r") . " " . php_uname("m");
2377

    
2378
		$snmpdconf .= <<<EOD
2379
system := 1     # pfSense
2380
%snmpd
2381
sysDescr			= "{$sysDescr}"
2382
begemotSnmpdDebugDumpPdus       = 2
2383
begemotSnmpdDebugSyslogPri      = 7
2384
begemotSnmpdCommunityString.0.1 = $(read)
2385

    
2386
EOD;
2387

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

    
2393
EOD;
2394
		}
2395
*/
2396

    
2397

    
2398
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2399
			$snmpdconf .= <<<EOD
2400
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
2401
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
2402
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
2403

    
2404
EOD;
2405
		}
2406

    
2407

    
2408
		$snmpdconf .= <<<EOD
2409
begemotSnmpdCommunityDisable    = 1
2410

    
2411
EOD;
2412

    
2413
		$bind_to_ip = "0.0.0.0";
2414
		if (isset($config['snmpd']['bindip'])) {
2415
			if (is_ipaddr($config['snmpd']['bindip'])) {
2416
				$bind_to_ip = $config['snmpd']['bindip'];
2417
			} else {
2418
				$if = get_real_interface($config['snmpd']['bindip']);
2419
				if (does_interface_exist($if)) {
2420
					$bind_to_ip = get_interface_ip($config['snmpd']['bindip']);
2421
				}
2422
			}
2423
		}
2424

    
2425
		if (is_port($config['snmpd']['pollport'])) {
2426
			$snmpdconf .= <<<EOD
2427
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
2428

    
2429
EOD;
2430

    
2431
		}
2432

    
2433
		$snmpdconf .= <<<EOD
2434
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
2435
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
2436

    
2437
# These are bsnmp macros not php vars.
2438
sysContact      = $(contact)
2439
sysLocation     = $(location)
2440
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
2441

    
2442
snmpEnableAuthenTraps = 2
2443

    
2444
EOD;
2445

    
2446
		if (is_array($config['snmpd']['modules'])) {
2447
			if (isset($config['snmpd']['modules']['mibii'])) {
2448
			$snmpdconf .= <<<EOD
2449
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
2450

    
2451
EOD;
2452
			}
2453

    
2454
			if (isset($config['snmpd']['modules']['netgraph'])) {
2455
				$snmpdconf .= <<<EOD
2456
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
2457
%netgraph
2458
begemotNgControlNodeName = "snmpd"
2459

    
2460
EOD;
2461
			}
2462

    
2463
			if (isset($config['snmpd']['modules']['pf'])) {
2464
				$snmpdconf .= <<<EOD
2465
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
2466

    
2467
EOD;
2468
			}
2469

    
2470
			if (isset($config['snmpd']['modules']['hostres'])) {
2471
				$snmpdconf .= <<<EOD
2472
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
2473

    
2474
EOD;
2475
			}
2476

    
2477
			if (isset($config['snmpd']['modules']['bridge'])) {
2478
				$snmpdconf .= <<<EOD
2479
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
2480
# config must end with blank line
2481

    
2482
EOD;
2483
			}
2484
			if (isset($config['snmpd']['modules']['ucd'])) {
2485
				$snmpdconf .= <<<EOD
2486
begemotSnmpdModulePath."ucd"     = "/usr/local/lib/snmp_ucd.so"
2487

    
2488
EOD;
2489
			}
2490
			if (isset($config['snmpd']['modules']['regex'])) {
2491
				$snmpdconf .= <<<EOD
2492
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"
2493

    
2494
EOD;
2495
			}
2496
		}
2497

    
2498
		fwrite($fd, $snmpdconf);
2499
		fclose($fd);
2500
		unset($snmpdconf);
2501

    
2502
		/* run bsnmpd */
2503
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
2504
			" -p {$g['varrun_path']}/snmpd.pid");
2505

    
2506
		if (platform_booting()) {
2507
			echo gettext("done.") . "\n";
2508
		}
2509
	}
2510

    
2511
	return 0;
2512
}
2513

    
2514
function services_dnsupdate_process($int = "", $updatehost = "", $forced = false) {
2515
	global $config, $g;
2516
	if (isset($config['system']['developerspew'])) {
2517
		$mt = microtime();
2518
		echo "services_dnsupdate_process() being called $mt\n";
2519
	}
2520

    
2521
	/* Dynamic DNS updating active? */
2522
	if (is_array($config['dnsupdates']['dnsupdate'])) {
2523
		$notify_text = "";
2524
		$gwgroups = return_gateway_groups_array();
2525
		foreach ($config['dnsupdates']['dnsupdate'] as $i => $dnsupdate) {
2526
			if (!isset($dnsupdate['enable'])) {
2527
				continue;
2528
			}
2529
			/*
2530
			 * If it's using a gateway group, check if interface is
2531
			 * the active gateway for that group
2532
			 */
2533
			$group_int = '';
2534
			if (is_array($gwgroups[$dnsupdate['interface']])) {
2535
				if (!empty($gwgroups[$dnsupdate['interface']][0]['vip'])) {
2536
					$group_int = $gwgroups[$dnsupdate['interface']][0]['vip'];
2537
				} else {
2538
					$group_int = $gwgroups[$dnsupdate['interface']][0]['int'];
2539
				}
2540
			}
2541
			if (!empty($int) && ($int != $dnsupdate['interface']) && ($int != $group_int)) {
2542
				continue;
2543
			}
2544
			if (!empty($updatehost) && ($updatehost != $dnsupdate['host'])) {
2545
				continue;
2546
			}
2547

    
2548
			/* determine interface name */
2549
			$if = get_failover_interface($dnsupdate['interface']);
2550

    
2551
			if (isset($dnsupdate['usepublicip'])) {
2552
				$wanip = dyndnsCheckIP($if);
2553
			} else {
2554
				$wanip = get_interface_ip($if);
2555
			}
2556

    
2557
			$wanipv6 = get_interface_ipv6($if);
2558
			$cacheFile = "{$g['conf_path']}/dyndns_{$dnsupdate['interface']}_rfc2136_" . escapeshellarg($dnsupdate['host']) . "_{$dnsupdate['server']}.cache";
2559
			$currentTime = time();
2560

    
2561
			if ($wanip || $wanipv6) {
2562
				$keyname = $dnsupdate['keyname'];
2563
				/* trailing dot */
2564
				if (substr($keyname, -1) != ".") {
2565
					$keyname .= ".";
2566
				}
2567

    
2568
				$hostname = $dnsupdate['host'];
2569
				/* trailing dot */
2570
				if (substr($hostname, -1) != ".") {
2571
					$hostname .= ".";
2572
				}
2573

    
2574
				/* write private key file
2575
				   this is dumb - public and private keys are the same for HMAC-MD5,
2576
				   but nsupdate insists on having both */
2577
				$fd = fopen("{$g['varetc_path']}/K{$i}{$keyname}+157+00000.private", "w");
2578
				$privkey = <<<EOD
2579
Private-key-format: v1.2
2580
Algorithm: 157 (HMAC)
2581
Key: {$dnsupdate['keydata']}
2582

    
2583
EOD;
2584
				fwrite($fd, $privkey);
2585
				fclose($fd);
2586

    
2587
				/* write public key file */
2588
				if ($dnsupdate['keytype'] == "zone") {
2589
					$flags = 257;
2590
					$proto = 3;
2591
				} else if ($dnsupdate['keytype'] == "host") {
2592
					$flags = 513;
2593
					$proto = 3;
2594
				} else if ($dnsupdate['keytype'] == "user") {
2595
					$flags = 0;
2596
					$proto = 2;
2597
				}
2598

    
2599
				$fd = fopen("{$g['varetc_path']}/K{$i}{$keyname}+157+00000.key", "w");
2600
				fwrite($fd, "{$keyname} IN KEY {$flags} {$proto} 157 {$dnsupdate['keydata']}\n");
2601
				fclose($fd);
2602

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

    
2609
				if (file_exists($cacheFile)) {
2610
					list($cachedipv4, $cacheTimev4) = explode("|", file_get_contents($cacheFile));
2611
				}
2612
				if (file_exists("{$cacheFile}.ipv6")) {
2613
					list($cachedipv6, $cacheTimev6) = explode("|", file_get_contents("{$cacheFile}.ipv6"));
2614
				}
2615

    
2616
				// 25 Days
2617
				$maxCacheAgeSecs = 25 * 24 * 60 * 60;
2618
				$need_update = false;
2619

    
2620
				conf_mount_rw();
2621
				/* Update IPv4 if we have it. */
2622
				if (is_ipaddrv4($wanip) && $dnsupdate['recordtype'] != "AAAA") {
2623
					if (($wanip != $cachedipv4) || (($currentTime - $cacheTimev4) > $maxCacheAgeSecs) || $forced) {
2624
						$upinst .= "update delete {$dnsupdate['host']}. A\n";
2625
						$upinst .= "update add {$dnsupdate['host']}. {$dnsupdate['ttl']} A {$wanip}\n";
2626
						$notify_text .= sprintf(gettext('DynDNS updated IP Address (A) for %1$s on %2$s (%3$s) to %4$s'), $dnsupdate['host'], convert_real_interface_to_friendly_descr($if), $if, $wanip) . "\n";
2627
						@file_put_contents($cacheFile, "{$wanip}|{$currentTime}");
2628
						log_error(sprintf(gettext('phpDynDNS: updating cache file %1$s: %2$s'), $cacheFile, $wanip));
2629
						$need_update = true;
2630
					} else {
2631
						log_error(sprintf(gettext("phpDynDNS: Not updating %s A record because the IP address has not changed."), $dnsupdate['host']));
2632
					}
2633
				} else {
2634
					@unlink($cacheFile);
2635
				}
2636

    
2637
				/* Update IPv6 if we have it. */
2638
				if (is_ipaddrv6($wanipv6) && $dnsupdate['recordtype'] != "A") {
2639
					if (($wanipv6 != $cachedipv6) || (($currentTime - $cacheTimev6) > $maxCacheAgeSecs) || $forced) {
2640
						$upinst .= "update delete {$dnsupdate['host']}. AAAA\n";
2641
						$upinst .= "update add {$dnsupdate['host']}. {$dnsupdate['ttl']} AAAA {$wanipv6}\n";
2642
						$notify_text .= sprintf(gettext('DynDNS updated IPv6 Address (AAAA) for %1$s on %2$s (%3$s) to %4$s'), $dnsupdate['host'], convert_real_interface_to_friendly_descr($if), $if, $wanipv6) . "\n";
2643
						@file_put_contents("{$cacheFile}.ipv6", "{$wanipv6}|{$currentTime}");
2644
						log_error(sprintf(gettext('phpDynDNS: updating cache file %1$s.ipv6: %2$s'), $cacheFile, $wanipv6));
2645
						$need_update = true;
2646
					} else {
2647
						log_error(sprintf(gettext("phpDynDNS: Not updating %s AAAA record because the IPv6 address has not changed."), $dnsupdate['host']));
2648
					}
2649
				} else {
2650
					@unlink("{$cacheFile}.ipv6");
2651
				}
2652
				conf_mount_ro();
2653

    
2654
				$upinst .= "\n";	/* mind that trailing newline! */
2655

    
2656
				if ($need_update) {
2657
					@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}", $upinst);
2658
					unset($upinst);
2659
					/* invoke nsupdate */
2660
					$cmd = "/usr/local/bin/nsupdate -k {$g['varetc_path']}/K{$i}{$keyname}+157+00000.key";
2661
					if (isset($dnsupdate['usetcp'])) {
2662
						$cmd .= " -v";
2663
					}
2664
					$cmd .= " {$g['varetc_path']}/nsupdatecmds{$i}";
2665
					mwexec_bg($cmd);
2666
					unset($cmd);
2667
				}
2668
			}
2669
		}
2670
		if (!empty($notify_text)) {
2671
			notify_all_remote($notify_text);
2672
		}
2673
	}
2674

    
2675
	return 0;
2676
}
2677

    
2678
/* configure cron service */
2679
function configure_cron() {
2680
	global $g, $config;
2681

    
2682
	conf_mount_rw();
2683
	/* preserve existing crontab entries */
2684
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2685

    
2686
	for ($i = 0; $i < count($crontab_contents); $i++) {
2687
		$cron_item =& $crontab_contents[$i];
2688
		if (strpos($cron_item, "# pfSense specific crontab entries") !== false) {
2689
			array_splice($crontab_contents, $i - 1);
2690
			break;
2691
		}
2692
	}
2693
	$crontab_contents = implode("\n", $crontab_contents) . "\n";
2694

    
2695

    
2696
	if (is_array($config['cron']['item'])) {
2697
		$crontab_contents .= "#\n";
2698
		$crontab_contents .= "# pfSense specific crontab entries\n";
2699
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
2700
		$crontab_contents .= "#\n";
2701

    
2702
		if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) {
2703
			$http_proxy = $config['system']['proxyurl'];
2704
			if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) {
2705
				$http_proxy .= ':' . $config['system']['proxyport'];
2706
			}
2707
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
2708
		}
2709

    
2710
		foreach ($config['cron']['item'] as $item) {
2711
			$crontab_contents .= "\n{$item['minute']}\t";
2712
			$crontab_contents .= "{$item['hour']}\t";
2713
			$crontab_contents .= "{$item['mday']}\t";
2714
			$crontab_contents .= "{$item['month']}\t";
2715
			$crontab_contents .= "{$item['wday']}\t";
2716
			$crontab_contents .= "{$item['who']}\t";
2717
			$crontab_contents .= "{$item['command']}";
2718
		}
2719

    
2720
		$crontab_contents .= "\n#\n";
2721
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
2722
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
2723
		$crontab_contents .= "#\n\n";
2724
	}
2725

    
2726
	/* please maintain the newline at the end of file */
2727
	file_put_contents("/etc/crontab", $crontab_contents);
2728
	unset($crontab_contents);
2729

    
2730
	/* make sure that cron is running and start it if it got killed somehow */
2731
	if (!is_process_running("cron")) {
2732
		exec("cd /tmp && /usr/sbin/cron -s 2>/dev/null");
2733
	} else {
2734
	/* do a HUP kill to force sync changes */
2735
		sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP");
2736
	}
2737

    
2738
	conf_mount_ro();
2739
}
2740

    
2741
function upnp_action ($action) {
2742
	global $g, $config;
2743
	switch ($action) {
2744
		case "start":
2745
			if (file_exists('/var/etc/miniupnpd.conf')) {
2746
				@unlink("{$g['varrun_path']}/miniupnpd.pid");
2747
				mwexec_bg("/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf -P {$g['varrun_path']}/miniupnpd.pid");
2748
			}
2749
			break;
2750
		case "stop":
2751
			killbypid("{$g['varrun_path']}/miniupnpd.pid");
2752
			while ((int)exec("/bin/pgrep -a miniupnpd | wc -l") > 0) {
2753
				mwexec('/usr/bin/killall miniupnpd 2>/dev/null', true);
2754
			}
2755
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
2756
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
2757
			break;
2758
		case "restart":
2759
			upnp_action('stop');
2760
			upnp_action('start');
2761
			break;
2762
	}
2763
}
2764

    
2765
function upnp_start() {
2766
	global $config;
2767

    
2768
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
2769
		return;
2770
	}
2771

    
2772
	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
2773
		echo gettext("Starting UPnP service... ");
2774
		require_once('/usr/local/pkg/miniupnpd.inc');
2775
		sync_package_miniupnpd();
2776
		echo "done.\n";
2777
	}
2778
}
2779

    
2780
function install_cron_job($command, $active = false, $minute = "0", $hour = "*", $monthday = "*", $month = "*", $weekday = "*", $who = "root") {
2781
	global $config, $g;
2782

    
2783
	$is_installed = false;
2784
	$cron_changed = true;
2785

    
2786
	if (!is_array($config['cron'])) {
2787
		$config['cron'] = array();
2788
	}
2789
	if (!is_array($config['cron']['item'])) {
2790
		$config['cron']['item'] = array();
2791
	}
2792

    
2793
	$x = 0;
2794
	foreach ($config['cron']['item'] as $item) {
2795
		if (strstr($item['command'], $command)) {
2796
			$is_installed = true;
2797
			break;
2798
		}
2799
		$x++;
2800
	}
2801

    
2802
	if ($active) {
2803
		$cron_item = array();
2804
		$cron_item['minute'] = $minute;
2805
		$cron_item['hour'] = $hour;
2806
		$cron_item['mday'] = $monthday;
2807
		$cron_item['month'] = $month;
2808
		$cron_item['wday'] = $weekday;
2809
		$cron_item['who'] = $who;
2810
		$cron_item['command'] = $command;
2811
		if (!$is_installed) {
2812
			$config['cron']['item'][] = $cron_item;
2813
			write_config(sprintf(gettext("Installed cron job for %s"), $command));
2814
		} else {
2815
			if ($config['cron']['item'][$x] == $cron_item) {
2816
				$cron_changed = false;
2817
				log_error(sprintf(gettext("Checked cron job for %s, no change needed"), $command));
2818
			} else {
2819
				$config['cron']['item'][$x] = $cron_item;
2820
				write_config(sprintf(gettext("Updated cron job for %s"), $command));
2821
			}
2822
		}
2823
	} else {
2824
		if ($is_installed == true) {
2825
			unset($config['cron']['item'][$x]);
2826
			write_config(sprintf(gettext("Removed cron job for %s"), $command));
2827
		}
2828
	}
2829

    
2830
	if ($cron_changed) {
2831
		configure_cron();
2832
	}
2833
}
2834

    
2835
?>
(49-49/65)