Project

General

Profile

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
169
	unlock($dnslock);
170

    
171
	return 0;
172
}
173

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

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

    
193
	return $master_list;
194
}
195

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

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

    
224
	return $master_list;
225
}
226

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

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

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

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

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

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

    
291
		if (isset($dnsmasqcfg['dhcpfirst']))
292
			$hosts .= $dhosts . $lhosts;
293
		else
294
			$hosts .= $lhosts . $dhosts;
295
	}
296

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

    
313
	system_dhcpleases_configure();
314

    
315
	return 0;
316
}
317

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

    
339
function system_hostname_configure() {
340
	global $config, $g;
341
	if(isset($config['system']['developerspew'])) {
342
		$mt = microtime();
343
		echo "system_hostname_configure() being called $mt\n";
344
	}
345

    
346
	$syscfg = $config['system'];
347

    
348
	/* set hostname */
349
	$status = mwexec("/bin/hostname " .
350
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
351

    
352
    /* Setup host GUID ID.  This is used by ZFS. */
353
	mwexec("/etc/rc.d/hostid start");
354

    
355
	return $status;
356
}
357

    
358
function system_routing_configure($interface = "") {
359
	global $config, $g;
360
	if ($g['platform'] == 'jail')
361
		return;
362
	if(isset($config['system']['developerspew'])) {
363
		$mt = microtime();
364
		echo "system_routing_configure() being called $mt\n";
365
	}
366

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

    
432
	if ($dont_add_route == false ) {
433
		if (!empty($interface) && $interface != $interfacegw)
434
			;
435
		else if (($interfacegw <> "bgpd") && (is_ipaddrv4($gatewayip))) {
436
			log_error("ROUTING: setting default route to $gatewayip");
437
			mwexec("/sbin/route change -inet default " . escapeshellarg($gatewayip));
438
		}
439

    
440
		if (!empty($interface) && $interface != $interfacegwv6)
441
			;
442
		else if (($interfacegwv6 <> "bgpd") && (is_ipaddrv6($gatewayipv6))) {
443
			$ifscope = "";
444
			if (is_linklocal($gatewayipv6))
445
				$ifscope = "%{$defaultifv6}";
446
			log_error("ROUTING: setting IPv6 default route to {$gatewayipv6}{$ifscope}");
447
			mwexec("/sbin/route change -inet6 default " . escapeshellarg($gatewayipv6) ."{$ifscope}");
448
		}
449
	}
450

    
451
	system_staticroutes_configure($interface, false);
452

    
453
	return 0;
454
}
455

    
456
function system_staticroutes_configure($interface = "", $update_dns = false) {
457
	global $config, $g, $aliastable;
458

    
459
	$filterdns_list = array();
460

    
461
	$static_routes = get_staticroutes(false, true);
462
	if (count($static_routes)) {
463
		$gateways_arr = return_gateways_array(false, true);
464

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

    
474
			$gatewayip = $gateway['gateway'];
475
			$interfacegw = $gateway['interface'];
476

    
477
			$blackhole = "";
478
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 3)))
479
				$blackhole = "-blackhole";
480

    
481
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network']))
482
				continue;
483

    
484
			$dnscache = array();
485
			if ($update_dns === true) {
486
				if (is_subnet($rtent['network']))
487
					continue;
488
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
489
				if (empty($dnscache))
490
					continue;
491
			}
492

    
493
			if (is_subnet($rtent['network']))
494
				$ips = array($rtent['network']);
495
			else {
496
				if (!isset($rtent['disabled']))
497
					$filterdns_list[] = $rtent['network'];
498
				$ips = add_hostname_to_watch($rtent['network']);
499
			}
500

    
501
			foreach ($dnscache as $ip) {
502
				if (in_array($ip, $ips))
503
					continue;
504
				mwexec("/sbin/route delete " . escapeshellarg($ip), true);
505
			}
506

    
507
			if (isset($rtent['disabled'])) {
508
				/* XXX: This is a bit dangerous in case of routing daemons!? */
509
				foreach ($ips as $ip)
510
					mwexec("/sbin/route delete " . escapeshellarg($ip), true);
511
				continue;
512
			}
