Project

General

Profile

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

    
715
	} else {
716
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c -l {$g['dhcpd_chroot_path']}/var/run/log");
717
	}
718

    
719
	if ($g['booting'])
720
		echo gettext("done.") . "\n";
721

    
722
	return $retval;
723
}
724

    
725
function system_pccard_start() {
726
	global $config, $g;
727
	if(isset($config['system']['developerspew'])) {
728
		$mt = microtime();
729
		echo "system_pccard_start() being called $mt\n";
730
	}
731

    
732
	if ($g['booting'])
733
		echo gettext("Initializing PCMCIA...");
734

    
735
	/* kill any running pccardd */
736
	killbypid("{$g['varrun_path']}/pccardd.pid");
737

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

    
741
	if ($g['booting']) {
742
		if ($res == 0)
743
			echo gettext("done.") . "\n";
744
		else
745
			echo gettext("failed!") . "\n";
746
	}
747

    
748
	return $res;
749
}
750

    
751

    
752
function system_webgui_start() {
753
	global $config, $g;
754

    
755
	if ($g['booting'])
756
		echo gettext("Starting webConfigurator...");
757

    
758
	chdir($g['www_path']);
759

    
760
	/* defaults */
761
	$portarg = "80";
762
	$crt = "";
763
	$key = "";
764
	$ca = "";
765

    
766
	/* non-standard port? */
767
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
768
		$portarg = "{$config['system']['webgui']['port']}";
769

    
770
	if ($config['system']['webgui']['protocol'] == "https") {
771
		// Ensure that we have a webConfigurator CERT
772
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
773
		if(!is_array($cert) && !$cert['crt'] && !$cert['prv']) {
774
			if (!is_array($config['ca']))
775
				$config['ca'] = array();
776
			$a_ca =& $config['ca'];
777
			if (!is_array($config['cert']))
778
				$config['cert'] = array();
779
			$a_cert =& $config['cert'];
780
			log_error("Creating SSL Certificate for this host");
781
			$cert = array();
782
			$cert['refid'] = uniqid();
783
			$cert['descr'] = gettext("webConfigurator default");
784
			mwexec("/usr/local/bin/openssl genrsa 1024 > {$g['tmp_path']}/ssl.key");
785
			mwexec("/usr/local/bin/openssl req -new -x509 -nodes -sha256 -days 2000 -key {$g['tmp_path']}/ssl.key > {$g['tmp_path']}/ssl.crt");
786
			$crt = file_get_contents("{$g['tmp_path']}/ssl.crt");
787
			$key = file_get_contents("{$g['tmp_path']}/ssl.key");
788
			unlink("{$g['tmp_path']}/ssl.key");
789
			unlink("{$g['tmp_path']}/ssl.crt");
790
			cert_import($cert, $crt, $key);
791
			$a_cert[] = $cert;
792
			$config['system']['webgui']['ssl-certref'] = $cert['refid'];
793
			write_config(gettext("Importing HTTPS certificate"));
794
			if(!$config['system']['webgui']['port'])
795
				$portarg = "443";
796
			$ca = ca_chain($cert);
797
		} else {
798
			$crt = base64_decode($cert['crt']);
799
			$key = base64_decode($cert['prv']);
800
			if(!$config['system']['webgui']['port'])
801
				$portarg = "443";
802
			$ca = ca_chain($cert);
803
		}
804
	}
805

    
806
	/* generate lighttpd configuration */
807
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
808
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
809
		"cert.pem", "ca.pem");
810

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

    
814
	sleep(1);
815

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

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

    
821
	if ($g['booting']) {
822
		if ($res == 0)
823
			echo gettext("done.") . "\n";
824
		else
825
			echo gettext("failed!") . "\n";
826
	}
827

    
828
	return $res;
