Project

General

Profile

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

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

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

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

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

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

    
32
/*
33
	pfSense_BUILDER_BINARIES:	/usr/sbin/powerd	/usr/bin/killall	/sbin/sysctl	/sbin/route
34
	pfSense_BUILDER_BINARIES:	/bin/hostname	/bin/ls	/usr/sbin/syslogd	
35
	pfSense_BUILDER_BINARIES:	/usr/sbin/pccardd	/usr/local/sbin/lighttpd	/bin/chmod 	/bin/mkdir
36
	pfSense_BUILDER_BINARIES:	/usr/bin/tar		/usr/local/sbin/ntpd	/usr/sbin/ntpdate
37
	pfSense_BUILDER_BINARIES:	/usr/bin/nohup	/sbin/dmesg	/usr/local/sbin/atareinit	/sbin/kldload
38
	pfSense_MODULE:	utils
39
*/
40

    
41
function activate_powerd() {
42
	global $config, $g;
43
	if ($g['platform'] == 'jail')
44
		return;
45
	if(is_process_running("powerd"))
46
		exec("/usr/bin/killall powerd");
47
	if(isset($config['system']['powerd_enable'])) {
48
		if ($g["platform"] == "nanobsd")
49
			exec("/sbin/kldload cpufreq");
50
		$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=0x00000001");
69
	exec("/sbin/sysctl net.enc.out.ipsec_filter_mask=0x00000001");
70
	exec("/sbin/sysctl net.enc.in.ipsec_bpf_mask=0x00000002");
71
	exec("/sbin/sysctl net.enc.in.ipsec_filter_mask=0x00000002");
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
	}
262
	if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpd'])) {
263
		foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf)
264
			if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
265
					foreach ($dhcpifconf['staticmap'] as $host)
266
						if ($host['ipaddr'] && $host['hostname'])
267
							$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
268
	}
269
	if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpdv6'])) {
270
		foreach ($config['dhcpdv6'] as $dhcpif => $dhcpifconf)
271
			if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
272
					foreach ($dhcpifconf['staticmap'] as $host)
273
						if ($host['ipaddrv6'] && $host['hostname'])
274
							$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
275
	}
276

    
277
	if (isset($dnsmasqcfg['dhcpfirst']))
278
		$hosts .= $dhosts . $lhosts;
279
	else
280
		$hosts .= $lhosts . $dhosts;
281

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

    
298
	system_dhcpleases_configure();
299

    
300
	return 0;
