Projet

Général

Profil

Télécharger (62,5 ko) Statistiques
| Branche: | Tag: | Révision:

univnautes / etc / inc / system.inc @ 64a2da80

1
<?php
2
/* $Id$ */
3
/*
4
	system.inc
5
	part of m0n0wall (http://m0n0.ch/wall)
6

    
7
	Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
8
	All rights reserved.
9

    
10
	Redistribution and use in source and binary forms, with or without
11
	modification, are permitted provided that the following conditions are met:
12

    
13
	1. Redistributions of source code must retain the above copyright notice,
14
	   this list of conditions and the following disclaimer.
15

    
16
	2. Redistributions in binary form must reproduce the above copyright
17
	   notice, this list of conditions and the following disclaimer in the
18
	   documentation and/or other materials provided with the distribution.
19

    
20
	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
21
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
22
	AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
23
	AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
24
	OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29
	POSSIBILITY OF SUCH DAMAGE.
30
*/
31

    
32
/*
33
	pfSense_BUILDER_BINARIES:	/usr/sbin/powerd	/usr/bin/killall	/sbin/sysctl	/sbin/route
34
	pfSense_BUILDER_BINARIES:	/bin/hostname	/bin/ls	/usr/sbin/syslogd	
35
	pfSense_BUILDER_BINARIES:	/usr/sbin/pccardd	/usr/local/sbin/lighttpd	/bin/chmod 	/bin/mkdir
36
	pfSense_BUILDER_BINARIES:	/usr/bin/tar		/usr/local/sbin/ntpd	/usr/local/sbin/ntpdate
37
	pfSense_BUILDER_BINARIES:	/usr/bin/nohup	/sbin/dmesg	/usr/local/sbin/atareinit	/sbin/kldload
38
	pfSense_BUILDER_BINARIES:	/usr/local/sbin/filterdns
39
	pfSense_MODULE:	utils
40
*/
41

    
42
function activate_powerd() {
43
	global $config, $g;
44
	if ($g['platform'] == 'jail')
45
		return;
46
	if(is_process_running("powerd"))
47
		exec("/usr/bin/killall powerd");
48
	if(isset($config['system']['powerd_enable'])) {
49
		if ($g["platform"] == "nanobsd")
50
			exec("/sbin/kldload cpufreq");
51

    
52
		$ac_mode = "hadp";
53
		if (!empty($config['system']['powerd_ac_mode']))
54
			$ac_mode = $config['system']['powerd_ac_mode'];
55

    
56
		$battery_mode = "hadp";
57
		if (!empty($config['system']['powerd_battery_mode']))
58
			$battery_mode = $config['system']['powerd_battery_mode'];
59

    
60
		mwexec("/usr/sbin/powerd -b $battery_mode -a $ac_mode");
61
	}
62
}
63

    
64
function get_default_sysctl_value($id) {
65
	global $sysctls;
66

    
67
	if (isset($sysctls[$id]))
68
		return $sysctls[$id];
69
}
70

    
71
function activate_sysctls() {
72
	global $config, $g;
73
	if ($g['platform'] == 'jail')
74
		return;
75
	exec("/sbin/sysctl net.enc.out.ipsec_bpf_mask=0x0001");
76
	exec("/sbin/sysctl net.enc.out.ipsec_filter_mask=0x0001");
77
	exec("/sbin/sysctl net.enc.in.ipsec_bpf_mask=0x0002");
78
	exec("/sbin/sysctl net.enc.in.ipsec_filter_mask=0x0002");
79

    
80
	if(is_array($config['sysctl'])) {
81
		foreach($config['sysctl']['item'] as $tunable) {
82
			if($tunable['value'] == "default") {
83
				$value = get_default_sysctl_value($tunable['tunable']);
84
				mwexec("/sbin/sysctl " . $tunable['tunable'] . "=\"" . $value .  "\"", true);
85
			} else { 
86
				mwexec("/sbin/sysctl " . $tunable['tunable'] . "=\"" . $tunable['value'] .  "\"", true);
87
			}
88
		}
89
	}
90
}
91

    
92
function system_resolvconf_generate($dynupdate = false) {
93
	global $config, $g;
94

    
95
	if(isset($config['system']['developerspew'])) {
96
		$mt = microtime();
97
		echo "system_resolvconf_generate() being called $mt\n";
98
	}
99

    
100
	$syscfg = $config['system'];
101

    
102
	// Do not create blank domain lines, it breaks tools like dig.
103
	if($syscfg['domain'])
104
		$resolvconf = "domain {$syscfg['domain']}\n";
105

    
106
	if (((isset($config['dnsmasq']['enable']) && (empty($config['dnsmasq']['interface']) || in_array("lo0", explode(",", $config['dnsmasq']['interface']))))
107
		|| (isset($config['unbound']['enable'])) && (empty($config['unbound']['active_interface']) || in_array("lo0", explode(",", $config['unbound']['active_interface']))))
108
		&& !isset($config['system']['dnslocalhost']))
109
		$resolvconf .= "nameserver 127.0.0.1\n";
110

    
111
	if (isset($syscfg['dnsallowoverride'])) {
112
		/* get dynamically assigned DNS servers (if any) */
113
		$ns = array_unique(get_searchdomains());
114
		foreach($ns as $searchserver) {
115
			if($searchserver)
116
				$resolvconf .= "search {$searchserver}\n";
117
		}
118
		$ns = array_unique(get_nameservers());
119
		foreach($ns as $nameserver) {
120
			if($nameserver)
121
				$resolvconf .= "nameserver $nameserver\n";
122
		}
123
	}
124
	if (is_array($syscfg['dnsserver'])) {
125
		foreach ($syscfg['dnsserver'] as $ns) {
126
			if ($ns)
127
				$resolvconf .= "nameserver $ns\n";
128
		}
129
	}
130

    
131
	// Add EDNS support
132
	if (isset($config['unbound']['enable']) && isset($config['unbound']['edns']))
133
		$resolvconf .= "options edns0\n";
134

    
135
	$dnslock = lock('resolvconf', LOCK_EX);
136

    
137
	$fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
138
	if (!$fd) {
139
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
140
		unlock($dnslock);
141
		return 1;
142
	}
143

    
144
	fwrite($fd, $resolvconf);
145
	fclose($fd);
146

    
147
	if (!$g['booting']) {
148
		/* restart dhcpd (nameservers may have changed) */
149
		if (!$dynupdate)
150
			services_dhcpd_configure();
151
	}
152

    
153
	/* setup static routes for DNS servers. */
154
	for ($dnscounter=1; $dnscounter<5; $dnscounter++) {
155
		/* setup static routes for dns servers */
156
		$dnsgw = "dns{$dnscounter}gw";
157
		if (isset($config['system'][$dnsgw])) {
158
			$gwname = $config['system'][$dnsgw];
159
			if (($gwname <> "") && ($gwname <> "none")) {
160
				$gatewayip = lookup_gateway_ip_by_name($gwname);
161
				if (is_ipaddrv4($gatewayip)) {
162
					/* dns server array starts at 0 */
163
					$dnscountermo = $dnscounter - 1;
164
					mwexec("/sbin/route change -host " . $syscfg['dnsserver'][$dnscountermo] . " {$gatewayip}");
165
				}
166
				if (is_ipaddrv6($gatewayip)) {
167
					/* dns server array starts at 0 */
168
					$dnscountermo = $dnscounter - 1;
169
					mwexec("/sbin/route change -host -inet6 " . $syscfg['dnsserver'][$dnscountermo] . " {$gatewayip}");
170
				}
171
			}
172
		}
173
	}
174

    
175
	unlock($dnslock);
176

    
177
	return 0;
178
}
179

    
180
function get_searchdomains() {
181
	global $config, $g;
182

    
183
	$master_list = array();
184
	
185
	// Read in dhclient nameservers
186
	$search_list = glob("/var/etc/searchdomain_*");
187
	if (is_array($search_list)) {
188
		foreach($search_list as $fdns) {
189
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
190
			if (!is_array($contents))
191
				continue;
192
			foreach ($contents as $dns) {
193
				if(is_hostname($dns)) 
194
					$master_list[] = $dns;
195
			}
196
		}
197
	}
198

    
199
	return $master_list;
200
}
201

    
202
function get_nameservers() {
203
	global $config, $g;
204
	$master_list = array();
205
	
206
	// Read in dhclient nameservers
207
	$dns_lists = glob("/var/etc/nameserver_*");
208
	if (is_array($dns_lists)) {
209
		foreach($dns_lists as $fdns) {
210
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
211
			if (!is_array($contents))
212
				continue;
213
			foreach ($contents as $dns) {
214
				if(is_ipaddr($dns)) 
215
					$master_list[] = $dns;
216
			}
217
		}
218
	}
219

    
220
	// Read in any extra nameservers
221
	if(file_exists("/var/etc/nameservers.conf")) {
222
		$dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
223
		if(is_array($dns_s)) {
224
			foreach($dns_s as $dns)
225
				if (is_ipaddr($dns))
226
					$master_list[] = $dns;
227
		}
228
	}
229

    
230
	return $master_list;
231
}
232

    
233
function system_hosts_generate() {
234
	global $config, $g;
235
	if (isset($config['system']['developerspew'])) {
236
		$mt = microtime();
237
		echo "system_hosts_generate() being called $mt\n";
238
	}
239

    
240
	$syscfg = $config['system'];
241
	$dnsmasqcfg = $config['dnsmasq'];
242

    
243
	$hosts = "127.0.0.1	localhost localhost.{$syscfg['domain']}\n";
244
	$lhosts = "";
245
	$dhosts = "";
246

    
247
	if ($config['interfaces']['lan']) {
248
		$cfgip = get_interface_ip("lan");
249
		if (is_ipaddr($cfgip))
250
			$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
251
	} else {
252
		$sysiflist = get_configured_interface_list();
253
		foreach ($sysiflist as $sysif) {
254
			if (!interface_has_gateway($sysif)) {
255
				$cfgip = get_interface_ip($sysif);
256
				if (is_ipaddr($cfgip)) {
257
					$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
258
					break;
259
				}
260
			}
261
		}
262
	}
263

    
264
	if (isset($dnsmasqcfg['enable'])) {
265
		if (!is_array($dnsmasqcfg['hosts']))
266
			$dnsmasqcfg['hosts'] = array();
267

    
268
		foreach ($dnsmasqcfg['hosts'] as $host) {
269
			if ($host['host'])
270
				$lhosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
271
			else
272
				$lhosts .= "{$host['ip']}	{$host['domain']}\n";
273
			if (!is_array($host['aliases']) || !is_array($host['aliases']['item']))
274
				continue;
275
			foreach ($host['aliases']['item'] as $alias) {
276
				if ($alias['host'])
277
					$lhosts .= "{$host['ip']}	{$alias['host']}.{$alias['domain']} {$alias['host']}\n";
278
				else
279
					$lhosts .= "{$host['ip']}	{$alias['domain']}\n";
280
			}
281
		}
282
		if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpd'])) {
283
			foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf)
284
				if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
285
						foreach ($dhcpifconf['staticmap'] as $host)
286
							if ($host['ipaddr'] && $host['hostname'] && $host['domain'])
287
								$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$host['domain']} {$host['hostname']}\n";
