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
		
107
	}
108
	unset($disp_cache);
109
	return $disp_sysctl;
110
}
111

    
112
function activate_sysctls() {
113
	global $config, $g, $sysctls;
114

    
115
	if ($g['platform'] == 'jail')
116
		return;
117

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

    
125
			$sysctls[$tunable['tunable']] = $value;
126
		}
127
	}
128

    
129
	set_sysctl($sysctls);
130
}
131

    
132
function system_resolvconf_generate($dynupdate = false) {
133
	global $config, $g;
134

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

    
140
	$syscfg = $config['system'];
141

    
142
	if (((isset($config['dnsmasq']['enable']) && (!isset($config['dnsmasq']['port'])) || $config['dnsmasq']['port'] == "53" && (empty($config['dnsmasq']['interface']) || in_array("lo0", explode(",", $config['dnsmasq']['interface']))))
143
		|| (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']))))
144
		&& !isset($config['system']['dnslocalhost']))
145
		$resolvconf .= "nameserver 127.0.0.1\n";
146

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

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

    
175
	$dnslock = lock('resolvconf', LOCK_EX);
176

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

    
184
	fwrite($fd, $resolvconf);
185
	fclose($fd);
186

    
187
	if (!$g['booting']) {
188
		/* restart dhcpd (nameservers may have changed) */
189
		if (!$dynupdate)
190
			services_dhcpd_configure();
191
	}
192

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

    
223
	unlock($dnslock);
224

    
225
	return 0;
226
}
227

    
228
function get_searchdomains() {
229
	global $config, $g;
230

    
231
	$master_list = array();
232
	
233
	// Read in dhclient nameservers
234
	$search_list = glob("/var/etc/searchdomain_*");
235
	if (is_array($search_list)) {
236
		foreach($search_list as $fdns) {
237
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
238
			if (!is_array($contents))
239
				continue;
240
			foreach ($contents as $dns) {
241
				if(is_hostname($dns)) 
242
					$master_list[] = $dns;
243
			}
244
		}
245
	}
246

    
247
	return $master_list;
248
}
249

    
250
function get_nameservers() {
251
	global $config, $g;
252
	$master_list = array();
253
	
254
	// Read in dhclient nameservers
255
	$dns_lists = glob("/var/etc/nameserver_*");
256
	if (is_array($dns_lists)) {
257
		foreach($dns_lists as $fdns) {
258
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
259
			if (!is_array($contents))
260
				continue;
261
			foreach ($contents as $dns) {
262
				if(is_ipaddr($dns)) 
263
					$master_list[] = $dns;
264
			}
265
		}
266
	}
267

    
268
	// Read in any extra nameservers
269
	if(file_exists("/var/etc/nameservers.conf")) {
270
		$dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
271
		if(is_array($dns_s)) {
272
			foreach($dns_s as $dns)
273
				if (is_ipaddr($dns))
274
					$master_list[] = $dns;
275
		}
276
	}
277

    
278
	return $master_list;
279
}
280

    
281
function system_hosts_generate() {
282
	global $config, $g;
283
	if (isset($config['system']['developerspew'])) {
284
		$mt = microtime();
285
		echo "system_hosts_generate() being called $mt\n";
286
	}
287

    
288
	$syscfg = $config['system'];
289
	if (isset($config['unbound']) && isset($config['unbound']['enable']))
290
		$dnsmasqcfg = $config['unbound'];
291
	else
292
		$dnsmasqcfg = $config['dnsmasq'];
293

    
294
	$hosts =  "127.0.0.1	localhost localhost.{$syscfg['domain']}\n";
295
	$hosts .= "::1		localhost localhost.{$syscfg['domain']}\n";
296
	$lhosts = "";
297
	$dhosts = "";
298

    
299
	if ($config['interfaces']['lan']) {
300
		$cfgip = get_interface_ip("lan");
301
		if (is_ipaddr($cfgip))
302
			$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
303
	} else {
304
		$sysiflist = get_configured_interface_list();
305
		foreach ($sysiflist as $sysif) {
306
			if (!interface_has_gateway($sysif)) {
307
				$cfgip = get_interface_ip($sysif);
308
				if (is_ipaddr($cfgip)) {
309
					$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
310
					break;
311
				}
312
			}
313
		}
314
	}
315

    
316
	if (isset($dnsmasqcfg['enable'])) {
317
		if (!is_array($dnsmasqcfg['hosts']))
318
			$dnsmasqcfg['hosts'] = array();
319

    
320
		foreach ($dnsmasqcfg['hosts'] as $host) {
321
			if ($host['host'])
322
				$lhosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
323
			else
324
				$lhosts .= "{$host['ip']}	{$host['domain']}\n";
325
			if (!is_array($host['aliases']) || !is_array($host['aliases']['item']))
326
				continue;
327
			foreach ($host['aliases']['item'] as $alias) {
328
				if ($alias['host'])
329
					$lhosts .= "{$host['ip']}	{$alias['host']}.{$alias['domain']} {$alias['host']}\n";
330
				else
331
					$lhosts .= "{$host['ip']}	{$alias['domain']}\n";
332
			}
333
		}
334
		if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpd'])) {
335
			foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf)
336
				if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
337
						foreach ($dhcpifconf['staticmap'] as $host)
338
							if ($host['ipaddr'] && $host['hostname'] && $host['domain'])
339
								$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$host['domain']} {$host['hostname']}\n";
340
							else if ($host['ipaddr'] && $host['hostname'] && $dhcpifconf['domain'])
341
								$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$dhcpifconf['domain']} {$host['hostname']}\n";
342
							else if ($host['ipaddr'] && $host['hostname'])
343
								$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
344
		}
345
		if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpdv6'])) {
346
			foreach ($config['dhcpdv6'] as $dhcpif => $dhcpifconf)
347
				if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
348
						foreach ($dhcpifconf['staticmap'] as $host)
349
							if ($host['ipaddrv6'] && $host['hostname'] && $host['domain'])
350
								$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$host['domain']} {$host['hostname']}\n";
351
							else if ($host['ipaddrv6'] && $host['hostname'] && $dhcpifconf['domain'])
352
								$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$dhcpifconf['domain']} {$host['hostname']}\n";
353
							else if ($host['ipaddrv6'] && $host['hostname'])
354
								$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
355
		}
356

    
357
		if (isset($dnsmasqcfg['dhcpfirst']))
358
			$hosts .= $dhosts . $lhosts;
359
		else
360
			$hosts .= $lhosts . $dhosts;
361
	}
362

    
363
	/*
364
	 * Do not remove this because dhcpleases monitors with kqueue it needs to be 
365
	 * killed before writing to hosts files.
366
	 */
367
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
368
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
369
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
370
	}
371
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
372
	if (!$fd) {
373
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
374
		return 1;
375
	}
376
	fwrite($fd, $hosts);
377
	fclose($fd);
378

    
379
	if (isset($config['unbound']['enable'])) {
380
		require_once("unbound.inc");
381
		unbound_hosts_generate();
382
	}
383

    
384
	system_dhcpleases_configure();
