Project

General

Profile

Download (55.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/sysctl	/sbin/route
34
	pfSense_BUILDER_BINARIES:	/bin/hostname	/bin/ls	/usr/sbin/syslogd	
35
	pfSense_BUILDER_BINARIES:	/usr/sbin/pccardd	/usr/local/sbin/lighttpd	/bin/chmod 	/bin/mkdir
36
	pfSense_BUILDER_BINARIES:	/usr/bin/tar		/usr/local/sbin/ntpd	/usr/local/sbin/ntpdate
37
	pfSense_BUILDER_BINARIES:	/usr/bin/nohup	/sbin/dmesg	/usr/local/sbin/atareinit	/sbin/kldload
38
	pfSense_BUILDER_BINARIES:	/usr/local/sbin/filterdns
39
	pfSense_MODULE:	utils
40
*/
41

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

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

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

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

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

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

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

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

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

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

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

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

    
106
	if (isset($config['dnsmasq']['enable']) && !isset($config['system']['dnslocalhost']))
107
		$resolvconf .= "nameserver 127.0.0.1\n";
108

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

    
129
	$dnslock = lock('resolvconf', LOCK_EX);
130

    
131
	$fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
132
	if (!$fd) {
133
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
134
		unlock($dnslock);
135
		return 1;
136
	}
137

    
138
	fwrite($fd, $resolvconf);
139
	fclose($fd);
140

    
141
	if (!$g['booting']) {
142
		/* restart dhcpd (nameservers may have changed) */
143
		if (!$dynupdate)
144
			services_dhcpd_configure();
145
	}
146

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

    
169
	unlock($dnslock);
170

    
171
	return 0;
172
}
173

    
174
function get_searchdomains() {
175
	global $config, $g;
176

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

    
193
	return $master_list;
194
}
195

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

    
214
	// Read in any extra nameservers
215
	if(file_exists("/var/etc/nameservers.conf")) {
216
		$dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
217
		if(is_array($dns_s)) {
218
			foreach($dns_s as $dns)
219
				if (is_ipaddr($dns))
220
					$master_list[] = $dns;
221
		}
222
	}
223

    
224
	return $master_list;
225
}
226

    
227
function system_hosts_generate() {
228
	global $config, $g;
229
	if(isset($config['system']['developerspew'])) {
230
		$mt = microtime();
231
		echo "system_hosts_generate() being called $mt\n";
232
	}
233

    
234
	$syscfg = $config['system'];
235
	$dnsmasqcfg = $config['dnsmasq'];
236

    
237
	$hosts = "127.0.0.1	localhost localhost.{$syscfg['domain']}\n";
238
	$lhosts = "";
239
	$dhosts = "";
240

    
241
	if ($config['interfaces']['lan']) {
242
		$cfgip = get_interface_ip("lan");
243
		if (is_ipaddr($cfgip))
244
			$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
245
	} else {
246
		$sysiflist = get_configured_interface_list();
247
		foreach ($sysiflist as $sysif) {
248
			if (!interface_has_gateway($sysif)) {
249
				$cfgip = get_interface_ip($sysif);
250
				if (is_ipaddr($cfgip)) {
251
					$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
252
					break;
253
				}
254
			}
255
		}
256
	}
257

    
258
	if (isset($dnsmasqcfg['enable'])) {
259
		if (!is_array($dnsmasqcfg['hosts']))
260
			$dnsmasqcfg['hosts'] = array();
261

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

    
299
		if (isset($dnsmasqcfg['dhcpfirst']))
300
			$hosts .= $dhosts . $lhosts;
301
		else
302
			$hosts .= $lhosts . $dhosts;
303
	}
304

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

    
321
	system_dhcpleases_configure();
322

    
323
	return 0;
324
}
325

    
326
function system_dhcpleases_configure() {
327
	global $config, $g;
328
	
329
	if ($g['platform'] == 'jail')
330
		return;
331
	/* Start the monitoring process for dynamic dhcpclients. */
332
	if (isset($config['dnsmasq']['enable']) && isset($config['dnsmasq']['regdhcp'])) {
333
		/* Make sure we do not error out */
334
		mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db");
335
		if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases"))
336
			@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
337
		if (isvalidpid("{$g['varrun_path']}/dhcpleases.pid"))
338
			sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "HUP");
339
		else
340
			mwexec("/usr/local/sbin/dhcpleases -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases -d {$config['system']['domain']} -p {$g['varrun_path']}/dnsmasq.pid -h {$g['varetc_path']}/hosts");
341
	} else {
342
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
343
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
344
	}