288
							else if ($host['ipaddr'] && $host['hostname'] && $dhcpifconf['domain'])
289
								$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$dhcpifconf['domain']} {$host['hostname']}\n";
290
							else if ($host['ipaddr'] && $host['hostname'])
291
								$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
292
		}
293
		if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpdv6'])) {
294
			foreach ($config['dhcpdv6'] as $dhcpif => $dhcpifconf)
295
				if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
296
						foreach ($dhcpifconf['staticmap'] as $host)
297
							if ($host['ipaddrv6'] && $host['hostname'] && $host['domain'])
298
								$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$host['domain']} {$host['hostname']}\n";
299
							else if ($host['ipaddrv6'] && $host['hostname'] && $dhcpifconf['domain'])
300
								$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$dhcpifconf['domain']} {$host['hostname']}\n";
301
							else if ($host['ipaddrv6'] && $host['hostname'])
302
								$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
303
		}
304

    
305
		if (isset($dnsmasqcfg['dhcpfirst']))
306
			$hosts .= $dhosts . $lhosts;
307
		else
308
			$hosts .= $lhosts . $dhosts;
309
	}
310

    
311
	/*
312
	 * Do not remove this because dhcpleases monitors with kqueue it needs to be 
313
	 * killed before writing to hosts files.
314
	 */
315
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
316
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
317
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
318
	}
319
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
320
	if (!$fd) {
321
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
322
		return 1;
323
	}
324
	fwrite($fd, $hosts);
325
	fclose($fd);
326

    
327
	if (isset($config['unbound']['enable'])) {
328
		require_once("unbound.inc");
329
		unbound_hosts_generate();
330
	}
331

    
332
	system_dhcpleases_configure();
333

    
334
	return 0;
335
}
336

    
337
function system_dhcpleases_configure() {
338
	global $config, $g;
339
	
340
	if ($g['platform'] == 'jail')
341
		return;
342
	/* Start the monitoring process for dynamic dhcpclients. */
343
	if ((isset($config['dnsmasq']['enable']) && isset($config['dnsmasq']['regdhcp'])) 
344
		|| (isset($config['unbound']['enable']) && isset($config['unbound']['regdhcp']))) {
345
		/* Make sure we do not error out */
346
		mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db");
347
		if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases"))
348
			@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
349
		if (isvalidpid("{$g['varrun_path']}/dhcpleases.pid"))
350
			sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "HUP");
351
		else {
352
			/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
353
			if (is_process_running("dhcpleases"))
354
				mwexec('/bin/pkill dhcpleases');
355
			@unlink("{$g['varrun_path']}/dhcpleases.pid");
356
			mwexec("/usr/local/sbin/dhcpleases -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases -d {$config['system']['domain']} -p {$g['varrun_path']}/dnsmasq.pid -h {$g['varetc_path']}/hosts");
357
		}
358
	} else {
359
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
360
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
361
	}
362
}
363

    
364
function system_hostname_configure() {
365
	global $config, $g;
366
	if(isset($config['system']['developerspew'])) {
367
		$mt = microtime();
368
		echo "system_hostname_configure() being called $mt\n";
369
	}
370

    
371
	$syscfg = $config['system'];
372

    
373
	/* set hostname */
374
	$status = mwexec("/bin/hostname " .
375
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
376

    
377
    /* Setup host GUID ID.  This is used by ZFS. */
378
	mwexec("/etc/rc.d/hostid start");
379

    
380
	return $status;
381
}
382

    
383
function system_routing_configure($interface = "") {
384
	global $config, $g;
385
	if ($g['platform'] == 'jail')
386
		return;
387
	if(isset($config['system']['developerspew'])) {
388
		$mt = microtime();
389
		echo "system_routing_configure() being called $mt\n";
390
	}
391

    
392
	$gatewayip = "";
393
	$interfacegw = "";
394
	$foundgw = false;
395
	$gatewayipv6 = "";
396
	$interfacegwv6 = "";
397
	$foundgwv6 = false;
398
	/* tack on all the hard defined gateways as well */
399
	if (is_array($config['gateways']['gateway_item'])) {
400
		array_map('unlink', glob("{$g['tmp_path']}/*_defaultgw{,v6}", GLOB_BRACE));
401
		foreach	($config['gateways']['gateway_item'] as $gateway) {
402
			if (isset($gateway['defaultgw'])) {
403
				if ($gateway['ipprotocol'] != "inet6" && (is_ipaddrv4($gateway['gateway']) || $gateway['gateway'] == "dynamic")) {
404
					if(strstr($gateway['gateway'], ":"))
405
						continue;
406
					if ($gateway['gateway'] == "dynamic")
407
						$gateway['gateway'] = get_interface_gateway($gateway['interface']);
408
					$gatewayip = $gateway['gateway'];
409
					$interfacegw = $gateway['interface'];
410
					if (!empty($gateway['interface'])) {
411
						$defaultif = get_real_interface($gateway['interface']);
412
						if ($defaultif)
413
							@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gateway['gateway']);
414
					}
415
					$foundgw = true;
416
				} else if ($gateway['ipprotocol'] == "inet6" && (is_ipaddrv6($gateway['gateway']) || $gateway['gateway'] == "dynamic")) {
417
					if ($gateway['gateway'] == "dynamic")
418
						$gateway['gateway'] = get_interface_gateway_v6($gateway['interface']);
419
					$gatewayipv6 = $gateway['gateway'];
420
					$interfacegwv6 = $gateway['interface'];
421
					if (!empty($gateway['interface'])) {
422
						$defaultifv6 = get_real_interface($gateway['interface']);
423
						if ($defaultifv6)
424
							@file_put_contents("{$g['tmp_path']}/{$defaultifv6}_defaultgwv6", $gateway['gateway']);
425
					}
426
					$foundgwv6 = true;
427
				}
428
			}
429
			if ($foundgw === true && $foundgwv6 === true)
430
				break;
431
		}
432
	}
433
	if ($foundgw == false) {
434
		$defaultif = get_real_interface("wan");
435
		$interfacegw = "wan";
436
		$gatewayip = get_interface_gateway("wan");
437
		@touch("{$g['tmp_path']}/{$defaultif}_defaultgw");
438
	}	
439
	if ($foundgwv6 == false) {
440
		$defaultifv6 = get_real_interface("wan");
441
		$interfacegwv6 = "wan";
442
		$gatewayipv6 = get_interface_gateway_v6("wan");
443
		@touch("{$g['tmp_path']}/{$defaultif}_defaultgwv6");
444
	}
445
	$dont_add_route = false;
446
	/* if OLSRD is enabled, allow WAN to house DHCP. */
447
	if (is_array($config['installedpackages']['olsrd'])) {
448
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
449
			if(($olsrd['enabledyngw'] == "on") && ($olsrd['enable'] == "on")) {
450
				$dont_add_route = true;
451
				log_error(sprintf(gettext("Not adding default route because OLSR dynamic gateway is enabled.")));
452
				break;
453
			}
454
		}
455
	}
456

    
457
	if ($dont_add_route == false ) {
458
		if (!empty($interface) && $interface != $interfacegw)
459
			;
460
		else if (($interfacegw <> "bgpd") && (is_ipaddrv4($gatewayip))) {
461
			log_error("ROUTING: setting default route to $gatewayip");
462
			mwexec("/sbin/route change -inet default " . escapeshellarg($gatewayip));
463
		}
464

    
465
		if (!empty($interface) && $interface != $interfacegwv6)
466
			;
467
		else if (($interfacegwv6 <> "bgpd") && (is_ipaddrv6($gatewayipv6))) {
468
			$ifscope = "";
469
			if (is_linklocal($gatewayipv6))
470
				$ifscope = "%{$defaultifv6}";
471
			log_error("ROUTING: setting IPv6 default route to {$gatewayipv6}{$ifscope}");
472
			mwexec("/sbin/route change -inet6 default " . escapeshellarg($gatewayipv6) ."{$ifscope}");
473
		}
474
	}
