Project

General

Profile

Download (66.1 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
	} else {
311
		$sysiflist = get_configured_interface_list();
312
		foreach ($sysiflist as $sysif) {
313
			if (!interface_has_gateway($sysif)) {
314
				$cfgip = get_interface_ip($sysif);
315
				if (is_ipaddr($cfgip)) {
316
					$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
317
					break;
318
				}
319
			}
320
		}
321
	}
322

    
323
	if (isset($dnsmasqcfg['enable'])) {
324
		if (!is_array($dnsmasqcfg['hosts']))
325
			$dnsmasqcfg['hosts'] = array();
326

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

    
364
		if (isset($dnsmasqcfg['dhcpfirst']))
365
			$hosts .= $dhosts . $lhosts;
366
		else
367
			$hosts .= $lhosts . $dhosts;
368
	}
369

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

    
386
	if (isset($config['unbound']['enable'])) {
387
		require_once("unbound.inc");
388
		unbound_hosts_generate();
389
	}
390

    
391
	return 0;
392
}
393

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

    
407
		if (isset($config['unbound']['enable'])) {
408
			$dns_pid = "unbound.pid";
409
			$unbound_conf = "-u {$g['unbound_chroot_path']}/dhcpleases_entries.conf";
410
		} else {
411
			$dns_pid = "dnsmasq.pid";
412
			$unbound_conf = "";
413
		}
