Project

General

Profile

Download (65.5 KB) Statistics
| Branch: | Tag: | Revision:
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/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
		$normal_mode = "hadp";
61
		if (!empty($config['system']['powerd_normal_mode']))
62
			$normal_mode = $config['system']['powerd_normal_mode'];
63

    
64
		mwexec("/usr/sbin/powerd -b $battery_mode -a $ac_mode -n $normal_mode");
65
	}
66
}
67

    
68
function get_default_sysctl_value($id) {
69
	global $sysctls;
70

    
71
	if (isset($sysctls[$id]))
72
		return $sysctls[$id];
73
}
74

    
75
function get_sysctl_descr($sysctl) {
76
	unset($output);
77
	$_gb = exec("/sbin/sysctl -nd {$sysctl}", $output);
78

    
79
	return $output[0];
80
}
81

    
82
function system_get_sysctls() {
83
	global $config, $sysctls;
84

    
85
	$disp_sysctl = array();
86
	$disp_cache = array();
87
	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
88
		foreach($config['sysctl']['item'] as $id => $tunable) {
89
			if ($tunable['value'] == "default")
90
				$value = get_default_sysctl_value($tunable['tunable']);
91
			else
92
				$value = $tunable['value'];
93

    
94
			$disp_sysctl[$id] = $tunable;
95
			$disp_sysctl[$id]['modified'] = true;
96
			$disp_cache[$tunable['tunable']] = 'set';
97
		}
98
	}
99

    
100
	foreach ($sysctls as $sysctl => $value) {
101
		if (isset($disp_cache[$sysctl]))
102
			continue;
103

    
104
		$disp_sysctl[$sysctl] = array('tunable' => $sysctl, 'value' => $value, 'descr' => get_sysctl_descr($sysctl));
105
	}
106
	unset($disp_cache);
107
	return $disp_sysctl;
108
}
109

    
110
function activate_sysctls() {
111
	global $config, $g, $sysctls;
112

    
113
	if ($g['platform'] == 'jail')
114
		return;
115

    
116
	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
117
		foreach($config['sysctl']['item'] as $tunable) {
118
			if($tunable['value'] == "default")
119
				$value = get_default_sysctl_value($tunable['tunable']);
120
			else
121
				$value = $tunable['value'];
122

    
123
			$sysctls[$tunable['tunable']] = $value;
124
		}
125
	}
126

    
127
	set_sysctl($sysctls);
128
}
129

    
130
function system_resolvconf_generate($dynupdate = false) {
131
	global $config, $g;
132

    
133
	if(isset($config['system']['developerspew'])) {
134
		$mt = microtime();
135
		echo "system_resolvconf_generate() being called $mt\n";
136
	}
137

    
138
	$syscfg = $config['system'];
139

    
140
	if (((isset($config['dnsmasq']['enable']) && (!isset($config['dnsmasq']['port']) || $config['dnsmasq']['port'] == "53") && (empty($config['dnsmasq']['interface']) || in_array("lo0", explode(",", $config['dnsmasq']['interface']))))
141
		|| (isset($config['unbound']['enable'])) && (!isset($config['unbound']['port']) || $config['unbound']['port'] == "53") && (empty($config['unbound']['active_interface']) || in_array("lo0", explode(",", $config['unbound']['active_interface'])) || in_array("all", explode(",", $config['unbound']['active_interface']), true)))
142
		&& !isset($config['system']['dnslocalhost']))
143
		$resolvconf .= "nameserver 127.0.0.1\n";
144

    
145
	if (isset($syscfg['dnsallowoverride'])) {
146
		/* get dynamically assigned DNS servers (if any) */
147
		$ns = array_unique(get_searchdomains());
148
		foreach($ns as $searchserver) {
149
			if($searchserver)
150
				$resolvconf .= "search {$searchserver}\n";
151
		}
152
		$ns = array_unique(get_nameservers());
153
		foreach($ns as $nameserver) {
154
			if($nameserver)
155
				$resolvconf .= "nameserver $nameserver\n";
156
		}
157
	} else {
158
		// Do not create blank search/domain lines, it can break tools like dig.
159
		if($syscfg['domain'])
160
			$resolvconf .= "search {$syscfg['domain']}\n";
161
	}
162
	if (is_array($syscfg['dnsserver'])) {
163
		foreach ($syscfg['dnsserver'] as $ns) {
164
			if ($ns)
165
				$resolvconf .= "nameserver $ns\n";
166
		}
167
	}
168

    
169
	// Add EDNS support
170
	if (isset($config['unbound']['enable']) && isset($config['unbound']['edns']))
171
		$resolvconf .= "options edns0\n";
172

    
173
	$dnslock = lock('resolvconf', LOCK_EX);
174

    
175
	$fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
176
	if (!$fd) {
177
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
178
		unlock($dnslock);
179
		return 1;
180
	}
181

    
182
	fwrite($fd, $resolvconf);
183
	fclose($fd);
184

    
185
	// Prevent resolvconf(8) from rewriting our resolv.conf
186
	$fd = fopen("{$g['varetc_path']}/resolvconf.conf", "w");
187
	if (!$fd) {
188
		printf("Error: cannot open resolvconf.conf in system_resolvconf_generate().\n");
189
		return 1;
190
	}
191
	fwrite($fd, "resolv_conf=\"/dev/null\"\n");
192
	fclose($fd);
193

    
194
	if (!platform_booting()) {
195
		/* restart dhcpd (nameservers may have changed) */
196
		if (!$dynupdate)
197
			services_dhcpd_configure();
198
	}
199

    
200
	/* setup static routes for DNS servers. */
201
	for ($dnscounter=1; $dnscounter<5; $dnscounter++) {
202
		/* setup static routes for dns servers */
203
		$dnsgw = "dns{$dnscounter}gw";
204
		if (isset($config['system'][$dnsgw])) {
205
			$gwname = $config['system'][$dnsgw];
206
			if (($gwname <> "") && ($gwname <> "none")) {
207
				$gatewayip = lookup_gateway_ip_by_name($gwname);
208
				if (is_ipaddrv4($gatewayip)) {
209
					/* dns server array starts at 0 */
210
					$dnscountermo = $dnscounter - 1;
211
					mwexec("/sbin/route change -host " . $syscfg['dnsserver'][$dnscountermo] . " {$gatewayip}");
212
					if (isset($config['system']['route-debug'])) {
213
						$mt = microtime();
214
						log_error("ROUTING debug: $mt - route change -host {$syscfg['dnsserver'][$dnscountermo]} $gatewayip ");
215
					}
216
				}
217
				if (is_ipaddrv6($gatewayip)) {
218
					/* dns server array starts at 0 */
219
					$dnscountermo = $dnscounter - 1;
220
					mwexec("/sbin/route change -host -inet6 " . $syscfg['dnsserver'][$dnscountermo] . " {$gatewayip}");
221
					if (isset($config['system']['route-debug'])) {
222
						$mt = microtime();
223
						log_error("ROUTING debug: $mt - route change -host -inet6 {$syscfg['dnsserver'][$dnscountermo]} $gatewayip ");
224
					}					
225
				}
226
			}
227
		}
228
	}
229

    
230
	unlock($dnslock);
231

    
232
	return 0;
233
}
234

    
235
function get_searchdomains() {
236
	global $config, $g;
237

    
238
	$master_list = array();
239
	
240
	// Read in dhclient nameservers
241
	$search_list = glob("/var/etc/searchdomain_*");
242
	if (is_array($search_list)) {
243
		foreach($search_list as $fdns) {
244
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
245
			if (!is_array($contents))
246
				continue;
247
			foreach ($contents as $dns) {
248
				if(is_hostname($dns)) 
249
					$master_list[] = $dns;
250
			}
251
		}
252
	}
253

    
254
	return $master_list;
255
}
256

    
257
function get_nameservers() {
258
	global $config, $g;
259
	$master_list = array();
260
	
261
	// Read in dhclient nameservers
262
	$dns_lists = glob("/var/etc/nameserver_*");
263
	if (is_array($dns_lists)) {
264
		foreach($dns_lists as $fdns) {
265
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
266
			if (!is_array($contents))
267
				continue;
268
			foreach ($contents as $dns) {
269
				if(is_ipaddr($dns)) 
270
					$master_list[] = $dns;
271
			}
272
		}
273
	}
274

    
275
	// Read in any extra nameservers
276
	if(file_exists("/var/etc/nameservers.conf")) {
277
		$dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
278
		if(is_array($dns_s)) {
279
			foreach($dns_s as $dns)
280
				if (is_ipaddr($dns))
281
					$master_list[] = $dns;
282
		}
283
	}
284

    
285
	return $master_list;
286
}
287

    
288
function system_hosts_generate() {
289
	global $config, $g;
290
	if (isset($config['system']['developerspew'])) {
291
		$mt = microtime();
292
		echo "system_hosts_generate() being called $mt\n";
293
	}
294

    
295
	$syscfg = $config['system'];
296
	if (isset($config['unbound']) && isset($config['unbound']['enable']))
297
		$dnsmasqcfg = $config['unbound'];
298
	else
299
		$dnsmasqcfg = $config['dnsmasq'];
300

    
301
	$hosts =  "127.0.0.1	localhost localhost.{$syscfg['domain']}\n";
302
	$hosts .= "::1		localhost localhost.{$syscfg['domain']}\n";
303
	$lhosts = "";
304
	$dhosts = "";
305

    
306
	if ($config['interfaces']['lan']) {
307
		$cfgip = get_interface_ip("lan");
308
		if (is_ipaddr($cfgip))
309
			$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
310
		$cfgipv6 = get_interface_ipv6("lan");
311
		if (is_ipaddrv6($cfgipv6))
312
			$hosts .= "{$cfgipv6}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
313
	} else {
314
		$sysiflist = get_configured_interface_list();
315
		$hosts_if_found = false;
316
		foreach ($sysiflist as $sysif) {
317
			if (!interface_has_gateway($sysif)) {
318
				$cfgip = get_interface_ip($sysif);
319
				if (is_ipaddr($cfgip)) {
320
					$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
321
					$hosts_if_found = true;
322
				}
323
				$cfgipv6 = get_interface_ipv6($sysif);
324
				if (is_ipaddrv6($cfgipv6)) {
325
					$hosts .= "{$cfgipv6}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
326
					$hosts_if_found = true;
327
				}
328
				if ($hosts_if_found == true)
329
					break;
330
			}
331
		}
332
	}
333

    
334
	if (isset($dnsmasqcfg['enable'])) {
335
		if (!is_array($dnsmasqcfg['hosts']))
336
			$dnsmasqcfg['hosts'] = array();
337

    
338
		foreach ($dnsmasqcfg['hosts'] as $host) {
339
			if ($host['host'])
340
				$lhosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
341
			else
342
				$lhosts .= "{$host['ip']}	{$host['domain']}\n";
343
			if (!is_array($host['aliases']) || !is_array($host['aliases']['item']))
344
				continue;
345
			foreach ($host['aliases']['item'] as $alias) {
346
				if ($alias['host'])
347
					$lhosts .= "{$host['ip']}	{$alias['host']}.{$alias['domain']} {$alias['host']}\n";
348
				else
349
					$lhosts .= "{$host['ip']}	{$alias['domain']}\n";
350
			}
351
		}
352
		if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpd'])) {
353
			foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf)
354
				if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
355
						foreach ($dhcpifconf['staticmap'] as $host)
356
							if ($host['ipaddr'] && $host['hostname'] && $host['domain'])
357
								$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$host['domain']} {$host['hostname']}\n";
