Project

General

Profile

Download (52 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
		$mode = "hadp";
51
		if (!empty($config['system']['powerd_mode']))
52
			$mode = $config['system']['powerd_mode'];
53
		mwexec("/usr/sbin/powerd -b $mode -a $mode");
54
	}
55
}
56

    
57
function get_default_sysctl_value($id) {
58
	global $sysctls;
59

    
60
	if (isset($sysctls[$id]))
61
		return $sysctls[$id];
62
}
63

    
64
function activate_sysctls() {
65
	global $config, $g;
66
	if ($g['platform'] == 'jail')
67
		return;
68
	exec("/sbin/sysctl net.enc.out.ipsec_bpf_mask=0x0001");
69
	exec("/sbin/sysctl net.enc.out.ipsec_filter_mask=0x0001");
70
	exec("/sbin/sysctl net.enc.in.ipsec_bpf_mask=0x0002");
71
	exec("/sbin/sysctl net.enc.in.ipsec_filter_mask=0x0002");
72

    
73
	if(is_array($config['sysctl'])) {
74
		foreach($config['sysctl']['item'] as $tunable) {
75
			if($tunable['value'] == "default") {
76
				$value = get_default_sysctl_value($tunable['tunable']);
77
				mwexec("/sbin/sysctl " . $tunable['tunable'] . "=\"" . $value .  "\"");
78
			} else { 
79
				mwexec("/sbin/sysctl " . $tunable['tunable'] . "=\"" . $tunable['value'] .  "\"");
80
			}
81
		}
82
	}
83
}
84

    
85
function system_resolvconf_generate($dynupdate = false) {
86
	global $config, $g;
87

    
88
	if(isset($config['system']['developerspew'])) {
89
		$mt = microtime();
90
		echo "system_resolvconf_generate() being called $mt\n";
91
	}
92

    
93
	$syscfg = $config['system'];
94

    
95
	// Do not create blank domain lines, it breaks tools like dig.
96
	if($syscfg['domain'])
97
		$resolvconf = "domain {$syscfg['domain']}\n";
98

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

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

    
122
	$dnslock = lock('resolvconf', LOCK_EX);
123

    
124
	$fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
125
	if (!$fd) {
126
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
127
		unlock($dnslock);
128
		return 1;
129
	}
130

    
131
	fwrite($fd, $resolvconf);
132
	fclose($fd);
133

    
134
	if (!$g['booting']) {
135
		/* restart dhcpd (nameservers may have changed) */
136
		if (!$dynupdate)
137
			services_dhcpd_configure();
138
	}
139

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

    
162
	unlock($dnslock);
163

    
164
	return 0;
165
}
166

    
167
function get_searchdomains() {
168
	global $config, $g;
169

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

    
186
	return $master_list;
187
}
188

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

    
207
	// Read in any extra nameservers
208
	if(file_exists("/var/etc/nameservers.conf")) {
209
		$dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
210
		if(is_array($dns_s)) {
211
			foreach($dns_s as $dns)
212
				if (is_ipaddr($dns))
213
					$master_list[] = $dns;
214
		}
215
	}
216

    
217
	return $master_list;
218
}
219

    
220
function system_hosts_generate() {
221
	global $config, $g;
222
	if(isset($config['system']['developerspew'])) {
223
		$mt = microtime();
224
		echo "system_hosts_generate() being called $mt\n";
225
	}
226

    
227
	$syscfg = $config['system'];
228
	$dnsmasqcfg = $config['dnsmasq'];
229

    
230
	if (!is_array($dnsmasqcfg['hosts'])) {
231
		$dnsmasqcfg['hosts'] = array();
232
	}
233
	$hostscfg = $dnsmasqcfg['hosts'];
234

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

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

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

    
285
	if (isset($dnsmasqcfg['dhcpfirst']))
286
		$hosts .= $dhosts . $lhosts;
287
	else
288
		$hosts .= $lhosts . $dhosts;
289

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

    
306
	system_dhcpleases_configure();
307

    
308
	return 0;
309
}
310

    
311
function system_dhcpleases_configure() {
312
	global $config, $g;
313
	
314
	if ($g['platform'] == 'jail')
315
		return;
316
	/* Start the monitoring process for dynamic dhcpclients. */
317
	if (isset($config['dnsmasq']['regdhcp'])) {
318
		/* Make sure we do not error out */
319
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
320
		if (file_exists("{$g['varrun_path']}/dhcpleases.pid"))
321
				sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "HUP");
322
		else
323
			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");
324
	} else {
325
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
326
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
327
	}
