Project

General

Profile

Download (84.5 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * services.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2004-2016 Electric Sheep Fencing, LLC
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', 'citynetwork cloudflare custom custom-v6 dnsexit dnsimple dnsmadeeasy dnsomatic 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', 'City Network,CloudFlare,Custom,Custom (v6),DNSexit,DNSimple,DNS Made Easy,DNS-O-Matic,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
	/* configure DHCPD chroot once */
431
	$fd = fopen("{$g['tmp_path']}/dhcpd.sh", "w");
432
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}\n");
433
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/dev\n");
434
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/etc\n");
435
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/usr/local/sbin\n");
436
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db\n");
437
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run\n");
438
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/usr\n");
439
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/lib\n");
440
	fwrite($fd, "/bin/mkdir -p {$g['dhcpd_chroot_path']}/run\n");
441
	fwrite($fd, "/usr/sbin/chown -R dhcpd:_dhcp {$g['dhcpd_chroot_path']}/*\n");
442
	fwrite($fd, "/bin/cp -n /lib/libc.so.* {$g['dhcpd_chroot_path']}/lib/\n");
443
	fwrite($fd, "/bin/cp -n /usr/local/sbin/dhcpd {$g['dhcpd_chroot_path']}/usr/local/sbin/\n");
444
	fwrite($fd, "/bin/chmod a+rx {$g['dhcpd_chroot_path']}/usr/local/sbin/dhcpd\n");
445

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

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

    
462
function services_dhcpdv4_configure() {
463
	global $config, $g;
464
	$need_ddns_updates = false;
465
	$ddns_zones = array();
466

    
467
	if ($g['services_dhcp_server_enable'] == false) {
468
		return;
469
	}
470

    
471
	if (isset($config['system']['developerspew'])) {
472
		$mt = microtime();
473
		echo "services_dhcpdv4_configure($if) being called $mt\n";
474
	}
475

    
476
	/* kill any running dhcpd */
477
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid")) {
478
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpd.pid");
479
	}
480

    
481
	/* DHCP enabled on any interfaces? */
482
	if (!is_dhcp_server_enabled()) {
483
		return 0;
484
	}
485

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

    
499
	if (platform_booting()) {
500
		/* restore the leases, if we have them */
501
		if (file_exists("{$g['cf_conf_path']}/dhcpleases.tgz")) {
502
			$dhcprestore = "";
503
			$dhcpreturn = "";
504
			exec("cd /;LANG=C /usr/bin/tar -xzf {$g['cf_conf_path']}/dhcpleases.tgz 2>&1", $dhcprestore, $dhcpreturn);
505
			$dhcprestore = implode(" ", $dhcprestore);
506
			if ($dhcpreturn <> 0) {
507
				log_error(sprintf(gettext('DHCP leases restore failed exited with %1$s, the error is: %2$s%3$s'), $dhcpreturn, $dhcprestore, "\n"));
508
			}
509
		}
510
		/* 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. */
511
		if (($g['platform'] == $g['product_name']) && !isset($config['system']['use_mfs_tmpvar'])) {
512
			unlink_if_exists("{$g['cf_conf_path']}/dhcpleases.tgz");
513
		}
514
	}
515

    
516
	$syscfg = $config['system'];
517
	if (!is_array($config['dhcpd'])) {
518
		$config['dhcpd'] = array();
519
	}
520
	$dhcpdcfg = $config['dhcpd'];
521
	$Iflist = get_configured_interface_list();
522

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

    
533
	if (platform_booting()) {
534
		echo gettext("Starting DHCP service...");
535
	} else {
536
		sleep(1);
537
	}
538

    
539
	$custoptions = "";
540
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
541
		if (is_array($dhcpifconf['numberoptions']) && is_array($dhcpifconf['numberoptions']['item'])) {
542
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
543
				if (!empty($item['type'])) {
544
					$itemtype = $item['type'];
545
				} else {
546
					$itemtype = "text";
547
				}
548
				$custoptions .= "option custom-{$dhcpif}-{$itemidx} code {$item['number']} = {$itemtype};\n";
549
			}
550
		}
551
	}
552

    
553
	$dhcpdconf = <<<EOD
554

    
555
option domain-name "{$syscfg['domain']}";
556
option ldap-server code 95 = text;
557
option domain-search-list code 119 = text;
558
option arch code 93 = unsigned integer 16; # RFC4578
559
{$custoptions}
560
default-lease-time 7200;
561
max-lease-time 86400;
562
log-facility local7;
563
one-lease-per-client true;
564
deny duplicates;
565
ping-check true;
566
update-conflict-detection false;
567
dhcp-cache-threshold 0;
568

    
569
EOD;
570

    
571
	if (!isset($dhcpifconf['disableauthoritative'])) {
572
		$dhcpdconf .= "authoritative;\n";
573
	}
574

    
575
	if (isset($dhcpifconf['alwaysbroadcast'])) {
576
		$dhcpdconf .= "always-broadcast on\n";
577
	}
578

    
579
	$dhcpdifs = array();
580
	$enable_add_routers = false;
581
	$gateways_arr = return_gateways_array();
582
	/* only add a routers line if the system has any IPv4 gateway at all */
583
	/* a static route has a gateway, manually overriding this field always works */
584
	foreach ($gateways_arr as $gwitem) {
585
		if ($gwitem['ipprotocol'] == "inet") {
586
			$enable_add_routers = true;
587
			break;
588
		}
589
	}
590

    
591
	/*    loop through and determine if we need to setup
592
	 *    failover peer "bleh" entries
593
	 */
594
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
595

    
596
		if (!isset($config['interfaces'][$dhcpif]['enable'])) {
597
			continue;
598
		}
599

    
600
		interfaces_staticarp_configure($dhcpif);
601

    
602
		if (!isset($dhcpifconf['enable'])) {
603
			continue;
604
		}
605

    
606
		if ($dhcpifconf['failover_peerip'] <> "") {
607
			$intip = get_interface_ip($dhcpif);
608
			/*
609
			 *    yep, failover peer is defined.
610
			 *    does it match up to a defined vip?
611
			 */
612
			$skew = 110;
613
			if (is_array($config['virtualip']['vip'])) {
614
				foreach ($config['virtualip']['vip'] as $vipent) {
615
					if ($vipent['interface'] == $dhcpif) {
616
						$carp_nw = gen_subnet($vipent['subnet'], $vipent['subnet_bits']);
617
						if (ip_in_subnet($dhcpifconf['failover_peerip'], "{$carp_nw}/{$vipent['subnet_bits']}")) {
618
							/* this is the interface! */
619
							if (is_numeric($vipent['advskew']) && (intval($vipent['advskew']) < 20)) {
620
								$skew = 0;
621
								break;
622
							}
623
						}
624
					}
625
				}
626
			} else {
627
				log_error(gettext("Warning!  DHCP Failover setup and no CARP virtual IPs defined!"));
628
			}
629
			if ($skew > 10) {
630
				$type = "secondary";
631
				$my_port = "520";
632
				$peer_port = "519";
633
			} else {
634
				$my_port = "519";
635
				$peer_port = "520";
636
				$type = "primary";
637
				$dhcpdconf_pri = "split 128;\n";
638
				$dhcpdconf_pri .= "  mclt 600;\n";
639
			}
640

    
641
			if (is_ipaddrv4($intip)) {
642
				$dhcpdconf .= <<<EOPP
643
failover peer "dhcp_{$dhcpif}" {
644
  {$type};
645
  address {$intip};
646
  port {$my_port};
647
  peer address {$dhcpifconf['failover_peerip']};
648
  peer port {$peer_port};
649
  max-response-delay 10;
650
  max-unacked-updates 10;
651
  {$dhcpdconf_pri}
652
  load balance max seconds 3;
653
}
654
\n
655
EOPP;
656
			}
657
		}
658
	}
659

    
660
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
661

    
662
		$newzone = array();
663
		$ifcfg = $config['interfaces'][$dhcpif];
664

    
665
		if (!isset($dhcpifconf['enable']) || !isset($Iflist[$dhcpif])) {
666
			continue;
667
		}
668
		$ifcfgip = get_interface_ip($dhcpif);
669
		$ifcfgsn = get_interface_subnet($dhcpif);
670
		$subnet = gen_subnet($ifcfgip, $ifcfgsn);
671
		$subnetmask = gen_subnet_mask($ifcfgsn);
672

    
673
		if (!is_ipaddr($subnet)) {
674
			continue;
675
		}
676

    
677
		if ($is_olsr_enabled == true) {
678
			if ($dhcpifconf['netmask']) {
679
				$subnetmask = gen_subnet_mask($dhcpifconf['netmask']);
680
			}
681
		}
682

    
683
		$all_pools = array();
684
		$all_pools[] = $dhcpifconf;
685
		if (is_array($dhcpifconf['pool'])) {
686
			$all_pools = array_merge($all_pools, $dhcpifconf['pool']);
687
		}
688

    
689
		$dnscfg = "";
690

    
691
		if ($dhcpifconf['domain']) {
692
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
693
		}
694

    
695
		if ($dhcpifconf['domainsearchlist'] <> "") {
696
			$dnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpifconf['domainsearchlist'])) . "\";\n";
697
		}
698

    
699
		if (isset($dhcpifconf['ddnsupdate'])) {
700
			$need_ddns_updates = true;
701
			$newzone = array();
702
			if ($dhcpifconf['ddnsdomain'] <> "") {
703
				$newzone['domain-name'] = $dhcpifconf['ddnsdomain'];
704
				$dnscfg .= "	ddns-domainname \"{$dhcpifconf['ddnsdomain']}\";\n";
705
			} else {
706
				$newzone['domain-name'] = $config['system']['domain'];
707
			}
708

    
709
			$revsubnet = array_reverse(explode('.',$subnet));
710

    
711
			/* Take care of full classes first */
712
			switch ($ifcfgsn) {
713
				case 8:
714
					$start_octet = 3;
715
					break;
716
				case 16:
717
					$start_octet = 2;
718
					break;
719
				case 24:
720
					$start_octet = 1;
721
					break;
722
				default:
723
					$start_octet = 0;
724
					/* Add subnet bitmask to first octet */
725
					$revsubnet[0] .= '-' . $ifcfgsn;
726
					break;
727

    
728
			}
729

    
730
			$ptr_domain = '';
731
			for ($octet = 0; $octet <= 3; $octet++) {
732
				if ($octet < $start_octet) {
733
					continue;
734
				}
735
				$ptr_domain .= ((empty($ptr_domain) && $ptr_domain !== "0") ? '' : '.');
736
				$ptr_domain .= $revsubnet[$octet];
737
			}
738
			$ptr_domain .= ".in-addr.arpa";
739
			$newzone['ptr-domain'] = $ptr_domain;
740
			unset($ptr_domain, $revsubnet, $start_octet);
741
		}
