Project

General

Profile

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

    
58
define('DYNDNS_PROVIDER_VALUES', 'all-inkl citynetwork cloudflare cloudflare-v6 custom custom-v6 dnsexit dnsimple dnsmadeeasy dnsomatic duiadns duiadns-v6 dyndns dyndns-custom dyndns-static dyns easydns eurodns freedns freedns-v6 glesys googledomains gratisdns he-net he-net-v6 he-net-tunnelbroker loopia namecheap noip noip-free ods opendns ovh-dynhost route53 selfhost spdyn spdyn-v6 zoneedit');
59
define('DYNDNS_PROVIDER_DESCRIPTIONS', 'All-Inkl.com,City Network,CloudFlare,CloudFlare (v6),Custom,Custom (v6),DNSexit,DNSimple,DNS Made Easy,DNS-O-Matic,DuiaDns.net,DuiaDns.net (v6),DynDNS (dynamic),DynDNS (custom),DynDNS (static),DyNS,easyDNS,Euro Dns,freeDNS,freeDNS (v6),GleSYS,Google Domains,GratisDNS,HE.net,HE.net (v6),HE.net Tunnelbroker,Loopia,Namecheap,No-IP,No-IP (free),ODS.org,OpenDNS,OVH DynHOST,Route 53,SelfHost,SPDYN,SPDYN (v6),ZoneEdit');
60

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
463
	unlock($dhcpdconfigurelck);
464
}
465

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

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

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

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

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

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

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

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

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

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

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

    
571
	$dhcpdconf = <<<EOD
572

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

    
586
EOD;
587

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

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

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

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

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

    
617
		interfaces_staticarp_configure($dhcpif);
618

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

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

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

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

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

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

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

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

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

    
706
		$dnscfg = "";
707

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

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

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

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

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

    
745
			}
746

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

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

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

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

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

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

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

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

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

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

    
886
			$pdnscfg = "";
887

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1062
EOD;
1063

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

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

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

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

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

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

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

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

    
1100
				$smdnscfg = "";
1101

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

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

    
1110
				if (isset($sm['ddnsupdate'])) {
1111
					if (($sm['ddnsdomain'] <> "") && ($sm['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
1112
						$smdnscfg .= "		ddns-domainname \"{$sm['ddnsdomain']}\";\n";
1113
					}
1114
# TODO: Implement ddnsforcehostname option for DHCP Server per interface
1115
					if (isset($dhcpifconf['ddnsforcehostname']) && $sm['hostname']) {
1116
						$ddnshostname = str_replace(" ", "_", $sm['hostname']);
1117
						$ddnshostname = str_replace(".", "_", $ddnshostname);
1118
						$smdnscfg .= "		ddns-hostname \"{$ddnshostname}\";\n";
1119
					}
1120
					$smdnscfg .= "		ddns-update-style interim;\n";
1121
				}
1122

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

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

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

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

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

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

    
1154
				$dhcpdconf .= "}\n";
1155
				$i++;
1156
			}
1157
		}
1158

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

    
1171
	if ($need_ddns_updates) {
1172
		$dhcpdconf .= "ddns-update-style interim;\n";
1173
		$dhcpdconf .= "update-static-leases on;\n";
1174

    
1175
		$dhcpdconf .= dhcpdzones($ddns_zones);
1176
	}
1177

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

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

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

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

    
1201
	if (platform_booting()) {
1202
		print "done.\n";
1203
	}
1204

    
1205
	return 0;
1206
}
1207

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

    
1217
	return $dhcpdconf;