829
}
830

    
831
function system_generate_lighty_config($filename,
832
	$cert,
833
	$key,
834
	$ca,
835
	$pid_file,
836
	$port = 80,
837
	$document_root = "/usr/local/www/",
838
	$cert_location = "cert.pem",
839
	$ca_location = "ca.pem",
840
	$captive_portal = false) {
841

    
842
	global $config, $g;
843

    
844
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
845
		mkdir("{$g['tmp_path']}/lighttpdcompress");
846

    
847
	if(isset($config['system']['developerspew'])) {
848
		$mt = microtime();
849
		echo "system_generate_lighty_config() being called $mt\n";
850
	}
851

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

    
856
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
857
		if (empty($maxprocperip))
858
			$maxprocperip = 10;
859
		$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
860

    
861
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
862
		exec("mkdir -p {$g['tmp_path']}/captiveportal");
863
		exec("chmod a-w {$g['tmp_path']}/captiveportal");
864
		$server_max_request_size = "server.max-request-size    = 384";
865
		$cgi_config = "";
866
	} else {
867
		$captiveportal = ",\"mod_cgi\"";
868
		$captive_portal_rewrite = "";
869
		$captive_portal_mod_evasive = "";
870
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
871
		$server_max_request_size = "server.max-request-size    = 2097152";
872
		$cgi_config = "cgi.assign                 = ( \".cgi\" => \"\" )";
873
	}
874
	
875
	if (empty($port))
876
		$lighty_port = "80";
877
	else
878
		$lighty_port = $port;
879

    
880
	$memory = get_memory();
881
	$avail = $memory[1];
882

    
883
	// Determine web GUI process settings and take into account low memory systems
884
	if ($avail < 255)
885
		$max_procs = 1;
886
	else
887
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
888

    
889
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM 
890
	if ($captive_portal !== false)  {
891
		if ($avail > 135 and $avail < 256) {
892
			$max_procs += 1; // 2 worker processes
893
		} else if ($avail > 255 and $avail < 513) {
894
			$max_procs += 2; // 3 worker processes
895
		} else if ($avail > 512) {
896
			$max_procs += 4; // 6 worker processes
897
		}
898
		if ($max_procs > 1)
899
			$max_php_children = intval($max_procs/2);
900
		else
901
			$max_php_children = 1;
902

    
903
	} else {
904
		if ($avail < 78)
905
			$max_php_children = 0;
906
		else
907
			$max_php_children = 1;
908
	}
909

    
910
	if ($captive_portal !== false)
911
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi-{$captive_portal}.socket";
912
	else
913
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi.socket";
914

    
915
	if(!isset($config['syslog']['nologlighttpd'])) {
916
		$lighty_use_syslog = <<<EOD
917
## where to send error-messages to
918
server.errorlog-use-syslog="enable"
919
EOD;
920
	}
921

    
922

    
923
	$fastcgi_config = <<<EOD
924
#### fastcgi module
925
## read fastcgi.txt for more info
926
fastcgi.server = ( ".php" =>
927
	( "localhost" =>
928
		(
929
			"socket" => "{$fast_cgi_path}",
930
			"max-procs" => {$max_procs},
931
			"bin-environment" => (
932
				"PHP_FCGI_CHILDREN" => "{$max_php_children}",
933
				"PHP_FCGI_MAX_REQUESTS" => "500"
934
			),
935
			"bin-path" => "/usr/local/bin/php"
936
		)
937
	)
938
)
939

    
940
EOD;
941

    
942
	$lighty_config = <<<EOD
943
#
944
# lighttpd configuration file
945
#
946
# use a it as base for lighttpd 1.0.0 and above
947
#
948
############ Options you really have to take care of ####################
949

    
950
## FreeBSD!
951
server.event-handler	= "freebsd-kqueue"
952
server.network-backend 	= "writev"
953
#server.use-ipv6 = "enable"
954

    
955
## modules to load
956
server.modules              =   ( "mod_access", "mod_expire", "mod_compress", "mod_redirect",
957
	{$captiveportal}, "mod_fastcgi"
958
)
959

    
960
server.max-keep-alive-requests = 15
961
server.max-keep-alive-idle = 30
962

    
963
## a static document-root, for virtual-hosting take look at the
964
## server.virtual-* options
965
server.document-root        = "{$document_root}"
966
{$captive_portal_rewrite}
967

    
968
# Maximum idle time with nothing being written (php downloading)
969
server.max-write-idle = 999
970

    
971
{$lighty_use_syslog}
972

    
973
# files to check for if .../ is requested
974
server.indexfiles           = ( "index.php", "index.html",
975
                                "index.htm", "default.htm" )
