Project

General

Profile

Download (98.6 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * services.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2004-2013 BSD Perimeter
7
 * Copyright (c) 2013-2016 Electric Sheep Fencing
8
 * Copyright (c) 2014-2020 Rubicon Communications, LLC (Netgate)
9
 * All rights reserved.
10
 *
11
 * originally part of m0n0wall (http://m0n0.ch/wall)
12
 * Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>.
13
 * All rights reserved.
14
 *
15
 * Licensed under the Apache License, Version 2.0 (the "License");
16
 * you may not use this file except in compliance with the License.
17
 * You may obtain a copy of the License at
18
 *
19
 * http://www.apache.org/licenses/LICENSE-2.0
20
 *
21
 * Unless required by applicable law or agreed to in writing, software
22
 * distributed under the License is distributed on an "AS IS" BASIS,
23
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24
 * See the License for the specific language governing permissions and
25
 * limitations under the License.
26
 */
27

    
28

    
29
define('DYNDNS_PROVIDER_VALUES', 'all-inkl azure azurev6 citynetwork cloudflare cloudflare-v6 cloudns custom custom-v6 digitalocean digitalocean-v6 dnsexit dnsimple dnsmadeeasy dnsomatic dreamhost dreamhost-v6 duiadns duiadns-v6 dyndns dyndns-custom dyndns-static dyns dynv6 dynv6-v6 easydns eurodns freedns freedns-v6 freedns2 freedns2-v6 glesys gandi-livedns godaddy godaddy-v6 googledomains gratisdns he-net he-net-v6 he-net-tunnelbroker hover linode linode-v6 loopia namecheap noip noip-v6 noip-free noip-free-v6 ods opendns ovh-dynhost route53 route53-v6 selfhost spdyn spdyn-v6 zoneedit');
30
define('DYNDNS_PROVIDER_DESCRIPTIONS', 'All-Inkl.com,Azure DNS,Azure DNS (v6),City Network,Cloudflare,Cloudflare (v6),ClouDNS,Custom,Custom (v6),DigitalOcean,DigitalOcean (v6),DNSexit,DNSimple,DNS Made Easy,DNS-O-Matic,DreamHost,Dreamhost (v6),DuiaDns.net,DuiaDns.net (v6),DynDNS (dynamic),DynDNS (custom),DynDNS (static),DyNS,Dynv6,Dynv6 (v6),easyDNS,Euro Dns,freeDNS,freeDNS (v6),freeDNS API Version 2, freeDNS API Version 2 (v6),GleSYS,Gandi Live DNS,GoDaddy,GoDaddy (v6),Google Domains,GratisDNS,HE.net,HE.net (v6),HE.net Tunnelbroker,Hover,Linode,Linode (v6),Loopia,Namecheap,No-IP,No-IP (v6),No-IP (free),No-IP (free-v6),ODS.org,OpenDNS,OVH DynHOST,Route 53,Route 53 (v6),SelfHost,SPDYN,SPDYN (v6),ZoneEdit');
31

    
32
/* implement ipv6 route advertising daemon */
33
function services_radvd_configure($blacklist = array()) {
34
	global $config, $g;
35

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

    
41
	if (!is_array($config['dhcpdv6'])) {
42
		$config['dhcpdv6'] = array();
43
	}
44

    
45
	$Iflist = get_configured_interface_list();
46
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
47

    
48
	$radvdconf = "# Automatically Generated, do not edit\n";
49

    
50
	/* Process all links which need the router advertise daemon */
51
	$radvdifs = array();
52

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

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

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

    
75
		if (!isset($dhcpv6ifconf['rapriority'])) {
76
			$dhcpv6ifconf['rapriority'] = "medium";
77
		}
78

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

    
92
		$realif = get_real_interface($dhcpv6if, "inet6");
93

    
94
		if (isset($radvdifs[$realif])) {
95
			continue;
96
		}
97

    
98
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
99
		if (!is_ipaddrv6($ifcfgipv6)) {
100
			continue;
101
		}
102

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

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

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

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

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

    
193
		if (is_numericint($dhcpv6ifconf['ravalidlifetime'])) {
194
		  $radvdconf .= "\t\tAdvValidLifetime {$dhcpv6ifconf['ravalidlifetime']};\n";
195
		} else {
196
		  $radvdconf .= "\t\tAdvValidLifetime 86400;\n";
197
		}
198

    
199
		if (is_numericint($dhcpv6ifconf['rapreferredlifetime'])) {
200
		  $radvdconf .= "\t\tAdvPreferredLifetime {$dhcpv6ifconf['rapreferredlifetime']};\n";
201
		} else {
202
		  $radvdconf .= "\t\tAdvPreferredLifetime 14400;\n";
203
		}
204

    
205
		$radvdconf .= "\t};\n";
206

    
207
		if (is_array($dhcpv6ifconf['subnets']['item'])) {
208
			foreach ($dhcpv6ifconf['subnets']['item'] as $subnet) {
209
				if (is_subnetv6($subnet)) {
210
					$radvdconf .= "\tprefix {$subnet} {\n";
211
					$radvdconf .= "\t\tDeprecatePrefix on;\n";
212
					switch ($dhcpv6ifconf['ramode']) {
213
						case "managed":
214
							$radvdconf .= "\t\tAdvOnLink on;\n";
215
							$radvdconf .= "\t\tAdvAutonomous off;\n";
216
							break;
217
						case "router":
218
							$radvdconf .= "\t\tAdvOnLink off;\n";
219
							$radvdconf .= "\t\tAdvAutonomous off;\n";
220
							break;
221
						case "assist":
222
							$radvdconf .= "\t\tAdvOnLink on;\n";
223
							$radvdconf .= "\t\tAdvAutonomous on;\n";
224
							break;
225
						case "unmanaged":
226
							$radvdconf .= "\t\tAdvOnLink on;\n";
227
							$radvdconf .= "\t\tAdvAutonomous on;\n";
228
							break;
229
					}
230
					$radvdconf .= "\t};\n";
231
				}
232
			}
233
		}
234
		$radvdconf .= "\troute ::/0 {\n";
235
		switch ($dhcpv6ifconf['rapriority']) {
236
			case "low":
237
				$radvdconf .= "\t\tAdvRoutePreference low;\n";
238
				break;
239
			case "high":
240
				$radvdconf .= "\t\tAdvRoutePreference high;\n";
241
				break;
242
			default:
243
				$radvdconf .= "\t\tAdvRoutePreference medium;\n";
244
				break;
245
		}
246
		$radvdconf .= "\t\tRemoveRoute on;\n";
247
		$radvdconf .= "\t};\n";
248

    
249
		/* add DNS servers */
250
		if ($dhcpv6ifconf['radvd-dns'] != 'disabled') {
251
			$dnslist = array();
252
			if (isset($dhcpv6ifconf['rasamednsasdhcp6']) && is_array($dhcpv6ifconf['dnsserver']) && !empty($dhcpv6ifconf['dnsserver'])) {
253
				foreach ($dhcpv6ifconf['dnsserver'] as $server) {
254
					if (is_ipaddrv6($server)) {
255
						$dnslist[] = $server;
256
					}
257
				}
258
			} elseif (!isset($dhcpv6ifconf['rasamednsasdhcp6']) && isset($dhcpv6ifconf['radnsserver']) && is_array($dhcpv6ifconf['radnsserver'])) {
259
				foreach ($dhcpv6ifconf['radnsserver'] as $server) {
260
					if (is_ipaddrv6($server)) {
261
						$dnslist[] = $server;
262
					}
263
				}
264
			} elseif (isset($config['dnsmasq']['enable']) || isset($config['unbound']['enable'])) {
265
				$dnslist[] = get_interface_ipv6($realif);
266
			} elseif (is_array($config['system']['dnsserver']) && !empty($config['system']['dnsserver'])) {
267
				foreach ($config['system']['dnsserver'] as $server) {
268
					if (is_ipaddrv6($server)) {
269
						$dnslist[] = $server;
270
					}
271
				}
272
			}
273
			if (count($dnslist) > 0) {
274
				$dnsstring = implode(" ", $dnslist);
275
				if ($dnsstring <> "") {
276
					$radvdconf .= "\tRDNSS {$dnsstring} { };\n";
277
				}
278
			}
279

    
280
			$searchlist = array();
281
			$domainsearchlist = explode(';', $dhcpv6ifconf['radomainsearchlist']);
282
			foreach ($domainsearchlist as $sd) {
283
				$sd = trim($sd);
284
				if (is_hostname($sd)) {
285
					$searchlist[] = $sd;
286
				}
287
			}
288
			if (count($searchlist) > 0) {
289
				$searchliststring = trim(implode(" ", $searchlist));
290
			}
291
			if (!empty($dhcpv6ifconf['domain'])) {
292
				$radvdconf .= "\tDNSSL {$dhcpv6ifconf['domain']} {$searchliststring} { };\n";
293
			} elseif (!empty($config['system']['domain'])) {
294
				$radvdconf .= "\tDNSSL {$config['system']['domain']} {$searchliststring} { };\n";
295
			}
296
		}
297
		$radvdconf .= "};\n";
298
	}
299

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

    
322
		$realif = get_real_interface($if, "inet6");
323

    
324
		/* prevent duplicate entries, manual overrides */
325
		if (isset($radvdifs[$realif])) {
326
			continue;
327
		}
328

    
329
		$ifcfgipv6 = get_interface_ipv6($if);
330
		if (!is_ipaddrv6($ifcfgipv6)) {
331
			$subnetv6 = "::";
332
			$ifcfgsnv6 = "64";
333
		} else {
334
			$ifcfgsnv6 = get_interface_subnetv6($if);
335
			$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
336
		}
337
		$radvdifs[$realif] = $realif;
338

    
339
		$autotype = $config['interfaces'][$trackif]['ipaddrv6'];
340

    
341
		if ($g['debug']) {
342
			log_error("configuring RA on {$if} for type {$autotype} radvd subnet {$subnetv6}/{$ifcfgsnv6}");
343
		}
344

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

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

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

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

    
422
function services_dhcpd_configure($family = "all", $blacklist = array()) {
423
	global $config, $g;
424

    
425
	$dhcpdconfigurelck = lock("dhcpdconfigure", LOCK_EX);
426

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

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

    
450
	if ($family == "all" || $family == "inet") {
451
		services_dhcpdv4_configure();
452
	}
453
	if ($family == "all" || $family == "inet6") {
454
		services_dhcpdv6_configure($blacklist);
455
		services_radvd_configure($blacklist);
456
	}
457

    
458
	unlock($dhcpdconfigurelck);
459
}
460

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

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

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

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

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

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

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

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

    
508
	$custoptions = "";
509
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
510
		if (is_array($dhcpifconf['numberoptions']) && is_array($dhcpifconf['numberoptions']['item'])) {
511
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
512
				if (!empty($item['type'])) {
513
					$itemtype = $item['type'];
514
				} else {
515
					$itemtype = "text";
516
				}
517
				$custoptions .= "option custom-{$dhcpif}-{$itemidx} code {$item['number']} = {$itemtype};\n";
518
			}
519
		}
520
		if (is_array($dhcpifconf['pool'])) {
521
			foreach ($dhcpifconf['pool'] as $poolidx => $poolconf) {
522
				if (is_array($poolconf['numberoptions']) && is_array($poolconf['numberoptions']['item'])) {
523
					foreach ($poolconf['numberoptions']['item'] as $itemidx => $item) {
524
						if (!empty($item['type'])) {
525
							$itemtype = $item['type'];
526
						} else {
527
							$itemtype = "text";
528
						}
529
						$custoptions .= "option custom-{$dhcpif}-{$poolidx}-{$itemidx} code {$item['number']} = {$itemtype};\n";
530
					}
531
				}
532
			}
533
		}
534
		if (is_array($dhcpifconf['staticmap'])) {
535
			$i = 0;
536
			foreach ($dhcpifconf['staticmap'] as $sm) {
537
				if (is_array($sm['numberoptions']) && is_array($sm['numberoptions']['item'])) {
538
					foreach ($sm['numberoptions']['item'] as $itemidx => $item) {
539
						if (!empty($item['type'])) {
540
							$itemtype = $item['type'];
541
						} else {
542
							$itemtype = "text";
543
						}
544
						$custoptions .= "option custom-s_{$dhcpif}_{$i}-{$itemidx} code {$item['number']} = {$itemtype};\n";
545
					}
546
				}
547
				$i++;
548
			}
549
		}
550
	}
551

    
552
	$dhcpdconf = <<<EOD
553

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

    
566
EOD;
567

    
568
	if (!isset($dhcpifconf['disableauthoritative'])) {
569
		$dhcpdconf .= "authoritative;\n";
570
	}
571

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

    
576
	// OMAPI Settings
577
	if (isset($dhcpifconf['omapi_port']) && is_numeric($dhcpifconf['omapi_port'])) {
578
		$dhcpdconf .= <<<EOD
579

    
580
key omapi_key {
581
  algorithm {$dhcpifconf['omapi_key_algorithm']};
582
  secret "{$dhcpifconf['omapi_key']}";
583
};
584
omapi-port {$dhcpifconf['omapi_port']};
585
omapi-key omapi_key;
586

    
587
EOD;
588
	}
589

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

    
602
	/*    loop through and determine if we need to setup
603
	 *    failover peer "bleh" entries
604
	 */
605
	foreach ($dhcpdcfg as $dhcpif => $dhcpifconf) {
606

    
607
		if (!isset($config['interfaces'][$dhcpif]['enable'])) {
608
			continue;
609
		}
610

    
611
		interfaces_staticarp_configure($dhcpif);
612

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

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

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

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

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

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

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

    
694
		$all_pools = array();
695
		$all_pools[] = $dhcpifconf;
696
		if (is_array($dhcpifconf['pool'])) {
697
			$all_pools = array_merge($all_pools, $dhcpifconf['pool']);
698
		}
699

    
700
		$dnscfg = "";
701

    
702
		if ($dhcpifconf['domain']) {
703
			$dnscfg .= "	option domain-name \"{$dhcpifconf['domain']}\";\n";
704
		}
705

    
706
		if ($dhcpifconf['domainsearchlist'] <> "") {
707
			$dnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpifconf['domainsearchlist'])) . "\";\n";
708
		}