1218
}
1219

    
1220
function dhcpdzones($ddns_zones) {
1221
	$dhcpdconf = "";
1222

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

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

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

    
1270
	return $dhcpdconf;
1271
}
1272

    
1273
function services_dhcpdv6_configure($blacklist = array()) {
1274
	global $config, $g;
1275

    
1276
	if ($g['services_dhcp_server_enable'] == false) {
1277
		return;
1278
	}
1279

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

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

    
1293
	/* DHCP enabled on any interfaces? */
1294
	if (!is_dhcpv6_server_enabled()) {
1295
		return 0;
1296
	}
1297

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

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

    
1323

    
1324
	if (platform_booting()) {
1325
		echo "Starting DHCPv6 service...";
1326
	} else {
1327
		sleep(1);
1328
	}
1329

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

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

    
1343
	$dhcpdv6conf = <<<EOD
1344

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

    
1357
EOD;
1358

    
1359
	if (!isset($dhcpv6ifconf['disableauthoritative'])) {
1360
		$dhcpdv6conf .= "authoritative;\n";
1361
	}
1362

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

    
1367
	$dhcpdv6ifs = array();
1368

    
1369
	$dhcpv6num = 0;
1370
	$nsupdate = false;
1371

    
1372
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1373

    
1374
		$ddns_zones = array();
1375

    
1376
		$ifcfgv6 = $config['interfaces'][$dhcpv6if];
1377

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

    
1393
		if ($is_olsr_enabled == true) {
1394
			if ($dhcpv6ifconf['netmask']) {
1395
				$subnetmask = gen_subnet_maskv6($dhcpv6ifconf['netmask']);
1396
			}
1397
		}
1398

    
1399
		$dnscfgv6 = "";
1400

    
1401
		if ($dhcpv6ifconf['domain']) {
1402
			$dnscfgv6 .= "	option domain-name \"{$dhcpv6ifconf['domain']}\";\n";
1403
		}
1404

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

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

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

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

    
1445
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1446

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

    
1467
		$dhcpdv6conf .= " {\n";
1468

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

    
1476
		$dhcpdv6conf .= <<<EOD
1477
	range6 {$range_from} {$range_to};
1478
$dnscfgv6
1479

    
1480
EOD;
1481

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

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

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

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

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

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

    
1553
		$dhcpdv6conf .= "}\n";
1554

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

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

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

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

    
1586
				$dhcpdv6conf .= "}\n";
1587
				$i++;
1588
			}
1589
		}
1590

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

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

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

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

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

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

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

    
1650
	return 0;
1651
}
1652

    
1653
function services_igmpproxy_configure() {
1654
	global $config, $g;
1655

    
1656
	/* kill any running igmpproxy */
1657
	killbyname("igmpproxy");
1658

    
1659
	if (!is_array($config['igmpproxy']['igmpentry']) || (count($config['igmpproxy']['igmpentry']) == 0)) {
1660
		return 1;
1661
	}
1662

    
1663
	$iflist = get_configured_interface_list();
1664

    
1665
	$igmpconf = <<<EOD
1666

    
1667
##------------------------------------------------------
1668
## Enable Quickleave mode (Sends Leave instantly)
1669
##------------------------------------------------------
1670
quickleave
1671

    
1672
EOD;
1673

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

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

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

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

    
1713
	log_error(gettext("Started IGMP proxy service."));
1714

    
1715
	return 0;
1716
}
1717

    
1718
function services_dhcrelay_configure() {
1719
	global $config, $g;
1720

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

    
1726
	/* kill any running dhcrelay */
1727
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
1728

    
1729
	$dhcrelaycfg =& $config['dhcrelay'];
1730

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

    
1736
	if (platform_booting()) {
1737
		echo gettext("Starting DHCP relay service...");
1738
	} else {
1739
		sleep(1);
1740
	}
1741

    
1742
	$iflist = get_configured_interface_list();
1743

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

    
1751
		if (is_ipaddr(get_interface_ip($dhcrelayif))) {
1752
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1753
		}
1754
	}
1755

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

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

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

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

    
1827
		if (!empty($destif)) {
1828
			$dhcrelayifs[] = $destif;
1829
		}
1830
	}
1831
	$dhcrelayifs = array_unique($dhcrelayifs);
1832

    
1833
	/* fire up dhcrelay */
