Project

General

Profile

Download (54.3 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
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c -l {$g['dhcpd_chroot_path']}/var/run/log -f {$g['varetc_path']}/syslog.conf");
773

    
774
	} else {
775
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c -l {$g['dhcpd_chroot_path']}/var/run/log");
776
	}
777

    
778
	if ($g['booting'])
779
		echo gettext("done.") . "\n";
780

    
781
	return $retval;
782
}
783

    
784
function system_pccard_start() {
785
	global $config, $g;
786
	if(isset($config['system']['developerspew'])) {
787
		$mt = microtime();
788
		echo "system_pccard_start() being called $mt\n";
789
	}
790

    
791
	if ($g['booting'])
792
		echo gettext("Initializing PCMCIA...");
793

    
794
	/* kill any running pccardd */
795
	killbypid("{$g['varrun_path']}/pccardd.pid");
796

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

    
800
	if ($g['booting']) {
801
		if ($res == 0)
802
			echo gettext("done.") . "\n";
803
		else
804
			echo gettext("failed!") . "\n";
805
	}
806

    
807
	return $res;
808
}
809

    
810

    
811
function system_webgui_start() {
812
	global $config, $g;
813

    
814
	if ($g['booting'])
815
		echo gettext("Starting webConfigurator...");
816

    
817
	chdir($g['www_path']);
818

    
819
	/* defaults */
820
	$portarg = "80";
821
	$crt = "";
822
	$key = "";
823
	$ca = "";
824

    
825
	/* non-standard port? */
826
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
827
		$portarg = "{$config['system']['webgui']['port']}";
828

    
829
	if ($config['system']['webgui']['protocol'] == "https") {
830
		// Ensure that we have a webConfigurator CERT
831
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
832
		if(!is_array($cert) && !$cert['crt'] && !$cert['prv']) {
833
			if (!is_array($config['ca']))
834
				$config['ca'] = array();
835
			$a_ca =& $config['ca'];
836
			if (!is_array($config['cert']))
837
				$config['cert'] = array();
838
			$a_cert =& $config['cert'];
839
			log_error("Creating SSL Certificate for this host");
840
			$cert = array();
841
			$cert['refid'] = uniqid();
842
			$cert['descr'] = gettext("webConfigurator default");
843
			mwexec("/usr/local/bin/openssl genrsa 1024 > {$g['tmp_path']}/ssl.key");
844
			mwexec("/usr/local/bin/openssl req -new -x509 -nodes -sha256 -days 2000 -key {$g['tmp_path']}/ssl.key > {$g['tmp_path']}/ssl.crt");
845
			$crt = file_get_contents("{$g['tmp_path']}/ssl.crt");
846
			$key = file_get_contents("{$g['tmp_path']}/ssl.key");
847
			unlink("{$g['tmp_path']}/ssl.key");
848
			unlink("{$g['tmp_path']}/ssl.crt");
849
			cert_import($cert, $crt, $key);
850
			$a_cert[] = $cert;
851
			$config['system']['webgui']['ssl-certref'] = $cert['refid'];
852
			write_config(gettext("Importing HTTPS certificate"));
853
			if(!$config['system']['webgui']['port'])
854
				$portarg = "443";
855
			$ca = ca_chain($cert);
856
		} else {
857
			$crt = base64_decode($cert['crt']);
858
			$key = base64_decode($cert['prv']);
859
			if(!$config['system']['webgui']['port'])
860
				$portarg = "443";
861
			$ca = ca_chain($cert);
862
		}
863
	}
864

    
865
	/* generate lighttpd configuration */
866
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
867
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
868
		"cert.pem", "ca.pem");
869

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

    
873
	sleep(1);
874

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

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

    
880
	if ($g['booting']) {
881
		if ($res == 0)
882
			echo gettext("done.") . "\n";
883
		else
884
			echo gettext("failed!") . "\n";
885
	}
886

    
887
	return $res;