414

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

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

    
437
function system_hostname_configure() {
438
	global $config, $g;
439
	if(isset($config['system']['developerspew'])) {
440
		$mt = microtime();
441
		echo "system_hostname_configure() being called $mt\n";
442
	}
443

    
444
	$syscfg = $config['system'];
445

    
446
	/* set hostname */
447
	$status = mwexec("/bin/hostname " .
448
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
449

    
450
    /* Setup host GUID ID.  This is used by ZFS. */
451
	mwexec("/etc/rc.d/hostid start");
452

    
453
	return $status;
454
}
455

    
456
function system_routing_configure($interface = "") {
457
	global $config, $g;
458
	if ($g['platform'] == 'jail')
459
		return;
460
	if(isset($config['system']['developerspew'])) {
461
		$mt = microtime();
462
		echo "system_routing_configure() being called $mt\n";
463
	}
464

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

    
530
	if ($dont_add_route == false ) {
531
		if (!empty($interface) && $interface != $interfacegw)
532
			;
533
		else if (is_ipaddrv4($gatewayip)) {
534
			log_error("ROUTING: setting default route to $gatewayip");
535
			mwexec("/sbin/route change -inet default " . escapeshellarg($gatewayip));
536
		}
537

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

    
549
	system_staticroutes_configure($interface, false);
550

    
551
	return 0;
552
}
553

    
554
function system_staticroutes_configure($interface = "", $update_dns = false) {
555
	global $config, $g, $aliastable;
556

    
557
	$filterdns_list = array();
558

    
559
	$static_routes = get_staticroutes(false, true);
560
	if (count($static_routes)) {
561
		$gateways_arr = return_gateways_array(false, true);
562

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

    
572
			$gatewayip = $gateway['gateway'];
573
			$interfacegw = $gateway['interface'];
574

    
575
			$blackhole = "";
576
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 3)))
577
				$blackhole = "-blackhole";
578

    
579
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network']))
580
				continue;
581

    
582
			$dnscache = array();
583
			if ($update_dns === true) {
584
				if (is_subnet($rtent['network']))
585
					continue;
586
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
587
				if (empty($dnscache))
588
					continue;
589
			}
590

    
591
			if (is_subnet($rtent['network']))
592
				$ips = array($rtent['network']);
593
			else {
594
				if (!isset($rtent['disabled']))
595
					$filterdns_list[] = $rtent['network'];
596
				$ips = add_hostname_to_watch($rtent['network']);
597
			}
598

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

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

    
621
			foreach ($ips as $ip) {
622
				if (is_ipaddrv4($ip))
623
					$ip .= "/32";
624
				// do NOT do the same check here on v6, is_ipaddrv6 returns true when including the CIDR mask. doing so breaks v6 routes
625
					
626
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
627

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

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

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

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

    
671
	return 0;
672
}
673

    
674
function system_routing_enable() {
675
	global $config, $g;
676
	if(isset($config['system']['developerspew'])) {
677
		$mt = microtime();
678
		echo "system_routing_enable() being called $mt\n";
679
	}
680

    
681
	set_sysctl(array(
682
		"net.inet.ip.forwarding" => "1",
683
		"net.inet6.ip6.forwarding" => "1"
684
	));
685

    
686
	return;
687
}
688

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

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

    
712
function system_syslogd_start() {
713
	global $config, $g;
714
	if(isset($config['system']['developerspew'])) {
715
		$mt = microtime();
716
		echo "system_syslogd_start() being called $mt\n";
717
	}
718

    
719
	mwexec("/etc/rc.d/hostid start");
720

    
721
	$syslogcfg = $config['syslog'];
722

    
723
	if (platform_booting())
724
		echo gettext("Starting syslog...");
725

    
726
	if (is_process_running("fifolog_writer"))
727
		mwexec('/bin/pkill fifolog_writer');
728

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

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

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

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

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

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

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

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

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

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

    
800
		$syslogconf .= "!dnsmasq,filterdns,unbound\n";
801
		if (!isset($syslogcfg['disablelocallogging']))
802
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
803

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

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

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

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

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

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

    
861
		if (isset($syslogcfg['zmqserver'])) {
862
				$syslogconf .= <<<EOD
863
*.*								^{$syslogcfg['zmqserver']}
864

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

    
875
		// Ensure that the log directory exists
876
		if (!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
877
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
878

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

    
895
		$syslogd_extra = "-f {$g['varetc_path']}/syslog.conf {$sourceip}";
896
	}
897

    
898
	if (isvalidpid("{$g['varrun_path']}/syslog.pid"))
899
		sigkillbypid("{$g['varrun_path']}/syslog.pid", "TERM");
900
	
901
	$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}");
902

    
903
	if (platform_booting())
904
		echo gettext("done.") . "\n";
905

    
906
	return $retval;
907
}
908

    
909
function system_webgui_create_certificate() {
910
	global $config, $g;
911

    
912
	if (!is_array($config['ca']))
913
		$config['ca'] = array();
914
	$a_ca =& $config['ca'];
915
	if (!is_array($config['cert']))
916
		$config['cert'] = array();
917
	$a_cert =& $config['cert'];
918
	log_error("Creating SSL Certificate for this host");
919

    
920
	$cert = array();
921
	$cert['refid'] = uniqid();
922
	$cert['descr'] = gettext("webConfigurator default ({$cert['refid']})");
923

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

    
941
	$a_cert[] = $cert;
942
	$config['system']['webgui']['ssl-certref'] = $cert['refid'];
943
	write_config(gettext("Generated new self-signed HTTPS certificate ({$cert['refid']})"));
944
	return $cert;
945
}
946

    
947
function system_webgui_start() {
948
	global $config, $g;
949

    
950
	if (platform_booting())
951
		echo gettext("Starting webConfigurator...");
952

    
953
	chdir($g['www_path']);
954

    
955
	/* defaults */
956
	$portarg = "80";
957
	$crt = "";
958
	$key = "";
959
	$ca = "";
960

    
961
	/* non-standard port? */
962
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
963
		$portarg = "{$config['system']['webgui']['port']}";
964

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

    
973
		if(!$config['system']['webgui']['port'])
974
			$portarg = "443";
975
		$ca  = ca_chain($cert);
976
	}
977

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

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

    
986
	sleep(1);
987

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

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

    
993
	if (platform_booting()) {
994
		if ($res == 0)
995
			echo gettext("done.") . "\n";
996
		else
997
			echo gettext("failed!") . "\n";
998
	}
999

    
1000
	return $res;
1001
}
1002

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

    
1014
	global $config, $g;
1015

    
1016
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
1017
		mkdir("{$g['tmp_path']}/lighttpdcompress");
1018

    
1019
	if(isset($config['system']['developerspew'])) {
1020
		$mt = microtime();
1021
		echo "system_generate_lighty_config() being called $mt\n";
1022
	}