385

    
386
	return 0;
387
}
388

    
389
function system_dhcpleases_configure() {
390
	global $config, $g;
391
	
392
	if ($g['platform'] == 'jail')
393
		return;
394
	/* Start the monitoring process for dynamic dhcpclients. */
395
	if ((isset($config['dnsmasq']['enable']) && isset($config['dnsmasq']['regdhcp'])) 
396
		|| (isset($config['unbound']['enable']) && isset($config['unbound']['regdhcp']))) {
397
		/* Make sure we do not error out */
398
		mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db");
399
		if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases"))
400
			@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
401

    
402
		if (isset($config['unbound']['enable'])) {
403
			$dns_pid = "unbound.pid";
404
			$unbound_conf = "-u {$g['unbound_chroot_path']}/dhcpleases_entries.conf";
405
		} else {
406
			$dns_pid = "dnsmasq.pid";
407
			$unbound_conf = "";
408
		}
409

    
410
		$pidfile = "{$g['varrun_path']}/dhcpleases.pid";
411
		if (isvalidpid($pidfile)) {
412
			/* Make sure dhcpleases is using correct unbound or dnsmasq */
413
			$_gb = exec("/bin/pgrep -F {$pidfile} -f {$dns_pid}", $output, $retval);
414
			if (intval($retval) == 0) {
415
				sigkillbypid($pidfile, "HUP");
416
				return;
417
			} else
418
				sigkillbypid($pidfile, "TERM");
419
		}
420

    
421
		/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
422
		if (is_process_running("dhcpleases"))
423
			sigkillbyname('dhcpleases', "TERM");
424
		@unlink($pidfile);
425
		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");
426
	} else {
427
		sigkillbypid($pidfile, "TERM");
428
		@unlink($pidfile);
429
	}
430
}
431

    
432
function system_hostname_configure() {
433
	global $config, $g;
434
	if(isset($config['system']['developerspew'])) {
435
		$mt = microtime();
436
		echo "system_hostname_configure() being called $mt\n";
437
	}
438

    
439
	$syscfg = $config['system'];
440

    
441
	/* set hostname */
442
	$status = mwexec("/bin/hostname " .
443
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
444

    
445
    /* Setup host GUID ID.  This is used by ZFS. */
446
	mwexec("/etc/rc.d/hostid start");
447

    
448
	return $status;
449
}
450

    
451
function system_routing_configure($interface = "") {
452
	global $config, $g;
453
	if ($g['platform'] == 'jail')
454
		return;
455
	if(isset($config['system']['developerspew'])) {
456
		$mt = microtime();
457
		echo "system_routing_configure() being called $mt\n";
458
	}
459

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

    
525
	if ($dont_add_route == false ) {
526
		if (!empty($interface) && $interface != $interfacegw)
527
			;
528
		else if (is_ipaddrv4($gatewayip)) {
529
			log_error("ROUTING: setting default route to $gatewayip");
530
			mwexec("/sbin/route change -inet default " . escapeshellarg($gatewayip));
531
		}
532

    
533
		if (!empty($interface) && $interface != $interfacegwv6)
534
			;
535
		else if (is_ipaddrv6($gatewayipv6)) {
536
			$ifscope = "";
537
			if (is_linklocal($gatewayipv6) && !strpos($gatewayipv6, '%'))
538
				$ifscope = "%{$defaultifv6}";
539
			log_error("ROUTING: setting IPv6 default route to {$gatewayipv6}{$ifscope}");
540
			mwexec("/sbin/route change -inet6 default " . escapeshellarg("{$gatewayipv6}{$ifscope}"));
541
		}
542
	}
543

    
544
	system_staticroutes_configure($interface, false);
545

    
546
	return 0;
547
}
548

    
549
function system_staticroutes_configure($interface = "", $update_dns = false) {
550
	global $config, $g, $aliastable;
551

    
552
	$filterdns_list = array();
553

    
554
	$static_routes = get_staticroutes(false, true);
555
	if (count($static_routes)) {
556
		$gateways_arr = return_gateways_array(false, true);
557

    
558
		foreach ($static_routes as $rtent) {
559
			if (empty($gateways_arr[$rtent['gateway']])) {
560
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
561
				continue;
562
			}
563
			$gateway = $gateways_arr[$rtent['gateway']];
564
			if (!empty($interface) && $interface != $gateway['friendlyiface'])
565
				continue;
566

    
567
			$gatewayip = $gateway['gateway'];
568
			$interfacegw = $gateway['interface'];
569

    
570
			$blackhole = "";
571
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 3)))
572
				$blackhole = "-blackhole";
573

    
574
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network']))
575
				continue;
576

    
577
			$dnscache = array();
578
			if ($update_dns === true) {
579
				if (is_subnet($rtent['network']))
580
					continue;
581
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
582
				if (empty($dnscache))
583
					continue;
584
			}
585

    
586
			if (is_subnet($rtent['network']))
587
				$ips = array($rtent['network']);
588
			else {
589
				if (!isset($rtent['disabled']))
590
					$filterdns_list[] = $rtent['network'];
591
				$ips = add_hostname_to_watch($rtent['network']);
592
			}
593

    
594
			foreach ($dnscache as $ip) {
595
				if (in_array($ip, $ips))
596
					continue;
597
				mwexec("/sbin/route delete " . escapeshellarg($ip), true);
598
				if (isset($config['system']['route-debug'])) {
599
					$mt = microtime();
600
					log_error("ROUTING debug: $mt - route delete $ip ");
601
				}
602
			}
603

    
604
			if (isset($rtent['disabled'])) {
605
				/* XXX: This can break things by deleting routes that shouldn't be deleted - OpenVPN, dynamic routing scenarios, etc. redmine #3709 */
606
				foreach ($ips as $ip) {
607
					mwexec("/sbin/route delete " . escapeshellarg($ip), true);
608
					if (isset($config['system']['route-debug'])) {
609
						$mt = microtime();
610
						log_error("ROUTING debug: $mt - route delete $ip ");
611
					}
612
				}
613
				continue;
614
			}
615

    
616
			foreach ($ips as $ip) {
617
				if (is_ipaddrv4($ip))
618
					$ip .= "/32";
619
				else if (is_ipaddrv6($ip))
620
					$ip .= "/128";
621

    
622
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
623

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

    
626
				if (is_subnet($ip))
627
					if (is_ipaddr($gatewayip)) {
628
						mwexec($cmd . escapeshellarg($gatewayip));
629
						if (isset($config['system']['route-debug'])) {
630
							$mt = microtime();
631
							log_error("ROUTING debug: $mt - $cmd $gatewayip");
632
						}
633
					} else if (!empty($interfacegw)) {
634
						mwexec($cmd . "-iface " . escapeshellarg($interfacegw));
635
						if (isset($config['system']['route-debug'])) {
636
							$mt = microtime();
637
							log_error("ROUTING debug: $mt - $cmd -iface $interfacegw ");
638
						}
639
					}
640
			}
641
		}
642
		unset($gateways_arr);
643
	}
644
	unset($static_routes);