888
}
889

    
890
function system_generate_lighty_config($filename,
891
	$cert,
892
	$key,
893
	$ca,
894
	$pid_file,
895
	$port = 80,
896
	$document_root = "/usr/local/www/",
897
	$cert_location = "cert.pem",
898
	$ca_location = "ca.pem",
899
	$captive_portal = false) {
900

    
901
	global $config, $g;
902

    
903
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
904
		mkdir("{$g['tmp_path']}/lighttpdcompress");
905

    
906
	if(isset($config['system']['developerspew'])) {
907
		$mt = microtime();
908
		echo "system_generate_lighty_config() being called $mt\n";
909
	}
910

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

    
915
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
916
		if (empty($maxprocperip))
917
			$maxprocperip = 10;
918
		$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
919

    
920
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
921
		exec("mkdir -p {$g['tmp_path']}/captiveportal");
922
		exec("chmod a-w {$g['tmp_path']}/captiveportal");
923
		$server_max_request_size = "server.max-request-size    = 384";
924
		$cgi_config = "";
925
	} else {
926
		$captiveportal = ",\"mod_cgi\"";
927
		$captive_portal_rewrite = "";
928
		$captive_portal_mod_evasive = "";
929
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
930
		$server_max_request_size = "server.max-request-size    = 2097152";
931
		$cgi_config = "cgi.assign                 = ( \".cgi\" => \"\" )";
932
	}
933
	
934
	if (empty($port))
935
		$lighty_port = "80";
936
	else
937
		$lighty_port = $port;
938

    
939
	$memory = get_memory();
940
	$realmem = $memory[1];
941

    
942
	// Determine web GUI process settings and take into account low memory systems
943
	if ($realmem < 255)
944
		$max_procs = 1;
945
	else
946
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
947

    
948
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM 
949
	if ($captive_portal !== false)  {
950
		if ($realmem > 135 and $realmem < 256) {
951
			$max_procs += 1; // 2 worker processes
952
		} else if ($realmem > 255 and $realmem < 513) {
953
			$max_procs += 2; // 3 worker processes
954
		} else if ($realmem > 512) {
955
			$max_procs += 4; // 6 worker processes
956
		}
957
		if ($max_procs > 1)
958
			$max_php_children = intval($max_procs/2);
959
		else
960
			$max_php_children = 1;
961

    
962
	} else {
963
		if ($realmem < 78)
964
			$max_php_children = 0;
965
		else
966
			$max_php_children = 1;
967
	}
968

    
969
	if ($captive_portal !== false)
970
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi-{$captive_portal}.socket";
971
	else
972
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi.socket";
973

    
974
	if(!isset($config['syslog']['nologlighttpd'])) {
975
		$lighty_use_syslog = <<<EOD
976
## where to send error-messages to
977
server.errorlog-use-syslog="enable"
978
EOD;
979
	}
980

    
981

    
982
	$fastcgi_config = <<<EOD
983
#### fastcgi module
984
## read fastcgi.txt for more info
985
fastcgi.server = ( ".php" =>
986
	( "localhost" =>
987
		(
988
			"socket" => "{$fast_cgi_path}",
989
			"max-procs" => {$max_procs},
990
			"bin-environment" => (
991
				"PHP_FCGI_CHILDREN" => "{$max_php_children}",
992
				"PHP_FCGI_MAX_REQUESTS" => "500"
993
			),
994
			"bin-path" => "/usr/local/bin/php"
995
		)
996
	)
997
)
998

    
999
EOD;
1000

    
1001
	$lighty_config = <<<EOD
1002
#
1003
# lighttpd configuration file
1004
#
1005
# use a it as base for lighttpd 1.0.0 and above
1006
#
1007
############ Options you really have to take care of ####################
1008

    
1009
## FreeBSD!
1010
server.event-handler	= "freebsd-kqueue"
1011
server.network-backend 	= "writev"
1012
#server.use-ipv6 = "enable"
1013

    
1014
## modules to load
1015
server.modules              =   ( "mod_access", "mod_expire", "mod_compress", "mod_redirect",
1016
	{$captiveportal}, "mod_fastcgi"
1017
)
1018

    
1019
server.max-keep-alive-requests = 15
1020
server.max-keep-alive-idle = 30
1021

    
1022
## a static document-root, for virtual-hosting take look at the
1023
## server.virtual-* options
1024
server.document-root        = "{$document_root}"
1025
{$captive_portal_rewrite}
1026

    
1027
# Maximum idle time with nothing being written (php downloading)
1028
server.max-write-idle = 999
1029

    
1030
{$lighty_use_syslog}
1031

    
1032
# files to check for if .../ is requested
1033
server.indexfiles           = ( "index.php", "index.html",
1034
                                "index.htm", "default.htm" )
