Project

General

Profile

Download (55.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/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/bin/ntpd	/usr/local/bin/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 .  "\"");
85
			} else { 
86
				mwexec("/sbin/sysctl " . $tunable['tunable'] . "=\"" . $tunable['value'] .  "\"");
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_lists)) {
182
		foreach($search_lists 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 = "10240";
631
		$log_create_directive = "/usr/sbin/fifolog_create -s ";
632
	} else { // Defaults to CLOG
633
		$log_directive = "%";
634
		$log_size = "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/local/bin/openssl genrsa 1024 > {$g['tmp_path']}/ssl.key");
860
			mwexec("/usr/local/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 ($captive_portal !== false)
986
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi-{$captive_portal}.socket";
987
	else
988
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi.socket";
989

    
990
	if(!isset($config['syslog']['nologlighttpd'])) {
991
		$lighty_use_syslog = <<<EOD
992
## where to send error-messages to
993
server.errorlog-use-syslog="enable"
994
EOD;
995
	}
996

    
997

    
998
	$fastcgi_config = <<<EOD
999
#### fastcgi module
1000
## read fastcgi.txt for more info
1001
fastcgi.server = ( ".php" =>
1002
	( "localhost" =>
1003
		(
1004
			"socket" => "{$fast_cgi_path}",
1005
			"max-procs" => {$max_procs},
1006
			"bin-environment" => (
1007
				"PHP_FCGI_CHILDREN" => "{$max_php_children}",
1008
				"PHP_FCGI_MAX_REQUESTS" => "500"
1009
			),
1010
			"bin-path" => "/usr/local/bin/php"
1011
		)
1012
	)
1013
)
1014

    
1015
EOD;
1016

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

    
1025
## FreeBSD!
1026
server.event-handler	= "freebsd-kqueue"
1027
server.network-backend 	= "writev"
1028
#server.use-ipv6 = "enable"
1029

    
1030
## modules to load
1031
server.modules              =   ( "mod_access", "mod_expire", "mod_compress", "mod_redirect",
1032
	{$captiveportal}, "mod_fastcgi"
1033
)
1034

    
1035
server.max-keep-alive-requests = 15
1036
server.max-keep-alive-idle = 30
1037

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

    
1043
# Maximum idle time with nothing being written (php downloading)
1044
server.max-write-idle = 999
1045

    
1046
{$lighty_use_syslog}
1047

    
1048
# files to check for if .../ is requested
1049
server.indexfiles           = ( "index.php", "index.html",
1050
                                "index.htm", "default.htm" )
1051

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

    
1105
# Use the "Content-Type" extended attribute to obtain mime type if possible
1106
#mimetypes.use-xattr        = "enable"
1107

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

    
1115

    
1116
######### Options that are good to be but not neccesary to be changed #######
1117

    
1118
## bind to port (default: 80)
1119

    
1120
EOD;
1121

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

    
1136

    
1137
	$lighty_config .= <<<EOD
1138

    
1139
## error-handler for status 404
1140
#server.error-handler-404   = "/error-handler.html"
1141
#server.error-handler-404   = "/error-handler.php"
1142

    
1143
## to help the rc.scripts
1144
server.pid-file            = "{$g['varrun_path']}/{$pid_file}"
1145

    
1146
## virtual directory listings
1147
server.dir-listing         = "disable"
1148

    
1149
## enable debugging
1150
debug.log-request-header   = "disable"
1151
debug.log-response-header  = "disable"
1152
debug.log-request-handling = "disable"
1153
debug.log-file-not-found   = "disable"
1154

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

    
1159
{$server_upload_dirs}
1160

    
1161
{$server_max_request_size}
1162

    
1163
{$fastcgi_config}
1164

    
1165
{$cgi_config}
1166

    
1167
{$captive_portal_mod_evasive}
1168

    
1169
expire.url = (
1170
				"" => "access 50 hours",	
1171
        )
1172

    
1173
EOD;
1174

    
1175
	$cert = str_replace("\r", "", $cert);
1176
	$key = str_replace("\r", "", $key);
1177
	$ca = str_replace("\r", "", $ca);
1178

    
1179
	$cert = str_replace("\n\n", "\n", $cert);
1180
	$key = str_replace("\n\n", "\n", $key);
1181
	$ca = str_replace("\n\n", "\n", $ca);
1182

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

    
1209
		// Harden SSL a bit for PCI conformance testing
1210
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
1211

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

    
1226
		if (isset($config['system']['webgui']['beast_protection'])) {
1227
			$lighty_config .= "ssl.honor-cipher-order = \"enable\"\n";
1228
			$lighty_config .= "ssl.cipher-list = \"ECDHE-RSA-AES256-SHA384:AES256-SHA256:RC4-SHA:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM\"\n";
1229
		} else {
1230
			$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";
1231
		}
1232

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

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

    
1250
	$fd = fopen("{$filename}", "w");
1251
	if (!$fd) {
1252
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1253
		return 1;
1254
	}
1255
	fwrite($fd, $lighty_config);
1256
	fclose($fd);
1257

    
1258
	return 0;
1259

    
1260
}
1261

    
1262
function system_timezone_configure() {
1263
	global $config, $g;
1264
	if(isset($config['system']['developerspew'])) {
1265
		$mt = microtime();
1266
		echo "system_timezone_configure() being called $mt\n";
1267
	}
1268

    
1269
	$syscfg = $config['system'];
1270

    
1271
	if ($g['booting'])
1272
		echo gettext("Setting timezone...");
1273

    
1274
	/* extract appropriate timezone file */
1275
	$timezone = $syscfg['timezone'];
1276
	if ($timezone) {
1277
		exec('/usr/bin/tar -tvzf /usr/share/zoneinfo.tgz', $tzs);
1278
		foreach ($tzs as $tz) {
1279
			if (preg_match(",{$timezone}$,", $tz))
1280
				break;
1281
			if (preg_match(",{$timezone} link to *(.*)$,", $tz, $matches)) {
1282
				$timezone = $matches[1];
1283
				break;
1284
			}
1285
		}
1286
	} else
1287
		$timezone = "Etc/UTC";
1288

    
1289
	conf_mount_rw();
1290

    
1291
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1292
		escapeshellarg($timezone) . " > /etc/localtime");
1293

    
1294
	mwexec("sync");
1295
	conf_mount_ro();
1296

    
1297
	if ($g['booting'])
1298
		echo gettext("done.") . "\n";
1299
}
1300

    
1301
function system_ntp_setup_gps($serialport) {
1302
	$gps_device = '/dev/gps0';
1303
	$serialport = '/dev/'.$serialport;
1304

    
1305
	if (!file_exists($serialport))
1306
		return false;
1307

    
1308
	conf_mount_rw();
1309
	// Create symlink that ntpd requires
1310
	unlink_if_exists($gps_device);
1311
	symlink($serialport, $gps_device);
1312

    
1313
	/* Send the following to the GPS port to initialize the GPS */
1314
	$gps_init = <<<EOF
1315
\$PUBX,40,GSV,0,0,0,0*59
1316
\$PUBX,40,GLL,0,0,0,0*5C
1317
\$PUBX,40,ZDA,0,0,0,0*44
1318
\$PUBX,40,VTG,0,0,0,0*5E
1319
\$PUBX,40,GSV,0,0,0,0*59
1320
\$PUBX,40,GSA,0,0,0,0*4E
1321
\$PUBX,40,GGA,0,0,0,0
1322
\$PUBX,40,TXT,0,0,0,0
1323
\$PUBX,40,RMC,0,0,0,0*46
1324
\$PUBX,41,1,0007,0003,4800,0
1325
\$PUBX,40,ZDA,1,1,1,1
1326
EOF;
1327
	file_put_contents("/tmp/gps.init", $gps_init);
1328
	`cat /tmp/gps.init > $serialport`;
1329

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

    
1334
	conf_mount_ro();
1335

    
1336
	return true;
1337
}
1338

    
1339
function system_ntp_configure($start_ntpd=true) {
1340
	global $config, $g;
1341
	$driftfile = "/var/db/ntpd.drift";
1342
	$statsdir = "/var/log/ntp";
1343
	$gps_device = '/dev/gps0';
1344

    
1345
	if ($g['platform'] == 'jail')
1346
		return;
1347

    
1348
	safe_mkdir($statsdir);
1349

    
1350
	$ntpcfg = "# \n";
1351
	$ntpcfg .= "# pfSense ntp configuration file \n";
1352
	$ntpcfg .= "# \n\n";
1353
	$ntpcfg .= "tinker panic 0 \n";
1354

    
1355
	if (!empty($config['ntpd']['gpsport'])
1356
		&& file_exists('/dev/'.$config['ntpd']['gpsport'])
1357
		&& system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1358
		$ntpcfg .= "# GPS Setup\n";
1359
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1360
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1361
		// Fall back to local clock if GPS is out of sync?
1362
		$ntpcfg .= "server 127.127.1.0\n";
1363
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1364
	}
1365

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

    
1371
	$ntpcfg .= "enable monitor\n";
1372
	$ntpcfg .= "enable stats\n";
1373
	$ntpcfg .= "statistics clockstats\n";
1374
	$ntpcfg .= "statsdir {$statsdir}\n";
1375
	$ntpcfg .= "logconfig =syncall +clockall\n";
1376
	$ntpcfg .= "driftfile {$driftfile}\n";
1377
	$ntpcfg .= "restrict default kod nomodify notrap nopeer\n";
1378
	$ntpcfg .= "restrict -6 default kod nomodify notrap nopeer\n";
1379

    
1380
	if (empty($config['ntpd']['interface']))
1381
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface']))
1382
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1383
		else
1384
			$interfaces = array();
1385
	else
1386
		$interfaces = explode(",", $config['ntpd']['interface']);
1387

    
1388
	if (is_array($interfaces) && count($interfaces)) {
1389
		$ntpcfg .= "interface ignore all\n";
1390
		foreach ($interfaces as $interface) {
1391
			if (!is_ipaddr($interface)) {
1392
				$interface = get_real_interface($interface);
1393
			}
1394
			$ntpcfg .= "interface listen {$interface}\n";
1395
		}
1396
	}
1397

    
1398
	/* open configuration for wrting or bail */
1399
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
1400
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1401
		return;
1402
	}