709

    
710
		if (isset($dhcpifconf['ddnsupdate'])) {
711
			$need_ddns_updates = true;
712
			$newzone = array();
713
			if ($dhcpifconf['ddnsdomain'] <> "") {
714
				$newzone['domain-name'] = $dhcpifconf['ddnsdomain'];
715
				$dnscfg .= "	ddns-domainname \"{$dhcpifconf['ddnsdomain']}\";\n";
716
			} else {
717
				$newzone['domain-name'] = $config['system']['domain'];
718
			}
719

    
720
			if (empty($dhcpifconf['ddnsclientupdates'])) {
721
				$ddnsclientupdates = 'allow';
722
			} else {
723
				$ddnsclientupdates = $dhcpifconf['ddnsclientupdates'];
724
			}
725

    
726
			$dnscfg .= "	{$ddnsclientupdates} client-updates;\n";
727

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

    
730
			$subnet_mask_bits = 32 - $ifcfgsn;
731
			$start_octet = $subnet_mask_bits >> 3;
732
			$octet_mask_bits = $subnet_mask_bits & ($subnet_mask_bits % 8);
733
			if ($octet_mask_bits) {
734
			    $octet_mask = (1 << $octet_mask_bits) - 1;
735
			    $octet_start = $revsubnet[$start_octet] & ~$octet_mask;
736
			    $revsubnet[$start_octet] = $octet_start . "-" . ($octet_start + $octet_mask);
737
			}
738

    
739
			$ptr_domain = '';
740
			for ($octet = 0; $octet <= 3; $octet++) {
741
				if ($octet < $start_octet) {
742
					continue;
743
				}
744
				$ptr_domain .= ((empty($ptr_domain) && $ptr_domain !== "0") ? '' : '.');
745
				$ptr_domain .= $revsubnet[$octet];
746
			}
747
			$ptr_domain .= ".in-addr.arpa";
748
			$newzone['ptr-domain'] = $ptr_domain;
749
			unset($ptr_domain, $revsubnet, $start_octet);
750
		}
751

    
752
		if (is_array($dhcpifconf['dnsserver']) && ($dhcpifconf['dnsserver'][0])) {
753
			$dnscfg .= "	option domain-name-servers " . join(",", $dhcpifconf['dnsserver']) . ";";
754
			if ($newzone['domain-name']) {
755
				$newzone['dns-servers'] = $dhcpifconf['dnsserver'];
756
			}
757
		} else if (isset($config['dnsmasq']['enable'])) {
758
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
759
			if ($newzone['domain-name'] && is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
760
				$newzone['dns-servers'] = $syscfg['dnsserver'];
761
			}
762
		} else if (isset($config['unbound']['enable'])) {
763
			$dnscfg .= "	option domain-name-servers {$ifcfgip};";
764
		} else if (!empty($dns_arrv4)) {
765
			$dnscfg .= "	option domain-name-servers " . join(",", $dns_arrv4) . ";";
766
			if ($newzone['domain-name']) {
767
				$newzone['dns-servers'] = $dns_arrv4;
768
			}
769
		}
770

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

    
795
		// instantiate class before pool definition
796
		$dhcpdconf .= "class \"s_{$dhcpif}\" {\n	match pick-first-value (option dhcp-client-identifier, hardware);\n}\n";
797

    
798
		$dhcpdconf .= "subnet {$subnet} netmask {$subnetmask} {\n";
799

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

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

    
865
			if ($poolconf['failover_peerip'] <> "") {
866
				$dhcpdconf .= "		$deny_action dynamic bootp clients;\n";
867
			}
868

    
869
			// set pool MAC limitations
870
			if (isset($poolconf['denyunknown'])) {
871
				if ($poolconf['denyunknown'] == "class") {
872
					$dhcpdconf .= "		allow members of \"s_{$dhcpif}\";\n";
873
					$dhcpdconf .= "		$deny_action unknown-clients;\n";
874
				} else if ($poolconf['denyunknown'] == "disabled") {
875
					// add nothing to $dhcpdconf; condition added to prevent next condition applying if ever engine changes such that: isset("disabled") == true
876
				} else {	// "catch-all" covering "enabled" value post-PR#4066, and covering non-upgraded boolean option (i.e. literal value "enabled")
877
					$dhcpdconf .= "		$deny_action unknown-clients;\n";
878
				}
879
			}
880

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

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

    
889
			$pdnscfg = "";
890

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

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

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

    
906
			$dhcpdconf .= "{$pdnscfg}";
907

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

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

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

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

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

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

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

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

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

    
966
			// net boot information
967
			if (isset($poolconf['netboot'])) {
968
				if (!empty($poolconf['nextserver']) && ($poolconf['nextserver'] != $dhcpifconf['nextserver'])) {
969
					$dhcpdconf .= "		next-server {$poolconf['nextserver']};\n";
970
				}
971

    
972
				if (!empty($poolconf['filename']) &&
973
				    (!isset($dhcpifconf['filename']) ||
974
				    ($poolconf['filename'] != $dhcpifconf['filename']))) {
975
					$filename = $poolconf['filename'];
976
				}
977
				if (!empty($poolconf['filename32']) &&
978
				    (!isset($dhcpifconf['filename32']) ||
979
				    ($poolconf['filename32'] != $dhcpifconf['filename32']))) {
980
					$filename32 = $poolconf['filename32'];
981
				}
982
				if (!empty($poolconf['filename64']) &&
983
				    (!isset($dhcpifconf['filename64']) ||
984
				    ($poolconf['filename64'] != $dhcpifconf['filename64']))) {
985
					$filename64 = $poolconf['filename64'];
986
				}
987
				if (!empty($poolconf['filename32arm']) &&
988
				    (!isset($dhcpifconf['filename32arm']) ||
989
				    ($poolconf['filename32arm'] != $dhcpifconf['filename32arm']))) {
990
					$filename32arm = $poolconf['filename32arm'];
991
				}
992
				if (!empty($poolconf['filename64arm']) &&
993
				    (!isset($dhcpifconf['filename64arm']) ||
994
				    ($poolconf['filename64arm'] != $dhcpifconf['filename64arm']))) {
995
					$filename64arm = $poolconf['filename64arm'];
996
				}
997

    
998
				if (!empty($filename32) || !empty($filename64) || !empty($filename32arm) || !empty($filename64arm)) {
999
					if (empty($filename) && !empty($dhcpifconf['filename'])) {
1000
						$filename = $dhcpifconf['filename'];
1001
					}
1002
					if (empty($filename32) && !empty($dhcpifconf['filename32'])) {
1003
						$filename32 = $dhcpifconf['filename32'];
1004
					}
1005
					if (empty($filename64) && !empty($dhcpifconf['filename64'])) {
1006
						$filename64 = $dhcpifconf['filename64'];
1007
					}
1008
					if (empty($filename32arm) && !empty($dhcpifconf['filename32arm'])) {
1009
						$filename32arm = $dhcpifconf['filename32arm'];
1010
					}
1011
					if (empty($filename64arm) && !empty($dhcpifconf['filename64arm'])) {
1012
						$filename64arm = $dhcpifconf['filename64arm'];
1013
					}
1014
				}
1015

    
1016
				if (!empty($filename) && !empty($filename32) && !empty($filename64) && !empty($filename32arm) && !empty($filename64arm)) {
1017
					$dhcpdconf .= "		if option arch = 00:06 {\n";
1018
					$dhcpdconf .= "			filename \"{$filename32}\";\n";
1019
					$dhcpdconf .= "		} else if option arch = 00:07 {\n";
1020
					$dhcpdconf .= "			filename \"{$filename64}\";\n";
1021
					$dhcpdconf .= "		} else if option arch = 00:09 {\n";
1022
					$dhcpdconf .= "			filename \"{$filename64}\";\n";
1023
					$dhcpdconf .= "		} else if option arch = 00:0a {\n";
1024
					$dhcpdconf .= "			filename \"{$filename32arm}\";\n";
1025
					$dhcpdconf .= "		} else if option arch = 00:0b {\n";
1026
					$dhcpdconf .= "			filename \"{$filename64arm}\";\n";
1027
					$dhcpdconf .= "		} else {\n";
1028
					$dhcpdconf .= "			filename \"{$filename}\";\n";
1029
					$dhcpdconf .= "		}\n\n";
1030
				} elseif (!empty($filename)) {
1031
					$dhcpdconf .= "		filename \"{$filename}\";\n";
1032
				}
1033
				unset($filename, $filename32, $filename64, $filename32arm, $filename64arm);
1034

    
1035
				if (!empty($poolconf['rootpath']) && ($poolconf['rootpath'] != $dhcpifconf['rootpath'])) {
1036
					$dhcpdconf .= "		option root-path \"{$poolconf['rootpath']}\";\n";
1037
				}
1038
			}
1039
			$dhcpdconf .= "		range {$poolconf['range']['from']} {$poolconf['range']['to']};\n";
1040
			$dhcpdconf .= "	}\n\n";
1041
		}
1042
// End of settings inside pools
1043

    
1044
		if ($dhcpifconf['gateway'] && $dhcpifconf['gateway'] != "none") {
1045
			$routers = $dhcpifconf['gateway'];
1046
			$add_routers = true;
1047
		} elseif ($dhcpifconf['gateway'] == "none") {
1048
			$add_routers = false;
1049
		} else {
1050
			$add_routers = $enable_add_routers;
1051
			$routers = $ifcfgip;
1052
		}
1053
		if ($add_routers) {
1054
			$dhcpdconf .= "	option routers {$routers};\n";
1055
		}
1056

    
1057
		$dhcpdconf .= <<<EOD
1058
$dnscfg
1059

    
1060
EOD;
1061
		// default-lease-time
1062
		if ($dhcpifconf['defaultleasetime']) {
1063
			$dhcpdconf .= "	default-lease-time {$dhcpifconf['defaultleasetime']};\n";
1064
		}
1065

    
1066
		// max-lease-time
1067
		if ($dhcpifconf['maxleasetime']) {
1068
			$dhcpdconf .= "	max-lease-time {$dhcpifconf['maxleasetime']};\n";
1069
		}
1070

    
1071
		if (!isset($dhcpifconf['disablepingcheck'])) {
1072
			$dhcpdconf .= "	ping-check true;\n";
1073
		} else {
1074
			$dhcpdconf .= "	ping-check false;\n";
1075
		}
1076

    
1077
		// netbios-name*
1078
		if (is_array($dhcpifconf['winsserver']) && $dhcpifconf['winsserver'][0]) {
1079
			$dhcpdconf .= "	option netbios-name-servers " . join(",", $dhcpifconf['winsserver']) . ";\n";
1080
			$dhcpdconf .= "	option netbios-node-type 8;\n";
1081
		}
1082

    
1083
		// ntp-servers
1084
		if (is_array($dhcpifconf['ntpserver']) && $dhcpifconf['ntpserver'][0]) {
1085
			$dhcpdconf .= "	option ntp-servers " . join(",", $dhcpifconf['ntpserver']) . ";\n";
1086
		}
1087

    
1088
		// tftp-server-name
1089
		if ($dhcpifconf['tftp'] <> "") {
1090
			$dhcpdconf .= "	option tftp-server-name \"{$dhcpifconf['tftp']}\";\n";
1091
		}
1092

    
1093
		// Handle option, number rowhelper values
1094
		$dhcpdconf .= "\n";
1095
		if (isset($dhcpifconf['numberoptions']['item']) && is_array($dhcpifconf['numberoptions']['item'])) {
1096
			foreach ($dhcpifconf['numberoptions']['item'] as $itemidx => $item) {
1097
				$item_value = base64_decode($item['value']);
1098
				if (empty($item['type']) || $item['type'] == "text") {
1099
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} \"{$item_value}\";\n";
1100
				} else {
1101
					$dhcpdconf .= "	option custom-{$dhcpif}-{$itemidx} {$item_value};\n";
1102
				}
1103
			}
1104
		}
1105

    
1106
		// ldap-server
1107
		if ($dhcpifconf['ldap'] <> "") {
1108
			$dhcpdconf .= "	option ldap-server \"{$dhcpifconf['ldap']}\";\n";
1109
		}
1110

    
1111
		// net boot information
1112
		if (isset($dhcpifconf['netboot'])) {
1113
			if ($dhcpifconf['nextserver'] <> "") {
1114
				$dhcpdconf .= "	next-server {$dhcpifconf['nextserver']};\n";
1115
			}
1116
			if (!empty($dhcpifconf['filename']) && !empty($dhcpifconf['filename32']) && !empty($dhcpifconf['filename64'])) {
1117
				$dhcpdconf .= "	if option arch = 00:06 {\n";
1118
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename32']}\";\n";
1119
				$dhcpdconf .= "	} else if option arch = 00:07 {\n";
1120
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1121
				$dhcpdconf .= "	} else if option arch = 00:09 {\n";
1122
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename64']}\";\n";
1123
				$dhcpdconf .= "	} else {\n";
1124
				$dhcpdconf .= "		filename \"{$dhcpifconf['filename']}\";\n";
1125
				$dhcpdconf .= "	}\n\n";
1126
			} elseif (!empty($dhcpifconf['filename'])) {
1127
				$dhcpdconf .= "	filename \"{$dhcpifconf['filename']}\";\n";
1128
			}
1129
			if (!empty($dhcpifconf['rootpath'])) {
1130
				$dhcpdconf .= "	option root-path \"{$dhcpifconf['rootpath']}\";\n";
1131
			}
1132
		}
1133

    
1134
		$dhcpdconf .= <<<EOD
1135
}
1136

    
1137
EOD;
1138

    
1139
		/* add static mappings */