1023

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

    
1028
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1029
		if (empty($maxprocperip))
1030
			$maxprocperip = 10;
1031
		$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
1032

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

    
1052
	$memory = get_memory();
1053
	$realmem = $memory[1];
1054

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

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

    
1075
	} else {
1076
		if ($realmem < 78)
1077
			$max_php_children = 0;
1078
		else
1079
			$max_php_children = 1;
1080
	}
1081

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

    
1089

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

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

    
1124
EOD;
1125
	}
1126

    
1127

    
1128
	$lighty_config = <<<EOD
1129
#
1130
# lighttpd configuration file
1131
#
1132
# use a it as base for lighttpd 1.0.0 and above
1133
#
1134
############ Options you really have to take care of ####################
1135

    
1136
## FreeBSD!
1137
server.event-handler	= "freebsd-kqueue"
1138
server.network-backend 	= "writev"
1139
#server.use-ipv6 = "enable"
1140

    
1141
## modules to load
1142
server.modules              =   ( "mod_access", "mod_expire", "mod_compress", "mod_redirect",
1143
	{$captiveportal}, "mod_fastcgi"
1144
)
1145

    
1146
server.max-keep-alive-requests = 15
1147
server.max-keep-alive-idle = 30
1148

    
1149
## a static document-root, for virtual-hosting take look at the
1150
## server.virtual-* options
1151
server.document-root        = "{$document_root}"
1152
{$captive_portal_rewrite}
1153

    
1154
# Maximum idle time with nothing being written (php downloading)
1155
server.max-write-idle = 999
1156

    
1157
{$lighty_use_syslog}
1158

    
1159
# files to check for if .../ is requested
1160
server.indexfiles           = ( "index.php", "index.html",
1161
                                "index.htm", "default.htm" )
1162

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

    
1216
# Use the "Content-Type" extended attribute to obtain mime type if possible
1217
#mimetypes.use-xattr        = "enable"
1218

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

    
1226

    
1227
######### Options that are good to be but not neccesary to be changed #######
1228

    
1229
## bind to port (default: 80)
1230

    
1231
EOD;
1232

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

    
1247

    
1248
	$lighty_config .= <<<EOD
1249

    
1250
## error-handler for status 404
1251
#server.error-handler-404   = "/error-handler.html"
1252
#server.error-handler-404   = "/error-handler.php"
1253

    
1254
## to help the rc.scripts
1255
server.pid-file            = "{$g['varrun_path']}/{$pid_file}"
1256

    
1257
## virtual directory listings
1258
server.dir-listing         = "disable"
1259

    
1260
## enable debugging
1261
debug.log-request-header   = "disable"
1262
debug.log-response-header  = "disable"
1263
debug.log-request-handling = "disable"
1264
debug.log-file-not-found   = "disable"
1265

    
1266
# gzip compression
1267
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1268
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1269

    
1270
{$server_upload_dirs}
1271

    
1272
{$server_max_request_size}
1273

    
1274
{$fastcgi_config}
1275

    
1276
{$cgi_config}
1277

    
1278
{$captive_portal_mod_evasive}
1279

    
1280
expire.url = (
1281
				"" => "access 50 hours",	
1282
        )
1283

    
1284
EOD;
1285

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

    
1290
	$cert = str_replace("\n\n", "\n", $cert);
1291
	$key = str_replace("\n\n", "\n", $key);
1292
	$ca = str_replace("\n\n", "\n", $ca);
1293

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

    
1320
		// SSLv2/3 is deprecated, force use of TLS
1321
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
1322
		$lighty_config .= "ssl.use-sslv3 = \"disable\"\n";
1323

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

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

    
1345
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1346
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1347
	}
1348

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

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

    
1375
	return 0;
1376

    
1377
}
1378

    
1379
function system_timezone_configure() {
1380
	global $config, $g;
1381
	if(isset($config['system']['developerspew'])) {
1382
		$mt = microtime();
1383
		echo "system_timezone_configure() being called $mt\n";
1384
	}
1385

    
1386
	$syscfg = $config['system'];
1387

    
1388
	if (platform_booting())
1389
		echo gettext("Setting timezone...");
1390

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

    
1406
	conf_mount_rw();
1407

    
1408
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1409
		escapeshellarg($timezone) . " > /etc/localtime");