742

    
743
		if (is_array($dhcpifconf['dnsserver']) && ($dhcpifconf['dnsserver'][0])) {
744
			$dnscfg .= "	option domain-name-servers " . join(",", $dhcpifconf['dnsserver']) . ";";
745
			if ($newzone['domain-name']) {
746
				$newzone['dns-servers'] = $dhcpifconf['dnsserver'];
747
			}
748
		} else if (isset($config['dnsmasq']['enable'])) {
749
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
750
			if ($newzone['domain-name'] && is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
751
				$newzone['dns-servers'] = $syscfg['dnsserver'];
752
			}
753
		} else if (isset($config['unbound']['enable'])) {
754
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
755
		} else if (!empty($dns_arrv4)) {
756
			$dnscfg .= "	option domain-name-servers " . join(",", $dns_arrv4) . ";";
757
			if ($newzone['domain-name']) {
758
				$newzone['dns-servers'] = $dns_arrv4;
759
			}
760
		}
761

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

    
786
		$dhcpdconf .= "subnet {$subnet} netmask {$subnetmask} {\n";
787

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

    
833
			/* allow/deny MACs */
834
			$mac_allow_list = array_unique(explode(',', $poolconf['mac_allow']));
835
			foreach ($mac_allow_list as $mac) {
836
				if (empty($mac)) {
837
					continue;
838
				}
839
				$dhcpdconf .= "		allow members of \"" . str_replace(':', '', $mac) . "\";\n";
840
			}
841
			$deny_action = "deny";
842
			if (isset($poolconf['nonak']) && empty($poolconf['failover_peerip'])) {
843
				$deny_action = "ignore";
844
			}
845
			$mac_deny_list = array_unique(explode(',', $poolconf['mac_deny']));
846
			foreach ($mac_deny_list as $mac) {
847
				if (empty($mac)) {
848
					continue;
849
				}
850
				$dhcpdconf .= "		$deny_action members of \"" . str_replace(':', '', $mac) . "\";\n";
851
			}
852

    
853
			if ($poolconf['failover_peerip'] <> "") {
854
				$dhcpdconf .= "		$deny_action dynamic bootp clients;\n";
855
			}
856

    
857
			if (isset($poolconf['denyunknown'])) {
858
				$dhcpdconf .= "		$deny_action unknown-clients;\n";
859
			}
860

    
861
			if ($poolconf['gateway'] && $poolconf['gateway'] != "none" && ($poolconf['gateway'] != $dhcpifconf['gateway'])) {
862
				$dhcpdconf .= "		option routers {$poolconf['gateway']};\n";
863
			}
864

    
865
			if ($dhcpifconf['failover_peerip'] <> "") {
866
				$dhcpdconf .= "		failover peer \"dhcp_{$dhcpif}\";\n";
867
			}
868

    
869
			$pdnscfg = "";
870

    
871
			if ($poolconf['domain'] && ($poolconf['domain'] != $dhcpifconf['domain'])) {
872
				$pdnscfg .= "		option domain-name \"{$poolconf['domain']}\";\n";
873
			}