1834
	if (empty($dhcrelayifs)) {
1835
		log_error(gettext("No suitable interface found for running dhcrelay!"));
1836
		return; /* XXX */
1837
	}
1838

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

    
1841
	if (isset($dhcrelaycfg['agentoption'])) {
1842
		$cmd .= " -a -m replace";
1843
	}
1844

    
1845
	$cmd .= " " . implode(" ", $srvips);
1846
	mwexec($cmd);
1847
	unset($cmd);
1848

    
1849
	return 0;
1850
}
1851

    
1852
function services_dhcrelay6_configure() {
1853
	global $config, $g;
1854

    
1855
	if (isset($config['system']['developerspew'])) {
1856
		$mt = microtime();
1857
		echo "services_dhcrelay6_configure() being called $mt\n";
1858
	}
1859

    
1860
	/* kill any running dhcrelay */
1861
	killbypid("{$g['varrun_path']}/dhcrelay6.pid");
1862

    
1863
	$dhcrelaycfg =& $config['dhcrelay6'];
1864

    
1865
	/* DHCPv6 Relay enabled on any interfaces? */
1866
	if (!isset($dhcrelaycfg['enable'])) {
1867
		return 0;
1868
	}
1869

    
1870
	if (platform_booting()) {
1871
		echo gettext("Starting DHCPv6 relay service...");
1872
	} else {
1873
		sleep(1);
1874
	}
1875

    
1876
	$iflist = get_configured_interface_list();
1877

    
1878
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1879
	foreach ($dhcifaces as $dhcrelayif) {
1880
		if (!isset($iflist[$dhcrelayif]) ||
1881
		    link_interface_to_bridge($dhcrelayif)) {
1882
			continue;
1883
		}
1884

    
1885
		if (is_ipaddrv6(get_interface_ipv6($dhcrelayif))) {
1886
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1887
		}
1888
	}
1889
	$dhcrelayifs = array_unique($dhcrelayifs);
1890

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

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

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

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

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

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

    
1973
	return 0;
1974
}
1975

    
1976
function services_dyndns_configure_client($conf) {
1977

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

    
1982
	/* load up the dyndns.class */
1983
	require_once("dyndns.class");
1984

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

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

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

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

    
2044
		if (platform_booting()) {
2045
			echo gettext("done.") . "\n";
2046
		}
2047
	}
2048

    
2049
	return 0;
2050
}
2051

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

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

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

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

    
2100
function services_dnsmasq_configure($restart_dhcp = true) {
2101
	global $config, $g;
2102
	$return = 0;
2103

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

    
2111

    
2112
	if (isset($config['system']['developerspew'])) {
2113
		$mt = microtime();
2114
		echo "services_dnsmasq_configure() being called $mt\n";
2115
	}
2116

    
2117
	/* kill any running dnsmasq */
2118
	if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) {
2119
		sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
2120
	}
2121

    
2122
	if (isset($config['dnsmasq']['enable'])) {
2123

    
2124
		if (platform_booting()) {
2125
			echo gettext("Starting DNS forwarder...");
2126
		} else {
2127
			sleep(1);
2128
		}
2129

    
2130
		/* generate hosts file */
2131
		if (system_hosts_generate() != 0) {
2132
			$return = 1;
2133
		}
2134

    
2135
		$args = "";
2136

    
2137
		if (isset($config['dnsmasq']['regdhcp'])) {
2138
			$args .= " --dhcp-hostsfile={$g['varetc_path']}/hosts ";
2139
		}
2140

    
2141
		/* Setup listen port, if non-default */
2142
		if (is_port($config['dnsmasq']['port'])) {
2143
			$args .= " --port={$config['dnsmasq']['port']} ";
2144
		}
2145

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

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

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

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

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

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

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

    
2230
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2231
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2232
		}
2233

    
2234
		if (isset($config['dnsmasq']['strict_order'])) {
2235
			$args .= " --strict-order ";
2236
		}
2237

    
2238
		if (isset($config['dnsmasq']['domain_needed'])) {
2239
			$args .= " --domain-needed ";
2240
		}
