Project

General

Profile

Download (53.7 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/sbin/ntpdate
37
	pfSense_BUILDER_BINARIES:	/usr/bin/nohup	/sbin/dmesg	/usr/local/sbin/atareinit	/sbin/kldload
38
	pfSense_MODULE:	utils
39
*/
40

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
168
	unlock($dnslock);
169

    
170
	return 0;
171
}
172

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

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

    
192
	return $master_list;
193
}
194

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

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

    
223
	return $master_list;
224
}
225

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

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

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

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

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

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

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

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

    
320
	system_dhcpleases_configure();
321

    
322
	return 0;
323
}
324

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

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

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

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

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

    
362
	return $status;
363
}
364

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

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

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

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

    
458
	$static_routes = get_staticroutes();
459
	if (count($static_routes)) {
460
		$gateways_arr = return_gateways_array(false, true);
461

    
462
		foreach ($static_routes as $rtent) {
463
			$gatewayip = "";
464
			if (empty($gateways_arr[$rtent['gateway']])) {
465
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
466
				continue;
467
			}
468
			$gateway = $gateways_arr[$rtent['gateway']];
469
			if (!empty($interface) && $interface != $gateway['friendlyiface'])
470
				continue;
471

    
472
			/* XXX: This is a bit dangerous in case of routing daemons!? */
473
			if(isset($rtent['disabled'])) {
474
				mwexec("/sbin/route delete " . escapeshellarg($rtent['network']), true);
475
				continue;
476
			}
477

    
478
			$gatewayip = $gateway['gateway'];
479
			$interfacegw = $gateway['interface'];
480

    
481
			$blackhole = "";
482
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 3)))
483
				$blackhole = "-blackhole";
484

    
485
			if (is_subnetv6($rtent['network'])) {
486
				if (is_ipaddrv6($gatewayip))
487
					mwexec("/sbin/route change -inet6 {$blackhole} " . escapeshellarg($rtent['network']) .
488
						" " . escapeshellarg($gatewayip));
489
				else if (!empty($interfacegw))
490
					mwexec("/sbin/route change -inet6 {$blackhole} " . escapeshellarg($rtent['network']) .
491
						" -iface " . escapeshellarg($interfacegw));
492
			 } else if (is_subnetv4($rtent['network'])) {
493
				if (is_ipaddrv4($gatewayip))
494
					mwexec("/sbin/route change -inet {$blackhole} " . escapeshellarg($rtent['network']) .
495
						" " . escapeshellarg($gatewayip));
496
				else if (!empty($interfacegw))
497
					mwexec("/sbin/route change -inet {$blackhole} " . escapeshellarg($rtent['network']) .
498
						" -iface " . escapeshellarg($interfacegw));
499
			}
500
		}
501
		unset($gateways_arr);
502
	}
503
	unset($static_routes);
504

    
505
	return 0;
506
}
507

    
508
function system_routing_enable() {
509
	global $config, $g;
510
	if(isset($config['system']['developerspew'])) {
511
		$mt = microtime();
512
		echo "system_routing_enable() being called $mt\n";
513
	}
514

    
515
	mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
516
	mwexec("/sbin/sysctl net.inet6.ip6.forwarding=1");
517
	return;
518
}
519

    
520
function system_syslogd_fixup_server($server) {
521
	/* If it's an IPv6 IP alone, encase it in brackets */
522
	if (is_ipaddrv6($server))
523
		return "[$server]";
524
	else
525
		return $server;
526
}
527

    
528
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
529
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
530
	$facility .= " ".
531
	$remote_servers = "";
532
	$pad_to  = 56;
533
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
534
	if($syslogcfg['remoteserver'])
535
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
536
	if($syslogcfg['remoteserver2'])
537
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
538
	if($syslogcfg['remoteserver3'])
539
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
540
	return $remote_servers;