874

    
875
			if (!empty($poolconf['domainsearchlist']) && ($poolconf['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
876
				$pdnscfg .= "		option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $poolconf['domainsearchlist'])) . "\";\n";
877
			}
878

    
879
			if (isset($poolconf['ddnsupdate'])) {
880
				if (($poolconf['ddnsdomain'] <> "") && ($poolconf['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
881
					$pdnscfg .= "		ddns-domainname \"{$poolconf['ddnsdomain']}\";\n";
882
				}
883
				$pdnscfg .= "		ddns-update-style interim;\n";
884
			}
885

    
886
			if (is_array($poolconf['dnsserver']) && ($poolconf['dnsserver'][0]) && ($poolconf['dnsserver'][0] != $dhcpifconf['dnsserver'][0])) {
887
				$pdnscfg .= "		option domain-name-servers " . join(",", $poolconf['dnsserver']) . ";\n";
888
			}
889
			$dhcpdconf .= "{$pdnscfg}";
890

    
891
			// default-lease-time
892
			if ($poolconf['defaultleasetime'] && ($poolconf['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
893
				$dhcpdconf .= "		default-lease-time {$poolconf['defaultleasetime']};\n";
894
			}
895

    
896
			// max-lease-time
897
			if ($poolconf['maxleasetime'] && ($poolconf['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
898
				$dhcpdconf .= "		max-lease-time {$poolconf['maxleasetime']};\n";
899
			}
900

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

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

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

    
917
			// ldap-server
918
			if (!empty($poolconf['ldap']) && ($poolconf['ldap'] != $dhcpifconf['ldap'])) {
919
				$dhcpdconf .= "		option ldap-server \"{$poolconf['ldap']}\";\n";
920
			}
921

    
922
			// net boot information
923
			if (isset($poolconf['netboot'])) {
924
				if (!empty($poolconf['nextserver']) && ($poolconf['nextserver'] != $dhcpifconf['nextserver'])) {
925
					$dhcpdconf .= "		next-server {$poolconf['nextserver']};\n";
926
				}
927
				if (!empty($poolconf['filename']) && ($poolconf['filename'] != $dhcpifconf['filename'])) {
928
					$dhcpdconf .= "		filename \"{$poolconf['filename']}\";\n";
929
				}
930
				if (!empty($poolconf['rootpath']) && ($poolconf['rootpath'] != $dhcpifconf['rootpath'])) {
931
					$dhcpdconf .= "		option root-path \"{$poolconf['rootpath']}\";\n";
932
				}
933
			}
934
			$dhcpdconf .= "		range {$poolconf['range']['from']} {$poolconf['range']['to']};\n";
935
			$dhcpdconf .= "	}\n\n";
936
		}
937
// End of settings inside pools
938

    
939
		if ($dhcpifconf['gateway'] && $dhcpifconf['gateway'] != "none") {
940
			$routers = $dhcpifconf['gateway'];
941
			$add_routers = true;
942
		} elseif ($dhcpifconf['gateway'] == "none") {
943
			$add_routers = false;
944
		} else {
945
			$add_routers = $enable_add_routers;
946
			$routers = $ifcfgip;
947
		}
948
		if ($add_routers) {
949
			$dhcpdconf .= "	option routers {$routers};\n";
950
		}
951

    
952
		$dhcpdconf .= <<<EOD
953
$dnscfg
954

    
955
EOD;
956
		// default-lease-time
957
		if ($dhcpifconf['defaultleasetime']) {
958
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
959
		}
960

    
961
		// max-lease-time
962
		if ($dhcpifconf['maxleasetime']) {
963
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
964
		}
965

    
966
		// netbios-name*
967
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
968
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
969
			$dhcpdconf .= "	option netbios-node-type 8;\n";
970
		}
971

    
972
		// ntp-servers
973
		if (is_array($dhcpifconf['ntpserver']) && $dhcpifconf['ntpserver'][0]) {
974
			$dhcpdconf .= "	option ntp-servers " . join(",", $dhcpifconf['ntpserver']) . ";\n";
975
		}
976

    
977
		// tftp-server-name
978
		if ($dhcpifconf['tftp'] <> "") {
979
			$dhcpdconf .= "	option tftp-server-name \"{$dhcpifconf['tftp']}\";\n";
980
		}
981

    
982
		// Handle option, number rowhelper values
983
		$dhcpdconf .= "\n";
984
		if ($dhcpifconf['numberoptions']['item']) {
985
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
986
				$item_value = base64_decode($item['value']);
987
				if (empty($item['type']) || $item['type'] == "text") {
988
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} \"{$item_value}\";\n";
989
				} else {
990
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} {$item_value};\n";
991
				}
992
			}
993
		}
994

    
995
		// ldap-server
996
		if ($dhcpifconf['ldap'] <> "") {
997
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
998
		}
999

    
1000
		// net boot information
1001
		if (isset($dhcpifconf['netboot'])) {
1002
			if ($dhcpifconf['nextserver'] <> "") {
1003
				$dhcpdconf .= "	next-server {$dhcpifconf['nextserver']};\n";
1004
			}
1005
			if (!empty($dhcpifconf['filename']) && !empty($dhcpifconf['filename32']) && !empty($dhcpifconf['filename64'])) {
1006
				$dhcpdconf .= "	if option arch = 00:06 {\n";
1007
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename32']}\";\n";
1008
				$dhcpdconf .= "	} else if option arch = 00:07 {\n";
1009
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1010
				$dhcpdconf .= "	} else if option arch = 00:09 {\n";
1011
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1012
				$dhcpdconf .= "	} else {\n";
1013
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename']}\";\n";
1014
				$dhcpdconf .= "	}\n\n";
1015
			} elseif (!empty($dhcpifconf['filename'])) {
1016
				$dhcpdconf .= "	filename \"{$dhcpifconf['filename']}\";\n";
1017
			}
1018
			if (!empty($dhcpifconf['rootpath'])) {
1019
				$dhcpdconf .= "	option root-path \"{$dhcpifconf['rootpath']}\";\n";
1020
			}
1021
		}
1022

    
1023
		$dhcpdconf .= <<<EOD
1024
}
1025

    
1026
EOD;
1027

    
1028
		/* add static mappings */
1029
		if (is_array($dhcpifconf['staticmap'])) {
1030

    
1031
			$i = 0;
1032
			foreach ($dhcpifconf['staticmap'] as $sm) {
1033
				$dhcpdconf .= "host s_{$dhcpif}_{$i} {\n";
1034

    
1035
				if ($sm['mac']) {
1036
					$dhcpdconf .= "        hardware ethernet {$sm['mac']};\n";
1037
				}
1038

    
1039
				if ($sm['cid']) {
1040
					$dhcpdconf .= "        option dhcp-client-identifier \"{$sm['cid']}\";\n";
1041
				}
1042

    
1043
				if ($sm['ipaddr']) {
1044
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
1045
				}
1046

    
1047
				if ($sm['hostname']) {
1048
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1049
					$dhhostname = str_replace(".", "_", $dhhostname);
1050
					$dhcpdconf .= "	option host-name \"{$dhhostname}\";\n";
1051
				}
1052
				if ($sm['filename']) {
1053
					$dhcpdconf .= "	filename \"{$sm['filename']}\";\n";
1054
				}
1055

    
1056
				if ($sm['rootpath']) {
1057
					$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1058
				}
1059

    
1060
				if ($sm['gateway'] && ($sm['gateway'] != $dhcpifconf['gateway'])) {
1061
					$dhcpdconf .= "	option routers {$sm['gateway']};\n";
1062
				}
1063

    
1064
				$smdnscfg = "";
1065

    
1066
				if ($sm['domain'] && ($sm['domain'] != $dhcpifconf['domain'])) {
1067
					$smdnscfg .= "	option domain-name \"{$sm['domain']}\";\n";
1068
				}
1069

    
1070
				if (!empty($sm['domainsearchlist']) && ($sm['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
1071
					$smdnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $sm['domainsearchlist'])) . "\";\n";
1072
				}
1073

    
1074
				if (isset($sm['ddnsupdate'])) {
1075
					if (($sm['ddnsdomain'] <> "") && ($sm['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
1076
						$pdnscfg .= "		ddns-domainname \"{$sm['ddnsdomain']}\";\n";
1077
					}
1078
					$pdnscfg .= "		ddns-update-style interim;\n";
1079
				}
1080

    
1081
				if (is_array($sm['dnsserver']) && ($sm['dnsserver'][0]) && ($sm['dnsserver'][0] != $dhcpifconf['dnsserver'][0])) {
1082
					$smdnscfg .= "	option domain-name-servers " . join(",", $sm['dnsserver']) . ";\n";
1083
				}
1084
				$dhcpdconf .= "{$smdnscfg}";
1085

    
1086
				// default-lease-time
1087
				if ($sm['defaultleasetime'] && ($sm['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
1088
					$dhcpdconf .= "	default-lease-time {$sm['defaultleasetime']};\n";
1089
				}
1090

    
1091
				// max-lease-time
1092
				if ($sm['maxleasetime'] && ($sm['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
1093
					$dhcpdconf .= "	max-lease-time {$sm['maxleasetime']};\n";
1094
				}
1095

    
1096
				// netbios-name*
1097
				if (is_array($sm['winsserver']) && $sm['winsserver'][0] && ($sm['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
1098
					$dhcpdconf .= "	option netbios-name-servers " . join(",", $sm['winsserver']) . ";\n";
1099
					$dhcpdconf .= "	option netbios-node-type 8;\n";
1100
				}
1101

    
1102
				// ntp-servers
1103
				if (is_array($sm['ntpserver']) && $sm['ntpserver'][0] && ($sm['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
1104
					$dhcpdconf .= "	option ntp-servers " . join(",", $sm['ntpserver']) . ";\n";
1105
				}
1106

    
1107
				// tftp-server-name
1108
				if (!empty($sm['tftp']) && ($sm['tftp'] != $dhcpifconf['tftp'])) {
1109
					$dhcpdconf .= "	option tftp-server-name \"{$sm['tftp']}\";\n";
1110
				}
1111

    
1112
				$dhcpdconf .= "}\n";
1113
				$i++;
1114
			}
1115
		}
1116

    
1117
		$dhcpdifs[] = get_real_interface($dhcpif);
1118
		if ($newzone['domain-name']) {
1119
			if ($need_ddns_updates) {
1120
				$newzone['dns-servers'] = array($dhcpifconf['ddnsdomainprimary']);
1121
				$newzone['ddnsdomainkeyname'] = $dhcpifconf['ddnsdomainkeyname'];
1122
				$newzone['ddnsdomainkey'] = $dhcpifconf['ddnsdomainkey'];
1123
				$dhcpdconf .= dhcpdkey($dhcpifconf);
1124
			}
1125
			$ddns_zones[] = $newzone;
1126
		}
1127
	}
1128

    
1129
	if ($need_ddns_updates) {
1130
		$dhcpdconf .= "ddns-update-style interim;\n";
1131
		$dhcpdconf .= "update-static-leases on;\n";
1132

    
1133
		$dhcpdconf .= dhcpdzones($ddns_zones);
1134
	}
1135

    
1136
	/* write dhcpd.conf */
1137
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpd.conf", $dhcpdconf)) {
1138
		printf(gettext("Error: cannot open dhcpd.conf in services_dhcpdv4_configure().%s"), "\n");
1139
		unset($dhcpdconf);
1140
		return 1;
1141
	}
1142
	unset($dhcpdconf);
1143

    
1144
	/* create an empty leases database */
1145
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
1146
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
1147
	}
1148

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

    
1153
	/* fire up dhcpd in a chroot */
1154
	if (count($dhcpdifs) > 0) {
1155
		mwexec("/usr/local/sbin/dhcpd -user dhcpd -group _dhcp -chroot {$g['dhcpd_chroot_path']} -cf /etc/dhcpd.conf -pf {$g['varrun_path']}/dhcpd.pid " .
1156
			join(" ", $dhcpdifs));
1157
	}
1158

    
1159
	if (platform_booting()) {
1160
		print "done.\n";
1161
	}
1162

    
1163
	return 0;
1164
}
1165

    
1166
function dhcpdkey($dhcpifconf) {
1167
	$dhcpdconf = "";
1168
	if ($dhcpifconf['ddnsdomainkeyname'] <> "" && $dhcpifconf['ddnsdomainkey'] <> "") {
1169
		$dhcpdconf .= "key {$dhcpifconf['ddnsdomainkeyname']} {\n";
1170
		$dhcpdconf .= "	algorithm hmac-md5;\n";
1171
		$dhcpdconf .= "	secret {$dhcpifconf['ddnsdomainkey']};\n";
1172
		$dhcpdconf .= "}\n";
1173
	}
1174

    
1175
	return $dhcpdconf;
1176
}
1177

    
1178
function dhcpdzones($ddns_zones) {
1179
	$dhcpdconf = "";
1180

    
1181
	if (is_array($ddns_zones)) {
1182
		$added_zones = array();
1183
		foreach ($ddns_zones as $zone) {
1184
			if (!is_array($zone) || empty($zone) || !is_array($zone['dns-servers'])) {
1185
				continue;
1186
			}
1187
			$primary = $zone['dns-servers'][0];
1188
			$secondary = empty($zone['dns-servers'][1]) ? "" : $zone['dns-servers'][1];
1189

    
1190
			// Make sure we aren't using any invalid or IPv6 DNS servers.
1191
			if (!is_ipaddrv4($primary)) {
1192
				if (is_ipaddrv4($secondary)) {
1193
					$primary = $secondary;
1194
					$secondary = "";
1195
				} else {
1196
					continue;
1197
				}
1198
			}
1199

    
1200
			// We don't need to add zones multiple times.
1201
			if ($zone['domain-name'] && !in_array($zone['domain-name'], $added_zones)) {
1202
				$dhcpdconf .= "zone {$zone['domain-name']}. {\n";
1203
				$dhcpdconf .= "	primary {$primary};\n";
1204
				if (is_ipaddrv4($secondary)) {
1205
					$dhcpdconf .= "	secondary {$secondary};\n";
1206
				}
1207
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1208
					$dhcpdconf .= "	key {$zone['ddnsdomainkeyname']};\n";
1209
				}
1210
				$dhcpdconf .= "}\n";
1211
				$added_zones[] = $zone['domain-name'];
1212
			}
1213
			if ($zone['ptr-domain'] && !in_array($zone['ptr-domain'], $added_zones)) {
1214
				$dhcpdconf .= "zone {$zone['ptr-domain']} {\n";
1215
				$dhcpdconf .= "	primary {$primary};\n";
1216
				if (is_ipaddrv4($secondary)) {
1217
					$dhcpdconf .= "	secondary {$secondary};\n";
1218
				}
1219
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1220
					$dhcpdconf .= "	key {$zone['ddnsdomainkeyname']};\n";
1221
				}
1222
				$dhcpdconf .= "}\n";
1223
				$added_zones[] = $zone['ptr-domain'];
1224
			}
1225
		}
1226
	}
1227

    
1228
	return $dhcpdconf;
1229
}
1230

    
1231
function services_dhcpdv6_configure($blacklist = array()) {
1232
	global $config, $g;
1233

    
1234
	if ($g['services_dhcp_server_enable'] == false) {
1235
		return;
1236
	}
1237

    
1238
	if (isset($config['system']['developerspew'])) {
1239
		$mt = microtime();
1240
		echo "services_dhcpd_configure($if) being called $mt\n";
1241
	}
1242

    
1243
	/* kill any running dhcpd */
1244
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid")) {
1245
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid");
1246
	}
1247
	if (isvalidpid("{$g['varrun_path']}/dhcpleases6.pid")) {
1248
		killbypid("{$g['varrun_path']}/dhcpleases6.pid");
1249
	}
1250

    
1251
	/* DHCP enabled on any interfaces? */
1252
	if (!is_dhcpv6_server_enabled()) {
1253
		return 0;
1254
	}
1255

    
1256
	if (platform_booting()) {
1257
		if ($g['platform'] != $g['product_name']) {
1258
			/* restore the leases, if we have them */
1259
			if (file_exists("{$g['cf_conf_path']}/dhcp6leases.tgz")) {
1260
				$dhcprestore = "";
1261
				$dhcpreturn = "";
1262
				exec("cd /;LANG=C /usr/bin/tar -xzf {$g['cf_conf_path']}/dhcp6leases.tgz 2>&1", $dhcprestore, $dhcpreturn);
1263
				$dhcprestore = implode(" ", $dhcprestore);
1264
				if ($dhcpreturn <> 0) {
1265
					log_error(sprintf(gettext('DHCP leases v6 restore failed exited with %1$s, the error is: %2$s'), $dhcpreturn, $dhcprestore));
1266
				}
1267
			}
1268
		}
1269
	}
1270

    
1271
	$syscfg = $config['system'];
1272
	if (!is_array($config['dhcpdv6'])) {
1273
		$config['dhcpdv6'] = array();
1274
	}
1275
	$dhcpdv6cfg = $config['dhcpdv6'];
1276
	$Iflist = get_configured_interface_list();
1277
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
1278

    
1279

    
1280
	if (platform_booting()) {
1281
		echo "Starting DHCPv6 service...";
1282
	} else {
1283
		sleep(1);
1284
	}
1285

    
1286
	$custoptionsv6 = "";
1287
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1288
		if (is_array($dhcpv6ifconf['numberoptions']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1289
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1290
				$custoptionsv6 .= "option custom-{$dhcpv6if}-{$itemv6idx} code {$itemv6['number']} = text;\n";
1291
			}
1292
		}
1293
	}
1294

    
1295
	if (isset($dhcpv6ifconf['netboot']) && !empty($dhcpv6ifconf['bootfile_url'])) {
1296
		$custoptionsv6 .= "option dhcp6.bootfile-url code 59 = string;\n";
1297
	}
1298

    
1299
	$dhcpdv6conf = <<<EOD
1300

    
1301
option domain-name "{$syscfg['domain']}";
1302
option ldap-server code 95 = text;
1303
option domain-search-list code 119 = text;
1304
{$custoptionsv6}
1305
default-lease-time 7200;
1306
max-lease-time 86400;
1307
log-facility local7;
1308
one-lease-per-client true;
1309
deny duplicates;
1310
ping-check true;
1311
update-conflict-detection false;
1312

    
1313
EOD;
1314

    
1315
	if (!isset($dhcpv6ifconf['disableauthoritative'])) {
1316
		$dhcpdv6conf .= "authoritative;\n";
1317
	}
1318

    
1319
	if (isset($dhcpv6ifconf['alwaysbroadcast'])) {
1320
		$dhcpdv6conf .= "always-broadcast on\n";
1321
	}
1322

    
1323
	$dhcpdv6ifs = array();
1324

    
1325
	$dhcpv6num = 0;
1326
	$nsupdate = false;
1327

    
1328
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1329

    
1330
		$ddns_zones = array();
1331

    
1332
		$ifcfgv6 = $config['interfaces'][$dhcpv6if];
1333

    
1334
		if (!isset($dhcpv6ifconf['enable']) || !isset($Iflist[$dhcpv6if]) || !isset($ifcfgv6['enable'])) {
1335
			continue;
1336
		}
1337
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1338
		if (!is_ipaddrv6($ifcfgipv6)) {
1339
			continue;
1340
		}
1341
		$ifcfgsnv6 = get_interface_subnetv6($dhcpv6if);
1342
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1343

    
1344
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
1345
			$trackifname = $config['interfaces'][$ifname]['track6-interface'];
1346
			$trackcfg = $config['interfaces'][$trackifname];
1347
			$pdlen = 64 - $trackcfg['dhcp6-ia-pd-len'];
1348
		}
1349

    
1350
		if ($is_olsr_enabled == true) {
1351
			if ($dhcpv6ifconf['netmask']) {
1352
				$subnetmask = gen_subnet_maskv6($dhcpv6ifconf['netmask']);
1353
			}
1354
		}
1355

    
1356
		$dnscfgv6 = "";
1357

    
1358
		if ($dhcpv6ifconf['domain']) {
1359
			$dnscfgv6 .= "	option domain-name \"{$dhcpv6ifconf['domain']}\";\n";
1360
		}
1361

    
1362
		if ($dhcpv6ifconf['domainsearchlist'] <> "") {
1363
			$dnscfgv6 .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpv6ifconf['domainsearchlist'])) . "\";\n";
1364
		}
1365

    
1366
		if (isset($dhcpv6ifconf['ddnsupdate'])) {
1367
			if ($dhcpv6ifconf['ddnsdomain'] <> "") {
1368
				$dnscfgv6 .= "	ddns-domainname \"{$dhcpv6ifconf['ddnsdomain']}\";\n";
1369
			}
1370
			if (empty($dhcpv6ifconf['ddnsclientupdates'])) {
1371
				$ddnsclientupdates = 'allow';
1372
			} else {
1373
				$ddnsclientupdates = $dhcpv6ifconf['ddnsclientupdates'];
1374
			}
1375
			$dnscfgv6 .= "	{$ddnsclientupdates} client-updates;\n";
1376
			$nsupdate = true;
1377
		} else {
1378
			$dnscfgv6 .= "	do-forward-updates false;\n";
1379
		}
1380

    
1381
		if (is_array($dhcpv6ifconf['dnsserver']) && ($dhcpv6ifconf['dnsserver'][0])) {
1382
			$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dhcpv6ifconf['dnsserver']) . ";";
1383
		} else if (((isset($config['dnsmasq']['enable'])) || isset($config['unbound']['enable'])) && (is_ipaddrv6($ifcfgipv6))) {
1384
			$dnscfgv6 .= "	option dhcp6.name-servers {$ifcfgipv6};";
1385
		} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1386
			$dns_arrv6 = array();
1387
			foreach ($syscfg['dnsserver'] as $dnsserver) {
1388
				if (is_ipaddrv6($dnsserver)) {
1389
					$dns_arrv6[] = $dnsserver;
1390
				}
1391
			}
1392
			if (!empty($dns_arrv6)) {
1393
				$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dns_arrv6) . ";";
1394
			}