301
}
302

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

    
322
function system_hostname_configure() {
323
	global $config, $g;
324
	if(isset($config['system']['developerspew'])) {
325
		$mt = microtime();
326
		echo "system_hostname_configure() being called $mt\n";
327
	}
328

    
329
	$syscfg = $config['system'];
330

    
331
	/* set hostname */
332
	$status = mwexec("/bin/hostname " .
333
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
334

    
335
    /* Setup host GUID ID.  This is used by ZFS. */
336
	mwexec("/etc/rc.d/hostid start");
337

    
338
	return $status;
339
}
340

    
341
function system_routing_configure($interface = "") {
342
	global $config, $g;
343
	if ($g['platform'] == 'jail')
344
		return;
345
	if(isset($config['system']['developerspew'])) {
346
		$mt = microtime();
347
		echo "system_routing_configure() being called $mt\n";
348
	}
349

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

    
416
	if ($dont_add_route == false ) {
417
		if (!empty($interface) && $interface != $interfacegw)
418
			;
419
		else if (($interfacegw <> "bgpd") && (is_ipaddrv4($gatewayip))) {
420
			log_error("ROUTING: setting default route to $gatewayip");
421
			mwexec("/sbin/route change -inet default " . escapeshellarg($gatewayip));
422
		}
423

    
424
		if (!empty($interface) && $interface != $interfacegwv6)
425
			;
426
		else if (($interfacegwv6 <> "bgpd") && (is_ipaddrv6($gatewayipv6))) {
427
			if(preg_match("/fe80::/i", $gatewayipv6))
428
				$ifscope = "%{$defaultifv6}";
429
			log_error("ROUTING: setting IPv6 default route to {$gatewayipv6}{$ifscope}");
430
			mwexec("/sbin/route change -inet6 default " . escapeshellarg($gatewayipv6) ."{$ifscope}");
431
		}
432
	}
433

    
434
	$static_routes = get_staticroutes();
435
	if (count($static_routes)) {
436
		$gateways_arr = return_gateways_array();
437

    
438
		foreach ($static_routes as $rtent) {
439
			$gatewayip = "";
440
			if (empty($gateways_arr[$rtent['gateway']])) {
441
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
442
				continue;
443
			}
444
			$gateway = $gateways_arr[$rtent['gateway']];
445
			if (!empty($interface) && $interface != $gateway['friendlyiface'])
446
				continue;
447

    
448
			if(isset($rtent['disabled'])) {
449
				mwexec("/sbin/route delete " . escapeshellarg($rtent['network']), true);
450
				continue;
451
			}
452

    
453
			$gatewayip = $gateway['gateway'];
454
			$interfacegw = $gateway['interface'];
455

    
456
			if(is_ipaddrv6($gatewayip)) {
457
				$inetfamily = "-inet6";
458
			} else {
459
				$inetfamily = "-inet";
460
			}
461
			if (is_ipaddr($gatewayip)) {
462
				mwexec("/sbin/route change {$inetfamily} " . escapeshellarg($rtent['network']) .
463
					" " . escapeshellarg($gatewayip));
464
			} else if (!empty($interfacegw)) {
465
				mwexec("/sbin/route change {$inetfamily} " . escapeshellarg($rtent['network']) .
466
					" -iface " . escapeshellarg($interfacegw));
467
			}
468
		}
469
	}
470

    
471
	return 0;
472
}
473

    
474
function system_routing_enable() {
475
	global $config, $g;
476
	if(isset($config['system']['developerspew'])) {
477
		$mt = microtime();
478
		echo "system_routing_enable() being called $mt\n";
479
	}
480

    
481
	mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
482
	mwexec("/sbin/sysctl net.inet6.ip6.forwarding=1");
483
	return;
484
}
485

    
486
function system_syslogd_fixup_server($server) {
487
	/* If it's an IPv6 IP alone, encase it in brackets */
488
	if (is_ipaddrv6($server))
489
		return "[$server]";
490
	else
491
		return $server;
492
}
493

    
494
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
495
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
496
	$facility .= " ".
497
	$remote_servers = "";
498
	$pad_to  = 56;
499
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
500
	if($syslogcfg['remoteserver'])
501
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
502
	if($syslogcfg['remoteserver2'])
503
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
504
	if($syslogcfg['remoteserver3'])
505
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
506
	return $remote_servers;
507
}
508

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

    
516
	mwexec("/etc/rc.d/hostid start");
517

    
518
	$syslogcfg = $config['syslog'];
519

    
520
	if ($g['booting'])
521
		echo gettext("Starting syslog...");
522
	else
523
		killbypid("{$g['varrun_path']}/syslog.pid");
524

    
525
	if(is_process_running("syslogd"))
526
		mwexec('/bin/pkill syslogd');
527
	if(is_process_running("fifolog_writer"))
528
		mwexec('/bin/pkill fifolog_writer');
529
	
530
	// Define carious commands for logging
531
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
532
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
533
	$clog_create = "/usr/sbin/clog -i -s ";
534
	$clog_log = "%";
535

    
536
	// Which logging type are we using this week??
537
	if(isset($config['system']['usefifolog'])) {
538
		$log_directive = $fifolog_log;
539
		$log_create_directive = $fifolog_create;
540
	} else { // Defaults to CLOG
541
		$log_directive = $clog_log;
542
		$log_create_directive = $clog_create;
543
	}
544
	