475

    
476
	system_staticroutes_configure($interface, false);
477

    
478
	return 0;
479
}
480

    
481
function system_staticroutes_configure($interface = "", $update_dns = false) {
482
	global $config, $g, $aliastable;
483

    
484
	$filterdns_list = array();
485

    
486
	$static_routes = get_staticroutes(false, true);
487
	if (count($static_routes)) {
488
		$gateways_arr = return_gateways_array(false, true);
489

    
490
		foreach ($static_routes as $rtent) {
491
			if (empty($gateways_arr[$rtent['gateway']])) {
492
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
493
				continue;
494
			}
495
			$gateway = $gateways_arr[$rtent['gateway']];
496
			if (!empty($interface) && $interface != $gateway['friendlyiface'])
497
				continue;
498

    
499
			$gatewayip = $gateway['gateway'];
500
			$interfacegw = $gateway['interface'];
501

    
502
			$blackhole = "";
503
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 3)))
504
				$blackhole = "-blackhole";
505

    
506
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network']))
507
				continue;
508

    
509
			$dnscache = array();
510
			if ($update_dns === true) {
511
				if (is_subnet($rtent['network']))
512
					continue;
513
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
514
				if (empty($dnscache))
515
					continue;
516
			}
517

    
518
			if (is_subnet($rtent['network']))
519
				$ips = array($rtent['network']);
520
			else {
521
				if (!isset($rtent['disabled']))
522
					$filterdns_list[] = $rtent['network'];
523
				$ips = add_hostname_to_watch($rtent['network']);
524
			}
525

    
526
			foreach ($dnscache as $ip) {
527
				if (in_array($ip, $ips))
528
					continue;
529
				mwexec("/sbin/route delete " . escapeshellarg($ip), true);
530
			}
531

    
532
			if (isset($rtent['disabled'])) {
533
				/* XXX: This is a bit dangerous in case of routing daemons!? */
534
				foreach ($ips as $ip)
535
					mwexec("/sbin/route delete " . escapeshellarg($ip), true);
536
				continue;
537
			}
538

    
539
			foreach ($ips as $ip) {
540
				if (is_ipaddrv4($ip))
541
					$ip .= "/32";
542
				else if (is_ipaddrv6($ip))
543
					$ip .= "/128";
544

    
545
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
546

    
547
				$cmd = "/sbin/route change {$inet} {$blackhole} " . escapeshellarg($ip) . " ";
548

    
549
				if (is_subnet($ip))
550
					if (is_ipaddr($gatewayip))
551
						mwexec($cmd . escapeshellarg($gatewayip));
552
					else if (!empty($interfacegw))
553
						mwexec($cmd . "-iface " . escapeshellarg($interfacegw));
554
			}
555
		}
556
		unset($gateways_arr);
557
	}
558
	unset($static_routes);
559

    
560
	if ($update_dns === false) {
561
		if (count($filterdns_list)) {
562
			$interval = 60;
563
			$hostnames = "";
564
			array_unique($filterdns_list);
565
			foreach ($filterdns_list as $hostname)
566
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
567
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
568
			unset($hostnames);
569

    
570
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid"))
571
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
572
			else
573
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
574
		} else {
575
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
576
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
577
		}
578
	}
579
	unset($filterdns_list);
580

    
581
	return 0;
582
}
583

    
584
function system_routing_enable() {
585
	global $config, $g;
586
	if(isset($config['system']['developerspew'])) {
587
		$mt = microtime();
588
		echo "system_routing_enable() being called $mt\n";
589
	}
590

    
591
	mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
592
	mwexec("/sbin/sysctl net.inet6.ip6.forwarding=1");
593
	return;
594
}
595

    
596
function system_syslogd_fixup_server($server) {
597
	/* If it's an IPv6 IP alone, encase it in brackets */
598
	if (is_ipaddrv6($server))
599
		return "[$server]";
600
	else
601
		return $server;
602
}
603

    
604
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
605
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
606
	$facility .= " ".
607
	$remote_servers = "";
608
	$pad_to  = 56;
609
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
610
	if($syslogcfg['remoteserver'])
611
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
612
	if($syslogcfg['remoteserver2'])
613
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
614
	if($syslogcfg['remoteserver3'])
615
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
616
	return $remote_servers;
617
}
618

    
619
function system_syslogd_start() {
620
	global $config, $g;
621
	if(isset($config['system']['developerspew'])) {
622
		$mt = microtime();
623
		echo "system_syslogd_start() being called $mt\n";
624
	}
625

    
626
	mwexec("/etc/rc.d/hostid start");
627

    
628
	$syslogcfg = $config['syslog'];
629

    
630
	if ($g['booting'])
631
		echo gettext("Starting syslog...");
632

    
633
	if (is_process_running("fifolog_writer"))
634
		mwexec('/bin/pkill fifolog_writer');
635

    
636
	// Which logging type are we using this week??
637
	if (isset($config['system']['disablesyslogclog'])) {
638
		$log_directive = "";
639
		$log_create_directive = "/usr/bin/touch ";
640
		$log_size = "";
641
	} else if (isset($config['system']['usefifolog'])) {
642
		$log_directive = "|/usr/sbin/fifolog_writer ";
643
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
644
		$log_create_directive = "/usr/sbin/fifolog_create -s ";
645
	} else { // Defaults to CLOG
646
		$log_directive = "%";
647
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
648
		$log_create_directive = "/usr/local/sbin/clog -i -s ";
649
	}
650

    
651
	$syslogd_extra = "";
652
	if (isset($syslogcfg)) {
653
		$separatelogfacilities = array('ntp','ntpd','ntpdate','charon','openvpn','pptps','poes','l2tps','relayd','hostapd','dnsmasq','filterdns','unbound','dhcpd','dhcrelay','dhclient','apinger','radvd','routed','olsrd','zebra','ospfd','bgpd','miniupnpd','filterlog');
654
		$syslogconf = "";
655
		if($config['installedpackages']['package']) {
656
			foreach($config['installedpackages']['package'] as $package) {
657
				if($package['logging']) {
658
					array_push($separatelogfacilities, $package['logging']['facilityname']);
659
					mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
660
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
661
				}
662
			}
663
		}
664
		$facilitylist = implode(',', array_unique($separatelogfacilities));
665
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd,miniupnpd\n";
666
		if (!isset($syslogcfg['disablelocallogging']))
667
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
668

    
669
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
670
		if (!isset($syslogcfg['disablelocallogging'])) 
671
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
672

    
673
		$syslogconf .= "!ppp\n";
674
		if (!isset($syslogcfg['disablelocallogging'])) 
675
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
676

    
677
		$syslogconf .= "!pptps\n";
678
		if (!isset($syslogcfg['disablelocallogging'])) 
679
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/pptps.log\n";
680

    
681
		$syslogconf .= "!poes\n";
682
		if (!isset($syslogcfg['disablelocallogging'])) 
683
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
684

    
685
		$syslogconf .= "!l2tps\n";
686
		if (!isset($syslogcfg['disablelocallogging'])) 
687
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/l2tps.log\n";
688

    
689
		$syslogconf .= "!charon\n";
690
		if (!isset($syslogcfg['disablelocallogging'])) 
691
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ipsec.log\n";
692
		if (isset($syslogcfg['vpn']))
693
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
694

    
695
		$syslogconf .= "!openvpn\n";
696
		if (!isset($syslogcfg['disablelocallogging'])) 
697
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/openvpn.log\n";
698
		if (isset($syslogcfg['vpn']))
699
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
700

    
701
		$syslogconf .= "!apinger\n";
702
		if (!isset($syslogcfg['disablelocallogging']))
703
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/gateways.log\n";
704
		if (isset($syslogcfg['apinger']))
705
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
706

    
707
		$syslogconf .= "!dnsmasq,filterdns,unbound\n";
708
		if (!isset($syslogcfg['disablelocallogging']))
709
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
710

    
711
		$syslogconf .= "!dhcpd,dhcrelay,dhclient\n";
712
		if (!isset($syslogcfg['disablelocallogging']))
713
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/dhcpd.log\n";
714
		if (isset($syslogcfg['dhcp']))
715
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
716

    
717
		$syslogconf .= "!relayd\n";
718
		if (!isset($syslogcfg['disablelocallogging']))
719
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/relayd.log\n";
720
		if (isset($syslogcfg['relayd']))
721
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
722

    
723
		$syslogconf .= "!hostapd\n";
724
		if (!isset($syslogcfg['disablelocallogging']))
725
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
726
		if (isset($syslogcfg['hostapd']))
727
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
728

    
729
		$syslogconf .= "!filterlog\n";
730
		$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/filter.log\n";
731
		if (isset($syslogcfg['filter']))
732
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
733

    
734
		$syslogconf .= "!-{$facilitylist}\n";
735
		if (!isset($syslogcfg['disablelocallogging'])) 
736
			$syslogconf .= <<<EOD
737
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
738
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
739
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
740
*.notice;kern.debug;lpr.info;mail.crit;daemon.none;		{$log_directive}{$g['varlog_path']}/system.log
741
news.err;local0.none;local3.none;local4.none;			{$log_directive}{$g['varlog_path']}/system.log
742
local7.none							{$log_directive}{$g['varlog_path']}/system.log
743
security.*							{$log_directive}{$g['varlog_path']}/system.log
744
auth.info;authpriv.info;daemon.info				{$log_directive}{$g['varlog_path']}/system.log
745
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
746
*.emerg								*
747

    
748
EOD;
749
		if (isset($syslogcfg['vpn']))
750
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
751
		if (isset($syslogcfg['portalauth']))
752
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
753
		if (isset($syslogcfg['dhcp']))
754
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
755
		if (isset($syslogcfg['system'])) {
756
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.notice;kern.debug;lpr.info;mail.crit;");
757
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "news.err;local0.none;local3.none;local7.none");
758
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "security.*");
759
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "auth.info;authpriv.info;daemon.info");
760
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.emerg");
761
		}