358
							else if ($host['ipaddr'] && $host['hostname'] && $dhcpifconf['domain'])
359
								$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$dhcpifconf['domain']} {$host['hostname']}\n";
360
							else if ($host['ipaddr'] && $host['hostname'])
361
								$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
362
		}
363
		if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpdv6'])) {
364
			foreach ($config['dhcpdv6'] as $dhcpif => $dhcpifconf)
365
				if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
366
						foreach ($dhcpifconf['staticmap'] as $host)
367
							if ($host['ipaddrv6'] && $host['hostname'] && $host['domain'])
368
								$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$host['domain']} {$host['hostname']}\n";
369
							else if ($host['ipaddrv6'] && $host['hostname'] && $dhcpifconf['domain'])
370
								$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$dhcpifconf['domain']} {$host['hostname']}\n";
371
							else if ($host['ipaddrv6'] && $host['hostname'])
372
								$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
373
		}
374

    
375
		if (isset($dnsmasqcfg['dhcpfirst']))
376
			$hosts .= $dhosts . $lhosts;
377
		else
378
			$hosts .= $lhosts . $dhosts;
379
	}
380

    
381
	/*
382
	 * Do not remove this because dhcpleases monitors with kqueue it needs to be 
383
	 * killed before writing to hosts files.
384
	 */
385
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
386
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
387
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
388
	}
389
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
390
	if (!$fd) {
391
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
392
		return 1;
393
	}
394
	fwrite($fd, $hosts);
395
	fclose($fd);
396

    
397
	if (isset($config['unbound']['enable'])) {
398
		require_once("unbound.inc");
399
		unbound_hosts_generate();
400
	}
401

    
402
	return 0;
403
}
404

    
405
function system_dhcpleases_configure() {
406
	global $config, $g;
407
	
408
	if ($g['platform'] == 'jail')
409
		return;
410
	/* Start the monitoring process for dynamic dhcpclients. */
411
	if ((isset($config['dnsmasq']['enable']) && isset($config['dnsmasq']['regdhcp'])) 
412
		|| (isset($config['unbound']['enable']) && isset($config['unbound']['regdhcp']))) {
413
		/* Make sure we do not error out */
414
		mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db");
415
		if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases"))
416
			@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
417

    
418
		if (isset($config['unbound']['enable'])) {
419
			$dns_pid = "unbound.pid";
420
			$unbound_conf = "-u {$g['unbound_chroot_path']}/dhcpleases_entries.conf";
421
		} else {
422
			$dns_pid = "dnsmasq.pid";
423
			$unbound_conf = "";
424
		}
425

    
426
		$pidfile = "{$g['varrun_path']}/dhcpleases.pid";
427
		if (isvalidpid($pidfile)) {
428
			/* Make sure dhcpleases is using correct unbound or dnsmasq */
429
			$_gb = exec("/bin/pgrep -F {$pidfile} -f {$dns_pid}", $output, $retval);
430
			if (intval($retval) == 0) {
431
				sigkillbypid($pidfile, "HUP");
432
				return;
433
			} else
434
				sigkillbypid($pidfile, "TERM");
435
		}
436

    
437
		/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
438
		if (is_process_running("dhcpleases"))
439
			sigkillbyname('dhcpleases', "TERM");
440
		@unlink($pidfile);
441
		mwexec("/usr/local/sbin/dhcpleases -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases -d {$config['system']['domain']} -p {$g['varrun_path']}/{$dns_pid} {$unbound_conf} -h {$g['varetc_path']}/hosts");
442
	} else {
443
		sigkillbypid($pidfile, "TERM");
444
		@unlink($pidfile);
445
	}
446
}
447

    
448
function system_hostname_configure() {
449
	global $config, $g;
450
	if(isset($config['system']['developerspew'])) {
451
		$mt = microtime();
452
		echo "system_hostname_configure() being called $mt\n";
453
	}
454

    
455
	$syscfg = $config['system'];
456

    
457
	/* set hostname */
458
	$status = mwexec("/bin/hostname " .
459
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
460

    
461
    /* Setup host GUID ID.  This is used by ZFS. */
462
	mwexec("/etc/rc.d/hostid start");
463

    
464
	return $status;
465
}
466

    
467
function system_routing_configure($interface = "") {
468
	global $config, $g;
469
	if ($g['platform'] == 'jail')
470
		return;
471
	if(isset($config['system']['developerspew'])) {
472
		$mt = microtime();
473
		echo "system_routing_configure() being called $mt\n";
474
	}
475

    
476
	$gatewayip = "";
477
	$interfacegw = "";
478
	$gatewayipv6 = "";
479
	$interfacegwv6 = "";
480
	$foundgw = false;
481
	$foundgwv6 = false;
482
	/* tack on all the hard defined gateways as well */
483
	if (is_array($config['gateways']['gateway_item'])) {
484
		array_map('unlink', glob("{$g['tmp_path']}/*_defaultgw{,v6}", GLOB_BRACE));
485
		foreach	($config['gateways']['gateway_item'] as $gateway) {
486
			if (isset($gateway['defaultgw'])) {
487
				if ($foundgw == false && ($gateway['ipprotocol'] != "inet6" && (is_ipaddrv4($gateway['gateway']) || $gateway['gateway'] == "dynamic"))) {
488
					if(strpos($gateway['gateway'], ":"))
489
						continue;
490
					if ($gateway['gateway'] == "dynamic")
491
						$gateway['gateway'] = get_interface_gateway($gateway['interface']);
492
					$gatewayip = $gateway['gateway'];
493
					$interfacegw = $gateway['interface'];
494
					if (!empty($gateway['interface'])) {
495
						$defaultif = get_real_interface($gateway['interface']);
496
						if ($defaultif)
497
							@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gateway['gateway']);
498
					}
499
					$foundgw = true;
500
				} else if ($foundgwv6 == false && ($gateway['ipprotocol'] == "inet6" && (is_ipaddrv6($gateway['gateway']) || $gateway['gateway'] == "dynamic"))) {
501
					if ($gateway['gateway'] == "dynamic")
502
						$gateway['gateway'] = get_interface_gateway_v6($gateway['interface']);
503
					$gatewayipv6 = $gateway['gateway'];
504
					$interfacegwv6 = $gateway['interface'];
505
					if (!empty($gateway['interface'])) {
506
						$defaultifv6 = get_real_interface($gateway['interface']);
507
						if ($defaultifv6)
508
							@file_put_contents("{$g['tmp_path']}/{$defaultifv6}_defaultgwv6", $gateway['gateway']);
509
					}
510
					$foundgwv6 = true;
511
				}
512
			}
513
			if ($foundgw === true && $foundgwv6 === true)
514
				break;
515
		}
516
	}
517
	if ($foundgw == false) {
518
		$defaultif = get_real_interface("wan");
519
		$interfacegw = "wan";
520
		$gatewayip = get_interface_gateway("wan");
521
		@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gatewayip);
522
	}	
523
	if ($foundgwv6 == false) {
524
		$defaultifv6 = get_real_interface("wan");
525
		$interfacegwv6 = "wan";
526
		$gatewayipv6 = get_interface_gateway_v6("wan");
527
		@file_put_contents("{$g['tmp_path']}/{$defaultifv6}_defaultgwv6", $gatewayipv6);
528
	}
529
	$dont_add_route = false;
530
	/* if OLSRD is enabled, allow WAN to house DHCP. */