545
	if (isset($syslogcfg)) {
546
		$separatelogfacilities = array('ntpd','ntpdate','racoon','openvpn','pptps','poes','l2tps','relayd','hostapd','dnsmasq','unbound','dhcpd','dhcrelay','apinger');
547
		if($config['installedpackages']['package']) {
548
			foreach($config['installedpackages']['package'] as $package) {
549
				if($package['logging']) {
550
					array_push($separatelogfacilities, $package['logging']['facilityname']);
551
					mwexec("{$log_create_directive} 10240 {$g['varlog_path']}/{$package['logging']['logfilename']}");
552
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
553
				}
554
			}
555
		}
556
		$facilitylist = implode(',', array_unique($separatelogfacilities));
557
		/* write syslog.conf */		
558
		$fd = fopen("{$g['varetc_path']}/syslog.conf", "w");
559
		if (!$fd) {
560
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
561
			return 1;
562
		}
563
		$syslogconf .= "!ntpdate,ntp,ntpd\n";
564
		if (!isset($syslogcfg['disablelocallogging'])) 
565
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
566

    
567
		$syslogconf .= "!ppp\n";
568
		if (!isset($syslogcfg['disablelocallogging'])) 
569
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
570

    
571
		$syslogconf .= "!pptps\n";
572
		if (!isset($syslogcfg['disablelocallogging'])) 
573
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/pptps.log\n";
574

    
575
		$syslogconf .= "!poes\n";
576
		if (!isset($syslogcfg['disablelocallogging'])) 
577
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
578

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

    
583
		$syslogconf .= "!racoon\n";
584
		if (!isset($syslogcfg['disablelocallogging'])) 
585
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ipsec.log\n";
586
		if (isset($syslogcfg['vpn']))
587
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
588

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

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

    
601
		$syslogconf .= "!dnsmasq,unbound\n";
602
		if (!isset($syslogcfg['disablelocallogging']))
603
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
604
		if (isset($syslogcfg['apinger']))
605
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
606

    
607
		$syslogconf .= "!dhcpd,dhcrelay\n";
608
		if (!isset($syslogcfg['disablelocallogging']))
609
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/dhcpd.log\n";
610
		if (isset($syslogcfg['apinger']))
611
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
612

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

    
619
		$syslogconf .= "!hostapd\n";
620
		if (!isset($syslogcfg['disablelocallogging']))
621
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
622
		if (isset($syslogcfg['hostapd']))
623
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
624

    
625
		$syslogconf .= "!-{$facilitylist}\n";
626
		if (!isset($syslogcfg['disablelocallogging'])) 
627
			$syslogconf .= <<<EOD
628
local0.*							{$log_directive}{$g['varlog_path']}/filter.log
629
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
630
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
631
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
632
*.notice;kern.debug;lpr.info;mail.crit;				{$log_directive}{$g['varlog_path']}/system.log
633
news.err;local0.none;local3.none;local4.none;			{$log_directive}{$g['varlog_path']}/system.log
634
local7.none							{$log_directive}{$g['varlog_path']}/system.log
635
security.*							{$log_directive}{$g['varlog_path']}/system.log
636
auth.info;authpriv.info;daemon.info				{$log_directive}{$g['varlog_path']}/system.log
637
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
638
*.emerg								*
639

    
640
EOD;
641
		if (isset($syslogcfg['filter']))
642
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local0.*");
643
		if (isset($syslogcfg['vpn']))
644
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
645
		if (isset($syslogcfg['portalauth']))
646
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
647
		if (isset($syslogcfg['dhcp']))
648
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
649
		if (isset($syslogcfg['system'])) {
650
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.notice;kern.debug;lpr.info;mail.crit;");
651
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "news.err;local0.none;local3.none;local7.none");
652
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "security.*");
653
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "auth.info;authpriv.info;daemon.info");
654
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.emerg");
655
		}
656
		if (isset($syslogcfg['logall'])) {
657
			// Make everything mean everything, including facilities excluded above.
658
			$syslogconf .= "!*\n";
659
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
660
		}
661

    
662
		if (isset($syslogcfg['zmqserver'])) {
663
				$syslogconf .= <<<EOD
664
*.*								^{$syslogcfg['zmqserver']}
665

    
666
EOD;
667
		}
668
		fwrite($fd, $syslogconf);
669
		fclose($fd);
670

    
671
		// Ensure that the log directory exists
672
		if(!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
673
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
674

    
675
		// Are we logging to a least one remote server ?
676
		if(strpos($syslogconf, "@") != false)
677
			$retval = mwexec_bg("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log -f {$g['varetc_path']}/syslog.conf");
678
		else {
679
			$retval = mwexec_bg("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log -f {$g['varetc_path']}/syslog.conf");
680
		}
681

    
682
	} else {
683
		$retval = mwexec_bg("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log");
684
	}
685

    
686
	if ($g['booting'])
687
		echo gettext("done.") . "\n";
688

    
689
	return $retval;