2241

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

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

    
2259
		system_dhcpleases_configure();
2260

    
2261
		if (platform_booting()) {
2262
			echo gettext("done.") . "\n";
2263
		}
2264
	}
2265

    
2266
	if (!platform_booting() && $restart_dhcp) {
2267
		if (services_dhcpd_configure() != 0) {
2268
			$return = 1;
2269
		}
2270
	}
2271

    
2272
	return $return;
2273
}
2274

    
2275
function services_unbound_configure($restart_dhcp = true) {
2276
	global $config, $g;
2277
	$return = 0;
2278

    
2279
	if (isset($config['system']['developerspew'])) {
2280
		$mt = microtime();
2281
		echo "services_unbound_configure() being called $mt\n";
2282
	}
2283

    
2284
	// kill any running Unbound instance
2285
	if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2286
		sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
2287
	}
2288

    
2289
	if (isset($config['unbound']['enable'])) {
2290
		if (platform_booting()) {
2291
			echo gettext("Starting DNS Resolver...");
2292
		} else {
2293
			sleep(1);
2294
		}
2295

    
2296
		/* generate hosts file */
2297
		if (system_hosts_generate() != 0) {
2298
			$return = 1;
2299
		}
2300

    
2301
		require_once('/etc/inc/unbound.inc');
2302
		sync_unbound_service();
2303
		if (platform_booting()) {
2304
			echo gettext("done.") . "\n";
2305
		}
2306

    
2307
		system_dhcpleases_configure();
2308
	}
2309

    
2310
	if (!platform_booting() && $restart_dhcp) {
2311
		if (services_dhcpd_configure() != 0) {
2312
			$return = 1;
2313
		}
2314
	}
2315

    
2316
	return $return;
2317
}
2318

    
2319
function services_snmpd_configure() {
2320
	global $config, $g;
2321
	if (isset($config['system']['developerspew'])) {
2322
		$mt = microtime();
2323
		echo "services_snmpd_configure() being called $mt\n";
2324
	}
2325

    
2326
	/* kill any running snmpd */
2327
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
2328
	sleep(2);
2329
	if (is_process_running("bsnmpd")) {
2330
		mwexec("/usr/bin/killall bsnmpd", true);
2331
	}
2332

    
2333
	if (isset($config['snmpd']['enable'])) {
2334

    
2335
		if (platform_booting()) {
2336
			echo gettext("Starting SNMP daemon... ");
2337
		}
2338

    
2339
		/* generate snmpd.conf */
2340
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
2341
		if (!$fd) {
2342
			printf(gettext("Error: cannot open snmpd.conf in services_snmpd_configure().%s"), "\n");
2343
			return 1;
2344
		}
2345

    
2346

    
2347
		$snmpdconf = <<<EOD
2348
location := "{$config['snmpd']['syslocation']}"
2349
contact := "{$config['snmpd']['syscontact']}"
2350
read := "{$config['snmpd']['rocommunity']}"
2351

    
2352
EOD;
2353

    
2354
/* No docs on what write strings do there so disable for now.
2355
		if (isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])) {
2356
			$snmpdconf .= <<<EOD
2357
# write string
2358
write := "{$config['snmpd']['rwcommunity']}"
2359

    
2360
EOD;
2361
		}
2362
*/
2363

    
2364

    
2365
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2366
			$snmpdconf .= <<<EOD
2367
# SNMP Trap support.
2368
traphost := {$config['snmpd']['trapserver']}
2369
trapport := {$config['snmpd']['trapserverport']}
2370
trap := "{$config['snmpd']['trapstring']}"
2371

    
2372

    
2373
EOD;
2374
		}
2375

    
2376
		$platform = trim(file_get_contents('/etc/platform'));
2377
		if (($platform == "pfSense") && ($g['product_name'] != "pfSense")) {
2378
			$platform = $g['product_name'];
2379
		}
2380
		$sysDescr = "{$g['product_name']} " . php_uname("n") .
2381
			" {$g['product_version']} {$platform} " . php_uname("s") .
2382
			" " . php_uname("r") . " " . php_uname("m");
2383

    
2384
		$snmpdconf .= <<<EOD
2385
system := 1     # pfSense
2386
%snmpd
2387
sysDescr			= "{$sysDescr}"
2388
begemotSnmpdDebugDumpPdus       = 2
2389
begemotSnmpdDebugSyslogPri      = 7
2390
begemotSnmpdCommunityString.0.1 = $(read)
2391

    
2392
EOD;
2393

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

    
2399
EOD;
2400
		}