541
}
542

    
543
function system_syslogd_start() {
544
	global $config, $g;
545
	if(isset($config['system']['developerspew'])) {
546
		$mt = microtime();
547
		echo "system_syslogd_start() being called $mt\n";
548
	}
549

    
550
	mwexec("/etc/rc.d/hostid start");
551

    
552
	$syslogcfg = $config['syslog'];
553

    
554
	if ($g['booting'])
555
		echo gettext("Starting syslog...");
556
	else
557
		killbypid("{$g['varrun_path']}/syslog.pid");
558

    
559
	if (is_process_running("syslogd"))
560
		mwexec('/bin/pkill syslogd');
561
	if (is_process_running("fifolog_writer"))
562
		mwexec('/bin/pkill fifolog_writer');
563

    
564
	// Which logging type are we using this week??
565
	if (isset($config['system']['disablesyslogclog'])) {
566
		$log_directive = "";
567
		$log_create_directive = "/usr/bin/touch ";
568
		$log_size = "";
569
	} else if (isset($config['system']['usefifolog'])) {
570
		$log_directive = "|/usr/sbin/fifolog_writer ";
571
		$log_size = "10240";
572
		$log_create_directive = "/usr/sbin/fifolog_create -s ";
573
	} else { // Defaults to CLOG
574
		$log_directive = "%";
575
		$log_size = "10240";
576
		$log_create_directive = "/usr/sbin/clog -i -s ";
577
	}
578
	
579
	if (isset($syslogcfg)) {
580
		$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');
581
		$syslogconf = "";
582
		if($config['installedpackages']['package']) {
583
			foreach($config['installedpackages']['package'] as $package) {
584
				if($package['logging']) {
585
					array_push($separatelogfacilities, $package['logging']['facilityname']);
586
					mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
587
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
588
				}
589
			}
590
		}
591
		$facilitylist = implode(',', array_unique($separatelogfacilities));
592
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd,miniupnpd\n";
593
		if (!isset($syslogcfg['disablelocallogging']))
594
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
595

    
596
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
597
		if (!isset($syslogcfg['disablelocallogging'])) 
598
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
599

    
600
		$syslogconf .= "!ppp\n";
601
		if (!isset($syslogcfg['disablelocallogging'])) 
602
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
603

    
604
		$syslogconf .= "!pptps\n";
605
		if (!isset($syslogcfg['disablelocallogging'])) 
606
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/pptps.log\n";
607

    
608
		$syslogconf .= "!poes\n";
609
		if (!isset($syslogcfg['disablelocallogging'])) 
610
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
611

    
612
		$syslogconf .= "!l2tps\n";
613
		if (!isset($syslogcfg['disablelocallogging'])) 
614
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/l2tps.log\n";
615

    
616
		$syslogconf .= "!racoon\n";
617
		if (!isset($syslogcfg['disablelocallogging'])) 
618
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ipsec.log\n";
619
		if (isset($syslogcfg['vpn']))
620
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
621

    
622
		$syslogconf .= "!openvpn\n";
623
		if (!isset($syslogcfg['disablelocallogging'])) 
624
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/openvpn.log\n";
625
		if (isset($syslogcfg['vpn']))
626
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
627

    
628
		$syslogconf .= "!apinger\n";
629
		if (!isset($syslogcfg['disablelocallogging']))
630
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/gateways.log\n";
631
		if (isset($syslogcfg['apinger']))
632
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
633

    
634
		$syslogconf .= "!dnsmasq,filterdns,unbound\n";
635
		if (!isset($syslogcfg['disablelocallogging']))
636
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
637
		if (isset($syslogcfg['apinger']))
638
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
639

    
640
		$syslogconf .= "!dhcpd,dhcrelay,dhclient\n";
641
		if (!isset($syslogcfg['disablelocallogging']))
642
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/dhcpd.log\n";
643
		if (isset($syslogcfg['apinger']))
644
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
645

    
646
		$syslogconf .= "!relayd\n";
647
		if (!isset($syslogcfg['disablelocallogging']))
648
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/relayd.log\n";
649
		if (isset($syslogcfg['relayd']))
650
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
651

    
652
		$syslogconf .= "!hostapd\n";
653
		if (!isset($syslogcfg['disablelocallogging']))
654
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
655
		if (isset($syslogcfg['hostapd']))
656
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
657

    
658
		$syslogconf .= "!-{$facilitylist}\n";
659
		if (!isset($syslogcfg['disablelocallogging'])) 
660
			$syslogconf .= <<<EOD
661
local0.*							{$log_directive}{$g['varlog_path']}/filter.log
662
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
663
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
664
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
665
*.notice;kern.debug;lpr.info;mail.crit;daemon.none;		{$log_directive}{$g['varlog_path']}/system.log
666
news.err;local0.none;local3.none;local4.none;			{$log_directive}{$g['varlog_path']}/system.log
667
local7.none							{$log_directive}{$g['varlog_path']}/system.log
668
security.*							{$log_directive}{$g['varlog_path']}/system.log
669
auth.info;authpriv.info;daemon.info				{$log_directive}{$g['varlog_path']}/system.log
670
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
671
*.emerg								*
672

    
673
EOD;
674
		if (isset($syslogcfg['filter']))
675
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local0.*");
676
		if (isset($syslogcfg['vpn']))
677
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
678
		if (isset($syslogcfg['portalauth']))
679
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
680
		if (isset($syslogcfg['dhcp']))
681
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
682
		if (isset($syslogcfg['system'])) {
683
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.notice;kern.debug;lpr.info;mail.crit;");
684
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "news.err;local0.none;local3.none;local7.none");
685
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "security.*");
686
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "auth.info;authpriv.info;daemon.info");
687
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.emerg");
688
		}
689
		if (isset($syslogcfg['logall'])) {
690
			// Make everything mean everything, including facilities excluded above.
691
			$syslogconf .= "!*\n";
692
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
693
		}
694

    
695
		if (isset($syslogcfg['zmqserver'])) {
696
				$syslogconf .= <<<EOD
697
*.*								^{$syslogcfg['zmqserver']}
698

    
699
EOD;
700
		}
701
		/* write syslog.conf */		
702
		if (!@file_put_contents("{$g['varetc_path']}/syslog.conf", $syslogconf)) {
703
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
704
			unset($syslogconf);
705
			return 1;
706
		}
707
		unset($syslogconf);
708

    
709
		// Ensure that the log directory exists
710
		if (!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
711
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
712

    
713
		$sourceip = "";
714
		if (!empty($syslogcfg['sourceip'])) {
715
			if ($syslogcfg['ipproto'] == "ipv6") {
716
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
717
				if (!is_ipaddr($ifaddr))
718
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
719
			} else {
720
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
721
				if (!is_ipaddr($ifaddr))
722
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
723
			}
724
			if (is_ipaddr($ifaddr)) {
725
				$sourceip = "-b {$ifaddr}";
726
			}
727
		}
728

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

    
731
	} else {
732
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c -l {$g['dhcpd_chroot_path']}/var/run/log");
733
	}
734

    
735
	if ($g['booting'])
736
		echo gettext("done.") . "\n";
737

    
738
	return $retval;