690
}
691

    
692
function system_pccard_start() {
693
	global $config, $g;
694
	if(isset($config['system']['developerspew'])) {
695
		$mt = microtime();
696
		echo "system_pccard_start() being called $mt\n";
697
	}
698

    
699
	if ($g['booting'])
700
		echo gettext("Initializing PCMCIA...");
701

    
702
	/* kill any running pccardd */
703
	killbypid("{$g['varrun_path']}/pccardd.pid");
704

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

    
708
	if ($g['booting']) {
709
		if ($res == 0)
710
			echo gettext("done.") . "\n";
711
		else
712
			echo gettext("failed!") . "\n";
713
	}
714

    
715
	return $res;
716
}
717

    
718

    
719
function system_webgui_start() {
720
	global $config, $g;
721

    
722
	if ($g['booting'])
723
		echo gettext("Starting webConfigurator...");
724

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

    
728
	sleep(1);
729

    
730
	chdir($g['www_path']);
731

    
732
	/* defaults */
733
	$portarg = "80";
734
	$crt = "";
735
	$key = "";
736
	$ca = "";
737

    
738
	/* non-standard port? */
739
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
740
		$portarg = "{$config['system']['webgui']['port']}";
741

    
742
	if ($config['system']['webgui']['protocol'] == "https") {
743
		// Ensure that we have a webConfigurator CERT
744
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
745
		if(!is_array($cert) && !$cert['crt'] && !$cert['prv']) {
746
			if (!is_array($config['ca']))
747
				$config['ca'] = array();
748
			$a_ca =& $config['ca'];
749
			if (!is_array($config['cert']))
750
				$config['cert'] = array();
751
			$a_cert =& $config['cert'];
752
			log_error("Creating SSL Certificate for this host");
753
			$cert = array();
754
			$cert['refid'] = uniqid();
755
			$cert['descr'] = gettext("webConfigurator default");
756
			mwexec("/usr/bin/openssl genrsa 1024 > {$g['tmp_path']}/ssl.key");
757
			mwexec("/usr/bin/openssl req -new -x509 -nodes -sha1 -days 2000 -key {$g['tmp_path']}/ssl.key > {$g['tmp_path']}/ssl.crt");
758
			$crt = file_get_contents("{$g['tmp_path']}/ssl.crt");
759
			$key = file_get_contents("{$g['tmp_path']}/ssl.key");
760
			unlink("{$g['tmp_path']}/ssl.key");
761
			unlink("{$g['tmp_path']}/ssl.crt");
762
			cert_import($cert, $crt, $key);
763
			$a_cert[] = $cert;
764
			$config['system']['webgui']['ssl-certref'] = $cert['refid'];
765
			write_config(gettext("Importing HTTPS certificate"));
766
			if(!$config['system']['webgui']['port'])
767
				$portarg = "443";
768
			$ca = ca_chain($cert);
769
		} else {
770
			$crt = base64_decode($cert['crt']);
771
			$key = base64_decode($cert['prv']);
772
			if(!$config['system']['webgui']['port'])
773
				$portarg = "443";
774
			$ca = ca_chain($cert);
775
		}
776
	}
777

    
778
	/* generate lighttpd configuration */
779
	$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
780
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
781
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
782
		"cert.pem", "ca.pem", $max_procs);
783

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

    
787
	/* fetch page to preload apc cache */
788
	$proto = "http";
789
	if ($config['system']['webgui']['protocol'])
790
		$proto = $config['system']['webgui']['protocol'];
791
	mwexec_bg("/usr/bin/fetch -o /dev/null -q {$proto}://localhost:{$portarg}/preload.php");
792

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

    
800
	return $res;