2401
*/
2402

    
2403

    
2404
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2405
			$snmpdconf .= <<<EOD
2406
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
2407
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
2408
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
2409

    
2410
EOD;
2411
		}
2412

    
2413

    
2414
		$snmpdconf .= <<<EOD
2415
begemotSnmpdCommunityDisable    = 1
2416

    
2417
EOD;
2418

    
2419
		$bind_to_ip = "0.0.0.0";
2420
		if (isset($config['snmpd']['bindip'])) {
2421
			if (is_ipaddr($config['snmpd']['bindip'])) {
2422
				$bind_to_ip = $config['snmpd']['bindip'];
2423
			} else {
2424
				$if = get_real_interface($config['snmpd']['bindip']);
2425
				if (does_interface_exist($if)) {
2426
					$bind_to_ip = get_interface_ip($config['snmpd']['bindip']);
2427
				}
2428
			}
2429
		}
2430

    
2431
		if (is_port($config['snmpd']['pollport'])) {
2432
			$snmpdconf .= <<<EOD
2433
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
2434

    
2435
EOD;
2436

    
2437
		}
2438

    
2439
		$snmpdconf .= <<<EOD
2440
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
2441
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
2442

    
2443
# These are bsnmp macros not php vars.
2444
sysContact      = $(contact)
2445
sysLocation     = $(location)
2446
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
2447

    
2448
snmpEnableAuthenTraps = 2
2449

    
2450
EOD;
2451

    
2452
		if (is_array($config['snmpd']['modules'])) {
2453
			if (isset($config['snmpd']['modules']['mibii'])) {
2454
			$snmpdconf .= <<<EOD
2455
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
2456

    
2457
EOD;
2458
			}
2459

    
2460
			if (isset($config['snmpd']['modules']['netgraph'])) {
2461
				$snmpdconf .= <<<EOD
2462
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
2463
%netgraph
2464
begemotNgControlNodeName = "snmpd"
2465

    
2466
EOD;
2467
			}
2468

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

    
2473
EOD;
2474
			}
2475

    
2476
			if (isset($config['snmpd']['modules']['hostres'])) {
2477
				$snmpdconf .= <<<EOD
2478
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
2479

    
2480
EOD;
2481
			}
2482

    
2483
			if (isset($config['snmpd']['modules']['bridge'])) {
2484
				$snmpdconf .= <<<EOD
2485
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
2486
# config must end with blank line
2487

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

    
2494
EOD;
2495
			}
2496
			if (isset($config['snmpd']['modules']['regex'])) {
2497
				$snmpdconf .= <<<EOD
2498
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"
2499

    
2500
EOD;
2501
			}
2502
		}
2503

    
2504
		fwrite($fd, $snmpdconf);
2505
		fclose($fd);
2506
		unset($snmpdconf);
2507

    
2508
		/* run bsnmpd */
2509
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
2510
			" -p {$g['varrun_path']}/snmpd.pid");
2511

    
2512
		if (platform_booting()) {
2513
			echo gettext("done.") . "\n";
2514
		}
2515
	}
2516

    
2517
	return 0;