328
}
329

    
330
function system_hostname_configure() {
331
	global $config, $g;
332
	if(isset($config['system']['developerspew'])) {
333
		$mt = microtime();
334
		echo "system_hostname_configure() being called $mt\n";
335
	}
336

    
337
	$syscfg = $config['system'];
338

    
339
	/* set hostname */
340
	$status = mwexec("/bin/hostname " .
341
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
342

    
343
    /* Setup host GUID ID.  This is used by ZFS. */
344
	mwexec("/etc/rc.d/hostid start");
345

    
346
	return $status;
347
}
348

    
349
function system_routing_configure($interface = "") {
350
	global $config, $g;
351
	if ($g['platform'] == 'jail')
352
		return;
353
	if(isset($config['system']['developerspew'])) {
354
		$mt = microtime();
355
		echo "system_routing_configure() being called $mt\n";
356
	}
357

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

    
424
	if ($dont_add_route == false ) {
425
		if (!empty($interface) && $interface != $interfacegw)
426
			;
427
		else if (($interfacegw <> "bgpd") && (is_ipaddrv4($gatewayip))) {
428
			log_error("ROUTING: setting default route to $gatewayip");
429
			mwexec("/sbin/route change -inet default " . escapeshellarg($gatewayip));
430
		}
431

    
432
		if (!empty($interface) && $interface != $interfacegwv6)
433
			;
434
		else if (($interfacegwv6 <> "bgpd") && (is_ipaddrv6($gatewayipv6))) {
435
			if(preg_match("/fe80::/i", $gatewayipv6))
436
				$ifscope = "%{$defaultifv6}";
437
			log_error("ROUTING: setting IPv6 default route to {$gatewayipv6}{$ifscope}");
438
			mwexec("/sbin/route change -inet6 default " . escapeshellarg($gatewayipv6) ."{$ifscope}");
439
		}
440
	}
441

    
442
	$static_routes = get_staticroutes();
443
	if (count($static_routes)) {
444
		$gateways_arr = return_gateways_array(false, true);
445

    
446
		foreach ($static_routes as $rtent) {
447
			$gatewayip = "";
448
			if (empty($gateways_arr[$rtent['gateway']])) {
449
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
450
				continue;
451
			}
452
			$gateway = $gateways_arr[$rtent['gateway']];
453
			if (!empty($interface) && $interface != $gateway['friendlyiface'])
454
				continue;
455

    
456
			if(isset($rtent['disabled'])) {
457
				mwexec("/sbin/route delete " . escapeshellarg($rtent['network']), true);
458
				continue;
459
			}
460

    
461
			$gatewayip = $gateway['gateway'];
462
			$interfacegw = $gateway['interface'];
463

    
464
			if(is_ipaddrv6($gatewayip)) {
465
				$inetfamily = "-inet6";
466
			} else {
467
				$inetfamily = "-inet";
468
			}
469
			$blackhole = "";
470
			if(preg_match("/^Null/i", $rtent['gateway']))
471
				$blackhole = "-blackhole";
472

    
473
			if (is_ipaddr($gatewayip) && ((is_ipaddrv6($gatewayip) && is_subnetv6($rtent['network'])) || (is_ipaddrv4($gatewayip) && is_subnetv4($rtent['network'])))) {
474
				mwexec("/sbin/route change {$inetfamily} {$blackhole} " . escapeshellarg($rtent['network']) .
475
					" " . escapeshellarg($gatewayip));
476
			} else if (!empty($interfacegw) &&  ((is_ipaddrv6($gatewayip) && is_subnetv6($rtent['network'])) || (is_ipaddrv4($gatewayip) && is_subnetv4($rtent['network'])))) {
477
				mwexec("/sbin/route change {$inetfamily} {$blackhole} " . escapeshellarg($rtent['network']) .
478
					" -iface " . escapeshellarg($interfacegw));
479
			}
480
		}
481
	}
482

    
483
	return 0;
484
}
485

    
486
function system_routing_enable() {
487
	global $config, $g;
488
	if(isset($config['system']['developerspew'])) {
489
		$mt = microtime();
490
		echo "system_routing_enable() being called $mt\n";
491
	}
492

    
493
	mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
494
	mwexec("/sbin/sysctl net.inet6.ip6.forwarding=1");
495
	return;
496
}
497

    
498
function system_syslogd_fixup_server($server) {
499
	/* If it's an IPv6 IP alone, encase it in brackets */
500
	if (is_ipaddrv6($server))
501
		return "[$server]";
502
	else
503
		return $server;
504
}
505

    
506
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
507
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
508
	$facility .= " ".
509
	$remote_servers = "";
510
	$pad_to  = 56;
511
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
512
	if($syslogcfg['remoteserver'])
513
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
514
	if($syslogcfg['remoteserver2'])
515
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
516
	if($syslogcfg['remoteserver3'])
517
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
518
	return $remote_servers;
519
}
520

    
521
function system_syslogd_start() {
522
	global $config, $g;
523
	if(isset($config['system']['developerspew'])) {
524
		$mt = microtime();
525
		echo "system_syslogd_start() being called $mt\n";
526
	}
527

    
528
	mwexec("/etc/rc.d/hostid start");
529

    
530
	$syslogcfg = $config['syslog'];
531

    
532
	if ($g['booting'])
533
		echo gettext("Starting syslog...");
534
	else
535
		killbypid("{$g['varrun_path']}/syslog.pid");
536

    
537
	if(is_process_running("syslogd"))
538
		mwexec('/bin/pkill syslogd');
539
	if(is_process_running("fifolog_writer"))
540
		mwexec('/bin/pkill fifolog_writer');
541
	
542
	// Define carious commands for logging
543
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
544
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
545
	$clog_create = "/usr/sbin/clog -i -s ";
546
	$clog_log = "%";
547

    
548
	// Which logging type are we using this week??
549
	if(isset($config['system']['usefifolog'])) {
550
		$log_directive = $fifolog_log;
551
		$log_create_directive = $fifolog_create;
552
	} else { // Defaults to CLOG
553
		$log_directive = $clog_log;
554
		$log_create_directive = $clog_create;
555
	}
556
	
557
	if (isset($syslogcfg)) {
558
		$separatelogfacilities = array('ntp','ntpd','ntpdate','racoon','openvpn','pptps','poes','l2tps','relayd','hostapd','dnsmasq','unbound','dhcpd','dhcrelay','apinger','radvd','routed','olsrd','zebra','ospfd','bgpd');
559
		if($config['installedpackages']['package']) {
560
			foreach($config['installedpackages']['package'] as $package) {
561
				if($package['logging']) {
562
					array_push($separatelogfacilities, $package['logging']['facilityname']);
563
					mwexec("{$log_create_directive} 10240 {$g['varlog_path']}/{$package['logging']['logfilename']}");
564
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
565
				}
566
			}
567
		}
568
		$facilitylist = implode(',', array_unique($separatelogfacilities));
569
		/* write syslog.conf */		
570
		$fd = fopen("{$g['varetc_path']}/syslog.conf", "w");
571
		if (!$fd) {
572
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
573
			return 1;
574
		}
575
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd\n";
576
		if (!isset($syslogcfg['disablelocallogging']))
577
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
578

    
579
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
580
		if (!isset($syslogcfg['disablelocallogging'])) 
581
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
582

    
583
		$syslogconf .= "!ppp\n";
584
		if (!isset($syslogcfg['disablelocallogging'])) 
585
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
586

    
587
		$syslogconf .= "!pptps\n";
588
		if (!isset($syslogcfg['disablelocallogging'])) 
589
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/pptps.log\n";
590

    
591
		$syslogconf .= "!poes\n";
592
		if (!isset($syslogcfg['disablelocallogging'])) 
593
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
594

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

    
599
		$syslogconf .= "!racoon\n";
600
		if (!isset($syslogcfg['disablelocallogging'])) 
601
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ipsec.log\n";
602
		if (isset($syslogcfg['vpn']))
603
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
604

    
605
		$syslogconf .= "!openvpn\n";
606
		if (!isset($syslogcfg['disablelocallogging'])) 
607
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/openvpn.log\n";
608
		if (isset($syslogcfg['vpn']))
609
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
610

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

    
617
		$syslogconf .= "!dnsmasq,unbound\n";
618
		if (!isset($syslogcfg['disablelocallogging']))
619
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
620
		if (isset($syslogcfg['apinger']))
621
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
622

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

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

    
635
		$syslogconf .= "!hostapd\n";
636
		if (!isset($syslogcfg['disablelocallogging']))
637
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
638
		if (isset($syslogcfg['hostapd']))
639
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
640

    
641
		$syslogconf .= "!-{$facilitylist}\n";
642
		if (!isset($syslogcfg['disablelocallogging'])) 
643
			$syslogconf .= <<<EOD
644
local0.*							{$log_directive}{$g['varlog_path']}/filter.log
645
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
646
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
647
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
648
*.notice;kern.debug;lpr.info;mail.crit;				{$log_directive}{$g['varlog_path']}/system.log
649
news.err;local0.none;local3.none;local4.none;			{$log_directive}{$g['varlog_path']}/system.log
650
local7.none							{$log_directive}{$g['varlog_path']}/system.log
651
security.*							{$log_directive}{$g['varlog_path']}/system.log
652
auth.info;authpriv.info;daemon.info				{$log_directive}{$g['varlog_path']}/system.log
653
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
654
*.emerg								*
655

    
656
EOD;
657
		if (isset($syslogcfg['filter']))
658
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local0.*");
659
		if (isset($syslogcfg['vpn']))
660
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
661
		if (isset($syslogcfg['portalauth']))
662
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
663
		if (isset($syslogcfg['dhcp']))
664
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
665
		if (isset($syslogcfg['system'])) {
666
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.notice;kern.debug;lpr.info;mail.crit;");
667
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "news.err;local0.none;local3.none;local7.none");
668
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "security.*");
669
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "auth.info;authpriv.info;daemon.info");
670
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.emerg");
671
		}