531
	if (is_array($config['installedpackages']['olsrd'])) {
532
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
533
			if(($olsrd['enabledyngw'] == "on") && ($olsrd['enable'] == "on")) {
534
				$dont_add_route = true;
535
				log_error(sprintf(gettext("Not adding default route because OLSR dynamic gateway is enabled.")));
536
				break;
537
			}
538
		}
539
	}
540

    
541
	if ($dont_add_route == false ) {
542
		if (!empty($interface) && $interface != $interfacegw)
543
			;
544
		else if (is_ipaddrv4($gatewayip)) {
545
			log_error("ROUTING: setting default route to $gatewayip");
546
			mwexec("/sbin/route change -inet default " . escapeshellarg($gatewayip));
547
		}
548

    
549
		if (!empty($interface) && $interface != $interfacegwv6)
550
			;
551
		else if (is_ipaddrv6($gatewayipv6)) {
552
			$ifscope = "";
553
			if (is_linklocal($gatewayipv6) && !strpos($gatewayipv6, '%'))
554
				$ifscope = "%{$defaultifv6}";
555
			log_error("ROUTING: setting IPv6 default route to {$gatewayipv6}{$ifscope}");
556
			mwexec("/sbin/route change -inet6 default " . escapeshellarg("{$gatewayipv6}{$ifscope}"));
557
		}
558
	}
559

    
560
	system_staticroutes_configure($interface, false);
561

    
562
	return 0;
563
}
564

    
565
function system_staticroutes_configure($interface = "", $update_dns = false) {
566
	global $config, $g, $aliastable;
567

    
568
	$filterdns_list = array();
569

    
570
	$static_routes = get_staticroutes(false, true);
571
	if (count($static_routes)) {
572
		$gateways_arr = return_gateways_array(false, true);
573

    
574
		foreach ($static_routes as $rtent) {
575
			if (empty($gateways_arr[$rtent['gateway']])) {
576
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
577
				continue;
578
			}
579
			$gateway = $gateways_arr[$rtent['gateway']];
580
			if (!empty($interface) && $interface != $gateway['friendlyiface'])
581
				continue;
582

    
583
			$gatewayip = $gateway['gateway'];
584
			$interfacegw = $gateway['interface'];
585

    
586
			$blackhole = "";
587
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 3)))
588
				$blackhole = "-blackhole";
589

    
590
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network']))
591
				continue;
592

    
593
			$dnscache = array();
594
			if ($update_dns === true) {
595
				if (is_subnet($rtent['network']))
596
					continue;
597
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
598
				if (empty($dnscache))
599
					continue;
600
			}
601

    
602
			if (is_subnet($rtent['network']))
603
				$ips = array($rtent['network']);
604
			else {
605
				if (!isset($rtent['disabled']))
606
					$filterdns_list[] = $rtent['network'];
607
				$ips = add_hostname_to_watch($rtent['network']);
608
			}
609

    
610
			foreach ($dnscache as $ip) {
611
				if (in_array($ip, $ips))
612
					continue;
613
				mwexec("/sbin/route delete " . escapeshellarg($ip), true);
614
				if (isset($config['system']['route-debug'])) {
615
					$mt = microtime();
616
					log_error("ROUTING debug: $mt - route delete $ip ");
617
				}
618
			}
619

    
620
			if (isset($rtent['disabled'])) {
621
				/* XXX: This can break things by deleting routes that shouldn't be deleted - OpenVPN, dynamic routing scenarios, etc. redmine #3709 */
622
				foreach ($ips as $ip) {
623
					mwexec("/sbin/route delete " . escapeshellarg($ip), true);
624
					if (isset($config['system']['route-debug'])) {
625
						$mt = microtime();
626
						log_error("ROUTING debug: $mt - route delete $ip ");
627
					}
628
				}
629
				continue;
630
			}
631

    
632
			foreach ($ips as $ip) {
633
				if (is_ipaddrv4($ip))
634
					$ip .= "/32";
635
				// do NOT do the same check here on v6, is_ipaddrv6 returns true when including the CIDR mask. doing so breaks v6 routes
636
					
637
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
638

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

    
641
				if (is_subnet($ip))
642
					if (is_ipaddr($gatewayip)) {
643
						mwexec($cmd . escapeshellarg($gatewayip));
644
						if (isset($config['system']['route-debug'])) {
645
							$mt = microtime();
646
							log_error("ROUTING debug: $mt - $cmd $gatewayip");
647
						}
648
					} else if (!empty($interfacegw)) {
649
						mwexec($cmd . "-iface " . escapeshellarg($interfacegw));
650
						if (isset($config['system']['route-debug'])) {
651
							$mt = microtime();
652
							log_error("ROUTING debug: $mt - $cmd -iface $interfacegw ");
653
						}
654
					}
655
			}
656
		}
657
		unset($gateways_arr);
658
	}
659
	unset($static_routes);
660

    
661
	if ($update_dns === false) {
662
		if (count($filterdns_list)) {
663
			$interval = 60;
664
			$hostnames = "";
665
			array_unique($filterdns_list);
666
			foreach ($filterdns_list as $hostname)
667
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
668
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
669
			unset($hostnames);
670

    
671
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid"))
672
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
673
			else
674
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
675
		} else {
676
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
677
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
678
		}
679
	}
680
	unset($filterdns_list);
681

    
682
	return 0;
683
}
684

    
685
function system_routing_enable() {
686
	global $config, $g;
687
	if(isset($config['system']['developerspew'])) {
688
		$mt = microtime();
689
		echo "system_routing_enable() being called $mt\n";
690
	}
691

    
692
	set_sysctl(array(
693
		"net.inet.ip.forwarding" => "1",
694
		"net.inet6.ip6.forwarding" => "1"
695
	));
696

    
697
	return;
698
}
699

    
700
function system_syslogd_fixup_server($server) {
701
	/* If it's an IPv6 IP alone, encase it in brackets */
702
	if (is_ipaddrv6($server))
703
		return "[$server]";
704
	else
705
		return $server;
706
}
707

    
708
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
709
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
710
	$facility .= " ".
711
	$remote_servers = "";
712
	$pad_to  = 56;
713
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
714
	if($syslogcfg['remoteserver'])
715
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
716
	if($syslogcfg['remoteserver2'])
717
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
718
	if($syslogcfg['remoteserver3'])
719
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
720
	return $remote_servers;
721
}
722

    
723
function system_syslogd_start() {
724
	global $config, $g;
725
	if(isset($config['system']['developerspew'])) {
726
		$mt = microtime();
727
		echo "system_syslogd_start() being called $mt\n";
728
	}
729

    
730
	mwexec("/etc/rc.d/hostid start");
731

    
732
	$syslogcfg = $config['syslog'];
733

    
734
	if (platform_booting())
735
		echo gettext("Starting syslog...");
736

    
737
	if (is_process_running("fifolog_writer"))
738
		mwexec('/bin/pkill fifolog_writer');
739

    
740
	// Which logging type are we using this week??
741
	if (isset($config['system']['disablesyslogclog'])) {
742
		$log_directive = "";
743
		$log_create_directive = "/usr/bin/touch ";
744
		$log_size = "";
745
	} else if (isset($config['system']['usefifolog'])) {
746
		$log_directive = "|/usr/sbin/fifolog_writer ";
747
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
748
		$log_create_directive = "/usr/sbin/fifolog_create -s ";
749
	} else { // Defaults to CLOG
750
		$log_directive = "%";
751
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
752
		$log_create_directive = "/usr/local/sbin/clog -i -s ";
753
	}
754

    
755
	$syslogd_extra = "";
756
	if (isset($syslogcfg)) {
757
		$separatelogfacilities = array('ntp','ntpd','ntpdate','charon','ipsec_starter','openvpn','pptps','poes','l2tps','relayd','hostapd','dnsmasq','filterdns','unbound','dhcpd','dhcrelay','dhclient','dhcp6c','apinger','radvd','routed','olsrd','zebra','ospfd','bgpd','miniupnpd','filterlog');
758
		$syslogconf = "";
759
		if($config['installedpackages']['package']) {
760
			foreach($config['installedpackages']['package'] as $package) {
761
				if($package['logging']) {
762
					array_push($separatelogfacilities, $package['logging']['facilityname']);
763
					mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
764
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
765
				}
766
			}
767
		}
768
		$facilitylist = implode(',', array_unique($separatelogfacilities));
769
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd,miniupnpd\n";
770
		if (!isset($syslogcfg['disablelocallogging']))
771
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
772

    
773
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
774
		if (!isset($syslogcfg['disablelocallogging'])) 
775
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
776

    
777
		$syslogconf .= "!ppp\n";
778
		if (!isset($syslogcfg['disablelocallogging'])) 
779
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
780

    
781
		$syslogconf .= "!pptps\n";
782
		if (!isset($syslogcfg['disablelocallogging'])) 
783
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/pptps.log\n";
784

    
785
		$syslogconf .= "!poes\n";
786
		if (!isset($syslogcfg['disablelocallogging'])) 
787
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
788

    
789
		$syslogconf .= "!l2tps\n";
790
		if (!isset($syslogcfg['disablelocallogging'])) 
791
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/l2tps.log\n";
792

    
793
		$syslogconf .= "!charon,ipsec_starter\n";
794
		if (!isset($syslogcfg['disablelocallogging'])) 
795
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ipsec.log\n";
796
		if (isset($syslogcfg['vpn']))
797
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
798

    
799
		$syslogconf .= "!openvpn\n";
800
		if (!isset($syslogcfg['disablelocallogging'])) 
801
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/openvpn.log\n";
802
		if (isset($syslogcfg['vpn']))
803
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
804

    
805
		$syslogconf .= "!apinger\n";
806
		if (!isset($syslogcfg['disablelocallogging']))
807
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/gateways.log\n";
808
		if (isset($syslogcfg['apinger']))
809
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
810

    
811
		$syslogconf .= "!dnsmasq,filterdns,unbound\n";
812
		if (!isset($syslogcfg['disablelocallogging']))
813
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
814

    
815
		$syslogconf .= "!dhcpd,dhcrelay,dhclient,dhcp6c\n";
816
		if (!isset($syslogcfg['disablelocallogging']))
817
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/dhcpd.log\n";
818
		if (isset($syslogcfg['dhcp']))
819
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
820

    
821
		$syslogconf .= "!relayd\n";
822
		if (!isset($syslogcfg['disablelocallogging']))
823
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/relayd.log\n";
824
		if (isset($syslogcfg['relayd']))
825
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
826

    
827
		$syslogconf .= "!hostapd\n";
828
		if (!isset($syslogcfg['disablelocallogging']))
829
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
830
		if (isset($syslogcfg['hostapd']))
831
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
832

    
833
		$syslogconf .= "!filterlog\n";
834
		$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/filter.log\n";
835
		if (isset($syslogcfg['filter']))
836
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
837

    
838
		$syslogconf .= "!-{$facilitylist}\n";
839
		if (!isset($syslogcfg['disablelocallogging'])) 
840
			$syslogconf .= <<<EOD
841
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
842
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
843
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
844
*.notice;kern.debug;lpr.info;mail.crit;daemon.none;		{$log_directive}{$g['varlog_path']}/system.log
845
news.err;local0.none;local3.none;local4.none;			{$log_directive}{$g['varlog_path']}/system.log
846
local7.none							{$log_directive}{$g['varlog_path']}/system.log
847
security.*							{$log_directive}{$g['varlog_path']}/system.log
848
auth.info;authpriv.info;daemon.info				{$log_directive}{$g['varlog_path']}/system.log
849
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
850
*.emerg								*
851

    
852
EOD;
853
		if (isset($syslogcfg['vpn']))
854
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
855
		if (isset($syslogcfg['portalauth']))
856
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
857
		if (isset($syslogcfg['dhcp']))
858
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
859
		if (isset($syslogcfg['system'])) {
860
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.notice;kern.debug;lpr.info;mail.crit;");
861
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "news.err;local0.none;local3.none;local7.none");
862
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "security.*");
863
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "auth.info;authpriv.info;daemon.info");
864
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.emerg");
865
		}