739
}
740

    
741
function system_pccard_start() {
742
	global $config, $g;
743
	if(isset($config['system']['developerspew'])) {
744
		$mt = microtime();
745
		echo "system_pccard_start() being called $mt\n";
746
	}
747

    
748
	if ($g['booting'])
749
		echo gettext("Initializing PCMCIA...");
750

    
751
	/* kill any running pccardd */
752
	killbypid("{$g['varrun_path']}/pccardd.pid");
753

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

    
757
	if ($g['booting']) {
758
		if ($res == 0)
759
			echo gettext("done.") . "\n";
760
		else
761
			echo gettext("failed!") . "\n";
762
	}
763

    
764
	return $res;
765
}
766

    
767

    
768
function system_webgui_start() {
769
	global $config, $g;
770

    
771
	if ($g['booting'])
772
		echo gettext("Starting webConfigurator...");
773

    
774
	chdir($g['www_path']);
775

    
776
	/* defaults */
777
	$portarg = "80";
778
	$crt = "";
779
	$key = "";
780
	$ca = "";
781

    
782
	/* non-standard port? */
783
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
784
		$portarg = "{$config['system']['webgui']['port']}";
785

    
786
	if ($config['system']['webgui']['protocol'] == "https") {
787
		// Ensure that we have a webConfigurator CERT
788
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
789
		if(!is_array($cert) && !$cert['crt'] && !$cert['prv']) {
790
			if (!is_array($config['ca']))
791
				$config['ca'] = array();
792
			$a_ca =& $config['ca'];
793
			if (!is_array($config['cert']))
794
				$config['cert'] = array();
795
			$a_cert =& $config['cert'];
796
			log_error("Creating SSL Certificate for this host");
797
			$cert = array();
798
			$cert['refid'] = uniqid();
799
			$cert['descr'] = gettext("webConfigurator default");
800
			mwexec("/usr/local/bin/openssl genrsa 1024 > {$g['tmp_path']}/ssl.key");
801
			mwexec("/usr/local/bin/openssl req -new -x509 -nodes -sha256 -days 2000 -key {$g['tmp_path']}/ssl.key > {$g['tmp_path']}/ssl.crt");
802
			$crt = file_get_contents("{$g['tmp_path']}/ssl.crt");
803
			$key = file_get_contents("{$g['tmp_path']}/ssl.key");
804
			unlink("{$g['tmp_path']}/ssl.key");
805
			unlink("{$g['tmp_path']}/ssl.crt");
806
			cert_import($cert, $crt, $key);
807
			$a_cert[] = $cert;
808
			$config['system']['webgui']['ssl-certref'] = $cert['refid'];
809
			write_config(gettext("Importing HTTPS certificate"));
810
			if(!$config['system']['webgui']['port'])
811
				$portarg = "443";
812
			$ca = ca_chain($cert);
813
		} else {
814
			$crt = base64_decode($cert['crt']);
815
			$key = base64_decode($cert['prv']);
816
			if(!$config['system']['webgui']['port'])
817
				$portarg = "443";
818
			$ca = ca_chain($cert);
819
		}
820
	}
821

    
822
	/* generate lighttpd configuration */
823
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
824
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
825
		"cert.pem", "ca.pem");
826

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

    
830
	sleep(1);
831

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

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

    
837
	if ($g['booting']) {
838
		if ($res == 0)
839
			echo gettext("done.") . "\n";
840
		else
841
			echo gettext("failed!") . "\n";
842
	}
843

    
844
	return $res;
845
}
846

    
847
function system_generate_lighty_config($filename,
848
	$cert,
849
	$key,
850
	$ca,
851
	$pid_file,
852
	$port = 80,
853
	$document_root = "/usr/local/www/",
854
	$cert_location = "cert.pem",
855
	$ca_location = "ca.pem",
856
	$captive_portal = false) {
857

    
858
	global $config, $g;
859

    
860
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
861
		mkdir("{$g['tmp_path']}/lighttpdcompress");
862

    
863
	if(isset($config['system']['developerspew'])) {
864
		$mt = microtime();
865
		echo "system_generate_lighty_config() being called $mt\n";
866
	}
867

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

    
872
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
873
		if (empty($maxprocperip))
874
			$maxprocperip = 10;
875
		$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
876

    
877
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
878
		exec("mkdir -p {$g['tmp_path']}/captiveportal");
879
		exec("chmod a-w {$g['tmp_path']}/captiveportal");
880
		$server_max_request_size = "server.max-request-size    = 384";
881
		$cgi_config = "";
882
	} else {
883
		$captiveportal = ",\"mod_cgi\"";
884
		$captive_portal_rewrite = "";
885
		$captive_portal_mod_evasive = "";
886
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
887
		$server_max_request_size = "server.max-request-size    = 2097152";
888
		$cgi_config = "cgi.assign                 = ( \".cgi\" => \"\" )";
889
	}
890
	
891
	if (empty($port))
892
		$lighty_port = "80";
893
	else
894
		$lighty_port = $port;
895

    
896
	$memory = get_memory();
897
	$realmem = $memory[1];
898

    
899
	// Determine web GUI process settings and take into account low memory systems
900
	if ($realmem < 255)
901
		$max_procs = 1;
902
	else