672
		if (isset($syslogcfg['logall'])) {
673
			// Make everything mean everything, including facilities excluded above.
674
			$syslogconf .= "!*\n";
675
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
676
		}
677

    
678
		if (isset($syslogcfg['zmqserver'])) {
679
				$syslogconf .= <<<EOD
680
*.*								^{$syslogcfg['zmqserver']}
681

    
682
EOD;
683
		}
684
		fwrite($fd, $syslogconf);
685
		fclose($fd);
686

    
687
		// Ensure that the log directory exists
688
		if(!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
689
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
690

    
691
		// Are we logging to a least one remote server ?
692
		if(strpos($syslogconf, "@") != false)
693
			$retval = mwexec_bg("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log -f {$g['varetc_path']}/syslog.conf");
694
		else {
695
			$retval = mwexec_bg("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log -f {$g['varetc_path']}/syslog.conf");
696
		}
697

    
698
	} else {
699
		$retval = mwexec_bg("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log");
700
	}
701

    
702
	if ($g['booting'])
703
		echo gettext("done.") . "\n";
704

    
705
	return $retval;
706
}
707

    
708
function system_pccard_start() {
709
	global $config, $g;
710
	if(isset($config['system']['developerspew'])) {
711
		$mt = microtime();
712
		echo "system_pccard_start() being called $mt\n";
713
	}
714

    
715
	if ($g['booting'])
716
		echo gettext("Initializing PCMCIA...");
717

    
718
	/* kill any running pccardd */
719
	killbypid("{$g['varrun_path']}/pccardd.pid");
720

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

    
724
	if ($g['booting']) {
725
		if ($res == 0)
726
			echo gettext("done.") . "\n";
727
		else
728
			echo gettext("failed!") . "\n";
729
	}
730

    
731
	return $res;
732
}
733

    
734

    
735
function system_webgui_start() {
736
	global $config, $g;
737

    
738
	if ($g['booting'])
739
		echo gettext("Starting webConfigurator...");
740

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

    
744
	sleep(1);
745

    
746
	chdir($g['www_path']);
747

    
748
	/* defaults */
749
	$portarg = "80";
750
	$crt = "";
751
	$key = "";
752
	$ca = "";
753

    
754
	/* non-standard port? */
755
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
756
		$portarg = "{$config['system']['webgui']['port']}";
757

    
758
	if ($config['system']['webgui']['protocol'] == "https") {
759
		// Ensure that we have a webConfigurator CERT
760
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
761
		if(!is_array($cert) && !$cert['crt'] && !$cert['prv']) {
762
			if (!is_array($config['ca']))
763
				$config['ca'] = array();
764
			$a_ca =& $config['ca'];
765
			if (!is_array($config['cert']))
766
				$config['cert'] = array();
767
			$a_cert =& $config['cert'];
768
			log_error("Creating SSL Certificate for this host");
769
			$cert = array();
770
			$cert['refid'] = uniqid();
771
			$cert['descr'] = gettext("webConfigurator default");
772
			mwexec("/usr/bin/openssl genrsa 1024 > {$g['tmp_path']}/ssl.key");
773
			mwexec("/usr/bin/openssl req -new -x509 -nodes -sha1 -days 2000 -key {$g['tmp_path']}/ssl.key > {$g['tmp_path']}/ssl.crt");
774
			$crt = file_get_contents("{$g['tmp_path']}/ssl.crt");
775
			$key = file_get_contents("{$g['tmp_path']}/ssl.key");
776
			unlink("{$g['tmp_path']}/ssl.key");
777
			unlink("{$g['tmp_path']}/ssl.crt");
778
			cert_import($cert, $crt, $key);
779
			$a_cert[] = $cert;
780
			$config['system']['webgui']['ssl-certref'] = $cert['refid'];
781
			write_config(gettext("Importing HTTPS certificate"));
782
			if(!$config['system']['webgui']['port'])
783
				$portarg = "443";
784
			$ca = ca_chain($cert);
785
		} else {
786
			$crt = base64_decode($cert['crt']);
787
			$key = base64_decode($cert['prv']);
788
			if(!$config['system']['webgui']['port'])
789
				$portarg = "443";
790
			$ca = ca_chain($cert);
791
		}
792
	}
793

    
794
	/* generate lighttpd configuration */
795
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
796
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
797
		"cert.pem", "ca.pem");