645

    
646
	if ($update_dns === false) {
647
		if (count($filterdns_list)) {
648
			$interval = 60;
649
			$hostnames = "";
650
			array_unique($filterdns_list);
651
			foreach ($filterdns_list as $hostname)
652
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
653
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
654
			unset($hostnames);
655

    
656
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid"))
657
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
658
			else
659
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
660
		} else {
661
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
662
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
663
		}
664
	}
665
	unset($filterdns_list);
666

    
667
	return 0;
668
}
669

    
670
function system_routing_enable() {
671
	global $config, $g;
672
	if(isset($config['system']['developerspew'])) {
673
		$mt = microtime();
674
		echo "system_routing_enable() being called $mt\n";
675
	}
676

    
677
	set_sysctl(array(
678
		"net.inet.ip.forwarding" => "1",
679
		"net.inet6.ip6.forwarding" => "1"
680
	));
681

    
682
	return;
683
}
684

    
685
function system_syslogd_fixup_server($server) {
686
	/* If it's an IPv6 IP alone, encase it in brackets */
687
	if (is_ipaddrv6($server))
688
		return "[$server]";
689
	else
690
		return $server;
691
}
692

    
693
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
694
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
695
	$facility .= " ".
696
	$remote_servers = "";
697
	$pad_to  = 56;
698
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
699
	if($syslogcfg['remoteserver'])
700
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
701
	if($syslogcfg['remoteserver2'])
702
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
703
	if($syslogcfg['remoteserver3'])
704
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
705
	return $remote_servers;
706
}
707

    
708
function system_syslogd_start() {
709
	global $config, $g;
710
	if(isset($config['system']['developerspew'])) {
711
		$mt = microtime();
712
		echo "system_syslogd_start() being called $mt\n";
713
	}
714

    
715
	mwexec("/etc/rc.d/hostid start");
716

    
717
	$syslogcfg = $config['syslog'];
718

    
719
	if ($g['booting'])
720
		echo gettext("Starting syslog...");
721

    
722
	if (is_process_running("fifolog_writer"))
723
		mwexec('/bin/pkill fifolog_writer');
724

    
725
	// Which logging type are we using this week??
726
	if (isset($config['system']['disablesyslogclog'])) {
727
		$log_directive = "";
728
		$log_create_directive = "/usr/bin/touch ";
729
		$log_size = "";
730
	} else if (isset($config['system']['usefifolog'])) {
731
		$log_directive = "|/usr/sbin/fifolog_writer ";
732
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
733
		$log_create_directive = "/usr/sbin/fifolog_create -s ";
734
	} else { // Defaults to CLOG
735
		$log_directive = "%";
736
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
737
		$log_create_directive = "/usr/local/sbin/clog -i -s ";
738
	}
739

    
740
	$syslogd_extra = "";
741
	if (isset($syslogcfg)) {
742
		$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');
743
		$syslogconf = "";
744
		if($config['installedpackages']['package']) {
745
			foreach($config['installedpackages']['package'] as $package) {
746
				if($package['logging']) {
747
					array_push($separatelogfacilities, $package['logging']['facilityname']);
748
					mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
749
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
750
				}
751
			}
752
		}
753
		$facilitylist = implode(',', array_unique($separatelogfacilities));
754
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd,miniupnpd\n";
755
		if (!isset($syslogcfg['disablelocallogging']))
756
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
757

    
758
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
759
		if (!isset($syslogcfg['disablelocallogging'])) 
760
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
761

    
762
		$syslogconf .= "!ppp\n";
763
		if (!isset($syslogcfg['disablelocallogging'])) 
764
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
765

    
766
		$syslogconf .= "!pptps\n";
767
		if (!isset($syslogcfg['disablelocallogging'])) 
768
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/pptps.log\n";
769

    
770
		$syslogconf .= "!poes\n";
771
		if (!isset($syslogcfg['disablelocallogging'])) 
772
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
773

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

    
778
		$syslogconf .= "!charon,ipsec_starter\n";
779
		if (!isset($syslogcfg['disablelocallogging'])) 
780
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ipsec.log\n";
781
		if (isset($syslogcfg['vpn']))
782
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
783

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

    
790
		$syslogconf .= "!apinger\n";
791
		if (!isset($syslogcfg['disablelocallogging']))
792
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/gateways.log\n";
793
		if (isset($syslogcfg['apinger']))
794
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
795

    
796
		$syslogconf .= "!dnsmasq,filterdns,unbound\n";
797
		if (!isset($syslogcfg['disablelocallogging']))
798
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
799

    
800
		$syslogconf .= "!dhcpd,dhcrelay,dhclient,dhcp6c\n";
801
		if (!isset($syslogcfg['disablelocallogging']))
802
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/dhcpd.log\n";
803
		if (isset($syslogcfg['dhcp']))
804
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
805

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

    
812
		$syslogconf .= "!hostapd\n";
813
		if (!isset($syslogcfg['disablelocallogging']))
814
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
815
		if (isset($syslogcfg['hostapd']))
816
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
817

    
818
		$syslogconf .= "!filterlog\n";
819
		$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/filter.log\n";
820
		if (isset($syslogcfg['filter']))
821
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
822

    
823
		$syslogconf .= "!-{$facilitylist}\n";
824
		if (!isset($syslogcfg['disablelocallogging'])) 
825
			$syslogconf .= <<<EOD
826
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
827
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
828
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
829
*.notice;kern.debug;lpr.info;mail.crit;daemon.none;		{$log_directive}{$g['varlog_path']}/system.log
830
news.err;local0.none;local3.none;local4.none;			{$log_directive}{$g['varlog_path']}/system.log
831
local7.none							{$log_directive}{$g['varlog_path']}/system.log
832
security.*							{$log_directive}{$g['varlog_path']}/system.log
833
auth.info;authpriv.info;daemon.info				{$log_directive}{$g['varlog_path']}/system.log
834
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
835
*.emerg								*
836

    
837
EOD;
838
		if (isset($syslogcfg['vpn']))
839
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
840
		if (isset($syslogcfg['portalauth']))
841
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
842
		if (isset($syslogcfg['dhcp']))
843
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
844
		if (isset($syslogcfg['system'])) {
845
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.notice;kern.debug;lpr.info;mail.crit;");
846
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "news.err;local0.none;local3.none;local7.none");
847
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "security.*");
848
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "auth.info;authpriv.info;daemon.info");
849
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.emerg");
850
		}
851
		if (isset($syslogcfg['logall'])) {
852
			// Make everything mean everything, including facilities excluded above.
853
			$syslogconf .= "!*\n";
854
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
855
		}
856

    
857
		if (isset($syslogcfg['zmqserver'])) {
858
				$syslogconf .= <<<EOD
859
*.*								^{$syslogcfg['zmqserver']}
860

    
861
EOD;
862
		}
863
		/* write syslog.conf */		
864
		if (!@file_put_contents("{$g['varetc_path']}/syslog.conf", $syslogconf)) {
865
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
866
			unset($syslogconf);
867
			return 1;
868
		}