976

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

    
1030
# Use the "Content-Type" extended attribute to obtain mime type if possible
1031
#mimetypes.use-xattr        = "enable"
1032

    
1033
## deny access the file-extensions
1034
#
1035
# ~    is for backupfiles from vi, emacs, joe, ...
1036
# .inc is often used for code includes which should in general not be part
1037
#      of the document-root
1038
url.access-deny             = ( "~", ".inc" )
1039

    
1040

    
1041
######### Options that are good to be but not neccesary to be changed #######
1042

    
1043
## bind to port (default: 80)
1044

    
1045
EOD;
1046

    
1047
	$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1048
	$lighty_config .= "server.port  = {$lighty_port}\n";
1049
	$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1050
	$lighty_config .= "\$SERVER[\"socket\"]  == \"[::]:{$lighty_port}\" { \n";
1051
	if($cert <> "" and $key <> "") {
1052
		$lighty_config .= "\n";
1053
		$lighty_config .= "## ssl configuration\n";
1054
		$lighty_config .= "ssl.engine = \"enable\"\n";
1055
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1056
		if($ca <> "")
1057
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1058
	}
1059
	$lighty_config .= " }\n";
1060

    
1061

    
1062
	$lighty_config .= <<<EOD
1063

    
1064
## error-handler for status 404
1065
#server.error-handler-404   = "/error-handler.html"
1066
#server.error-handler-404   = "/error-handler.php"
1067

    
1068
## to help the rc.scripts
1069
server.pid-file            = "{$g['varrun_path']}/{$pid_file}"
1070

    
1071
## virtual directory listings
1072
server.dir-listing         = "disable"
1073

    
1074
## enable debugging
1075
debug.log-request-header   = "disable"
1076
debug.log-response-header  = "disable"
1077
debug.log-request-handling = "disable"
1078
debug.log-file-not-found   = "disable"
1079

    
1080
# gzip compression
1081
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1082
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1083

    
1084
{$server_upload_dirs}
1085

    
1086
{$server_max_request_size}
1087

    
1088
{$fastcgi_config}
1089

    
1090
{$cgi_config}
1091

    
1092
{$captive_portal_mod_evasive}
1093

    
1094
expire.url = (
1095
				"" => "access 50 hours",	
1096
        )
1097

    
1098
EOD;
1099

    
1100
	$cert = str_replace("\r", "", $cert);
1101
	$key = str_replace("\r", "", $key);
1102
	$ca = str_replace("\r", "", $ca);
1103

    
1104
	$cert = str_replace("\n\n", "\n", $cert);
1105
	$key = str_replace("\n\n", "\n", $key);
1106
	$ca = str_replace("\n\n", "\n", $ca);
1107

    
1108
	if($cert <> "" and $key <> "") {
1109
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1110
		if (!$fd) {
1111
			printf(gettext("Error: cannot open cert.pem in system_webgui_start().%s"), "\n");
1112
			return 1;
1113
		}
1114
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1115
		fwrite($fd, $cert);
1116
		fwrite($fd, "\n");
1117
		fwrite($fd, $key);
1118
		fclose($fd);
1119
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
1120
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1121
			if (!$fd) {
1122
				printf(gettext("Error: cannot open ca.pem in system_webgui_start().%s"), "\n");
1123
				return 1;
1124
			}
1125
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1126
			fwrite($fd, $ca);
1127
			fclose($fd);
1128
		}
1129
		$lighty_config .= "\n";
1130
		$lighty_config .= "## " . gettext("ssl configuration") . "\n";
1131
		$lighty_config .= "ssl.engine = \"enable\"\n";
1132
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1133

    
1134
		// Harden SSL a bit for PCI conformance testing
1135
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
1136

    
1137
		/* Hifn accelerators do NOT work with the BEAST mitigation code. Do not allow it to be enabled if a Hifn card has been detected. */
1138
		$fd = @fopen("{$g['varlog_path']}/dmesg.boot", "r");
1139
		if ($fd) {
1140
			while (!feof($fd)) {
1141
				$dmesgl = fgets($fd);
1142
				if (preg_match("/^hifn.: (.*?),/", $dmesgl, $matches) && isset($config['system']['webgui']['beast_protection'])) {
1143
						unset($config['system']['webgui']['beast_protection']);
1144
						log_error("BEAST Protection disabled because a conflicting cryptographic accelerator card has been detected (" . $matches[1] . ")");
1145
					break;
1146
				}
1147
			}
1148
			fclose($fd);
1149
		}