2518
}
2519

    
2520
function services_dnsupdate_process($int = "", $updatehost = "", $forced = false) {
2521
	global $config, $g;
2522
	if (isset($config['system']['developerspew'])) {
2523
		$mt = microtime();
2524
		echo "services_dnsupdate_process() being called $mt\n";
2525
	}
2526

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

    
2554
			/* determine interface name */
2555
			$if = get_failover_interface($dnsupdate['interface']);
2556

    
2557
			if (isset($dnsupdate['usepublicip'])) {
2558
				$wanip = dyndnsCheckIP($if);
2559
			} else {
2560
				$wanip = get_interface_ip($if);
2561
			}
2562

    
2563
			$wanipv6 = get_interface_ipv6($if);
2564
			$cacheFile = "{$g['conf_path']}/dyndns_{$dnsupdate['interface']}_rfc2136_" . escapeshellarg($dnsupdate['host']) . "_{$dnsupdate['server']}.cache";
2565
			$currentTime = time();
2566

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

    
2574
				$hostname = $dnsupdate['host'];
2575
				/* trailing dot */
2576
				if (substr($hostname, -1) != ".") {
2577
					$hostname .= ".";
2578
				}
2579

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

    
2589
EOD;
2590
				fwrite($fd, $privkey);
2591
				fclose($fd);
2592

    
2593
				/* write public key file */
2594
				if ($dnsupdate['keytype'] == "zone") {
2595
					$flags = 257;
2596
					$proto = 3;
2597
				} else if ($dnsupdate['keytype'] == "host") {
2598
					$flags = 513;
2599
					$proto = 3;
2600
				} else if ($dnsupdate['keytype'] == "user") {
2601
					$flags = 0;
2602
					$proto = 2;
2603
				}
2604

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

    
2609
				/* generate update instructions */
2610
				$upinst = "";
2611
				if (!empty($dnsupdate['server'])) {
2612
					$upinst .= "server {$dnsupdate['server']}\n";
2613
				}
2614

    
2615
				if (file_exists($cacheFile)) {
2616
					list($cachedipv4, $cacheTimev4) = explode("|", file_get_contents($cacheFile));
2617
				}
2618
				if (file_exists("{$cacheFile}.ipv6")) {
2619
					list($cachedipv6, $cacheTimev6) = explode("|", file_get_contents("{$cacheFile}.ipv6"));
2620
				}
2621

    
2622
				// 25 Days
2623
				$maxCacheAgeSecs = 25 * 24 * 60 * 60;
2624
				$need_update = false;
2625

    
2626
				conf_mount_rw();
2627
				/* Update IPv4 if we have it. */
2628
				if (is_ipaddrv4($wanip) && $dnsupdate['recordtype'] != "AAAA") {
2629
					if (($wanip != $cachedipv4) || (($currentTime - $cacheTimev4) > $maxCacheAgeSecs) || $forced) {
2630
						$upinst .= "update delete {$dnsupdate['host']}. A\n";
2631
						$upinst .= "update add {$dnsupdate['host']}. {$dnsupdate['ttl']} A {$wanip}\n";
2632
						$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";
2633
						@file_put_contents($cacheFile, "{$wanip}|{$currentTime}");
2634
						log_error(sprintf(gettext('phpDynDNS: updating cache file %1$s: %2$s'), $cacheFile, $wanip));
2635
						$need_update = true;
2636
					} else {
2637
						log_error(sprintf(gettext("phpDynDNS: Not updating %s A record because the IP address has not changed."), $dnsupdate['host']));
2638
					}
2639
				} else {
2640
					@unlink($cacheFile);
2641
				}
2642

    
2643
				/* Update IPv6 if we have it. */
2644
				if (is_ipaddrv6($wanipv6) && $dnsupdate['recordtype'] != "A") {
2645
					if (($wanipv6 != $cachedipv6) || (($currentTime - $cacheTimev6) > $maxCacheAgeSecs) || $forced) {
2646
						$upinst .= "update delete {$dnsupdate['host']}. AAAA\n";
2647
						$upinst .= "update add {$dnsupdate['host']}. {$dnsupdate['ttl']} AAAA {$wanipv6}\n";
2648
						$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";
2649
						@file_put_contents("{$cacheFile}.ipv6", "{$wanipv6}|{$currentTime}");
2650
						log_error(sprintf(gettext('phpDynDNS: updating cache file %1$s.ipv6: %2$s'), $cacheFile, $wanipv6));
2651
						$need_update = true;
2652
					} else {
2653
						log_error(sprintf(gettext("phpDynDNS: Not updating %s AAAA record because the IPv6 address has not changed."), $dnsupdate['host']));
2654
					}
2655
				} else {
2656
					@unlink("{$cacheFile}.ipv6");
2657
				}
2658
				conf_mount_ro();
2659

    
2660
				$upinst .= "\n";	/* mind that trailing newline! */
2661

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

    
2681
	return 0;
2682
}
2683

    
2684
/* configure cron service */
2685
function configure_cron() {
2686
	global $g, $config;
2687

    
2688
	conf_mount_rw();
2689
	/* preserve existing crontab entries */
2690
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2691

    
2692
	for ($i = 0; $i < count($crontab_contents); $i++) {
2693
		$cron_item =& $crontab_contents[$i];
2694
		if (strpos($cron_item, "# pfSense specific crontab entries") !== false) {
2695
			array_splice($crontab_contents, $i - 1);
2696
			break;
2697
		}
2698
	}
2699
	$crontab_contents = implode("\n", $crontab_contents) . "\n";
2700

    
2701

    
2702
	if (is_array($config['cron']['item'])) {
2703
		$crontab_contents .= "#\n";
2704
		$crontab_contents .= "# pfSense specific crontab entries\n";
2705
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
2706
		$crontab_contents .= "#\n";
2707

    
2708
		if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) {
2709
			$http_proxy = $config['system']['proxyurl'];
2710
			if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) {
2711
				$http_proxy .= ':' . $config['system']['proxyport'];
2712
			}
2713
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
2714
		}
