Project

General

Profile

Download (89.5 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 hover 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,Hover,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
				$dhcpdconf_pri = '';
651
			} else {
652
				$my_port = "519";
653
				$peer_port = "520";
654
				$type = "primary";
655
				$dhcpdconf_pri = "split 128;\n";
656
				$dhcpdconf_pri .= "  mclt 600;\n";
657
			}
658

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

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

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

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

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

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

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

    
707
		$dnscfg = "";
708

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

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

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

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

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

    
746
			}
747

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

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

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

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

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

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

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

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

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

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

    
887
			$pdnscfg = "";
888

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
994
		$dhcpdconf .= <<<EOD
995
$dnscfg
996

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

    
1003
		// max-lease-time
1004
		if ($dhcpifconf['maxleasetime']) {
1005
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
1006
		}
1007

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

    
1014
		// ntp-servers
1015
		if (is_array($dhcpifconf['ntpserver']) && $dhcpifconf['ntpserver'][0]) {
1016
			$dhcpdconf .= "	option ntp-servers " . join(",", $dhcpifconf['ntpserver']) . ";\n";
1017
		}
1018

    
1019
		// tftp-server-name
1020
		if ($dhcpifconf['tftp'] <> "") {
1021
			$dhcpdconf .= "	option tftp-server-name \"{$dhcpifconf['tftp']}\";\n";
1022
		}
1023

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

    
1037
		// ldap-server
1038
		if ($dhcpifconf['ldap'] <> "") {
1039
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
1040
		}
1041

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

    
1065
		$dhcpdconf .= <<<EOD
1066
}
1067

    
1068
EOD;
1069

    
1070
		/* add static mappings */
1071
		if (is_array($dhcpifconf['staticmap'])) {
1072

    
1073
			$i = 0;
1074
			foreach ($dhcpifconf['staticmap'] as $sm) {
1075
				$dhcpdconf .= "host s_{$dhcpif}_{$i} {\n";
1076

    
1077
				if ($sm['mac']) {
1078
					$dhcpdconf .= "        hardware ethernet {$sm['mac']};\n";
1079
				}
1080

    
1081
				if ($sm['cid']) {
1082
					$dhcpdconf .= "        option dhcp-client-identifier \"{$sm['cid']}\";\n";
1083
				}
1084

    
1085
				if ($sm['ipaddr']) {
1086
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
1087
				}
1088

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

    
1101
				if ($sm['rootpath']) {
1102
					$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1103
				}
1104

    
1105
				if ($sm['gateway'] && ($sm['gateway'] != $dhcpifconf['gateway'])) {
1106
					$dhcpdconf .= "	option routers {$sm['gateway']};\n";
1107
				}
1108

    
1109
				$smdnscfg = "";
1110

    
1111
				if ($sm['domain'] && ($sm['domain'] != $dhcpifconf['domain'])) {
1112
					$smdnscfg .= "	option domain-name \"{$sm['domain']}\";\n";
1113
				}
1114

    
1115
				if (!empty($sm['domainsearchlist']) && ($sm['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
1116
					$smdnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $sm['domainsearchlist'])) . "\";\n";
1117
				}
1118

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

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

    
1131
				// default-lease-time
1132
				if ($sm['defaultleasetime'] && ($sm['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
1133
					$dhcpdconf .= "	default-lease-time {$sm['defaultleasetime']};\n";
1134
				}
1135

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

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

    
1147
				// ntp-servers
1148
				if (is_array($sm['ntpserver']) && $sm['ntpserver'][0] && ($sm['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
1149
					$dhcpdconf .= "	option ntp-servers " . join(",", $sm['ntpserver']) . ";\n";
1150
				}
1151

    
1152
				// tftp-server-name
1153
				if (!empty($sm['tftp']) && ($sm['tftp'] != $dhcpifconf['tftp'])) {
1154
					$dhcpdconf .= "	option tftp-server-name \"{$sm['tftp']}\";\n";
1155
				}
1156

    
1157
				$dhcpdconf .= "}\n";
1158
				$i++;
1159
			}
1160
		}
1161

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

    
1174
	if ($need_ddns_updates) {
1175
		$dhcpdconf .= "ddns-update-style interim;\n";
1176
		$dhcpdconf .= "update-static-leases on;\n";
1177

    
1178
		$dhcpdconf .= dhcpdzones($ddns_zones);
1179
	}
1180

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

    
1189
	/* create an empty leases database */
1190
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
1191
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
1192
	}
1193

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

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

    
1204
	if (platform_booting()) {
1205
		print "done.\n";
1206
	}
1207

    
1208
	return 0;
1209
}
1210

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

    
1220
	return $dhcpdconf;
1221
}
1222

    
1223
function dhcpdzones($ddns_zones) {
1224
	$dhcpdconf = "";
1225

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

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

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

    
1273
	return $dhcpdconf;
1274
}
1275

    
1276
function services_dhcpdv6_configure($blacklist = array()) {
1277
	global $config, $g;
1278

    
1279
	if ($g['services_dhcp_server_enable'] == false) {
1280
		return;
1281
	}
1282

    
1283
	if (isset($config['system']['developerspew'])) {
1284
		$mt = microtime();
1285
		echo "services_dhcpd_configure($if) being called $mt\n";
1286
	}
1287

    
1288
	/* kill any running dhcpd */
1289
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid")) {
1290
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid");
1291
	}
1292
	if (isvalidpid("{$g['varrun_path']}/dhcpleases6.pid")) {
1293
		killbypid("{$g['varrun_path']}/dhcpleases6.pid");
1294
	}
1295

    
1296
	/* DHCP enabled on any interfaces? */
1297
	if (!is_dhcpv6_server_enabled()) {
1298
		return 0;
1299
	}
1300

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

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

    
1326

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

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

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

    
1346
	$dhcpdv6conf = <<<EOD
1347

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

    
1360
EOD;
1361

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

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

    
1370
	$dhcpdv6ifs = array();
1371

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

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

    
1377
		$ddns_zones = array();
1378

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

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

    
1396
		if ($is_olsr_enabled == true) {
1397
			if ($dhcpv6ifconf['netmask']) {
1398
				$subnetmask = gen_subnet_maskv6($dhcpv6ifconf['netmask']);
1399
			}
1400
		}
1401

    
1402
		$dnscfgv6 = "";
1403

    
1404
		if ($dhcpv6ifconf['domain']) {
1405
			$dnscfgv6 .= "	option domain-name \"{$dhcpv6ifconf['domain']}\";\n";
1406
		}
1407

    
1408
		if ($dhcpv6ifconf['domainsearchlist'] <> "") {
1409
			$dnscfgv6 .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpv6ifconf['domainsearchlist'])) . "\";\n";