762
		if (isset($syslogcfg['logall'])) {
763
			// Make everything mean everything, including facilities excluded above.
764
			$syslogconf .= "!*\n";
765
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
766
		}
767

    
768
		if (isset($syslogcfg['zmqserver'])) {
769
				$syslogconf .= <<<EOD
770
*.*								^{$syslogcfg['zmqserver']}
771

    
772
EOD;
773
		}
774
		/* write syslog.conf */		
775
		if (!@file_put_contents("{$g['varetc_path']}/syslog.conf", $syslogconf)) {
776
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
777
			unset($syslogconf);
778
			return 1;
779
		}
780
		unset($syslogconf);
781

    
782
		// Ensure that the log directory exists
783
		if (!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
784
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
785

    
786
		$sourceip = "";
787
		if (!empty($syslogcfg['sourceip'])) {
788
			if ($syslogcfg['ipproto'] == "ipv6") {
789
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
790
				if (!is_ipaddr($ifaddr))
791
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
792
			} else {
793
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
794
				if (!is_ipaddr($ifaddr))
795
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
796
			}
797
			if (is_ipaddr($ifaddr)) {
798
				$sourceip = "-b {$ifaddr}";
799
			}
800
		}
801

    
802
		$syslogd_extra = "-f {$g['varetc_path']}/syslog.conf {$sourceip}";
803
	}
804

    
805
	if (isvalidpid("{$g['varrun_path']}/syslog.pid"))
806
		sigkillbypid("{$g['varrun_path']}/syslog.pid", "HUP");
807
	else
808
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c -l {$g['dhcpd_chroot_path']}/var/run/log -P {$g['varrun_path']}/syslog.pid {$syslogd_extra}");
809

    
810
	if ($g['booting'])
811
		echo gettext("done.") . "\n";
812

    
813
	return $retval;
814
}
815

    
816
function system_webgui_start() {
817
	global $config, $g;
818

    
819
	if ($g['booting'])
820
		echo gettext("Starting webConfigurator...");
821

    
822
	chdir($g['www_path']);
823

    
824
	/* defaults */
825
	$portarg = "80";
826
	$crt = "";
827
	$key = "";
828
	$ca = "";
829

    
830
	/* non-standard port? */
831
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
832
		$portarg = "{$config['system']['webgui']['port']}";
833

    
834
	if ($config['system']['webgui']['protocol'] == "https") {
835
		// Ensure that we have a webConfigurator CERT
836
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
837
		if(!is_array($cert) && !$cert['crt'] && !$cert['prv']) {
838
			if (!is_array($config['ca']))
839
				$config['ca'] = array();
840
			$a_ca =& $config['ca'];
841
			if (!is_array($config['cert']))
842
				$config['cert'] = array();
843
			$a_cert =& $config['cert'];
844
			log_error("Creating SSL Certificate for this host");
845
			$cert = array();
846
			$cert['refid'] = uniqid();
847
			$cert['descr'] = gettext("webConfigurator default");
848
			mwexec("/usr/bin/openssl genrsa 1024 > {$g['tmp_path']}/ssl.key");
849
			mwexec("/usr/bin/openssl req -new -x509 -nodes -sha256 -days 2000 -key {$g['tmp_path']}/ssl.key > {$g['tmp_path']}/ssl.crt");
850
			$crt = file_get_contents("{$g['tmp_path']}/ssl.crt");
851
			$key = file_get_contents("{$g['tmp_path']}/ssl.key");
852
			unlink("{$g['tmp_path']}/ssl.key");
853
			unlink("{$g['tmp_path']}/ssl.crt");
854
			cert_import($cert, $crt, $key);
855
			$a_cert[] = $cert;
856
			$config['system']['webgui']['ssl-certref'] = $cert['refid'];
857
			write_config(gettext("Importing HTTPS certificate"));
858
			if(!$config['system']['webgui']['port'])
859
				$portarg = "443";
860
			$ca = ca_chain($cert);
861
		} else {
862
			$crt = base64_decode($cert['crt']);
863
			$key = base64_decode($cert['prv']);
864
			if(!$config['system']['webgui']['port'])
865
				$portarg = "443";
866
			$ca = ca_chain($cert);
867
		}
868
	}
869

    
870
	/* generate lighttpd configuration */
871
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
872
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
873
		"cert.pem", "ca.pem");
874

    
875
	/* kill any running lighttpd */
876
	killbypid("{$g['varrun_path']}/lighty-webConfigurator.pid");
877

    
878
	sleep(1);
879

    
880
	@unlink("{$g['varrun_path']}/lighty-webConfigurator.pid");
881

    
882
	/* attempt to start lighthttpd */
883
	$res = mwexec("/usr/local/sbin/lighttpd -f {$g['varetc_path']}/lighty-webConfigurator.conf");
884

    
885
	if ($g['booting']) {
886
		if ($res == 0)
887
			echo gettext("done.") . "\n";
888
		else
889
			echo gettext("failed!") . "\n";
890
	}
891

    
892
	return $res;