866
		if (isset($syslogcfg['logall'])) {
867
			// Make everything mean everything, including facilities excluded above.
868
			$syslogconf .= "!*\n";
869
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
870
		}
871

    
872
		if (isset($syslogcfg['zmqserver'])) {
873
				$syslogconf .= <<<EOD
874
*.*								^{$syslogcfg['zmqserver']}
875

    
876
EOD;
877
		}
878
		/* write syslog.conf */		
879
		if (!@file_put_contents("{$g['varetc_path']}/syslog.conf", $syslogconf)) {
880
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
881
			unset($syslogconf);
882
			return 1;
883
		}
884
		unset($syslogconf);
885

    
886
		// Ensure that the log directory exists
887
		if (!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
888
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
889

    
890
		$sourceip = "";
891
		if (!empty($syslogcfg['sourceip'])) {
892
			if ($syslogcfg['ipproto'] == "ipv6") {
893
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
894
				if (!is_ipaddr($ifaddr))
895
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
896
			} else {
897
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
898
				if (!is_ipaddr($ifaddr))
899
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
900
			}
901
			if (is_ipaddr($ifaddr)) {
902
				$sourceip = "-b {$ifaddr}";
903
			}
904
		}
905

    
906
		$syslogd_extra = "-f {$g['varetc_path']}/syslog.conf {$sourceip}";
907
	}
908

    
909
	if (isvalidpid("{$g['varrun_path']}/syslog.pid"))
910
		sigkillbypid("{$g['varrun_path']}/syslog.pid", "TERM");
911
	
912
	$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}");
913

    
914
	if (platform_booting())
915
		echo gettext("done.") . "\n";
916

    
917
	return $retval;
918
}
919

    
920
function system_webgui_create_certificate() {
921
	global $config, $g;
922

    
923
	if (!is_array($config['ca']))
924
		$config['ca'] = array();
925
	$a_ca =& $config['ca'];
926
	if (!is_array($config['cert']))
927
		$config['cert'] = array();
928
	$a_cert =& $config['cert'];
929
	log_error("Creating SSL Certificate for this host");
930

    
931
	$cert = array();
932
	$cert['refid'] = uniqid();
933
	$cert['descr'] = gettext("webConfigurator default ({$cert['refid']})");
934

    
935
	$dn = array(
936
		'countryName' => "US",
937
		'stateOrProvinceName' => "State",
938
		'localityName' => "Locality",
939
		'organizationName' => "{$g['product_name']} webConfigurator Self-Signed Certificate",
940
		'emailAddress' => "admin@{$config['system']['hostname']}.{$config['system']['domain']}",
941
		'commonName' => "{$config['system']['hostname']}-{$cert['refid']}");
942
	$old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warings directly to a page screwing menu tab */
943
	if (!cert_create($cert, null, 2048, 2000, $dn, "self-signed", "sha256")){
944
		while($ssl_err = openssl_error_string()){
945
			log_error("Error creating WebGUI Certificate: openssl library returns: " . $ssl_err);
946
		}
947
		error_reporting($old_err_level);
948
		return null;
949
	}
950
	error_reporting($old_err_level);
951

    
952
	$a_cert[] = $cert;
953
	$config['system']['webgui']['ssl-certref'] = $cert['refid'];
954
	write_config(gettext("Generated new self-signed HTTPS certificate ({$cert['refid']})"));
955
	return $cert;
956
}
957

    
958
function system_webgui_start() {
959
	global $config, $g;
960

    
961
	if (platform_booting())
962
		echo gettext("Starting webConfigurator...");
963

    
964
	chdir($g['www_path']);
965

    
966
	/* defaults */
967
	$portarg = "80";
968
	$crt = "";
969
	$key = "";
970
	$ca = "";
971

    
972
	/* non-standard port? */
973
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
974
		$portarg = "{$config['system']['webgui']['port']}";
975

    
976
	if ($config['system']['webgui']['protocol'] == "https") {
977
		// Ensure that we have a webConfigurator CERT
978
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
979
		if(!is_array($cert) || !$cert['crt'] || !$cert['prv'])
980
			$cert = system_webgui_create_certificate();
981
		$crt = base64_decode($cert['crt']);
982
		$key = base64_decode($cert['prv']);
983

    
984
		if(!$config['system']['webgui']['port'])
985
			$portarg = "443";
986
		$ca  = ca_chain($cert);
987
	}
988

    
989
	/* generate lighttpd configuration */
990
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
991
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
992
		"cert.pem", "ca.pem");
993

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

    
997
	sleep(1);
998

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

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

    
1004
	if (platform_booting()) {
1005
		if ($res == 0)
1006
			echo gettext("done.") . "\n";
1007
		else
1008
			echo gettext("failed!") . "\n";
1009
	}
1010

    
1011
	return $res;
1012
}
1013

    
1014
function system_generate_lighty_config($filename,
1015
	$cert,
1016
	$key,
1017
	$ca,
1018
	$pid_file,
1019
	$port = 80,
1020
	$document_root = "/usr/local/www/",
1021
	$cert_location = "cert.pem",
1022
	$ca_location = "ca.pem",
1023
	$captive_portal = false) {
1024

    
1025
	global $config, $g;
1026

    
1027
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
1028
		mkdir("{$g['tmp_path']}/lighttpdcompress");
1029

    
1030
	if(isset($config['system']['developerspew'])) {
1031
		$mt = microtime();
1032
		echo "system_generate_lighty_config() being called $mt\n";
1033
	}
1034

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

    
1039
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1040
		if (empty($maxprocperip))
1041
			$maxprocperip = 10;
1042
		$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
1043

    
1044
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
1045
		if(!is_dir("{$g['tmp_path']}/captiveportal"))
1046
			@mkdir("{$g['tmp_path']}/captiveportal", 0555);
1047
		$server_max_request_size = "server.max-request-size    = 384";
1048
		$cgi_config = "";
1049
	} else {
1050
		$captiveportal = ",\"mod_cgi\"";
1051
		$captive_portal_rewrite = "";
1052
		$captive_portal_mod_evasive = "";
1053
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
1054
		$server_max_request_size = "server.max-request-size    = 2097152";
1055
		$cgi_config = "cgi.assign                 = ( \".cgi\" => \"\" )";
1056
	}
1057
	
1058
	if (empty($port))
1059
		$lighty_port = "80";
1060
	else
1061
		$lighty_port = $port;
1062

    
1063
	$memory = get_memory();
1064
	$realmem = $memory[1];
1065

    
1066
	// Determine web GUI process settings and take into account low memory systems
1067
	if ($realmem < 255)
1068
		$max_procs = 1;
1069
	else