1410
		}
1411

    
1412
		if (isset($dhcpv6ifconf['ddnsupdate'])) {
1413
			if ($dhcpv6ifconf['ddnsdomain'] <> "") {
1414
				$dnscfgv6 .= "	ddns-domainname \"{$dhcpv6ifconf['ddnsdomain']}\";\n";
1415
			}
1416
			if (empty($dhcpv6ifconf['ddnsclientupdates'])) {
1417
				$ddnsclientupdates = 'allow';
1418
			} else {
1419
				$ddnsclientupdates = $dhcpv6ifconf['ddnsclientupdates'];
1420
			}
1421
			$dnscfgv6 .= "	{$ddnsclientupdates} client-updates;\n";
1422
			$nsupdate = true;
1423
		} else {
1424
			$dnscfgv6 .= "	do-forward-updates false;\n";
1425
		}
1426

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

    
1443
		if (!is_ipaddrv6($ifcfgipv6)) {
1444
			$ifcfgsnv6 = "64";
1445
			$subnetv6 = gen_subnetv6($dhcpv6ifconf['range']['from'], $ifcfgsnv6);
1446
		}
1447

    
1448
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1449

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

    
1470
		$dhcpdv6conf .= " {\n";
1471

    
1472
		$range_from = $dhcpv6ifconf['range']['from'];
1473
		$range_to = $dhcpv6ifconf['range']['to'];
1474
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
1475
			$range_from = merge_ipv6_delegated_prefix($ifcfgipv6, $range_from, $pdlen);
1476
			$range_to = merge_ipv6_delegated_prefix($ifcfgipv6, $range_to, $pdlen);
1477
		}
1478

    
1479
		$dhcpdv6conf .= <<<EOD
1480
	range6 {$range_from} {$range_to};
1481
$dnscfgv6
1482

    
1483
EOD;
1484

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

    
1501
		// max-lease-time
1502
		if ($dhcpv6ifconf['maxleasetime']) {
1503
			$dhcpdv6conf .= "	max-lease-time {$dhcpv6ifconf['maxleasetime']};\n";
1504
		}
1505

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

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

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

    
1549
		// net boot information
1550
		if (isset($dhcpv6ifconf['netboot'])) {
1551
			if (!empty($dhcpv6ifconf['bootfile_url'])) {
1552
				$dhcpdv6conf .= "	option dhcp6.bootfile-url \"{$dhcpv6ifconf['bootfile_url']}\";\n";
1553
			}
1554
		}
1555

    
1556
		$dhcpdv6conf .= "}\n";
1557

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

    
1567
EOD;
1568
				if ($sm['ipaddrv6']) {
1569
					$ipaddrv6 = $sm['ipaddrv6'];
1570
					if ($ifcfgv6['ipaddrv6'] == 'track6') {
1571
						$ipaddrv6 = merge_ipv6_delegated_prefix($ifcfgipv6, $ipaddrv6, $pdlen);
1572
					}
1573
					$dhcpdv6conf .= "	fixed-address6 {$ipaddrv6};\n";
1574
				}