893
}
894

    
895
function system_generate_lighty_config($filename,
896
	$cert,
897
	$key,
898
	$ca,
899
	$pid_file,
900
	$port = 80,
901
	$document_root = "/usr/local/www/",
902
	$cert_location = "cert.pem",
903
	$ca_location = "ca.pem",
904
	$captive_portal = false) {
905

    
906
	global $config, $g;
907

    
908
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
909
		mkdir("{$g['tmp_path']}/lighttpdcompress");
910

    
911
	if(isset($config['system']['developerspew'])) {
912
		$mt = microtime();
913
		echo "system_generate_lighty_config() being called $mt\n";
914
	}
915

    
916
	if ($captive_portal !== false)  {
917
		$captiveportal = ",\"mod_rewrite\",\"mod_evasive\"";
918
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?zone={$captive_portal}&redirurl=$1\" )\n";
919

    
920
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
921
		if (empty($maxprocperip))
922
			$maxprocperip = 10;
923
		$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
924

    
925
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
926
		if(!is_dir("{$g['tmp_path']}/captiveportal"))
927
			@mkdir("{$g['tmp_path']}/captiveportal", 0555);
928
		$server_max_request_size = "server.max-request-size    = 384";
929
		$cgi_config = "";
930
	} else {
931
		$captiveportal = ",\"mod_cgi\"";
932
		$captive_portal_rewrite = "";
933
		$captive_portal_mod_evasive = "";
934
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
935
		$server_max_request_size = "server.max-request-size    = 2097152";
936
		$cgi_config = "cgi.assign                 = ( \".cgi\" => \"\" )";
937
	}
938
	
939
	if (empty($port))
940
		$lighty_port = "80";
941
	else
942
		$lighty_port = $port;
943

    
944
	$memory = get_memory();
945
	$realmem = $memory[1];
946

    
947
	// Determine web GUI process settings and take into account low memory systems
948
	if ($realmem < 255)
949
		$max_procs = 1;
950
	else
951
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
952

    
953
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM 
954
	if ($captive_portal !== false)  {
955
		if ($realmem > 135 and $realmem < 256) {
956
			$max_procs += 1; // 2 worker processes
957
		} else if ($realmem > 255 and $realmem < 513) {
958
			$max_procs += 2; // 3 worker processes
959
		} else if ($realmem > 512) {
960
			$max_procs += 4; // 6 worker processes
961
		}
962
		if ($max_procs > 1)
963
			$max_php_children = intval($max_procs/2);
964
		else
965
			$max_php_children = 1;
966

    
967
	} else {
968
		if ($realmem < 78)
969
			$max_php_children = 0;
970
		else
971
			$max_php_children = 1;
972
	}
973

    
974
	if(!isset($config['syslog']['nologlighttpd'])) {
975
		$lighty_use_syslog = <<<EOD
976
## where to send error-messages to
977
server.errorlog-use-syslog="enable"
978
EOD;
979
	}
980

    
981

    
982
	if ($captive_portal !== false) {
983
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi-{$captive_portal}.socket";
984
		$fastcgi_config = <<<EOD
985
#### fastcgi module
986
## read fastcgi.txt for more info
987
fastcgi.server = ( ".php" =>
988
	( "localhost" =>
989
		(
990
			"socket" => "{$fast_cgi_path}",
991
			"max-procs" => {$max_procs},
992
			"bin-environment" => (
993
				"PHP_FCGI_CHILDREN" => "{$max_php_children}",
994
				"PHP_FCGI_MAX_REQUESTS" => "500"
995
			),
996
			"bin-path" => "/usr/local/bin/php"
997
		)
998
	)
999
)
1000

    
1001
EOD;
1002
	} else {
1003
		$fast_cgi_path = "{$g['varrun_path']}/php-fpm.socket";
1004
		$fastcgi_config = <<<EOD
1005
#### fastcgi module
1006
## read fastcgi.txt for more info
1007
fastcgi.server = ( ".php" =>
1008
	( "localhost" =>
1009
		(
1010
			"socket" => "{$fast_cgi_path}",
1011
			"broken-scriptfilename" => "enable"
1012
		)
1013
	)
1014
)
1015

    
1016
EOD;
1017
	}
1018

    
1019

    
1020
	$lighty_config = <<<EOD
1021
#
1022
# lighttpd configuration file
1023
#
1024
# use a it as base for lighttpd 1.0.0 and above
1025
#
1026
############ Options you really have to take care of ####################
1027

    
1028
## FreeBSD!
1029
server.event-handler	= "freebsd-kqueue"
1030
server.network-backend 	= "writev"
1031
#server.use-ipv6 = "enable"
1032

    
1033
## modules to load
1034
server.modules              =   ( "mod_access", "mod_expire", "mod_compress", "mod_redirect",
1035
	{$captiveportal}, "mod_fastcgi"
1036
)
1037

    
1038
server.max-keep-alive-requests = 15
1039
server.max-keep-alive-idle = 30
1040

    
1041
## a static document-root, for virtual-hosting take look at the
1042
## server.virtual-* options
1043
server.document-root        = "{$document_root}"
1044
{$captive_portal_rewrite}
1045

    
1046
# Maximum idle time with nothing being written (php downloading)
1047
server.max-write-idle = 999
1048

    
1049
{$lighty_use_syslog}
1050

    
1051
# files to check for if .../ is requested
1052
server.indexfiles           = ( "index.php", "index.html",
1053
                                "index.htm", "default.htm" )
1054

    
1055
# mimetype mapping
1056
mimetype.assign             = (
1057
  ".pdf"          =>      "application/pdf",
1058
  ".sig"          =>      "application/pgp-signature",
1059
  ".spl"          =>      "application/futuresplash",
1060
  ".class"        =>      "application/octet-stream",
1061
  ".ps"           =>      "application/postscript",
1062
  ".torrent"      =>      "application/x-bittorrent",
1063
  ".dvi"          =>      "application/x-dvi",
1064
  ".gz"           =>      "application/x-gzip",
1065
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
1066
  ".swf"          =>      "application/x-shockwave-flash",
1067
  ".tar.gz"       =>      "application/x-tgz",
1068
  ".tgz"          =>      "application/x-tgz",
1069
  ".tar"          =>      "application/x-tar",
1070
  ".zip"          =>      "application/zip",
1071
  ".mp3"          =>      "audio/mpeg",
1072
  ".m3u"          =>      "audio/x-mpegurl",
1073
  ".wma"          =>      "audio/x-ms-wma",
1074
  ".wax"          =>      "audio/x-ms-wax",
1075
  ".ogg"          =>      "audio/x-wav",
1076
  ".wav"          =>      "audio/x-wav",
1077
  ".gif"          =>      "image/gif",
1078
  ".jpg"          =>      "image/jpeg",
1079
  ".jpeg"         =>      "image/jpeg",
1080
  ".png"          =>      "image/png",
1081
  ".xbm"          =>      "image/x-xbitmap",
1082
  ".xpm"          =>      "image/x-xpixmap",
1083
  ".xwd"          =>      "image/x-xwindowdump",
1084
  ".css"          =>      "text/css",
1085
  ".html"         =>      "text/html",
1086
  ".htm"          =>      "text/html",
1087
  ".js"           =>      "text/javascript",
1088
  ".asc"          =>      "text/plain",
1089
  ".c"            =>      "text/plain",
1090
  ".conf"         =>      "text/plain",
1091
  ".text"         =>      "text/plain",
1092
  ".txt"          =>      "text/plain",
1093
  ".dtd"          =>      "text/xml",
1094
  ".xml"          =>      "text/xml",
1095
  ".mpeg"         =>      "video/mpeg",
1096
  ".mpg"          =>      "video/mpeg",
1097
  ".mov"          =>      "video/quicktime",
1098
  ".qt"           =>      "video/quicktime",
1099
  ".avi"          =>      "video/x-msvideo",
1100
  ".asf"          =>      "video/x-ms-asf",
1101
  ".asx"          =>      "video/x-ms-asf",
1102
  ".wmv"          =>      "video/x-ms-wmv",
1103
  ".bz2"          =>      "application/x-bzip",
1104
  ".tbz"          =>      "application/x-bzip-compressed-tar",
1105
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
1106
 )
1107

    
1108
# Use the "Content-Type" extended attribute to obtain mime type if possible
1109
#mimetypes.use-xattr        = "enable"
1110

    
1111
## deny access the file-extensions
1112
#
1113
# ~    is for backupfiles from vi, emacs, joe, ...
1114
# .inc is often used for code includes which should in general not be part
1115
#      of the document-root
1116
url.access-deny             = ( "~", ".inc" )
1117

    
1118

    
1119
######### Options that are good to be but not neccesary to be changed #######
1120

    
1121
## bind to port (default: 80)
1122

    
1123
EOD;
1124

    
1125
	$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1126
	$lighty_config .= "server.port  = {$lighty_port}\n";
1127
	$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1128
	$lighty_config .= "\$SERVER[\"socket\"]  == \"[::]:{$lighty_port}\" { \n";
1129
	if($cert <> "" and $key <> "") {
1130
		$lighty_config .= "\n";
1131
		$lighty_config .= "## ssl configuration\n";
1132
		$lighty_config .= "ssl.engine = \"enable\"\n";
1133
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1134
		if($ca <> "")
1135
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1136
	}
1137
	$lighty_config .= " }\n";
1138

    
1139

    
1140
	$lighty_config .= <<<EOD
1141

    
1142
## error-handler for status 404
1143
#server.error-handler-404   = "/error-handler.html"
1144
#server.error-handler-404   = "/error-handler.php"
1145

    
1146
## to help the rc.scripts
1147
server.pid-file            = "{$g['varrun_path']}/{$pid_file}"
1148

    
1149
## virtual directory listings
1150
server.dir-listing         = "disable"
1151

    
1152
## enable debugging
1153
debug.log-request-header   = "disable"
1154
debug.log-response-header  = "disable"
1155
debug.log-request-handling = "disable"
1156
debug.log-file-not-found   = "disable"
1157

    
1158
# gzip compression
1159
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1160
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1161

    
1162
{$server_upload_dirs}
1163

    
1164
{$server_max_request_size}
1165

    
1166
{$fastcgi_config}
1167

    
1168
{$cgi_config}
1169

    
1170
{$captive_portal_mod_evasive}
1171

    
1172
expire.url = (
1173
				"" => "access 50 hours",	
1174
        )
1175

    
1176
EOD;
1177

    
1178
	$cert = str_replace("\r", "", $cert);
1179
	$key = str_replace("\r", "", $key);
1180
	$ca = str_replace("\r", "", $ca);
1181

    
1182
	$cert = str_replace("\n\n", "\n", $cert);
1183
	$key = str_replace("\n\n", "\n", $key);
1184
	$ca = str_replace("\n\n", "\n", $ca);
1185

    
1186
	if($cert <> "" and $key <> "") {
1187
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1188
		if (!$fd) {
1189
			printf(gettext("Error: cannot open cert.pem in system_webgui_start().%s"), "\n");
1190
			return 1;
1191
		}
1192
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1193
		fwrite($fd, $cert);
1194
		fwrite($fd, "\n");
1195
		fwrite($fd, $key);
1196
		fclose($fd);
1197
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
1198
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1199
			if (!$fd) {
1200
				printf(gettext("Error: cannot open ca.pem in system_webgui_start().%s"), "\n");
1201
				return 1;
1202
			}
1203
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1204
			fwrite($fd, $ca);
1205
			fclose($fd);
1206
		}
1207
		$lighty_config .= "\n";
1208
		$lighty_config .= "## " . gettext("ssl configuration") . "\n";
1209
		$lighty_config .= "ssl.engine = \"enable\"\n";
1210
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1211

    
1212
		// Harden SSL a bit for PCI conformance testing
1213
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
1214

    
1215
		/* Hifn accelerators do NOT work with the BEAST mitigation code. Do not allow it to be enabled if a Hifn card has been detected. */
1216
		$fd = @fopen("{$g['varlog_path']}/dmesg.boot", "r");
1217
		if ($fd) {
1218
			while (!feof($fd)) {
1219
				$dmesgl = fgets($fd);
1220
				if (preg_match("/^hifn.: (.*?),/", $dmesgl, $matches) && isset($config['system']['webgui']['beast_protection'])) {
1221
						unset($config['system']['webgui']['beast_protection']);
1222
						log_error("BEAST Protection disabled because a conflicting cryptographic accelerator card has been detected (" . $matches[1] . ")");
1223
					break;
1224
				}
1225
			}
1226
			fclose($fd);
1227
		}
1228

    
1229
		if (isset($config['system']['webgui']['beast_protection'])) {
1230
			$lighty_config .= "ssl.honor-cipher-order = \"enable\"\n";
1231
			$lighty_config .= "ssl.cipher-list = \"ECDHE-RSA-AES256-SHA384:AES256-SHA256:RC4-SHA:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM\"\n";
1232
		} else {
1233
			$lighty_config .= "ssl.cipher-list = \"DHE-RSA-CAMELLIA256-SHA:DHE-DSS-CAMELLIA256-SHA:CAMELLIA256-SHA:DHE-DSS-AES256-SHA:AES256-SHA:DHE-RSA-CAMELLIA128-SHA:DHE-DSS-CAMELLIA128-SHA:CAMELLIA128-SHA:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA:AES128-SHA:RC4-SHA:RC4-MD5:!aNULL:!eNULL:!3DES:@STRENGTH\"\n";
1234
		}
1235

    
1236
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1237
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1238
	}