513

    
514
			foreach ($ips as $ip) {
515
				if (is_ipaddrv4($ip))
516
					$ip .= "/32";
517
				else if (is_ipaddrv6($ip))
518
					$ip .= "/128";
519

    
520
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
521

    
522
				$cmd = "/sbin/route change {$inet} {$blackhole} " . escapeshellarg($ip) . " ";
523

    
524
				if (is_subnet($ip))
525
					if (is_ipaddr($gatewayip))
526
						mwexec($cmd . escapeshellarg($gatewayip));
527
					else if (!empty($interfacegw))
528
						mwexec($cmd . "-iface " . escapeshellarg($interfacegw));
529
			}
530
		}
531
		unset($gateways_arr);
532
	}
533
	unset($static_routes);
534

    
535
	if ($update_dns === false) {
536
		if (count($filterdns_list)) {
537
			$interval = 60;
538
			$hostnames = "";
539
			array_unique($filterdns_list);
540
			foreach ($filterdns_list as $hostname)
541
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
542
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
543
			unset($hostnames);
544

    
545
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid"))
546
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
547
			else
548
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
549
		} else {
550
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
551
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
552
		}
553
	}
554
	unset($filterdns_list);
555

    
556
	return 0;
557
}
558

    
559
function system_routing_enable() {
560
	global $config, $g;
561
	if(isset($config['system']['developerspew'])) {
562
		$mt = microtime();
563
		echo "system_routing_enable() being called $mt\n";
564
	}
565

    
566
	mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
567
	mwexec("/sbin/sysctl net.inet6.ip6.forwarding=1");
568
	return;
569
}
570

    
571
function system_syslogd_fixup_server($server) {
572
	/* If it's an IPv6 IP alone, encase it in brackets */
573
	if (is_ipaddrv6($server))
574
		return "[$server]";
575
	else
576
		return $server;
577
}
578

    
579
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
580
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
581
	$facility .= " ".
582
	$remote_servers = "";
583
	$pad_to  = 56;
584
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
585
	if($syslogcfg['remoteserver'])
586
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
587
	if($syslogcfg['remoteserver2'])
588
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
589
	if($syslogcfg['remoteserver3'])
590
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
591
	return $remote_servers;