1575

    
1576
				if ($sm['hostname']) {
1577
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1578
					$dhhostname = str_replace(".", "_", $dhhostname);
1579
					$dhcpdv6conf .= "	option host-name {$dhhostname};\n";
1580
				}
1581
				if ($sm['filename']) {
1582
					$dhcpdv6conf .= "	filename \"{$sm['filename']}\";\n";
1583
				}
1584

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

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

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

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

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

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

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

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

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

    
1653
	return 0;
1654
}
1655

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

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

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

    
1666
	$iflist = get_configured_interface_list();
1667

    
1668
	$igmpconf = <<<EOD
1669

    
1670
##------------------------------------------------------
1671
## Enable Quickleave mode (Sends Leave instantly)
1672
##------------------------------------------------------
1673
quickleave
1674

    
1675
EOD;
1676

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

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

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

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

    
1716
	log_error(gettext("Started IGMP proxy service."));
1717

    
1718
	return 0;
1719
}
1720

    
1721
function services_dhcrelay_configure() {
1722
	global $config, $g;
1723

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

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

    
1732
	$dhcrelaycfg =& $config['dhcrelay'];
1733

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

    
1739
	if (platform_booting()) {
1740
		echo gettext("Starting DHCP relay service...");
1741
	} else {
1742
		sleep(1);
1743
	}
1744

    
1745
	$iflist = get_configured_interface_list();
1746

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

    
1754
		if (is_ipaddr(get_interface_ip($dhcrelayif))) {
1755
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1756
		}
1757
	}
1758

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

    
1769
	foreach ($srvips as $srcidx => $srvip) {
1770
		unset($destif);
1771
		foreach ($iflist as $ifname) {
1772
			$subnet = get_interface_ip($ifname);
1773
			if (!is_ipaddr($subnet)) {
1774
				continue;
1775
			}
1776
			$subnet .= "/" . get_interface_subnet($ifname);
1777
			if (ip_in_subnet($srvip, $subnet)) {
1778
				$destif = get_real_interface($ifname);
1779
				break;
1780
			}
1781
		}
1782
		if (!isset($destif)) {
1783
			// For each enabled static route
1784
			foreach (get_staticroutes(false, false, true) as $rtent) {
1785
				if (ip_in_subnet($srvip, $rtent['network'])) {
1786
					$a_gateways = return_gateways_array(true);
1787
					$destif = $a_gateways[$rtent['gateway']]['interface'];
1788
					break;
1789
				}
1790
			}
1791
		}
1792

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

    
1818
		if (!isset($destif)) {
1819
			if (is_array($config['gateways']['gateway_item'])) {
1820
				foreach ($config['gateways']['gateway_item'] as $gateway) {
1821
					if (isset($gateway['defaultgw'])) {
1822
						$destif = get_real_interface($gateway['interface']);
1823
						break;
1824
					}
1825
				}
1826
			} else {
1827
				$destif = get_real_interface("wan");
1828
			}
1829
		}
1830

    
1831
		if (!empty($destif)) {
1832
			$dhcrelayifs[] = $destif;
1833
		}
1834
	}
1835
	$dhcrelayifs = array_unique($dhcrelayifs);
1836

    
1837
	/* fire up dhcrelay */
1838
	if (empty($dhcrelayifs)) {
1839
		log_error(gettext("No suitable interface found for running dhcrelay!"));
1840
		return; /* XXX */
1841
	}
1842

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

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

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

    
1853
	return 0;
1854
}
1855

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

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

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

    
1867
	$dhcrelaycfg =& $config['dhcrelay6'];
1868

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

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

    
1880
	$iflist = get_configured_interface_list();
1881

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

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

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

    
1929
		if (!isset($destif)) {
1930
			/* Create a array from the existing route table */
1931
			exec("/usr/bin/netstat -rnWf inet6", $route_str);
1932
			array_shift($route_str);
1933
			array_shift($route_str);
1934
			array_shift($route_str);
1935
			array_shift($route_str);
1936
			$route_arr = array();
1937
			foreach ($route_str as $routeline) {
1938
				$items = preg_split("/[ ]+/i", $routeline);
1939
				if (ip_in_subnet($srvip, $items[0])) {
1940
					$destif = trim($items[6]);
1941
					break;
1942
				}
1943
			}
1944
		}
1945

    
1946
		if (!isset($destif)) {
1947
			if (is_array($config['gateways']['gateway_item'])) {
1948
				foreach ($config['gateways']['gateway_item'] as $gateway) {
1949
					if (isset($gateway['defaultgw'])) {
1950
						$destif = get_real_interface($gateway['interface']);
1951
						break;
1952
					}
1953
				}
1954
			} else {
1955
				$destif = get_real_interface("wan");
1956
			}
1957
		}
1958

    
1959
		if (!empty($destif)) {
1960
			$srvifaces[] = "{$srvip}%{$destif}";
1961
		}