1239

    
1240
	// Add HTTP to HTTPS redirect	
1241
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1242
		if($lighty_port != "443") 
1243
			$redirectport = ":{$lighty_port}";
1244
		$lighty_config .= <<<EOD
1245
\$SERVER["socket"] == ":80" {
1246
	\$HTTP["host"] =~ "(.*)" {
1247
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1248
	}
1249
}
1250
\$SERVER["socket"] == "[::]:80" {
1251
	\$HTTP["host"] =~ "(.*)" {
1252
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1253
	}
1254
}
1255
EOD;
1256
	}
1257

    
1258
	$fd = fopen("{$filename}", "w");
1259
	if (!$fd) {
1260
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1261
		return 1;
1262
	}
1263
	fwrite($fd, $lighty_config);
1264
	fclose($fd);
1265

    
1266
	return 0;
1267

    
1268
}
1269

    
1270
function system_timezone_configure() {
1271
	global $config, $g;
1272
	if(isset($config['system']['developerspew'])) {
1273
		$mt = microtime();
1274
		echo "system_timezone_configure() being called $mt\n";
1275
	}
1276

    
1277
	$syscfg = $config['system'];
1278

    
1279
	if ($g['booting'])
1280
		echo gettext("Setting timezone...");
1281

    
1282
	/* extract appropriate timezone file */
1283
	$timezone = $syscfg['timezone'];
1284
	if ($timezone) {
1285
		exec('/usr/bin/tar -tvzf /usr/share/zoneinfo.tgz', $tzs);
1286
		foreach ($tzs as $tz) {
1287
			if (preg_match(",{$timezone}$,", $tz))
1288
				break;
1289
			if (preg_match(",{$timezone} link to *(.*)$,", $tz, $matches)) {
1290
				$timezone = $matches[1];
1291
				break;
1292
			}
1293
		}
1294
	} else
1295
		$timezone = "Etc/UTC";
1296

    
1297
	conf_mount_rw();
1298

    
1299
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1300
		escapeshellarg($timezone) . " > /etc/localtime");
1301

    
1302
	mwexec("sync");
1303
	conf_mount_ro();
1304

    
1305
	if ($g['booting'])
1306
		echo gettext("done.") . "\n";
1307
}
1308

    
1309
function system_ntp_setup_gps($serialport) {
1310
	global $config, $g;
1311
	$gps_device = '/dev/gps0';
1312
	$serialport = '/dev/'.$serialport;
1313

    
1314
	if (!file_exists($serialport))
1315
		return false;
1316

    
1317
	conf_mount_rw();
1318
	// Create symlink that ntpd requires
1319
	unlink_if_exists($gps_device);
1320
	symlink($serialport, $gps_device);
1321

    
1322
	/* Send the following to the GPS port to initialize the GPS */
1323
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
1324
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
1325
	}else{
1326
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1327
	}
1328

    
1329
	/* XXX: Why not file_put_contents to the device */
1330
	@file_put_contents('/tmp/gps.init', $gps_init);
1331
	`cat /tmp/gps.init > $serialport`;
1332

    
1333
	/* Add /etc/remote entry in case we need to read from the GPS with tip */
1334
	if (intval(`grep -c '^gps0' /etc/remote`) == 0) {
1335
		$gpsbaud = '4800';
1336
		if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['speed'])) {
1337
			switch($config['ntpd']['gps']['speed']) {
1338
				case '16':
1339
					$gpsbaud = '9600';
1340
					break;
1341
				case '32':
1342
					$gpsbaud = '19200';
1343
					break;
1344
				case '48':
1345
					$gpsbaud = '38400';
1346
					break;
1347
				case '64':
1348
					$gpsbaud = '57600';
1349
					break;
1350
				case '80':
1351
					$gpsbaud = '115200';
1352
					break;
1353
			}
1354
		}
1355
		@file_put_contents("/etc/remote", "gps0:dv={$serialport}:br#{$gpsbaud}:pa=none:", FILE_APPEND);
1356
	}
1357

    
1358
	conf_mount_ro();
1359

    
1360
	return true;
1361
}
1362

    
1363
function system_ntp_setup_pps($serialport) {
1364
	global $config, $g;
1365

    
1366
	$pps_device = '/dev/pps0';
1367
	$serialport = '/dev/'.$serialport;
1368

    
1369
	if (!file_exists($serialport))
1370
		return false;
1371

    
1372
	conf_mount_rw();
1373
	// Create symlink that ntpd requires
1374
	unlink_if_exists($pps_device);
1375
	@symlink($serialport, $pps_device);
1376

    
1377
	conf_mount_ro();
1378

    
1379
	return true;
1380
}
1381

    
1382

    
1383
function system_ntp_configure($start_ntpd=true) {
1384
	global $config, $g;
1385

    
1386
	$driftfile = "/var/db/ntpd.drift";
1387
	$statsdir = "/var/log/ntp";
1388
	$gps_device = '/dev/gps0';
1389

    
1390
	if ($g['platform'] == 'jail')
1391
		return;
1392

    
1393
	safe_mkdir($statsdir);
1394

    
1395
	if (!is_array($config['ntpd']))
1396
		$config['ntpd'] = array();
1397

    
1398
	$ntpcfg = "# \n";
1399
	$ntpcfg .= "# pfSense ntp configuration file \n";
1400
	$ntpcfg .= "# \n\n";
1401
	$ntpcfg .= "tinker panic 0 \n";
1402

    
1403
	/* Add Orphan mode */
1404
	$ntpcfg .= "# Orphan mode stratum\n";
1405
	$ntpcfg .= 'tos orphan ';
1406
	if (!empty($config['ntpd']['orphan'])) {
1407
		$ntpcfg .= $config['ntpd']['orphan'];
1408
	}else{
1409
		$ntpcfg .= '12';
1410
	}
1411
	$ntpcfg .= "\n";
1412

    
1413
	/* Add PPS configuration */
1414
	if (!empty($config['ntpd']['pps'])
1415
		&& file_exists('/dev/'.$config['ntpd']['pps']['port'])
1416
		&& system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
1417
		$ntpcfg .= "\n";
1418
		$ntpcfg .= "# PPS Setup\n";
1419
		$ntpcfg .= 'server 127.127.22.0';
1420
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1421
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
1422
			$ntpcfg .= ' prefer'; 
1423
		}
1424
		if (!empty($config['ntpd']['pps']['noselect'])) {
1425
			$ntpcfg .= ' noselect ';
1426
		}
1427
		$ntpcfg .= "\n";
1428
		$ntpcfg .= 'fudge 127.127.22.0';
1429
		if (!empty($config['ntpd']['pps']['fudge1'])) {
1430
			$ntpcfg .= ' time1 ';
1431
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
1432
		}
1433
		if (!empty($config['ntpd']['pps']['flag2'])) {
1434
			$ntpcfg .= ' flag2 1';
1435
		}
1436
		if (!empty($config['ntpd']['pps']['flag3'])) {
1437
			$ntpcfg .= ' flag3 1';
1438
		}else{
1439
			$ntpcfg .= ' flag3 0';
1440
		}
1441
		if (!empty($config['ntpd']['pps']['flag4'])) {
1442
			$ntpcfg .= ' flag4 1';
1443
		}
1444
		if (!empty($config['ntpd']['pps']['refid'])) {
1445
			$ntpcfg .= ' refid ';
1446
			$ntpcfg .= $config['ntpd']['pps']['refid'];
1447
		}
1448
		$ntpcfg .= "\n";
1449
	}
1450
	/* End PPS configuration */
1451

    
1452
	/* Add GPS configuration */