1035

    
1036
# mimetype mapping
1037
mimetype.assign             = (
1038
  ".pdf"          =>      "application/pdf",
1039
  ".sig"          =>      "application/pgp-signature",
1040
  ".spl"          =>      "application/futuresplash",
1041
  ".class"        =>      "application/octet-stream",
1042
  ".ps"           =>      "application/postscript",
1043
  ".torrent"      =>      "application/x-bittorrent",
1044
  ".dvi"          =>      "application/x-dvi",
1045
  ".gz"           =>      "application/x-gzip",
1046
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
1047
  ".swf"          =>      "application/x-shockwave-flash",
1048
  ".tar.gz"       =>      "application/x-tgz",
1049
  ".tgz"          =>      "application/x-tgz",
1050
  ".tar"          =>      "application/x-tar",
1051
  ".zip"          =>      "application/zip",
1052
  ".mp3"          =>      "audio/mpeg",
1053
  ".m3u"          =>      "audio/x-mpegurl",
1054
  ".wma"          =>      "audio/x-ms-wma",
1055
  ".wax"          =>      "audio/x-ms-wax",
1056
  ".ogg"          =>      "audio/x-wav",
1057
  ".wav"          =>      "audio/x-wav",
1058
  ".gif"          =>      "image/gif",
1059
  ".jpg"          =>      "image/jpeg",
1060
  ".jpeg"         =>      "image/jpeg",
1061
  ".png"          =>      "image/png",
1062
  ".xbm"          =>      "image/x-xbitmap",
1063
  ".xpm"          =>      "image/x-xpixmap",
1064
  ".xwd"          =>      "image/x-xwindowdump",
1065
  ".css"          =>      "text/css",
1066
  ".html"         =>      "text/html",
1067
  ".htm"          =>      "text/html",
1068
  ".js"           =>      "text/javascript",
1069
  ".asc"          =>      "text/plain",
1070
  ".c"            =>      "text/plain",
1071
  ".conf"         =>      "text/plain",
1072
  ".text"         =>      "text/plain",
1073
  ".txt"          =>      "text/plain",
1074
  ".dtd"          =>      "text/xml",
1075
  ".xml"          =>      "text/xml",
1076
  ".mpeg"         =>      "video/mpeg",
1077
  ".mpg"          =>      "video/mpeg",
1078
  ".mov"          =>      "video/quicktime",
1079
  ".qt"           =>      "video/quicktime",
1080
  ".avi"          =>      "video/x-msvideo",
1081
  ".asf"          =>      "video/x-ms-asf",
1082
  ".asx"          =>      "video/x-ms-asf",
1083
  ".wmv"          =>      "video/x-ms-wmv",
1084
  ".bz2"          =>      "application/x-bzip",
1085
  ".tbz"          =>      "application/x-bzip-compressed-tar",
1086
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
1087
 )
1088

    
1089
# Use the "Content-Type" extended attribute to obtain mime type if possible
1090
#mimetypes.use-xattr        = "enable"
1091

    
1092
## deny access the file-extensions
1093
#
1094
# ~    is for backupfiles from vi, emacs, joe, ...
1095
# .inc is often used for code includes which should in general not be part
1096
#      of the document-root
1097
url.access-deny             = ( "~", ".inc" )
1098

    
1099

    
1100
######### Options that are good to be but not neccesary to be changed #######
1101

    
1102
## bind to port (default: 80)
1103

    
1104
EOD;
1105

    
1106
	$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1107
	$lighty_config .= "server.port  = {$lighty_port}\n";
1108
	$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1109
	$lighty_config .= "\$SERVER[\"socket\"]  == \"[::]:{$lighty_port}\" { \n";