1962
	}
1963

    
1964
	/* fire up dhcrelay */
1965
	if (empty($dhcrelayifs) || empty($srvifaces)) {
1966
		log_error(gettext("No suitable interface found for running dhcrelay -6!"));
1967
		return; /* XXX */
1968
	}
1969

    
1970
	$cmd = "/usr/local/sbin/dhcrelay -6 -pf \"{$g['varrun_path']}/dhcrelay6.pid\"";
1971
	foreach ($dhcrelayifs as $dhcrelayif) {
1972
		$cmd .= " -l {$dhcrelayif}";
1973
	}
1974
	foreach ($srvifaces as $srviface) {
1975
		$cmd .= " -u \"{$srviface}\"";
1976
	}
1977
	mwexec($cmd);
1978
	unset($cmd);
1979

    
1980
	return 0;
1981
}
1982

    
1983
function services_dyndns_configure_client($conf) {
1984

    
1985
	if (!isset($conf['enable'])) {
1986
		return;
1987
	}
1988

    
1989
	/* load up the dyndns.class */
1990
	require_once("dyndns.class");
1991

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

    
2016
function services_dyndns_configure($int = "") {
2017
	global $config, $g;
2018
	if (isset($config['system']['developerspew'])) {
2019
		$mt = microtime();
2020
		echo "services_dyndns_configure() being called $mt\n";
2021
	}
2022

    
2023
	$dyndnscfg = $config['dyndnses']['dyndns'];
2024
	$gwgroups = return_gateway_groups_array();
2025
	if (is_array($dyndnscfg)) {
2026
		if (platform_booting()) {
2027
			echo gettext("Starting DynDNS clients...");
2028
		}
2029

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

    
2052
		if (platform_booting()) {
2053
			echo gettext("done.") . "\n";
2054
		}
2055
	}
2056

    
2057
	return 0;
2058
}
2059

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

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

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

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

    
2108
function services_dnsmasq_configure($restart_dhcp = true) {
2109
	global $config, $g;
2110
	$return = 0;
2111

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

    
2119

    
2120
	if (isset($config['system']['developerspew'])) {
2121
		$mt = microtime();
2122
		echo "services_dnsmasq_configure() being called $mt\n";
2123
	}
2124

    
2125
	/* kill any running dnsmasq */
2126
	if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) {
2127
		sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
2128
	}
2129

    
2130
	if (isset($config['dnsmasq']['enable'])) {
2131

    
2132
		if (platform_booting()) {
2133
			echo gettext("Starting DNS forwarder...");
2134
		} else {
2135
			sleep(1);
2136
		}
2137

    
2138
		/* generate hosts file */
2139
		if (system_hosts_generate() != 0) {
2140
			$return = 1;
2141
		}
2142

    
2143
		$args = "";
2144

    
2145
		if (isset($config['dnsmasq']['regdhcp'])) {
2146
			$args .= " --dhcp-hostsfile={$g['varetc_path']}/hosts ";
2147
		}
2148

    
2149
		/* Setup listen port, if non-default */
2150
		if (is_port($config['dnsmasq']['port'])) {
2151
			$args .= " --port={$config['dnsmasq']['port']} ";
2152
		}
2153

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

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

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

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

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

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

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

    
2238
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2239
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2240
		}
2241

    
2242
		if (isset($config['dnsmasq']['strict_order'])) {
2243
			$args .= " --strict-order ";
2244
		}
2245

    
2246
		if (isset($config['dnsmasq']['domain_needed'])) {
2247
			$args .= " --domain-needed ";
2248
		}
2249

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

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

    
2267
		system_dhcpleases_configure();
2268

    
2269
		if (platform_booting()) {
2270
			echo gettext("done.") . "\n";
2271
		}
2272
	}
2273

    
2274
	if (!platform_booting() && $restart_dhcp) {
2275
		if (services_dhcpd_configure() != 0) {
2276
			$return = 1;
2277
		}
2278
	}
2279

    
2280
	return $return;
2281
}
2282

    
2283
function services_unbound_configure($restart_dhcp = true) {
2284
	global $config, $g;
2285
	$return = 0;
2286

    
2287
	if (isset($config['system']['developerspew'])) {
2288
		$mt = microtime();
2289
		echo "services_unbound_configure() being called $mt\n";
2290
	}
2291

    
2292
	if (isset($config['unbound']['enable'])) {
2293
		require_once('/etc/inc/unbound.inc');
2294

    
2295
		/* Stop Unbound using TERM */
2296
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2297
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
2298
		}
2299

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

    
2307
		if (platform_booting()) {
2308
			echo gettext("Starting DNS Resolver...");
2309
		} else {
2310
			sleep(1);
2311
		}
2312

    
2313
		/* generate hosts file */
2314
		if (system_hosts_generate() != 0) {
2315
			$return = 1;
2316
		}
2317

    
2318
		sync_unbound_service();
2319
		if (platform_booting()) {
2320
			echo gettext("done.") . "\n";
2321
		}
2322

    
2323
		system_dhcpleases_configure();
2324
	} else {
2325
		/* kill Unbound since it should not be enabled */
2326
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2327
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "KILL");
2328
		}