1150

    
1151
		if (isset($config['system']['webgui']['beast_protection'])) {
1152
			$lighty_config .= "ssl.honor-cipher-order = \"enable\"\n";
1153
			$lighty_config .= "ssl.cipher-list = \"ECDHE-RSA-AES256-SHA384:AES256-SHA256:RC4-SHA:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM\"\n";
1154
		} else {
1155
			$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";
1156
		}
1157

    
1158
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1159
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1160
	}
1161

    
1162
	// Add HTTP to HTTPS redirect	
1163
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1164
		if($lighty_port != "443") 
1165
			$redirectport = ":{$lighty_port}";
1166
		$lighty_config .= <<<EOD
1167
\$SERVER["socket"] == ":80" {
1168
	\$HTTP["host"] =~ "(.*)" {
1169
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1170
	}
1171
}
1172
EOD;
1173
	}
1174

    
1175
	$fd = fopen("{$filename}", "w");
1176
	if (!$fd) {
1177
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1178
		return 1;
1179
	}
1180
	fwrite($fd, $lighty_config);
1181
	fclose($fd);
1182

    
1183
	return 0;
1184

    
1185
}
1186

    
1187
function system_timezone_configure() {
1188
	global $config, $g;
1189
	if(isset($config['system']['developerspew'])) {
1190
		$mt = microtime();
1191
		echo "system_timezone_configure() being called $mt\n";
1192
	}
1193

    
1194
	$syscfg = $config['system'];
1195

    
1196
	if ($g['booting'])
1197
		echo gettext("Setting timezone...");
1198

    
1199
	/* extract appropriate timezone file */
1200
	$timezone = $syscfg['timezone'];
1201
	if (!$timezone)
1202
		$timezone = "Etc/UTC";
1203

    
1204
	conf_mount_rw();
1205

    
1206
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1207
		escapeshellarg($timezone) . " > /etc/localtime");
1208

    
1209
	mwexec("sync");
1210
	conf_mount_ro();
1211

    
1212
	if ($g['booting'])
1213
		echo gettext("done.") . "\n";
1214
}
1215

    
1216
function system_ntp_setup_gps($serialport) {
1217
	$gps_device = '/dev/gps0';
1218
	$serialport = '/dev/'.$serialport;
1219

    
1220
	if (!file_exists($serialport))
1221
		return false;
1222

    
1223
	conf_mount_rw();
1224
	// Create symlink that ntpd requires
1225
	unlink_if_exists($gps_device);
1226
	symlink($serialport, $gps_device);
1227

    
1228
	/* Send the following to the GPS port to initialize the GPS */
1229
	$gps_init = <<<EOF
1230
\$PUBX,40,GSV,0,0,0,0*59
1231
\$PUBX,40,GLL,0,0,0,0*5C
1232
\$PUBX,40,ZDA,0,0,0,0*44
1233
\$PUBX,40,VTG,0,0,0,0*5E
1234
\$PUBX,40,GSV,0,0,0,0*59
1235
\$PUBX,40,GSA,0,0,0,0*4E
1236
\$PUBX,40,GGA,0,0,0,0
1237
\$PUBX,40,TXT,0,0,0,0
1238
\$PUBX,40,RMC,0,0,0,0*46
1239
\$PUBX,41,1,0007,0003,4800,0
1240
\$PUBX,40,ZDA,1,1,1,1
1241
EOF;
1242
	file_put_contents("/tmp/gps.init", $gps_init);
1243
	`cat /tmp/gps.init > $serialport`;
1244

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

    
1249
	conf_mount_ro();
1250

    
1251
	return true;
1252
}
1253

    
1254
function system_ntp_configure($start_ntpd=true) {
1255
	global $config, $g;
1256
	$driftfile = "/var/db/ntpd.drift";
1257
	$statsdir = "/var/log/ntp";
1258
	$gps_device = '/dev/gps0';
1259

    
1260
	if ($g['platform'] == 'jail')
1261
		return;
1262

    
1263
	safe_mkdir($statsdir);
1264

    
1265
	$ntpcfg = "# \n";
1266
	$ntpcfg .= "# pfSense ntp configuration file \n";
1267
	$ntpcfg .= "# \n\n";
1268
	$ntpcfg .= "tinker panic 0 \n";
1269

    
1270
	if (!empty($config['ntpd']['gpsport'])
1271
		&& file_exists('/dev/'.$config['ntpd']['gpsport'])
1272
		&& system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1273
		$ntpcfg .= "# GPS Setup\n";
1274
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1275
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1276
		// Fall back to local clock if GPS is out of sync?
1277
		$ntpcfg .= "server 127.127.1.0\n";
1278
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1279
	}
1280

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

    
1286
	$ntpcfg .= "enable monitor\n";
1287
	$ntpcfg .= "enable stats\n";
1288
	$ntpcfg .= "statistics clockstats\n";
1289
	$ntpcfg .= "statsdir {$statsdir}\n";
1290
	$ntpcfg .= "logconfig =syncall +clockall\n";
1291
	$ntpcfg .= "driftfile {$driftfile}\n";
1292
	$ntpcfg .= "restrict default kod nomodify notrap nopeer\n";
1293
	$ntpcfg .= "restrict -6 default kod nomodify notrap nopeer\n";
1294

    
1295
	if (empty($config['ntpd']['interface']))
1296
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface']))
1297
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1298
		else
1299
			$interfaces = array();
1300
	else
1301
		$interfaces = explode(",", $config['ntpd']['interface']);
1302

    
1303
	if (is_array($interfaces) && count($interfaces)) {
1304
		$ntpcfg .= "interface ignore all\n";
1305
		foreach ($interfaces as $interface) {
1306
			if (!is_ipaddr($interface)) {
1307
				$interface = get_real_interface($interface);
1308
			}
1309
			$ntpcfg .= "interface listen {$interface}\n";
1310
		}
1311
	}
1312

    
1313
	/* open configuration for wrting or bail */
1314
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
1315
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1316
		return;
1317
	}