801
}
802

    
803
function system_generate_lighty_config($filename,
804
	$cert,
805
	$key,
806
	$ca,
807
	$pid_file,
808
	$port = 80,
809
	$document_root = "/usr/local/www/",
810
	$cert_location = "cert.pem",
811
	$ca_location = "ca.pem",
812
	$max_procs = 1,
813
	$max_requests = "2",
814
	$fast_cgi_enable = true,
815
	$captive_portal = false) {
816

    
817
	global $config, $g;
818

    
819
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
820
		mkdir("{$g['tmp_path']}/lighttpdcompress");
821

    
822
	if(isset($config['system']['developerspew'])) {
823
		$mt = microtime();
824
		echo "system_generate_lighty_config() being called $mt\n";
825
	}
826

    
827
	if($captive_portal != false)  {
828
		$captiveportal = ",\"mod_rewrite\"";
829
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?zone={$captive_portal}&redirurl=$1\" )\n";
830
		$captive_portal_module = "";
831
		$maxprocperip = $config['captiveportal']['maxprocperip'];
832
		if($maxprocperip and $maxprocperip > 0)
833
			$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
834
		else
835
			$captive_portal_mod_evasive = "";
836
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
837
		exec("mkdir -p {$g['tmp_path']}/captiveportal");
838
		exec("chmod a-w {$g['tmp_path']}/captiveportal");
839
		$server_max_request_size = "server.max-request-size    = 384";
840
	} else {
841
		$captiveportal = "";
842
		$captive_portal_rewrite = "";
843
		$captive_portal_module = "";
844
		$captive_portal_mod_evasive = "";
845
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
846
		$server_max_request_size = "server.max-request-size    = 2097152";
847
	}
848
	
849
	if($port <> "")
850
		$lighty_port = $port;
851
	else
852
		$lighty_port = "80";
853

    
854
	$memory = get_memory();
855
	$avail = $memory[0];
856

    
857
	if($avail > 0 and $avail < 65) {
858
		$fast_cgi_enable = false;
859
	}
860

    
861
	// Ramp up captive portal max procs
862
	//  Work relative to the default of 2, for values that would be >2.
863
	if($captive_portal == true)  {
864
		if($avail > 65 and $avail < 98) {
865
			$max_procs = 1;
866
		}
867
		if($avail > 97 and $avail < 128) {
868
			$max_procs = 2;
869
		}
870
		if($avail > 127 and $avail < 256) {
871
			$max_procs += 1;
872
		}
873
		if($avail > 255 and $avail < 384) {
874
			$max_procs += 2;
875
		}
876
		if($avail > 383) {
877
			$max_procs += 3;
878
		}
879
	}
880

    
881
	if($captive_portal == true)  {	
882
		$bin_environment =  <<<EOC
883
			"bin-environment" => (
884
				"PHP_FCGI_CHILDREN" => "0",
885
				"PHP_FCGI_MAX_REQUESTS" => "500"
886
			),
887
EOC;
888

    
889
	} else if ($avail > 0 and $avail < 128) {
890
		$bin_environment = <<<EOC
891
			"bin-environment" => (
892
				"PHP_FCGI_CHILDREN" => "0",
893
				"PHP_FCGI_MAX_REQUESTS" => "2",
894
			),
895

    
896
EOC;
897
	} else
898
		$bin_environment =  <<<EOC
899
			"bin-environment" => (
900
				"PHP_FCGI_CHILDREN" => "0",
901
				"PHP_FCGI_MAX_REQUESTS" => "500"
902
			),
903
EOC;
904

    
905
	if($fast_cgi_enable == true) {
906
		$module = "\"mod_fastcgi\", \"mod_cgi\"";
907
		if ($captive_portal != false)
908
			$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi-{$captive_portal}.socket";
909
		else
910
			$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi.socket";
911
		$cgi_config = "";
912
		$fastcgi_config = <<<EOD
913
#### fastcgi module
914
## read fastcgi.txt for more info
915
fastcgi.server = ( ".php" =>
916
	( "localhost" =>
917
		(
918
			"socket" => "{$fast_cgi_path}",
919
			"min-procs" => 0,
920
			"max-procs" => {$max_procs},
921
{$bin_environment}
922
			"bin-path" => "/usr/local/bin/php"
923
		)
924
	)
925
)
926

    
927
#### CGI module
928
cgi.assign                 = ( ".cgi" => "" )
929

    
930
EOD;
931
	} else {
932
		$fastcgi_config = "";
933
		$module = "\"mod_cgi\"";
934
		$cgi_config = <<<EOD
935
#### CGI module
936
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
937
                               ".cgi" => "" )
938

    
939
EOD;
940
	}
941

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

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

    
956
## modules to load
957
server.modules              =   (
958
	{$captive_portal_module}
959
	"mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect",
960
	{$module}{$captiveportal}
961
)
962

    
963
## Unused modules
964
#                               "mod_setenv",
965
#                               "mod_rewrite",
966
#                               "mod_ssi",
967
#                               "mod_usertrack",
968
#                               "mod_expire",
969
#                               "mod_secdownload",
970
#                               "mod_rrdtool",
971
#                               "mod_auth",
972
#                               "mod_status",
973
#                               "mod_alias",
974
#                               "mod_proxy",
975
#                               "mod_simple_vhost",
976
#                               "mod_evhost",
977
#                               "mod_userdir",
978
#                               "mod_cgi",
979

    
980
server.max-keep-alive-requests = 15
981
server.max-keep-alive-idle = 30
982

    
983
## a static document-root, for virtual-hosting take look at the
984
## server.virtual-* options
985
server.document-root        = "{$document_root}"
986
{$captive_portal_rewrite}
987

    
988
# Maximum idle time with nothing being written (php downloading)
989
server.max-write-idle = 999
990

    
991
## where to send error-messages to
992
server.errorlog             = "/var/log/lighttpd.error.log"
993

    
994
# files to check for if .../ is requested
995
server.indexfiles           = ( "index.php", "index.html",
996
                                "index.htm", "default.htm" )