1140
		if (is_array($dhcpifconf['staticmap'])) {
1141

    
1142
			$i = 0;
1143
			foreach ($dhcpifconf['staticmap'] as $sm) {
1144
				$cid = '';
1145
				$dhcpdconf .= "host s_{$dhcpif}_{$i} {\n";
1146

    
1147
				if ($sm['mac']) {
1148
					$dhcpdconf .= "	hardware ethernet {$sm['mac']};\n";
1149
				}
1150

    
1151
				if ($sm['cid']) {
1152
					$cid = str_replace('"', '\"', $sm['cid']);
1153
					$dhcpdconf .= "	option dhcp-client-identifier \"{$cid}\";\n";
1154
				}
1155

    
1156
				if ($sm['ipaddr']) {
1157
					$dhcpdconf .= "	fixed-address {$sm['ipaddr']};\n";
1158
				}
1159

    
1160
				if ($sm['hostname']) {
1161
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1162
					$dhhostname = str_replace(".", "_", $dhhostname);
1163
					$dhcpdconf .= "	option host-name \"{$dhhostname}\";\n";
1164
					if ((isset($dhcpifconf['ddnsupdate']) || isset($sm['ddnsupdate'])) && (isset($dhcpifconf['ddnsforcehostname']) || isset($sm['ddnsforcehostname']))) {
1165
						$dhcpdconf .= "	ddns-hostname \"{$dhhostname}\";\n";
1166
					}
1167
				}
1168
				if ($sm['filename']) {
1169
					$dhcpdconf .= "	filename \"{$sm['filename']}\";\n";
1170
				}
1171

    
1172
				if ($sm['rootpath']) {
1173
					$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1174
				}
1175

    
1176
				if ($sm['gateway'] && ($sm['gateway'] != $dhcpifconf['gateway'])) {
1177
					$dhcpdconf .= "	option routers {$sm['gateway']};\n";
1178
				}
1179

    
1180
				$smdnscfg = "";
1181

    
1182
				if ($sm['domain'] && ($sm['domain'] != $dhcpifconf['domain'])) {
1183
					$smdnscfg .= "	option domain-name \"{$sm['domain']}\";\n";
1184
				}
1185

    
1186
				if (!empty($sm['domainsearchlist']) && ($sm['domainsearchlist'] != $dhcpifconf['domainsearchlist'])) {
1187
					$smdnscfg .= "	option domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $sm['domainsearchlist'])) . "\";\n";
1188
				}
1189

    
1190
				if (isset($sm['ddnsupdate'])) {
1191
					if (($sm['ddnsdomain'] <> "") && ($sm['ddnsdomain'] != $dhcpifconf['ddnsdomain'])) {
1192
						$smdnscfg .= "		ddns-domainname \"{$sm['ddnsdomain']}\";\n";
1193
					}
1194
					$smdnscfg .= "		ddns-update-style interim;\n";
1195
				}
1196

    
1197
				if (is_array($sm['dnsserver']) && ($sm['dnsserver'][0]) && ($sm['dnsserver'][0] != $dhcpifconf['dnsserver'][0])) {
1198
					$smdnscfg .= "	option domain-name-servers " . join(",", $sm['dnsserver']) . ";\n";
1199
				}
1200
				$dhcpdconf .= "{$smdnscfg}";
1201

    
1202
				// default-lease-time
1203
				if ($sm['defaultleasetime'] && ($sm['defaultleasetime'] != $dhcpifconf['defaultleasetime'])) {
1204
					$dhcpdconf .= "	default-lease-time {$sm['defaultleasetime']};\n";
1205
				}
1206

    
1207
				// max-lease-time
1208
				if ($sm['maxleasetime'] && ($sm['maxleasetime'] != $dhcpifconf['maxleasetime'])) {
1209
					$dhcpdconf .= "	max-lease-time {$sm['maxleasetime']};\n";
1210
				}
1211

    
1212
				// netbios-name*
1213
				if (is_array($sm['winsserver']) && $sm['winsserver'][0] && ($sm['winsserver'][0] != $dhcpifconf['winsserver'][0])) {
1214
					$dhcpdconf .= "	option netbios-name-servers " . join(",", $sm['winsserver']) . ";\n";
1215
					$dhcpdconf .= "	option netbios-node-type 8;\n";
1216
				}
1217

    
1218
				// ntp-servers
1219
				if (is_array($sm['ntpserver']) && $sm['ntpserver'][0] && ($sm['ntpserver'][0] != $dhcpifconf['ntpserver'][0])) {
1220
					$dhcpdconf .= "	option ntp-servers " . join(",", $sm['ntpserver']) . ";\n";
1221
				}
1222

    
1223
				// tftp-server-name
1224
				if (!empty($sm['tftp']) && ($sm['tftp'] != $dhcpifconf['tftp'])) {
1225
					$dhcpdconf .= "	option tftp-server-name \"{$sm['tftp']}\";\n";
1226
				}
1227

    
1228
				// Handle option, number rowhelper values
1229
				$dhcpdconf .= "\n";
1230
				if (isset($sm['numberoptions']['item']) && is_array($sm['numberoptions']['item'])) {
1231
					foreach ($sm['numberoptions']['item'] as $itemidx => $item) {
1232
						$item_value = base64_decode($item['value']);
1233
						if (empty($item['type']) || $item['type'] == "text") {
1234
							$dhcpdconf .= "	option custom-s_{$dhcpif}_{$i}-{$itemidx} \"{$item_value}\";\n";
1235
						} else {
1236
							$dhcpdconf .= "	option custom-s_{$dhcpif}_{$i}-{$itemidx} {$item_value};\n";
1237
						}
1238
					}
1239
				}
1240

    
1241
				// ldap-server
1242
				if (!empty($sm['ldap']) && ($sm['ldap'] != $dhcpifconf['ldap'])) {
1243
					$dhcpdconf .= "	option ldap-server \"{$sm['ldap']}\";\n";
1244
				}
1245

    
1246
				// net boot information
1247
				if (isset($sm['netboot'])) {
1248
					if ($sm['nextserver'] <> "") {
1249
						$dhcpdconf .= "	next-server {$sm['nextserver']};\n";
1250
					}
1251
					if (!empty($sm['filename']) && !empty($sm['filename32']) && !empty($sm['filename64'])) {
1252
						$dhcpdconf .= "	if option arch = 00:06 {\n";
1253
						$dhcpdconf .= "		filename \"{$sm['filename32']}\";\n";
1254
						$dhcpdconf .= "	} else if option arch = 00:07 {\n";
1255
						$dhcpdconf .= "		filename \"{$sm['filename64']}\";\n";
1256
						$dhcpdconf .= "	} else if option arch = 00:09 {\n";
1257
						$dhcpdconf .= "		filename \"{$sm['filename64']}\";\n";
1258
						$dhcpdconf .= "	} else {\n";
1259
						$dhcpdconf .= "		filename \"{$sm['filename']}\";\n";
1260
						$dhcpdconf .= "	}\n\n";
1261
					} elseif (!empty($sm['filename'])) {
1262
						$dhcpdconf .= "	filename \"{$sm['filename']}\";\n";
1263
					}
1264
					if (!empty($dhcpifconf['rootpath'])) {
1265
						$dhcpdconf .= "	option root-path \"{$sm['rootpath']}\";\n";
1266
					}
1267
				}
1268

    
1269
				$dhcpdconf .= "}\n";
1270

    
1271
				// subclass for DHCP limiting
1272
				if (!empty($sm['mac'])) {
1273
					// assuming ALL addresses are ethernet hardware type ("1:" prefix)
1274
					$dhcpdconf .= "subclass \"s_{$dhcpif}\" 1:{$sm['mac']};\n";
1275
				}
1276
				if (!empty($cid)) {
1277
					$dhcpdconf .= "subclass \"s_{$dhcpif}\" \"{$cid}\";\n";
1278
				}
1279

    
1280

    
1281
				$i++;
1282
			}
1283
		}
1284

    
1285
		$dhcpdifs[] = get_real_interface($dhcpif);
1286
		if ($newzone['domain-name']) {
1287
			if ($need_ddns_updates) {
1288
				$newzone['dns-servers'] = array($dhcpifconf['ddnsdomainprimary'], $dhcpifconf['ddnsdomainsecondary']);
1289
				$newzone['ddnsdomainkeyname'] = $dhcpifconf['ddnsdomainkeyname'];
1290
				$newzone['ddnsdomainkeyalgorithm'] = $dhcpifconf['ddnsdomainkeyalgorithm'];
1291
				$newzone['ddnsdomainkey'] = $dhcpifconf['ddnsdomainkey'];
1292
				$dhcpdconf .= dhcpdkey($dhcpifconf);
1293
			}
1294
			$ddns_zones[] = $newzone;
1295
		}
1296
	}
1297

    
1298
	if ($need_ddns_updates) {
1299
		$dhcpdconf .= "ddns-update-style interim;\n";
1300
		$dhcpdconf .= "update-static-leases on;\n";
1301

    
1302
		$dhcpdconf .= dhcpdzones($ddns_zones);
1303
	}
1304

    
1305
	/* write dhcpd.conf */
1306
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpd.conf", $dhcpdconf)) {
1307
		printf(gettext("Error: cannot open dhcpd.conf in services_dhcpdv4_configure().%s"), "\n");
1308
		unset($dhcpdconf);
1309
		return 1;
1310
	}
1311
	unset($dhcpdconf);
1312

    
1313
	/* create an empty leases database */
1314
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
1315
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
1316
	}
1317

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

    
1322
	/* fire up dhcpd in a chroot */
1323
	if (count($dhcpdifs) > 0) {
1324
		mwexec("/usr/local/sbin/dhcpd -user dhcpd -group _dhcp -chroot {$g['dhcpd_chroot_path']} -cf /etc/dhcpd.conf -pf {$g['varrun_path']}/dhcpd.pid " .
1325
			join(" ", $dhcpdifs));
1326
	}
1327

    
1328
	if (platform_booting()) {
1329
		print "done.\n";
1330
	}
1331

    
1332
	return 0;
1333
}
1334

    
1335
function dhcpdkey($dhcpifconf) {
1336
	$dhcpdconf = "";
1337
	if (!empty($dhcpifconf['ddnsdomainkeyname']) && !empty($dhcpifconf['ddnsdomainkey'])) {
1338
		$algorithm = empty($dhcpifconf['ddnsdomainkeyalgorithm']) ? 'hmac-md5' : $dhcpifconf['ddnsdomainkeyalgorithm'];
1339
		$dhcpdconf .= "key {$dhcpifconf['ddnsdomainkeyname']} {\n";
1340
		$dhcpdconf .= "	algorithm {$algorithm};\n";
1341
		$dhcpdconf .= "	secret {$dhcpifconf['ddnsdomainkey']};\n";
1342
		$dhcpdconf .= "}\n";
1343
	}
1344

    
1345
	return $dhcpdconf;
1346
}
1347

    
1348
function dhcpdzones($ddns_zones) {
1349
	$dhcpdconf = "";
1350

    
1351
	if (is_array($ddns_zones)) {
1352
		$added_zones = array();
1353
		foreach ($ddns_zones as $zone) {
1354
			if (!is_array($zone) || empty($zone) || !is_array($zone['dns-servers'])) {
1355
				continue;
1356
			}
1357
			$primary = $zone['dns-servers'][0];
1358
			$secondary = empty($zone['dns-servers'][1]) ? "" : $zone['dns-servers'][1];
1359

    
1360
			// Make sure we aren't using any invalid servers.
1361
			if (!is_ipaddr($primary)) {
1362
				if (is_ipaddr($secondary)) {
1363
					$primary = $secondary;
1364
					$secondary = "";
1365
				} else {
1366
					continue;
1367
				}
1368
			}
1369

    
1370
			// We don't need to add zones multiple times.
1371
			if ($zone['domain-name'] && !in_array($zone['domain-name'], $added_zones)) {
1372
				$dhcpdconf .= "zone {$zone['domain-name']}. {\n";
1373
				if (is_ipaddrv4($primary)) {
1374
					$dhcpdconf .= "	primary {$primary};\n";
1375
				} else {
1376
					$dhcpdconf .= "	primary6 {$primary};\n";
1377
				}
1378
				if (is_ipaddrv4($secondary)) {
1379
					$dhcpdconf .= "	secondary {$secondary};\n";
1380
				} elseif (is_ipaddrv6($secondary)) {
1381
					$dhcpdconf .= "	secondary6 {$secondary};\n";
1382
				}
1383
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1384
					$dhcpdconf .= "	key {$zone['ddnsdomainkeyname']};\n";
1385
				}
1386
				$dhcpdconf .= "}\n";
1387
				$added_zones[] = $zone['domain-name'];
1388
			}
1389
			if ($zone['ptr-domain'] && !in_array($zone['ptr-domain'], $added_zones)) {
1390
				$dhcpdconf .= "zone {$zone['ptr-domain']} {\n";
1391
				if (is_ipaddrv4($primary)) {
1392
					$dhcpdconf .= "	primary {$primary};\n";
1393
				} else {
1394
					$dhcpdconf .= "	primary6 {$primary};\n";
1395
				}
1396
				if (is_ipaddrv4($secondary)) {
1397
					$dhcpdconf .= "	secondary {$secondary};\n";
1398
				} elseif (is_ipaddrv6($secondary)) {
1399
					$dhcpdconf .= "	secondary6 {$secondary};\n";
1400
				}
1401
				if ($zone['ddnsdomainkeyname'] <> "" && $zone['ddnsdomainkey'] <> "") {
1402
					$dhcpdconf .= "	key {$zone['ddnsdomainkeyname']};\n";
1403
				}
1404
				$dhcpdconf .= "}\n";
1405
				$added_zones[] = $zone['ptr-domain'];
1406
			}
1407
		}
1408
	}
1409

    
1410
	return $dhcpdconf;
1411
}
1412

    
1413
function services_dhcpdv6_configure($blacklist = array()) {
1414
	global $config, $g;
1415

    
1416
	if ($g['services_dhcp_server_enable'] == false) {
1417
		return;
1418
	}
1419

    
1420
	if (isset($config['system']['developerspew'])) {
1421
		$mt = microtime();
1422
		echo "services_dhcpd_configure($if) being called $mt\n";
1423
	}
1424

    
1425
	/* kill any running dhcpd */
1426
	if (isvalidpid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid")) {
1427
		killbypid("{$g['dhcpd_chroot_path']}{$g['varrun_path']}/dhcpdv6.pid");
1428
	}
1429
	if (isvalidpid("{$g['varrun_path']}/dhcpleases6.pid")) {
1430
		killbypid("{$g['varrun_path']}/dhcpleases6.pid");
1431
	}
1432

    
1433
	/* DHCP enabled on any interfaces? */
1434
	if (!is_dhcpv6_server_enabled()) {
1435
		return 0;
1436
	}
1437

    
1438
	$syscfg = $config['system'];
1439
	if (!is_array($config['dhcpdv6'])) {
1440
		$config['dhcpdv6'] = array();
1441
	}
1442
	$dhcpdv6cfg = $config['dhcpdv6'];
1443
	$Iflist = get_configured_interface_list();
1444
	$Iflist = array_merge($Iflist, get_configured_pppoe_server_interfaces());
1445

    
1446

    
1447
	if (platform_booting()) {
1448
		echo "Starting DHCPv6 service...";
1449
	} else {
1450
		sleep(1);
1451
	}
1452

    
1453
	$custoptionsv6 = "";
1454
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1455
		if (is_array($dhcpv6ifconf['numberoptions']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1456
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1457
				$custoptionsv6 .= "option custom-{$dhcpv6if}-{$itemv6idx} code {$itemv6['number']} = text;\n";
1458
			}
1459
		}
1460
	}