1318

    
1319
	/* At bootup we just want to write out the config. */
1320
	if (!$start_ntpd)
1321
		return;
1322

    
1323
	/* if ntpd is running, kill it */
1324
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1325
		killbypid("{$g['varrun_path']}/ntpd.pid");
1326
	}
1327
	@unlink("{$g['varrun_path']}/ntpd.pid");
1328

    
1329
	/* if /var/empty does not exist, create it */
1330
	if(!is_dir("/var/empty"))
1331
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1332

    
1333
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1334
	mwexec("/usr/local/bin/ntpd -g -c {$g['varetc_path']}/ntpd.conf -p {$g['varrun_path']}/ntpd.pid", false, true);
1335
	
1336
	// Note that we are starting up
1337
	log_error("NTPD is starting up.");
1338
	return;
1339
}
1340

    
1341
function sync_system_time() {
1342
	global $config, $g;
1343

    
1344
	if ($g['booting'])
1345
		echo gettext("Syncing system time before startup...");
1346

    
1347
	/* foreach through servers and write out to ntpd.conf */
1348
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1349
		mwexec("/usr/sbin/ntpdate -s $ts");
1350
	}
1351
	
1352
	if ($g['booting'])
1353
		echo gettext("done.") . "\n";
1354
	
1355
}
1356

    
1357
function system_halt() {
1358
	global $g;
1359

    
1360
	system_reboot_cleanup();
1361

    
1362
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1363
}
1364

    
1365
function system_reboot() {
1366
	global $g;
1367

    
1368
	system_reboot_cleanup();
1369

    
1370
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1371
}
1372

    
1373
function system_reboot_sync() {
1374
	global $g;
1375

    
1376
	system_reboot_cleanup();
1377

    
1378
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1379
}
1380

    
1381
function system_reboot_cleanup() {
1382
	global $config, $cpzone;
1383

    
1384
	mwexec("/usr/local/bin/beep.sh stop");
1385
	require_once("captiveportal.inc");
1386
	if (is_array($config['captiveportal'])) {
1387
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
1388
			captiveportal_radius_stop_all();
1389
			captiveportal_send_server_accounting(true);
1390
		}
1391
	}
1392
	require_once("voucher.inc");
1393
	voucher_save_db_to_config();
1394
	require_once("pkg-utils.inc");
1395
	stop_packages();