345
}
346

    
347
function system_hostname_configure() {
348
	global $config, $g;
349
	if(isset($config['system']['developerspew'])) {
350
		$mt = microtime();
351
		echo "system_hostname_configure() being called $mt\n";
352
	}
353

    
354
	$syscfg = $config['system'];
355

    
356
	/* set hostname */
357
	$status = mwexec("/bin/hostname " .
358
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
359

    
360
    /* Setup host GUID ID.  This is used by ZFS. */
361
	mwexec("/etc/rc.d/hostid start");
362

    
363
	return $status;
364
}
365

    
366
function system_routing_configure($interface = "") {
367
	global $config, $g;
368
	if ($g['platform'] == 'jail')
369
		return;
370
	if(isset($config['system']['developerspew'])) {
371
		$mt = microtime();
372
		echo "system_routing_configure() being called $mt\n";
373
	}
374

    
375
	$gatewayip = "";
376
	$interfacegw = "";
377
	$foundgw = false;
378
	$gatewayipv6 = "";
379
	$interfacegwv6 = "";
380
	$foundgwv6 = false;
381
	/* tack on all the hard defined gateways as well */
382
	if (is_array($config['gateways']['gateway_item'])) {
383
		mwexec("/bin/rm -f {$g['tmp_path']}/*_defaultgw {$g['tmp_path']}/*_defaultgwv6", true);
384
		foreach	($config['gateways']['gateway_item'] as $gateway) {
385
			if (isset($gateway['defaultgw'])) {
386
				if ($gateway['ipprotocol'] != "inet6" && (is_ipaddrv4($gateway['gateway']) || $gateway['gateway'] == "dynamic")) {
387
					if(strstr($gateway['gateway'], ":"))
388
						continue;
389
					if ($gateway['gateway'] == "dynamic")
390
						$gateway['gateway'] = get_interface_gateway($gateway['interface']);
391
					$gatewayip = $gateway['gateway'];
392
					$interfacegw = $gateway['interface'];
393
					if (!empty($gateway['interface'])) {
394
						$defaultif = get_real_interface($gateway['interface']);
395
						if ($defaultif)
396
							@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gateway['gateway']);
397
					}
398
					$foundgw = true;
399
				} else if ($gateway['ipprotocol'] == "inet6" && (is_ipaddrv6($gateway['gateway']) || $gateway['gateway'] == "dynamic6")) {
400
					if ($gateway['gateway'] == "dynamic6")
401
						$gateway['gateway'] = get_interface_gateway_v6($gateway['interface']);
402
					$gatewayipv6 = $gateway['gateway'];
403
					$interfacegwv6 = $gateway['interface'];
404
					if (!empty($gateway['interface'])) {
405
						$defaultifv6 = get_real_interface($gateway['interface'], "inet6");
406
						if ($defaultifv6)
407
							@file_put_contents("{$g['tmp_path']}/{$defaultifv6}_defaultgwv6", $gateway['gateway']);
408
					}
409
					$foundgwv6 = true;
410
				}
411
			}
412
			if ($foundgw === true && $foundgwv6 === true)
413
				break;
414
		}
415
	}
416
	if ($foundgw == false) {
417
		$defaultif = get_real_interface("wan");
418
		$interfacegw = "wan";
419
		$gatewayip = get_interface_gateway("wan");
420
		@touch("{$g['tmp_path']}/{$defaultif}_defaultgw");
421
	}	
422
	if ($foundgwv6 == false) {
423
		$defaultifv6 = get_real_interface("wan", "inet6");
424
		$interfacegwv6 = "wan";
425
		$gatewayipv6 = get_interface_gateway_v6("wan");
426
		@touch("{$g['tmp_path']}/{$defaultif}_defaultgwv6");
427
	}
428
	$dont_add_route = false;
429
	/* if OLSRD is enabled, allow WAN to house DHCP. */
430
	if (is_array($config['installedpackages']['olsrd'])) {
431
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
432
			if(($olsrd['enabledyngw'] == "on") && ($olsrd['enable'] == "on")) {
433
				$dont_add_route = true;
434
				log_error(sprintf(gettext("Not adding default route because OLSR dynamic gateway is enabled.")));
435
				break;
436
			}
437
		}
438
	}
439

    
440
	if ($dont_add_route == false ) {
441
		if (!empty($interface) && $interface != $interfacegw)
442
			;
443
		else if (($interfacegw <> "bgpd") && (is_ipaddrv4($gatewayip))) {
444
			log_error("ROUTING: setting default route to $gatewayip");
445
			mwexec("/sbin/route change -inet default " . escapeshellarg($gatewayip));
446
		}
447

    
448
		if (!empty($interface) && $interface != $interfacegwv6)
449
			;
450
		else if (($interfacegwv6 <> "bgpd") && (is_ipaddrv6($gatewayipv6))) {
451
			$ifscope = "";
452
			if (is_linklocal($gatewayipv6))
453
				$ifscope = "%{$defaultifv6}";
454
			log_error("ROUTING: setting IPv6 default route to {$gatewayipv6}{$ifscope}");
455
			mwexec("/sbin/route change -inet6 default " . escapeshellarg($gatewayipv6) ."{$ifscope}");
456
		}
457
	}
458

    
459
	system_staticroutes_configure($interface, false);
460

    
461
	return 0;
462
}
463

    
464
function system_staticroutes_configure($interface = "", $update_dns = false) {
465
	global $config, $g, $aliastable;
466

    
467
	$filterdns_list = array();
468

    
469
	$static_routes = get_staticroutes(false, true);
470
	if (count($static_routes)) {
471
		$gateways_arr = return_gateways_array(false, true);
472

    
473
		foreach ($static_routes as $rtent) {
474
			if (empty($gateways_arr[$rtent['gateway']])) {
475
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
476
				continue;
477
			}
478
			$gateway = $gateways_arr[$rtent['gateway']];
479
			if (!empty($interface) && $interface != $gateway['friendlyiface'])
480
				continue;
481

    
482
			$gatewayip = $gateway['gateway'];
483
			$interfacegw = $gateway['interface'];
484

    
485
			$blackhole = "";
486
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 3)))
487
				$blackhole = "-blackhole";
488

    
489
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network']))
490
				continue;
491

    
492
			$dnscache = array();
493
			if ($update_dns === true) {
494
				if (is_subnet($rtent['network']))
495
					continue;
496
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
497
				if (empty($dnscache))
498
					continue;
499
			}
500

    
501
			if (is_subnet($rtent['network']))
502
				$ips = array($rtent['network']);
503
			else {
504
				if (!isset($rtent['disabled']))
505
					$filterdns_list[] = $rtent['network'];
506
				$ips = add_hostname_to_watch($rtent['network']);
507
			}
508

    
509
			foreach ($dnscache as $ip) {
510
				if (in_array($ip, $ips))
511
					continue;
512
				mwexec("/sbin/route delete " . escapeshellarg($ip), true);
513
			}
514

    
515
			if (isset($rtent['disabled'])) {
516
				/* XXX: This is a bit dangerous in case of routing daemons!? */
517
				foreach ($ips as $ip)
518
					mwexec("/sbin/route delete " . escapeshellarg($ip), true);
519
				continue;
520
			}
521

    
522
			foreach ($ips as $ip) {
523
				if (is_ipaddrv4($ip))
524
					$ip .= "/32";
525
				else if (is_ipaddrv6($ip))
526
					$ip .= "/128";
527

    
528
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
529

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

    
532
				if (is_subnet($ip))
533
					if (is_ipaddr($gatewayip))
534
						mwexec($cmd . escapeshellarg($gatewayip));
535
					else if (!empty($interfacegw))
536
						mwexec($cmd . "-iface " . escapeshellarg($interfacegw));
537
			}
538
		}
539
		unset($gateways_arr);
540
	}
541
	unset($static_routes);