1461

    
1462
	if (isset($dhcpv6ifconf['netboot']) && !empty($dhcpv6ifconf['bootfile_url'])) {
1463
		$custoptionsv6 .= "option dhcp6.bootfile-url code 59 = string;\n";
1464
	}
1465

    
1466
	$dhcpdv6conf = <<<EOD
1467

    
1468
option domain-name "{$syscfg['domain']}";
1469
option ldap-server code 95 = text;
1470
option domain-search-list code 119 = text;
1471
{$custoptionsv6}
1472
default-lease-time 7200;
1473
max-lease-time 86400;
1474
log-facility local7;
1475
one-lease-per-client true;
1476
deny duplicates;
1477
ping-check true;
1478
update-conflict-detection false;
1479

    
1480
EOD;
1481

    
1482
	if (!isset($dhcpv6ifconf['disableauthoritative'])) {
1483
		$dhcpdv6conf .= "authoritative;\n";
1484
	}
1485

    
1486
	if (isset($dhcpv6ifconf['alwaysbroadcast'])) {
1487
		$dhcpdv6conf .= "always-broadcast on\n";
1488
	}
1489

    
1490
	$dhcpdv6ifs = array();
1491

    
1492
	$dhcpv6num = 0;
1493
	$nsupdate = false;
1494

    
1495
	foreach ($dhcpdv6cfg as $dhcpv6if => $dhcpv6ifconf) {
1496

    
1497
		$ddns_zones = array();
1498

    
1499
		$ifcfgv6 = $config['interfaces'][$dhcpv6if];
1500

    
1501
		if (!isset($dhcpv6ifconf['enable']) || !isset($Iflist[$dhcpv6if]) || !isset($ifcfgv6['enable'])) {
1502
			continue;
1503
		}
1504
		$ifcfgipv6 = get_interface_ipv6($dhcpv6if);
1505
		if (!is_ipaddrv6($ifcfgipv6)) {
1506
			continue;
1507
		}
1508
		$ifcfgsnv6 = get_interface_subnetv6($dhcpv6if);
1509
		$subnetv6 = gen_subnetv6($ifcfgipv6, $ifcfgsnv6);
1510
		// We might have some prefix-delegation on WAN (e.g. /48),
1511
		// but then it is split and given out to individual interfaces
1512
		// (LAN, OPT1, OPT2...) as multiple /64 subnets. So the size
1513
		// of each subnet here is always /64.
1514
		$pdlen = 64;
1515

    
1516
		$dnscfgv6 = "";
1517

    
1518
		if ($dhcpv6ifconf['domain']) {
1519
			$dnscfgv6 .= "	option domain-name \"{$dhcpv6ifconf['domain']}\";\n";
1520
		}
1521

    
1522
		if ($dhcpv6ifconf['domainsearchlist'] <> "") {
1523
			$dnscfgv6 .= "	option dhcp6.domain-search \"" . join("\",\"", preg_split("/[ ;]+/", $dhcpv6ifconf['domainsearchlist'])) . "\";\n";
1524
		}
1525

    
1526
		if (isset($dhcpv6ifconf['ddnsupdate'])) {
1527
			if ($dhcpv6ifconf['ddnsdomain'] <> "") {
1528
				$dnscfgv6 .= "	ddns-domainname \"{$dhcpv6ifconf['ddnsdomain']}\";\n";
1529
			}
1530
			if (empty($dhcpv6ifconf['ddnsclientupdates'])) {
1531
				$ddnsclientupdates = 'allow';
1532
			} else {
1533
				$ddnsclientupdates = $dhcpv6ifconf['ddnsclientupdates'];
1534
			}
1535
			$dnscfgv6 .= "	{$ddnsclientupdates} client-updates;\n";
1536
			$nsupdate = true;
1537
		} else {
1538
			$dnscfgv6 .= "	do-forward-updates false;\n";
1539
		}
1540

    
1541
		if ($dhcpv6ifconf['dhcp6c-dns'] != 'disabled') {
1542
			if (is_array($dhcpv6ifconf['dnsserver']) && ($dhcpv6ifconf['dnsserver'][0])) {
1543
				$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dhcpv6ifconf['dnsserver']) . ";\n";
1544
			} else if (((isset($config['dnsmasq']['enable'])) || isset($config['unbound']['enable'])) && (is_ipaddrv6($ifcfgipv6))) {
1545
				$dnscfgv6 .= "	option dhcp6.name-servers {$ifcfgipv6};\n";
1546
			} else if (is_array($syscfg['dnsserver']) && ($syscfg['dnsserver'][0])) {
1547
				$dns_arrv6 = array();
1548
				foreach ($syscfg['dnsserver'] as $dnsserver) {
1549
					if (is_ipaddrv6($dnsserver)) {
1550
						$dns_arrv6[] = $dnsserver;
1551
					}
1552
				}
1553
				if (!empty($dns_arrv6)) {
1554
					$dnscfgv6 .= "	option dhcp6.name-servers " . join(",", $dns_arrv6) . ";\n";
1555
				}
1556
			}
1557
		} else {
1558
			$dnscfgv6 .= "	#option dhcp6.name-servers --;\n";
1559
		}
1560

    
1561
		if (!is_ipaddrv6($ifcfgipv6)) {
1562
			$ifcfgsnv6 = "64";
1563
			$subnetv6 = gen_subnetv6($dhcpv6ifconf['range']['from'], $ifcfgsnv6);
1564
		}
1565

    
1566
		$dhcpdv6conf .= "subnet6 {$subnetv6}/{$ifcfgsnv6}";
1567

    
1568
		if (isset($dhcpv6ifconf['ddnsupdate']) &&
1569
		    !empty($dhcpv6ifconf['ddnsdomain'])) {
1570
			$newzone = array();
1571
			$newzone['domain-name'] = $dhcpv6ifconf['ddnsdomain'];
1572
			$newzone['dns-servers'] = array($dhcpv6ifconf['ddnsdomainprimary'], $dhcpv6ifconf['ddnsdomainsecondary']);
1573
			$newzone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1574
			$newzone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1575
			$ddns_zones[] = $newzone;
1576
			if (isset($dhcpv6ifconf['ddnsreverse'])) {
1577
				$ptr_zones = get_v6_ptr_zones($subnetv6, $ifcfgsnv6);
1578
				foreach ($ptr_zones as $ptr_zone) {
1579
					$reversezone = array();
1580
					$reversezone['ptr-domain'] = $ptr_zone;
1581
					$reversezone['dns-servers'] = array($dhcpv6ifconf['ddnsdomainprimary'], $dhcpv6ifconf['ddnsdomainsecondary']);
1582
					$reversezone['ddnsdomainkeyname'] = $dhcpv6ifconf['ddnsdomainkeyname'];
1583
					$reversezone['ddnsdomainkey'] = $dhcpv6ifconf['ddnsdomainkey'];
1584
					$ddns_zones[] = $reversezone;
1585
				}
1586
			}
1587
		}
1588

    
1589
		$dhcpdv6conf .= " {\n";
1590

    
1591
		$range_from = $dhcpv6ifconf['range']['from'];
1592
		$range_to = $dhcpv6ifconf['range']['to'];
1593
		if ($ifcfgv6['ipaddrv6'] == 'track6') {
1594
			$range_from = merge_ipv6_delegated_prefix($ifcfgipv6, $range_from, $pdlen);
1595
			$range_to = merge_ipv6_delegated_prefix($ifcfgipv6, $range_to, $pdlen);
1596
		}
1597

    
1598
		if (!empty($dhcpv6ifconf['range']['from']) && !empty($dhcpv6ifconf['range']['to'])) {
1599
			$dhcpdv6conf .= "	range6 {$range_from} {$range_to};\n";
1600
		}
1601

    
1602
		$dhcpdv6conf .= $dnscfgv6;
1603

    
1604
		if (is_ipaddrv6($dhcpv6ifconf['prefixrange']['from']) && is_ipaddrv6($dhcpv6ifconf['prefixrange']['to'])) {
1605
			$dhcpdv6conf .= "	prefix6 {$dhcpv6ifconf['prefixrange']['from']} {$dhcpv6ifconf['prefixrange']['to']} /{$dhcpv6ifconf['prefixrange']['prefixlength']};\n";
1606
		}
1607
		if (is_ipaddrv6($dhcpv6ifconf['dns6ip'])) {
1608
			$dns6ip = $dhcpv6ifconf['dns6ip'];
1609
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1610
			    Net_IPv6::isInNetmask($dns6ip, '::', $pdlen)) {
1611
				$dns6ip = merge_ipv6_delegated_prefix($ifcfgipv6, $dns6ip, $pdlen);
1612
			}
1613
			$dhcpdv6conf .= "	option dhcp6.name-servers {$dns6ip};\n";
1614
		}
1615
		// default-lease-time
1616
		if ($dhcpv6ifconf['defaultleasetime']) {
1617
			$dhcpdv6conf .= "	default-lease-time {$dhcpv6ifconf['defaultleasetime']};\n";
1618
		}
1619

    
1620
		// max-lease-time
1621
		if ($dhcpv6ifconf['maxleasetime']) {
1622
			$dhcpdv6conf .= "	max-lease-time {$dhcpv6ifconf['maxleasetime']};\n";
1623
		}
1624

    
1625
		// ntp-servers
1626
		if (is_array($dhcpv6ifconf['ntpserver']) && $dhcpv6ifconf['ntpserver'][0]) {
1627
			$ntpservers = array();
1628
			foreach ($dhcpv6ifconf['ntpserver'] as $ntpserver) {
1629
				if (!is_ipaddrv6($ntpserver)) {
1630
					continue;
1631
				}
1632
				if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1633
				    Net_IPv6::isInNetmask($ntpserver, '::', $pdlen)) {
1634
					$ntpserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ntpserver, $pdlen);
1635
				}
1636
				$ntpservers[] = $ntpserver;
1637
			}
1638
			if (count($ntpservers) > 0) {
1639
				$dhcpdv6conf .= "        option dhcp6.sntp-servers " . join(",", $dhcpv6ifconf['ntpserver']) . ";\n";
1640
			}
1641
		}
1642
		// tftp-server-name
1643
		/* Needs ISC DHCPD support
1644
		 if ($dhcpv6ifconf['tftp'] <> "") {
1645
			$dhcpdv6conf .= "	option tftp-server-name \"{$dhcpv6ifconf['tftp']}\";\n";
1646
		 }
1647
		*/
1648

    
1649
		// Handle option, number rowhelper values
1650
		$dhcpdv6conf .= "\n";
1651
		if (isset($dhcpv6ifconf['numberoptions']['item']) && is_array($dhcpv6ifconf['numberoptions']['item'])) {
1652
			foreach ($dhcpv6ifconf['numberoptions']['item'] as $itemv6idx => $itemv6) {
1653
				$itemv6_value = base64_decode($itemv6['value']);
1654
				$dhcpdv6conf .= "	option custom-{$dhcpv6if}-{$itemv6idx} \"{$itemv6_value}\";\n";
1655
			}
1656
		}
1657

    
1658
		// ldap-server
1659
		if ($dhcpv6ifconf['ldap'] <> "") {
1660
			$ldapserver = $dhcpv6ifconf['ldap'];
1661
			if ($ifcfgv6['ipaddrv6'] == 'track6' &&
1662
			    Net_IPv6::isInNetmask($ldapserver, '::', $pdlen)) {
1663
				$ldapserver = merge_ipv6_delegated_prefix($ifcfgipv6, $ldapserver, $pdlen);
1664
			}
1665
			$dhcpdv6conf .= "	option ldap-server \"{$ldapserver}\";\n";
1666
		}
1667

    
1668
		// net boot information
1669
		if (isset($dhcpv6ifconf['netboot'])) {
1670
			if (!empty($dhcpv6ifconf['bootfile_url'])) {
1671
				$dhcpdv6conf .= "	option dhcp6.bootfile-url \"{$dhcpv6ifconf['bootfile_url']}\";\n";
1672
			}
1673
		}
1674

    
1675
		$dhcpdv6conf .= "}\n";
1676

    
1677
		/* add static mappings */
1678
		/* Needs to use DUID */
1679
		if (is_array($dhcpv6ifconf['staticmap'])) {
1680
			$i = 0;
1681
			foreach ($dhcpv6ifconf['staticmap'] as $sm) {
1682
				$dhcpdv6conf .= <<<EOD
1683
host s_{$dhcpv6if}_{$i} {
1684
	host-identifier option dhcp6.client-id {$sm['duid']};
1685

    
1686
EOD;
1687
				if ($sm['ipaddrv6']) {
1688
					$ipaddrv6 = $sm['ipaddrv6'];
1689
					if ($ifcfgv6['ipaddrv6'] == 'track6') {
1690
						$ipaddrv6 = merge_ipv6_delegated_prefix($ifcfgipv6, $ipaddrv6, $pdlen);
1691
					}
1692
					$dhcpdv6conf .= "	fixed-address6 {$ipaddrv6};\n";
1693
				}
1694

    
1695
				if ($sm['hostname']) {
1696
					$dhhostname = str_replace(" ", "_", $sm['hostname']);
1697
					$dhhostname = str_replace(".", "_", $dhhostname);
1698
					$dhcpdv6conf .= "	option host-name {$dhhostname};\n";
1699
					if (isset($dhcpv6ifconf['ddnsupdate']) &&
1700
					    isset($dhcpv6ifconf['ddnsforcehostname'])) {
1701
						$dhcpdv6conf .= "	ddns-hostname \"{$dhhostname}\";\n";
1702
					}
1703
				}
1704
				if ($sm['filename']) {
1705
					$dhcpdv6conf .= "	filename \"{$sm['filename']}\";\n";
1706
				}
1707

    
1708
				if ($sm['rootpath']) {
1709
					$dhcpdv6conf .= "	option root-path \"{$sm['rootpath']}\";\n";
1710
				}
1711

    
1712
				$dhcpdv6conf .= "}\n";
1713
				$i++;
1714
			}
1715
		}
1716

    
1717
		if ($dhcpv6ifconf['ddnsdomain']) {
1718
			$dhcpdv6conf .= dhcpdkey($dhcpv6ifconf);
1719
			$dhcpdv6conf .= dhcpdzones($ddns_zones);
1720
		}
1721

    
1722
		if ($config['dhcpdv6'][$dhcpv6if]['ramode'] <> "unmanaged" && isset($config['interfaces'][$dhcpv6if]['enable'])) {
1723
			if (preg_match("/poes/si", $dhcpv6if)) {
1724
				/* magic here */
1725
				$dhcpdv6ifs = array_merge($dhcpdv6ifs, get_pppoes_child_interfaces($dhcpv6if));
1726
			} else {
1727
				$realif = get_real_interface($dhcpv6if, "inet6");
1728
				if (stristr("$realif", "bridge")) {
1729
					$mac = get_interface_mac($realif);
1730
					$v6address = generate_ipv6_from_mac($mac);
1731
					/* Create link local address for bridges */
1732
					mwexec("/sbin/ifconfig {$realif} inet6 {$v6address}");
1733
				}
1734
				$realif = escapeshellcmd($realif);
1735
				$dhcpdv6ifs[] = $realif;
1736
			}
1737
		}
1738
	}