1395
		}
1396

    
1397
		if (!is_ipaddrv6($ifcfgipv6)) {
1398
			$ifcfgsnv6 = "64";
1399
			$subnetv6 = gen_subnetv6($dhcpv6ifconf['range']['from'], $ifcfgsnv6);
1400
		}
1401

    
1402
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1403

    
1404
		if (isset($dhcpv6ifconf['ddnsupdate']) &&
1405
		    !empty($dhcpv6ifconf['ddnsdomain'])) {
1406
			$newzone = array();
1407
			$newzone['domain-name'] = $dhcpv6ifconf['ddnsdomain'];
1408
			$newzone['dns-servers'][] = $dhcpv6ifconf['ddnsdomainprimary'];
1409
			$newzone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1410
			$newzone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1411
			$ddns_zones[] = $newzone;
1412
			if (isset($dhcpv6ifconf['ddnsreverse'])) {
1413
				$ptr_zones = get_v6_ptr_zones($subnetv6, $ifcfgsnv6);
1414
				foreach ($ptr_zones as $ptr_zone) {
1415
					$reversezone = array();
1416
					$reversezone['domain-name'] = $ptr_zone;
1417
					$reversezone['dns-servers'][] =
1418
					    $dhcpv6ifconf['ddnsdomainprimary'];
1419
					$ddns_zones[] = $reversezone;
1420
				}
1421
			}
1422
		}
1423

    
1424
		$dhcpdv6conf .= " {\n";
1425

    
1426
		$range_from = $dhcpv6ifconf['range']['from'];
1427
		$range_to = $dhcpv6ifconf['range']['to'];
1428
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
1429
			$range_from = merge_ipv6_delegated_prefix($ifcfgipv6, $range_from, $pdlen);
1430
			$range_to = merge_ipv6_delegated_prefix($ifcfgipv6, $range_to, $pdlen);
1431
		}
1432

    
1433
		$dhcpdv6conf .= <<<EOD
1434
	range6 {$range_from} {$range_to};
1435
$dnscfgv6
1436

    
1437
EOD;
1438

    
1439
		if (is_ipaddrv6($dhcpv6ifconf['prefixrange']['from']) && is_ipaddrv6($dhcpv6ifconf['prefixrange']['to'])) {
1440
			$dhcpdv6conf .= "	prefix6 {$dhcpv6ifconf['prefixrange']['from']} {$dhcpv6ifconf['prefixrange']['to']} /{$dhcpv6ifconf['prefixrange']['prefixlength']};\n";
1441
		}
1442
		if (is_ipaddrv6($dhcpv6ifconf['dns6ip'])) {
1443
			$dns6ip = $dhcpv6ifconf['dns6ip'];
1444
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1445
			    Net_IPv6::isInNetmask($dns6ip, '::', $pdlen)) {
1446
				$dns6ip = merge_ipv6_delegated_prefix($ifcfgipv6, $dns6ip, $pdlen);
1447
			}
1448
			$dhcpdv6conf .= "	option dhcp6.name-servers {$dns6ip};\n";
1449
		}
1450
		// default-lease-time
1451
		if ($dhcpv6ifconf['defaultleasetime']) {
1452
			$dhcpdv6conf .= "	default-lease-time {$dhcpv6ifconf['defaultleasetime']};\n";
1453
		}
1454

    
1455
		// max-lease-time
1456
		if ($dhcpv6ifconf['maxleasetime']) {
1457
			$dhcpdv6conf .= "	max-lease-time {$dhcpv6ifconf['maxleasetime']};\n";
1458
		}
1459

    
1460
		// ntp-servers
1461
		if (is_array($dhcpv6ifconf['ntpserver']) && $dhcpv6ifconf['ntpserver'][0]) {
1462
			$ntpservers = array();
1463
			foreach ($dhcpv6ifconf['ntpserver'] as $ntpserver) {
1464
				if (!is_ipaddrv6($ntpserver)) {
1465
					continue;
1466
				}
1467
				if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1468
				    Net_IPv6::isInNetmask($ntpserver, '::', $pdlen)) {
1469
					$ntpserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ntpserver, $pdlen);
1470
				}
1471
				$ntpservers[] = $ntpserver;
1472
			}
1473
			if (count($ntpservers) > 0) {
1474
				$dhcpdv6conf .= "        option dhcp6.sntp-servers " . join(",", $dhcpv6ifconf['ntpserver']) . ";\n";
1475
			}
1476
		}
1477
		// tftp-server-name
1478
		/* Needs ISC DHCPD support
1479
		 if ($dhcpv6ifconf['tftp'] <> "") {
1480
			$dhcpdv6conf .= "	option tftp-server-name \"{$dhcpv6ifconf['tftp']}\";\n";
1481
		 }
1482
		*/
1483

    
1484
		// Handle option, number rowhelper values
1485
		$dhcpdv6conf .= "\n";
1486
		if ($dhcpv6ifconf['numberoptions']['item']) {
1487
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1488
				$itemv6_value = base64_decode($itemv6['value']);
1489
				$dhcpdv6conf .= "	option custom-{$dhcpv6if}-{$itemv6idx} \"{$itemv6_value}\";\n";
1490
			}
1491
		}
1492

    
1493
		// ldap-server
1494
		if ($dhcpv6ifconf['ldap'] <> "") {
1495
			$ldapserver = $dhcpv6ifconf['ldap'];
1496
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1497
			    Net_IPv6::isInNetmask($ldapserver, '::', $pdlen)) {
1498
				$ldapserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ldapserver, $pdlen);
1499
			}
1500
			$dhcpdv6conf .= "	option ldap-server \"{$ldapserver}\";\n";
1501
		}
1502

    
1503
		// net boot information
1504
		if (isset($dhcpv6ifconf['netboot'])) {
1505
			if (!empty($dhcpv6ifconf['bootfile_url'])) {
1506
				$dhcpdv6conf .= "	option dhcp6.bootfile-url \"{$dhcpv6ifconf['bootfile_url']}\";\n";
1507
			}
1508
		}
1509

    
1510
		$dhcpdv6conf .= "}\n";
1511

    
1512
		/* add static mappings */
1513
		/* Needs to use DUID */
1514
		if (is_array($dhcpv6ifconf['staticmap'])) {
1515
			$i = 0;
1516
			foreach ($dhcpv6ifconf['staticmap'] as $sm) {
1517
				$dhcpdv6conf .= <<<EOD
1518
host s_{$dhcpv6if}_{$i} {
1519
	host-identifier option dhcp6.client-id {$sm['duid']};
1520

    
1521
EOD;
1522
				if ($sm['ipaddrv6']) {
1523
					$ipaddrv6 = $sm['ipaddrv6'];
1524
					if ($ifcfgv6['ipaddrv6'] == 'track6') {
1525
						$ipaddrv6 = merge_ipv6_delegated_prefix($ifcfgipv6, $ipaddrv6, $pdlen);
1526
					}
1527
					$dhcpdv6conf .= "	fixed-address6 {$ipaddrv6};\n";
1528
				}
1529

    
1530
				if ($sm['hostname']) {
1531
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1532
					$dhhostname = str_replace(".", "_", $dhhostname);
1533
					$dhcpdv6conf .= "	option host-name {$dhhostname};\n";
1534
				}
1535
				if ($sm['filename']) {
1536
					$dhcpdv6conf .= "	filename \"{$sm['filename']}\";\n";
1537
				}
1538

    
1539
				if ($sm['rootpath']) {
1540
					$dhcpdv6conf .= "	option root-path \"{$sm['rootpath']}\";\n";
1541
				}
1542

    
1543
				$dhcpdv6conf .= "}\n";
1544
				$i++;
1545
			}
1546
		}
1547

    
1548
		if ($dhcpv6ifconf['ddnsdomain']) {
1549
			$dhcpdv6conf .= dhcpdkey($dhcpv6ifconf);
1550
			$dhcpdv6conf .= dhcpdzones($ddns_zones);
1551
		}
1552

    
1553
		if ($config['dhcpdv6'][$dhcpv6if]['ramode'] <> "unmanaged" && isset($config['interfaces'][$dhcpv6if]['enable'])) {
1554
			if (preg_match("/poes/si", $dhcpv6if)) {
1555
				/* magic here */
1556
				$dhcpdv6ifs = array_merge($dhcpdv6ifs, get_pppoes_child_interfaces($dhcpv6if));
1557
			} else {
1558
				$realif = get_real_interface($dhcpv6if, "inet6");
1559
				if (stristr("$realif", "bridge")) {
1560
					$mac = get_interface_mac($realif);
1561
					$v6address = generate_ipv6_from_mac($mac);
1562
					/* Create link local address for bridges */
1563
					mwexec("/sbin/ifconfig {$realif} inet6 {$v6address}");
1564
				}
1565
				$realif = escapeshellcmd($realif);
1566
				$dhcpdv6ifs[] = $realif;
1567
			}
1568
		}
1569
	}