542

    
543
	if ($update_dns === false) {
544
		if (count($filterdns_list)) {
545
			$interval = 60;
546
			$hostnames = "";
547
			array_unique($filterdns_list);
548
			foreach ($filterdns_list as $hostname)
549
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
550
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
551
			unset($hostnames);
552

    
553
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid"))
554
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
555
			else
556
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
557
		} else {
558
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
559
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
560
		}
561
	}
562
	unset($filterdns_list);
563

    
564
	return 0;
565
}
566

    
567
function system_routing_enable() {
568
	global $config, $g;
569
	if(isset($config['system']['developerspew'])) {
570
		$mt = microtime();
571
		echo "system_routing_enable() being called $mt\n";
572
	}
573

    
574
	mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
575
	mwexec("/sbin/sysctl net.inet6.ip6.forwarding=1");
576
	return;
577
}
578

    
579
function system_syslogd_fixup_server($server) {
580
	/* If it's an IPv6 IP alone, encase it in brackets */
581
	if (is_ipaddrv6($server))
582
		return "[$server]";
583
	else
584
		return $server;
585
}
586

    
587
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
588
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
589
	$facility .= " ".
590
	$remote_servers = "";
591
	$pad_to  = 56;
592
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
593
	if($syslogcfg['remoteserver'])
594
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
595
	if($syslogcfg['remoteserver2'])
596
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
597
	if($syslogcfg['remoteserver3'])
598
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
599
	return $remote_servers;
600
}
601

    
602
function system_syslogd_start() {
603
	global $config, $g;
604
	if(isset($config['system']['developerspew'])) {
605
		$mt = microtime();
606
		echo "system_syslogd_start() being called $mt\n";
607
	}
608

    
609
	mwexec("/etc/rc.d/hostid start");
610

    
611
	$syslogcfg = $config['syslog'];
612

    
613
	if ($g['booting'])
614
		echo gettext("Starting syslog...");
615
	else
616
		killbypid("{$g['varrun_path']}/syslog.pid");
617

    
618
	if (is_process_running("syslogd"))
619
		mwexec('/bin/pkill syslogd');
620
	if (is_process_running("fifolog_writer"))
621
		mwexec('/bin/pkill fifolog_writer');
622

    
623
	// Which logging type are we using this week??
624
	if (isset($config['system']['disablesyslogclog'])) {
625
		$log_directive = "";
626
		$log_create_directive = "/usr/bin/touch ";
627
		$log_size = "";
628
	} else if (isset($config['system']['usefifolog'])) {
629
		$log_directive = "|/usr/sbin/fifolog_writer ";
630
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
631
		$log_create_directive = "/usr/sbin/fifolog_create -s ";
632
	} else { // Defaults to CLOG
633
		$log_directive = "%";
634
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
635
		$log_create_directive = "/usr/sbin/clog -i -s ";
636
	}
637
	
638
	if (isset($syslogcfg)) {
639
		$separatelogfacilities = array('ntp','ntpd','ntpdate','racoon','openvpn','pptps','poes','l2tps','relayd','hostapd','dnsmasq','filterdns','unbound','dhcpd','dhcrelay','dhclient','apinger','radvd','routed','olsrd','zebra','ospfd','bgpd','miniupnpd');
640
		$syslogconf = "";
641
		if($config['installedpackages']['package']) {
642
			foreach($config['installedpackages']['package'] as $package) {
643
				if($package['logging']) {
644
					array_push($separatelogfacilities, $package['logging']['facilityname']);
645
					mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
646
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
647
				}
648
			}
649
		}
650
		$facilitylist = implode(',', array_unique($separatelogfacilities));
651
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd,miniupnpd\n";
652
		if (!isset($syslogcfg['disablelocallogging']))
653
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
654

    
655
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
656
		if (!isset($syslogcfg['disablelocallogging'])) 
657
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
658

    
659
		$syslogconf .= "!ppp\n";
660
		if (!isset($syslogcfg['disablelocallogging'])) 
661
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
662

    
663
		$syslogconf .= "!pptps\n";
664
		if (!isset($syslogcfg['disablelocallogging'])) 
665
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/pptps.log\n";
666

    
667
		$syslogconf .= "!poes\n";
668
		if (!isset($syslogcfg['disablelocallogging'])) 
669
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
670

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

    
675
		$syslogconf .= "!racoon\n";
676
		if (!isset($syslogcfg['disablelocallogging'])) 
677
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ipsec.log\n";
678
		if (isset($syslogcfg['vpn']))
679
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
680

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

    
687
		$syslogconf .= "!apinger\n";
688
		if (!isset($syslogcfg['disablelocallogging']))
689
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/gateways.log\n";
690
		if (isset($syslogcfg['apinger']))
691
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
692

    
693
		$syslogconf .= "!dnsmasq,filterdns,unbound\n";
694
		if (!isset($syslogcfg['disablelocallogging']))
695
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
696
		if (isset($syslogcfg['apinger']))
697
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
698

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

    
705
		$syslogconf .= "!relayd\n";
706
		if (!isset($syslogcfg['disablelocallogging']))
707
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/relayd.log\n";
708
		if (isset($syslogcfg['relayd']))
709
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
710

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

    
717
		$syslogconf .= "!-{$facilitylist}\n";
718
		if (!isset($syslogcfg['disablelocallogging'])) 
719
			$syslogconf .= <<<EOD
720
local0.*							{$log_directive}{$g['varlog_path']}/filter.log
721
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
722
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
723
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
724
*.notice;kern.debug;lpr.info;mail.crit;daemon.none;		{$log_directive}{$g['varlog_path']}/system.log
725
news.err;local0.none;local3.none;local4.none;			{$log_directive}{$g['varlog_path']}/system.log
726
local7.none							{$log_directive}{$g['varlog_path']}/system.log
727
security.*							{$log_directive}{$g['varlog_path']}/system.log
728
auth.info;authpriv.info;daemon.info				{$log_directive}{$g['varlog_path']}/system.log
729
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
730
*.emerg								*
731

    
732
EOD;
733
		if (isset($syslogcfg['filter']))
734
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local0.*");
735
		if (isset($syslogcfg['vpn']))
736
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
737
		if (isset($syslogcfg['portalauth']))
738
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
739
		if (isset($syslogcfg['dhcp']))
740
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
741
		if (isset($syslogcfg['system'])) {
742
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.notice;kern.debug;lpr.info;mail.crit;");
743
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "news.err;local0.none;local3.none;local7.none");
744
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "security.*");
745
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "auth.info;authpriv.info;daemon.info");
746
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.emerg");
747
		}