1070
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
1071

    
1072
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM 
1073
	if ($captive_portal !== false)  {
1074
		if ($realmem > 135 and $realmem < 256) {
1075
			$max_procs += 1; // 2 worker processes
1076
		} else if ($realmem > 255 and $realmem < 513) {
1077
			$max_procs += 2; // 3 worker processes
1078
		} else if ($realmem > 512) {
1079
			$max_procs += 4; // 6 worker processes
1080
		}
1081
		if ($max_procs > 1)
1082
			$max_php_children = intval($max_procs/2);
1083
		else
1084
			$max_php_children = 1;
1085

    
1086
	} else {
1087
		if ($realmem < 78)
1088
			$max_php_children = 0;
1089
		else
1090
			$max_php_children = 1;
1091
	}
1092

    
1093
	if(!isset($config['syslog']['nologlighttpd'])) {
1094
		$lighty_use_syslog = <<<EOD
1095
## where to send error-messages to
1096
server.errorlog-use-syslog="enable"
1097
EOD;
1098
	}
1099

    
1100

    
1101
	if ($captive_portal !== false) {
1102
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi-{$captive_portal}.socket";
1103
		$fastcgi_config = <<<EOD
1104
#### fastcgi module
1105
## read fastcgi.txt for more info
1106
fastcgi.server = ( ".php" =>
1107
	( "localhost" =>
1108
		(
1109
			"socket" => "{$fast_cgi_path}",
1110
			"max-procs" => {$max_procs},
1111
			"bin-environment" => (
1112
				"PHP_FCGI_CHILDREN" => "{$max_php_children}",
1113
				"PHP_FCGI_MAX_REQUESTS" => "500"
1114
			),
1115
			"bin-path" => "/usr/local/bin/php"
1116
		)
1117
	)
1118
)
1119

    
1120
EOD;
1121
	} else {
1122
		$fast_cgi_path = "{$g['varrun_path']}/php-fpm.socket";
1123
		$fastcgi_config = <<<EOD
1124
#### fastcgi module
1125
## read fastcgi.txt for more info
1126
fastcgi.server = ( ".php" =>
1127
	( "localhost" =>
1128
		(
1129
			"socket" => "{$fast_cgi_path}",
1130
			"broken-scriptfilename" => "enable"
1131
		)
1132
	)
1133
)
1134

    
1135
EOD;
1136
	}
1137

    
1138

    
1139
	$lighty_config = <<<EOD
1140
#
1141
# lighttpd configuration file
1142
#
1143
# use a it as base for lighttpd 1.0.0 and above
1144
#
1145
############ Options you really have to take care of ####################
1146

    
1147
## FreeBSD!
1148
server.event-handler	= "freebsd-kqueue"
1149
server.network-backend 	= "writev"
1150
#server.use-ipv6 = "enable"
1151

    
1152
## modules to load
1153
server.modules              =   ( "mod_access", "mod_expire", "mod_compress", "mod_redirect",
1154
	{$captiveportal}, "mod_fastcgi"
1155
)
1156

    
1157
server.max-keep-alive-requests = 15
1158
server.max-keep-alive-idle = 30
1159

    
1160
## a static document-root, for virtual-hosting take look at the
1161
## server.virtual-* options
1162
server.document-root        = "{$document_root}"
1163
{$captive_portal_rewrite}
1164

    
1165
# Maximum idle time with nothing being written (php downloading)
1166
server.max-write-idle = 999
1167

    
1168
{$lighty_use_syslog}
1169

    
1170
# files to check for if .../ is requested
1171
server.indexfiles           = ( "index.php", "index.html",
1172
                                "index.htm", "default.htm" )
1173

    
1174
# mimetype mapping
1175
mimetype.assign             = (
1176
  ".pdf"          =>      "application/pdf",
1177
  ".sig"          =>      "application/pgp-signature",
1178
  ".spl"          =>      "application/futuresplash",
1179
  ".class"        =>      "application/octet-stream",
1180
  ".ps"           =>      "application/postscript",
1181
  ".torrent"      =>      "application/x-bittorrent",
1182
  ".dvi"          =>      "application/x-dvi",
1183
  ".gz"           =>      "application/x-gzip",
1184
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
1185
  ".swf"          =>      "application/x-shockwave-flash",
1186
  ".tar.gz"       =>      "application/x-tgz",
1187
  ".tgz"          =>      "application/x-tgz",
1188
  ".tar"          =>      "application/x-tar",
1189
  ".zip"          =>      "application/zip",
1190
  ".mp3"          =>      "audio/mpeg",
1191
  ".m3u"          =>      "audio/x-mpegurl",
1192
  ".wma"          =>      "audio/x-ms-wma",
1193
  ".wax"          =>      "audio/x-ms-wax",
1194
  ".ogg"          =>      "audio/x-wav",
1195
  ".wav"          =>      "audio/x-wav",
1196
  ".gif"          =>      "image/gif",
1197
  ".jpg"          =>      "image/jpeg",
1198
  ".jpeg"         =>      "image/jpeg",
1199
  ".png"          =>      "image/png",
1200
  ".xbm"          =>      "image/x-xbitmap",
1201
  ".xpm"          =>      "image/x-xpixmap",
1202
  ".xwd"          =>      "image/x-xwindowdump",
1203
  ".css"          =>      "text/css",
1204
  ".html"         =>      "text/html",
1205
  ".htm"          =>      "text/html",
1206
  ".js"           =>      "text/javascript",
1207
  ".asc"          =>      "text/plain",
1208
  ".c"            =>      "text/plain",
1209
  ".conf"         =>      "text/plain",
1210
  ".text"         =>      "text/plain",
1211
  ".txt"          =>      "text/plain",
1212
  ".dtd"          =>      "text/xml",
1213
  ".xml"          =>      "text/xml",
1214
  ".mpeg"         =>      "video/mpeg",
1215
  ".mpg"          =>      "video/mpeg",
1216
  ".mov"          =>      "video/quicktime",
1217
  ".qt"           =>      "video/quicktime",
1218
  ".avi"          =>      "video/x-msvideo",
1219
  ".asf"          =>      "video/x-ms-asf",
1220
  ".asx"          =>      "video/x-ms-asf",
1221
  ".wmv"          =>      "video/x-ms-wmv",
1222
  ".bz2"          =>      "application/x-bzip",
1223
  ".tbz"          =>      "application/x-bzip-compressed-tar",
1224
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
1225
 )
1226

    
1227
# Use the "Content-Type" extended attribute to obtain mime type if possible
1228
#mimetypes.use-xattr        = "enable"
1229

    
1230
## deny access the file-extensions
1231
#
1232
# ~    is for backupfiles from vi, emacs, joe, ...
1233
# .inc is often used for code includes which should in general not be part
1234
#      of the document-root
1235
url.access-deny             = ( "~", ".inc" )
1236

    
1237

    
1238
######### Options that are good to be but not neccesary to be changed #######
1239

    
1240
## bind to port (default: 80)
1241

    
1242
EOD;
1243

    
1244
	$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1245
	$lighty_config .= "server.port  = {$lighty_port}\n";
1246
	$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1247
	$lighty_config .= "\$SERVER[\"socket\"]  == \"[::]:{$lighty_port}\" { \n";
1248
	if($cert <> "" and $key <> "") {
1249
		$lighty_config .= "\n";
1250
		$lighty_config .= "## ssl configuration\n";
1251
		$lighty_config .= "ssl.engine = \"enable\"\n";
1252
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1253
		if($ca <> "")
1254
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1255
	}
1256
	$lighty_config .= " }\n";
1257

    
1258

    
1259
	$lighty_config .= <<<EOD
1260

    
1261
## error-handler for status 404
1262
#server.error-handler-404   = "/error-handler.html"
1263
#server.error-handler-404   = "/error-handler.php"
1264

    
1265
## to help the rc.scripts
1266
server.pid-file            = "{$g['varrun_path']}/{$pid_file}"
1267

    
1268
## virtual directory listings
1269
server.dir-listing         = "disable"
1270

    
1271
## enable debugging
1272
debug.log-request-header   = "disable"
1273
debug.log-response-header  = "disable"
1274
debug.log-request-handling = "disable"
1275
debug.log-file-not-found   = "disable"
1276

    
1277
# gzip compression
1278
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1279
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1280

    
1281
{$server_upload_dirs}
1282

    
1283
{$server_max_request_size}
1284

    
1285
{$fastcgi_config}
1286

    
1287
{$cgi_config}
1288

    
1289
{$captive_portal_mod_evasive}
1290

    
1291
expire.url = (
1292
				"" => "access 50 hours",	
1293
        )
1294

    
1295
EOD;
1296

    
1297
	$cert = str_replace("\r", "", $cert);
1298
	$key = str_replace("\r", "", $key);
1299
	$ca = str_replace("\r", "", $ca);
1300

    
1301
	$cert = str_replace("\n\n", "\n", $cert);
1302
	$key = str_replace("\n\n", "\n", $key);
1303
	$ca = str_replace("\n\n", "\n", $ca);
1304

    
1305
	if($cert <> "" and $key <> "") {
1306
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1307
		if (!$fd) {
1308
			printf(gettext("Error: cannot open cert.pem in system_webgui_start().%s"), "\n");
1309
			return 1;
1310
		}
1311
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1312
		fwrite($fd, $cert);
1313
		fwrite($fd, "\n");
1314
		fwrite($fd, $key);
1315
		fclose($fd);
1316
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
1317
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1318
			if (!$fd) {
1319
				printf(gettext("Error: cannot open ca.pem in system_webgui_start().%s"), "\n");
1320
				return 1;
1321
			}
1322
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1323
			fwrite($fd, $ca);
1324
			fclose($fd);
1325
		}