2329
	}
2330

    
2331
	if (!platform_booting() && $restart_dhcp) {
2332
		if (services_dhcpd_configure() != 0) {
2333
			$return = 1;
2334
		}
2335
	}
2336

    
2337
	return $return;
2338
}
2339

    
2340
function services_snmpd_configure() {
2341
	global $config, $g;
2342
	if (isset($config['system']['developerspew'])) {
2343
		$mt = microtime();
2344
		echo "services_snmpd_configure() being called $mt\n";
2345
	}
2346

    
2347
	/* kill any running snmpd */
2348
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
2349
	sleep(2);
2350
	if (is_process_running("bsnmpd")) {
2351
		mwexec("/usr/bin/killall bsnmpd", true);
2352
	}
2353

    
2354
	if (isset($config['snmpd']['enable'])) {
2355

    
2356
		if (platform_booting()) {
2357
			echo gettext("Starting SNMP daemon... ");
2358
		}
2359

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

    
2365
		/* generate snmpd.conf */
2366
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
2367
		if (!$fd) {
2368
			printf(gettext("Error: cannot open snmpd.conf in services_snmpd_configure().%s"), "\n");
2369
			return 1;
2370
		}
2371

    
2372

    
2373
		$snmpdconf = <<<EOD
2374
location := "{$config['snmpd']['syslocation']}"
2375
contact := "{$config['snmpd']['syscontact']}"
2376
read := "{$config['snmpd']['rocommunity']}"
2377

    
2378
EOD;
2379

    
2380
/* No docs on what write strings do there so disable for now.
2381
		if (isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])) {
2382
			$snmpdconf .= <<<EOD
2383
# write string
2384
write := "{$config['snmpd']['rwcommunity']}"
2385

    
2386
EOD;
2387
		}
2388
*/
2389

    
2390

    
2391
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2392
			$snmpdconf .= <<<EOD
2393
# SNMP Trap support.
2394
traphost := {$config['snmpd']['trapserver']}
2395
trapport := {$config['snmpd']['trapserverport']}
2396
trap := "{$config['snmpd']['trapstring']}"
2397

    
2398

    
2399
EOD;
2400
		}
2401

    
2402
		$platform = trim(file_get_contents('/etc/platform'));
2403
		if (($platform == "pfSense") && ($g['product_name'] != "pfSense")) {
2404
			$platform = $g['product_name'];
2405
		}
2406
		$sysDescr = "{$g['product_name']} " . php_uname("n") .
2407
			" {$g['product_version']} {$platform} " . php_uname("s") .
2408
			" " . php_uname("r") . " " . php_uname("m");
2409

    
2410
		$snmpdconf .= <<<EOD
2411
system := 1     # pfSense
2412
%snmpd
2413
sysDescr			= "{$sysDescr}"
2414
begemotSnmpdDebugDumpPdus       = 2
2415
begemotSnmpdDebugSyslogPri      = 7
2416
begemotSnmpdCommunityString.0.1 = $(read)
2417

    
2418
EOD;
2419

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

    
2425
EOD;
2426
		}
2427
*/
2428

    
2429

    
2430
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2431
			$snmpdconf .= <<<EOD
2432
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
2433
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
2434
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
2435

    
2436
EOD;
2437
		}
2438

    
2439

    
2440
		$snmpdconf .= <<<EOD
2441
begemotSnmpdCommunityDisable    = 1
2442

    
2443
EOD;
2444

    
2445
		$bind_to_ip = "0.0.0.0";
2446
		if (isset($config['snmpd']['bindip'])) {
2447
			if (is_ipaddr($config['snmpd']['bindip'])) {
2448
				$bind_to_ip = $config['snmpd']['bindip'];
2449
			} else {
2450
				$if = get_real_interface($config['snmpd']['bindip']);
2451
				if (does_interface_exist($if)) {
2452
					$bind_to_ip = get_interface_ip($config['snmpd']['bindip']);
2453
				}
2454
			}
2455
		}
2456

    
2457
		if (is_port($config['snmpd']['pollport'])) {
2458
			$snmpdconf .= <<<EOD
2459
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
2460

    
2461
EOD;
2462

    
2463
		}
2464

    
2465
		$snmpdconf .= <<<EOD