997

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

    
1051
# Use the "Content-Type" extended attribute to obtain mime type if possible
1052
#mimetypes.use-xattr        = "enable"
1053

    
1054
#### accesslog module
1055
#accesslog.filename          = "/dev/null"
1056

    
1057
## deny access the file-extensions
1058
#
1059
# ~    is for backupfiles from vi, emacs, joe, ...
1060
# .inc is often used for code includes which should in general not be part
1061
#      of the document-root
1062
url.access-deny             = ( "~", ".inc" )
1063

    
1064

    
1065
######### Options that are good to be but not neccesary to be changed #######
1066

    
1067
## bind to port (default: 80)
1068

    
1069
EOD;
1070

    
1071
	if($captive_portal == true) {
1072
		$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1073
		$lighty_config .= "server.port  = {$lighty_port}\n";
1074
		$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1075
		$lighty_config .= "\$SERVER[\"socket\"]  == \"[::1]:{$lighty_port}\" { \n";
1076
		if($cert <> "" and $key <> "") {
1077
			$lighty_config .= "\n";
1078
			$lighty_config .= "## ssl configuration\n";
1079
			$lighty_config .= "ssl.engine = \"enable\"\n";
1080
			$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1081
			if($ca <> "")
1082
				$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1083
		}
1084
		$lighty_config .= " }\n";
1085
	} else {
1086
		$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1087
		$lighty_config .= "server.port  = {$lighty_port}\n";
1088
		$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1089
		$lighty_config .= "\$SERVER[\"socket\"]  == \"[::]:{$lighty_port}\" { \n";
1090
		if($cert <> "" and $key <> "") {
1091
			$lighty_config .= "\n";
1092
			$lighty_config .= "## ssl configuration\n";
1093
			$lighty_config .= "ssl.engine = \"enable\"\n";
1094
			$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1095
			if($ca <> "")
1096
				$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1097
		}
1098
		$lighty_config .= " }\n";
1099
	}
1100

    
1101

    
1102
	$lighty_config .= <<<EOD
1103

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

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

    
1111
## virtual directory listings
1112
server.dir-listing         = "disable"
1113

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

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

    
1124
{$server_upload_dirs}
1125

    
1126
{$server_max_request_size}
1127

    
1128
{$fastcgi_config}
1129

    
1130
{$cgi_config}
1131

    
1132
{$captive_portal_mod_evasive}
1133

    
1134
expire.url = (
1135
				"" => "access 50 hours",	
1136
        )
1137

    
1138
EOD;
1139

    
1140
	$cert = str_replace("\r", "", $cert);
1141
	$key = str_replace("\r", "", $key);
1142
	$ca = str_replace("\r", "", $ca);
1143

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

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

    
1174
		// Harden SSL a bit for PCI conformance testing
1175
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
1176
		$lighty_config .= "ssl.cipher-list = \"TLSv1+HIGH !SSLv2 RC4+MEDIUM !aNULL !eNULL !3DES @STRENGTH\"\n";
1177

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

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

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

    
1203
	return 0;
1204

    
1205
}
1206

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

    
1214
	$syscfg = $config['system'];
1215

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

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

    
1224
	conf_mount_rw();
1225

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

    
1229
	mwexec("sync");
1230
	conf_mount_ro();
1231

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

    
1236
function system_ntp_configure() {
1237
	global $config, $g;
1238

    
1239
	if ($g['platform'] == 'jail')
1240
		return;
1241

    
1242
	$ntpcfg = "# \n";
1243
	$ntpcfg .= "# pfSense OpenNTPD configuration file \n";
1244
	$ntpcfg .= "# \n\n";
1245

    
1246
	/* foreach through servers and write out to ntpd.conf */
1247
	foreach (explode(' ', $config['system']['timeservers']) as $ts)
1248
		$ntpcfg .= "servers {$ts}\n";
1249

    
1250
	/* Setup listener(s) if the user has configured one */
1251
        if ($config['installedpackages']['openntpd']) {
1252
    		/* server config is in coregui1 */
1253
		$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
1254
		if ($xmlsettings['enable'] == 'on') {
1255
			$ifaces = explode(',', $xmlsettings['interface']);
1256
			$ips = array();
1257
			foreach ($ifaces as $if) {
1258
				if (is_ipaddr($if)) {
1259
					$ips[] = $if;
1260
				} else {
1261
					$if = get_real_interface($if);
1262
					if (does_interface_exist($if))
1263
						$ips[] = find_interface_ip($if);
1264
				}
1265
			}
1266
			foreach ($ips as $ip) {
1267
				if (is_ipaddr($ip))
1268
					$ntpcfg .= "listen on $ip\n";
1269
			}
1270
		}
1271
	}
1272
	$ntpcfg .= "\n";
1273

    
1274
	/* open configuration for wrting or bail */
1275
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1276
	if(!$fd) {
1277
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1278
		return;
1279
	}
1280
	fwrite($fd, $ntpcfg);
1281

    
1282
	/* slurp! */
1283
	fclose($fd);
1284

    
1285
	/* if openntpd is running, kill it */
1286
	while(is_process_running("ntpd")) {
1287
		killbyname("ntpd");
1288
	}
1289

    
1290
	/* if /var/empty does not exist, create it */
1291
	if(!is_dir("/var/empty"))
1292
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1293

    
1294
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1295
	exec("/usr/local/sbin/ntpd -v -s -f {$g['varetc_path']}/ntpd.conf");
1296
	
1297
	// Note that we are starting up
1298
	log_error("OpenNTPD is starting up.");
1299

    
1300
}
1301

    
1302
function sync_system_time() {
1303
	global $config, $g;
1304

    
1305
	if ($g['booting'])
1306
		echo gettext("Syncing system time before startup...");
1307

    
1308
	/* foreach through servers and write out to ntpd.conf */
1309
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1310
		mwexec("/usr/sbin/ntpdate -s $ts");
1311
	}