1739

    
1740
	if ($nsupdate) {
1741
		$dhcpdv6conf .= "ddns-update-style interim;\n";
1742
		$dhcpdv6conf .= "update-static-leases on;\n";
1743
	} else {
1744
		$dhcpdv6conf .= "ddns-update-style none;\n";
1745
	}
1746

    
1747
	/* write dhcpdv6.conf */
1748
	if (!@file_put_contents("{$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf", $dhcpdv6conf)) {
1749
		log_error("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1750
		if (platform_booting()) {
1751
			printf("Error: cannot open {$g['dhcpd_chroot_path']}/etc/dhcpdv6.conf in services_dhcpdv6_configure().\n");
1752
		}
1753
		unset($dhcpdv6conf);
1754
		return 1;
1755
	}
1756
	unset($dhcpdv6conf);
1757

    
1758
	/* create an empty leases v6 database */
1759
	if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases")) {
1760
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd6.leases");
1761
	}
1762

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

    
1767
	/* fire up dhcpd in a chroot */
1768
	if (count($dhcpdv6ifs) > 0) {
1769
		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 " .
1770
			join(" ", $dhcpdv6ifs));
1771
		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");
1772
	}
1773
	if (platform_booting()) {
1774
		print gettext("done.") . "\n";
1775
	}
1776

    
1777
	return 0;
1778
}
1779

    
1780
function services_igmpproxy_configure() {
1781
	global $config, $g;
1782

    
1783
	/* kill any running igmpproxy */
1784
	killbyname("igmpproxy");
1785

    
1786
	if (!isset($config['igmpproxy']['enable'])) {
1787
		return 0;
1788
	}
1789
	if (!is_array($config['igmpproxy']['igmpentry']) || (count($config['igmpproxy']['igmpentry']) == 0)) {
1790
		return 1;
1791
	}
1792

    
1793
	$iflist = get_configured_interface_list();
1794

    
1795
	$igmpconf = <<<EOD
1796

    
1797
##------------------------------------------------------
1798
## Enable Quickleave mode (Sends Leave instantly)
1799
##------------------------------------------------------
1800
quickleave
1801

    
1802
EOD;
1803

    
1804
	foreach ($config['igmpproxy']['igmpentry'] as $igmpcf) {
1805
		unset($iflist[$igmpcf['ifname']]);
1806
		$realif = get_real_interface($igmpcf['ifname']);
1807
		if (empty($igmpcf['threshold'])) {
1808
			$threshld = 1;
1809
		} else {
1810
			$threshld = $igmpcf['threshold'];
1811
		}
1812
		$igmpconf .= "phyint {$realif} {$igmpcf['type']} ratelimit 0 threshold {$threshld}\n";
1813

    
1814
		if ($igmpcf['address'] <> "") {
1815
			$item = explode(" ", $igmpcf['address']);
1816
			foreach ($item as $iww) {
1817
				$igmpconf .= "altnet {$iww}\n";
1818
			}
1819
		}
1820
		$igmpconf .= "\n";
1821
	}
1822
	foreach ($iflist as $ifn) {
1823
		$realif = get_real_interface($ifn);
1824
		$igmpconf .= "phyint {$realif} disabled\n";
1825
	}
1826
	$igmpconf .= "\n";
1827

    
1828
	$igmpfl = fopen($g['varetc_path'] . "/igmpproxy.conf", "w");
1829
	if (!$igmpfl) {
1830
		log_error(gettext("Could not write Igmpproxy configuration file!"));
1831
		return;
1832
	}
1833
	fwrite($igmpfl, $igmpconf);
1834
	fclose($igmpfl);
1835
	unset($igmpconf);
1836

    
1837
	if (isset($config['syslog']['igmpxverbose'])) {
1838
		mwexec_bg("/usr/local/sbin/igmpproxy -v {$g['varetc_path']}/igmpproxy.conf");
1839
	} else {
1840
		mwexec_bg("/usr/local/sbin/igmpproxy {$g['varetc_path']}/igmpproxy.conf");
1841
	}
1842

    
1843
	log_error(gettext("Started IGMP proxy service."));
1844

    
1845
	return 0;
1846
}
1847

    
1848
function services_dhcrelay_configure() {
1849
	global $config, $g;
1850

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

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

    
1859
	init_config_arr(array('dhcrelay'));
1860
	$dhcrelaycfg = &$config['dhcrelay'];
1861

    
1862
	/* DHCPRelay enabled on any interfaces? */
1863
	if (!isset($dhcrelaycfg['enable'])) {
1864
		return 0;
1865
	}
1866

    
1867
	if (platform_booting()) {
1868
		echo gettext("Starting DHCP relay service...");
1869
	} else {
1870
		sleep(1);
1871
	}
1872

    
1873
	$iflist = get_configured_interface_list();
1874

    
1875
	$dhcrelayifs = array();
1876
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1877
	foreach ($dhcifaces as $dhcrelayif) {
1878
		if (!isset($iflist[$dhcrelayif])) {
1879
			continue;
1880
		}
1881

    
1882
		if (get_interface_ip($dhcrelayif)) {
1883
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1884
		}
1885
	}
1886
	$dhcrelayifs = array_unique($dhcrelayifs);
1887

    
1888
	/*
1889
	 * In order for the relay to work, it needs to be active
1890
	 * on the interface in which the destination server sits.
1891
	 */
1892
	$srvips = explode(",", $dhcrelaycfg['server']);
1893
	if (!is_array($srvips)) {
1894
		log_error(gettext("No destination IP has been configured!"));
1895
		return;
1896
	}
1897
	$srvifaces = array();
1898
	foreach ($srvips as $srcidx => $srvip) {
1899
		$destif = guess_interface_from_ip($srvip);
1900
		if (!empty($destif) && !is_pseudo_interface($destif)) {
1901
			$srvifaces[] = $destif;
1902
		}
1903
	}
1904
	$srvifaces = array_unique($srvifaces);
1905

    
1906
	/* Check for relays in the same subnet as clients so they can bind for
1907
	 * either direction (up or down) */
1908
	$srvrelayifs = array_intersect($dhcrelayifs, $srvifaces);
1909

    
1910
	/* The server interface(s) should not be in this list */
1911
	$dhcrelayifs = array_diff($dhcrelayifs, $srvifaces);
1912

    
1913
	/* Remove the dual-role interfaces from up and down lists */
1914
	$srvifaces = array_diff($srvifaces, $srvrelayifs);
1915
	$dhcrelayifs = array_diff($dhcrelayifs, $srvrelayifs);
1916

    
1917
	/* fire up dhcrelay */
1918
	if (empty($dhcrelayifs) && empty($srvrelayifs)) {
1919
		log_error(gettext("No suitable downstream interfaces found for running dhcrelay!"));
1920
		return; /* XXX */
1921
	}
1922
	if (empty($srvifaces) && empty($srvrelayifs)) {
1923
		log_error(gettext("No suitable upstream interfaces found for running dhcrelay!"));
1924
		return; /* XXX */
1925
	}
1926

    
1927
	$cmd = "/usr/local/sbin/dhcrelay";
1928

    
1929
	if (!empty($dhcrelayifs)) {
1930
		$cmd .= " -id " . implode(" -id ", $dhcrelayifs);
1931
	}
1932
	if (!empty($srvifaces)) {
1933
		$cmd .= " -iu " . implode(" -iu ", $srvifaces);
1934
	}
1935
	if (!empty($srvrelayifs)) {
1936
		$cmd .= " -i " . implode(" -i ", $srvrelayifs);
1937
	}
1938

    
1939
	if (isset($dhcrelaycfg['agentoption'])) {
1940
		$cmd .= " -a -m replace";
1941
	}
1942

    
1943
	$cmd .= " " . implode(" ", $srvips);
1944
	mwexec($cmd);
1945
	unset($cmd);
1946

    
1947
	return 0;
1948
}
1949

    
1950
function services_dhcrelay6_configure() {
1951
	global $config, $g;
1952

    
1953
	if (isset($config['system']['developerspew'])) {
1954
		$mt = microtime();
1955
		echo "services_dhcrelay6_configure() being called $mt\n";
1956
	}
1957

    
1958
	/* kill any running dhcrelay */
1959
	killbypid("{$g['varrun_path']}/dhcrelay6.pid");
1960

    
1961
	init_config_arr(array('dhcrelay6'));
1962
	$dhcrelaycfg = &$config['dhcrelay6'];
1963

    
1964
	/* DHCPv6 Relay enabled on any interfaces? */
1965
	if (!isset($dhcrelaycfg['enable'])) {
1966
		return 0;
1967
	}
1968

    
1969
	if (platform_booting()) {
1970
		echo gettext("Starting DHCPv6 relay service...");
1971
	} else {
1972
		sleep(1);
1973
	}
1974

    
1975
	$iflist = get_configured_interface_list();
1976

    
1977
	$dhcifaces = explode(",", $dhcrelaycfg['interface']);
1978
	foreach ($dhcifaces as $dhcrelayif) {
1979
		if (!isset($iflist[$dhcrelayif])) {
1980
			continue;
1981
		}
1982

    
1983
		if (get_interface_ipv6($dhcrelayif)) {
1984
			$dhcrelayifs[] = get_real_interface($dhcrelayif);
1985
		}
1986
	}
1987
	$dhcrelayifs = array_unique($dhcrelayifs);
1988

    
1989
	/*
1990
	 * In order for the relay to work, it needs to be active
1991
	 * on the interface in which the destination server sits.
1992
	 */
1993
	$srvips = explode(",", $dhcrelaycfg['server']);
1994
	$srvifaces = array();
1995
	foreach ($srvips as $srcidx => $srvip) {
1996
		$destif = guess_interface_from_ip($srvip);
1997
		if (!empty($destif) && !is_pseudo_interface($destif)) {
1998
			$srvifaces[] = "{$srvip}%{$destif}";
1999
		}
2000
	}
2001

    
2002
	/* fire up dhcrelay */
2003
	if (empty($dhcrelayifs) || empty($srvifaces)) {
2004
		log_error(gettext("No suitable interface found for running dhcrelay -6!"));
2005
		return; /* XXX */
2006
	}
2007

    
2008
	$cmd = "/usr/local/sbin/dhcrelay -6 -pf \"{$g['varrun_path']}/dhcrelay6.pid\"";
2009
	foreach ($dhcrelayifs as $dhcrelayif) {
2010
		$cmd .= " -l {$dhcrelayif}";
2011
	}
2012
	foreach ($srvifaces as $srviface) {
2013
		$cmd .= " -u \"{$srviface}\"";
2014
	}
2015
	mwexec($cmd);
2016
	unset($cmd);
2017

    
2018
	return 0;
2019
}
2020

    
2021
function services_dyndns_configure_client($conf) {
2022

    
2023
	if (!isset($conf['enable'])) {
2024
		return;
2025
	}
2026

    
2027
	/* load up the dyndns.class */
2028
	require_once("dyndns.class");
2029

    
2030
	$dns = new updatedns($dnsService = $conf['type'],
2031
		$dnsHost = $conf['host'],
2032
		$dnsDomain = $conf['domainname'],
2033
		$dnsUser = $conf['username'],
2034
		$dnsPass = $conf['password'],
2035
		$dnsWildcard = $conf['wildcard'],
2036
		$dnsProxied = $conf['proxied'],
2037
		$dnsMX = $conf['mx'],
2038
		$dnsIf = "{$conf['interface']}",
2039
		$dnsBackMX = NULL,
2040
		$dnsServer = NULL,
2041
		$dnsPort = NULL,
2042
		$dnsUpdateURL = "{$conf['updateurl']}",
2043
		$forceUpdate = $conf['force'],
2044
		$dnsZoneID = $conf['zoneid'],
2045
		$dnsTTL = $conf['ttl'],
2046
		$dnsResultMatch = "{$conf['resultmatch']}",
2047
		$dnsRequestIf = "{$conf['requestif']}",
2048
		$dnsID = "{$conf['id']}",
2049
		$dnsVerboseLog = $conf['verboselog'],
2050
		$curlIpresolveV4 = $conf['curl_ipresolve_v4'],
2051
		$curlSslVerifypeer = $conf['curl_ssl_verifypeer']);
2052
}
2053

    
2054
function services_dyndns_configure($int = "") {
2055
	global $config, $g;
2056
	if (isset($config['system']['developerspew'])) {
2057
		$mt = microtime();
2058
		echo "services_dyndns_configure() being called $mt\n";
2059
	}
2060

    
2061
	if (isset($config['dyndnses']['dyndns']) && is_array($config['dyndnses']['dyndns'])) {
2062
		$dyndnscfg = $config['dyndnses']['dyndns'];
2063
	} else {
2064
		return 0;
2065
	}
2066
	$gwgroups = return_gateway_groups_array(true);
2067
	if (is_array($dyndnscfg)) {
2068
		if (platform_booting()) {
2069
			echo gettext("Starting DynDNS clients...");
2070
		}
2071

    
2072
		foreach ($dyndnscfg as $dyndns) {
2073
			/*
2074
			 * If it's using a gateway group, check if interface is
2075
			 * the active gateway for that group
2076
			 */
2077
			$group_int = '';
2078
			$friendly_group_int = '';
2079
			$gwgroup_member = false;
2080
			if (is_array($gwgroups[$dyndns['interface']])) {
2081
				if (!empty($gwgroups[$dyndns['interface']][0]['vip'])) {
2082
					$group_int = $gwgroups[$dyndns['interface']][0]['vip'];
2083
				} else {
2084
					$group_int = $gwgroups[$dyndns['interface']][0]['int'];
2085
					$friendly_group_int =
2086
					    convert_real_interface_to_friendly_interface_name(
2087
						$group_int);
2088
					if (!empty($int)) {
2089
						$gwgroup_member =
2090
						    interface_gateway_group_member(get_real_interface($int),
2091
						    $dyndns['interface']);
2092
					}
2093
				}
2094
			}
2095
			if ((empty($int)) || ($int == $dyndns['interface']) || $gwgroup_member ||
2096
			    ($int == $group_int) || ($int == $friendly_group_int)) {
2097
				$dyndns['verboselog'] = isset($dyndns['verboselog']);
2098
				$dyndns['curl_ipresolve_v4'] = isset($dyndns['curl_ipresolve_v4']);
2099
				$dyndns['curl_ssl_verifypeer'] = isset($dyndns['curl_ssl_verifypeer']);
2100
				$dyndns['proxied'] = isset($dyndns['proxied']);
2101
				services_dyndns_configure_client($dyndns);
2102
				sleep(1);
2103
			}
2104
		}
2105

    
2106
		if (platform_booting()) {
2107
			echo gettext("done.") . "\n";
2108
		}
2109
	}
2110

    
2111
	return 0;
2112
}
2113

    
2114
function dyndnsCheckIP($int) {
2115
	global $config, $factory_default_checkipservice;
2116
	$ip_address = get_interface_ip($int);
2117
	if (is_private_ip($ip_address)) {
2118
		$gateways_status = return_gateways_status(true);
2119
		// If the gateway for this interface is down, then the external check cannot work.
2120
		// Avoid the long wait for the external check to timeout.
2121
		if (stristr($gateways_status[$config['interfaces'][$int]['gateway']]['status'], "down")) {
2122
			return "down";
2123
		}
2124

    
2125
		// Append the factory default check IP service to the list (if not disabled).
2126
		if (!isset($config['checkipservices']['disable_factory_default'])) {
2127
			if (!is_array($config['checkipservices'])) {
2128
				$config['checkipservices'] = array();
2129
			}
2130
			if (!is_array($config['checkipservices']['checkipservice'])) {
2131
				$config['checkipservices']['checkipservice'] = array();
2132
			}
2133
			$config['checkipservices']['checkipservice'][] = $factory_default_checkipservice;
2134
		}
2135

    
2136
		// Use the first enabled check IP service as the default.
2137
		if (is_array($config['checkipservices']['checkipservice'])) {
2138
			foreach ($config['checkipservices']['checkipservice'] as $i => $checkipservice) {
2139
				if (isset($checkipservice['enable'])) {
2140
					$url = $checkipservice['url'];
2141
					$username = $checkipservice['username'];
2142
					$password = $checkipservice['password'];
2143
					$verifysslpeer = isset($checkipservice['verifysslpeer']);
2144
					break;
2145
				}
2146
			}
2147
		}
2148

    
2149
		$hosttocheck = $url;
2150
		$ip_ch = curl_init($hosttocheck);
2151
		curl_setopt($ip_ch, CURLOPT_RETURNTRANSFER, 1);
2152
		curl_setopt($ip_ch, CURLOPT_SSL_VERIFYPEER, $verifysslpeer);
2153
		curl_setopt($ip_ch, CURLOPT_INTERFACE, 'host!' . $ip_address);
2154
		curl_setopt($ip_ch, CURLOPT_CONNECTTIMEOUT, '30');
2155
		curl_setopt($ip_ch, CURLOPT_TIMEOUT, 120);
2156
		curl_setopt($ip_ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
2157
		curl_setopt($ip_ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
2158
		curl_setopt($ip_ch, CURLOPT_USERPWD, "{$username}:{$password}");
2159
		$ip_result_page = curl_exec($ip_ch);
2160
		curl_close($ip_ch);
2161
		$ip_result_decoded = urldecode($ip_result_page);
2162
		preg_match('=Current IP Address: (.*)</body>=siU', $ip_result_decoded, $matches);
2163
		$ip_address = trim($matches[1]);
2164
	}
2165
	return $ip_address;
2166
}
2167

    
2168
function services_dnsmasq_configure($restart_dhcp = true) {
2169
	global $config, $g;
2170
	$return = 0;
2171

    
2172
	// hard coded args: will be removed to avoid duplication if specified in custom_options
2173
	$standard_args = array(
2174
		"dns-forward-max" => "--dns-forward-max=5000",
2175
		"cache-size" => "--cache-size=10000",
2176
		"local-ttl" => "--local-ttl=1"
2177
	);
2178

    
2179

    
2180
	if (isset($config['system']['developerspew'])) {
2181
		$mt = microtime();
2182
		echo "services_dnsmasq_configure() being called $mt\n";
2183
	}
2184

    
2185
	/* kill any running dnsmasq */
2186
	if (file_exists("{$g['varrun_path']}/dnsmasq.pid")) {
2187
		sigkillbypid("{$g['varrun_path']}/dnsmasq.pid", "TERM");
2188
	}
2189

    
2190
	if (isset($config['dnsmasq']['enable'])) {
2191

    
2192
		if (platform_booting()) {
2193
			echo gettext("Starting DNS forwarder...");
2194
		} else {
2195
			sleep(1);
2196
		}
2197

    
2198
		/* generate hosts file */
2199
		if (system_hosts_generate() != 0) {
2200
			$return = 1;
2201
		}
2202

    
2203
		$args = "";
2204

    
2205
		if (isset($config['dnsmasq']['regdhcp'])) {
2206
			$args .= " --dhcp-hostsfile={$g['etc_path']}/hosts ";
2207
		}
2208

    
2209
		/* Setup listen port, if non-default */
2210
		if (is_port($config['dnsmasq']['port'])) {
2211
			$args .= " --port={$config['dnsmasq']['port']} ";
2212
		}
2213

    
2214
		$listen_addresses = "";
2215
		if (isset($config['dnsmasq']['interface'])) {
2216
			$interfaces = explode(",", $config['dnsmasq']['interface']);
2217
			foreach ($interfaces as $interface) {
2218
				$if = get_real_interface($interface);
2219
				if (does_interface_exist($if)) {
2220
					$laddr = get_interface_ip($interface);
2221
					if (is_ipaddrv4($laddr)) {
2222
						$listen_addresses .= " --listen-address={$laddr} ";
2223
					}
2224
					$laddr6 = get_interface_ipv6($interface);
2225
					if (is_ipaddrv6($laddr6) && !isset($config['dnsmasq']['strictbind'])) {
2226
						/*
2227
						 * XXX: Since dnsmasq does not support link-local address
2228
						 * with scope specified. These checks are being done.
2229
						 */
2230
						if (is_linklocal($laddr6) && strstr($laddr6, "%")) {
2231
							$tmpaddrll6 = explode("%", $laddr6);
2232
							$listen_addresses .= " --listen-address={$tmpaddrll6[0]} ";
2233
						} else {
2234
							$listen_addresses .= " --listen-address={$laddr6} ";
2235
						}
2236
					}
2237
				}
2238
			}
2239
			if (!empty($listen_addresses)) {
2240
				$args .= " {$listen_addresses} ";
2241
				if (isset($config['dnsmasq']['strictbind'])) {
2242
					$args .= " --bind-interfaces ";
2243
				}
2244
			}
2245
		}
2246

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

    
2254
			// Build an array of domain overrides to help in checking for matches.
2255
			$override_a = array();
2256
			if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2257
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2258
					$override_a[$override['domain']] = "y";
2259
				}
2260
			}
2261

    
2262
			// Build an array of the private reverse lookup domain names
2263
			$reverse_domain_a = array("10.in-addr.arpa", "168.192.in-addr.arpa");
2264
			// Unfortunately the 172.16.0.0/12 range does not map nicely to the in-addr.arpa scheme.
2265
			for ($subnet_num = 16; $subnet_num < 32; $subnet_num++) {
2266
				$reverse_domain_a[] = "$subnet_num.172.in-addr.arpa";
2267
			}
2268

    
2269
			// Set the --server parameter to nowhere for each reverse domain name that was not specifically specified in a domain override.
2270
			foreach ($reverse_domain_a as $reverse_domain) {
2271
				if (!isset($override_a[$reverse_domain])) {
2272
					$args .= " --server=/$reverse_domain/ ";
2273
				}
2274
			}
2275
			unset($override_a);
2276
			unset($reverse_domain_a);
2277
		}
2278

    
2279
		/* Setup forwarded domains */
2280
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2281
			foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2282
				if ($override['ip'] == "!") {
2283
					$override[ip] = "";
2284
				}
2285
				$args .= ' --server=/' . $override['domain'] . '/' . $override['ip'];
2286
			}