869
		unset($syslogconf);
870

    
871
		// Ensure that the log directory exists
872
		if (!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
873
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
874

    
875
		$sourceip = "";
876
		if (!empty($syslogcfg['sourceip'])) {
877
			if ($syslogcfg['ipproto'] == "ipv6") {
878
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
879
				if (!is_ipaddr($ifaddr))
880
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
881
			} else {
882
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
883
				if (!is_ipaddr($ifaddr))
884
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
885
			}
886
			if (is_ipaddr($ifaddr)) {
887
				$sourceip = "-b {$ifaddr}";
888
			}
889
		}
890

    
891
		$syslogd_extra = "-f {$g['varetc_path']}/syslog.conf {$sourceip}";
892
	}
893

    
894
	if (isvalidpid("{$g['varrun_path']}/syslog.pid"))
895
		sigkillbypid("{$g['varrun_path']}/syslog.pid", "HUP");
896
	else
897
		$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}");
898

    
899
	if ($g['booting'])
900
		echo gettext("done.") . "\n";
901

    
902
	return $retval;
903
}
904

    
905
function system_webgui_create_certificate() {
906
	global $config, $g;
907

    
908
	if (!is_array($config['ca']))
909
		$config['ca'] = array();
910
	$a_ca =& $config['ca'];
911
	if (!is_array($config['cert']))
912
		$config['cert'] = array();
913
	$a_cert =& $config['cert'];
914
	log_error("Creating SSL Certificate for this host");
915

    
916
	$cert = array();
917
	$cert['refid'] = uniqid();
918
	$cert['descr'] = gettext("webConfigurator default ({$cert['refid']})");
919

    
920
	$dn = array(
921
		'countryName' => "US",
922
		'stateOrProvinceName' => "State",
923
		'localityName' => "Locality",
924
		'organizationName' => "{$g['product_name']} webConfigurator Self-Signed Certificate",
925
		'emailAddress' => "admin@{$config['system']['hostname']}.{$config['system']['domain']}",
926
		'commonName' => "{$config['system']['hostname']}-{$cert['refid']}");
927
	$old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warings directly to a page screwing menu tab */
928
	if (!cert_create($cert, null, 2048, 2000, $dn, "self-signed", "sha256")){
929
		while($ssl_err = openssl_error_string()){
930
			log_error("Error creating WebGUI Certificate: openssl library returns: " . $ssl_err);
931
		}
932
		error_reporting($old_err_level);
933
		return null;
934
	}
935
	error_reporting($old_err_level);
936

    
937
	$a_cert[] = $cert;
938
	$config['system']['webgui']['ssl-certref'] = $cert['refid'];
939
	write_config(gettext("Generated new self-signed HTTPS certificate ({$cert['refid']})"));
940
	return $cert;
941
}
942

    
943
function system_webgui_start() {
944
	global $config, $g;
945

    
946
	if ($g['booting'])
947
		echo gettext("Starting webConfigurator...");
948

    
949
	chdir($g['www_path']);
950

    
951
	/* defaults */
952
	$portarg = "80";
953
	$crt = "";
954
	$key = "";
955
	$ca = "";
956

    
957
	/* non-standard port? */
958
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
959
		$portarg = "{$config['system']['webgui']['port']}";
960

    
961
	if ($config['system']['webgui']['protocol'] == "https") {
962
		// Ensure that we have a webConfigurator CERT
963
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
964
		if(!is_array($cert) || !$cert['crt'] || !$cert['prv'])
965
			$cert = system_webgui_create_certificate();
966
		$crt = base64_decode($cert['crt']);
967
		$key = base64_decode($cert['prv']);
968

    
969
		if(!$config['system']['webgui']['port'])
970
			$portarg = "443";
971
		$ca  = ca_chain($cert);
972
	}
973

    
974
	/* generate lighttpd configuration */
975
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
976
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
977
		"cert.pem", "ca.pem");
978

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

    
982
	sleep(1);
983

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

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

    
989
	if ($g['booting']) {
990
		if ($res == 0)
991
			echo gettext("done.") . "\n";
992
		else
993
			echo gettext("failed!") . "\n";
994
	}
995

    
996
	return $res;
997
}
998

    
999
function system_generate_lighty_config($filename,
1000
	$cert,
1001
	$key,
1002
	$ca,
1003
	$pid_file,
1004
	$port = 80,
1005
	$document_root = "/usr/local/www/",
1006
	$cert_location = "cert.pem",
1007
	$ca_location = "ca.pem",
1008
	$captive_portal = false) {
1009

    
1010
	global $config, $g;
1011

    
1012
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
1013
		mkdir("{$g['tmp_path']}/lighttpdcompress");
1014

    
1015
	if(isset($config['system']['developerspew'])) {
1016
		$mt = microtime();
1017
		echo "system_generate_lighty_config() being called $mt\n";
1018
	}
1019

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

    
1024
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1025
		if (empty($maxprocperip))
1026
			$maxprocperip = 10;
1027
		$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
1028

    
1029
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
1030
		if(!is_dir("{$g['tmp_path']}/captiveportal"))
1031
			@mkdir("{$g['tmp_path']}/captiveportal", 0555);
1032
		$server_max_request_size = "server.max-request-size    = 384";
1033
		$cgi_config = "";
1034
	} else {
1035
		$captiveportal = ",\"mod_cgi\"";
1036
		$captive_portal_rewrite = "";
1037
		$captive_portal_mod_evasive = "";
1038
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
1039
		$server_max_request_size = "server.max-request-size    = 2097152";
1040
		$cgi_config = "cgi.assign                 = ( \".cgi\" => \"\" )";
1041
	}
1042
	
1043
	if (empty($port))
1044
		$lighty_port = "80";
1045
	else
1046
		$lighty_port = $port;
1047

    
1048
	$memory = get_memory();
1049
	$realmem = $memory[1];
1050

    
1051
	// Determine web GUI process settings and take into account low memory systems
1052
	if ($realmem < 255)
1053
		$max_procs = 1;
1054
	else
1055
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
1056

    
1057
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM 
1058
	if ($captive_portal !== false)  {
1059
		if ($realmem > 135 and $realmem < 256) {
1060
			$max_procs += 1; // 2 worker processes
1061
		} else if ($realmem > 255 and $realmem < 513) {
1062
			$max_procs += 2; // 3 worker processes
1063
		} else if ($realmem > 512) {
1064
			$max_procs += 4; // 6 worker processes
1065
		}
1066
		if ($max_procs > 1)
1067
			$max_php_children = intval($max_procs/2);
1068
		else
1069
			$max_php_children = 1;
1070

    
1071
	} else {
1072
		if ($realmem < 78)
1073
			$max_php_children = 0;
1074
		else
1075
			$max_php_children = 1;
1076
	}
1077

    
1078
	if(!isset($config['syslog']['nologlighttpd'])) {
1079
		$lighty_use_syslog = <<<EOD
1080
## where to send error-messages to
1081
server.errorlog-use-syslog="enable"
1082
EOD;
1083
	}