1403

    
1404
	/* At bootup we just want to write out the config. */
1405
	if (!$start_ntpd)
1406
		return;
1407

    
1408
	/* if ntpd is running, kill it */
1409
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1410
		killbypid("{$g['varrun_path']}/ntpd.pid");
1411
	}
1412
	@unlink("{$g['varrun_path']}/ntpd.pid");
1413

    
1414
	/* if /var/empty does not exist, create it */
1415
	if(!is_dir("/var/empty"))
1416
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1417

    
1418
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1419
	mwexec("/usr/local/bin/ntpd -g -c {$g['varetc_path']}/ntpd.conf -p {$g['varrun_path']}/ntpd.pid", false, true);
1420
	
1421
	// Note that we are starting up
1422
	log_error("NTPD is starting up.");
1423
	return;
1424
}
1425

    
1426
function sync_system_time() {
1427
	global $config, $g;
1428

    
1429
	if ($g['booting'])
1430
		echo gettext("Syncing system time before startup...");
1431

    
1432
	/* foreach through servers and write out to ntpd.conf */
1433
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1434
		mwexec("/usr/local/bin/ntpdate -s $ts");
1435
	}
1436
	
1437
	if ($g['booting'])
1438
		echo gettext("done.") . "\n";
1439
	
1440
}
1441

    
1442
function system_halt() {
1443
	global $g;
1444

    
1445
	system_reboot_cleanup();
1446

    
1447
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1448
}
1449

    
1450
function system_reboot() {
1451
	global $g;
1452

    
1453
	system_reboot_cleanup();
1454

    
1455
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1456
}
1457

    
1458
function system_reboot_sync() {
1459
	global $g;
1460

    
1461
	system_reboot_cleanup();
1462

    
1463
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1464
}
1465

    
1466
function system_reboot_cleanup() {
1467
	global $config, $cpzone;
1468

    
1469
	mwexec("/usr/local/bin/beep.sh stop");
1470
	require_once("captiveportal.inc");
1471
	if (is_array($config['captiveportal'])) {
1472
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
1473
			captiveportal_radius_stop_all();
1474
			captiveportal_send_server_accounting(true);
1475
		}
1476
	}