1326
		$lighty_config .= "\n";
1327
		$lighty_config .= "## " . gettext("ssl configuration") . "\n";
1328
		$lighty_config .= "ssl.engine = \"enable\"\n";
1329
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1330

    
1331
		// SSLv2/3 is deprecated, force use of TLS
1332
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
1333
		$lighty_config .= "ssl.use-sslv3 = \"disable\"\n";
1334

    
1335
		/* Hifn accelerators do NOT work with the BEAST mitigation code. Do not allow it to be enabled if a Hifn card has been detected. */
1336
		$fd = @fopen("{$g['varlog_path']}/dmesg.boot", "r");
1337
		if ($fd) {
1338
			while (!feof($fd)) {
1339
				$dmesgl = fgets($fd);
1340
				if (preg_match("/^hifn.: (.*?),/", $dmesgl, $matches) && isset($config['system']['webgui']['beast_protection'])) {
1341
						unset($config['system']['webgui']['beast_protection']);
1342
						log_error("BEAST Protection disabled because a conflicting cryptographic accelerator card has been detected (" . $matches[1] . ")");
1343
					break;
1344
				}
1345
			}
1346
			fclose($fd);
1347
		}
1348

    
1349
		if (isset($config['system']['webgui']['beast_protection'])) {
1350
			$lighty_config .= "ssl.honor-cipher-order = \"enable\"\n";
1351
			$lighty_config .= "ssl.cipher-list = \"ECDHE-RSA-AES256-SHA384:AES256-SHA256:HIGH:!MD5:!aNULL:!EDH:!AESGCM\"\n";
1352
		} else {
1353
			$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:!aNULL:!eNULL:!3DES:@STRENGTH\"\n";
1354
		}
1355

    
1356
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1357
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1358
	}
1359

    
1360
	// Add HTTP to HTTPS redirect	
1361
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1362
		if($lighty_port != "443") 
1363
			$redirectport = ":{$lighty_port}";
1364
		$lighty_config .= <<<EOD
1365
\$SERVER["socket"] == ":80" {
1366
	\$HTTP["host"] =~ "(.*)" {
1367
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1368
	}
1369
}
1370
\$SERVER["socket"] == "[::]:80" {
1371
	\$HTTP["host"] =~ "(.*)" {
1372
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1373
	}
1374
}
1375
EOD;
1376
	}
1377

    
1378
	$fd = fopen("{$filename}", "w");
1379
	if (!$fd) {
1380
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1381
		return 1;
1382
	}
1383
	fwrite($fd, $lighty_config);
1384
	fclose($fd);
1385

    
1386
	return 0;
1387

    
1388
}
1389

    
1390
function system_timezone_configure() {
1391
	global $config, $g;
1392
	if(isset($config['system']['developerspew'])) {
1393
		$mt = microtime();
1394
		echo "system_timezone_configure() being called $mt\n";
1395
	}
1396

    
1397
	$syscfg = $config['system'];
1398

    
1399
	if (platform_booting())
1400
		echo gettext("Setting timezone...");
1401

    
1402
	/* extract appropriate timezone file */
1403
	$timezone = $syscfg['timezone'];
1404
	if ($timezone) {
1405
		exec('/usr/bin/tar -tvzf /usr/share/zoneinfo.tgz', $tzs);
1406
		foreach ($tzs as $tz) {
1407
			if (preg_match(",{$timezone}$,", $tz))
1408
				break;
1409
			if (preg_match(",{$timezone} link to *(.*)$,", $tz, $matches)) {
1410
				$timezone = $matches[1];
1411
				break;
1412
			}
1413
		}
1414
	} else
1415
		$timezone = "Etc/UTC";
1416

    
1417
	conf_mount_rw();
1418

    
1419
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1420
		escapeshellarg($timezone) . " > /etc/localtime");
1421

    
1422
	mwexec("sync");
1423
	conf_mount_ro();
1424

    
1425
	if (platform_booting())
1426
		echo gettext("done.") . "\n";
1427
}
1428

    
1429
function system_ntp_setup_gps($serialport) {
1430
	global $config, $g;
1431
	$gps_device = '/dev/gps0';
1432
	$serialport = '/dev/'.$serialport;
1433

    
1434
	if (!file_exists($serialport))
1435
		return false;
1436

    
1437
	conf_mount_rw();
1438
	// Create symlink that ntpd requires
1439
	unlink_if_exists($gps_device);
1440
	@symlink($serialport, $gps_device);
1441

    
1442
	/* Send the following to the GPS port to initialize the GPS */
1443
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
1444
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
1445
	}else{
1446
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1447
	}
1448

    
1449
	/* XXX: Why not file_put_contents to the device */
1450
	@file_put_contents('/tmp/gps.init', $gps_init);
1451
	`cat /tmp/gps.init > $serialport`;
1452

    
1453
	/* Add /etc/remote entry in case we need to read from the GPS with tip */
1454
	if (intval(`grep -c '^gps0' /etc/remote`) == 0) {
1455
		$gpsbaud = '4800';
1456
		if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['speed'])) {
1457
			switch($config['ntpd']['gps']['speed']) {
1458
				case '16':
1459
					$gpsbaud = '9600';
1460
					break;
1461
				case '32':
1462
					$gpsbaud = '19200';
1463
					break;
1464
				case '48':
1465
					$gpsbaud = '38400';
1466
					break;
1467
				case '64':
1468
					$gpsbaud = '57600';
1469
					break;
1470
				case '80':
1471
					$gpsbaud = '115200';
1472
					break;
1473
			}
1474
		}
1475
		@file_put_contents("/etc/remote", "gps0:dv={$serialport}:br#{$gpsbaud}:pa=none:", FILE_APPEND);
1476
	}
1477

    
1478
	conf_mount_ro();
1479

    
1480
	return true;
1481
}
1482

    
1483
function system_ntp_setup_pps($serialport) {
1484
	global $config, $g;
1485

    
1486
	$pps_device = '/dev/pps0';
1487
	$serialport = '/dev/'.$serialport;
1488

    
1489
	if (!file_exists($serialport))
1490
		return false;
1491

    
1492
	conf_mount_rw();
1493
	// Create symlink that ntpd requires
1494
	unlink_if_exists($pps_device);
1495
	@symlink($serialport, $pps_device);
1496

    
1497
	conf_mount_ro();
1498

    
1499
	return true;
1500
}
1501

    
1502

    
1503
function system_ntp_configure($start_ntpd=true) {
1504
	global $config, $g;
1505

    
1506
	$driftfile = "/var/db/ntpd.drift";
1507
	$statsdir = "/var/log/ntp";
1508
	$gps_device = '/dev/gps0';
1509

    
1510
	if ($g['platform'] == 'jail')
1511
		return;
1512

    
1513
	safe_mkdir($statsdir);
1514

    
1515
	if (!is_array($config['ntpd']))
1516
		$config['ntpd'] = array();
1517

    
1518
	$ntpcfg = "# \n";
1519
	$ntpcfg .= "# pfSense ntp configuration file \n";
1520
	$ntpcfg .= "# \n\n";
1521
	$ntpcfg .= "tinker panic 0 \n";
1522

    
1523
	/* Add Orphan mode */
1524
	$ntpcfg .= "# Orphan mode stratum\n";
1525
	$ntpcfg .= 'tos orphan ';
1526
	if (!empty($config['ntpd']['orphan'])) {
1527
		$ntpcfg .= $config['ntpd']['orphan'];
1528
	}else{
1529
		$ntpcfg .= '12';
1530
	}
1531
	$ntpcfg .= "\n";
1532

    
1533
	/* Add PPS configuration */
1534
	if (is_array($config['ntpd']['pps']) && !empty($config['ntpd']['pps']['port'])
1535
		&& file_exists('/dev/'.$config['ntpd']['pps']['port'])
1536
		&& system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
1537
		$ntpcfg .= "\n";
1538
		$ntpcfg .= "# PPS Setup\n";
1539
		$ntpcfg .= 'server 127.127.22.0';
1540
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1541
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
1542
			$ntpcfg .= ' prefer'; 
1543
		}
1544
		if (!empty($config['ntpd']['pps']['noselect'])) {
1545
			$ntpcfg .= ' noselect ';
1546
		}
1547
		$ntpcfg .= "\n";
1548
		$ntpcfg .= 'fudge 127.127.22.0';
1549
		if (!empty($config['ntpd']['pps']['fudge1'])) {
1550
			$ntpcfg .= ' time1 ';
1551
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
1552
		}
1553
		if (!empty($config['ntpd']['pps']['flag2'])) {
1554
			$ntpcfg .= ' flag2 1';
1555
		}
1556
		if (!empty($config['ntpd']['pps']['flag3'])) {
1557
			$ntpcfg .= ' flag3 1';
1558
		}else{
1559
			$ntpcfg .= ' flag3 0';
1560
		}
1561
		if (!empty($config['ntpd']['pps']['flag4'])) {
1562
			$ntpcfg .= ' flag4 1';
1563
		}
1564
		if (!empty($config['ntpd']['pps']['refid'])) {
1565
			$ntpcfg .= ' refid ';
1566
			$ntpcfg .= $config['ntpd']['pps']['refid'];
1567
		}
1568
		$ntpcfg .= "\n";
1569
	}
1570
	/* End PPS configuration */
1571

    
1572
	/* Add GPS configuration */
1573
	if (is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['port'])
1574
		&& file_exists('/dev/'.$config['ntpd']['gps']['port'])