1084

    
1085

    
1086
	if ($captive_portal !== false) {
1087
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi-{$captive_portal}.socket";
1088
		$fastcgi_config = <<<EOD
1089
#### fastcgi module
1090
## read fastcgi.txt for more info
1091
fastcgi.server = ( ".php" =>
1092
	( "localhost" =>
1093
		(
1094
			"socket" => "{$fast_cgi_path}",
1095
			"max-procs" => {$max_procs},
1096
			"bin-environment" => (
1097
				"PHP_FCGI_CHILDREN" => "{$max_php_children}",
1098
				"PHP_FCGI_MAX_REQUESTS" => "500"
1099
			),
1100
			"bin-path" => "/usr/local/bin/php"
1101
		)
1102
	)
1103
)
1104

    
1105
EOD;
1106
	} else {
1107
		$fast_cgi_path = "{$g['varrun_path']}/php-fpm.socket";
1108
		$fastcgi_config = <<<EOD
1109
#### fastcgi module
1110
## read fastcgi.txt for more info
1111
fastcgi.server = ( ".php" =>
1112
	( "localhost" =>
1113
		(
1114
			"socket" => "{$fast_cgi_path}",
1115
			"broken-scriptfilename" => "enable"
1116
		)
1117
	)
1118
)
1119

    
1120
EOD;
1121
	}
1122

    
1123

    
1124
	$lighty_config = <<<EOD
1125
#
1126
# lighttpd configuration file
1127
#
1128
# use a it as base for lighttpd 1.0.0 and above
1129
#
1130
############ Options you really have to take care of ####################
1131

    
1132
## FreeBSD!
1133
server.event-handler	= "freebsd-kqueue"
1134
server.network-backend 	= "writev"
1135
#server.use-ipv6 = "enable"
1136

    
1137
## modules to load
1138
server.modules              =   ( "mod_access", "mod_expire", "mod_compress", "mod_redirect",
1139
	{$captiveportal}, "mod_fastcgi"
1140
)
1141

    
1142
server.max-keep-alive-requests = 15
1143
server.max-keep-alive-idle = 30
1144

    
1145
## a static document-root, for virtual-hosting take look at the
1146
## server.virtual-* options
1147
server.document-root        = "{$document_root}"
1148
{$captive_portal_rewrite}
1149

    
1150
# Maximum idle time with nothing being written (php downloading)
1151
server.max-write-idle = 999
1152

    
1153
{$lighty_use_syslog}
1154

    
1155
# files to check for if .../ is requested
1156
server.indexfiles           = ( "index.php", "index.html",
1157
                                "index.htm", "default.htm" )
1158

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

    
1212
# Use the "Content-Type" extended attribute to obtain mime type if possible
1213
#mimetypes.use-xattr        = "enable"
1214

    
1215
## deny access the file-extensions
1216
#
1217
# ~    is for backupfiles from vi, emacs, joe, ...
1218
# .inc is often used for code includes which should in general not be part
1219
#      of the document-root
1220
url.access-deny             = ( "~", ".inc" )
1221

    
1222

    
1223
######### Options that are good to be but not neccesary to be changed #######
1224

    
1225
## bind to port (default: 80)
1226

    
1227
EOD;
1228

    
1229
	$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1230
	$lighty_config .= "server.port  = {$lighty_port}\n";
1231
	$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1232
	$lighty_config .= "\$SERVER[\"socket\"]  == \"[::]:{$lighty_port}\" { \n";
1233
	if($cert <> "" and $key <> "") {
1234
		$lighty_config .= "\n";
1235
		$lighty_config .= "## ssl configuration\n";
1236
		$lighty_config .= "ssl.engine = \"enable\"\n";
1237
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1238
		if($ca <> "")
1239
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1240
	}
1241
	$lighty_config .= " }\n";
1242

    
1243

    
1244
	$lighty_config .= <<<EOD
1245

    
1246
## error-handler for status 404
1247
#server.error-handler-404   = "/error-handler.html"
1248
#server.error-handler-404   = "/error-handler.php"
1249

    
1250
## to help the rc.scripts
1251
server.pid-file            = "{$g['varrun_path']}/{$pid_file}"
1252

    
1253
## virtual directory listings
1254
server.dir-listing         = "disable"
1255

    
1256
## enable debugging
1257
debug.log-request-header   = "disable"
1258
debug.log-response-header  = "disable"
1259
debug.log-request-handling = "disable"
1260
debug.log-file-not-found   = "disable"
1261

    
1262
# gzip compression
1263
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1264
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1265

    
1266
{$server_upload_dirs}
1267

    
1268
{$server_max_request_size}
1269

    
1270
{$fastcgi_config}
1271

    
1272
{$cgi_config}
1273

    
1274
{$captive_portal_mod_evasive}
1275

    
1276
expire.url = (
1277
				"" => "access 50 hours",	
1278
        )
1279

    
1280
EOD;
1281

    
1282
	$cert = str_replace("\r", "", $cert);
1283
	$key = str_replace("\r", "", $key);
1284
	$ca = str_replace("\r", "", $ca);
1285

    
1286
	$cert = str_replace("\n\n", "\n", $cert);
1287
	$key = str_replace("\n\n", "\n", $key);
1288
	$ca = str_replace("\n\n", "\n", $ca);
1289

    
1290
	if($cert <> "" and $key <> "") {
1291
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1292
		if (!$fd) {
1293
			printf(gettext("Error: cannot open cert.pem in system_webgui_start().%s"), "\n");
1294
			return 1;
1295
		}
1296
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1297
		fwrite($fd, $cert);
1298
		fwrite($fd, "\n");
1299
		fwrite($fd, $key);
1300
		fclose($fd);
1301
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
1302
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1303
			if (!$fd) {
1304
				printf(gettext("Error: cannot open ca.pem in system_webgui_start().%s"), "\n");
1305
				return 1;
1306
			}
1307
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1308
			fwrite($fd, $ca);
1309
			fclose($fd);
1310
		}
1311
		$lighty_config .= "\n";
1312
		$lighty_config .= "## " . gettext("ssl configuration") . "\n";
1313
		$lighty_config .= "ssl.engine = \"enable\"\n";
1314
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1315

    
1316
		// SSLv2/3 is deprecated, force use of TLS
1317
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
1318
		$lighty_config .= "ssl.use-sslv3 = \"disable\"\n";
1319

    
1320
		/* Hifn accelerators do NOT work with the BEAST mitigation code. Do not allow it to be enabled if a Hifn card has been detected. */
1321
		$fd = @fopen("{$g['varlog_path']}/dmesg.boot", "r");
1322
		if ($fd) {
1323
			while (!feof($fd)) {
1324
				$dmesgl = fgets($fd);
1325
				if (preg_match("/^hifn.: (.*?),/", $dmesgl, $matches) && isset($config['system']['webgui']['beast_protection'])) {
1326
						unset($config['system']['webgui']['beast_protection']);
1327
						log_error("BEAST Protection disabled because a conflicting cryptographic accelerator card has been detected (" . $matches[1] . ")");
1328
					break;
1329
				}
1330
			}
1331
			fclose($fd);
1332
		}