903
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
904

    
905
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM 
906
	if ($captive_portal !== false)  {
907
		if ($realmem > 135 and $realmem < 256) {
908
			$max_procs += 1; // 2 worker processes
909
		} else if ($realmem > 255 and $realmem < 513) {
910
			$max_procs += 2; // 3 worker processes
911
		} else if ($realmem > 512) {
912
			$max_procs += 4; // 6 worker processes
913
		}
914
		if ($max_procs > 1)
915
			$max_php_children = intval($max_procs/2);
916
		else
917
			$max_php_children = 1;
918

    
919
	} else {
920
		if ($realmem < 78)
921
			$max_php_children = 0;
922
		else
923
			$max_php_children = 1;
924
	}
925

    
926
	if ($captive_portal !== false)
927
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi-{$captive_portal}.socket";
928
	else
929
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi.socket";
930

    
931
	if(!isset($config['syslog']['nologlighttpd'])) {
932
		$lighty_use_syslog = <<<EOD
933
## where to send error-messages to
934
server.errorlog-use-syslog="enable"
935
EOD;
936
	}
937

    
938

    
939
	$fastcgi_config = <<<EOD
940
#### fastcgi module
941
## read fastcgi.txt for more info
942
fastcgi.server = ( ".php" =>
943
	( "localhost" =>
944
		(
945
			"socket" => "{$fast_cgi_path}",
946
			"max-procs" => {$max_procs},
947
			"bin-environment" => (
948
				"PHP_FCGI_CHILDREN" => "{$max_php_children}",
949
				"PHP_FCGI_MAX_REQUESTS" => "500"
950
			),
951
			"bin-path" => "/usr/local/bin/php"
952
		)
953
	)
954
)
955

    
956
EOD;
957

    
958
	$lighty_config = <<<EOD
959
#
960
# lighttpd configuration file
961
#
962
# use a it as base for lighttpd 1.0.0 and above
963
#
964
############ Options you really have to take care of ####################
965

    
966
## FreeBSD!
967
server.event-handler	= "freebsd-kqueue"
968
server.network-backend 	= "writev"
969
#server.use-ipv6 = "enable"
970

    
971
## modules to load
972
server.modules              =   ( "mod_access", "mod_expire", "mod_compress", "mod_redirect",
973
	{$captiveportal}, "mod_fastcgi"
974
)
975

    
976
server.max-keep-alive-requests = 15
977
server.max-keep-alive-idle = 30
978

    
979
## a static document-root, for virtual-hosting take look at the
980
## server.virtual-* options
981
server.document-root        = "{$document_root}"
982
{$captive_portal_rewrite}
983

    
984
# Maximum idle time with nothing being written (php downloading)
985
server.max-write-idle = 999
986

    
987
{$lighty_use_syslog}
988

    
989
# files to check for if .../ is requested
990
server.indexfiles           = ( "index.php", "index.html",
991
                                "index.htm", "default.htm" )
992

    
993
# mimetype mapping
994
mimetype.assign             = (
995
  ".pdf"          =>      "application/pdf",
996
  ".sig"          =>      "application/pgp-signature",
997
  ".spl"          =>      "application/futuresplash",
998
  ".class"        =>      "application/octet-stream",
999
  ".ps"           =>      "application/postscript",
1000
  ".torrent"      =>      "application/x-bittorrent",
1001
  ".dvi"          =>      "application/x-dvi",
1002
  ".gz"           =>      "application/x-gzip",
1003
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
1004
  ".swf"          =>      "application/x-shockwave-flash",
1005
  ".tar.gz"       =>      "application/x-tgz",
1006
  ".tgz"          =>      "application/x-tgz",
1007
  ".tar"          =>      "application/x-tar",
1008
  ".zip"          =>      "application/zip",
1009
  ".mp3"          =>      "audio/mpeg",
1010
  ".m3u"          =>      "audio/x-mpegurl",
1011
  ".wma"          =>      "audio/x-ms-wma",
1012
  ".wax"          =>      "audio/x-ms-wax",
1013
  ".ogg"          =>      "audio/x-wav",
1014
  ".wav"          =>      "audio/x-wav",
1015
  ".gif"          =>      "image/gif",
1016
  ".jpg"          =>      "image/jpeg",
1017
  ".jpeg"         =>      "image/jpeg",
1018
  ".png"          =>      "image/png",
1019
  ".xbm"          =>      "image/x-xbitmap",
1020
  ".xpm"          =>      "image/x-xpixmap",
1021
  ".xwd"          =>      "image/x-xwindowdump",
1022
  ".css"          =>      "text/css",
1023
  ".html"         =>      "text/html",
1024
  ".htm"          =>      "text/html",
1025
  ".js"           =>      "text/javascript",
1026
  ".asc"          =>      "text/plain",
1027
  ".c"            =>      "text/plain",
1028
  ".conf"         =>      "text/plain",
1029
  ".text"         =>      "text/plain",
1030
  ".txt"          =>      "text/plain",
1031
  ".dtd"          =>      "text/xml",
1032
  ".xml"          =>      "text/xml",
1033
  ".mpeg"         =>      "video/mpeg",
1034
  ".mpg"          =>      "video/mpeg",
1035
  ".mov"          =>      "video/quicktime",
1036
  ".qt"           =>      "video/quicktime",
1037
  ".avi"          =>      "video/x-msvideo",
1038
  ".asf"          =>      "video/x-ms-asf",
1039
  ".asx"          =>      "video/x-ms-asf",
1040
  ".wmv"          =>      "video/x-ms-wmv",
1041
  ".bz2"          =>      "application/x-bzip",
1042
  ".tbz"          =>      "application/x-bzip-compressed-tar",
1043
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
1044
 )