798

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

    
802
	/* fetch page to preload apc cache */
803
	$proto = "http";
804
	if ($config['system']['webgui']['protocol'])
805
		$proto = $config['system']['webgui']['protocol'];
806
	mwexec_bg("/usr/bin/fetch -o /dev/null -q {$proto}://localhost:{$portarg}/preload.php");
807

    
808
	if ($g['booting']) {
809
		if ($res == 0)
810
			echo gettext("done.") . "\n";
811
		else
812
			echo gettext("failed!") . "\n";
813
	}
814

    
815
	return $res;
816
}
817

    
818
function system_generate_lighty_config($filename,
819
	$cert,
820
	$key,
821
	$ca,
822
	$pid_file,
823
	$port = 80,
824
	$document_root = "/usr/local/www/",
825
	$cert_location = "cert.pem",
826
	$ca_location = "ca.pem",
827
	$max_requests = "2",
828
	$fast_cgi_enable = true,
829
	$captive_portal = false) {
830

    
831
	global $config, $g;
832

    
833
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
834
		mkdir("{$g['tmp_path']}/lighttpdcompress");
835

    
836
	if(isset($config['system']['developerspew'])) {
837
		$mt = microtime();
838
		echo "system_generate_lighty_config() being called $mt\n";
839
	}
840

    
841
	if($captive_portal !== false)  {
842
		$captiveportal = ",\"mod_rewrite\"";
843
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?zone={$captive_portal}&redirurl=$1\" )\n";
844
		$captive_portal_module = "";
845

    
846
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
847
		if(empty($maxprocperip))
848
			$maxprocperip = 4;
849
		$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
850

    
851
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
852
		exec("mkdir -p {$g['tmp_path']}/captiveportal");
853
		exec("chmod a-w {$g['tmp_path']}/captiveportal");
854
		$server_max_request_size = "server.max-request-size    = 384";
855
	} else {
856
		$captiveportal = "";
857
		$captive_portal_rewrite = "";
858
		$captive_portal_module = "";
859
		$captive_portal_mod_evasive = "";
860
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
861
		$server_max_request_size = "server.max-request-size    = 2097152";
862
	}
863
	
864
	if($port <> "")
865
		$lighty_port = $port;
866
	else
867
		$lighty_port = "80";
868

    
869
	$memory = get_memory();
870
	$avail = $memory[0];
871

    
872
	// Determine web GUI process settings and take into account low memory systems
873
	if($avail > 0 and $avail < 65) {
874
		$fast_cgi_enable = false;
875
	}
876
	if($avail > 64 and $avail < 256) {
877
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 1;
878
	}
879
	if($avail > 255 ) {
880
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
881
	}
882

    
883
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM 
884
	if($captive_portal !== false)  {
885
		if($avail > 107 and $avail < 256) {
886
			$max_procs += 1; // 2 worker processes
887
		}
888
		if($avail > 255 and $avail < 320) {
889
			$max_procs += 1; // 3 worker processes
890
		}
891
		if($avail > 319 and $avail < 384) {
892
			$max_procs += 2; // 4 worker processes
893
		}
894
		if($avail > 383 and $avail < 448) {
895
			$max_procs += 3; // 5 worker processes
896
		}
897
		if($avail > 447) {
898
			$max_procs += 4; // 6 worker processes
899
		}
900
		$bin_environment =  <<<EOC
901
			"bin-environment" => (
902
				"PHP_FCGI_CHILDREN" => "0",
903
				"PHP_FCGI_MAX_REQUESTS" => "500"
904
			),
905
EOC;
906

    
907
	} else if ($avail > 0 and $avail < 128) {
908
		$bin_environment = <<<EOC
909
			"bin-environment" => (
910
				"PHP_FCGI_CHILDREN" => "0",
911
				"PHP_FCGI_MAX_REQUESTS" => "2",
912
			),
913

    
914
EOC;
915
	} else
916
		$bin_environment =  <<<EOC
917
			"bin-environment" => (
918
				"PHP_FCGI_CHILDREN" => "0",
919
				"PHP_FCGI_MAX_REQUESTS" => "500"
920
			),
921
EOC;
922

    
923
	if($fast_cgi_enable == true) {
924
		$module = "\"mod_fastcgi\", \"mod_cgi\"";
925
		if ($captive_portal !== false)
926
			$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi-{$captive_portal}.socket";
927
		else
928
			$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi.socket";
929
		$cgi_config = "";
930
		$fastcgi_config = <<<EOD
931
#### fastcgi module
932
## read fastcgi.txt for more info
933
fastcgi.server = ( ".php" =>
934
	( "localhost" =>
935
		(
936
			"socket" => "{$fast_cgi_path}",
937
			"min-procs" => 0,
938
			"max-procs" => {$max_procs},
939
{$bin_environment}
940
			"bin-path" => "/usr/local/bin/php"
941
		)
942
	)
943
)
944

    
945
#### CGI module
946
cgi.assign                 = ( ".cgi" => "" )
947

    
948
EOD;
949
	} else {
950
		$fastcgi_config = "";
951
		$module = "\"mod_cgi\"";
952
		$cgi_config = <<<EOD
953
#### CGI module
954
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
955
                               ".cgi" => "" )
956

    
957
EOD;
958
	}