748
		if (isset($syslogcfg['logall'])) {
749
			// Make everything mean everything, including facilities excluded above.
750
			$syslogconf .= "!*\n";
751
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
752
		}
753

    
754
		if (isset($syslogcfg['zmqserver'])) {
755
				$syslogconf .= <<<EOD
756
*.*								^{$syslogcfg['zmqserver']}
757

    
758
EOD;
759
		}
760
		/* write syslog.conf */		
761
		if (!@file_put_contents("{$g['varetc_path']}/syslog.conf", $syslogconf)) {
762
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
763
			unset($syslogconf);
764
			return 1;
765
		}
766
		unset($syslogconf);
767

    
768
		// Ensure that the log directory exists
769
		if (!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
770
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
771

    
772
		$sourceip = "";
773
		if (!empty($syslogcfg['sourceip'])) {
774
			if ($syslogcfg['ipproto'] == "ipv6") {
775
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
776
				if (!is_ipaddr($ifaddr))
777
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
778
			} else {
779
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
780
				if (!is_ipaddr($ifaddr))
781
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
782
			}
783
			if (is_ipaddr($ifaddr)) {
784
				$sourceip = "-b {$ifaddr}";
785
			}
786
		}
787

    
788
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c -l {$g['dhcpd_chroot_path']}/var/run/log -f {$g['varetc_path']}/syslog.conf {$sourceip}");
789

    
790
	} else {
791
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c -l {$g['dhcpd_chroot_path']}/var/run/log");
792
	}
793

    
794
	if ($g['booting'])
795
		echo gettext("done.") . "\n";
796

    
797
	return $retval;
798
}
799

    
800
function system_pccard_start() {
801
	global $config, $g;
802
	if(isset($config['system']['developerspew'])) {
803
		$mt = microtime();
804
		echo "system_pccard_start() being called $mt\n";
805
	}
806

    
807
	if ($g['booting'])
808
		echo gettext("Initializing PCMCIA...");
809

    
810
	/* kill any running pccardd */
811
	killbypid("{$g['varrun_path']}/pccardd.pid");
812

    
813
	/* fire up pccardd */
814
	$res = mwexec("/usr/sbin/pccardd -z -f {$g['etc_path']}/pccard.conf");
815

    
816
	if ($g['booting']) {
817
		if ($res == 0)
818
			echo gettext("done.") . "\n";
819
		else
820
			echo gettext("failed!") . "\n";
821
	}
822

    
823
	return $res;
824
}
825

    
826

    
827
function system_webgui_start() {
828
	global $config, $g;
829

    
830
	if ($g['booting'])
831
		echo gettext("Starting webConfigurator...");
832

    
833
	chdir($g['www_path']);
834

    
835
	/* defaults */
836
	$portarg = "80";
837
	$crt = "";
838
	$key = "";
839
	$ca = "";
840

    
841
	/* non-standard port? */
842
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
843
		$portarg = "{$config['system']['webgui']['port']}";
844

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

    
881
	/* generate lighttpd configuration */
882
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
883
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
884
		"cert.pem", "ca.pem");
885

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

    
889
	sleep(1);
890

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

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

    
896
	if ($g['booting']) {
897
		if ($res == 0)
898
			echo gettext("done.") . "\n";
899
		else
900
			echo gettext("failed!") . "\n";
901
	}
902

    
903
	return $res;
904
}
905

    
906
function system_generate_lighty_config($filename,
907
	$cert,
908
	$key,
909
	$ca,
910
	$pid_file,
911
	$port = 80,
912
	$document_root = "/usr/local/www/",
913
	$cert_location = "cert.pem",
914
	$ca_location = "ca.pem",
915
	$captive_portal = false) {
916

    
917
	global $config, $g;
918

    
919
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
920
		mkdir("{$g['tmp_path']}/lighttpdcompress");
921

    
922
	if(isset($config['system']['developerspew'])) {
923
		$mt = microtime();
924
		echo "system_generate_lighty_config() being called $mt\n";
925
	}
926

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

    
931
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
932
		if (empty($maxprocperip))
933
			$maxprocperip = 10;
934
		$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
935

    
936
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
937
		exec("mkdir -p {$g['tmp_path']}/captiveportal");
938
		exec("chmod a-w {$g['tmp_path']}/captiveportal");
939
		$server_max_request_size = "server.max-request-size    = 384";
940
		$cgi_config = "";
941
	} else {
942
		$captiveportal = ",\"mod_cgi\"";
943
		$captive_portal_rewrite = "";
944
		$captive_portal_mod_evasive = "";
945
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
946
		$server_max_request_size = "server.max-request-size    = 2097152";
947
		$cgi_config = "cgi.assign                 = ( \".cgi\" => \"\" )";
948
	}
949
	
950
	if (empty($port))
951
		$lighty_port = "80";
952
	else
953
		$lighty_port = $port;
954

    
955
	$memory = get_memory();
956
	$realmem = $memory[1];
957

    
958
	// Determine web GUI process settings and take into account low memory systems
959
	if ($realmem < 255)
960
		$max_procs = 1;
961
	else
962
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
963

    
964
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM 
965
	if ($captive_portal !== false)  {
966
		if ($realmem > 135 and $realmem < 256) {
967
			$max_procs += 1; // 2 worker processes
968
		} else if ($realmem > 255 and $realmem < 513) {
969
			$max_procs += 2; // 3 worker processes
970
		} else if ($realmem > 512) {
971
			$max_procs += 4; // 6 worker processes
972
		}
973
		if ($max_procs > 1)
974
			$max_php_children = intval($max_procs/2);
975
		else
976
			$max_php_children = 1;
977

    
978
	} else {
979
		if ($realmem < 78)
980
			$max_php_children = 0;
981
		else
982
			$max_php_children = 1;
983
	}
984

    
985
	if(!isset($config['syslog']['nologlighttpd'])) {
986
		$lighty_use_syslog = <<<EOD
987
## where to send error-messages to
988
server.errorlog-use-syslog="enable"
989
EOD;
990
	}
