Project

General

Profile

Download (53.6 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/* $Id$ */
3
/*
4
	system.inc
5
	part of m0n0wall (http://m0n0.ch/wall)
6

    
7
	Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
8
	All rights reserved.
9

    
10
	Redistribution and use in source and binary forms, with or without
11
	modification, are permitted provided that the following conditions are met:
12

    
13
	1. Redistributions of source code must retain the above copyright notice,
14
	   this list of conditions and the following disclaimer.
15

    
16
	2. Redistributions in binary form must reproduce the above copyright
17
	   notice, this list of conditions and the following disclaimer in the
18
	   documentation and/or other materials provided with the distribution.
19

    
20
	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
21
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
22
	AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
23
	AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
24
	OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29
	POSSIBILITY OF SUCH DAMAGE.
30
*/
31

    
32
/*
33
	pfSense_BUILDER_BINARIES:	/usr/sbin/powerd	/usr/bin/killall	/sbin/sysctl	/sbin/route
34
	pfSense_BUILDER_BINARIES:	/bin/hostname	/bin/ls	/usr/sbin/syslogd	
35
	pfSense_BUILDER_BINARIES:	/usr/sbin/pccardd	/usr/local/sbin/lighttpd	/bin/chmod 	/bin/mkdir
36
	pfSense_BUILDER_BINARIES:	/usr/bin/tar		/usr/local/sbin/ntpd	/usr/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_list)) {
181
		foreach($search_list 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
		array_map('unlink', glob("{$g['tmp_path']}/*_defaultgw{,v6}", GLOB_BRACE));
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
		mkdir("{$g['tmp_path']}/captiveportal", 0555);
879
		$server_max_request_size = "server.max-request-size    = 384";
880
		$cgi_config = "";
881
	} else {
882
		$captiveportal = ",\"mod_cgi\"";
883
		$captive_portal_rewrite = "";
884
		$captive_portal_mod_evasive = "";
885
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
886
		$server_max_request_size = "server.max-request-size    = 2097152";
887
		$cgi_config = "cgi.assign                 = ( \".cgi\" => \"\" )";
888
	}
889
	
890
	if (empty($port))
891
		$lighty_port = "80";
892
	else
893
		$lighty_port = $port;
894

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

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

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

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

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

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

    
937

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

    
955
EOD;
956

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

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

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

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

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

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

    
986
{$lighty_use_syslog}
987

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

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

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

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

    
1055

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

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

    
1060
EOD;
1061

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

    
1076

    
1077
	$lighty_config .= <<<EOD
1078

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

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

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

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

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

    
1099
{$server_upload_dirs}
1100

    
1101
{$server_max_request_size}
1102

    
1103
{$fastcgi_config}
1104

    
1105
{$cgi_config}
1106

    
1107
{$captive_portal_mod_evasive}
1108

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

    
1113
EOD;
1114

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

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

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

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

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

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

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

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

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

    
1198
	return 0;
1199

    
1200
}
1201

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

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

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

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

    
1229
	conf_mount_rw();
1230

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

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

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

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

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

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

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

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

    
1274
	conf_mount_ro();
1275

    
1276
	return true;
1277
}
1278

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

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

    
1288
	safe_mkdir($statsdir);
1289

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

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

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

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

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

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

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

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

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

    
1354
	/* if /var/empty does not exist, create it */
1355
	if(!is_dir("/var/empty"))
1356
		mkdir("/var/empty", 0775, true);
1357

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

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

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

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

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

    
1385
	system_reboot_cleanup();
1386

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

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

    
1393
	system_reboot_cleanup();
1394

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

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

    
1401
	system_reboot_cleanup();
1402

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

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

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

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

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

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

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

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

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

    
1447
	}
1448
}
1449

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

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

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

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

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

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

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

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

    
1491
	fclose($fd);
1492

    
1493
	return 0;
1494
}
1495

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

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

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

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

    
1535
	activate_sysctls();	
1536

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

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

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

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

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

    
1585
	$specplatform = system_identify_specific_platform();
1586

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

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

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

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

    
1602

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

    
1610
	return 0;
1611
}
1612

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

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

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

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

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