1410

    
1411
	mwexec("sync");
1412
	conf_mount_ro();
1413

    
1414
	if (platform_booting())
1415
		echo gettext("done.") . "\n";
1416
}
1417

    
1418
function system_ntp_setup_gps($serialport) {
1419
	global $config, $g;
1420
	$gps_device = '/dev/gps0';
1421
	$serialport = '/dev/'.$serialport;
1422

    
1423
	if (!file_exists($serialport))
1424
		return false;
1425

    
1426
	conf_mount_rw();
1427
	// Create symlink that ntpd requires
1428
	unlink_if_exists($gps_device);
1429
	@symlink($serialport, $gps_device);
1430

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

    
1438
	/* XXX: Why not file_put_contents to the device */
1439
	@file_put_contents('/tmp/gps.init', $gps_init);
1440
	`cat /tmp/gps.init > $serialport`;
1441

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

    
1467
	conf_mount_ro();
1468

    
1469
	return true;
1470
}
1471

    
1472
function system_ntp_setup_pps($serialport) {
1473
	global $config, $g;
1474

    
1475
	$pps_device = '/dev/pps0';
1476
	$serialport = '/dev/'.$serialport;
1477

    
1478
	if (!file_exists($serialport))
1479
		return false;
1480

    
1481
	conf_mount_rw();
1482
	// Create symlink that ntpd requires
1483
	unlink_if_exists($pps_device);
1484
	@symlink($serialport, $pps_device);
1485

    
1486
	conf_mount_ro();
1487

    
1488
	return true;
1489
}
1490

    
1491

    
1492
function system_ntp_configure($start_ntpd=true) {
1493
	global $config, $g;
1494

    
1495
	$driftfile = "/var/db/ntpd.drift";
1496
	$statsdir = "/var/log/ntp";
1497
	$gps_device = '/dev/gps0';
1498

    
1499
	if ($g['platform'] == 'jail')
1500
		return;
1501

    
1502
	safe_mkdir($statsdir);
1503

    
1504
	if (!is_array($config['ntpd']))
1505
		$config['ntpd'] = array();
1506

    
1507
	$ntpcfg = "# \n";
1508
	$ntpcfg .= "# pfSense ntp configuration file \n";
1509
	$ntpcfg .= "# \n\n";
1510
	$ntpcfg .= "tinker panic 0 \n";
1511

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

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

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

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

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

    
1719
	if (empty($config['ntpd']['interface']))
1720
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface']))
1721
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1722
		else
1723
			$interfaces = array();
1724
	else
1725
		$interfaces = explode(",", $config['ntpd']['interface']);
1726

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

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

    
1744
	/* At bootup we just want to write out the config. */
1745
	if (!$start_ntpd)
1746
		return;
1747

    
1748
	/* if ntpd is running, kill it */
1749
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1750
		killbypid("{$g['varrun_path']}/ntpd.pid");
1751
	}
1752
	@unlink("{$g['varrun_path']}/ntpd.pid");
1753

    
1754
	/* if /var/empty does not exist, create it */
1755
	if(!is_dir("/var/empty"))
1756
		mkdir("/var/empty", 0775, true);