991

    
992

    
993
	if ($captive_portal !== false) {
994
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi-{$captive_portal}.socket";
995
		$fastcgi_config = <<<EOD
996
#### fastcgi module
997
## read fastcgi.txt for more info
998
fastcgi.server = ( ".php" =>
999
	( "localhost" =>
1000
		(
1001
			"socket" => "{$fast_cgi_path}",
1002
			"max-procs" => {$max_procs},
1003
			"bin-environment" => (
1004
				"PHP_FCGI_CHILDREN" => "{$max_php_children}",
1005
				"PHP_FCGI_MAX_REQUESTS" => "500"
1006
			),
1007
			"bin-path" => "/usr/local/bin/php"
1008
		)
1009
	)
1010
)
1011

    
1012
EOD;
1013
	} else {
1014
		$fast_cgi_path = "{$g['varrun_path']}/php-fpm.socket";
1015
		$fastcgi_config = <<<EOD
1016
#### fastcgi module
1017
## read fastcgi.txt for more info
1018
fastcgi.server = ( ".php" =>
1019
	( "localhost" =>
1020
		(
1021
			"socket" => "{$fast_cgi_path}",
1022
			"broken-scriptfilename" => "enable"
1023
		)
1024
	)
1025
)
1026

    
1027
EOD;
1028
	}
1029

    
1030

    
1031
	$lighty_config = <<<EOD
1032
#
1033
# lighttpd configuration file
1034
#
1035
# use a it as base for lighttpd 1.0.0 and above
1036
#
1037
############ Options you really have to take care of ####################
1038

    
1039
## FreeBSD!
1040
server.event-handler	= "freebsd-kqueue"
1041
server.network-backend 	= "writev"
1042
#server.use-ipv6 = "enable"
1043

    
1044
## modules to load
1045
server.modules              =   ( "mod_access", "mod_expire", "mod_compress", "mod_redirect",
1046
	{$captiveportal}, "mod_fastcgi"
1047
)
1048

    
1049
server.max-keep-alive-requests = 15
1050
server.max-keep-alive-idle = 30
1051

    
1052
## a static document-root, for virtual-hosting take look at the
1053
## server.virtual-* options
1054
server.document-root        = "{$document_root}"
1055
{$captive_portal_rewrite}
1056

    
1057
# Maximum idle time with nothing being written (php downloading)
1058
server.max-write-idle = 999
1059

    
1060
{$lighty_use_syslog}
1061

    
1062
# files to check for if .../ is requested
1063
server.indexfiles           = ( "index.php", "index.html",
1064
                                "index.htm", "default.htm" )
1065

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

    
1119
# Use the "Content-Type" extended attribute to obtain mime type if possible
1120
#mimetypes.use-xattr        = "enable"
1121

    
1122
## deny access the file-extensions
1123
#
1124
# ~    is for backupfiles from vi, emacs, joe, ...
1125
# .inc is often used for code includes which should in general not be part
1126
#      of the document-root
1127
url.access-deny             = ( "~", ".inc" )
1128

    
1129

    
1130
######### Options that are good to be but not neccesary to be changed #######
1131

    
1132
## bind to port (default: 80)
1133

    
1134
EOD;
1135

    
1136
	$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1137
	$lighty_config .= "server.port  = {$lighty_port}\n";
1138
	$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1139
	$lighty_config .= "\$SERVER[\"socket\"]  == \"[::]:{$lighty_port}\" { \n";
1140
	if($cert <> "" and $key <> "") {
1141
		$lighty_config .= "\n";
1142
		$lighty_config .= "## ssl configuration\n";
1143
		$lighty_config .= "ssl.engine = \"enable\"\n";
1144
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1145
		if($ca <> "")
1146
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1147
	}
1148
	$lighty_config .= " }\n";
1149

    
1150

    
1151
	$lighty_config .= <<<EOD
1152

    
1153
## error-handler for status 404
1154
#server.error-handler-404   = "/error-handler.html"
1155
#server.error-handler-404   = "/error-handler.php"
1156

    
1157
## to help the rc.scripts
1158
server.pid-file            = "{$g['varrun_path']}/{$pid_file}"
1159

    
1160
## virtual directory listings
1161
server.dir-listing         = "disable"
1162

    
1163
## enable debugging
1164
debug.log-request-header   = "disable"
1165
debug.log-response-header  = "disable"
1166
debug.log-request-handling = "disable"
1167
debug.log-file-not-found   = "disable"
1168

    
1169
# gzip compression
1170
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1171
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1172

    
1173
{$server_upload_dirs}
1174

    
1175
{$server_max_request_size}
1176

    
1177
{$fastcgi_config}
1178

    
1179
{$cgi_config}
1180

    
1181
{$captive_portal_mod_evasive}
1182

    
1183
expire.url = (
1184
				"" => "access 50 hours",	
1185
        )
1186

    
1187
EOD;
1188

    
1189
	$cert = str_replace("\r", "", $cert);
1190
	$key = str_replace("\r", "", $key);
1191
	$ca = str_replace("\r", "", $ca);
1192

    
1193
	$cert = str_replace("\n\n", "\n", $cert);
1194
	$key = str_replace("\n\n", "\n", $key);
1195
	$ca = str_replace("\n\n", "\n", $ca);
1196

    
1197
	if($cert <> "" and $key <> "") {
1198
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1199
		if (!$fd) {
1200
			printf(gettext("Error: cannot open cert.pem in system_webgui_start().%s"), "\n");
1201
			return 1;
1202
		}
1203
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1204
		fwrite($fd, $cert);
1205
		fwrite($fd, "\n");
1206
		fwrite($fd, $key);
1207
		fclose($fd);
1208
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
1209
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1210
			if (!$fd) {
1211
				printf(gettext("Error: cannot open ca.pem in system_webgui_start().%s"), "\n");
1212
				return 1;
1213
			}
1214
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1215
			fwrite($fd, $ca);
1216
			fclose($fd);
1217
		}
1218
		$lighty_config .= "\n";
1219
		$lighty_config .= "## " . gettext("ssl configuration") . "\n";
1220
		$lighty_config .= "ssl.engine = \"enable\"\n";
1221
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1222

    
1223
		// Harden SSL a bit for PCI conformance testing