1110
	if($cert <> "" and $key <> "") {
1111
		$lighty_config .= "\n";
1112
		$lighty_config .= "## ssl configuration\n";
1113
		$lighty_config .= "ssl.engine = \"enable\"\n";
1114
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1115
		if($ca <> "")
1116
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1117
	}
1118
	$lighty_config .= " }\n";
1119

    
1120

    
1121
	$lighty_config .= <<<EOD
1122

    
1123
## error-handler for status 404
1124
#server.error-handler-404   = "/error-handler.html"
1125
#server.error-handler-404   = "/error-handler.php"
1126

    
1127
## to help the rc.scripts
1128
server.pid-file            = "{$g['varrun_path']}/{$pid_file}"
1129

    
1130
## virtual directory listings
1131
server.dir-listing         = "disable"
1132

    
1133
## enable debugging
1134
debug.log-request-header   = "disable"
1135
debug.log-response-header  = "disable"
1136
debug.log-request-handling = "disable"
1137
debug.log-file-not-found   = "disable"
1138

    
1139
# gzip compression
1140
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1141
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1142

    
1143
{$server_upload_dirs}
1144

    
1145
{$server_max_request_size}
1146

    
1147
{$fastcgi_config}
1148

    
1149
{$cgi_config}
1150

    
1151
{$captive_portal_mod_evasive}
1152

    
1153
expire.url = (
1154
				"" => "access 50 hours",	
1155
        )
1156

    
1157
EOD;
1158

    
1159
	$cert = str_replace("\r", "", $cert);
1160
	$key = str_replace("\r", "", $key);
1161
	$ca = str_replace("\r", "", $ca);
1162

    
1163
	$cert = str_replace("\n\n", "\n", $cert);
1164
	$key = str_replace("\n\n", "\n", $key);
1165
	$ca = str_replace("\n\n", "\n", $ca);
1166

    
1167
	if($cert <> "" and $key <> "") {
1168
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1169
		if (!$fd) {
1170
			printf(gettext("Error: cannot open cert.pem in system_webgui_start().%s"), "\n");
1171
			return 1;
1172
		}
1173
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1174
		fwrite($fd, $cert);
1175
		fwrite($fd, "\n");
1176
		fwrite($fd, $key);
1177
		fclose($fd);
1178
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
1179
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1180
			if (!$fd) {
1181
				printf(gettext("Error: cannot open ca.pem in system_webgui_start().%s"), "\n");
1182
				return 1;
1183
			}
1184
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1185
			fwrite($fd, $ca);
1186
			fclose($fd);
1187
		}
1188
		$lighty_config .= "\n";
1189
		$lighty_config .= "## " . gettext("ssl configuration") . "\n";
1190
		$lighty_config .= "ssl.engine = \"enable\"\n";
1191
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1192

    
1193
		// Harden SSL a bit for PCI conformance testing
1194
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
1195

    
1196
		/* Hifn accelerators do NOT work with the BEAST mitigation code. Do not allow it to be enabled if a Hifn card has been detected. */
1197
		$fd = @fopen("{$g['varlog_path']}/dmesg.boot", "r");
1198
		if ($fd) {
1199
			while (!feof($fd)) {
1200
				$dmesgl = fgets($fd);
1201
				if (preg_match("/^hifn.: (.*?),/", $dmesgl, $matches) && isset($config['system']['webgui']['beast_protection'])) {
1202
						unset($config['system']['webgui']['beast_protection']);
1203
						log_error("BEAST Protection disabled because a conflicting cryptographic accelerator card has been detected (" . $matches[1] . ")");
1204
					break;
1205
				}
1206
			}
1207
			fclose($fd);
1208
		}
1209

    
1210
		if (isset($config['system']['webgui']['beast_protection'])) {
1211
			$lighty_config .= "ssl.honor-cipher-order = \"enable\"\n";
1212
			$lighty_config .= "ssl.cipher-list = \"ECDHE-RSA-AES256-SHA384:AES256-SHA256:RC4-SHA:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM\"\n";
1213
		} else {
1214
			$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";
1215
		}
1216

    
1217
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1218
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1219
	}
1220

    
1221
	// Add HTTP to HTTPS redirect	
1222
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1223
		if($lighty_port != "443") 