1757

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

    
1766
function sync_system_time() {
1767
	global $config, $g;
1768

    
1769
	if (platform_booting())
1770
		echo gettext("Syncing system time before startup...");
1771

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

    
1782
function system_halt() {
1783
	global $g;
1784

    
1785
	system_reboot_cleanup();
1786

    
1787
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1788
}
1789

    
1790
function system_reboot() {
1791
	global $g;
1792

    
1793
	system_reboot_cleanup();
1794

    
1795
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1796
}
1797

    
1798
function system_reboot_sync() {
1799
	global $g;
1800

    
1801
	system_reboot_cleanup();
1802

    
1803
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1804
}
1805

    
1806
function system_reboot_cleanup() {
1807
	global $config, $cpzone;
1808

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

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

    
1830
	if ($early)
1831
		$cmdn = "earlyshellcmd";
1832
	else
1833
		$cmdn = "shellcmd";
1834

    
1835
	if (is_array($config['system'][$cmdn])) {
1836

    
1837
		/* *cmd is an array, loop through */
1838
		foreach ($config['system'][$cmdn] as $cmd) {
1839
			exec($cmd);
1840
		}
1841

    
1842
	} elseif($config['system'][$cmdn] <> "") {
1843

    
1844
		/* execute single item */
1845
		exec($config['system'][$cmdn]);
1846

    
1847
	}
1848
}
1849

    
1850
function system_console_configure() {
1851
	global $config, $g;
1852
	if(isset($config['system']['developerspew'])) {
1853
		$mt = microtime();
1854
		echo "system_console_configure() being called $mt\n";
1855
	}
1856

    
1857
	if (isset($config['system']['disableconsolemenu'])) {
1858
		touch("{$g['varetc_path']}/disableconsole");
1859
	} else {
1860
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1861
	}
1862
}
1863

    
1864
function system_dmesg_save() {
1865
	global $g;
1866
	if(isset($config['system']['developerspew'])) {
1867
		$mt = microtime();
1868
		echo "system_dmesg_save() being called $mt\n";
1869
	}
1870

    
1871
	$dmesg = "";
1872
	$_gb = exec("/sbin/dmesg", $dmesg);
1873

    
1874
	/* find last copyright line (output from previous boots may be present) */
1875
	$lastcpline = 0;
1876

    
1877
	for ($i = 0; $i < count($dmesg); $i++) {
1878
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1879
			$lastcpline = $i;
1880
	}
1881

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

    
1888
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1889
		fwrite($fd, $dmesg[$i] . "\n");
1890

    
1891
	fclose($fd);
1892
	unset($dmesg);
1893

    
1894
	return 0;
1895
}
1896

    
1897
function system_set_harddisk_standby() {
1898
	global $g, $config;
1899
	if(isset($config['system']['developerspew'])) {
1900
		$mt = microtime();
1901
		echo "system_set_harddisk_standby() being called $mt\n";
1902
	}
1903

    
1904
	if (isset($config['system']['harddiskstandby'])) {
1905
		if (platform_booting()) {
1906
			echo gettext('Setting hard disk standby... ');
1907
		}
1908

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

    
1929
function system_setup_sysctl() {
1930
	global $config;
1931
	if(isset($config['system']['developerspew'])) {
1932
		$mt = microtime();
1933
		echo "system_setup_sysctl() being called $mt\n";
1934
	}
1935

    
1936
	activate_sysctls();	
1937

    
1938
	if (isset($config['system']['sharednet'])) {
1939
		system_disable_arp_wrong_if();
1940
	}
1941
}
1942

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

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

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

    
1985
function system_check_reset_button() {
1986
	global $g;
1987
	if($g['platform'] != "nanobsd")
1988
		return 0;
1989

    
1990
	$specplatform = system_identify_specific_platform();
1991

    
1992
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1993
		return 0;
1994

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

    
1997
	if ($retval == 99) {
1998
		/* user has pressed reset button for 2 seconds - 
1999
		   reset to factory defaults */
2000
		echo <<<EOD
2001

    
2002
***********************************************************************
2003
* Reset button pressed - resetting configuration to factory defaults. *
2004
* The system will reboot after this completes.                        *
2005
***********************************************************************
2006

    
2007

    
2008
EOD;
2009
		
2010
		reset_factory_defaults();
2011
		system_reboot_sync();
2012
		exit(0);
2013
	}
2014

    
2015
	return 0;
2016
}
2017

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

    
2036
	$dmesg = get_single_sysctl('hw.model');
2037

    
2038
	if (strpos($dmesg, "PC Engines WRAP") !== false)
2039
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
2040
	
2041
	if (strpos($dmesg, "PC Engines ALIX") !== false)
2042
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2043

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

    
2057
function system_get_dmesg_boot() {
2058
	global $g;
2059
		
2060
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2061
}
2062

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

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