1224
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
1225

    
1226
		/* Hifn accelerators do NOT work with the BEAST mitigation code. Do not allow it to be enabled if a Hifn card has been detected. */
1227
		$fd = @fopen("{$g['varlog_path']}/dmesg.boot", "r");
1228
		if ($fd) {
1229
			while (!feof($fd)) {
1230
				$dmesgl = fgets($fd);
1231
				if (preg_match("/^hifn.: (.*?),/", $dmesgl, $matches) && isset($config['system']['webgui']['beast_protection'])) {
1232
						unset($config['system']['webgui']['beast_protection']);
1233
						log_error("BEAST Protection disabled because a conflicting cryptographic accelerator card has been detected (" . $matches[1] . ")");
1234
					break;
1235
				}
1236
			}
1237
			fclose($fd);
1238
		}
1239

    
1240
		if (isset($config['system']['webgui']['beast_protection'])) {
1241
			$lighty_config .= "ssl.honor-cipher-order = \"enable\"\n";
1242
			$lighty_config .= "ssl.cipher-list = \"ECDHE-RSA-AES256-SHA384:AES256-SHA256:RC4-SHA:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM\"\n";
1243
		} else {
1244
			$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";
1245
		}
1246

    
1247
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1248
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1249
	}
1250

    
1251
	// Add HTTP to HTTPS redirect	
1252
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1253
		if($lighty_port != "443") 
1254
			$redirectport = ":{$lighty_port}";
1255
		$lighty_config .= <<<EOD
1256
\$SERVER["socket"] == ":80" {
1257
	\$HTTP["host"] =~ "(.*)" {
1258
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1259
	}
1260
}
1261
EOD;
1262
	}
1263

    
1264
	$fd = fopen("{$filename}", "w");
1265
	if (!$fd) {
1266
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1267
		return 1;
1268
	}
1269
	fwrite($fd, $lighty_config);
1270
	fclose($fd);
1271

    
1272
	return 0;
1273

    
1274
}
1275

    
1276
function system_timezone_configure() {
1277
	global $config, $g;
1278
	if(isset($config['system']['developerspew'])) {
1279
		$mt = microtime();
1280
		echo "system_timezone_configure() being called $mt\n";
1281
	}
1282

    
1283
	$syscfg = $config['system'];
1284

    
1285
	if ($g['booting'])
1286
		echo gettext("Setting timezone...");
1287

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

    
1303
	conf_mount_rw();
1304

    
1305
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1306
		escapeshellarg($timezone) . " > /etc/localtime");
1307

    
1308
	mwexec("sync");
1309
	conf_mount_ro();
1310

    
1311
	if ($g['booting'])
1312
		echo gettext("done.") . "\n";
1313
}
1314

    
1315
function system_ntp_setup_gps($serialport) {
1316
	$gps_device = '/dev/gps0';
1317
	$serialport = '/dev/'.$serialport;
1318

    
1319
	if (!file_exists($serialport))
1320
		return false;
1321

    
1322
	conf_mount_rw();
1323
	// Create symlink that ntpd requires
1324
	unlink_if_exists($gps_device);
1325
	symlink($serialport, $gps_device);
1326

    
1327
	/* Send the following to the GPS port to initialize the GPS */
1328
	$gps_init = <<<EOF
1329
\$PUBX,40,GSV,0,0,0,0*59
1330
\$PUBX,40,GLL,0,0,0,0*5C
1331
\$PUBX,40,ZDA,0,0,0,0*44
1332
\$PUBX,40,VTG,0,0,0,0*5E
1333
\$PUBX,40,GSV,0,0,0,0*59
1334
\$PUBX,40,GSA,0,0,0,0*4E
1335
\$PUBX,40,GGA,0,0,0,0
1336
\$PUBX,40,TXT,0,0,0,0
1337
\$PUBX,40,RMC,0,0,0,0*46
1338
\$PUBX,41,1,0007,0003,4800,0
1339
\$PUBX,40,ZDA,1,1,1,1
1340
EOF;
1341
	file_put_contents("/tmp/gps.init", $gps_init);
1342
	`cat /tmp/gps.init > $serialport`;
1343

    
1344
	/* Add /etc/remote entry in case we need to read from the GPS with tip */
1345
	if (intval(`grep -c '^gps0' /etc/remote`) == 0)
1346
		`echo "gps0:dv={$serialport}:br#4800:pa=none:" >> /etc/remote`;
1347

    
1348
	conf_mount_ro();
1349

    
1350
	return true;
1351
}
1352

    
1353
function system_ntp_configure($start_ntpd=true) {
1354
	global $config, $g;
1355
	$driftfile = "/var/db/ntpd.drift";
1356
	$statsdir = "/var/log/ntp";
1357
	$gps_device = '/dev/gps0';
1358

    
1359
	if ($g['platform'] == 'jail')
1360
		return;
1361

    
1362
	safe_mkdir($statsdir);
1363

    
1364
	$ntpcfg = "# \n";
1365
	$ntpcfg .= "# pfSense ntp configuration file \n";
1366
	$ntpcfg .= "# \n\n";
1367
	$ntpcfg .= "tinker panic 0 \n";
1368

    
1369
	if (!empty($config['ntpd']['gpsport'])
1370
		&& file_exists('/dev/'.$config['ntpd']['gpsport'])
1371
		&& system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1372
		$ntpcfg .= "# GPS Setup\n";
1373
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1374
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1375
		// Fall back to local clock if GPS is out of sync?
1376
		$ntpcfg .= "server 127.127.1.0\n";
1377
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1378
	}
1379

    
1380
	$ntpcfg .= "\n\n# Upstream Servers\n";
1381
	/* foreach through servers and write out to ntpd.conf */
1382
	foreach (explode(' ', $config['system']['timeservers']) as $ts)
1383
		$ntpcfg .= "server {$ts} iburst maxpoll 9\n";
1384

    
1385
	$ntpcfg .= "disable monitor\n";
1386
	$ntpcfg .= "enable stats\n";
1387
	$ntpcfg .= "statistics clockstats\n";
1388
	$ntpcfg .= "statsdir {$statsdir}\n";
1389
	$ntpcfg .= "logconfig =syncall +clockall\n";
1390
	$ntpcfg .= "driftfile {$driftfile}\n";
1391
	$ntpcfg .= "restrict default kod limited nomodify notrap nopeer\n";
1392
	$ntpcfg .= "restrict -6 default kod limited nomodify notrap nopeer\n";
1393

    
1394
	if (empty($config['ntpd']['interface']))
1395
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface']))
1396
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1397
		else
1398
			$interfaces = array();
1399
	else
1400
		$interfaces = explode(",", $config['ntpd']['interface']);
1401

    
1402
	if (is_array($interfaces) && count($interfaces)) {
1403
		$ntpcfg .= "interface ignore all\n";
1404
		foreach ($interfaces as $interface) {
1405
			if (!is_ipaddr($interface)) {
1406
				$interface = get_real_interface($interface);
1407
			}
1408
			$ntpcfg .= "interface listen {$interface}\n";
1409
		}
1410
	}
1411

    
1412
	/* open configuration for wrting or bail */
1413
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
1414
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1415
		return;
1416
	}