1312
	
1313
	if ($g['booting'])
1314
		echo gettext("done.") . "\n";
1315
	
1316
}
1317

    
1318
function system_halt() {
1319
	global $g;
1320

    
1321
	system_reboot_cleanup();
1322

    
1323
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1324
}
1325

    
1326
function system_reboot() {
1327
	global $g;
1328

    
1329
	system_reboot_cleanup();
1330

    
1331
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1332
}
1333

    
1334
function system_reboot_sync() {
1335
	global $g;
1336

    
1337
	system_reboot_cleanup();
1338

    
1339
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1340
}
1341

    
1342
function system_reboot_cleanup() {
1343
	mwexec("/usr/local/bin/beep.sh stop");
1344
	require_once("captiveportal.inc");
1345
	captiveportal_radius_stop_all();
1346
	require_once("voucher.inc");
1347
	voucher_save_db_to_config();
1348
	mwexec("/etc/rc.stop_packages");
1349
}
1350

    
1351
function system_do_shell_commands($early = 0) {
1352
	global $config, $g;
1353
	if(isset($config['system']['developerspew'])) {
1354
		$mt = microtime();
1355
		echo "system_do_shell_commands() being called $mt\n";
1356
	}
1357

    
1358
	if ($early)
1359
		$cmdn = "earlyshellcmd";
1360
	else
1361
		$cmdn = "shellcmd";
1362

    
1363
	if (is_array($config['system'][$cmdn])) {
1364

    
1365
		/* *cmd is an array, loop through */
1366
		foreach ($config['system'][$cmdn] as $cmd) {
1367
			exec($cmd);
1368
		}
1369

    
1370
	} elseif($config['system'][$cmdn] <> "") {
1371

    
1372
		/* execute single item */
1373
		exec($config['system'][$cmdn]);
1374

    
1375
	}
1376
}
1377

    
1378
function system_console_configure() {
1379
	global $config, $g;
1380
	if(isset($config['system']['developerspew'])) {
1381
		$mt = microtime();
1382
		echo "system_console_configure() being called $mt\n";
1383
	}
1384

    
1385
	if (isset($config['system']['disableconsolemenu'])) {
1386
		touch("{$g['varetc_path']}/disableconsole");
1387
	} else {
1388
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1389
	}
1390
}
1391

    
1392
function system_dmesg_save() {
1393
	global $g;
1394
	if(isset($config['system']['developerspew'])) {
1395
		$mt = microtime();
1396
		echo "system_dmesg_save() being called $mt\n";
1397
	}
1398

    
1399
	$dmesg = "";
1400
	exec("/sbin/dmesg", $dmesg);
1401

    
1402
	/* find last copyright line (output from previous boots may be present) */
1403
	$lastcpline = 0;
1404

    
1405
	for ($i = 0; $i < count($dmesg); $i++) {
1406
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1407
			$lastcpline = $i;
1408
	}
1409

    
1410
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1411
	if (!$fd) {
1412
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1413
		return 1;
1414
	}
1415

    
1416
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1417
		fwrite($fd, $dmesg[$i] . "\n");
1418

    
1419
	fclose($fd);
1420

    
1421
	return 0;
1422
}
1423

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

    
1431
	if (isset($config['system']['harddiskstandby'])) {
1432
		if ($g['booting']) {
1433
			echo gettext('Setting hard disk standby... ');
1434
		}
1435

    
1436
		$standby = $config['system']['harddiskstandby'];
1437
		// Check for a numeric value
1438
		if (is_numeric($standby)) {
1439
			// Sync the disk(s)
1440
			pfSense_sync();
1441
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1442
				// Reinitialize ATA-drives
1443
				mwexec('/usr/local/sbin/atareinit');
1444
				if ($g['booting']) {
1445
					echo gettext("done.") . "\n";
1446
				}
1447
			} else if ($g['booting']) {
1448
				echo gettext("failed!") . "\n";
1449
			}
1450
		} else if ($g['booting']) {
1451
			echo gettext("failed!") . "\n";
1452
		}