1570

    
1571
	if ($nsupdate) {
1572
		$dhcpdv6conf .= "ddns-update-style interim;\n";
1573
	} else {
1574
		$dhcpdv6conf .= "ddns-update-style none;\n";
1575
	}
1576

    
1577
	/* write dhcpdv6.conf */
1578
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf", $dhcpdv6conf)) {
1579
		log_error("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1580
		if (platform_booting()) {
1581
			printf("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1582
		}
1583
		unset($dhcpdv6conf);
1584
		return 1;
1585
	}
1586
	unset($dhcpdv6conf);
1587

    
1588
	/* create an empty leases v6 database */
1589
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases")) {
1590
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1591
	}
1592

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

    
1597
	/* fire up dhcpd in a chroot */
1598
	if (count($dhcpdv6ifs) > 0) {
1599
		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 " .
1600
			join(" ", $dhcpdv6ifs));
1601
		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");
1602
	}
1603
	if (platform_booting()) {
1604
		print gettext("done.") . "\n";
1605
	}
1606

    
1607
	return 0;
1608
}
1609

    
1610
function services_igmpproxy_configure() {
1611
	global $config, $g;
1612

    
1613
	/* kill any running igmpproxy */
1614
	killbyname("igmpproxy");
1615

    
1616
	if (!is_array($config['igmpproxy']['igmpentry']) || (count($config['igmpproxy']['igmpentry']) == 0)) {
1617
		return 1;
1618
	}
1619

    
1620
	$iflist = get_configured_interface_list();
1621

    
1622
	$igmpconf = <<<EOD
1623

    
1624
##------------------------------------------------------
1625
## Enable Quickleave mode (Sends Leave instantly)
1626
##------------------------------------------------------
1627
quickleave
1628

    
1629
EOD;
1630

    
1631
	foreach ($config['igmpproxy']['igmpentry'] as $igmpcf) {
1632
		unset($iflist[$igmpcf['ifname']]);
1633
		$realif = get_real_interface($igmpcf['ifname']);
1634
		if (empty($igmpcf['threshold'])) {
1635
			$threshld = 1;
1636
		} else {
1637
			$threshld = $igmpcf['threshold'];
1638
		}
1639
		$igmpconf .= "phyint {$realif} {$igmpcf['type']} ratelimit 0 threshold {$threshld}\n";
1640

    
1641
		if ($igmpcf['address'] <> "") {
1642
			$item = explode(" ", $igmpcf['address']);
1643
			foreach ($item as $iww) {
1644
				$igmpconf .= "altnet {$iww}\n";
1645
			}
1646
		}
1647
		$igmpconf .= "\n";
1648
	}
1649
	foreach ($iflist as $ifn) {
1650
		$realif = get_real_interface($ifn);
1651
		$igmpconf .= "phyint {$realif} disabled\n";
1652
	}
1653
	$igmpconf .= "\n";
1654

    
1655
	$igmpfl = fopen($g['tmp_path'] . "/igmpproxy.conf", "w");
1656
	if (!$igmpfl) {
1657
		log_error(gettext("Could not write Igmpproxy configuration file!"));
1658
		return;
1659
	}
1660
	fwrite($igmpfl, $igmpconf);
1661
	fclose($igmpfl);
1662
	unset($igmpconf);
1663

    
1664
	if (isset($config['syslog']['igmpxverbose'])) {
1665
		mwexec_bg("/usr/local/sbin/igmpproxy -v {$g['tmp_path']}/igmpproxy.conf");
1666
	} else {
1667
		mwexec_bg("/usr/local/sbin/igmpproxy {$g['tmp_path']}/igmpproxy.conf");
1668
	}
1669

    
1670
	log_error(gettext("Started IGMP proxy service."));
1671

    
1672
	return 0;
1673
}
1674

    
1675
function services_dhcrelay_configure() {
1676
	global $config, $g;
1677

    
1678
	if (isset($config['system']['developerspew'])) {
1679
		$mt = microtime();
1680
		echo "services_dhcrelay_configure() being called $mt\n";
1681
	}
1682

    
1683
	/* kill any running dhcrelay */
1684
	killbypid("{$g['varrun_path']}/dhcrelay.pid");
1685

    
1686
	$dhcrelaycfg =& $config['dhcrelay'];
1687

    
1688
	/* DHCPRelay enabled on any interfaces? */
1689
	if (!isset($dhcrelaycfg['enable'])) {
1690
		return 0;
1691
	}
1692

    
1693
	if (platform_booting()) {
1694
		echo gettext("Starting DHCP relay service...");
1695
	} else {
1696
		sleep(1);
1697
	}
1698

    
1699
	$iflist = get_configured_interface_list();
1700

    
1701
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1702
	foreach ($dhcifaces as $dhcrelayif) {
1703
		if (!isset($iflist[$dhcrelayif]) ||
1704
		    link_interface_to_bridge($dhcrelayif)) {
1705
			continue;
1706
		}
1707

    
1708
		if (is_ipaddr(get_interface_ip($dhcrelayif))) {
1709
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1710
		}
1711
	}
1712

    
1713
	/*
1714
	 * In order for the relay to work, it needs to be active
1715
	 * on the interface in which the destination server sits.
1716
	 */
1717
	$srvips = explode(",", $dhcrelaycfg['server']);
1718
	if (!is_array($srvips)) {
1719
		log_error(gettext("No destination IP has been configured!"));
1720
		return;
1721
	}
1722

    
1723
	foreach ($srvips as $srcidx => $srvip) {
1724
		unset($destif);
1725
		foreach ($iflist as $ifname) {
1726
			$subnet = get_interface_ip($ifname);
1727
			if (!is_ipaddr($subnet)) {
1728
				continue;
1729
			}
1730
			$subnet .= "/" . get_interface_subnet($ifname);
1731
			if (ip_in_subnet($srvip, $subnet)) {
1732
				$destif = get_real_interface($ifname);
1733
				break;
1734
			}
1735
		}
1736
		if (!isset($destif)) {
1737
			foreach (get_staticroutes() as $rtent) {
1738
				if (ip_in_subnet($srvip, $rtent['network'])) {
1739
					$a_gateways = return_gateways_array(true);
1740
					$destif = $a_gateways[$rtent['gateway']]['interface'];
1741
					break;
1742
				}
1743
			}
1744
		}
1745

    
1746
		if (!isset($destif)) {
1747
			/* Create a array from the existing route table */
1748
			exec("/usr/bin/netstat -rnWf inet", $route_str);
1749
			array_shift($route_str);
1750
			array_shift($route_str);
1751
			array_shift($route_str);
1752
			array_shift($route_str);
1753
			$route_arr = array();
1754
			foreach ($route_str as $routeline) {
1755
				$items = preg_split("/[ ]+/i", $routeline);
1756
				if (is_subnetv4($items[0])) {
1757
					$subnet = $items[0];
1758
				} elseif (is_ipaddrv4($items[0])) {
1759
					$subnet = "{$items[0]}/32";
1760
				} else {
1761
					// Not a subnet or IP address, skip to the next line.
1762
					continue;
1763
				}
1764
				if (ip_in_subnet($srvip, $subnet)) {
1765
					$destif = trim($items[6]);
1766
					break;
1767
				}
1768
			}
1769
		}
1770

    
1771
		if (!isset($destif)) {
1772
			if (is_array($config['gateways']['gateway_item'])) {
1773
				foreach ($config['gateways']['gateway_item'] as $gateway) {
1774
					if (isset($gateway['defaultgw'])) {
1775
						$destif = get_real_interface($gateway['interface']);
1776
						break;
1777
					}
1778
				}
1779
			} else {
1780
				$destif = get_real_interface("wan");
1781
			}
1782
		}
1783

    
1784
		if (!empty($destif)) {
1785
			$dhcrelayifs[] = $destif;
1786
		}
1787
	}
1788
	$dhcrelayifs = array_unique($dhcrelayifs);
1789

    
1790
	/* fire up dhcrelay */
1791
	if (empty($dhcrelayifs)) {
1792
		log_error(gettext("No suitable interface found for running dhcrelay!"));
1793
		return; /* XXX */
1794
	}
1795

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

    
1798
	if (isset($dhcrelaycfg['agentoption'])) {
1799
		$cmd .= " -a -m replace";
1800
	}
1801

    
1802
	$cmd .= " " . implode(" ", $srvips);
1803
	mwexec($cmd);
1804
	unset($cmd);
1805

    
1806
	return 0;
1807
}
1808

    
1809
function services_dhcrelay6_configure() {
1810
	global $config, $g;
1811

    
1812
	if (isset($config['system']['developerspew'])) {
1813
		$mt = microtime();
1814
		echo "services_dhcrelay6_configure() being called $mt\n";
1815
	}
1816

    
1817
	/* kill any running dhcrelay */
1818
	killbypid("{$g['varrun_path']}/dhcrelay6.pid");
1819

    
1820
	$dhcrelaycfg =& $config['dhcrelay6'];
1821

    
1822
	/* DHCPv6 Relay enabled on any interfaces? */
1823
	if (!isset($dhcrelaycfg['enable'])) {
1824
		return 0;
1825
	}
1826

    
1827
	if (platform_booting()) {
1828
		echo gettext("Starting DHCPv6 relay service...");
1829
	} else {
1830
		sleep(1);
1831
	}
1832

    
1833
	$iflist = get_configured_interface_list();
1834

    
1835
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1836
	foreach ($dhcifaces as $dhcrelayif) {
1837
		if (!isset($iflist[$dhcrelayif]) ||
1838
		    link_interface_to_bridge($dhcrelayif)) {
1839
			continue;
1840
		}
1841

    
1842
		if (is_ipaddrv6(get_interface_ipv6($dhcrelayif))) {
1843
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1844
		}
1845
	}
1846
	$dhcrelayifs = array_unique($dhcrelayifs);
1847

    
1848
	/*
1849
	 * In order for the relay to work, it needs to be active
1850
	 * on the interface in which the destination server sits.
1851
	 */
1852
	$srvips = explode(",", $dhcrelaycfg['server']);
1853
	$srvifaces = array();
1854
	foreach ($srvips as $srcidx => $srvip) {
1855
		unset($destif);
1856
		foreach ($iflist as $ifname) {
1857
			$subnet = get_interface_ipv6($ifname);
1858
			if (!is_ipaddrv6($subnet)) {
1859
				continue;
1860
			}
1861
			$subnet .= "/" . get_interface_subnetv6($ifname);
1862
			if (ip_in_subnet($srvip, $subnet)) {
1863
				$destif = get_real_interface($ifname);
1864
				break;
1865
			}
1866
		}
1867
		if (!isset($destif)) {
1868
			if (is_array($config['staticroutes']['route'])) {
1869
				foreach ($config['staticroutes']['route'] as $rtent) {
1870
					if (ip_in_subnet($srvip, $rtent['network'])) {
1871
						$a_gateways = return_gateways_array(true);
1872
						$destif = $a_gateways[$rtent['gateway']]['interface'];
1873
						break;
1874
					}
1875
				}
1876
			}
1877
		}
1878

    
1879
		if (!isset($destif)) {
1880
			/* Create a array from the existing route table */
1881
			exec("/usr/bin/netstat -rnWf inet6", $route_str);
1882
			array_shift($route_str);
1883
			array_shift($route_str);
1884
			array_shift($route_str);
1885
			array_shift($route_str);
1886
			$route_arr = array();
1887
			foreach ($route_str as $routeline) {
1888
				$items = preg_split("/[ ]+/i", $routeline);
1889
				if (ip_in_subnet($srvip, $items[0])) {
1890
					$destif = trim($items[6]);
1891
					break;
1892
				}
1893
			}
1894
		}
1895

    
1896
		if (!isset($destif)) {
1897
			if (is_array($config['gateways']['gateway_item'])) {
1898
				foreach ($config['gateways']['gateway_item'] as $gateway) {
1899
					if (isset($gateway['defaultgw'])) {
1900
						$destif = get_real_interface($gateway['interface']);
1901
						break;
1902
					}
1903
				}
1904
			} else {
1905
				$destif = get_real_interface("wan");
1906
			}
1907
		}
1908

    
1909
		if (!empty($destif)) {
1910
			$srvifaces[] = "{$srvip}%{$destif}";
1911
		}
1912
	}
1913

    
1914
	/* fire up dhcrelay */
1915
	if (empty($dhcrelayifs) || empty($srvifaces)) {
1916
		log_error(gettext("No suitable interface found for running dhcrelay -6!"));
1917
		return; /* XXX */
1918
	}
1919

    
1920
	$cmd = "/usr/local/sbin/dhcrelay -6 -pf \"{$g['varrun_path']}/dhcrelay6.pid\"";
1921
	foreach ($dhcrelayifs as $dhcrelayif) {
1922
		$cmd .= " -l {$dhcrelayif}";
1923
	}
1924
	foreach ($srvifaces as $srviface) {
1925
		$cmd .= " -u \"{$srviface}\"";
1926
	}
1927
	mwexec($cmd);
1928
	unset($cmd);
1929

    
1930
	return 0;
1931
}
1932

    
1933
function services_dyndns_configure_client($conf) {
1934

    
1935
	if (!isset($conf['enable'])) {
1936
		return;
1937
	}
1938

    
1939
	/* load up the dyndns.class */
1940
	require_once("dyndns.class");
1941

    
1942
	$dns = new updatedns($dnsService = $conf['type'],
1943
		$dnsHost = $conf['host'],
1944
		$dnsDomain = $conf['domainname'],
1945
		$dnsUser = $conf['username'],
1946
		$dnsPass = $conf['password'],
1947
		$dnsWildcard = $conf['wildcard'],
1948
		$dnsMX = $conf['mx'],
1949
		$dnsIf = "{$conf['interface']}",
1950
		$dnsBackMX = NULL,
1951
		$dnsServer = NULL,
1952
		$dnsPort = NULL,
1953
		$dnsUpdateURL = "{$conf['updateurl']}",
1954
		$forceUpdate = $conf['force'],
1955
		$dnsZoneID = $conf['zoneid'],
1956
		$dnsTTL = $conf['ttl'],
1957
		$dnsResultMatch = "{$conf['resultmatch']}",
1958
		$dnsRequestIf = "{$conf['requestif']}",
1959
		$dnsID = "{$conf['id']}",
1960
		$dnsVerboseLog = $conf['verboselog'],
1961
		$curlIpresolveV4 = $conf['curl_ipresolve_v4'],
1962
		$curlSslVerifypeer = $conf['curl_ssl_verifypeer']);
1963
}
1964

    
1965
function services_dyndns_configure($int = "") {
1966
	global $config, $g;
1967
	if (isset($config['system']['developerspew'])) {
1968
		$mt = microtime();
1969
		echo "services_dyndns_configure() being called $mt\n";
1970
	}
1971

    
1972
	$dyndnscfg = $config['dyndnses']['dyndns'];
1973
	$gwgroups = return_gateway_groups_array();
1974
	if (is_array($dyndnscfg)) {
1975
		if (platform_booting()) {
1976
			echo gettext("Starting DynDNS clients...");
1977
		}
1978

    
1979
		foreach ($dyndnscfg as $dyndns) {
1980
			if ((empty($int)) || ($int == $dyndns['interface']) || (is_array($gwgroups[$dyndns['interface']]))) {
1981
				$dyndns['verboselog'] = isset($dyndns['verboselog']);
1982
				$dyndns['curl_ipresolve_v4'] = isset($dyndns['curl_ipresolve_v4']);
1983
				$dyndns['curl_ssl_verifypeer'] = isset($dyndns['curl_ssl_verifypeer']);
1984
				services_dyndns_configure_client($dyndns);
1985
				sleep(1);
1986
			}
1987
		}
1988

    
1989
		if (platform_booting()) {
1990
			echo gettext("done.") . "\n";
1991
		}
1992
	}
1993

    
1994
	return 0;
1995
}
1996

    
1997
function dyndnsCheckIP($int) {
1998
	global $config;
1999
	$ip_address = get_interface_ip($int);
2000
	if (is_private_ip($ip_address)) {
2001
		$gateways_status = return_gateways_status(true);
2002
		// If the gateway for this interface is down, then the external check cannot work.
2003
		// Avoid the long wait for the external check to timeout.
2004
		if (stristr($gateways_status[$config['interfaces'][$int]['gateway']]['status'], "down")) {
2005
			return "down";
2006
		}
2007
		$hosttocheck = "http://checkip.dyndns.org";
2008
		$ip_ch = curl_init($hosttocheck);
2009
		curl_setopt($ip_ch, CURLOPT_RETURNTRANSFER, 1);
2010
		curl_setopt($ip_ch, CURLOPT_SSL_VERIFYPEER, FALSE);
2011
		curl_setopt($ip_ch, CURLOPT_INTERFACE, 'host!' . $ip_address);
2012
		curl_setopt($ip_ch, CURLOPT_CONNECTTIMEOUT, '30');
2013
		curl_setopt($ip_ch, CURLOPT_TIMEOUT, 120);
2014
		curl_setopt($ip_ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
2015
		$ip_result_page = curl_exec($ip_ch);
2016
		curl_close($ip_ch);
2017
		$ip_result_decoded = urldecode($ip_result_page);
2018
		preg_match('=Current IP Address: (.*)</body>=siU', $ip_result_decoded, $matches);
2019
		$ip_address = trim($matches[1]);
2020
	}
2021
	return $ip_address;
2022
}
2023

    
2024
function services_dnsmasq_configure($restart_dhcp = true) {
2025
	global $config, $g;
2026
	$return = 0;
2027

    
2028
	// hard coded args: will be removed to avoid duplication if specified in custom_options
2029
	$standard_args = array(
2030
		"dns-forward-max" => "--dns-forward-max=5000",
2031
		"cache-size" => "--cache-size=10000",
2032
		"local-ttl" => "--local-ttl=1"
2033
	);
2034

    
2035

    
2036
	if (isset($config['system']['developerspew'])) {
2037
		$mt = microtime();
2038
		echo "services_dnsmasq_configure() being called $mt\n";
2039
	}
2040

    
2041
	/* kill any running dnsmasq */
2042
	if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) {
2043
		sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
2044
	}
2045

    
2046
	if (isset($config['dnsmasq']['enable'])) {
2047

    
2048
		if (platform_booting()) {
2049
			echo gettext("Starting DNS forwarder...");
2050
		} else {
2051
			sleep(1);
2052
		}
2053

    
2054
		/* generate hosts file */
2055
		if (system_hosts_generate() != 0) {
2056
			$return = 1;
2057
		}
2058

    
2059
		$args = "";
2060

    
2061
		if (isset($config['dnsmasq']['regdhcp'])) {
2062
			$args .= " --dhcp-hostsfile={$g['varetc_path']}/hosts ";
2063
		}
2064

    
2065
		/* Setup listen port, if non-default */
2066
		if (is_port($config['dnsmasq']['port'])) {
2067
			$args .= " --port={$config['dnsmasq']['port']} ";
2068
		}
2069

    
2070
		$listen_addresses = "";
2071
		if (isset($config['dnsmasq']['interface'])) {
2072
			$interfaces = explode(",", $config['dnsmasq']['interface']);
2073
			foreach ($interfaces as $interface) {
2074
				$if = get_real_interface($interface);
2075
				if (does_interface_exist($if)) {
2076
					$laddr = get_interface_ip($interface);
2077
					if (is_ipaddrv4($laddr)) {
2078
						$listen_addresses .= " --listen-address={$laddr} ";
2079
					}
2080
					$laddr6 = get_interface_ipv6($interface);
2081
					if (is_ipaddrv6($laddr6) && !isset($config['dnsmasq']['strictbind'])) {
2082
						/*
2083
						 * XXX: Since dnsmasq does not support link-local address
2084
						 * with scope specified. These checks are being done.
2085
						 */
2086
						if (is_linklocal($laddr6) && strstr($laddr6, "%")) {
2087
							$tmpaddrll6 = explode("%", $laddr6);
2088
							$listen_addresses .= " --listen-address={$tmpaddrll6[0]} ";
2089
						} else {
2090
							$listen_addresses .= " --listen-address={$laddr6} ";
2091
						}
2092
					}
2093
				}
2094
			}
2095
			if (!empty($listen_addresses)) {
2096
				$args .= " {$listen_addresses} ";
2097
				if (isset($config['dnsmasq']['strictbind'])) {
2098
					$args .= " --bind-interfaces ";
2099
				}
2100
			}
2101
		}
2102

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

    
2110
			// Build an array of domain overrides to help in checking for matches.
2111
			$override_a = array();
2112
			if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2113
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2114
					$override_a[$override['domain']] = "y";
2115
				}
2116
			}