592
}
593

    
594
function system_syslogd_start() {
595
	global $config, $g;
596
	if(isset($config['system']['developerspew'])) {
597
		$mt = microtime();
598
		echo "system_syslogd_start() being called $mt\n";
599
	}
600

    
601
	mwexec("/etc/rc.d/hostid start");
602

    
603
	$syslogcfg = $config['syslog'];
604

    
605
	if ($g['booting'])
606
		echo gettext("Starting syslog...");
607
	else
608
		killbypid("{$g['varrun_path']}/syslog.pid");
609

    
610
	if (is_process_running("syslogd"))
611
		mwexec('/bin/pkill syslogd');
612
	if (is_process_running("fifolog_writer"))
613
		mwexec('/bin/pkill fifolog_writer');
614

    
615
	// Which logging type are we using this week??
616
	if (isset($config['system']['disablesyslogclog'])) {
617
		$log_directive = "";
618
		$log_create_directive = "/usr/bin/touch ";
619
		$log_size = "";
620
	} else if (isset($config['system']['usefifolog'])) {
621
		$log_directive = "|/usr/sbin/fifolog_writer ";
622
		$log_size = "10240";
623
		$log_create_directive = "/usr/sbin/fifolog_create -s ";
624
	} else { // Defaults to CLOG
625
		$log_directive = "%";
626
		$log_size = "10240";
627
		$log_create_directive = "/usr/sbin/clog -i -s ";
628
	}
629
	
630
	if (isset($syslogcfg)) {
631
		$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');
632
		$syslogconf = "";
633
		if($config['installedpackages']['package']) {
634
			foreach($config['installedpackages']['package'] as $package) {
635
				if($package['logging']) {
636
					array_push($separatelogfacilities, $package['logging']['facilityname']);
637
					mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
638
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
639
				}
640
			}
641
		}
642
		$facilitylist = implode(',', array_unique($separatelogfacilities));
643
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd,miniupnpd\n";
644
		if (!isset($syslogcfg['disablelocallogging']))
645
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
646

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

    
651
		$syslogconf .= "!ppp\n";
652
		if (!isset($syslogcfg['disablelocallogging'])) 
653
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
654

    
655
		$syslogconf .= "!pptps\n";
656
		if (!isset($syslogcfg['disablelocallogging'])) 
657
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/pptps.log\n";
658

    
659
		$syslogconf .= "!poes\n";
660
		if (!isset($syslogcfg['disablelocallogging'])) 
661
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
662

    
663
		$syslogconf .= "!l2tps\n";
664
		if (!isset($syslogcfg['disablelocallogging'])) 
665
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/l2tps.log\n";
666

    
667
		$syslogconf .= "!racoon\n";
668
		if (!isset($syslogcfg['disablelocallogging'])) 
669
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ipsec.log\n";
670
		if (isset($syslogcfg['vpn']))
671
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
672

    
673
		$syslogconf .= "!openvpn\n";
674
		if (!isset($syslogcfg['disablelocallogging'])) 
675
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/openvpn.log\n";
676
		if (isset($syslogcfg['vpn']))
677
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
678

    
679
		$syslogconf .= "!apinger\n";
680
		if (!isset($syslogcfg['disablelocallogging']))
681
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/gateways.log\n";
682
		if (isset($syslogcfg['apinger']))
683
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
684

    
685
		$syslogconf .= "!dnsmasq,filterdns,unbound\n";
686
		if (!isset($syslogcfg['disablelocallogging']))
687
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
688
		if (isset($syslogcfg['apinger']))
689
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
690

    
691
		$syslogconf .= "!dhcpd,dhcrelay,dhclient\n";
692
		if (!isset($syslogcfg['disablelocallogging']))
693
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/dhcpd.log\n";
694
		if (isset($syslogcfg['apinger']))
695
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
696

    
697
		$syslogconf .= "!relayd\n";
698
		if (!isset($syslogcfg['disablelocallogging']))
699
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/relayd.log\n";
700
		if (isset($syslogcfg['relayd']))
701
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
702

    
703
		$syslogconf .= "!hostapd\n";
704
		if (!isset($syslogcfg['disablelocallogging']))
705
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
706
		if (isset($syslogcfg['hostapd']))
707
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
708

    
709
		$syslogconf .= "!-{$facilitylist}\n";
710
		if (!isset($syslogcfg['disablelocallogging'])) 
711
			$syslogconf .= <<<EOD
712
local0.*							{$log_directive}{$g['varlog_path']}/filter.log
713
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
714
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
715
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
716
*.notice;kern.debug;lpr.info;mail.crit;daemon.none;		{$log_directive}{$g['varlog_path']}/system.log
717
news.err;local0.none;local3.none;local4.none;			{$log_directive}{$g['varlog_path']}/system.log
718
local7.none							{$log_directive}{$g['varlog_path']}/system.log
719
security.*							{$log_directive}{$g['varlog_path']}/system.log
720
auth.info;authpriv.info;daemon.info				{$log_directive}{$g['varlog_path']}/system.log
721
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
722
*.emerg								*
723

    
724
EOD;
725
		if (isset($syslogcfg['filter']))
726
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local0.*");
727
		if (isset($syslogcfg['vpn']))
728
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
729
		if (isset($syslogcfg['portalauth']))
730
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
731
		if (isset($syslogcfg['dhcp']))
732
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
733
		if (isset($syslogcfg['system'])) {
734
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.notice;kern.debug;lpr.info;mail.crit;");
735
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "news.err;local0.none;local3.none;local7.none");
736
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "security.*");
737
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "auth.info;authpriv.info;daemon.info");
738
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.emerg");
739
		}
740
		if (isset($syslogcfg['logall'])) {
741
			// Make everything mean everything, including facilities excluded above.
742
			$syslogconf .= "!*\n";
743
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
744
		}
745

    
746
		if (isset($syslogcfg['zmqserver'])) {
747
				$syslogconf .= <<<EOD
748
*.*								^{$syslogcfg['zmqserver']}
749

    
750
EOD;
751
		}
752
		/* write syslog.conf */		