2287
		}
2288

    
2289
		/* Allow DNS Rebind for forwarded domains */
2290
		if (isset($config['dnsmasq']['domainoverrides']) && is_array($config['dnsmasq']['domainoverrides'])) {
2291
			if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2292
				foreach ($config['dnsmasq']['domainoverrides'] as $override) {
2293
					$args .= ' --rebind-domain-ok=/' . $override['domain'] . '/ ';
2294
				}
2295
			}
2296
		}
2297

    
2298
		if (!isset($config['system']['webgui']['nodnsrebindcheck'])) {
2299
			$dns_rebind = "--rebind-localhost-ok --stop-dns-rebind";
2300
		}
2301

    
2302
		if (isset($config['dnsmasq']['strict_order'])) {
2303
			$args .= " --strict-order ";
2304
		}
2305

    
2306
		if (isset($config['dnsmasq']['domain_needed'])) {
2307
			$args .= " --domain-needed ";
2308
		}
2309

    
2310
		if ($config['dnsmasq']['custom_options']) {
2311
			foreach (preg_split('/\s+/', $config['dnsmasq']['custom_options']) as $c) {
2312
				$args .= " " . escapeshellarg("--{$c}");
2313
				$p = explode('=', $c);
2314
				if (array_key_exists($p[0], $standard_args)) {
2315
					unset($standard_args[$p[0]]);
2316
				}
2317
			}
2318
		}
2319
		$args .= ' ' . implode(' ', array_values($standard_args));
2320

    
2321
		/* run dnsmasq. Use "-C /dev/null" since we use command line args only (Issue #6730) */
2322
		$cmd = "/usr/local/sbin/dnsmasq --all-servers -C /dev/null {$dns_rebind} {$args}";
2323
		//log_error("dnsmasq command: {$cmd}");
2324
		mwexec_bg($cmd);
2325
		unset($args);
2326

    
2327
		system_dhcpleases_configure();
2328

    
2329
		if (platform_booting()) {
2330
			echo gettext("done.") . "\n";
2331
		}
2332
	}
2333

    
2334
	if (!platform_booting() && $restart_dhcp) {
2335
		if (services_dhcpd_configure() != 0) {
2336
			$return = 1;
2337
		}
2338
	}
2339

    
2340
	return $return;
2341
}
2342

    
2343
function services_unbound_configure($restart_dhcp = true) {
2344
	global $config, $g;
2345
	$return = 0;
2346

    
2347
	if (isset($config['system']['developerspew'])) {
2348
		$mt = microtime();
2349
		echo "services_unbound_configure() being called $mt\n";
2350
	}
2351

    
2352
	if (isset($config['unbound']['enable'])) {
2353
		require_once('/etc/inc/unbound.inc');
2354

    
2355
		/* Stop Unbound using TERM */
2356
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2357
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "TERM");
2358
		}
2359

    
2360
		/* If unbound is still running, wait up to 30 seconds for it to terminate. */
2361
		for ($i=1; $i <= 30; $i++) {
2362
			if (is_process_running('unbound')) {
2363
				sleep(1);
2364
			}
2365
		}
2366

    
2367
		$python_mode = false;
2368
		if (isset($config['unbound']['python']) && !empty($config['unbound']['python_script'])) {
2369
			$python_mode = true;
2370
		}
2371

    
2372
		/* Include any additional functions as defined by python script include file */
2373
		if (file_exists("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc")) {
2374
			exec("/usr/local/bin/php -l " . escapeshellarg("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc")
2375
				. " 2>&1", $py_output, $py_retval);
2376
			if ($py_retval == 0) {
2377
				require_once("{$g['unbound_chroot_path']}/{$config['unbound']['python_script']}_include.inc");
2378
			}
2379
		}
2380

    
2381
		/* DNS Resolver python integration */
2382
		if ($python_mode) {
2383
			if (!is_dir("{$g['unbound_chroot_path']}/dev")) {
2384
				safe_mkdir("{$g['unbound_chroot_path']}/dev");
2385
			}
2386
			exec("/sbin/mount -t devfs devfs " . escapeshellarg("{$g['unbound_chroot_path']}/dev"));
2387
		} else {
2388
			if (is_dir("{$g['unbound_chroot_path']}/dev")) {
2389
				exec("/sbin/umount -f " . escapeshellarg("{$g['unbound_chroot_path']}/dev"));
2390
			}
2391
		}
2392
		$base_folder = '/usr/local';