1333

    
1334
		if (isset($config['system']['webgui']['beast_protection'])) {
1335
			$lighty_config .= "ssl.honor-cipher-order = \"enable\"\n";
1336
			$lighty_config .= "ssl.cipher-list = \"ECDHE-RSA-AES256-SHA384:AES256-SHA256:RC4-SHA:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM\"\n";
1337
		} else {
1338
			$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";
1339
		}
1340

    
1341
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1342
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1343
	}
1344

    
1345
	// Add HTTP to HTTPS redirect	
1346
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1347
		if($lighty_port != "443") 
1348
			$redirectport = ":{$lighty_port}";
1349
		$lighty_config .= <<<EOD
1350
\$SERVER["socket"] == ":80" {
1351
	\$HTTP["host"] =~ "(.*)" {
1352
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1353
	}
1354
}
1355
\$SERVER["socket"] == "[::]:80" {
1356
	\$HTTP["host"] =~ "(.*)" {
1357
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1358
	}
1359
}
1360
EOD;
1361
	}
1362

    
1363
	$fd = fopen("{$filename}", "w");
1364
	if (!$fd) {
1365
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1366
		return 1;
1367
	}
1368
	fwrite($fd, $lighty_config);
1369
	fclose($fd);
1370

    
1371
	return 0;
1372

    
1373
}
1374

    
1375
function system_timezone_configure() {
1376
	global $config, $g;
1377
	if(isset($config['system']['developerspew'])) {
1378
		$mt = microtime();
1379
		echo "system_timezone_configure() being called $mt\n";
1380
	}
1381

    
1382
	$syscfg = $config['system'];
1383

    
1384
	if ($g['booting'])
1385
		echo gettext("Setting timezone...");
1386

    
1387
	/* extract appropriate timezone file */
1388
	$timezone = $syscfg['timezone'];
1389
	if ($timezone) {
1390
		exec('/usr/bin/tar -tvzf /usr/share/zoneinfo.tgz', $tzs);
1391
		foreach ($tzs as $tz) {
1392
			if (preg_match(",{$timezone}$,", $tz))
1393
				break;
1394
			if (preg_match(",{$timezone} link to *(.*)$,", $tz, $matches)) {
1395
				$timezone = $matches[1];
1396
				break;
1397
			}
1398
		}
1399
	} else
1400
		$timezone = "Etc/UTC";
1401

    
1402
	conf_mount_rw();
1403

    
1404
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1405
		escapeshellarg($timezone) . " > /etc/localtime");
1406

    
1407
	mwexec("sync");
1408
	conf_mount_ro();
1409

    
1410
	if ($g['booting'])
1411
		echo gettext("done.") . "\n";
1412
}
1413

    
1414
function system_ntp_setup_gps($serialport) {
1415
	global $config, $g;
1416
	$gps_device = '/dev/gps0';
1417
	$serialport = '/dev/'.$serialport;
1418

    
1419
	if (!file_exists($serialport))
1420
		return false;
1421

    
1422
	conf_mount_rw();
1423
	// Create symlink that ntpd requires
1424
	unlink_if_exists($gps_device);
1425
	symlink($serialport, $gps_device);
1426

    
1427
	/* Send the following to the GPS port to initialize the GPS */
1428
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
1429
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
1430
	}else{
1431
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1432
	}
1433

    
1434
	/* XXX: Why not file_put_contents to the device */
1435
	@file_put_contents('/tmp/gps.init', $gps_init);
1436
	`cat /tmp/gps.init > $serialport`;
1437

    
1438
	/* Add /etc/remote entry in case we need to read from the GPS with tip */
1439
	if (intval(`grep -c '^gps0' /etc/remote`) == 0) {
1440
		$gpsbaud = '4800';
1441
		if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['speed'])) {
1442
			switch($config['ntpd']['gps']['speed']) {
1443
				case '16':
1444
					$gpsbaud = '9600';
1445
					break;
1446
				case '32':
1447
					$gpsbaud = '19200';
1448
					break;
1449
				case '48':
1450
					$gpsbaud = '38400';
1451
					break;
1452
				case '64':
1453
					$gpsbaud = '57600';
1454
					break;
1455
				case '80':
1456
					$gpsbaud = '115200';
1457
					break;
1458
			}
1459
		}
1460
		@file_put_contents("/etc/remote", "gps0:dv={$serialport}:br#{$gpsbaud}:pa=none:", FILE_APPEND);
1461
	}
1462

    
1463
	conf_mount_ro();
1464

    
1465
	return true;
1466
}
1467

    
1468
function system_ntp_setup_pps($serialport) {
1469
	global $config, $g;
1470

    
1471
	$pps_device = '/dev/pps0';
1472
	$serialport = '/dev/'.$serialport;
1473

    
1474
	if (!file_exists($serialport))
1475
		return false;
1476

    
1477
	conf_mount_rw();
1478
	// Create symlink that ntpd requires
1479
	unlink_if_exists($pps_device);
1480
	@symlink($serialport, $pps_device);
1481

    
1482
	conf_mount_ro();
1483

    
1484
	return true;
1485
}
1486

    
1487

    
1488
function system_ntp_configure($start_ntpd=true) {
1489
	global $config, $g;
1490

    
1491
	$driftfile = "/var/db/ntpd.drift";
1492
	$statsdir = "/var/log/ntp";
1493
	$gps_device = '/dev/gps0';
1494

    
1495
	if ($g['platform'] == 'jail')
1496
		return;
1497

    
1498
	safe_mkdir($statsdir);
1499

    
1500
	if (!is_array($config['ntpd']))
1501
		$config['ntpd'] = array();
1502

    
1503
	$ntpcfg = "# \n";
1504
	$ntpcfg .= "# pfSense ntp configuration file \n";
1505
	$ntpcfg .= "# \n\n";
1506
	$ntpcfg .= "tinker panic 0 \n";
1507

    
1508
	/* Add Orphan mode */
1509
	$ntpcfg .= "# Orphan mode stratum\n";
1510
	$ntpcfg .= 'tos orphan ';
1511
	if (!empty($config['ntpd']['orphan'])) {
1512
		$ntpcfg .= $config['ntpd']['orphan'];
1513
	}else{
1514
		$ntpcfg .= '12';
1515
	}
1516
	$ntpcfg .= "\n";
1517

    
1518
	/* Add PPS configuration */
1519
	if (!empty($config['ntpd']['pps'])
1520
		&& file_exists('/dev/'.$config['ntpd']['pps']['port'])
1521
		&& system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
1522
		$ntpcfg .= "\n";
1523
		$ntpcfg .= "# PPS Setup\n";
1524
		$ntpcfg .= 'server 127.127.22.0';
1525
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1526
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
1527
			$ntpcfg .= ' prefer'; 
1528
		}
1529
		if (!empty($config['ntpd']['pps']['noselect'])) {
1530
			$ntpcfg .= ' noselect ';
1531
		}
1532
		$ntpcfg .= "\n";
1533
		$ntpcfg .= 'fudge 127.127.22.0';
1534
		if (!empty($config['ntpd']['pps']['fudge1'])) {
1535
			$ntpcfg .= ' time1 ';
1536
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
1537
		}
1538
		if (!empty($config['ntpd']['pps']['flag2'])) {
1539
			$ntpcfg .= ' flag2 1';
1540
		}
1541
		if (!empty($config['ntpd']['pps']['flag3'])) {
1542
			$ntpcfg .= ' flag3 1';
1543
		}else{
1544
			$ntpcfg .= ' flag3 0';
1545
		}
1546
		if (!empty($config['ntpd']['pps']['flag4'])) {
1547
			$ntpcfg .= ' flag4 1';
1548
		}
1549
		if (!empty($config['ntpd']['pps']['refid'])) {
1550
			$ntpcfg .= ' refid ';
1551
			$ntpcfg .= $config['ntpd']['pps']['refid'];
1552
		}
1553
		$ntpcfg .= "\n";
1554
	}