959

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

    
969
## FreeBSD!
970
server.event-handler	= "freebsd-kqueue"
971
server.network-backend 	= "writev"
972
#server.use-ipv6 = "enable"
973

    
974
## modules to load
975
server.modules              =   (
976
	{$captive_portal_module}
977
	"mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect",
978
	{$module}{$captiveportal}
979
)
980

    
981
## Unused modules
982
#                               "mod_setenv",
983
#                               "mod_rewrite",
984
#                               "mod_ssi",
985
#                               "mod_usertrack",
986
#                               "mod_expire",
987
#                               "mod_secdownload",
988
#                               "mod_rrdtool",
989
#                               "mod_auth",
990
#                               "mod_status",
991
#                               "mod_alias",
992
#                               "mod_proxy",
993
#                               "mod_simple_vhost",
994
#                               "mod_evhost",
995
#                               "mod_userdir",
996
#                               "mod_cgi",
997

    
998
server.max-keep-alive-requests = 15
999
server.max-keep-alive-idle = 30
1000

    
1001
## a static document-root, for virtual-hosting take look at the
1002
## server.virtual-* options
1003
server.document-root        = "{$document_root}"
1004
{$captive_portal_rewrite}
1005

    
1006
# Maximum idle time with nothing being written (php downloading)
1007
server.max-write-idle = 999
1008

    
1009
## where to send error-messages to
1010
server.errorlog             = "/var/log/lighttpd.error.log"
1011

    
1012
# files to check for if .../ is requested
1013
server.indexfiles           = ( "index.php", "index.html",
1014
                                "index.htm", "default.htm" )