2393
		foreach (array('/bin', '/lib') as $dir) {
2394
			$validate = exec("/sbin/mount | /usr/bin/grep " . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir} (nullfs") . " 2>&1");
2395
			if ($python_mode) {
2396

    
2397
				// Add DNS Resolver python integration
2398
				if (empty($validate)) {
2399
					if (!is_dir("{$g['unbound_chroot_path']}{$base_folder}{$dir}")) {
2400
						safe_mkdir("{$g['unbound_chroot_path']}{$base_folder}{$dir}");
2401
					}
2402
					$output = $retval = '';
2403
					exec("/sbin/mount_nullfs -o ro " . escapeshellarg("/usr/local{$dir}") . ' '
2404
					    . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir}") . " 2>&1", $output, $retval);
2405

    
2406
					// Disable Unbound python on mount failure
2407
					if ($retval != 0) {
2408
						$config['unbound']['python'] = '';
2409
						$log_msg = "[Unbound-pymod]: Disabling Unbound python due to failed mount";
2410
						write_config($log_msg);
2411
						log_error($log_msg);
2412
					}
2413
				}
2414
			}
2415

    
2416
			// Remove DNS Resolver python integration
2417
			elseif (!empty($validate)) {
2418
				exec("/sbin/umount -t nullfs " . escapeshellarg("{$g['unbound_chroot_path']}{$base_folder}{$dir}") . " 2>&1", $output, $retval);
2419
				if ($retval == 0) {
2420
					foreach (array( "/usr/local{$dir}", '/usr/local', '/usr') as $folder) {
2421
						if (!empty($g['unbound_chroot_path']) && $g['unbound_chroot_path'] != '/' && is_dir("{$g['unbound_chroot_path']}{$folder}")) {
2422
							@rmdir(escapeshellarg("{$g['unbound_chroot_path']}{$folder}"));
2423
						}
2424

    
2425
						// Delete remaining subfolders on next loop
2426
						if ($dir == '/bin') {
2427
							break;
2428
						}
2429
					}
2430
				}
2431
				else {
2432
					log_error("[Unbound-pymod]: Failed to unmount!");
2433
				}
2434
			}
2435
		}
2436

    
2437
		if (platform_booting()) {
2438
			echo gettext("Starting DNS Resolver...");
2439
		} else {
2440
			sleep(1);
2441
		}
2442

    
2443
		/* generate hosts file */
2444
		if (system_hosts_generate() != 0) {
2445
			$return = 1;
2446
		}
2447

    
2448
		/* Check here for dhcp6 complete - wait upto 10 seconds */
2449
		if($config['interfaces']["wan"]['ipaddrv6'] == 'dhcp6') {
2450
			$wanif = get_real_interface("wan", "inet6");
2451
			if (platform_booting()) {
2452
				for ($i=1; $i <= 10; $i++) {
2453
					if (!file_exists("/tmp/{$wanif}_dhcp6_complete")) {
2454
						log_error(gettext("Unbound start waiting on dhcp6c."));
2455
						sleep(1);
2456
					} else {
2457
						unlink_if_exists("/tmp/{$wanif}_dhcp6_complete");
2458
						log_error(gettext("dhcp6 init complete. Continuing"));
2459
						break;
2460
					}
2461
				}
2462
			}
2463
		}
2464

    
2465
		sync_unbound_service();
2466
		if (platform_booting()) {
2467
			log_error(gettext("sync unbound done."));
2468
			echo gettext("done.") . "\n";
2469
		}
2470

    
2471
		system_dhcpleases_configure();
2472
	} else {
2473
		/* kill Unbound since it should not be enabled */
2474
		if (file_exists("{$g['varrun_path']}/unbound.pid")) {
2475
			sigkillbypid("{$g['varrun_path']}/unbound.pid", "KILL");
2476
		}
2477
	}
2478

    
2479
	if (!platform_booting() && $restart_dhcp) {
2480
		if (services_dhcpd_configure() != 0) {
2481
			$return = 1;
2482
		}
2483
	}
2484

    
2485
	return $return;
2486
}
2487

    
2488
function services_snmpd_configure() {
2489
	global $config, $g;
2490
	if (isset($config['system']['developerspew'])) {
2491
		$mt = microtime();
2492
		echo "services_snmpd_configure() being called $mt\n";
2493
	}
2494

    
2495
	/* kill any running snmpd */
2496
	sigkillbypid("{$g['varrun_path']}/snmpd.pid", "TERM");
2497
	sleep(2);
2498
	if (is_process_running("bsnmpd")) {
2499
		mwexec("/usr/bin/killall bsnmpd", true);
2500
	}
2501

    
2502
	if (isset($config['snmpd']['enable'])) {
2503

    
2504
		if (platform_booting()) {
2505
			echo gettext("Starting SNMP daemon... ");
2506
		}
2507

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

    
2513
		/* generate snmpd.conf */
2514
		$fd = fopen("{$g['varetc_path']}/snmpd.conf", "w");
2515
		if (!$fd) {
2516
			printf(gettext("Error: cannot open snmpd.conf in services_snmpd_configure().%s"), "\n");
2517
			return 1;
2518
		}
2519

    
2520

    
2521
		$snmpdconf = <<<EOD
2522
location := "{$config['snmpd']['syslocation']}"
2523
contact := "{$config['snmpd']['syscontact']}"
2524
read := "{$config['snmpd']['rocommunity']}"
2525

    
2526
EOD;
2527

    
2528
/* No docs on what write strings do there so disable for now.
2529
		if (isset($config['snmpd']['rwenable']) && preg_match('/^\S+$/', $config['snmpd']['rwcommunity'])) {
2530
			$snmpdconf .= <<<EOD
2531
# write string
2532
write := "{$config['snmpd']['rwcommunity']}"
2533

    
2534
EOD;
2535
		}
2536
*/
2537

    
2538

    
2539
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2540
			$snmpdconf .= <<<EOD
2541
# SNMP Trap support.
2542
traphost := {$config['snmpd']['trapserver']}
2543
trapport := {$config['snmpd']['trapserverport']}
2544
trap := "{$config['snmpd']['trapstring']}"
2545

    
2546

    
2547
EOD;
2548
		}
2549

    
2550
		$sysDescr = "{$g['product_name']} {$config['system']['hostname']}.{$config['system']['domain']}" .
2551
			" {$g['product_version_string']} {$g['platform']} " . php_uname("s") .
2552
			" " . php_uname("r") . " " . php_uname("m");
2553

    
2554
		$snmpdconf .= <<<EOD
2555
system := 1     # pfSense
2556
%snmpd
2557
sysDescr			= "{$sysDescr}"
2558
begemotSnmpdDebugDumpPdus       = 2
2559
begemotSnmpdDebugSyslogPri      = 7
2560
begemotSnmpdCommunityString.0.1 = $(read)
2561

    
2562
EOD;
2563

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

    
2569
EOD;
2570
		}
2571
*/
2572

    
2573

    
2574
		if (isset($config['snmpd']['trapenable']) && preg_match('/^\S+$/', $config['snmpd']['trapserver'])) {
2575
			$snmpdconf .= <<<EOD
2576
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
2577
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
2578
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
2579

    
2580
EOD;
2581
		}
2582

    
2583

    
2584
		$snmpdconf .= <<<EOD
2585
begemotSnmpdCommunityDisable    = 1
2586

    
2587
EOD;
2588

    
2589
		$bind_to_ips = array();
2590
		if (isset($config['snmpd']['bindip'])) {
2591
			foreach (explode(",", $config['snmpd']['bindip']) as $bind_to_ip) {
2592
				if (is_ipaddr($bind_to_ip)) {
2593
					$bind_to_ips[] = $bind_to_ip;
2594
				} else {
2595
					$if = get_real_interface($bind_to_ip);
2596
					if (does_interface_exist($if)) {
2597
						$bindip = get_interface_ip($bind_to_ip);
2598
						if (is_ipaddr($bindip)) {
2599
							$bind_to_ips[] = $bindip;
2600
						}
2601
					}
2602
				}
2603
			}
2604
		}
2605
		if (!count($bind_to_ips)) {
2606
			$bind_to_ips = array("0.0.0.0");
2607
		}
2608

    
2609
		if (is_port($config['snmpd']['pollport'])) {
2610
			foreach ($bind_to_ips as $bind_to_ip) {
2611
				$snmpdconf .= <<<EOD
2612
begemotSnmpdPortStatus.{$bind_to_ip}.{$config['snmpd']['pollport']} = 1
2613

    
2614
EOD;
2615

    
2616
			}
2617
		}
2618

    
2619
		$snmpdconf .= <<<EOD
2620
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
2621
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
2622

    
2623
# These are bsnmp macros not php vars.
2624
sysContact      = $(contact)
2625
sysLocation     = $(location)
2626
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
2627

    
2628
snmpEnableAuthenTraps = 2
2629

    
2630
EOD;
2631

    
2632
		if (is_array($config['snmpd']['modules'])) {
2633
			if (isset($config['snmpd']['modules']['mibii'])) {
2634
			$snmpdconf .= <<<EOD
2635
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
2636

    
2637
EOD;
2638
			}
2639

    
2640
			if (isset($config['snmpd']['modules']['netgraph'])) {
2641
				$snmpdconf .= <<<EOD
2642
begemotSnmpdModulePath."netgraph" = "/usr/lib/snmp_netgraph.so"
2643
%netgraph
2644
begemotNgControlNodeName = "snmpd"
2645

    
2646
EOD;
2647
			}
2648

    
2649
			if (isset($config['snmpd']['modules']['pf'])) {
2650
				$snmpdconf .= <<<EOD
2651
begemotSnmpdModulePath."pf"     = "/usr/lib/snmp_pf.so"
2652

    
2653
EOD;
2654
			}
2655

    
2656
			if (isset($config['snmpd']['modules']['hostres'])) {
2657
				$snmpdconf .= <<<EOD
2658
begemotSnmpdModulePath."hostres"     = "/usr/lib/snmp_hostres.so"
2659

    
2660
EOD;
2661
			}
2662

    
2663
			if (isset($config['snmpd']['modules']['bridge'])) {
2664
				$snmpdconf .= <<<EOD
2665
begemotSnmpdModulePath."bridge"     = "/usr/lib/snmp_bridge.so"
2666
# config must end with blank line
2667

    
2668
EOD;
2669
			}
2670
			if (isset($config['snmpd']['modules']['ucd'])) {
2671
				$snmpdconf .= <<<EOD
2672
begemotSnmpdModulePath."ucd"     = "/usr/local/lib/snmp_ucd.so"
2673

    
2674
EOD;
2675
			}
2676
			if (isset($config['snmpd']['modules']['regex'])) {
2677
				$snmpdconf .= <<<EOD
2678
begemotSnmpdModulePath."regex"     = "/usr/local/lib/snmp_regex.so"
2679

    
2680
EOD;
2681
			}
2682
		}
2683

    
2684
		fwrite($fd, $snmpdconf);
2685
		fclose($fd);
2686
		unset($snmpdconf);
2687

    
2688
		/* run bsnmpd */
2689
		mwexec("/usr/sbin/bsnmpd -c {$g['varetc_path']}/snmpd.conf" .
2690
			" -p {$g['varrun_path']}/snmpd.pid");
2691

    
2692
		if (platform_booting()) {
2693
			echo gettext("done.") . "\n";
2694
		}
2695
	}
2696

    
2697
	return 0;