1477
	require_once("voucher.inc");
1478
	voucher_save_db_to_config();
1479
	require_once("pkg-utils.inc");
1480
	stop_packages();
1481
}
1482

    
1483
function system_do_shell_commands($early = 0) {
1484
	global $config, $g;
1485
	if(isset($config['system']['developerspew'])) {
1486
		$mt = microtime();
1487
		echo "system_do_shell_commands() being called $mt\n";
1488
	}
1489

    
1490
	if ($early)
1491
		$cmdn = "earlyshellcmd";
1492
	else
1493
		$cmdn = "shellcmd";
1494

    
1495
	if (is_array($config['system'][$cmdn])) {
1496

    
1497
		/* *cmd is an array, loop through */
1498
		foreach ($config['system'][$cmdn] as $cmd) {
1499
			exec($cmd);
1500
		}
1501

    
1502
	} elseif($config['system'][$cmdn] <> "") {
1503

    
1504
		/* execute single item */
1505
		exec($config['system'][$cmdn]);
1506

    
1507
	}
1508
}
1509

    
1510
function system_console_configure() {
1511
	global $config, $g;
1512
	if(isset($config['system']['developerspew'])) {
1513
		$mt = microtime();
1514
		echo "system_console_configure() being called $mt\n";
1515
	}
1516

    
1517
	if (isset($config['system']['disableconsolemenu'])) {
1518
		touch("{$g['varetc_path']}/disableconsole");
1519
	} else {
1520
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1521
	}
1522
}
1523

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

    
1531
	$dmesg = "";