2466
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
2467
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
2468

    
2469
# These are bsnmp macros not php vars.
2470
sysContact      = $(contact)
2471
sysLocation     = $(location)
2472
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
2473

    
2474
snmpEnableAuthenTraps = 2
2475

    
2476
EOD;
2477

    
2478
		if (is_array($config['snmpd']['modules'])) {
2479
			if (isset($config['snmpd']['modules']['mibii'])) {
2480
			$snmpdconf .= <<<EOD
2481
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
2482

    
2483
EOD;
2484
			}
2485

    
2486
			if (isset($config['snmpd']['modules']['netgraph'])) {
2487
				$snmpdconf .= <<<EOD
2488
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
2489
%netgraph
2490
begemotNgControlNodeName = "snmpd"
2491

    
2492
EOD;
2493
			}
2494

    
2495
			if (isset($config['snmpd']['modules']['pf'])) {
2496
				$snmpdconf .= <<<EOD
2497
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
2498

    
2499
EOD;
2500
			}
2501

    
2502
			if (isset($config['snmpd']['modules']['hostres'])) {
2503
				$snmpdconf .= <<<EOD
2504
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
2505

    
2506
EOD;
2507
			}
2508

    
2509
			if (isset($config['snmpd']['modules']['bridge'])) {
2510
				$snmpdconf .= <<<EOD
2511
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
2512
# config must end with blank line
2513

    
2514
EOD;
2515
			}
2516
			if (isset($config['snmpd']['modules']['ucd'])) {
2517
				$snmpdconf .= <<<EOD
2518
begemotSnmpdModulePath."ucd"     = "/usr/local/lib/snmp_ucd.so"
2519

    
2520
EOD;
2521
			}
2522
			if (isset($config['snmpd']['modules']['regex'])) {
2523
				$snmpdconf .= <<<EOD
2524
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"
2525

    
2526
EOD;
2527
			}
2528
		}
2529

    
2530
		fwrite($fd, $snmpdconf);
2531
		fclose($fd);
2532
		unset($snmpdconf);
2533

    
2534
		/* run bsnmpd */
2535
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
2536
			" -p {$g['varrun_path']}/snmpd.pid");
2537

    
2538
		if (platform_booting()) {
2539
			echo gettext("done.") . "\n";
2540
		}
2541
	}
2542

    
2543
	return 0;