2715

    
2716
		foreach ($config['cron']['item'] as $item) {
2717
			$crontab_contents .= "\n{$item['minute']}\t";
2718
			$crontab_contents .= "{$item['hour']}\t";
2719
			$crontab_contents .= "{$item['mday']}\t";
2720
			$crontab_contents .= "{$item['month']}\t";
2721
			$crontab_contents .= "{$item['wday']}\t";
2722
			$crontab_contents .= "{$item['who']}\t";
2723
			$crontab_contents .= "{$item['command']}";
2724
		}
2725

    
2726
		$crontab_contents .= "\n#\n";
2727
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
2728
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
2729
		$crontab_contents .= "#\n\n";
2730
	}
2731

    
2732
	/* please maintain the newline at the end of file */
2733
	file_put_contents("/etc/crontab", $crontab_contents);
2734
	unset($crontab_contents);
2735

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

    
2744
	conf_mount_ro();
2745
}
2746

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

    
2771
function upnp_start() {
2772
	global $config;
2773

    
2774
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
2775
		return;
2776
	}
2777

    
2778
	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
2779
		echo gettext("Starting UPnP service... ");
2780
		require_once('/usr/local/pkg/miniupnpd.inc');
2781
		sync_package_miniupnpd();
2782
		echo "done.\n";
2783
	}
2784
}
2785

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

    
2789
	$is_installed = false;
2790
	$cron_changed = true;
2791

    
2792
	if (!is_array($config['cron'])) {
2793
		$config['cron'] = array();
2794
	}
2795
	if (!is_array($config['cron']['item'])) {
2796
		$config['cron']['item'] = array();
2797
	}
2798

    
2799
	$x = 0;
2800
	foreach ($config['cron']['item'] as $item) {
2801
		if (strstr($item['command'], $command)) {
2802
			$is_installed = true;
2803
			break;
2804
		}
2805
		$x++;
2806
	}
2807

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

    
2836
	if ($cron_changed) {
2837
		configure_cron();
2838
	}
2839
}
2840

    
2841
?>
(49-49/65)