1224
			$redirectport = ":{$lighty_port}";
1225
		$lighty_config .= <<<EOD
1226
\$SERVER["socket"] == ":80" {
1227
	\$HTTP["host"] =~ "(.*)" {
1228
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1229
	}
1230
}
1231
EOD;
1232
	}
1233

    
1234
	$fd = fopen("{$filename}", "w");
1235
	if (!$fd) {
1236
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1237
		return 1;
1238
	}
1239
	fwrite($fd, $lighty_config);
1240
	fclose($fd);
1241

    
1242
	return 0;
1243

    
1244
}
1245

    
1246
function system_timezone_configure() {
1247
	global $config, $g;
1248
	if(isset($config['system']['developerspew'])) {
1249
		$mt = microtime();
1250
		echo "system_timezone_configure() being called $mt\n";
1251
	}
1252

    
1253
	$syscfg = $config['system'];
1254

    
1255
	if ($g['booting'])
1256
		echo gettext("Setting timezone...");
1257

    
1258
	/* extract appropriate timezone file */
1259
	$timezone = $syscfg['timezone'];
1260
	if (!$timezone)
1261
		$timezone = "Etc/UTC";
1262

    
1263
	conf_mount_rw();
1264

    
1265
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1266
		escapeshellarg($timezone) . " > /etc/localtime");
1267

    
1268
	mwexec("sync");
1269
	conf_mount_ro();
1270

    
1271
	if ($g['booting'])
1272
		echo gettext("done.") . "\n";
1273
}
1274

    
1275
function system_ntp_setup_gps($serialport) {
1276
	$gps_device = '/dev/gps0';
1277
	$serialport = '/dev/'.$serialport;
1278

    
1279
	if (!file_exists($serialport))
1280
		return false;
1281

    
1282
	conf_mount_rw();
1283
	// Create symlink that ntpd requires
1284
	unlink_if_exists($gps_device);
1285
	symlink($serialport, $gps_device);
1286

    
1287
	/* Send the following to the GPS port to initialize the GPS */
1288
	$gps_init = <<<EOF
1289
\$PUBX,40,GSV,0,0,0,0*59
1290
\$PUBX,40,GLL,0,0,0,0*5C
1291
\$PUBX,40,ZDA,0,0,0,0*44
1292
\$PUBX,40,VTG,0,0,0,0*5E
1293
\$PUBX,40,GSV,0,0,0,0*59
1294
\$PUBX,40,GSA,0,0,0,0*4E
1295
\$PUBX,40,GGA,0,0,0,0
1296
\$PUBX,40,TXT,0,0,0,0
1297
\$PUBX,40,RMC,0,0,0,0*46
1298
\$PUBX,41,1,0007,0003,4800,0
1299
\$PUBX,40,ZDA,1,1,1,1
1300
EOF;
1301
	file_put_contents("/tmp/gps.init", $gps_init);
1302
	`cat /tmp/gps.init > $serialport`;
1303

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

    
1308
	conf_mount_ro();
1309

    
1310
	return true;
1311
}
1312

    
1313
function system_ntp_configure($start_ntpd=true) {
1314
	global $config, $g;
1315
	$driftfile = "/var/db/ntpd.drift";
1316
	$statsdir = "/var/log/ntp";
1317
	$gps_device = '/dev/gps0';
1318

    
1319
	if ($g['platform'] == 'jail')
1320
		return;
1321

    
1322
	safe_mkdir($statsdir);
1323

    
1324
	$ntpcfg = "# \n";
1325
	$ntpcfg .= "# pfSense ntp configuration file \n";
1326
	$ntpcfg .= "# \n\n";
1327
	$ntpcfg .= "tinker panic 0 \n";
1328

    
1329
	if (!empty($config['ntpd']['gpsport'])
1330
		&& file_exists('/dev/'.$config['ntpd']['gpsport'])
1331
		&& system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1332
		$ntpcfg .= "# GPS Setup\n";
1333
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1334
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1335
		// Fall back to local clock if GPS is out of sync?
1336
		$ntpcfg .= "server 127.127.1.0\n";
1337
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1338
	}
1339

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

    
1345
	$ntpcfg .= "enable monitor\n";
1346
	$ntpcfg .= "enable stats\n";
1347
	$ntpcfg .= "statistics clockstats\n";
1348
	$ntpcfg .= "statsdir {$statsdir}\n";
1349
	$ntpcfg .= "logconfig =syncall +clockall\n";
1350
	$ntpcfg .= "driftfile {$driftfile}\n";
1351
	$ntpcfg .= "restrict default kod nomodify notrap nopeer\n";
1352
	$ntpcfg .= "restrict -6 default kod nomodify notrap nopeer\n";
1353

    
1354
	if (empty($config['ntpd']['interface']))
1355
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface']))
1356
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1357
		else
1358
			$interfaces = array();
1359
	else
1360
		$interfaces = explode(",", $config['ntpd']['interface']);
1361

    
1362
	if (is_array($interfaces) && count($interfaces)) {
1363
		$ntpcfg .= "interface ignore all\n";
1364
		foreach ($interfaces as $interface) {
1365
			if (!is_ipaddr($interface)) {
1366
				$interface = get_real_interface($interface);
1367
			}
1368
			$ntpcfg .= "interface listen {$interface}\n";
1369
		}
1370
	}
1371

    
1372
	/* open configuration for wrting or bail */
1373
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
1374
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1375
		return;
1376
	}