1532
	exec("/sbin/dmesg", $dmesg);
1533

    
1534
	/* find last copyright line (output from previous boots may be present) */
1535
	$lastcpline = 0;
1536

    
1537
	for ($i = 0; $i < count($dmesg); $i++) {
1538
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1539
			$lastcpline = $i;
1540
	}
1541

    
1542
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1543
	if (!$fd) {
1544
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1545
		return 1;
1546
	}
1547

    
1548
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1549
		fwrite($fd, $dmesg[$i] . "\n");
1550

    
1551
	fclose($fd);
1552

    
1553
	return 0;
1554
}
1555

    
1556
function system_set_harddisk_standby() {
1557
	global $g, $config;
1558
	if(isset($config['system']['developerspew'])) {
1559
		$mt = microtime();
1560
		echo "system_set_harddisk_standby() being called $mt\n";
1561
	}
1562

    
1563
	if (isset($config['system']['harddiskstandby'])) {
1564
		if ($g['booting']) {
1565
			echo gettext('Setting hard disk standby... ');
1566
		}
1567

    
1568
		$standby = $config['system']['harddiskstandby'];
1569
		// Check for a numeric value
1570
		if (is_numeric($standby)) {
1571
			// Sync the disk(s)
1572
			pfSense_sync();
1573
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1574
				// Reinitialize ATA-drives
1575
				mwexec('/usr/local/sbin/atareinit');
1576
				if ($g['booting']) {
1577
					echo gettext("done.") . "\n";
1578
				}
1579
			} else if ($g['booting']) {
1580
				echo gettext("failed!") . "\n";
1581
			}
1582
		} else if ($g['booting']) {
1583
			echo gettext("failed!") . "\n";
1584
		}
1585
	}