1045

    
1046
# Use the "Content-Type" extended attribute to obtain mime type if possible
1047
#mimetypes.use-xattr        = "enable"
1048

    
1049
## deny access the file-extensions
1050
#
1051
# ~    is for backupfiles from vi, emacs, joe, ...
1052
# .inc is often used for code includes which should in general not be part
1053
#      of the document-root
1054
url.access-deny             = ( "~", ".inc" )
1055

    
1056

    
1057
######### Options that are good to be but not neccesary to be changed #######
1058

    
1059
## bind to port (default: 80)
1060

    
1061
EOD;
1062

    
1063
	$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1064
	$lighty_config .= "server.port  = {$lighty_port}\n";
1065
	$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1066
	$lighty_config .= "\$SERVER[\"socket\"]  == \"[::]:{$lighty_port}\" { \n";
1067
	if($cert <> "" and $key <> "") {
1068
		$lighty_config .= "\n";
1069
		$lighty_config .= "## ssl configuration\n";
1070
		$lighty_config .= "ssl.engine = \"enable\"\n";
1071
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1072
		if($ca <> "")
1073
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1074
	}
1075
	$lighty_config .= " }\n";
1076

    
1077

    
1078
	$lighty_config .= <<<EOD
1079

    
1080
## error-handler for status 404
1081
#server.error-handler-404   = "/error-handler.html"
1082
#server.error-handler-404   = "/error-handler.php"
1083

    
1084
## to help the rc.scripts
1085
server.pid-file            = "{$g['varrun_path']}/{$pid_file}"
1086

    
1087
## virtual directory listings
1088
server.dir-listing         = "disable"
1089

    
1090
## enable debugging
1091
debug.log-request-header   = "disable"
1092
debug.log-response-header  = "disable"
1093
debug.log-request-handling = "disable"
1094
debug.log-file-not-found   = "disable"
1095

    
1096
# gzip compression
1097
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1098
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1099

    
1100
{$server_upload_dirs}
1101

    
1102
{$server_max_request_size}
1103

    
1104
{$fastcgi_config}
1105

    
1106
{$cgi_config}
1107

    
1108
{$captive_portal_mod_evasive}
1109

    
1110
expire.url = (
1111
				"" => "access 50 hours",	
1112
        )
1113

    
1114
EOD;
1115

    
1116
	$cert = str_replace("\r", "", $cert);
1117
	$key = str_replace("\r", "", $key);
1118
	$ca = str_replace("\r", "", $ca);
1119

    
1120
	$cert = str_replace("\n\n", "\n", $cert);
1121
	$key = str_replace("\n\n", "\n", $key);
1122
	$ca = str_replace("\n\n", "\n", $ca);
1123

    
1124
	if($cert <> "" and $key <> "") {
1125
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1126
		if (!$fd) {
1127
			printf(gettext("Error: cannot open cert.pem in system_webgui_start().%s"), "\n");
1128
			return 1;
1129
		}
1130
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1131
		fwrite($fd, $cert);
1132
		fwrite($fd, "\n");
1133
		fwrite($fd, $key);
1134
		fclose($fd);
1135
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
1136
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1137
			if (!$fd) {
1138
				printf(gettext("Error: cannot open ca.pem in system_webgui_start().%s"), "\n");
1139
				return 1;
1140
			}
1141
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1142
			fwrite($fd, $ca);
1143
			fclose($fd);
1144
		}
1145
		$lighty_config .= "\n";
1146
		$lighty_config .= "## " . gettext("ssl configuration") . "\n";
1147
		$lighty_config .= "ssl.engine = \"enable\"\n";
1148
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1149

    
1150
		// Harden SSL a bit for PCI conformance testing
1151
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
1152

    
1153
		/* Hifn accelerators do NOT work with the BEAST mitigation code. Do not allow it to be enabled if a Hifn card has been detected. */
1154
		$fd = @fopen("{$g['varlog_path']}/dmesg.boot", "r");
1155
		if ($fd) {
1156
			while (!feof($fd)) {
1157
				$dmesgl = fgets($fd);
1158
				if (preg_match("/^hifn.: (.*?),/", $dmesgl, $matches) && isset($config['system']['webgui']['beast_protection'])) {
1159
						unset($config['system']['webgui']['beast_protection']);
1160
						log_error("BEAST Protection disabled because a conflicting cryptographic accelerator card has been detected (" . $matches[1] . ")");
1161
					break;
1162
				}
1163
			}
1164
			fclose($fd);
1165
		}
1166

    
1167
		if (isset($config['system']['webgui']['beast_protection'])) {
1168
			$lighty_config .= "ssl.honor-cipher-order = \"enable\"\n";
1169
			$lighty_config .= "ssl.cipher-list = \"ECDHE-RSA-AES256-SHA384:AES256-SHA256:RC4-SHA:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM\"\n";
1170
		} else {
1171
			$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";
1172
		}
1173

    
1174
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1175
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1176
	}
1177

    
1178
	// Add HTTP to HTTPS redirect	
1179
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1180
		if($lighty_port != "443") 
1181
			$redirectport = ":{$lighty_port}";
1182
		$lighty_config .= <<<EOD
1183
\$SERVER["socket"] == ":80" {
1184
	\$HTTP["host"] =~ "(.*)" {
1185
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1186
	}
1187
}
1188
EOD;
1189
	}
1190

    
1191
	$fd = fopen("{$filename}", "w");
1192
	if (!$fd) {
1193
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1194
		return 1;
1195
	}
1196
	fwrite($fd, $lighty_config);