1377

    
1378
	/* At bootup we just want to write out the config. */
1379
	if (!$start_ntpd)
1380
		return;
1381

    
1382
	/* if ntpd is running, kill it */
1383
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1384
		killbypid("{$g['varrun_path']}/ntpd.pid");
1385
	}
1386
	@unlink("{$g['varrun_path']}/ntpd.pid");
1387

    
1388
	/* if /var/empty does not exist, create it */
1389
	if(!is_dir("/var/empty"))
1390
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1391

    
1392
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1393
	mwexec("/usr/local/bin/ntpd -g -c {$g['varetc_path']}/ntpd.conf -p {$g['varrun_path']}/ntpd.pid", false, true);
1394
	
1395
	// Note that we are starting up
1396
	log_error("NTPD is starting up.");
1397
	return;
1398
}
1399

    
1400
function sync_system_time() {
1401
	global $config, $g;
1402

    
1403
	if ($g['booting'])
1404
		echo gettext("Syncing system time before startup...");
1405

    
1406
	/* foreach through servers and write out to ntpd.conf */
1407
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1408
		mwexec("/usr/local/bin/ntpdate -s $ts");
1409
	}
1410
	
1411
	if ($g['booting'])
1412
		echo gettext("done.") . "\n";
1413
	
1414
}
1415

    
1416
function system_halt() {
1417
	global $g;
1418

    
1419
	system_reboot_cleanup();
1420

    
1421
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1422
}
1423

    
1424
function system_reboot() {
1425
	global $g;
1426

    
1427
	system_reboot_cleanup();
1428

    
1429
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1430
}
1431

    
1432
function system_reboot_sync() {
1433
	global $g;
1434

    
1435
	system_reboot_cleanup();
1436

    
1437
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1438
}
1439

    
1440
function system_reboot_cleanup() {
1441
	global $config, $cpzone;
1442

    
1443
	mwexec("/usr/local/bin/beep.sh stop");
1444
	require_once("captiveportal.inc");
1445
	if (is_array($config['captiveportal'])) {
1446
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
1447
			captiveportal_radius_stop_all();
1448
			captiveportal_send_server_accounting(true);
1449
		}
1450
	}
1451
	require_once("voucher.inc");
1452
	voucher_save_db_to_config();
1453
	require_once("pkg-utils.inc");
1454
	stop_packages();