1586
}
1587

    
1588
function system_setup_sysctl() {
1589
	global $config;
1590
	if(isset($config['system']['developerspew'])) {
1591
		$mt = microtime();
1592
		echo "system_setup_sysctl() being called $mt\n";
1593
	}
1594

    
1595
	activate_sysctls();	
1596

    
1597
	if (isset($config['system']['sharednet'])) {
1598
		system_disable_arp_wrong_if();
1599
	}
1600
}
1601

    
1602
function system_disable_arp_wrong_if() {
1603
	global $config;
1604
	if(isset($config['system']['developerspew'])) {
1605
		$mt = microtime();
1606
		echo "system_disable_arp_wrong_if() being called $mt\n";
1607
	}
1608
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1609
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1610
}
1611

    
1612
function system_enable_arp_wrong_if() {
1613
	global $config;
1614
	if(isset($config['system']['developerspew'])) {
1615
		$mt = microtime();
1616
		echo "system_enable_arp_wrong_if() being called $mt\n";
1617
	}
1618
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1619
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1620
}
1621

    
1622
function enable_watchdog() {
1623
	global $config;
1624
	return;
1625
	$install_watchdog = false;
1626
	$supported_watchdogs = array("Geode");
1627
	$file = file_get_contents("/var/log/dmesg.boot");
1628
	foreach($supported_watchdogs as $sd) {
1629
		if(stristr($file, "Geode")) {
1630
			$install_watchdog = true;
1631
		}
1632
	}
1633
	if($install_watchdog == true) {
1634
		if(is_process_running("watchdogd"))
1635
			mwexec("/usr/bin/killall watchdogd", true);
1636
		exec("/usr/sbin/watchdogd");
1637
	}
1638
}
1639

    
1640
function system_check_reset_button() {
1641
	global $g;
1642
	if($g['platform'] != "nanobsd")
1643
		return 0;
1644

    
1645
	$specplatform = system_identify_specific_platform();
1646

    
1647
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1648
		return 0;
1649

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

    
1652
	if ($retval == 99) {
1653
		/* user has pressed reset button for 2 seconds - 
1654
		   reset to factory defaults */
1655
		echo <<<EOD
1656

    
1657
***********************************************************************
1658
* Reset button pressed - resetting configuration to factory defaults. *
1659
* The system will reboot after this completes.                        *
1660
***********************************************************************
1661

    
1662

    
1663
EOD;
1664
		
1665
		reset_factory_defaults();
1666
		system_reboot_sync();
1667
		exit(0);
1668
	}
1669

    
1670
	return 0;
1671
}
1672

    
1673
/* attempt to identify the specific platform (for embedded systems)
1674
   Returns an array with two elements:
1675
	name => platform string (e.g. 'wrap', 'alix' etc.)
1676
	descr => human-readable description (e.g. "PC Engines WRAP")
1677
*/
1678
function system_identify_specific_platform() {
1679
	global $g;
1680
	
1681
	if ($g['platform'] == 'generic-pc')
1682
		return array('name' => 'generic-pc', 'descr' => gettext("Generic PC"));
1683
	
1684
	if ($g['platform'] == 'generic-pc-cdrom')
1685
		return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)"));
1686
	
1687
	/* the rest of the code only deals with 'embedded' platforms */
1688
	if ($g['platform'] != 'nanobsd')
1689
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1690
	
1691
	$dmesg = system_get_dmesg_boot();
1692
	
1693
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1694
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
1695
	
1696
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1697
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
1698

    
1699
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1700
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1701
	
1702
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1703
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1704
		
1705
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1706
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1707
	
1708
	/* unknown embedded platform */
1709
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
1710
}
1711

    
1712
function system_get_dmesg_boot() {
1713
	global $g;
1714
		
1715
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1716
}
1717

    
1718
function get_possible_listen_ips($include_ipv6_link_local=false) {
1719
	$interfaces = get_configured_interface_with_descr();
1720
	$carplist = get_configured_carp_interface_list();
1721
	$listenips = array();
1722
	foreach ($carplist as $cif => $carpip)
1723
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1724
	$aliaslist = get_configured_ip_aliases_list();
1725
	foreach ($aliaslist as $aliasip => $aliasif)
1726
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1727
	foreach ($interfaces as $iface => $ifacename) {
1728
		$tmp["name"]  = $ifacename;
1729
		$tmp["value"] = $iface;
1730
		$listenips[] = $tmp;
1731
		if ($include_ipv6_link_local) {
1732
			$llip = find_interface_ipv6_ll(get_real_interface($iface));
1733
			if (!empty($llip)) {
1734
				$tmp["name"]  = "{$ifacename} IPv6 Link-Local";
1735
				$tmp["value"] = $llip;
1736
				$listenips[] = $tmp;
1737
			}
1738
		}
1739
	}
1740
	$tmp["name"]  = "Localhost";
1741
	$tmp["value"] = "lo0";
1742
	$listenips[] = $tmp;
1743
	return $listenips;
1744
}
1745

    
1746
function get_possible_traffic_source_addresses($include_ipv6_link_local=false) {
1747
	global $config;
1748
	$sourceips = get_possible_listen_ips($include_ipv6_link_local);
1749
	foreach (array('server', 'client') as $mode) {
1750
		if (is_array($config['openvpn']["openvpn-{$mode}"])) {
1751
			foreach ($config['openvpn']["openvpn-{$mode}"] as $id => $setting) {
1752
				if (!isset($setting['disable'])) {
1753
					$vpn = array();
1754
					$vpn['value'] = 'ovpn' . substr($mode, 0, 1) . $setting['vpnid'];
1755
					$vpn['name'] = gettext("OpenVPN") . " ".$mode.": ".htmlspecialchars($setting['description']);
1756
					$sourceips[] = $vpn;
1757
				}
1758
			}
1759
		}
1760
	}
1761
	return $sourceips;
1762
}
1763
?>
(52-52/66)