1575
		&& system_ntp_setup_gps($config['ntpd']['gps']['port'])) {
1576
		$ntpcfg .= "\n";
1577
		$ntpcfg .= "# GPS Setup\n";
1578
		$ntpcfg .= 'server 127.127.20.0 mode ';
1579
		if (!empty($config['ntpd']['gps']['nmea']) || !empty($config['ntpd']['gps']['speed']) || !empty($config['ntpd']['gps']['subsec'])) {
1580
			if (!empty($config['ntpd']['gps']['nmea'])) {
1581
				$ntpmode = (int) $config['ntpd']['gps']['nmea'];
1582
			}
1583
			if (!empty($config['ntpd']['gps']['speed'])) {
1584
				$ntpmode += (int) $config['ntpd']['gps']['speed'];
1585
			}
1586
			if (!empty($config['ntpd']['gps']['subsec'])) {
1587
				$ntpmode += 128;
1588
			}
1589
			$ntpcfg .= (string) $ntpmode;
1590
		}else{
1591
			$ntpcfg .= '0';
1592
		}
1593
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1594
		if (empty($config['ntpd']['gps']['prefer'])) { /*note: this one works backwards */
1595
			$ntpcfg .= ' prefer'; 
1596
		}
1597
		if (!empty($config['ntpd']['gps']['noselect'])) {
1598
			$ntpcfg .= ' noselect ';
1599
		}
1600
		$ntpcfg .= "\n";
1601
		$ntpcfg .= 'fudge 127.127.20.0';
1602
		if (!empty($config['ntpd']['gps']['fudge1'])) {
1603
			$ntpcfg .= ' time1 ';
1604
			$ntpcfg .= $config['ntpd']['gps']['fudge1'];
1605
		}
1606
		if (!empty($config['ntpd']['gps']['fudge2'])) {
1607
			$ntpcfg .= ' time2 ';
1608
			$ntpcfg .= $config['ntpd']['gps']['fudge2'];
1609
		}
1610
		if (!empty($config['ntpd']['gps']['flag1'])) {
1611
			$ntpcfg .= ' flag1 1';
1612
		}else{
1613
			$ntpcfg .= ' flag1 0';
1614
		}
1615
		if (!empty($config['ntpd']['gps']['flag2'])) {
1616
			$ntpcfg .= ' flag2 1';
1617
		}
1618
		if (!empty($config['ntpd']['gps']['flag3'])) {
1619
			$ntpcfg .= ' flag3 1';
1620
		}else{
1621
			$ntpcfg .= ' flag3 0';
1622
		}
1623
		if (!empty($config['ntpd']['gps']['flag4'])) {
1624
			$ntpcfg .= ' flag4 1';
1625
		}
1626
		if (!empty($config['ntpd']['gps']['refid'])) {
1627
			$ntpcfg .= ' refid ';
1628
			$ntpcfg .= $config['ntpd']['gps']['refid'];
1629
		}
1630
		$ntpcfg .= "\n";
1631
	}elseif (is_array($config['ntpd']) && !empty($config['ntpd']['gpsport'])
1632
		&& file_exists('/dev/'.$config['ntpd']['gpsport'])
1633
		&& system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1634
		/* This handles a 2.1 and earlier config */
1635
		$ntpcfg .= "# GPS Setup\n";
1636
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1637
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1638
		// Fall back to local clock if GPS is out of sync?
1639
		$ntpcfg .= "server 127.127.1.0\n";
1640
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1641
	}
1642
	/* End GPS configuration */
1643
	
1644
	$ntpcfg .= "\n\n# Upstream Servers\n";
1645
	/* foreach through ntp servers and write out to ntpd.conf */
1646
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1647
		$ntpcfg .= "server {$ts} iburst maxpoll 9";
1648
		if (substr_count($config['ntpd']['prefer'], $ts)) $ntpcfg .= ' prefer';
1649
		if (substr_count($config['ntpd']['noselect'], $ts)) $ntpcfg .= ' noselect';
1650
		$ntpcfg .= "\n";
1651
	}
1652
	unset($ts);
1653

    
1654
	$ntpcfg .= "\n\n";
1655
	$ntpcfg .= "disable monitor\n"; //prevent NTP reflection attack, see https://forum.pfsense.org/index.php/topic,67189.msg389132.html#msg389132
1656
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
1657
		$ntpcfg .= "enable stats\n";
1658
		$ntpcfg .= 'statistics';
1659
		if (!empty($config['ntpd']['clockstats'])) {
1660
			$ntpcfg .= ' clockstats';
1661
		}
1662
		if (!empty($config['ntpd']['loopstats'])) {
1663
			$ntpcfg .= ' loopstats';
1664
		}
1665
		if (!empty($config['ntpd']['peerstats'])) {
1666
			$ntpcfg .= ' peerstats';
1667
		}
1668
		$ntpcfg .= "\n";
1669
	}
1670
	$ntpcfg .= "statsdir {$statsdir}\n";
1671
	$ntpcfg .= 'logconfig =syncall +clockall';
1672
	if (!empty($config['ntpd']['logpeer'])) {
1673
		$ntpcfg .= ' +peerall';
1674
	}
1675
	if (!empty($config['ntpd']['logsys'])) {
1676
		$ntpcfg .= ' +sysall';
1677
	}
1678
	$ntpcfg .= "\n";
1679
	$ntpcfg .= "driftfile {$driftfile}\n";
1680
	/* Access restrictions */
1681
	$ntpcfg .= 'restrict default';
1682
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1683
		$ntpcfg .= ' kod limited'; 
1684
	}
1685
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1686
		$ntpcfg .= ' nomodify'; 
1687
	}
1688
	if (!empty($config['ntpd']['noquery'])) {
1689
		$ntpcfg .= ' noquery';
1690
	}
1691
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1692
		$ntpcfg .= ' nopeer'; 
1693
	}
1694
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1695
		$ntpcfg .= ' notrap'; 
1696
	}
1697
	if (!empty($config['ntpd']['noserve'])) {
1698
		$ntpcfg .= ' noserve';
1699
	}
1700
	$ntpcfg .= "\nrestrict -6 default";
1701
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1702
		$ntpcfg .= ' kod limited'; 
1703
	}
1704
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1705
		$ntpcfg .= ' nomodify'; 
1706
	}
1707
	if (!empty($config['ntpd']['noquery'])) {
1708
		$ntpcfg .= ' noquery';
1709
	}
1710
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1711
		$ntpcfg .= ' nopeer'; 
1712
	}
1713
	if (!empty($config['ntpd']['noserve'])) {
1714
		$ntpcfg .= ' noserve';
1715
	}
1716
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1717
		$ntpcfg .= ' notrap'; 
1718
	}
1719
	$ntpcfg .= "\n";
1720

    
1721
	/* A leapseconds file is really only useful if this clock is stratum 1 */
1722
	$ntpcfg .= "\n";
1723
	if (!empty($config['ntpd']['leapsec'])) {
1724
		$leapsec .= base64_decode($config['ntpd']['leapsec']);
1725
		file_put_contents('/var/db/leap-seconds', $leapsec);
1726
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
1727
	}
1728
	
1729

    
1730
	if (empty($config['ntpd']['interface'])) {
1731
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface']))
1732
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1733
		else
1734
			$interfaces = array();
1735
	} else
1736
		$interfaces = explode(",", $config['ntpd']['interface']);
1737

    
1738
	if (is_array($interfaces) && count($interfaces)) {
1739
		$ntpcfg .= "interface ignore all\n";
1740
		foreach ($interfaces as $interface) {
1741
			if (!is_ipaddr($interface)) {
1742
				$interface = get_real_interface($interface);
1743
			}
1744
			if (!empty($interface))
1745
				$ntpcfg .= "interface listen {$interface}\n";
1746
		}
1747
	}
1748

    
1749
	/* open configuration for wrting or bail */
1750
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
1751
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1752
		return;
1753
	}
1754

    
1755
	/* At bootup we just want to write out the config. */
1756
	if (!$start_ntpd)
1757
		return;
1758

    
1759
	/* if ntpd is running, kill it */
1760
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1761
		killbypid("{$g['varrun_path']}/ntpd.pid");
1762
	}
1763
	@unlink("{$g['varrun_path']}/ntpd.pid");
1764

    
1765
	/* if /var/empty does not exist, create it */
1766
	if(!is_dir("/var/empty"))
1767
		mkdir("/var/empty", 0775, true);
1768

    
1769
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1770
	mwexec("/usr/local/sbin/ntpd -g -c {$g['varetc_path']}/ntpd.conf -p {$g['varrun_path']}/ntpd.pid", false, true);
1771
	
1772
	// Note that we are starting up
1773
	log_error("NTPD is starting up.");
1774
	return;
1775
}
1776

    
1777
function sync_system_time() {
1778
	global $config, $g;
1779

    
1780
	if (platform_booting())
1781
		echo gettext("Syncing system time before startup...");
1782

    
1783
	/* foreach through servers and write out to ntpd.conf */
1784
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1785
		mwexec("/usr/local/sbin/ntpdate -s $ts");
1786
	}
1787
	
1788
	if (platform_booting())
1789
		echo gettext("done.") . "\n";
1790
	