1455
}
1456

    
1457
function system_do_shell_commands($early = 0) {
1458
	global $config, $g;
1459
	if(isset($config['system']['developerspew'])) {
1460
		$mt = microtime();
1461
		echo "system_do_shell_commands() being called $mt\n";
1462
	}
1463

    
1464
	if ($early)
1465
		$cmdn = "earlyshellcmd";
1466
	else
1467
		$cmdn = "shellcmd";
1468

    
1469
	if (is_array($config['system'][$cmdn])) {
1470

    
1471
		/* *cmd is an array, loop through */
1472
		foreach ($config['system'][$cmdn] as $cmd) {
1473
			exec($cmd);
1474
		}
1475

    
1476
	} elseif($config['system'][$cmdn] <> "") {
1477

    
1478
		/* execute single item */
1479
		exec($config['system'][$cmdn]);
1480

    
1481
	}
1482
}
1483

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

    
1491
	if (isset($config['system']['disableconsolemenu'])) {
1492
		touch("{$g['varetc_path']}/disableconsole");
1493
	} else {
1494
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1495
	}
1496
}
1497

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

    
1505
	$dmesg = "";
1506
	exec("/sbin/dmesg", $dmesg);
1507

    
1508
	/* find last copyright line (output from previous boots may be present) */
1509
	$lastcpline = 0;
1510

    
1511
	for ($i = 0; $i < count($dmesg); $i++) {
1512
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1513
			$lastcpline = $i;
1514
	}
1515

    
1516
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1517
	if (!$fd) {
1518
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1519
		return 1;
1520
	}
1521

    
1522
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1523
		fwrite($fd, $dmesg[$i] . "\n");
1524

    
1525
	fclose($fd);
1526

    
1527
	return 0;
1528
}
1529

    
1530
function system_set_harddisk_standby() {
1531
	global $g, $config;
1532
	if(isset($config['system']['developerspew'])) {
1533
		$mt = microtime();
1534
		echo "system_set_harddisk_standby() being called $mt\n";
1535
	}
1536

    
1537
	if (isset($config['system']['harddiskstandby'])) {
1538
		if ($g['booting']) {
1539
			echo gettext('Setting hard disk standby... ');
1540
		}
1541

    
1542
		$standby = $config['system']['harddiskstandby'];
1543
		// Check for a numeric value
1544
		if (is_numeric($standby)) {
1545
			// Sync the disk(s)
1546
			pfSense_sync();
1547
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1548
				// Reinitialize ATA-drives
1549
				mwexec('/usr/local/sbin/atareinit');
1550
				if ($g['booting']) {
1551
					echo gettext("done.") . "\n";
1552
				}
1553
			} else if ($g['booting']) {
1554
				echo gettext("failed!") . "\n";
1555
			}
1556
		} else if ($g['booting']) {
1557
			echo gettext("failed!") . "\n";
1558
		}
1559
	}
1560
}
1561

    
1562
function system_setup_sysctl() {
1563
	global $config;
1564
	if(isset($config['system']['developerspew'])) {
1565
		$mt = microtime();
1566
		echo "system_setup_sysctl() being called $mt\n";
1567
	}
1568

    
1569
	activate_sysctls();	
1570

    
1571
	if (isset($config['system']['sharednet'])) {
1572
		system_disable_arp_wrong_if();
1573
	}
1574
}
1575

    
1576
function system_disable_arp_wrong_if() {
1577
	global $config;
1578
	if(isset($config['system']['developerspew'])) {
1579
		$mt = microtime();
1580
		echo "system_disable_arp_wrong_if() being called $mt\n";
1581
	}
1582
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1583
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1584
}
1585

    
1586
function system_enable_arp_wrong_if() {
1587
	global $config;
1588
	if(isset($config['system']['developerspew'])) {
1589
		$mt = microtime();
1590
		echo "system_enable_arp_wrong_if() being called $mt\n";
1591
	}
1592
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1593
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1594
}
1595

    
1596
function enable_watchdog() {
1597
	global $config;
1598
	return;
1599
	$install_watchdog = false;
1600
	$supported_watchdogs = array("Geode");
1601
	$file = file_get_contents("/var/log/dmesg.boot");
1602
	foreach($supported_watchdogs as $sd) {
1603
		if(stristr($file, "Geode")) {
1604
			$install_watchdog = true;
1605
		}
1606
	}
1607
	if($install_watchdog == true) {
1608
		if(is_process_running("watchdogd"))
1609
			mwexec("/usr/bin/killall watchdogd", true);
1610
		exec("/usr/sbin/watchdogd");
1611
	}
1612
}
1613

    
1614
function system_check_reset_button() {
1615
	global $g;
1616
	if($g['platform'] != "nanobsd")
1617
		return 0;
1618

    
1619
	$specplatform = system_identify_specific_platform();
1620

    
1621
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1622
		return 0;
1623

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

    
1626
	if ($retval == 99) {
1627
		/* user has pressed reset button for 2 seconds - 
1628
		   reset to factory defaults */
1629
		echo <<<EOD
1630

    
1631
***********************************************************************
1632
* Reset button pressed - resetting configuration to factory defaults. *
1633
* The system will reboot after this completes.                        *
1634
***********************************************************************
1635

    
1636

    
1637
EOD;
1638
		
1639
		reset_factory_defaults();
1640
		system_reboot_sync();
1641
		exit(0);
1642
	}
1643

    
1644
	return 0;
1645
}
1646

    
1647
/* attempt to identify the specific platform (for embedded systems)
1648
   Returns an array with two elements:
1649
	name => platform string (e.g. 'wrap', 'alix' etc.)
1650
	descr => human-readable description (e.g. "PC Engines WRAP")
1651
*/
1652
function system_identify_specific_platform() {
1653
	global $g;
1654
	
1655
	if ($g['platform'] == 'generic-pc')
1656
		return array('name' => 'generic-pc', 'descr' => gettext("Generic PC"));
1657
	
1658
	if ($g['platform'] == 'generic-pc-cdrom')
1659
		return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)"));