1555
	/* End PPS configuration */
1556

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

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

    
1706
	/* A leapseconds file is really only useful if this clock is stratum 1 */
1707
	$ntpcfg .= "\n";
1708
	if (!empty($config['ntpd']['leapsec'])) {
1709
		$leapsec .= base64_decode($config['ntpd']['leapsec']);
1710
		file_put_contents('/var/db/leap-seconds', $leapsec);
1711
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
1712
	}
1713
	
1714

    
1715
	if (empty($config['ntpd']['interface']))
1716
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface']))
1717
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1718
		else
1719
			$interfaces = array();
1720
	else
1721
		$interfaces = explode(",", $config['ntpd']['interface']);
1722

    
1723
	if (is_array($interfaces) && count($interfaces)) {
1724
		$ntpcfg .= "interface ignore all\n";
1725
		foreach ($interfaces as $interface) {
1726
			if (!is_ipaddr($interface)) {
1727
				$interface = get_real_interface($interface);
1728
			}
1729
			if (!empty($interface))
1730
				$ntpcfg .= "interface listen {$interface}\n";
1731
		}
1732
	}
1733

    
1734
	/* open configuration for wrting or bail */
1735
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
1736
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1737
		return;
1738
	}
1739

    
1740
	/* At bootup we just want to write out the config. */
1741
	if (!$start_ntpd)
1742
		return;
1743

    
1744
	/* if ntpd is running, kill it */
1745
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1746
		killbypid("{$g['varrun_path']}/ntpd.pid");
1747
	}
1748
	@unlink("{$g['varrun_path']}/ntpd.pid");
1749

    
1750
	/* if /var/empty does not exist, create it */
1751
	if(!is_dir("/var/empty"))
1752
		mkdir("/var/empty", 0775, true);
1753

    
1754
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1755
	mwexec("/usr/local/sbin/ntpd -g -c {$g['varetc_path']}/ntpd.conf -p {$g['varrun_path']}/ntpd.pid", false, true);
1756
	
1757
	// Note that we are starting up
1758
	log_error("NTPD is starting up.");
1759
	return;
1760
}
1761

    
1762
function sync_system_time() {
1763
	global $config, $g;
1764

    
1765
	if ($g['booting'])
1766
		echo gettext("Syncing system time before startup...");
1767

    
1768
	/* foreach through servers and write out to ntpd.conf */
1769
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1770
		mwexec("/usr/local/sbin/ntpdate -s $ts");
1771
	}
1772
	
1773
	if ($g['booting'])
1774
		echo gettext("done.") . "\n";
1775
	
1776
}
1777

    
1778
function system_halt() {
1779
	global $g;
1780

    
1781
	system_reboot_cleanup();
1782

    
1783
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1784
}
1785

    
1786
function system_reboot() {
1787
	global $g;
1788

    
1789
	system_reboot_cleanup();
1790

    
1791
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1792
}
1793

    
1794
function system_reboot_sync() {
1795
	global $g;
1796

    
1797
	system_reboot_cleanup();
1798

    
1799
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1800
}
1801

    
1802
function system_reboot_cleanup() {
1803
	global $config, $cpzone;
1804

    
1805
	mwexec("/usr/local/bin/beep.sh stop");
1806
	require_once("captiveportal.inc");
1807
	if (is_array($config['captiveportal'])) {
1808
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
1809
			captiveportal_radius_stop_all();
1810
			captiveportal_send_server_accounting(true);
1811
		}
1812
	}
1813
	require_once("voucher.inc");
1814
	voucher_save_db_to_config();
1815
	require_once("pkg-utils.inc");
1816
	stop_packages();
1817
}
1818

    
1819
function system_do_shell_commands($early = 0) {
1820
	global $config, $g;
1821
	if(isset($config['system']['developerspew'])) {
1822
		$mt = microtime();
1823
		echo "system_do_shell_commands() being called $mt\n";
1824
	}
1825

    
1826
	if ($early)
1827
		$cmdn = "earlyshellcmd";
1828
	else
1829
		$cmdn = "shellcmd";
1830

    
1831
	if (is_array($config['system'][$cmdn])) {
1832

    
1833
		/* *cmd is an array, loop through */
1834
		foreach ($config['system'][$cmdn] as $cmd) {
1835
			exec($cmd);
1836
		}
1837

    
1838
	} elseif($config['system'][$cmdn] <> "") {
1839

    
1840
		/* execute single item */
1841
		exec($config['system'][$cmdn]);
1842

    
1843
	}
1844
}
1845

    
1846
function system_console_configure() {
1847
	global $config, $g;
1848
	if(isset($config['system']['developerspew'])) {
1849
		$mt = microtime();
1850
		echo "system_console_configure() being called $mt\n";
1851
	}
1852

    
1853
	if (isset($config['system']['disableconsolemenu'])) {
1854
		touch("{$g['varetc_path']}/disableconsole");
1855
	} else {
1856
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1857
	}
1858
}
1859

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

    
1867
	$dmesg = "";
1868
	$_gb = exec("/sbin/dmesg", $dmesg);
1869

    
1870
	/* find last copyright line (output from previous boots may be present) */
1871
	$lastcpline = 0;
1872

    
1873
	for ($i = 0; $i < count($dmesg); $i++) {
1874
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1875
			$lastcpline = $i;
1876
	}
1877

    
1878
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1879
	if (!$fd) {
1880
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1881
		return 1;
1882
	}
1883

    
1884
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1885
		fwrite($fd, $dmesg[$i] . "\n");
1886

    
1887
	fclose($fd);
1888
	unset($dmesg);
1889

    
1890
	return 0;