1791
}
1792

    
1793
function system_halt() {
1794
	global $g;
1795

    
1796
	system_reboot_cleanup();
1797

    
1798
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1799
}
1800

    
1801
function system_reboot() {
1802
	global $g;
1803

    
1804
	system_reboot_cleanup();
1805

    
1806
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1807
}
1808

    
1809
function system_reboot_sync() {
1810
	global $g;
1811

    
1812
	system_reboot_cleanup();
1813

    
1814
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1815
}
1816

    
1817
function system_reboot_cleanup() {
1818
	global $config, $cpzone;
1819

    
1820
	mwexec("/usr/local/bin/beep.sh stop");
1821
	require_once("captiveportal.inc");
1822
	if (is_array($config['captiveportal'])) {
1823
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
1824
			captiveportal_radius_stop_all();
1825
			captiveportal_send_server_accounting(true);
1826
		}
1827
	}
1828
	require_once("voucher.inc");
1829
	voucher_save_db_to_config();
1830
	require_once("pkg-utils.inc");
1831
	stop_packages();
1832
}
1833

    
1834
function system_do_shell_commands($early = 0) {
1835
	global $config, $g;
1836
	if(isset($config['system']['developerspew'])) {
1837
		$mt = microtime();
1838
		echo "system_do_shell_commands() being called $mt\n";
1839
	}
1840

    
1841
	if ($early)
1842
		$cmdn = "earlyshellcmd";
1843
	else
1844
		$cmdn = "shellcmd";
1845

    
1846
	if (is_array($config['system'][$cmdn])) {
1847

    
1848
		/* *cmd is an array, loop through */
1849
		foreach ($config['system'][$cmdn] as $cmd) {
1850
			exec($cmd);
1851
		}
1852

    
1853
	} elseif($config['system'][$cmdn] <> "") {
1854

    
1855
		/* execute single item */
1856
		exec($config['system'][$cmdn]);
1857

    
1858
	}
1859
}
1860

    
1861
function system_console_configure() {
1862
	global $config, $g;
1863
	if(isset($config['system']['developerspew'])) {
1864
		$mt = microtime();
1865
		echo "system_console_configure() being called $mt\n";
1866
	}
1867

    
1868
	if (isset($config['system']['disableconsolemenu'])) {
1869
		touch("{$g['varetc_path']}/disableconsole");
1870
	} else {
1871
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1872
	}
1873
}
1874

    
1875
function system_dmesg_save() {
1876
	global $g;
1877
	if(isset($config['system']['developerspew'])) {
1878
		$mt = microtime();
1879
		echo "system_dmesg_save() being called $mt\n";
1880
	}
1881

    
1882
	$dmesg = "";
1883
	$_gb = exec("/sbin/dmesg", $dmesg);
1884

    
1885
	/* find last copyright line (output from previous boots may be present) */
1886
	$lastcpline = 0;
1887

    
1888
	for ($i = 0; $i < count($dmesg); $i++) {
1889
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1890
			$lastcpline = $i;
1891
	}
1892

    
1893
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1894
	if (!$fd) {
1895
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1896
		return 1;
1897
	}
1898

    
1899
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1900
		fwrite($fd, $dmesg[$i] . "\n");
1901

    
1902
	fclose($fd);
1903
	unset($dmesg);
1904

    
1905
	return 0;
1906
}
1907

    
1908
function system_set_harddisk_standby() {
1909
	global $g, $config;
1910
	if(isset($config['system']['developerspew'])) {
1911
		$mt = microtime();
1912
		echo "system_set_harddisk_standby() being called $mt\n";
1913
	}
1914

    
1915
	if (isset($config['system']['harddiskstandby'])) {
1916
		if (platform_booting()) {
1917
			echo gettext('Setting hard disk standby... ');
1918
		}
1919

    
1920
		$standby = $config['system']['harddiskstandby'];
1921
		// Check for a numeric value
1922
		if (is_numeric($standby)) {
1923
			// Sync the disk(s)
1924
			pfSense_sync();
1925
			if (set_single_sysctl('hw.ata.standby', (int)$standby)) {
1926
				// Reinitialize ATA-drives
1927
				mwexec('/usr/local/sbin/atareinit');
1928
				if (platform_booting()) {
1929
					echo gettext("done.") . "\n";
1930
				}
1931
			} else if (platform_booting()) {
1932
				echo gettext("failed!") . "\n";
1933
			}
1934
		} else if (platform_booting()) {
1935
			echo gettext("failed!") . "\n";
1936
		}
1937
	}
1938
}
1939

    
1940
function system_setup_sysctl() {
1941
	global $config;
1942
	if(isset($config['system']['developerspew'])) {
1943
		$mt = microtime();
1944
		echo "system_setup_sysctl() being called $mt\n";
1945
	}
1946

    
1947
	activate_sysctls();	
1948

    
1949
	if (isset($config['system']['sharednet'])) {
1950
		system_disable_arp_wrong_if();
1951
	}
1952
}
1953

    
1954
function system_disable_arp_wrong_if() {
1955
	global $config;
1956
	if(isset($config['system']['developerspew'])) {
1957
		$mt = microtime();
1958
		echo "system_disable_arp_wrong_if() being called $mt\n";
1959
	}
1960
	set_sysctl(array(
1961
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
1962
		"net.link.ether.inet.log_arp_movements" => "0"
1963
	));
1964
}
1965

    
1966
function system_enable_arp_wrong_if() {
1967
	global $config;
1968
	if(isset($config['system']['developerspew'])) {
1969
		$mt = microtime();
1970
		echo "system_enable_arp_wrong_if() being called $mt\n";
1971
	}
1972
	set_sysctl(array(
1973
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
1974
		"net.link.ether.inet.log_arp_movements" => "1"
1975
	));
1976
}
1977

    
1978
function enable_watchdog() {
1979
	global $config;
1980
	return;
1981
	$install_watchdog = false;
1982
	$supported_watchdogs = array("Geode");
1983
	$file = file_get_contents("/var/log/dmesg.boot");
1984
	foreach($supported_watchdogs as $sd) {
1985
		if(stristr($file, "Geode")) {
1986
			$install_watchdog = true;
1987
		}
1988
	}
1989
	if($install_watchdog == true) {
1990
		if(is_process_running("watchdogd"))
1991
			mwexec("/usr/bin/killall watchdogd", true);
1992
		exec("/usr/sbin/watchdogd");
1993
	}
1994
}
1995

    
1996
function system_check_reset_button() {
1997
	global $g;
1998

    
1999
	$specplatform = system_identify_specific_platform();
2000

    
2001
	switch ($specplatform['name']) {
2002
	case 'alix':
2003
	case 'wrap':
2004
	case 'FW7541':
2005
	case 'APU':
2006
		break;
2007
	default:
2008
		return 0;
2009
	}
2010

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

    
2013
	if ($retval == 99) {
2014
		/* user has pressed reset button for 2 seconds - 
2015
		   reset to factory defaults */
2016
		echo <<<EOD
2017

    
2018
***********************************************************************
2019
* Reset button pressed - resetting configuration to factory defaults. *
2020
* The system will reboot after this completes.                        *
2021
***********************************************************************
2022

    
2023

    
2024
EOD;
2025
		
2026
		reset_factory_defaults();
2027
		system_reboot_sync();
2028
		exit(0);
2029
	}
2030

    
2031
	return 0;
2032
}
2033

    
2034
/* attempt to identify the specific platform (for embedded systems)
2035
   Returns an array with two elements:
2036
	name => platform string (e.g. 'wrap', 'alix' etc.)
2037
	descr => human-readable description (e.g. "PC Engines WRAP")
2038
*/
2039
function system_identify_specific_platform() {
2040
	global $g;
2041
	
2042
	if ($g['platform'] == 'generic-pc')
2043
		return array('name' => 'generic-pc', 'descr' => gettext("Generic PC"));
2044
	
2045
	if ($g['platform'] == 'generic-pc-cdrom')
2046
		return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)"));
2047
	
2048
	/* Try to guess from smbios strings */
2049
	unset($output);
2050
	$_gb = exec('/bin/kenv smbios.system.product 2>/dev/null', $output);
2051
	switch ($output[0]) {
2052
	case 'FW7541':
2053
		return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2054
		break;
2055
	case 'APU':
2056
		return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2057
		break;
2058
	}
2059

    
2060
	/* the rest of the code only deals with 'embedded' platforms */
2061
	if ($g['platform'] != 'nanobsd')
2062
		return array('name' => $g['platform'], 'descr' => $g['platform']);
2063

    
2064
	$dmesg = get_single_sysctl('hw.model');
2065

    
2066
	if (strpos($dmesg, "PC Engines WRAP") !== false)
2067
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
2068
	
2069
	if (strpos($dmesg, "PC Engines ALIX") !== false)
2070
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2071

    
2072
	if (preg_match("/Soekris net45../", $dmesg, $matches))
2073
		return array('name' => 'net45xx', 'descr' => $matches[0]);
2074
	
2075
	if (preg_match("/Soekris net48../", $dmesg, $matches))
2076
		return array('name' => 'net48xx', 'descr' => $matches[0]);
2077
		
2078
	if (preg_match("/Soekris net55../", $dmesg, $matches))
2079
		return array('name' => 'net55xx', 'descr' => $matches[0]);
2080

    
2081
	unset($dmesg);
2082

    
2083
	$dmesg_boot = system_get_dmesg_boot();
2084
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false)
2085
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2086
	unset($dmesg_boot);
2087

    
2088
	/* unknown embedded platform */
2089
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
2090
}
2091

    
2092
function system_get_dmesg_boot() {
2093
	global $g;
2094
		
2095
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2096
}
2097

    
2098
?>
(53-53/68)