2117

    
2118
			// Build an array of the private reverse lookup domain names
2119
			$reverse_domain_a = array("10.in-addr.arpa", "168.192.in-addr.arpa");
2120
			// Unfortunately the 172.16.0.0/12 range does not map nicely to the in-addr.arpa scheme.
2121
			for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) {
2122
				$reverse_domain_a[] = "$subnet_num.172.in-addr.arpa";
2123
			}
2124

    
2125
			// Set the --server parameter to nowhere for each reverse domain name that was not specifically specified in a domain override.
2126
			foreach ($reverse_domain_a as $reverse_domain) {
2127
				if (!isset($override_a[$reverse_domain])) {
2128
					$args .= " --server=/$reverse_domain/ ";
2129
				}
2130
			}
2131
			unset($override_a);
2132
			unset($reverse_domain_a);
2133
		}
2134

    
2135
		/* Setup forwarded domains */
2136
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2137
			foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2138
				if ($override['ip'] == "!") {
2139
					$override[ip] = "";
2140
				}
2141
				$args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
2142
			}
2143
		}
2144

    
2145
		/* Allow DNS Rebind for forwarded domains */
2146
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2147
			if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2148
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2149
					$args .= ' --rebind-domain-ok=/' . $override['domain'] . '/ ';
2150
				}