2544
}
2545

    
2546
function services_dnsupdate_process($int = "", $updatehost = "", $forced = false) {
2547
	global $config, $g;
2548
	if (isset($config['system']['developerspew'])) {
2549
		$mt = microtime();
2550
		echo "services_dnsupdate_process() being called $mt\n";
2551
	}
2552

    
2553
	/* Dynamic DNS updating active? */
2554
	if (is_array($config['dnsupdates']['dnsupdate'])) {
2555
		$notify_text = "";
2556
		$gwgroups = return_gateway_groups_array();
2557
		foreach ($config['dnsupdates']['dnsupdate'] as $i => $dnsupdate) {
2558
			if (!isset($dnsupdate['enable'])) {
2559
				continue;
2560
			}
2561
			/*
2562
			 * If it's using a gateway group, check if interface is
2563
			 * the active gateway for that group
2564
			 */
2565
			$group_int = '';
2566
			if (is_array($gwgroups[$dnsupdate['interface']])) {
2567
				if (!empty($gwgroups[$dnsupdate['interface']][0]['vip'])) {
2568
					$group_int = $gwgroups[$dnsupdate['interface']][0]['vip'];
2569
				} else {
2570
					$group_int = $gwgroups[$dnsupdate['interface']][0]['int'];
2571
				}
2572
			}
2573
			if (!empty($int) && ($int != $dnsupdate['interface']) && ($int != $group_int)) {
2574
				continue;
2575
			}
2576
			if (!empty($updatehost) && ($updatehost != $dnsupdate['host'])) {
2577
				continue;
2578
			}
2579

    
2580
			/* determine interface name */
2581
			$if = get_failover_interface($dnsupdate['interface']);
2582

    
2583
			if (isset($dnsupdate['usepublicip'])) {
2584
				$wanip = dyndnsCheckIP($if);
2585
			} else {
2586
				$wanip = get_interface_ip($if);
2587
			}
2588

    
2589
			$wanipv6 = get_interface_ipv6($if);
2590
			$cacheFile = "{$g['conf_path']}/dyndns_{$dnsupdate['interface']}_rfc2136_" . escapeshellarg($dnsupdate['host']) . "_{$dnsupdate['server']}.cache";
2591
			$cacheFilev6 = "{$g['conf_path']}/dyndns_{$dnsupdate['interface']}_rfc2136_" . escapeshellarg($dnsupdate['host']) . "_{$dnsupdate['server']}_v6.cache";
2592
			$currentTime = time();
2593

    
2594
			if ($wanip || $wanipv6) {
2595
				$keyname = $dnsupdate['keyname'];
2596
				/* trailing dot */
2597
				if (substr($keyname, -1) != ".") {
2598
					$keyname .= ".";
2599
				}
2600

    
2601
				$hostname = $dnsupdate['host'];
2602
				/* trailing dot */
2603
				if (substr($hostname, -1) != ".") {
2604
					$hostname .= ".";
2605
				}
2606

    
2607
				/* write private key file
2608
				   this is dumb - public and private keys are the same for HMAC-MD5,
2609
				   but nsupdate insists on having both */
2610
				$fd = fopen("{$g['varetc_path']}/K{$i}{$keyname}+157+00000.private", "w");
2611
				$privkey = <<<EOD
2612
Private-key-format: v1.2
2613
Algorithm: 157 (HMAC)
2614
Key: {$dnsupdate['keydata']}
2615

    
2616
EOD;
2617
				fwrite($fd, $privkey);
2618
				fclose($fd);
2619

    
2620
				/* write public key file */
2621
				if ($dnsupdate['keytype'] == "zone") {
2622
					$flags = 257;
2623
					$proto = 3;
2624
				} else if ($dnsupdate['keytype'] == "host") {
2625
					$flags = 513;
2626
					$proto = 3;
2627
				} else if ($dnsupdate['keytype'] == "user") {
2628
					$flags = 0;
2629
					$proto = 2;
2630
				}
2631

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

    
2636
				/* generate update instructions */
2637
				$upinst = "";
2638
				if (!empty($dnsupdate['server'])) {
2639
					$upinst .= "server {$dnsupdate['server']}\n";
2640
				}
2641

    
2642
				$cachedipv4 = '';
2643
				$cacheTimev4 = 0;
2644
				if (file_exists($cacheFile)) {
2645
					list($cachedipv4, $cacheTimev4) = explode("|", file_get_contents($cacheFile));
2646
				}
2647
				$cachedipv6 = '';
2648
				$cacheTimev6 = 0;
2649
				if (file_exists($cacheFilev6)) {
2650
					list($cachedipv6, $cacheTimev6) = explode("|", file_get_contents($cacheFilev6));
2651
				}
2652

    
2653
				// 25 Days
2654
				$maxCacheAgeSecs = 25 * 24 * 60 * 60;
2655
				$need_update = false;
2656

    
2657
				conf_mount_rw();
2658
				/* Update IPv4 if we have it. */
2659
				if (is_ipaddrv4($wanip) && $dnsupdate['recordtype'] != "AAAA") {
2660
					if (($wanip != $cachedipv4) || (($currentTime - $cacheTimev4) > $maxCacheAgeSecs) || $forced) {
2661
						$upinst .= "update delete {$dnsupdate['host']}. A\n";
2662
						$upinst .= "update add {$dnsupdate['host']}. {$dnsupdate['ttl']} A {$wanip}\n";
2663
						$need_update = true;
2664
					} else {
2665
						log_error(sprintf(gettext("phpDynDNS: Not updating %s A record because the IP address has not changed."), $dnsupdate['host']));
2666
					}
2667
				} else {
2668
					@unlink($cacheFile);
2669
					unset($cacheFile);
2670
				}
2671

    
2672
				/* Update IPv6 if we have it. */
2673
				if (is_ipaddrv6($wanipv6) && $dnsupdate['recordtype'] != "A") {
2674
					if (($wanipv6 != $cachedipv6) || (($currentTime - $cacheTimev6) > $maxCacheAgeSecs) || $forced) {
2675
						$upinst .= "update delete {$dnsupdate['host']}. AAAA\n";
2676
						$upinst .= "update add {$dnsupdate['host']}. {$dnsupdate['ttl']} AAAA {$wanipv6}\n";
2677
						$need_update = true;
2678
					} else {
2679
						log_error(sprintf(gettext("phpDynDNS: Not updating %s AAAA record because the IPv6 address has not changed."), $dnsupdate['host']));
2680
					}
2681
				} else {
2682
					@unlink($cacheFilev6);
2683
					unset($cacheFilev6);
2684
				}
2685
				conf_mount_ro();
2686

    
2687
				$upinst .= "\n";	/* mind that trailing newline! */
2688

    
2689
				if ($need_update) {
2690
					@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}", $upinst);
2691
					unset($upinst);
2692
					/* invoke nsupdate */
2693
					$cmd = "/usr/local/bin/nsupdate -k {$g['varetc_path']}/K{$i}{$keyname}+157+00000.key";
2694
					if (isset($dnsupdate['usetcp'])) {
2695
						$cmd .= " -v";
2696
					}
2697
					$cmd .= " {$g['varetc_path']}/nsupdatecmds{$i}";
2698
					if (mwexec($cmd) == 0) {
2699
						if (!empty($cacheFile)) {
2700
							@file_put_contents($cacheFile, "{$wanip}|{$currentTime}");
2701
							log_error(sprintf(gettext('phpDynDNS: updating cache file %1$s: %2$s'), $cacheFile, $wanip));
2702
							$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";
2703
						}
2704
						if (!empty($cacheFilev6)) {
2705
							@file_put_contents($cacheFilev6, "{$wanipv6}|{$currentTime}");
2706
							log_error(sprintf(gettext('phpDynDNS: updating cache file %1$s: %2$s'), $cacheFilev6, $wanipv6));
2707
							$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";
2708
						}
2709
					} else {
2710
						if (!empty($cacheFile)) {
2711
							log_error(sprintf(gettext('phpDynDNS: ERROR while updating IP Address (A) for %1$s (%2$s)'), $dnsupdate['host'], $wanip));
2712
						}
2713
						if (!empty($cacheFilev6)) {
2714
							log_error(sprintf(gettext('phpDynDNS: ERROR while updating IP Address (AAAA) for %1$s (%2$s)'), $dnsupdate['host'], $wanipv6));
2715
						}
2716
					}
2717
					unset($cmd);
2718
				}
2719
			}
2720
		}
2721
		if (!empty($notify_text)) {
2722
			notify_all_remote($notify_text);
2723
		}
2724
	}