1015

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

    
1069
# Use the "Content-Type" extended attribute to obtain mime type if possible
1070
#mimetypes.use-xattr        = "enable"
1071

    
1072
#### accesslog module
1073
#accesslog.filename          = "/dev/null"
1074

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

    
1082

    
1083
######### Options that are good to be but not neccesary to be changed #######
1084

    
1085
## bind to port (default: 80)
1086

    
1087
EOD;
1088

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

    
1103

    
1104
	$lighty_config .= <<<EOD
1105

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

    
1110
## to help the rc.scripts
1111
server.pid-file            = "/var/run/{$pid_file}"
1112

    
1113
## virtual directory listings
1114
server.dir-listing         = "disable"
1115

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

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

    
1126
{$server_upload_dirs}
1127

    
1128
{$server_max_request_size}
1129

    
1130
{$fastcgi_config}
1131

    
1132
{$cgi_config}
1133

    
1134
{$captive_portal_mod_evasive}
1135

    
1136
expire.url = (
1137
				"" => "access 50 hours",	
1138
        )
1139

    
1140
EOD;
1141

    
1142
	$cert = str_replace("\r", "", $cert);
1143
	$key = str_replace("\r", "", $key);
1144
	$ca = str_replace("\r", "", $ca);
1145

    
1146
	$cert = str_replace("\n\n", "\n", $cert);