1891
}
1892

    
1893
function system_set_harddisk_standby() {
1894
	global $g, $config;
1895
	if(isset($config['system']['developerspew'])) {
1896
		$mt = microtime();
1897
		echo "system_set_harddisk_standby() being called $mt\n";
1898
	}
1899

    
1900
	if (isset($config['system']['harddiskstandby'])) {
1901
		if ($g['booting']) {
1902
			echo gettext('Setting hard disk standby... ');
1903
		}
1904

    
1905
		$standby = $config['system']['harddiskstandby'];
1906
		// Check for a numeric value
1907
		if (is_numeric($standby)) {
1908
			// Sync the disk(s)
1909
			pfSense_sync();
1910
			if (set_single_sysctl('hw.ata.standby', (int)$standby)) {
1911
				// Reinitialize ATA-drives
1912
				mwexec('/usr/local/sbin/atareinit');
1913
				if ($g['booting']) {
1914
					echo gettext("done.") . "\n";
1915
				}
1916
			} else if ($g['booting']) {
1917
				echo gettext("failed!") . "\n";
1918
			}
1919
		} else if ($g['booting']) {
1920
			echo gettext("failed!") . "\n";
1921
		}
1922
	}
1923
}
1924

    
1925
function system_setup_sysctl() {
1926
	global $config;
1927
	if(isset($config['system']['developerspew'])) {
1928
		$mt = microtime();
1929
		echo "system_setup_sysctl() being called $mt\n";
1930
	}
1931

    
1932
	activate_sysctls();	
1933

    
1934
	if (isset($config['system']['sharednet'])) {
1935
		system_disable_arp_wrong_if();
1936
	}
1937
}
1938

    
1939
function system_disable_arp_wrong_if() {
1940
	global $config;
1941
	if(isset($config['system']['developerspew'])) {
1942
		$mt = microtime();
1943
		echo "system_disable_arp_wrong_if() being called $mt\n";
1944
	}
1945
	set_sysctl(array(
1946
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
1947
		"net.link.ether.inet.log_arp_movements" => "0"
1948
	));
1949
}
1950

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

    
1963
function enable_watchdog() {
1964
	global $config;
1965
	return;
1966
	$install_watchdog = false;
1967
	$supported_watchdogs = array("Geode");
1968
	$file = file_get_contents("/var/log/dmesg.boot");
1969
	foreach($supported_watchdogs as $sd) {
1970
		if(stristr($file, "Geode")) {
1971
			$install_watchdog = true;
1972
		}
1973
	}
1974
	if($install_watchdog == true) {
1975
		if(is_process_running("watchdogd"))
1976
			mwexec("/usr/bin/killall watchdogd", true);
1977
		exec("/usr/sbin/watchdogd");
1978
	}
1979
}
1980

    
1981
function system_check_reset_button() {
1982
	global $g;
1983
	if($g['platform'] != "nanobsd")
1984
		return 0;
1985

    
1986
	$specplatform = system_identify_specific_platform();
1987

    
1988
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1989
		return 0;
1990

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

    
1993
	if ($retval == 99) {
1994
		/* user has pressed reset button for 2 seconds - 
1995
		   reset to factory defaults */
1996
		echo <<<EOD
1997

    
1998
***********************************************************************
1999
* Reset button pressed - resetting configuration to factory defaults. *
2000
* The system will reboot after this completes.                        *
2001
***********************************************************************
2002

    
2003

    
2004
EOD;
2005
		
2006
		reset_factory_defaults();
2007
		system_reboot_sync();
2008
		exit(0);
2009
	}
2010

    
2011
	return 0;
2012
}
2013

    
2014
/* attempt to identify the specific platform (for embedded systems)
2015
   Returns an array with two elements:
2016
	name => platform string (e.g. 'wrap', 'alix' etc.)
2017
	descr => human-readable description (e.g. "PC Engines WRAP")
2018
*/
2019
function system_identify_specific_platform() {
2020
	global $g;
2021
	
2022
	if ($g['platform'] == 'generic-pc')
2023
		return array('name' => 'generic-pc', 'descr' => gettext("Generic PC"));
2024
	
2025
	if ($g['platform'] == 'generic-pc-cdrom')
2026
		return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)"));
2027
	
2028
	/* the rest of the code only deals with 'embedded' platforms */
2029
	if ($g['platform'] != 'nanobsd')
2030
		return array('name' => $g['platform'], 'descr' => $g['platform']);
2031

    
2032
	$dmesg = get_single_sysctl('hw.model');
2033

    
2034
	if (strpos($dmesg, "PC Engines WRAP") !== false)
2035
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
2036
	
2037
	if (strpos($dmesg, "PC Engines ALIX") !== false)
2038
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2039

    
2040
	if (preg_match("/Soekris net45../", $dmesg, $matches))
2041
		return array('name' => 'net45xx', 'descr' => $matches[0]);
2042
	
2043
	if (preg_match("/Soekris net48../", $dmesg, $matches))
2044
		return array('name' => 'net48xx', 'descr' => $matches[0]);
2045
		
2046
	if (preg_match("/Soekris net55../", $dmesg, $matches))
2047
		return array('name' => 'net55xx', 'descr' => $matches[0]);
2048
	
2049
	/* unknown embedded platform */
2050
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
2051
}
2052

    
2053
function system_get_dmesg_boot() {
2054
	global $g;
2055
		
2056
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2057
}
2058

    
2059
function get_possible_listen_ips($include_ipv6_link_local=false) {
2060
	$interfaces = get_configured_interface_with_descr();
2061
	$carplist = get_configured_carp_interface_list();
2062
	$listenips = array();
2063
	foreach ($carplist as $cif => $carpip)
2064
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
2065
	$aliaslist = get_configured_ip_aliases_list();
2066
	foreach ($aliaslist as $aliasip => $aliasif)
2067
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
2068
	foreach ($interfaces as $iface => $ifacename) {
2069
		$tmp["name"]  = $ifacename;
2070
		$tmp["value"] = $iface;
2071
		$listenips[] = $tmp;
2072
		if ($include_ipv6_link_local) {
2073
			$llip = find_interface_ipv6_ll(get_real_interface($iface));
2074
			if (!empty($llip)) {
2075
				$tmp["name"]  = "{$ifacename} IPv6 Link-Local";
2076
				$tmp["value"] = $llip;
2077
				$listenips[] = $tmp;
2078
			}
2079
		}
2080
	}
2081
	$tmp["name"]  = "Localhost";
2082
	$tmp["value"] = "lo0";
2083
	$listenips[] = $tmp;
2084
	return $listenips;
2085
}
2086

    
2087
function get_possible_traffic_source_addresses($include_ipv6_link_local=false) {
2088
	global $config;
2089
	$sourceips = get_possible_listen_ips($include_ipv6_link_local);
2090
	foreach (array('server', 'client') as $mode) {
2091
		if (is_array($config['openvpn']["openvpn-{$mode}"])) {
2092
			foreach ($config['openvpn']["openvpn-{$mode}"] as $id => $setting) {
2093
				if (!isset($setting['disable'])) {
2094
					$vpn = array();
2095
					$vpn['value'] = 'ovpn' . substr($mode, 0, 1) . $setting['vpnid'];
2096
					$vpn['name'] = gettext("OpenVPN") . " ".$mode.": ".htmlspecialchars($setting['description']);
2097
					$sourceips[] = $vpn;
2098
				}
2099
			}
2100
		}
2101
	}
2102
	return $sourceips;
2103
}
2104
?>
(53-53/68)