2698
}
2699

    
2700
function services_dnsupdate_process($int = "", $updatehost = "", $forced = false) {
2701
	global $config, $g;
2702
	if (isset($config['system']['developerspew'])) {
2703
		$mt = microtime();
2704
		echo "services_dnsupdate_process() being called $mt\n";
2705
	}
2706

    
2707
	/* Dynamic DNS updating active? */
2708
	if (!is_array($config['dnsupdates']['dnsupdate'])) {
2709
		return 0;
2710
	}
2711

    
2712
	$notify_text = "";
2713
	$gwgroups = return_gateway_groups_array(true);
2714
	foreach ($config['dnsupdates']['dnsupdate'] as $i => $dnsupdate) {
2715
		if (!isset($dnsupdate['enable'])) {
2716
			continue;
2717
		}
2718
		/*
2719
		 * If it's using a gateway group, check if interface is
2720
		 * the active gateway for that group
2721
		 */
2722
		$group_int = '';
2723
		$friendly_group_int = '';
2724
		$gwgroup_member = false;
2725
		if (is_array($gwgroups[$dnsupdate['interface']])) {
2726
			if (!empty($gwgroups[$dnsupdate['interface']][0]['vip'])) {
2727
				$group_int = $gwgroups[$dnsupdate['interface']][0]['vip'];
2728
			} else {
2729
				$group_int = $gwgroups[$dnsupdate['interface']][0]['int'];
2730
				$friendly_group_int =
2731
				    convert_real_interface_to_friendly_interface_name(
2732
					$group_int);
2733
				if (!empty($int)) {
2734
					$gwgroup_member =
2735
					    interface_gateway_group_member(get_real_interface($int),
2736
					    $dnsupdate['interface']);
2737
				}
2738
			}
2739
		}
2740
		if (!empty($int) && ($int != $dnsupdate['interface']) && !$gwgroup_member &&
2741
		    ($int != $group_int) && ($int != $friendly_group_int)) {
2742
			continue;
2743
		}
2744
		if (!empty($updatehost) && ($updatehost != $dnsupdate['host'])) {
2745
			continue;
2746
		}
2747

    
2748
		/* determine interface name */
2749
		$if = get_failover_interface($dnsupdate['interface']);
2750

    
2751
		/* Determine address to update and default binding address */
2752
		if (isset($dnsupdate['usepublicip'])) {
2753
			$wanip = dyndnsCheckIP($if);
2754
			$bindipv4 = get_interface_ip($if);
2755
		} else {
2756
			$wanip = get_interface_ip($if);
2757
			$bindipv4 = $wanip;
2758
		}
2759
		if (is_stf_interface($dnsupdate['interface'])) { 
2760
			$wanipv6 = get_interface_ipv6($dnsupdate['interface'] . '_stf');
2761
		} else {
2762
			$wanipv6 = get_interface_ipv6($if);
2763
		}
2764
		$bindipv6 = $wanipv6;
2765

    
2766
		/* Handle non-default interface bindings */
2767
		if ($dnsupdate['updatesource'] == "none") {
2768
			/* When empty, the directive will be omitted. */
2769
			$bindipv4 = "";
2770
			$bindipv6 = "";
2771
		} elseif (!empty($dnsupdate['updatesource'])) {
2772
			/* Find the alternate binding address */
2773
			$bindipv4 = get_interface_ip($dnsupdate['updatesource']);
2774
			if (is_stf_interface($dnsupdate['interface'])) { 
2775
				$bindipv6 = get_interface_ipv6($dnsupdate['updatesource'] . '_stf');
2776
			} else {
2777
				$bindipv6 = get_interface_ipv6($dnsupdate['updatesource']);
2778
			}
2779
		}
2780

    
2781
		/* Handle IPv4/IPv6 selection for the update source interface/VIP */
2782
		switch ($dnsupdate['updatesourcefamily']) {
2783
			case "inet":
2784
				$bindip = $bindipv4;
2785
				break;
2786
			case "inet6":
2787
				$bindip = $bindipv6;
2788
				break;
2789
			case "":
2790
			default:
2791
				/* Try IPv4 first, if that is empty, try IPv6. */
2792
				/* Only specify the address if it's present, otherwise omit. */
2793
				if (!empty($bindipv4)) {
2794
					$bindip = $bindipv4;
2795
				} elseif (!empty($bindipv6)) {
2796
					$bindip = $bindipv6;
2797
				}
2798
				break;
2799
		}
2800

    
2801
		$cacheFile = $g['conf_path'] .
2802
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2803
		    escapeshellarg($dnsupdate['host']) .
2804
		    "_{$dnsupdate['server']}.cache";
2805
		$cacheFilev6 = $g['conf_path'] .
2806
		    "/dyndns_{$dnsupdate['interface']}_rfc2136_" .
2807
		    escapeshellarg($dnsupdate['host']) .
2808
		    "_{$dnsupdate['server']}_v6.cache";
2809
		$currentTime = time();
2810

    
2811
		if (!$wanip && !$wanipv6) {
2812
			continue;
2813
		}
2814

    
2815
		$keyname = $dnsupdate['keyname'];
2816
		/* trailing dot */
2817
		if (substr($keyname, -1) != ".") {
2818
			$keyname .= ".";
2819
		}
2820

    
2821
		$hostname = $dnsupdate['host'];
2822
		/* trailing dot */
2823
		if (substr($hostname, -1) != ".") {
2824
			$hostname .= ".";
2825
		}
2826

    
2827
		/* write key file */
2828
		$algorithm = empty($dnsupdate['keyalgorithm']) ? 'hmac-md5' : $dnsupdate['keyalgorithm'];
2829
		$upkey = <<<EOD
2830
key "{$keyname}" {
2831
	algorithm {$algorithm};
2832
	secret "{$dnsupdate['keydata']}";
2833
};
2834

    
2835
EOD;
2836
		@file_put_contents("{$g['varetc_path']}/nsupdatekey{$i}", $upkey);
2837

    
2838
		/* generate update instructions */
2839
		$upinst = "";
2840
		if (!empty($dnsupdate['server'])) {
2841
			$upinst .= "server {$dnsupdate['server']}\n";
2842
		}
2843

    
2844
		$cachedipv4 = '';
2845
		$cacheTimev4 = 0;
2846
		if (file_exists($cacheFile)) {
2847
			list($cachedipv4, $cacheTimev4) = explode("|",
2848
			    file_get_contents($cacheFile));
2849
		}
2850
		$cachedipv6 = '';
2851
		$cacheTimev6 = 0;
2852
		if (file_exists($cacheFilev6)) {
2853
			list($cachedipv6, $cacheTimev6) = explode("|",
2854
			    file_get_contents($cacheFilev6));
2855
		}
2856

    
2857
		// 25 Days
2858
		$maxCacheAgeSecs = 25 * 24 * 60 * 60;
2859
		$need_update = false;
2860

    
2861
		/* Update IPv4 if we have it. */
2862
		if (is_ipaddrv4($wanip) && $dnsupdate['recordtype'] != "AAAA") {
2863
			if (($wanip != $cachedipv4) || $forced ||
2864
			    (($currentTime - $cacheTimev4) > $maxCacheAgeSecs)) {
2865
				$upinst .= "update delete " .
2866
				    "{$dnsupdate['host']}. A\n";
2867
				$upinst .= "update add {$dnsupdate['host']}. " .
2868
				    "{$dnsupdate['ttl']} A {$wanip}\n";
2869
				if (!empty($bindip)) {
2870
					$upinst .= "local {$bindip}\n";
2871
				}
2872
				$need_update = true;
2873
			} else {
2874
				log_error(sprintf(gettext(
2875
				    "phpDynDNS: Not updating %s A record because the IP address has not changed."),
2876
				    $dnsupdate['host']));
2877
			}
2878
		} else {
2879
			@unlink($cacheFile);
2880
			unset($cacheFile);
2881
		}
2882

    
2883
		/* Update IPv6 if we have it. */
2884
		if (is_ipaddrv6($wanipv6) && $dnsupdate['recordtype'] != "A") {
2885
			if (($wanipv6 != $cachedipv6) || $forced ||
2886
			    (($currentTime - $cacheTimev6) > $maxCacheAgeSecs)) {
2887
				$upinst .= "update delete " .
2888
				    "{$dnsupdate['host']}. AAAA\n";
2889
				$upinst .= "update add {$dnsupdate['host']}. " .
2890
				    "{$dnsupdate['ttl']} AAAA {$wanipv6}\n";
2891
				$need_update = true;
2892
			} else {
2893
				log_error(sprintf(gettext(
2894
				    "phpDynDNS: Not updating %s AAAA record because the IPv6 address has not changed."),
2895
				    $dnsupdate['host']));
2896
			}
2897
		} else {
2898
			@unlink($cacheFilev6);
2899
			unset($cacheFilev6);
2900
		}
2901

    
2902
		$upinst .= "\n";	/* mind that trailing newline! */
2903

    
2904
		if (!$need_update) {
2905
			continue;
2906
		}
2907

    
2908
		@file_put_contents("{$g['varetc_path']}/nsupdatecmds{$i}", $upinst);
2909
		unset($upinst);
2910
		/* invoke nsupdate */
2911
		$cmd = "/usr/local/bin/nsupdate -k {$g['varetc_path']}/nsupdatekey{$i}";
2912

    
2913
		if (isset($dnsupdate['usetcp'])) {
2914
			$cmd .= " -v";
2915
		}
2916

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

    
2919
		if (mwexec($cmd) == 0) {
2920
			if (!empty($cacheFile)) {
2921
				@file_put_contents($cacheFile,
2922
				    "{$wanip}|{$currentTime}");
2923
				log_error(sprintf(gettext(
2924
				    'phpDynDNS: updating cache file %1$s: %2$s'),
2925
				    $cacheFile, $wanip));
2926
				$notify_text .= sprintf(gettext(
2927
				    'DynDNS updated IP Address (A) for %1$s on %2$s (%3$s) to %4$s'),
2928
				    $dnsupdate['host'],
2929
				    convert_real_interface_to_friendly_descr($if),
2930
				    $if, $wanip) . "\n";
2931
			}
2932
			if (!empty($cacheFilev6)) {
2933
				@file_put_contents($cacheFilev6,
2934
				    "{$wanipv6}|{$currentTime}");
2935
				log_error(sprintf(gettext(
2936
				    'phpDynDNS: updating cache file %1$s: %2$s'),
2937
				    $cacheFilev6, $wanipv6));
2938
				$notify_text .= sprintf(gettext(
2939
				    'DynDNS updated IPv6 Address (AAAA) for %1$s on %2$s (%3$s) to %4$s'),
2940
				    $dnsupdate['host'],
2941
				    convert_real_interface_to_friendly_descr($if),
2942
				    $if, $wanipv6) . "\n";
2943
			}
2944
		} else {
2945
			if (!empty($cacheFile)) {
2946
				log_error(sprintf(gettext(
2947
				    'phpDynDNS: ERROR while updating IP Address (A) for %1$s (%2$s)'),
2948
				    $dnsupdate['host'], $wanip));
2949
			}
2950
			if (!empty($cacheFilev6)) {
2951
				log_error(sprintf(gettext(
2952
				    'phpDynDNS: ERROR while updating IP Address (AAAA) for %1$s (%2$s)'),
2953
				    $dnsupdate['host'], $wanipv6));
2954
			}
2955
		}
2956
		unset($cmd);
2957
	}
2958

    
2959
	if (!empty($notify_text)) {
2960
		notify_all_remote($notify_text);
2961
	}
2962

    
2963
	return 0;
2964
}
2965

    
2966
/* configure cron service */
2967
function configure_cron() {
2968
	global $g, $config;
2969

    
2970
	/* preserve existing crontab entries */
2971
	$crontab_contents = file("/etc/crontab", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2972

    
2973
	for ($i = 0; $i < count($crontab_contents); $i++) {
2974
		$cron_item = &$crontab_contents[$i];
2975
		if (strpos($cron_item, "# pfSense specific crontab entries") !== false) {
2976
			array_splice($crontab_contents, $i - 1);
2977
			break;
2978
		}
2979
	}
2980
	$crontab_contents = implode("\n", $crontab_contents) . "\n";
2981

    
2982

    
2983
	if (is_array($config['cron']['item'])) {
2984
		$crontab_contents .= "#\n";
2985
		$crontab_contents .= "# pfSense specific crontab entries\n";
2986
		$crontab_contents .= "# " .gettext("Created:") . " " . date("F j, Y, g:i a") . "\n";
2987
		$crontab_contents .= "#\n";
2988

    
2989
		if (isset($config['system']['proxyurl']) && !empty($config['system']['proxyurl'])) {
2990
			$http_proxy = $config['system']['proxyurl'];
2991
			if (isset($config['system']['proxyport']) && !empty($config['system']['proxyport'])) {
2992
				$http_proxy .= ':' . $config['system']['proxyport'];
2993
			}
2994
			$crontab_contents .= "HTTP_PROXY={$http_proxy}";
2995

    
2996
			if (!empty($config['system']['proxyuser']) && !empty($config['system']['proxypass'])) {
2997
				$crontab_contents .= "HTTP_PROXY_AUTH=basic:*:{$config['system']['proxyuser']}:{$config['system']['proxypass']}";
2998
			}
2999
		}
3000

    
3001
		foreach ($config['cron']['item'] as $item) {
3002
			$crontab_contents .= "\n{$item['minute']}\t";
3003
			$crontab_contents .= "{$item['hour']}\t";
3004
			$crontab_contents .= "{$item['mday']}\t";
3005
			$crontab_contents .= "{$item['month']}\t";
3006
			$crontab_contents .= "{$item['wday']}\t";
3007
			$crontab_contents .= "{$item['who']}\t";
3008
			$crontab_contents .= "{$item['command']}";
3009
		}
3010

    
3011
		$crontab_contents .= "\n#\n";
3012
		$crontab_contents .= "# " . gettext("If possible do not add items to this file manually.") . "\n";
3013
		$crontab_contents .= "# " . gettext("If done so, this file must be terminated with a blank line (e.g. new line)") . "\n";
3014
		$crontab_contents .= "#\n\n";
3015
	}
3016

    
3017
	/* please maintain the newline at the end of file */
3018
	file_put_contents("/etc/crontab", $crontab_contents);
3019
	unset($crontab_contents);
3020

    
3021
	/* make sure that cron is running and start it if it got killed somehow */
3022
	if (!is_process_running("cron")) {
3023
		exec("cd /tmp && /usr/sbin/cron -s 2>/dev/null");
3024
	} else {
3025
	/* do a HUP kill to force sync changes */
3026
		sigkillbypid("{$g['varrun_path']}/cron.pid", "HUP");
3027
	}
3028

    
3029
}
3030

    
3031
function upnp_action ($action) {
3032
	global $g, $config;
3033
	switch ($action) {
3034
		case "start":
3035
			if (file_exists('/var/etc/miniupnpd.conf')) {
3036
				@unlink("{$g['varrun_path']}/miniupnpd.pid");
3037
				mwexec_bg("/usr/local/sbin/miniupnpd -f /var/etc/miniupnpd.conf -P {$g['varrun_path']}/miniupnpd.pid");
3038
			}
3039
			break;
3040
		case "stop":
3041
			killbypid("{$g['varrun_path']}/miniupnpd.pid");
3042
			while ((int)exec("/bin/pgrep -a miniupnpd | wc -l") > 0) {
3043
				mwexec('/usr/bin/killall miniupnpd 2>/dev/null', true);
3044
			}
3045
			mwexec('/sbin/pfctl -aminiupnpd -Fr 2>&1 >/dev/null');
3046
			mwexec('/sbin/pfctl -aminiupnpd -Fn 2>&1 >/dev/null');
3047
			break;
3048
		case "restart":
3049
			upnp_action('stop');
3050
			upnp_action('start');
3051
			break;
3052
	}
3053
}
3054

    
3055
function upnp_start() {
3056
	global $config;
3057

    
3058
	if (!isset($config['installedpackages']['miniupnpd']['config'])) {
3059
		return;
3060
	}
3061

    
3062
	if ($config['installedpackages']['miniupnpd']['config'][0]['enable']) {
3063
		echo gettext("Starting UPnP service... ");
3064
		require_once('/usr/local/pkg/miniupnpd.inc');
3065
		sync_package_miniupnpd();
3066
		echo "done.\n";
3067
	}
3068
}
3069

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

    
3073
	$is_installed = false;
3074
	$cron_changed = true;
3075
	$change_message = "";
3076

    
3077
	if (!is_array($config['cron'])) {
3078
		$config['cron'] = array();
3079
	}
3080
	if (!is_array($config['cron']['item'])) {
3081
		$config['cron']['item'] = array();
3082
	}
3083

    
3084
	$x = 0;
3085
	foreach ($config['cron']['item'] as $item) {
3086
		if (strstr($item['command'], $command)) {
3087
			$is_installed = true;
3088
			break;
3089
		}
3090
		$x++;
3091
	}
3092

    
3093
	if ($active) {
3094
		$cron_item = array();
3095
		$cron_item['minute'] = $minute;
3096
		$cron_item['hour'] = $hour;
3097
		$cron_item['mday'] = $monthday;
3098
		$cron_item['month'] = $month;
3099
		$cron_item['wday'] = $weekday;
3100
		$cron_item['who'] = $who;
3101
		$cron_item['command'] = $command;
3102
		if (!$is_installed) {
3103
			$config['cron']['item'][] = $cron_item;
3104
			$change_message = "Installed cron job for %s";
3105
		} else {
3106
			if ($config['cron']['item'][$x] == $cron_item) {
3107
				$cron_changed = false;
3108
			} else {
3109
				$config['cron']['item'][$x] = $cron_item;
3110
				$change_message = "Updated cron job for %s";
3111
			}
3112
		}
3113
	} else {
3114
		if ($is_installed == true) {
3115
			array_splice($config['cron']['item'], $x, 1);
3116
			$change_message = "Removed cron job for %s";
3117
		} else {
3118
			$cron_changed = false;
3119
		}
3120
	}
3121

    
3122
	if ($cron_changed) {
3123
		/* Optionally write the configuration if this function made changes.
3124
		 * Performing a write_config() in this way can have unintended side effects. See #7146
3125
		 * Base system instances of this function do not need to write, packages may.
3126
		 */
3127
		if ($write_config) {
3128
			write_config(sprintf(gettext($change_message), $command));
3129
		}
3130
		configure_cron();
3131
	}
3132
}
3133

    
3134
?>
(46-46/60)