2151
			}
2152
		}
2153

    
2154
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2155
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2156
		}
2157

    
2158
		if (isset($config['dnsmasq']['strict_order'])) {
2159
			$args .= " --strict-order ";
2160
		}
2161

    
2162
		if (isset($config['dnsmasq']['domain_needed'])) {
2163
			$args .= " --domain-needed ";
2164
		}
2165

    
2166
		if ($config['dnsmasq']['custom_options']) {
2167
			foreach (preg_split('/\s+/', $config['dnsmasq']['custom_options']) as $c) {
2168
				$args .= " " . escapeshellarg("--{$c}");
2169
				$p = explode('=', $c);
2170
				if (array_key_exists($p[0], $standard_args)) {
2171
					unset($standard_args[$p[0]]);
2172
				}
2173
			}
2174
		}
2175
		$args .= ' ' . implode(' ', array_values($standard_args));
2176

    
2177
		/* run dnsmasq */
2178
		$cmd = "/usr/local/sbin/dnsmasq --all-servers {$dns_rebind} {$args}";
2179
		//log_error("dnsmasq command: {$cmd}");
2180
		mwexec_bg($cmd);
2181
		unset($args);
2182

    
2183
		system_dhcpleases_configure();
2184

    
2185
		if (platform_booting()) {
2186
			echo gettext("done.") . "\n";
2187
		}
2188
	}
2189

    
2190
	if (!platform_booting() && $restart_dhcp) {
2191
		if (services_dhcpd_configure() != 0) {
2192
			$return = 1;
2193
		}
2194
	}
2195

    
2196
	return $return;
2197
}
2198

    
2199
function services_unbound_configure($restart_dhcp = true) {
2200
	global $config, $g;
2201
	$return = 0;
2202

    
2203
	if (isset($config['system']['developerspew'])) {
2204
		$mt = microtime();
2205
		echo "services_unbound_configure() being called $mt\n";
2206
	}
2207

    
2208
	// kill any running Unbound instance
2209
	if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2210
		sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
2211
	}
2212

    
2213
	if (isset($config['unbound']['enable'])) {
2214
		if (platform_booting()) {
2215
			echo gettext("Starting DNS Resolver...");
2216
		} else {
2217
			sleep(1);
2218
		}
2219

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

    
2225
		require_once('/etc/inc/unbound.inc');
2226
		sync_unbound_service();
2227
		if (platform_booting()) {
2228
			echo gettext("done.") . "\n";
2229
		}
2230

    
2231
		system_dhcpleases_configure();
2232
	}
2233

    
2234
	if (!platform_booting() && $restart_dhcp) {
2235
		if (services_dhcpd_configure() != 0) {
2236
			$return = 1;
2237
		}
2238
	}
2239

    
2240
	return $return;
2241
}
2242

    
2243
function services_snmpd_configure() {
2244
	global $config, $g;
2245
	if (isset($config['system']['developerspew'])) {
2246
		$mt = microtime();
2247
		echo "services_snmpd_configure() being called $mt\n";
2248
	}
2249

    
2250
	/* kill any running snmpd */
2251
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
2252
	sleep(2);
2253
	if (is_process_running("bsnmpd")) {
2254
		mwexec("/usr/bin/killall bsnmpd", true);
2255
	}
2256

    
2257
	if (isset($config['snmpd']['enable'])) {
2258

    
2259
		if (platform_booting()) {
2260
			echo gettext("Starting SNMP daemon... ");
2261
		}
2262

    
2263
		/* generate snmpd.conf */
2264
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
2265
		if (!$fd) {
2266
			printf(gettext("Error: cannot open snmpd.conf in services_snmpd_configure().%s"), "\n");
2267
			return 1;
2268
		}
2269

    
2270

    
2271
		$snmpdconf = <<<EOD
2272
location := "{$config['snmpd']['syslocation']}"
2273
contact := "{$config['snmpd']['syscontact']}"
2274
read := "{$config['snmpd']['rocommunity']}"
2275

    
2276
EOD;
2277

    
2278
/* No docs on what write strings do there so disable for now.
2279
		if (isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])) {
2280
			$snmpdconf .= <<<EOD
2281
# write string
2282
write := "{$config['snmpd']['rwcommunity']}"
2283

    
2284
EOD;
2285
		}
2286
*/
2287

    
2288

    
2289
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2290
			$snmpdconf .= <<<EOD
2291
# SNMP Trap support.
2292
traphost := {$config['snmpd']['trapserver']}
2293
trapport := {$config['snmpd']['trapserverport']}
2294
trap := "{$config['snmpd']['trapstring']}"
2295

    
2296

    
2297
EOD;
2298
		}
2299

    
2300
		$platform = trim(file_get_contents('/etc/platform'));
2301
		if (($platform == "pfSense") && ($g['product_name'] != "pfSense")) {
2302
			$platform = $g['product_name'];
2303
		}
2304
		$sysDescr = "{$g['product_name']} " . php_uname("n") .
2305
			" {$g['product_version']} {$platform} " . php_uname("s") .
2306
			" " . php_uname("r") . " " . php_uname("m");
2307

    
2308
		$snmpdconf .= <<<EOD
2309
system := 1     # pfSense
2310
%snmpd
2311
sysDescr			= "{$sysDescr}"
2312
begemotSnmpdDebugDumpPdus       = 2
2313
begemotSnmpdDebugSyslogPri      = 7
2314
begemotSnmpdCommunityString.0.1 = $(read)
2315

    
2316
EOD;
2317

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

    
2323
EOD;
2324
		}
2325
*/
2326

    
2327

    
2328
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2329
			$snmpdconf .= <<<EOD
2330
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
2331
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
2332
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
2333

    
2334
EOD;
2335
		}
2336

    
2337

    
2338
		$snmpdconf .= <<<EOD
2339
begemotSnmpdCommunityDisable    = 1
2340

    
2341
EOD;
2342

    
2343
		$bind_to_ip = "0.0.0.0";
2344
		if (isset($config['snmpd']['bindip'])) {
2345
			if (is_ipaddr($config['snmpd']['bindip'])) {
2346
				$bind_to_ip = $config['snmpd']['bindip'];
2347
			} else {
2348
				$if = get_real_interface($config['snmpd']['bindip']);
2349
				if (does_interface_exist($if)) {
2350
					$bind_to_ip = get_interface_ip($config['snmpd']['bindip']);
2351
				}
2352
			}
2353
		}
2354

    
2355
		if (is_port($config['snmpd']['pollport'])) {
2356
			$snmpdconf .= <<<EOD
2357
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
2358

    
2359
EOD;
2360

    
2361
		}
2362

    
2363
		$snmpdconf .= <<<EOD
2364
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
2365
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
2366

    
2367
# These are bsnmp macros not php vars.
2368
sysContact      = $(contact)
2369
sysLocation     = $(location)
2370
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
2371

    
2372
snmpEnableAuthenTraps = 2
2373

    
2374
EOD;
2375

    
2376
		if (is_array($config['snmpd']['modules'])) {
2377
			if (isset($config['snmpd']['modules']['mibii'])) {
2378
			$snmpdconf .= <<<EOD
2379
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
2380

    
2381
EOD;
2382
			}
2383

    
2384
			if (isset($config['snmpd']['modules']['netgraph'])) {
2385
				$snmpdconf .= <<<EOD
2386
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
2387
%netgraph
2388
begemotNgControlNodeName = "snmpd"
2389

    
2390
EOD;
2391
			}
2392

    
2393
			if (isset($config['snmpd']['modules']['pf'])) {
2394
				$snmpdconf .= <<<EOD
2395
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
2396

    
2397
EOD;
2398
			}
2399

    
2400
			if (isset($config['snmpd']['modules']['hostres'])) {
2401
				$snmpdconf .= <<<EOD
2402
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
2403

    
2404
EOD;
2405
			}
2406

    
2407
			if (isset($config['snmpd']['modules']['bridge'])) {
2408
				$snmpdconf .= <<<EOD
2409
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
2410
# config must end with blank line
2411

    
2412
EOD;
2413
			}
2414
			if (isset($config['snmpd']['modules']['ucd'])) {
2415
				$snmpdconf .= <<<EOD
2416
begemotSnmpdModulePath."ucd"     = "/usr/local/lib/snmp_ucd.so"
2417

    
2418
EOD;
2419
			}
2420
			if (isset($config['snmpd']['modules']['regex'])) {
2421
				$snmpdconf .= <<<EOD
2422
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"
2423

    
2424
EOD;
2425
			}
2426
		}
2427

    
2428
		fwrite($fd, $snmpdconf);
2429
		fclose($fd);
2430
		unset($snmpdconf);
2431

    
2432
		/* run bsnmpd */
2433
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
2434
			" -p {$g['varrun_path']}/snmpd.pid");
2435

    
2436
		if (platform_booting()) {
2437
			echo gettext("done.") . "\n";
2438
		}
2439
	}
2440

    
2441
	return 0;