753
		if (!@file_put_contents("{$g['varetc_path']}/syslog.conf", $syslogconf)) {
754
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
755
			unset($syslogconf);
756
			return 1;
757
		}
758
		unset($syslogconf);
759

    
760
		// Ensure that the log directory exists
761
		if (!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
762
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
763

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

    
766
	} else {
767
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c -l {$g['dhcpd_chroot_path']}/var/run/log");
768
	}
769

    
770
	if ($g['booting'])
771
		echo gettext("done.") . "\n";
772

    
773
	return $retval;
774
}
775

    
776
function system_pccard_start() {
777
	global $config, $g;
778
	if(isset($config['system']['developerspew'])) {
779
		$mt = microtime();
780
		echo "system_pccard_start() being called $mt\n";
781
	}
782

    
783
	if ($g['booting'])
784
		echo gettext("Initializing PCMCIA...");
785

    
786
	/* kill any running pccardd */
787
	killbypid("{$g['varrun_path']}/pccardd.pid");
788

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

    
792
	if ($g['booting']) {
793
		if ($res == 0)
794
			echo gettext("done.") . "\n";
795
		else
796
			echo gettext("failed!") . "\n";
797
	}
798

    
799
	return $res;
800
}
801

    
802

    
803
function system_webgui_start() {
804
	global $config, $g;
805

    
806
	if ($g['booting'])
807
		echo gettext("Starting webConfigurator...");
808

    
809
	chdir($g['www_path']);
810

    
811
	/* defaults */
812
	$portarg = "80";
813
	$crt = "";
814
	$key = "";
815
	$ca = "";
816

    
817
	/* non-standard port? */
818
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
819
		$portarg = "{$config['system']['webgui']['port']}";
820

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

    
857
	/* generate lighttpd configuration */
858
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
859
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
860
		"cert.pem", "ca.pem");
861

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

    
865
	sleep(1);
866

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

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

    
872
	if ($g['booting']) {
873
		if ($res == 0)
874
			echo gettext("done.") . "\n";
875
		else
876
			echo gettext("failed!") . "\n";
877
	}
878

    
879
	return $res;
880
}
881

    
882
function system_generate_lighty_config($filename,
883
	$cert,
884
	$key,
885
	$ca,
886
	$pid_file,
887
	$port = 80,
888
	$document_root = "/usr/local/www/",
889
	$cert_location = "cert.pem",
890
	$ca_location = "ca.pem",
891
	$captive_portal = false) {
892

    
893
	global $config, $g;
894

    
895
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
896
		mkdir("{$g['tmp_path']}/lighttpdcompress");
897

    
898
	if(isset($config['system']['developerspew'])) {
899
		$mt = microtime();
900
		echo "system_generate_lighty_config() being called $mt\n";
901
	}
902

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

    
907
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
908
		if (empty($maxprocperip))
909
			$maxprocperip = 10;
910
		$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
911

    
912
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
913
		exec("mkdir -p {$g['tmp_path']}/captiveportal");
914
		exec("chmod a-w {$g['tmp_path']}/captiveportal");
915
		$server_max_request_size = "server.max-request-size    = 384";
916
		$cgi_config = "";
917
	} else {
918
		$captiveportal = ",\"mod_cgi\"";
919
		$captive_portal_rewrite = "";
920
		$captive_portal_mod_evasive = "";
921
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
922
		$server_max_request_size = "server.max-request-size    = 2097152";
923
		$cgi_config = "cgi.assign                 = ( \".cgi\" => \"\" )";
924
	}
925
	
926
	if (empty($port))
927
		$lighty_port = "80";
928
	else
929
		$lighty_port = $port;
930

    
931
	$memory = get_memory();
932
	$avail = $memory[1];
933

    
934
	// Determine web GUI process settings and take into account low memory systems
935
	if ($avail < 255)
936
		$max_procs = 1;
937
	else
938
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
939

    
940
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM 
941
	if ($captive_portal !== false)  {
942
		if ($avail > 135 and $avail < 256) {
943
			$max_procs += 1; // 2 worker processes
944
		} else if ($avail > 255 and $avail < 513) {
945
			$max_procs += 2; // 3 worker processes
946
		} else if ($avail > 512) {
947
			$max_procs += 4; // 6 worker processes
948
		}
949
		if ($max_procs > 1)
950
			$max_php_children = intval($max_procs/2);
951
		else
952
			$max_php_children = 1;
953

    
954
	} else {
955
		if ($avail < 78)
956
			$max_php_children = 0;
957
		else
958
			$max_php_children = 1;
959
	}