1453
	if (!empty($config['ntpd']['gps'])
1454
		&& file_exists('/dev/'.$config['ntpd']['gps']['port'])
1455
		&& system_ntp_setup_gps($config['ntpd']['gps']['port'])) {
1456
		$ntpcfg .= "\n";
1457
		$ntpcfg .= "# GPS Setup\n";
1458
		$ntpcfg .= 'server 127.127.20.0 mode ';
1459
		if (!empty($config['ntpd']['gps']['nmea']) || !empty($config['ntpd']['gps']['speed']) || !empty($config['ntpd']['gps']['subsec'])) {
1460
			if (!empty($config['ntpd']['gps']['nmea'])) {
1461
				$ntpmode = (int) $config['ntpd']['gps']['nmea'];
1462
			}
1463
			if (!empty($config['ntpd']['gps']['speed'])) {
1464
				$ntpmode += (int) $config['ntpd']['gps']['speed'];
1465
			}
1466
			if (!empty($config['ntpd']['gps']['subsec'])) {
1467
				$ntpmode += 128;
1468
			}
1469
			$ntpcfg .= (string) $ntpmode;
1470
		}else{
1471
			$ntpcfg .= '0';
1472
		}
1473
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1474
		if (empty($config['ntpd']['gps']['prefer'])) { /*note: this one works backwards */
1475
			$ntpcfg .= ' prefer'; 
1476
		}
1477
		if (!empty($config['ntpd']['gps']['noselect'])) {
1478
			$ntpcfg .= ' noselect ';
1479
		}
1480
		$ntpcfg .= "\n";
1481
		$ntpcfg .= 'fudge 127.127.20.0';
1482
		if (!empty($config['ntpd']['gps']['fudge1'])) {
1483
			$ntpcfg .= ' time1 ';
1484
			$ntpcfg .= $config['ntpd']['gps']['fudge1'];
1485
		}
1486
		if (!empty($config['ntpd']['gps']['fudge2'])) {
1487
			$ntpcfg .= ' time2 ';
1488
			$ntpcfg .= $config['ntpd']['gps']['fudge2'];
1489
		}
1490
		if (!empty($config['ntpd']['gps']['flag1'])) {
1491
			$ntpcfg .= ' flag1 1';
1492
		}else{
1493
			$ntpcfg .= ' flag1 0';
1494
		}
1495
		if (!empty($config['ntpd']['gps']['flag2'])) {
1496
			$ntpcfg .= ' flag2 1';
1497
		}
1498
		if (!empty($config['ntpd']['gps']['flag3'])) {
1499
			$ntpcfg .= ' flag3 1';
1500
		}else{
1501
			$ntpcfg .= ' flag3 0';
1502
		}
1503
		if (!empty($config['ntpd']['gps']['flag4'])) {
1504
			$ntpcfg .= ' flag4 1';
1505
		}
1506
		if (!empty($config['ntpd']['gps']['refid'])) {
1507
			$ntpcfg .= ' refid ';
1508
			$ntpcfg .= $config['ntpd']['gps']['refid'];
1509
		}
1510
		$ntpcfg .= "\n";
1511
	}elseif (!empty($config['ntpd']['gpsport'])
1512
		&& file_exists('/dev/'.$config['ntpd']['gpsport'])
1513
		&& system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1514
		/* This handles a 2.1 and earlier config */
1515
		$ntpcfg .= "# GPS Setup\n";
1516
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1517
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1518
		// Fall back to local clock if GPS is out of sync?
1519
		$ntpcfg .= "server 127.127.1.0\n";
1520
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1521
	}
1522
	/* End GPS configuration */
1523
	
1524
	$ntpcfg .= "\n\n# Upstream Servers\n";
1525
	/* foreach through ntp servers and write out to ntpd.conf */
1526
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1527
		$ntpcfg .= "server {$ts} iburst maxpoll 9";
1528
		if (substr_count($config['ntpd']['prefer'], $ts)) $ntpcfg .= ' prefer';
1529
		if (substr_count($config['ntpd']['noselect'], $ts)) $ntpcfg .= ' noselect';
1530
		$ntpcfg .= "\n";
1531
	}
1532
	unset($ts);
1533

    
1534
	$ntpcfg .= "\n\n";
1535
	$ntpcfg .= "disable monitor\n"; //prevent NTP reflection attack, see https://forum.pfsense.org/index.php/topic,67189.msg389132.html#msg389132
1536
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
1537
		$ntpcfg .= "enable stats\n";
1538
		$ntpcfg .= 'statistics';
1539
		if (!empty($config['ntpd']['clockstats'])) {
1540
			$ntpcfg .= ' clockstats';
1541
		}
1542
		if (!empty($config['ntpd']['loopstats'])) {
1543
			$ntpcfg .= ' loopstats';
1544
		}
1545
		if (!empty($config['ntpd']['peerstats'])) {
1546
			$ntpcfg .= ' peerstats';
1547
		}
1548
		$ntpcfg .= "\n";
1549
	}
1550
	$ntpcfg .= "statsdir {$statsdir}\n";
1551
	$ntpcfg .= 'logconfig =syncall +clockall';
1552
	if (!empty($config['ntpd']['logpeer'])) {
1553
		$ntpcfg .= ' +peerall';
1554
	}
1555
	if (!empty($config['ntpd']['logsys'])) {
1556
		$ntpcfg .= ' +sysall';
1557
	}
1558
	$ntpcfg .= "\n";
1559
	$ntpcfg .= "driftfile {$driftfile}\n";
1560
	/* Access restrictions */
1561
	$ntpcfg .= 'restrict default';
1562
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1563
		$ntpcfg .= ' kod limited'; 
1564
	}
1565
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1566
		$ntpcfg .= ' nomodify'; 
1567
	}
1568
	if (!empty($config['ntpd']['noquery'])) {
1569
		$ntpcfg .= ' noquery';
1570
	}
1571
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1572
		$ntpcfg .= ' nopeer'; 
1573
	}
1574
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1575
		$ntpcfg .= ' notrap'; 
1576
	}
1577
	if (!empty($config['ntpd']['noserve'])) {
1578
		$ntpcfg .= ' noserve';
1579
	}
1580
	$ntpcfg .= "\nrestrict -6 default";
1581
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1582
		$ntpcfg .= ' kod limited'; 
1583
	}
1584
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1585
		$ntpcfg .= ' nomodify'; 
1586
	}
1587
	if (!empty($config['ntpd']['noquery'])) {
1588
		$ntpcfg .= ' noquery';
1589
	}
1590
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1591
		$ntpcfg .= ' nopeer'; 
1592
	}
1593
	if (!empty($config['ntpd']['noserve'])) {
1594
		$ntpcfg .= ' noserve';
1595
	}
1596
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1597
		$ntpcfg .= ' notrap'; 
1598
	}
1599
	$ntpcfg .= "\n";
1600

    
1601
	/* A leapseconds file is really only useful if this clock is stratum 1 */
1602
	$ntpcfg .= "\n";
1603
	if (!empty($config['ntpd']['leapsec'])) {
1604
		$leapsec .= base64_decode($config['ntpd']['leapsec']);
1605
		file_put_contents('/var/db/leap-seconds', $leapsec);
1606
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
1607
	}
1608
	
1609

    
1610
	if (empty($config['ntpd']['interface']))
1611
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface']))
1612
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1613
		else
1614
			$interfaces = array();
1615
	else
1616
		$interfaces = explode(",", $config['ntpd']['interface']);
1617

    
1618
	if (is_array($interfaces) && count($interfaces)) {
1619
		$ntpcfg .= "interface ignore all\n";
1620
		foreach ($interfaces as $interface) {
1621
			if (!is_ipaddr($interface)) {
1622
				$interface = get_real_interface($interface);
1623
			}
1624
			if (!empty($interface))
1625
				$ntpcfg .= "interface listen {$interface}\n";
1626
		}
1627
	}
1628

    
1629
	/* open configuration for wrting or bail */
1630
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
1631
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1632
		return;
1633
	}
1634

    
1635
	/* At bootup we just want to write out the config. */
1636
	if (!$start_ntpd)
1637
		return;
1638

    
1639
	/* if ntpd is running, kill it */
1640
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1641
		killbypid("{$g['varrun_path']}/ntpd.pid");
1642
	}
1643
	@unlink("{$g['varrun_path']}/ntpd.pid");
1644

    
1645
	/* if /var/empty does not exist, create it */
1646
	if(!is_dir("/var/empty"))
1647
		mkdir("/var/empty", 0775, true);
1648

    
1649
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1650
	mwexec("/usr/local/sbin/ntpd -g -c {$g['varetc_path']}/ntpd.conf -p {$g['varrun_path']}/ntpd.pid", false, true);
1651
	
1652
	// Note that we are starting up
1653
	log_error("NTPD is starting up.");
1654
	return;
1655
}
1656

    
1657
function sync_system_time() {
1658
	global $config, $g;
1659

    
1660
	if ($g['booting'])
1661
		echo gettext("Syncing system time before startup...");
1662

    
1663
	/* foreach through servers and write out to ntpd.conf */
1664
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1665
		mwexec("/usr/local/sbin/ntpdate -s $ts");
1666
	}
1667
	
1668
	if ($g['booting'])
1669
		echo gettext("done.") . "\n";
1670
	
1671
}
1672

    
1673
function system_halt() {
1674
	global $g;
1675

    
1676
	system_reboot_cleanup();
1677

    
1678
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1679
}
1680

    
1681
function system_reboot() {
1682
	global $g;
1683

    
1684
	system_reboot_cleanup();
1685

    
1686
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1687
}
1688

    
1689
function system_reboot_sync() {
1690
	global $g;
1691

    
1692
	system_reboot_cleanup();
1693

    
1694
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1695
}
1696

    
1697
function system_reboot_cleanup() {
1698
	global $config, $cpzone;
1699

    
1700
	mwexec("/usr/local/bin/beep.sh stop");
1701
	require_once("captiveportal.inc");
1702
	if (is_array($config['captiveportal'])) {
1703
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
1704
			captiveportal_radius_stop_all();
1705
			captiveportal_send_server_accounting(true);
1706
		}
1707
	}
1708
	require_once("voucher.inc");
1709
	voucher_save_db_to_config();
1710
	require_once("pkg-utils.inc");
1711
	stop_packages();