2442
}
2443

    
2444
function services_dnsupdate_process($int = "", $updatehost = "", $forced = false) {
2445
	global $config, $g;
2446
	if (isset($config['system']['developerspew'])) {
2447
		$mt = microtime();
2448
		echo "services_dnsupdate_process() being called $mt\n";
2449
	}
2450

    
2451
	/* Dynamic DNS updating active? */
2452
	if (is_array($config['dnsupdates']['dnsupdate'])) {
2453
		$notify_text = "";
2454
		$gwgroups = return_gateway_groups_array();
2455
		foreach ($config['dnsupdates']['dnsupdate'] as $i => $dnsupdate) {
2456
			if (!isset($dnsupdate['enable'])) {
2457
				continue;
2458
			}
2459
			if (!empty($int) && ($int != $dnsupdate['interface']) && (!is_array($gwgroups[$dnsupdate['interface']]))) {
2460
				continue;
2461
			}
2462
			if (!empty($updatehost) && ($updatehost != $dnsupdate['host'])) {
2463
				continue;
2464
			}
2465

    
2466
			/* determine interface name */
2467
			$if = get_failover_interface($dnsupdate['interface']);
2468

    
2469
			if (isset($dnsupdate['usepublicip'])) {
2470
				$wanip = dyndnsCheckIP($if);
2471
			} else {
2472
				$wanip = get_interface_ip($if);
2473
			}
2474

    
2475
			$wanipv6 = get_interface_ipv6($if);
2476
			$cacheFile = "{$g['conf_path']}/dyndns_{$dnsupdate['interface']}_rfc2136_" . escapeshellarg($dnsupdate['host']) . "_{$dnsupdate['server']}.cache";
2477
			$currentTime = time();
2478

    
2479
			if ($wanip || $wanipv6) {
2480
				$keyname = $dnsupdate['keyname'];
2481
				/* trailing dot */
2482
				if (substr($keyname, -1) != ".") {
2483
					$keyname .= ".";
2484
				}
2485

    
2486
				$hostname = $dnsupdate['host'];
2487
				/* trailing dot */
2488
				if (substr($hostname, -1) != ".") {
2489
					$hostname .= ".";
2490
				}
2491

    
2492
				/* write private key file
2493
				   this is dumb - public and private keys are the same for HMAC-MD5,
2494
				   but nsupdate insists on having both */
2495
				$fd = fopen("{$g['varetc_path']}/K{$i}{$keyname}+157+00000.private", "w");
2496
				$privkey = <<<EOD
2497
Private-key-format: v1.2
2498
Algorithm: 157 (HMAC)
2499
Key: {$dnsupdate['keydata']}
2500

    
2501
EOD;
2502
				fwrite($fd, $privkey);
2503
				fclose($fd);
2504

    
2505
				/* write public key file */
2506
				if ($dnsupdate['keytype'] == "zone") {
2507
					$flags = 257;
2508
					$proto = 3;
2509
				} else if ($dnsupdate['keytype'] == "host") {
2510
					$flags = 513;
2511
					$proto = 3;
2512
				} else if ($dnsupdate['keytype'] == "user") {
2513
					$flags = 0;
2514
					$proto = 2;
2515
				}
2516

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

    
2521
				/* generate update instructions */
2522
				$upinst = "";
2523
				if (!empty($dnsupdate['server'])) {
2524
					$upinst .= "server {$dnsupdate['server']}\n";
2525
				}
2526

    
2527
				if (file_exists($cacheFile)) {
2528
					list($cachedipv4, $cacheTimev4) = explode("|", file_get_contents($cacheFile));
2529
				}
2530
				if (file_exists("{$cacheFile}.ipv6")) {
2531
					list($cachedipv6, $cacheTimev6) = explode("|", file_get_contents("{$cacheFile}.ipv6"));
2532
				}
2533

    
2534
				// 25 Days
2535
				$maxCacheAgeSecs = 25 * 24 * 60 * 60;
2536
				$need_update = false;
2537

    
2538
				conf_mount_rw();
2539
				/* Update IPv4 if we have it. */
2540
				if (is_ipaddrv4($wanip) && $dnsupdate['recordtype'] != "AAAA") {
2541
					if (($wanip != $cachedipv4) || (($currentTime - $cacheTimev4) > $maxCacheAgeSecs) || $forced) {
2542
						$upinst .= "update delete {$dnsupdate['host']}. A\n";
2543
						$upinst .= "update add {$dnsupdate['host']}. {$dnsupdate['ttl']} A {$wanip}\n";
2544
						$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";
2545
						@file_put_contents($cacheFile, "{$wanip}|{$currentTime}");
2546
						log_error(sprintf(gettext('phpDynDNS: updating cache file %1$s: %2$s'), $cacheFile, $wanip));
2547
						$need_update = true;
2548
					} else {
2549
						log_error(sprintf(gettext("phpDynDNS: Not updating %s A record because the IP address has not changed."), $dnsupdate['host']));
2550
					}
2551
				} else {
2552
					@unlink($cacheFile);
2553
				}
2554

    
2555
				/* Update IPv6 if we have it. */
2556
				if (is_ipaddrv6($wanipv6) && $dnsupdate['recordtype'] != "A") {
2557
					if (($wanipv6 != $cachedipv6) || (($currentTime - $cacheTimev6) > $maxCacheAgeSecs) || $forced) {
2558
						$upinst .= "update delete {$dnsupdate['host']}. AAAA\n";
2559
						$upinst .= "update add {$dnsupdate['host']}. {$dnsupdate['ttl']} AAAA {$wanipv6}\n";
2560
						$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";
2561
						@file_put_contents("{$cacheFile}.ipv6", "{$wanipv6}|{$currentTime}");
2562
						log_error(sprintf(gettext('phpDynDNS: updating cache file %1$s.ipv6: %2$s'), $cacheFile, $wanipv6));
2563
						$need_update = true;
2564
					} else {
2565
						log_error(sprintf(gettext("phpDynDNS: Not updating %s AAAA record because the IPv6 address has not changed."), $dnsupdate['host']));
2566
					}
2567
				} else {
2568
					@unlink("{$cacheFile}.ipv6");
2569
				}
2570
				conf_mount_ro();
2571

    
2572
				$upinst .= "\n";	/* mind that trailing newline! */
2573

    
2574
				if ($need_update) {
2575
					@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}", $upinst);
2576
					unset($upinst);
2577
					/* invoke nsupdate */
2578
					$cmd = "/usr/local/bin/nsupdate -k {$g['varetc_path']}/K{$i}{$keyname}+157+00000.key";
2579
					if (isset($dnsupdate['usetcp'])) {
2580
						$cmd .= " -v";
2581
					}
2582
					$cmd .= " {$g['varetc_path']}/nsupdatecmds{$i}";
2583
					mwexec_bg($cmd);
2584
					unset($cmd);
2585
				}
2586
			}
2587
		}
2588
		if (!empty($notify_text)) {
2589
			notify_all_remote($notify_text);
2590
		}
2591
	}
2592

    
2593
	return 0;
2594
}
2595

    
2596
/* configure cron service */
2597
function configure_cron() {
2598
	global $g, $config;
2599

    
2600
	conf_mount_rw();
2601
	/* preserve existing crontab entries */
2602
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2603

    
2604
	for ($i = 0; $i < count($crontab_contents); $i++) {
2605
		$cron_item =& $crontab_contents[$i];
2606
		if (strpos($cron_item, "# pfSense specific crontab entries") !== false) {
2607
			array_splice($crontab_contents, $i - 1);
2608
			break;
2609
		}
2610
	}
2611
	$crontab_contents = implode("\n", $crontab_contents) . "\n";
2612

    
2613

    
2614
	if (is_array($config['cron']['item'])) {
2615
		$crontab_contents .= "#\n";
2616
		$crontab_contents .= "# pfSense specific crontab entries\n";
2617
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
2618
		$crontab_contents .= "#\n";
2619

    
2620
		if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) {
2621
			$http_proxy = $config['system']['proxyurl'];
2622
			if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) {
2623
				$http_proxy .= ':' . $config['system']['proxyport'];
2624
			}
2625
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
2626
		}
2627

    
2628
		foreach ($config['cron']['item'] as $item) {
2629
			$crontab_contents .= "\n{$item['minute']}\t";
2630
			$crontab_contents .= "{$item['hour']}\t";
2631
			$crontab_contents .= "{$item['mday']}\t";
2632
			$crontab_contents .= "{$item['month']}\t";
2633
			$crontab_contents .= "{$item['wday']}\t";
2634
			$crontab_contents .= "{$item['who']}\t";
2635
			$crontab_contents .= "{$item['command']}";
2636
		}
2637

    
2638
		$crontab_contents .= "\n#\n";
2639
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
2640
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
2641
		$crontab_contents .= "#\n\n";
2642
	}
2643

    
2644
	/* please maintain the newline at the end of file */
2645
	file_put_contents("/etc/crontab", $crontab_contents);
2646
	unset($crontab_contents);
2647

    
2648
	/* make sure that cron is running and start it if it got killed somehow */
2649
	if (!is_process_running("cron")) {
2650
		exec("cd /tmp && /usr/sbin/cron -s 2>/dev/null");
2651
	} else {
2652
	/* do a HUP kill to force sync changes */
2653
		sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP");
2654
	}
2655

    
2656
	conf_mount_ro();
2657
}
2658

    
2659
function upnp_action ($action) {
2660
	global $g, $config;
2661
	switch ($action) {
2662
		case "start":
2663
			if (file_exists('/var/etc/miniupnpd.conf')) {
2664
				@unlink("{$g['varrun_path']}/miniupnpd.pid");
2665
				mwexec_bg("/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf -P {$g['varrun_path']}/miniupnpd.pid");
2666
			}
2667
			break;
2668
		case "stop":
2669
			killbypid("{$g['varrun_path']}/miniupnpd.pid");
2670
			while ((int)exec("/bin/pgrep -a miniupnpd | wc -l") > 0) {
2671
				mwexec('/usr/bin/killall miniupnpd 2>/dev/null', true);
2672
			}
2673
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
2674
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
2675
			break;
2676
		case "restart":
2677
			upnp_action('stop');
2678
			upnp_action('start');
2679
			break;
2680
	}
2681
}
2682

    
2683
function upnp_start() {
2684
	global $config;
2685

    
2686
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
2687
		return;
2688
	}
2689

    
2690
	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
2691
		echo gettext("Starting UPnP service... ");
2692
		require_once('/usr/local/pkg/miniupnpd.inc');
2693
		sync_package_miniupnpd();
2694
		echo "done.\n";
2695
	}
2696
}
2697

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

    
2701
	$is_installed = false;
2702
	$cron_changed = true;
2703

    
2704
	if (!is_array($config['cron'])) {
2705
		$config['cron'] = array();
2706
	}
2707
	if (!is_array($config['cron']['item'])) {
2708
		$config['cron']['item'] = array();
2709
	}
2710

    
2711
	$x = 0;
2712
	foreach ($config['cron']['item'] as $item) {
2713
		if (strstr($item['command'], $command)) {
2714
			$is_installed = true;
2715
			break;
2716
		}
2717
		$x++;
2718
	}
2719

    
2720
	if ($active) {
2721
		$cron_item = array();
2722
		$cron_item['minute'] = $minute;
2723
		$cron_item['hour'] = $hour;
2724
		$cron_item['mday'] = $monthday;
2725
		$cron_item['month'] = $month;
2726
		$cron_item['wday'] = $weekday;
2727
		$cron_item['who'] = $who;
2728
		$cron_item['command'] = $command;
2729
		if (!$is_installed) {
2730
			$config['cron']['item'][] = $cron_item;
2731
			write_config(sprintf(gettext("Installed cron job for %s"), $command));
2732
		} else {
2733
			if ($config['cron']['item'][$x] == $cron_item) {
2734
				$cron_changed = false;
2735
				log_error(sprintf(gettext("Checked cron job for %s, no change needed"), $command));
2736
			} else {
2737
				$config['cron']['item'][$x] = $cron_item;
2738
				write_config(sprintf(gettext("Updated cron job for %s"), $command));
2739
			}
2740
		}
2741
	} else {
2742
		if ($is_installed == true) {
2743
			unset($config['cron']['item'][$x]);
2744
			write_config(sprintf(gettext("Removed cron job for %s"), $command));
2745
		}
2746
	}
2747

    
2748
	if ($cron_changed) {
2749
		configure_cron();
2750
	}
2751
}
2752

    
2753
?>
(49-49/65)