1147
	$key = str_replace("\n\n", "\n", $key);
1148
	$ca = str_replace("\n\n", "\n", $ca);
1149

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

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

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

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

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

    
1205
	return 0;
1206

    
1207
}
1208

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

    
1216
	$syscfg = $config['system'];
1217

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

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

    
1226
	conf_mount_rw();
1227

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

    
1231
	mwexec("sync");
1232
	conf_mount_ro();
1233

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

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

    
1242
	if (!file_exists($serialport))
1243
		return false;
1244

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

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

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

    
1271
	conf_mount_ro();
1272

    
1273
	return true;
1274
}
1275

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

    
1282
	if ($g['platform'] == 'jail')
1283
		return;
1284

    
1285
	safe_mkdir($statsdir);
1286

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

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

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

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

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

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

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

    
1343
	/* slurp! */
1344
	fclose($fd);
1345

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

    
1350
	/* if ntpd is running, kill it */
1351
	while(is_process_running("ntpd")) {
1352
		killbyname("ntpd");
1353
	}
1354

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

    
1359
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1360
	$oldset = array();
1361
	pcntl_sigprocmask(SIG_SETMASK, array(), $oldset);
1362
	exec("/usr/local/bin/ntpd -g -c {$g['varetc_path']}/ntpd.conf");
1363
	pcntl_sigprocmask(SIG_SETMASK, $oldset);