1712
}
1713

    
1714
function system_do_shell_commands($early = 0) {
1715
	global $config, $g;
1716
	if(isset($config['system']['developerspew'])) {
1717
		$mt = microtime();
1718
		echo "system_do_shell_commands() being called $mt\n";
1719
	}
1720

    
1721
	if ($early)
1722
		$cmdn = "earlyshellcmd";
1723
	else
1724
		$cmdn = "shellcmd";
1725

    
1726
	if (is_array($config['system'][$cmdn])) {
1727

    
1728
		/* *cmd is an array, loop through */
1729
		foreach ($config['system'][$cmdn] as $cmd) {
1730
			exec($cmd);
1731
		}
1732

    
1733
	} elseif($config['system'][$cmdn] <> "") {
1734

    
1735
		/* execute single item */
1736
		exec($config['system'][$cmdn]);
1737

    
1738
	}
1739
}
1740

    
1741
function system_console_configure() {
1742
	global $config, $g;
1743
	if(isset($config['system']['developerspew'])) {
1744
		$mt = microtime();
1745
		echo "system_console_configure() being called $mt\n";
1746
	}
1747

    
1748
	if (isset($config['system']['disableconsolemenu'])) {
1749
		touch("{$g['varetc_path']}/disableconsole");
1750
	} else {
1751
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1752
	}
1753
}
1754

    
1755
function system_dmesg_save() {
1756
	global $g;
1757
	if(isset($config['system']['developerspew'])) {
1758
		$mt = microtime();
1759
		echo "system_dmesg_save() being called $mt\n";
1760
	}
1761

    
1762
	$dmesg = "";
1763
	$_gb = exec("/sbin/dmesg", $dmesg);
1764

    
1765
	/* find last copyright line (output from previous boots may be present) */
1766
	$lastcpline = 0;
1767

    
1768
	for ($i = 0; $i < count($dmesg); $i++) {
1769
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1770
			$lastcpline = $i;
1771
	}
1772

    
1773
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1774
	if (!$fd) {
1775
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1776
		return 1;
1777
	}
1778

    
1779
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1780
		fwrite($fd, $dmesg[$i] . "\n");
1781

    
1782
	fclose($fd);
1783
	unset($dmesg);
1784

    
1785
	return 0;
1786
}
1787

    
1788
function system_set_harddisk_standby() {
1789
	global $g, $config;
1790
	if(isset($config['system']['developerspew'])) {
1791
		$mt = microtime();
1792
		echo "system_set_harddisk_standby() being called $mt\n";
1793
	}
1794

    
1795
	if (isset($config['system']['harddiskstandby'])) {
1796
		if ($g['booting']) {
1797
			echo gettext('Setting hard disk standby... ');
1798
		}
1799

    
1800
		$standby = $config['system']['harddiskstandby'];
1801
		// Check for a numeric value
1802
		if (is_numeric($standby)) {
1803
			// Sync the disk(s)
1804
			pfSense_sync();
1805
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1806
				// Reinitialize ATA-drives
1807
				mwexec('/usr/local/sbin/atareinit');
1808
				if ($g['booting']) {
1809
					echo gettext("done.") . "\n";
1810
				}
1811
			} else if ($g['booting']) {
1812
				echo gettext("failed!") . "\n";
1813
			}
1814
		} else if ($g['booting']) {
1815
			echo gettext("failed!") . "\n";
1816
		}
1817
	}
1818
}
1819

    
1820
function system_setup_sysctl() {
1821
	global $config;
1822
	if(isset($config['system']['developerspew'])) {
1823
		$mt = microtime();
1824
		echo "system_setup_sysctl() being called $mt\n";
1825
	}
1826

    
1827
	activate_sysctls();	
1828

    
1829
	if (isset($config['system']['sharednet'])) {
1830
		system_disable_arp_wrong_if();
1831
	}
1832
}
1833

    
1834
function system_disable_arp_wrong_if() {
1835
	global $config;
1836
	if(isset($config['system']['developerspew'])) {
1837
		$mt = microtime();
1838
		echo "system_disable_arp_wrong_if() being called $mt\n";
1839
	}
1840
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1841
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1842
}
1843

    
1844
function system_enable_arp_wrong_if() {
1845
	global $config;
1846
	if(isset($config['system']['developerspew'])) {
1847
		$mt = microtime();
1848
		echo "system_enable_arp_wrong_if() being called $mt\n";
1849
	}
1850
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1851
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1852
}
1853

    
1854
function enable_watchdog() {
1855
	global $config;
1856
	return;
1857
	$install_watchdog = false;
1858
	$supported_watchdogs = array("Geode");
1859
	$file = file_get_contents("/var/log/dmesg.boot");
1860
	foreach($supported_watchdogs as $sd) {
1861
		if(stristr($file, "Geode")) {
1862
			$install_watchdog = true;
1863
		}
1864
	}
1865
	if($install_watchdog == true) {
1866
		if(is_process_running("watchdogd"))
1867
			mwexec("/usr/bin/killall watchdogd", true);
1868
		exec("/usr/sbin/watchdogd");
1869
	}
1870
}
1871

    
1872
function system_check_reset_button() {
1873
	global $g;
1874
	if($g['platform'] != "nanobsd")
1875
		return 0;
1876

    
1877
	$specplatform = system_identify_specific_platform();
1878

    
1879
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1880
		return 0;
1881

    
1882
	$retval = mwexec("/usr/local/sbin/" . $specplatform['name'] . "resetbtn");
1883

    
1884
	if ($retval == 99) {
1885
		/* user has pressed reset button for 2 seconds - 
1886
		   reset to factory defaults */
1887
		echo <<<EOD
1888

    
1889
***********************************************************************
1890
* Reset button pressed - resetting configuration to factory defaults. *
1891
* The system will reboot after this completes.                        *
1892
***********************************************************************
1893

    
1894

    
1895
EOD;
1896
		
1897
		reset_factory_defaults();
1898
		system_reboot_sync();
1899
		exit(0);
1900
	}
1901

    
1902
	return 0;
1903
}
1904

    
1905
/* attempt to identify the specific platform (for embedded systems)
1906
   Returns an array with two elements:
1907
	name => platform string (e.g. 'wrap', 'alix' etc.)
1908
	descr => human-readable description (e.g. "PC Engines WRAP")
1909
*/
1910
function system_identify_specific_platform() {
1911
	global $g;
1912
	
1913
	if ($g['platform'] == 'generic-pc')
1914
		return array('name' => 'generic-pc', 'descr' => gettext("Generic PC"));
1915
	
1916
	if ($g['platform'] == 'generic-pc-cdrom')
1917
		return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)"));
1918
	
1919
	/* the rest of the code only deals with 'embedded' platforms */
1920
	if ($g['platform'] != 'nanobsd')
1921
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1922

    
1923
	unset($output);
1924
	$_gb = exec('/sbin/sysctl -n hw.model', $output);
1925
	$dmesg = $output[0];
1926

    
1927
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1928
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
1929
	
1930
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1931
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
1932

    
1933
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1934
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1935
	
1936
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1937
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1938
		
1939
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1940
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1941
	
1942
	/* unknown embedded platform */
1943
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
1944
}
1945

    
1946
function system_get_dmesg_boot() {
1947
	global $g;
1948
		
1949
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1950
}
1951

    
1952
function get_possible_listen_ips($include_ipv6_link_local=false) {
1953
	$interfaces = get_configured_interface_with_descr();
1954
	$carplist = get_configured_carp_interface_list();
1955
	$listenips = array();
1956
	foreach ($carplist as $cif => $carpip)
1957
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1958
	$aliaslist = get_configured_ip_aliases_list();
1959
	foreach ($aliaslist as $aliasip => $aliasif)
1960
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1961
	foreach ($interfaces as $iface => $ifacename) {
1962
		$tmp["name"]  = $ifacename;
1963
		$tmp["value"] = $iface;
1964
		$listenips[] = $tmp;
1965
		if ($include_ipv6_link_local) {
1966
			$llip = find_interface_ipv6_ll(get_real_interface($iface));
1967
			if (!empty($llip)) {
1968
				$tmp["name"]  = "{$ifacename} IPv6 Link-Local";
1969
				$tmp["value"] = $llip;
1970
				$listenips[] = $tmp;
1971
			}
1972
		}
1973
	}
1974
	$tmp["name"]  = "Localhost";
1975
	$tmp["value"] = "lo0";
1976
	$listenips[] = $tmp;
1977
	return $listenips;
1978
}
1979

    
1980
function get_possible_traffic_source_addresses($include_ipv6_link_local=false) {
1981
	global $config;
1982
	$sourceips = get_possible_listen_ips($include_ipv6_link_local);
1983
	foreach (array('server', 'client') as $mode) {
1984
		if (is_array($config['openvpn']["openvpn-{$mode}"])) {
1985
			foreach ($config['openvpn']["openvpn-{$mode}"] as $id => $setting) {
1986
				if (!isset($setting['disable'])) {
1987
					$vpn = array();
1988
					$vpn['value'] = 'ovpn' . substr($mode, 0, 1) . $setting['vpnid'];
1989
					$vpn['name'] = gettext("OpenVPN") . " ".$mode.": ".htmlspecialchars($setting['description']);
1990
					$sourceips[] = $vpn;
1991
				}
1992
			}
1993
		}
1994
	}
1995
	return $sourceips;
1996
}
1997
?>
(52-52/67)