1417

    
1418
	/* At bootup we just want to write out the config. */
1419
	if (!$start_ntpd)
1420
		return;
1421

    
1422
	/* if ntpd is running, kill it */
1423
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1424
		killbypid("{$g['varrun_path']}/ntpd.pid");
1425
	}
1426
	@unlink("{$g['varrun_path']}/ntpd.pid");
1427

    
1428
	/* if /var/empty does not exist, create it */
1429
	if(!is_dir("/var/empty"))
1430
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1431

    
1432
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1433
	mwexec("/usr/local/sbin/ntpd -g -c {$g['varetc_path']}/ntpd.conf -p {$g['varrun_path']}/ntpd.pid", false, true);
1434
	
1435
	// Note that we are starting up
1436
	log_error("NTPD is starting up.");
1437
	return;
1438
}
1439

    
1440
function sync_system_time() {
1441
	global $config, $g;
1442

    
1443
	if ($g['booting'])
1444
		echo gettext("Syncing system time before startup...");
1445

    
1446
	/* foreach through servers and write out to ntpd.conf */
1447
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1448
		mwexec("/usr/local/sbin/ntpdate -s $ts");
1449
	}
1450
	
1451
	if ($g['booting'])
1452
		echo gettext("done.") . "\n";
1453
	
1454
}
1455

    
1456
function system_halt() {
1457
	global $g;
1458

    
1459
	system_reboot_cleanup();
1460

    
1461
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1462
}
1463

    
1464
function system_reboot() {
1465
	global $g;
1466

    
1467
	system_reboot_cleanup();
1468

    
1469
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1470
}
1471

    
1472
function system_reboot_sync() {
1473
	global $g;
1474

    
1475
	system_reboot_cleanup();
1476

    
1477
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1478
}
1479

    
1480
function system_reboot_cleanup() {
1481
	global $config, $cpzone;
1482

    
1483
	mwexec("/usr/local/bin/beep.sh stop");
1484
	require_once("captiveportal.inc");
1485
	if (is_array($config['captiveportal'])) {
1486
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
1487
			captiveportal_radius_stop_all();
1488
			captiveportal_send_server_accounting(true);
1489
		}
1490
	}
1491
	require_once("voucher.inc");
1492
	voucher_save_db_to_config();
1493
	require_once("pkg-utils.inc");
1494
	stop_packages();
1495
}
1496

    
1497
function system_do_shell_commands($early = 0) {
1498
	global $config, $g;
1499
	if(isset($config['system']['developerspew'])) {
1500
		$mt = microtime();
1501
		echo "system_do_shell_commands() being called $mt\n";
1502
	}
1503

    
1504
	if ($early)
1505
		$cmdn = "earlyshellcmd";
1506
	else
1507
		$cmdn = "shellcmd";
1508

    
1509
	if (is_array($config['system'][$cmdn])) {
1510

    
1511
		/* *cmd is an array, loop through */
1512
		foreach ($config['system'][$cmdn] as $cmd) {
1513
			exec($cmd);
1514
		}
1515

    
1516
	} elseif($config['system'][$cmdn] <> "") {
1517

    
1518
		/* execute single item */
1519
		exec($config['system'][$cmdn]);
1520

    
1521
	}
1522
}
1523

    
1524
function system_console_configure() {
1525
	global $config, $g;
1526
	if(isset($config['system']['developerspew'])) {
1527
		$mt = microtime();
1528
		echo "system_console_configure() being called $mt\n";
1529
	}
1530

    
1531
	if (isset($config['system']['disableconsolemenu'])) {
1532
		touch("{$g['varetc_path']}/disableconsole");
1533
	} else {
1534
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1535
	}
1536
}
1537

    
1538
function system_dmesg_save() {
1539
	global $g;
1540
	if(isset($config['system']['developerspew'])) {
1541
		$mt = microtime();
1542
		echo "system_dmesg_save() being called $mt\n";
1543
	}
1544

    
1545
	$dmesg = "";
1546
	exec("/sbin/dmesg", $dmesg);
1547

    
1548
	/* find last copyright line (output from previous boots may be present) */
1549
	$lastcpline = 0;
1550

    
1551
	for ($i = 0; $i < count($dmesg); $i++) {
1552
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1553
			$lastcpline = $i;
1554
	}
1555

    
1556
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1557
	if (!$fd) {
1558
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1559
		return 1;
1560
	}
1561

    
1562
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1563
		fwrite($fd, $dmesg[$i] . "\n");
1564

    
1565
	fclose($fd);
1566

    
1567
	return 0;
1568
}
1569

    
1570
function system_set_harddisk_standby() {
1571
	global $g, $config;
1572
	if(isset($config['system']['developerspew'])) {
1573
		$mt = microtime();
1574
		echo "system_set_harddisk_standby() being called $mt\n";
1575
	}
1576

    
1577
	if (isset($config['system']['harddiskstandby'])) {
1578
		if ($g['booting']) {
1579
			echo gettext('Setting hard disk standby... ');
1580
		}
1581

    
1582
		$standby = $config['system']['harddiskstandby'];
1583
		// Check for a numeric value
1584
		if (is_numeric($standby)) {
1585
			// Sync the disk(s)
1586
			pfSense_sync();
1587
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1588
				// Reinitialize ATA-drives
1589
				mwexec('/usr/local/sbin/atareinit');
1590
				if ($g['booting']) {
1591
					echo gettext("done.") . "\n";
1592
				}
1593
			} else if ($g['booting']) {
1594
				echo gettext("failed!") . "\n";
1595
			}
1596
		} else if ($g['booting']) {
1597
			echo gettext("failed!") . "\n";
1598
		}
1599
	}