1197
	fclose($fd);
1198

    
1199
	return 0;
1200

    
1201
}
1202

    
1203
function system_timezone_configure() {
1204
	global $config, $g;
1205
	if(isset($config['system']['developerspew'])) {
1206
		$mt = microtime();
1207
		echo "system_timezone_configure() being called $mt\n";
1208
	}
1209

    
1210
	$syscfg = $config['system'];
1211

    
1212
	if ($g['booting'])
1213
		echo gettext("Setting timezone...");
1214

    
1215
	/* extract appropriate timezone file */
1216
	$timezone = $syscfg['timezone'];
1217
	if ($timezone) {
1218
		exec('/usr/bin/tar -tvzf /usr/share/zoneinfo.tgz', $tzs);
1219
		foreach ($tzs as $tz) {
1220
			if (preg_match(",{$timezone}$,", $tz))
1221
				break;
1222
			if (preg_match(",{$timezone} link to *(.*)$,", $tz, $matches)) {
1223
				$timezone = $matches[1];
1224
				break;
1225
			}
1226
		}
1227
	} else
1228
		$timezone = "Etc/UTC";
1229

    
1230
	conf_mount_rw();
1231

    
1232
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1233
		escapeshellarg($timezone) . " > /etc/localtime");
1234

    
1235
	mwexec("sync");
1236
	conf_mount_ro();
1237

    
1238
	if ($g['booting'])
1239
		echo gettext("done.") . "\n";
1240
}
1241

    
1242
function system_ntp_setup_gps($serialport) {
1243
	$gps_device = '/dev/gps0';
1244
	$serialport = '/dev/'.$serialport;
1245

    
1246
	if (!file_exists($serialport))
1247
		return false;
1248

    
1249
	conf_mount_rw();
1250
	// Create symlink that ntpd requires
1251
	unlink_if_exists($gps_device);
1252
	symlink($serialport, $gps_device);
1253

    
1254
	/* Send the following to the GPS port to initialize the GPS */
1255
	$gps_init = <<<EOF
1256
\$PUBX,40,GSV,0,0,0,0*59
1257
\$PUBX,40,GLL,0,0,0,0*5C
1258
\$PUBX,40,ZDA,0,0,0,0*44
1259
\$PUBX,40,VTG,0,0,0,0*5E
1260
\$PUBX,40,GSV,0,0,0,0*59
1261
\$PUBX,40,GSA,0,0,0,0*4E
1262
\$PUBX,40,GGA,0,0,0,0
1263
\$PUBX,40,TXT,0,0,0,0
1264
\$PUBX,40,RMC,0,0,0,0*46
1265
\$PUBX,41,1,0007,0003,4800,0
1266
\$PUBX,40,ZDA,1,1,1,1
1267
EOF;
1268
	file_put_contents("/tmp/gps.init", $gps_init);
1269
	`cat /tmp/gps.init > $serialport`;
1270

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

    
1275
	conf_mount_ro();
1276

    
1277
	return true;
1278
}
1279

    
1280
function system_ntp_configure($start_ntpd=true) {
1281
	global $config, $g;
1282
	$driftfile = "/var/db/ntpd.drift";
1283
	$statsdir = "/var/log/ntp";
1284
	$gps_device = '/dev/gps0';
1285

    
1286
	if ($g['platform'] == 'jail')
1287
		return;
1288

    
1289
	safe_mkdir($statsdir);
1290

    
1291
	$ntpcfg = "# \n";
1292
	$ntpcfg .= "# pfSense ntp configuration file \n";
1293
	$ntpcfg .= "# \n\n";
1294
	$ntpcfg .= "tinker panic 0 \n";
1295

    
1296
	if (!empty($config['ntpd']['gpsport'])
1297
		&& file_exists('/dev/'.$config['ntpd']['gpsport'])
1298
		&& system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1299
		$ntpcfg .= "# GPS Setup\n";
1300
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1301
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1302
		// Fall back to local clock if GPS is out of sync?
1303
		$ntpcfg .= "server 127.127.1.0\n";
1304
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1305
	}
1306

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

    
1312
	$ntpcfg .= "enable monitor\n";
1313
	$ntpcfg .= "enable stats\n";
1314
	$ntpcfg .= "statistics clockstats\n";
1315
	$ntpcfg .= "statsdir {$statsdir}\n";
1316
	$ntpcfg .= "logconfig =syncall +clockall\n";
1317
	$ntpcfg .= "driftfile {$driftfile}\n";
1318
	$ntpcfg .= "restrict default kod nomodify notrap nopeer\n";
1319
	$ntpcfg .= "restrict -6 default kod nomodify notrap nopeer\n";
1320

    
1321
	if (empty($config['ntpd']['interface']))
1322
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface']))
1323
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1324
		else
1325
			$interfaces = array();
1326
	else
1327
		$interfaces = explode(",", $config['ntpd']['interface']);
1328

    
1329
	if (is_array($interfaces) && count($interfaces)) {
1330
		$ntpcfg .= "interface ignore all\n";
1331
		foreach ($interfaces as $interface) {
1332
			if (!is_ipaddr($interface)) {
1333
				$interface = get_real_interface($interface);
1334
			}
1335
			$ntpcfg .= "interface listen {$interface}\n";
1336
		}
1337
	}
1338

    
1339
	/* open configuration for wrting or bail */
1340
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
1341
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1342
		return;
1343
	}
1344

    
1345
	/* At bootup we just want to write out the config. */
1346
	if (!$start_ntpd)