1660
	
1661
	/* the rest of the code only deals with 'embedded' platforms */
1662
	if ($g['platform'] != 'nanobsd')
1663
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1664
	
1665
	$dmesg = system_get_dmesg_boot();
1666
	
1667
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1668
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
1669
	
1670
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1671
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
1672

    
1673
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1674
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1675
	
1676
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1677
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1678
		
1679
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1680
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1681
	
1682
	/* unknown embedded platform */
1683
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
1684
}
1685

    
1686
function system_get_dmesg_boot() {
1687
	global $g;
1688
		
1689
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1690
}
1691

    
1692
function get_possible_listen_ips($include_ipv6_link_local=false) {
1693
	$interfaces = get_configured_interface_with_descr();
1694
	$carplist = get_configured_carp_interface_list();
1695
	$listenips = array();
1696
	foreach ($carplist as $cif => $carpip)
1697
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1698
	$aliaslist = get_configured_ip_aliases_list();
1699
	foreach ($aliaslist as $aliasip => $aliasif)
1700
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1701
	foreach ($interfaces as $iface => $ifacename) {
1702
		$tmp["name"]  = $ifacename;
1703
		$tmp["value"] = $iface;
1704
		$listenips[] = $tmp;
1705
		if ($include_ipv6_link_local) {
1706
			$llip = find_interface_ipv6_ll(get_real_interface($iface));
1707
			if (!empty($llip)) {
1708
				$tmp["name"]  = "{$ifacename} IPv6 Link-Local";
1709
				$tmp["value"] = $llip;
1710
				$listenips[] = $tmp;
1711
			}
1712
		}
1713
	}
1714
	$tmp["name"]  = "Localhost";
1715
	$tmp["value"] = "lo0";
1716
	$listenips[] = $tmp;
1717
	return $listenips;
1718
}
1719

    
1720
function get_possible_traffic_source_addresses($include_ipv6_link_local=false) {
1721
	global $config;
1722
	$sourceips = get_possible_listen_ips($include_ipv6_link_local);
1723
	foreach (array('server', 'client') as $mode) {
1724
		if (is_array($config['openvpn']["openvpn-{$mode}"])) {
1725
			foreach ($config['openvpn']["openvpn-{$mode}"] as $id => $setting) {
1726
				if (!isset($setting['disable'])) {
1727
					$vpn = array();
1728
					$vpn['value'] = 'ovpn' . substr($mode, 0, 1) . $setting['vpnid'];
1729
					$vpn['name'] = gettext("OpenVPN") . " ".$mode.": ".htmlspecialchars($setting['description']);
1730
					$sourceips[] = $vpn;
1731
				}
1732
			}
1733
		}
1734
	}
1735
	return $sourceips;
1736
}
1737
?>
(52-52/66)