1600
}
1601

    
1602
function system_setup_sysctl() {
1603
	global $config;
1604
	if(isset($config['system']['developerspew'])) {
1605
		$mt = microtime();
1606
		echo "system_setup_sysctl() being called $mt\n";
1607
	}
1608

    
1609
	activate_sysctls();	
1610

    
1611
	if (isset($config['system']['sharednet'])) {
1612
		system_disable_arp_wrong_if();
1613
	}
1614
}
1615

    
1616
function system_disable_arp_wrong_if() {
1617
	global $config;
1618
	if(isset($config['system']['developerspew'])) {
1619
		$mt = microtime();
1620
		echo "system_disable_arp_wrong_if() being called $mt\n";
1621
	}
1622
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1623
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1624
}
1625

    
1626
function system_enable_arp_wrong_if() {
1627
	global $config;
1628
	if(isset($config['system']['developerspew'])) {
1629
		$mt = microtime();
1630
		echo "system_enable_arp_wrong_if() being called $mt\n";
1631
	}
1632
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1633
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1634
}
1635

    
1636
function enable_watchdog() {
1637
	global $config;
1638
	return;
1639
	$install_watchdog = false;
1640
	$supported_watchdogs = array("Geode");
1641
	$file = file_get_contents("/var/log/dmesg.boot");
1642
	foreach($supported_watchdogs as $sd) {
1643
		if(stristr($file, "Geode")) {
1644
			$install_watchdog = true;
1645
		}
1646
	}
1647
	if($install_watchdog == true) {
1648
		if(is_process_running("watchdogd"))
1649
			mwexec("/usr/bin/killall watchdogd", true);
1650
		exec("/usr/sbin/watchdogd");
1651
	}
1652
}
1653

    
1654
function system_check_reset_button() {
1655
	global $g;
1656
	if($g['platform'] != "nanobsd")
1657
		return 0;
1658

    
1659
	$specplatform = system_identify_specific_platform();
1660

    
1661
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1662
		return 0;
1663

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

    
1666
	if ($retval == 99) {
1667
		/* user has pressed reset button for 2 seconds - 
1668
		   reset to factory defaults */
1669
		echo <<<EOD
1670

    
1671
***********************************************************************
1672
* Reset button pressed - resetting configuration to factory defaults. *
1673
* The system will reboot after this completes.                        *
1674
***********************************************************************
1675

    
1676

    
1677
EOD;
1678
		
1679
		reset_factory_defaults();
1680
		system_reboot_sync();
1681
		exit(0);
1682
	}
1683

    
1684
	return 0;
1685
}
1686

    
1687
/* attempt to identify the specific platform (for embedded systems)
1688
   Returns an array with two elements:
1689
	name => platform string (e.g. 'wrap', 'alix' etc.)
1690
	descr => human-readable description (e.g. "PC Engines WRAP")
1691
*/
1692
function system_identify_specific_platform() {
1693
	global $g;
1694
	
1695
	if ($g['platform'] == 'generic-pc')
1696
		return array('name' => 'generic-pc', 'descr' => gettext("Generic PC"));
1697
	
1698
	if ($g['platform'] == 'generic-pc-cdrom')
1699
		return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)"));
1700
	
1701
	/* the rest of the code only deals with 'embedded' platforms */
1702
	if ($g['platform'] != 'nanobsd')
1703
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1704
	
1705
	$dmesg = system_get_dmesg_boot();
1706
	
1707
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1708
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
1709
	
1710
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1711
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
1712

    
1713
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1714
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1715
	
1716
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1717
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1718
		
1719
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1720
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1721
	
1722
	/* unknown embedded platform */
1723
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
1724
}
1725

    
1726
function system_get_dmesg_boot() {
1727
	global $g;
1728
		
1729
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1730
}
1731

    
1732
function get_possible_listen_ips($include_ipv6_link_local=false) {
1733
	$interfaces = get_configured_interface_with_descr();
1734
	$carplist = get_configured_carp_interface_list();
1735
	$listenips = array();
1736
	foreach ($carplist as $cif => $carpip)
1737
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1738
	$aliaslist = get_configured_ip_aliases_list();
1739
	foreach ($aliaslist as $aliasip => $aliasif)
1740
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1741
	foreach ($interfaces as $iface => $ifacename) {
1742
		$tmp["name"]  = $ifacename;
1743
		$tmp["value"] = $iface;
1744
		$listenips[] = $tmp;
1745
		if ($include_ipv6_link_local) {
1746
			$llip = find_interface_ipv6_ll(get_real_interface($iface));
1747
			if (!empty($llip)) {
1748
				$tmp["name"]  = "{$ifacename} IPv6 Link-Local";
1749
				$tmp["value"] = $llip;
1750
				$listenips[] = $tmp;
1751
			}
1752
		}
1753
	}
1754
	$tmp["name"]  = "Localhost";
1755
	$tmp["value"] = "lo0";
1756
	$listenips[] = $tmp;
1757
	return $listenips;
1758
}
1759

    
1760
function get_possible_traffic_source_addresses($include_ipv6_link_local=false) {
1761
	global $config;
1762
	$sourceips = get_possible_listen_ips($include_ipv6_link_local);
1763
	foreach (array('server', 'client') as $mode) {
1764
		if (is_array($config['openvpn']["openvpn-{$mode}"])) {
1765
			foreach ($config['openvpn']["openvpn-{$mode}"] as $id => $setting) {
1766
				if (!isset($setting['disable'])) {
1767
					$vpn = array();
1768
					$vpn['value'] = 'ovpn' . substr($mode, 0, 1) . $setting['vpnid'];
1769
					$vpn['name'] = gettext("OpenVPN") . " ".$mode.": ".htmlspecialchars($setting['description']);
1770
					$sourceips[] = $vpn;
1771
				}
1772
			}
1773
		}
1774
	}
1775
	return $sourceips;
1776
}
1777
?>
(52-52/66)