1347
		return;
1348

    
1349
	/* if ntpd is running, kill it */
1350
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1351
		killbypid("{$g['varrun_path']}/ntpd.pid");
1352
	}
1353
	@unlink("{$g['varrun_path']}/ntpd.pid");
1354

    
1355
	/* if /var/empty does not exist, create it */
1356
	if(!is_dir("/var/empty"))
1357
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1358

    
1359
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1360
	mwexec("/usr/local/bin/ntpd -g -c {$g['varetc_path']}/ntpd.conf -p {$g['varrun_path']}/ntpd.pid", false, true);
1361
	
1362
	// Note that we are starting up
1363
	log_error("NTPD is starting up.");
1364
	return;
1365
}
1366

    
1367
function sync_system_time() {
1368
	global $config, $g;
1369

    
1370
	if ($g['booting'])
1371
		echo gettext("Syncing system time before startup...");
1372

    
1373
	/* foreach through servers and write out to ntpd.conf */
1374
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1375
		mwexec("/usr/sbin/ntpdate -s $ts");
1376
	}
1377
	
1378
	if ($g['booting'])
1379
		echo gettext("done.") . "\n";
1380
	
1381
}
1382

    
1383
function system_halt() {
1384
	global $g;
1385

    
1386
	system_reboot_cleanup();
1387

    
1388
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1389
}
1390

    
1391
function system_reboot() {
1392
	global $g;
1393

    
1394
	system_reboot_cleanup();
1395

    
1396
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1397
}
1398

    
1399
function system_reboot_sync() {
1400
	global $g;
1401

    
1402
	system_reboot_cleanup();
1403

    
1404
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1405
}
1406

    
1407
function system_reboot_cleanup() {
1408
	global $config, $cpzone;
1409

    
1410
	mwexec("/usr/local/bin/beep.sh stop");
1411
	require_once("captiveportal.inc");
1412
	if (is_array($config['captiveportal'])) {
1413
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
1414
			captiveportal_radius_stop_all();
1415
			captiveportal_send_server_accounting(true);
1416
		}
1417
	}
1418
	require_once("voucher.inc");
1419
	voucher_save_db_to_config();
1420
	require_once("pkg-utils.inc");
1421
	stop_packages();
1422
}
1423

    
1424
function system_do_shell_commands($early = 0) {
1425
	global $config, $g;
1426
	if(isset($config['system']['developerspew'])) {
1427
		$mt = microtime();
1428
		echo "system_do_shell_commands() being called $mt\n";
1429
	}
1430

    
1431
	if ($early)
1432
		$cmdn = "earlyshellcmd";
1433
	else
1434
		$cmdn = "shellcmd";
1435

    
1436
	if (is_array($config['system'][$cmdn])) {
1437

    
1438
		/* *cmd is an array, loop through */
1439
		foreach ($config['system'][$cmdn] as $cmd) {
1440
			exec($cmd);
1441
		}
1442

    
1443
	} elseif($config['system'][$cmdn] <> "") {
1444

    
1445
		/* execute single item */
1446
		exec($config['system'][$cmdn]);
1447

    
1448
	}
1449
}
1450

    
1451
function system_console_configure() {
1452
	global $config, $g;
1453
	if(isset($config['system']['developerspew'])) {
1454
		$mt = microtime();
1455
		echo "system_console_configure() being called $mt\n";
1456
	}
1457

    
1458
	if (isset($config['system']['disableconsolemenu'])) {
1459
		touch("{$g['varetc_path']}/disableconsole");
1460
	} else {
1461
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1462
	}
1463
}
1464

    
1465
function system_dmesg_save() {
1466
	global $g;
1467
	if(isset($config['system']['developerspew'])) {
1468
		$mt = microtime();
1469
		echo "system_dmesg_save() being called $mt\n";
1470
	}
1471

    
1472
	$dmesg = "";
1473
	exec("/sbin/dmesg", $dmesg);
1474

    
1475
	/* find last copyright line (output from previous boots may be present) */
1476
	$lastcpline = 0;
1477

    
1478
	for ($i = 0; $i < count($dmesg); $i++) {
1479
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1480
			$lastcpline = $i;
1481
	}
1482

    
1483
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1484
	if (!$fd) {
1485
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1486
		return 1;
1487
	}
1488

    
1489
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1490
		fwrite($fd, $dmesg[$i] . "\n");
1491

    
1492
	fclose($fd);
1493

    
1494
	return 0;
1495
}
1496

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

    
1504
	if (isset($config['system']['harddiskstandby'])) {
1505
		if ($g['booting']) {
1506
			echo gettext('Setting hard disk standby... ');
1507
		}
1508

    
1509
		$standby = $config['system']['harddiskstandby'];
1510
		// Check for a numeric value
1511
		if (is_numeric($standby)) {
1512
			// Sync the disk(s)
1513
			pfSense_sync();
1514
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1515
				// Reinitialize ATA-drives
1516
				mwexec('/usr/local/sbin/atareinit');
1517
				if ($g['booting']) {
1518
					echo gettext("done.") . "\n";
1519
				}
1520
			} else if ($g['booting']) {
1521
				echo gettext("failed!") . "\n";
1522
			}
1523
		} else if ($g['booting']) {
1524
			echo gettext("failed!") . "\n";
1525
		}
1526
	}
1527
}
1528

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

    
1536
	activate_sysctls();	
1537

    
1538
	if (isset($config['system']['sharednet'])) {
1539
		system_disable_arp_wrong_if();
1540
	}