2725

    
2726
	return 0;
2727
}
2728

    
2729
/* configure cron service */
2730
function configure_cron() {
2731
	global $g, $config;
2732

    
2733
	conf_mount_rw();
2734
	/* preserve existing crontab entries */
2735
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2736

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

    
2746

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

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

    
2761
		foreach ($config['cron']['item'] as $item) {
2762
			$crontab_contents .= "\n{$item['minute']}\t";
2763
			$crontab_contents .= "{$item['hour']}\t";
2764
			$crontab_contents .= "{$item['mday']}\t";
2765
			$crontab_contents .= "{$item['month']}\t";
2766
			$crontab_contents .= "{$item['wday']}\t";
2767
			$crontab_contents .= "{$item['who']}\t";
2768
			$crontab_contents .= "{$item['command']}";
2769
		}
2770

    
2771
		$crontab_contents .= "\n#\n";
2772
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
2773
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
2774
		$crontab_contents .= "#\n\n";
2775
	}
2776

    
2777
	/* please maintain the newline at the end of file */
2778
	file_put_contents("/etc/crontab", $crontab_contents);
2779
	unset($crontab_contents);
2780

    
2781
	/* make sure that cron is running and start it if it got killed somehow */
2782
	if (!is_process_running("cron")) {
2783
		exec("cd /tmp && /usr/sbin/cron -s 2>/dev/null");
2784
	} else {
2785
	/* do a HUP kill to force sync changes */
2786
		sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP");
2787
	}
2788

    
2789
	conf_mount_ro();
2790
}
2791

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

    
2816
function upnp_start() {
2817
	global $config;
2818

    
2819
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
2820
		return;
2821
	}
2822

    
2823
	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
2824
		echo gettext("Starting UPnP service... ");
2825
		require_once('/usr/local/pkg/miniupnpd.inc');
2826
		sync_package_miniupnpd();
2827
		echo "done.\n";
2828
	}
2829
}
2830

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

    
2834
	$is_installed = false;
2835
	$cron_changed = true;
2836

    
2837
	if (!is_array($config['cron'])) {
2838
		$config['cron'] = array();
2839
	}
2840
	if (!is_array($config['cron']['item'])) {
2841
		$config['cron']['item'] = array();
2842
	}
2843

    
2844
	$x = 0;
2845
	foreach ($config['cron']['item'] as $item) {
2846
		if (strstr($item['command'], $command)) {
2847
			$is_installed = true;
2848
			break;
2849
		}
2850
		$x++;
2851
	}
2852

    
2853
	if ($active) {
2854
		$cron_item = array();
2855
		$cron_item['minute'] = $minute;
2856
		$cron_item['hour'] = $hour;
2857
		$cron_item['mday'] = $monthday;
2858
		$cron_item['month'] = $month;
2859
		$cron_item['wday'] = $weekday;
2860
		$cron_item['who'] = $who;
2861
		$cron_item['command'] = $command;
2862
		if (!$is_installed) {
2863
			$config['cron']['item'][] = $cron_item;
2864
			write_config(sprintf(gettext("Installed cron job for %s"), $command));
2865
		} else {
2866
			if ($config['cron']['item'][$x] == $cron_item) {
2867
				$cron_changed = false;
2868
				log_error(sprintf(gettext("Checked cron job for %s, no change needed"), $command));
2869
			} else {
2870
				$config['cron']['item'][$x] = $cron_item;
2871
				write_config(sprintf(gettext("Updated cron job for %s"), $command));
2872
			}
2873
		}
2874
	} else {
2875
		if ($is_installed == true) {
2876
			array_splice($config['cron']['item'], $x, 1);
2877
			write_config(sprintf(gettext("Removed cron job for %s"), $command));
2878
		} else {
2879
			$cron_changed = false;
2880
		}
2881
	}
2882

    
2883
	if ($cron_changed) {
2884
		configure_cron();
2885
	}
2886
}
2887

    
2888
?>
(51-51/67)