960

    
961
	if ($captive_portal !== false)
962
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi-{$captive_portal}.socket";
963
	else
964
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi.socket";
965

    
966
	$fastcgi_config = <<<EOD
967
#### fastcgi module
968
## read fastcgi.txt for more info
969
fastcgi.server = ( ".php" =>
970
	( "localhost" =>
971
		(
972
			"socket" => "{$fast_cgi_path}",
973
			"max-procs" => {$max_procs},
974
			"bin-environment" => (
975
				"PHP_FCGI_CHILDREN" => "{$max_php_children}",
976
				"PHP_FCGI_MAX_REQUESTS" => "500"
977
			),
978
			"bin-path" => "/usr/local/bin/php"
979
		)
980
	)
981
)
982

    
983
EOD;
984

    
985
	$lighty_config = <<<EOD
986
#
987
# lighttpd configuration file
988
#
989
# use a it as base for lighttpd 1.0.0 and above
990
#
991
############ Options you really have to take care of ####################
992

    
993
## FreeBSD!
994
server.event-handler	= "freebsd-kqueue"
995
server.network-backend 	= "writev"
996
#server.use-ipv6 = "enable"
997

    
998
## modules to load
999
server.modules              =   ( "mod_access", "mod_expire", "mod_compress", "mod_redirect",
1000
	{$captiveportal}, "mod_fastcgi"
1001
)
1002

    
1003
server.max-keep-alive-requests = 15
1004
server.max-keep-alive-idle = 30
1005

    
1006
## a static document-root, for virtual-hosting take look at the
1007
## server.virtual-* options
1008
server.document-root        = "{$document_root}"
1009
{$captive_portal_rewrite}
1010

    
1011
# Maximum idle time with nothing being written (php downloading)
1012
server.max-write-idle = 999
1013

    
1014
## where to send error-messages to
1015
server.errorlog-use-syslog="enable"
1016

    
1017
# files to check for if .../ is requested
1018
server.indexfiles           = ( "index.php", "index.html",
1019
                                "index.htm", "default.htm" )
1020

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

    
1074
# Use the "Content-Type" extended attribute to obtain mime type if possible
1075
#mimetypes.use-xattr        = "enable"
1076

    
1077
## deny access the file-extensions
1078
#
1079
# ~    is for backupfiles from vi, emacs, joe, ...
1080
# .inc is often used for code includes which should in general not be part
1081
#      of the document-root
1082
url.access-deny             = ( "~", ".inc" )
1083

    
1084

    
1085
######### Options that are good to be but not neccesary to be changed #######
1086

    
1087
## bind to port (default: 80)
1088

    
1089
EOD;
1090

    
1091
	$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1092
	$lighty_config .= "server.port  = {$lighty_port}\n";
1093
	$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1094
	$lighty_config .= "\$SERVER[\"socket\"]  == \"[::]:{$lighty_port}\" { \n";
1095
	if($cert <> "" and $key <> "") {
1096
		$lighty_config .= "\n";
1097
		$lighty_config .= "## ssl configuration\n";
1098
		$lighty_config .= "ssl.engine = \"enable\"\n";
1099
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1100
		if($ca <> "")
1101
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1102
	}
1103
	$lighty_config .= " }\n";
1104

    
1105

    
1106
	$lighty_config .= <<<EOD
1107

    
1108
## error-handler for status 404
1109
#server.error-handler-404   = "/error-handler.html"
1110
#server.error-handler-404   = "/error-handler.php"
1111

    
1112
## to help the rc.scripts
1113
server.pid-file            = "{$g['varrun_path']}/{$pid_file}"
1114

    
1115
## virtual directory listings
1116
server.dir-listing         = "disable"
1117

    
1118
## enable debugging
1119
debug.log-request-header   = "disable"
1120
debug.log-response-header  = "disable"
1121
debug.log-request-handling = "disable"
1122
debug.log-file-not-found   = "disable"
1123

    
1124
# gzip compression
1125
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1126
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1127

    
1128
{$server_upload_dirs}
1129

    
1130
{$server_max_request_size}
1131

    
1132
{$fastcgi_config}
1133

    
1134
{$cgi_config}
1135

    
1136
{$captive_portal_mod_evasive}
1137

    
1138
expire.url = (
1139
				"" => "access 50 hours",	
1140
        )