1453
	}
1454
}
1455

    
1456
function system_setup_sysctl() {
1457
	global $config;
1458
	if(isset($config['system']['developerspew'])) {
1459
		$mt = microtime();
1460
		echo "system_setup_sysctl() being called $mt\n";
1461
	}
1462

    
1463
	activate_sysctls();	
1464

    
1465
	if (isset($config['system']['sharednet'])) {
1466
		system_disable_arp_wrong_if();
1467
	}
1468
}
1469

    
1470
function system_disable_arp_wrong_if() {
1471
	global $config;
1472
	if(isset($config['system']['developerspew'])) {
1473
		$mt = microtime();
1474
		echo "system_disable_arp_wrong_if() being called $mt\n";
1475
	}
1476
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1477
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1478
}
1479

    
1480
function system_enable_arp_wrong_if() {
1481
	global $config;
1482
	if(isset($config['system']['developerspew'])) {
1483
		$mt = microtime();
1484
		echo "system_enable_arp_wrong_if() being called $mt\n";
1485
	}
1486
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1487
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1488
}
1489

    
1490
function enable_watchdog() {
1491
	global $config;
1492
	return;
1493
	$install_watchdog = false;
1494
	$supported_watchdogs = array("Geode");
1495
	$file = file_get_contents("/var/log/dmesg.boot");
1496
	foreach($supported_watchdogs as $sd) {
1497
		if(stristr($file, "Geode")) {
1498
			$install_watchdog = true;
1499
		}
1500
	}
1501
	if($install_watchdog == true) {
1502
		if(is_process_running("watchdogd"))
1503
			mwexec("/usr/bin/killall watchdogd", true);
1504
		exec("/usr/sbin/watchdogd");
1505
	}
1506
}
1507

    
1508
function system_check_reset_button() {
1509
	global $g;
1510
	if($g['platform'] != "nanobsd")
1511
		return 0;
1512

    
1513
	$specplatform = system_identify_specific_platform();
1514

    
1515
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1516
		return 0;
1517

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

    
1520
	if ($retval == 99) {
1521
		/* user has pressed reset button for 2 seconds - 
1522
		   reset to factory defaults */
1523
		echo <<<EOD
1524

    
1525
***********************************************************************
1526
* Reset button pressed - resetting configuration to factory defaults. *
1527
* The system will reboot after this completes.                        *
1528
***********************************************************************
1529

    
1530

    
1531
EOD;
1532
		
1533
		reset_factory_defaults();
1534
		system_reboot_sync();
1535
		exit(0);
1536
	}
1537

    
1538
	return 0;
1539
}
1540

    
1541
/* attempt to identify the specific platform (for embedded systems)
1542
   Returns an array with two elements:
1543
	name => platform string (e.g. 'wrap', 'alix' etc.)
1544
	descr => human-readable description (e.g. "PC Engines WRAP")
1545
*/
1546
function system_identify_specific_platform() {
1547
	global $g;
1548
	
1549
	if ($g['platform'] == 'generic-pc')
1550
		return array('name' => 'generic-pc', 'descr' => gettext("Generic PC"));
1551
	
1552
	if ($g['platform'] == 'generic-pc-cdrom')
1553
		return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)"));
1554
	
1555
	/* the rest of the code only deals with 'embedded' platforms */
1556
	if ($g['platform'] != 'nanobsd')
1557
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1558
	
1559
	$dmesg = system_get_dmesg_boot();
1560
	
1561
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1562
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
1563
	
1564
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1565
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
1566

    
1567
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1568
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1569
	
1570
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1571
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1572
		
1573
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1574
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1575
	
1576
	/* unknown embedded platform */
1577
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
1578
}
1579

    
1580
function system_get_dmesg_boot() {
1581
	global $g;
1582
		
1583
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1584
}
1585

    
1586
function get_possible_listen_ips() {
1587
	$interfaces = get_configured_interface_with_descr();
1588
	$carplist = get_configured_carp_interface_list();
1589
	$listenips = array();
1590
	foreach ($carplist as $cif => $carpip)
1591
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1592
	$aliaslist = get_configured_ip_aliases_list();
1593
	foreach ($aliaslist as $aliasip => $aliasif)
1594
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1595
	foreach ($interfaces as $iface => $ifacename) {
1596
		$tmp["name"]  = $ifacename;
1597
		$tmp["value"] = $iface;
1598
		$listenips[] = $tmp;
1599
	}
1600
	$tmp["name"]  = "Localhost";
1601
	$tmp["value"] = "lo0";
1602
	$listenips[] = $tmp;
1603
	return $listenips;
1604
}
1605

    
1606
?>
(50-50/65)