1396
}
1397

    
1398
function system_do_shell_commands($early = 0) {
1399
	global $config, $g;
1400
	if(isset($config['system']['developerspew'])) {
1401
		$mt = microtime();
1402
		echo "system_do_shell_commands() being called $mt\n";
1403
	}
1404

    
1405
	if ($early)
1406
		$cmdn = "earlyshellcmd";
1407
	else
1408
		$cmdn = "shellcmd";
1409

    
1410
	if (is_array($config['system'][$cmdn])) {
1411

    
1412
		/* *cmd is an array, loop through */
1413
		foreach ($config['system'][$cmdn] as $cmd) {
1414
			exec($cmd);
1415
		}
1416

    
1417
	} elseif($config['system'][$cmdn] <> "") {
1418

    
1419
		/* execute single item */
1420
		exec($config['system'][$cmdn]);
1421

    
1422
	}
1423
}
1424

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

    
1432
	if (isset($config['system']['disableconsolemenu'])) {
1433
		touch("{$g['varetc_path']}/disableconsole");
1434
	} else {
1435
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1436
	}
1437
}
1438

    
1439
function system_dmesg_save() {
1440
	global $g;
1441
	if(isset($config['system']['developerspew'])) {
1442
		$mt = microtime();
1443
		echo "system_dmesg_save() being called $mt\n";
1444
	}
1445

    
1446
	$dmesg = "";
1447
	exec("/sbin/dmesg", $dmesg);
1448

    
1449
	/* find last copyright line (output from previous boots may be present) */
1450
	$lastcpline = 0;
1451

    
1452
	for ($i = 0; $i < count($dmesg); $i++) {
1453
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1454
			$lastcpline = $i;
1455
	}
1456

    
1457
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1458
	if (!$fd) {
1459
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1460
		return 1;
1461
	}
1462

    
1463
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1464
		fwrite($fd, $dmesg[$i] . "\n");
1465

    
1466
	fclose($fd);
1467

    
1468
	return 0;
1469
}
1470

    
1471
function system_set_harddisk_standby() {
1472
	global $g, $config;
1473
	if(isset($config['system']['developerspew'])) {
1474
		$mt = microtime();
1475
		echo "system_set_harddisk_standby() being called $mt\n";
1476
	}
1477

    
1478
	if (isset($config['system']['harddiskstandby'])) {
1479
		if ($g['booting']) {
1480
			echo gettext('Setting hard disk standby... ');
1481
		}
1482

    
1483
		$standby = $config['system']['harddiskstandby'];
1484
		// Check for a numeric value
1485
		if (is_numeric($standby)) {
1486
			// Sync the disk(s)
1487
			pfSense_sync();
1488
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1489
				// Reinitialize ATA-drives
1490
				mwexec('/usr/local/sbin/atareinit');
1491
				if ($g['booting']) {
1492
					echo gettext("done.") . "\n";
1493
				}
1494
			} else if ($g['booting']) {
1495
				echo gettext("failed!") . "\n";
1496
			}
1497
		} else if ($g['booting']) {
1498
			echo gettext("failed!") . "\n";
1499
		}
1500
	}
1501
}
1502

    
1503
function system_setup_sysctl() {
1504
	global $config;
1505
	if(isset($config['system']['developerspew'])) {
1506
		$mt = microtime();
1507
		echo "system_setup_sysctl() being called $mt\n";
1508
	}
1509

    
1510
	activate_sysctls();	
1511

    
1512
	if (isset($config['system']['sharednet'])) {
1513
		system_disable_arp_wrong_if();
1514
	}
1515
}
1516

    
1517
function system_disable_arp_wrong_if() {
1518
	global $config;
1519
	if(isset($config['system']['developerspew'])) {
1520
		$mt = microtime();
1521
		echo "system_disable_arp_wrong_if() being called $mt\n";
1522
	}
1523
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1524
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1525
}
1526

    
1527
function system_enable_arp_wrong_if() {
1528
	global $config;
1529
	if(isset($config['system']['developerspew'])) {
1530
		$mt = microtime();
1531
		echo "system_enable_arp_wrong_if() being called $mt\n";
1532
	}
1533
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1534
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1535
}
1536

    
1537
function enable_watchdog() {
1538
	global $config;
1539
	return;
1540
	$install_watchdog = false;
1541
	$supported_watchdogs = array("Geode");
1542
	$file = file_get_contents("/var/log/dmesg.boot");
1543
	foreach($supported_watchdogs as $sd) {
1544
		if(stristr($file, "Geode")) {
1545
			$install_watchdog = true;
1546
		}
1547
	}
1548
	if($install_watchdog == true) {
1549
		if(is_process_running("watchdogd"))
1550
			mwexec("/usr/bin/killall watchdogd", true);
1551
		exec("/usr/sbin/watchdogd");
1552
	}
1553
}
1554

    
1555
function system_check_reset_button() {
1556
	global $g;
1557
	if($g['platform'] != "nanobsd")
1558
		return 0;
1559

    
1560
	$specplatform = system_identify_specific_platform();
1561

    
1562
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1563
		return 0;
1564

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

    
1567
	if ($retval == 99) {
1568
		/* user has pressed reset button for 2 seconds - 
1569
		   reset to factory defaults */
1570
		echo <<<EOD
1571

    
1572
***********************************************************************
1573
* Reset button pressed - resetting configuration to factory defaults. *
1574
* The system will reboot after this completes.                        *
1575
***********************************************************************
1576

    
1577

    
1578
EOD;
1579
		
1580
		reset_factory_defaults();
1581
		system_reboot_sync();
1582
		exit(0);
1583
	}
1584

    
1585
	return 0;
1586
}
1587

    
1588
/* attempt to identify the specific platform (for embedded systems)
1589
   Returns an array with two elements:
1590
	name => platform string (e.g. 'wrap', 'alix' etc.)
1591
	descr => human-readable description (e.g. "PC Engines WRAP")
1592
*/
1593
function system_identify_specific_platform() {
1594
	global $g;
1595
	
1596
	if ($g['platform'] == 'generic-pc')
1597
		return array('name' => 'generic-pc', 'descr' => gettext("Generic PC"));
1598
	
1599
	if ($g['platform'] == 'generic-pc-cdrom')
1600
		return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)"));