1364
	
1365
	// Note that we are starting up
1366
	log_error("NTPD is starting up.");
1367
	return;
1368
}
1369

    
1370
function sync_system_time() {
1371
	global $config, $g;
1372

    
1373
	if ($g['booting'])
1374
		echo gettext("Syncing system time before startup...");
1375

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

    
1386
function system_halt() {
1387
	global $g;
1388

    
1389
	system_reboot_cleanup();
1390

    
1391
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1392
}
1393

    
1394
function system_reboot() {
1395
	global $g;
1396

    
1397
	system_reboot_cleanup();
1398

    
1399
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1400
}
1401

    
1402
function system_reboot_sync() {
1403
	global $g;
1404

    
1405
	system_reboot_cleanup();
1406

    
1407
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1408
}
1409

    
1410
function system_reboot_cleanup() {
1411
	mwexec("/usr/local/bin/beep.sh stop");
1412
	require_once("captiveportal.inc");
1413
	captiveportal_radius_stop_all();
1414
	require_once("voucher.inc");
1415
	voucher_save_db_to_config();
1416
	require_once("pkg-utils.inc");
1417
	stop_packages();
1418
}
1419

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

    
1427
	if ($early)
1428
		$cmdn = "earlyshellcmd";
1429
	else
1430
		$cmdn = "shellcmd";
1431

    
1432
	if (is_array($config['system'][$cmdn])) {
1433

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

    
1439
	} elseif($config['system'][$cmdn] <> "") {
1440

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

    
1444
	}
1445
}
1446

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

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

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

    
1468
	$dmesg = "";
1469
	exec("/sbin/dmesg", $dmesg);
1470

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

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

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

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

    
1488
	fclose($fd);
1489

    
1490
	return 0;
1491
}
1492

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

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

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

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

    
1532
	activate_sysctls();	
1533

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

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

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

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

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

    
1582
	$specplatform = system_identify_specific_platform();
1583

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

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

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

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

    
1599

    
1600
EOD;
1601
		
1602
		reset_factory_defaults();
1603
		system_reboot_sync();
1604
		exit(0);
1605
	}
1606

    
1607
	return 0;
1608
}
1609

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

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

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

    
1655
function get_possible_listen_ips() {
1656
	$interfaces = get_configured_interface_with_descr();
1657
	$carplist = get_configured_carp_interface_list();
1658
	$listenips = array();
1659
	foreach ($carplist as $cif => $carpip)
1660
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1661
	$aliaslist = get_configured_ip_aliases_list();
1662
	foreach ($aliaslist as $aliasip => $aliasif)
1663
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1664
	foreach ($interfaces as $iface => $ifacename) {
1665
		$tmp["name"]  = $ifacename;
1666
		$tmp["value"] = $iface;
1667
		$listenips[] = $tmp;
1668
	}
1669
	$tmp["name"]  = "Localhost";
1670
	$tmp["value"] = "lo0";
1671
	$listenips[] = $tmp;
1672
	return $listenips;
1673
}
1674

    
1675
/* Pick up IPv6 router advertisements on the interface */
1676
function pickup_ipv6_router_advertisement($interface) {
1677
	global $g;
1678
	$realif = get_real_interface($interface);
1679
	exec("/sbin/rtsol -d {$realif} 2>&1", $out, $ret);
1680
	if(!empty($out)) {
1681
		foreach($out as $line) {
1682
			if((stristr($line, "received")) && (!stristr($line, "unexpected"))) {
1683
				$parts = explode(" ", $line);
1684
				if(is_ipaddrv6($parts[3])) {
1685
					log_error("Found IPv6 default gateway '{$parts[3]}' on interface {$realif} by RA.");
1686
					file_put_contents("{$g['tmp_path']}/{$realif}_routerv6", "{$parts[3]}\n");
1687
					file_put_contents("{$g['tmp_path']}/{$realif}_defaultgwv6", "{$parts[3]}\n");
1688
					break;
1689
				}
1690
			}
1691
		}
1692
	}
1693
}
1694

    
1695
?>
(51-51/66)