1141

    
1142
EOD;
1143

    
1144
	$cert = str_replace("\r", "", $cert);
1145
	$key = str_replace("\r", "", $key);
1146
	$ca = str_replace("\r", "", $ca);
1147

    
1148
	$cert = str_replace("\n\n", "\n", $cert);
1149
	$key = str_replace("\n\n", "\n", $key);
1150
	$ca = str_replace("\n\n", "\n", $ca);
1151

    
1152
	if($cert <> "" and $key <> "") {
1153
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1154
		if (!$fd) {
1155
			printf(gettext("Error: cannot open cert.pem in system_webgui_start().%s"), "\n");
1156
			return 1;
1157
		}
1158
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1159
		fwrite($fd, $cert);
1160
		fwrite($fd, "\n");
1161
		fwrite($fd, $key);
1162
		fclose($fd);
1163
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
1164
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1165
			if (!$fd) {
1166
				printf(gettext("Error: cannot open ca.pem in system_webgui_start().%s"), "\n");
1167
				return 1;
1168
			}
1169
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1170
			fwrite($fd, $ca);
1171
			fclose($fd);
1172
		}
1173
		$lighty_config .= "\n";
1174
		$lighty_config .= "## " . gettext("ssl configuration") . "\n";
1175
		$lighty_config .= "ssl.engine = \"enable\"\n";
1176
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1177

    
1178
		// Harden SSL a bit for PCI conformance testing
1179
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
1180
		$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";
1181

    
1182
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1183
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1184
	}
1185

    
1186
	// Add HTTP to HTTPS redirect	
1187
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1188
		if($lighty_port != "443") 
1189
			$redirectport = ":{$lighty_port}";
1190
		$lighty_config .= <<<EOD
1191
\$SERVER["socket"] == ":80" {
1192
	\$HTTP["host"] =~ "(.*)" {
1193
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1194
	}
1195
}
1196
EOD;
1197
	}
1198

    
1199
	$fd = fopen("{$filename}", "w");
1200
	if (!$fd) {
1201
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1202
		return 1;
1203
	}
1204
	fwrite($fd, $lighty_config);
1205
	fclose($fd);
1206

    
1207
	return 0;
1208

    
1209
}
1210

    
1211
function system_timezone_configure() {
1212
	global $config, $g;
1213
	if(isset($config['system']['developerspew'])) {
1214
		$mt = microtime();
1215
		echo "system_timezone_configure() being called $mt\n";
1216
	}
1217

    
1218
	$syscfg = $config['system'];
1219

    
1220
	if ($g['booting'])
1221
		echo gettext("Setting timezone...");
1222

    
1223
	/* extract appropriate timezone file */
1224
	$timezone = $syscfg['timezone'];
1225
	if (!$timezone)
1226
		$timezone = "Etc/UTC";
1227

    
1228
	conf_mount_rw();
1229

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

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

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

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

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

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

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

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

    
1273
	conf_mount_ro();
1274

    
1275
	return true;
1276
}
1277

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

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

    
1287
	safe_mkdir($statsdir);
1288

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1384
	system_reboot_cleanup();
1385

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

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

    
1392
	system_reboot_cleanup();
1393

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

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

    
1400
	system_reboot_cleanup();
1401

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

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

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

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

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

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

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

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

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

    
1446
	}
1447
}
1448

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

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

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

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

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

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

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

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

    
1490
	fclose($fd);
1491

    
1492
	return 0;
1493
}
1494

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

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

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

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

    
1534
	activate_sysctls();	
1535

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

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

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

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

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

    
1584
	$specplatform = system_identify_specific_platform();
1585

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

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

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

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

    
1601

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

    
1609
	return 0;
1610
}
1611

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

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

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

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

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