1601
	
1602
	/* the rest of the code only deals with 'embedded' platforms */
1603
	if ($g['platform'] != 'nanobsd')
1604
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1605
	
1606
	$dmesg = system_get_dmesg_boot();
1607
	
1608
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1609
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
1610
	
1611
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1612
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
1613

    
1614
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1615
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1616
	
1617
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1618
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1619
		
1620
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1621
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1622
	
1623
	/* unknown embedded platform */
1624
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
1625
}
1626

    
1627
function system_get_dmesg_boot() {
1628
	global $g;
1629
		
1630
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1631
}
1632

    
1633
function get_possible_listen_ips($include_ipv6_link_local=false) {
1634
	$interfaces = get_configured_interface_with_descr();
1635
	$carplist = get_configured_carp_interface_list();
1636
	$listenips = array();
1637
	foreach ($carplist as $cif => $carpip)
1638
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1639
	$aliaslist = get_configured_ip_aliases_list();
1640
	foreach ($aliaslist as $aliasip => $aliasif)
1641
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1642
	foreach ($interfaces as $iface => $ifacename) {
1643
		$tmp["name"]  = $ifacename;
1644
		$tmp["value"] = $iface;
1645
		$listenips[] = $tmp;
1646
		if ($include_ipv6_link_local) {
1647
			$llip = find_interface_ipv6_ll(get_real_interface($iface));
1648
			if (!empty($llip)) {
1649
				$tmp["name"]  = "{$ifacename} IPv6 Link-Local";
1650
				$tmp["value"] = $llip;
1651
				$listenips[] = $tmp;
1652
			}
1653
		}
1654
	}
1655
	$tmp["name"]  = "Localhost";
1656
	$tmp["value"] = "lo0";
1657
	$listenips[] = $tmp;
1658
	return $listenips;
1659
}
1660

    
1661
function get_possible_traffic_source_addresses($include_ipv6_link_local=false) {
1662
	global $config;
1663
	$sourceips = get_possible_listen_ips($include_ipv6_link_local);
1664
	foreach (array('server', 'client') as $mode) {
1665
		if (is_array($config['openvpn']["openvpn-{$mode}"])) {
1666
			foreach ($config['openvpn']["openvpn-{$mode}"] as $id => $setting) {
1667
				if (!isset($setting['disable'])) {
1668
					$vpn = array();
1669
					$vpn['value'] = 'ovpn' . substr($mode, 0, 1) . $setting['vpnid'];
1670
					$vpn['name'] = gettext("OpenVPN") . " ".$mode.": ".htmlspecialchars($setting['description']);
1671
					$sourceips[] = $vpn;
1672
				}
1673
			}
1674
		}
1675
	}
1676
	return $sourceips;
1677
}
1678
?>
(52-52/66)