1541
}
1542

    
1543
function system_disable_arp_wrong_if() {
1544
	global $config;
1545
	if(isset($config['system']['developerspew'])) {
1546
		$mt = microtime();
1547
		echo "system_disable_arp_wrong_if() being called $mt\n";
1548
	}
1549
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1550
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1551
}
1552

    
1553
function system_enable_arp_wrong_if() {
1554
	global $config;
1555
	if(isset($config['system']['developerspew'])) {
1556
		$mt = microtime();
1557
		echo "system_enable_arp_wrong_if() being called $mt\n";
1558
	}
1559
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1560
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1561
}
1562

    
1563
function enable_watchdog() {
1564
	global $config;
1565
	return;
1566
	$install_watchdog = false;
1567
	$supported_watchdogs = array("Geode");
1568
	$file = file_get_contents("/var/log/dmesg.boot");
1569
	foreach($supported_watchdogs as $sd) {
1570
		if(stristr($file, "Geode")) {
1571
			$install_watchdog = true;
1572
		}
1573
	}
1574
	if($install_watchdog == true) {
1575
		if(is_process_running("watchdogd"))
1576
			mwexec("/usr/bin/killall watchdogd", true);
1577
		exec("/usr/sbin/watchdogd");
1578
	}
1579
}
1580

    
1581
function system_check_reset_button() {
1582
	global $g;
1583
	if($g['platform'] != "nanobsd")
1584
		return 0;
1585

    
1586
	$specplatform = system_identify_specific_platform();
1587

    
1588
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1589
		return 0;
1590

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

    
1593
	if ($retval == 99) {
1594
		/* user has pressed reset button for 2 seconds - 
1595
		   reset to factory defaults */
1596
		echo <<<EOD
1597

    
1598
***********************************************************************
1599
* Reset button pressed - resetting configuration to factory defaults. *
1600
* The system will reboot after this completes.                        *
1601
***********************************************************************
1602

    
1603

    
1604
EOD;
1605
		
1606
		reset_factory_defaults();
1607
		system_reboot_sync();
1608
		exit(0);
1609
	}
1610

    
1611
	return 0;
1612
}
1613

    
1614
/* attempt to identify the specific platform (for embedded systems)
1615
   Returns an array with two elements:
1616
	name => platform string (e.g. 'wrap', 'alix' etc.)
1617
	descr => human-readable description (e.g. "PC Engines WRAP")
1618
*/
1619
function system_identify_specific_platform() {
1620
	global $g;
1621
	
1622
	if ($g['platform'] == 'generic-pc')
1623
		return array('name' => 'generic-pc', 'descr' => gettext("Generic PC"));
1624
	
1625
	if ($g['platform'] == 'generic-pc-cdrom')
1626
		return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)"));
1627
	
1628
	/* the rest of the code only deals with 'embedded' platforms */
1629
	if ($g['platform'] != 'nanobsd')
1630
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1631
	
1632
	$dmesg = system_get_dmesg_boot();
1633
	
1634
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1635
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
1636
	
1637
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1638
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
1639

    
1640
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1641
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1642
	
1643
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1644
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1645
		
1646
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1647
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1648
	
1649
	/* unknown embedded platform */
1650
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
1651
}
1652

    
1653
function system_get_dmesg_boot() {
1654
	global $g;
1655
		
1656
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1657
}
1658

    
1659
function get_possible_listen_ips($include_ipv6_link_local=false) {
1660
	$interfaces = get_configured_interface_with_descr();
1661
	$carplist = get_configured_carp_interface_list();
1662
	$listenips = array();
1663
	foreach ($carplist as $cif => $carpip)
1664
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1665
	$aliaslist = get_configured_ip_aliases_list();
1666
	foreach ($aliaslist as $aliasip => $aliasif)
1667
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1668
	foreach ($interfaces as $iface => $ifacename) {
1669
		$tmp["name"]  = $ifacename;
1670
		$tmp["value"] = $iface;
1671
		$listenips[] = $tmp;
1672
		if ($include_ipv6_link_local) {
1673
			$llip = find_interface_ipv6_ll(get_real_interface($iface));
1674
			if (!empty($llip)) {
1675
				$tmp["name"]  = "{$ifacename} IPv6 Link-Local";
1676
				$tmp["value"] = $llip;
1677
				$listenips[] = $tmp;
1678
			}
1679
		}
1680
	}
1681
	$tmp["name"]  = "Localhost";
1682
	$tmp["value"] = "lo0";
1683
	$listenips[] = $tmp;
1684
	return $listenips;
1685
}
1686

    
1687
function get_possible_traffic_source_addresses($include_ipv6_link_local=false) {
1688
	global $config;
1689
	$sourceips = get_possible_listen_ips($include_ipv6_link_local);
1690
	foreach (array('server', 'client') as $mode) {
1691
		if (is_array($config['openvpn']["openvpn-{$mode}"])) {
1692
			foreach ($config['openvpn']["openvpn-{$mode}"] as $id => $setting) {
1693
				if (!isset($setting['disable'])) {
1694
					$vpn = array();
1695
					$vpn['value'] = 'ovpn' . substr($mode, 0, 1) . $setting['vpnid'];
1696
					$vpn['name'] = gettext("OpenVPN") . " ".$mode.": ".htmlspecialchars($setting['description']);
1697
					$sourceips[] = $vpn;
1698
				}
1699
			}
1700
		}
1701
	}
1702
	return $sourceips;
1703
}
1704
?>
(52-52/66)