Project

General

Profile

Download (32.2 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
/* include all configuration functions */
33
require_once("functions.inc");
34

    
35
function activate_powerd() {
36
	global $config, $g;
37
	if(isset($config['system']['powerd_enable'])) {
38
		exec("/usr/sbin/powerd -b adp -a adp");
39
	} else {
40
		exec("/usr/bin/killall powerd");
41
	}
42
}
43

    
44
function activate_sysctls() {
45
	global $config, $g;
46
	
47
	exec("/sbin/sysctl net.enc.out.ipsec_bpf_mask=0x00000000");
48
	exec("/sbin/sysctl net.enc.out.ipsec_filter_mask=0x00000001");
49
	exec("/sbin/sysctl net.enc.in.ipsec_bpf_mask=0x00000000");
50
	exec("/sbin/sysctl net.enc.in.ipsec_filter_mask=0x00000002");
51

    
52
	if (is_array($config['sysctl'])) 
53
		foreach ($config['sysctl']['item'] as $tunable) 
54
			mwexec("sysctl " . $tunable['tunable'] . "=\"" 
55
				. $tunable['value'] .  "\"");
56
}
57

    
58
function system_resolvconf_generate($dynupdate = false) {
59
	global $config, $g;
60

    
61
	if(isset($config['system']['developerspew'])) {
62
		$mt = microtime();
63
		echo "system_resolvconf_generate() being called $mt\n";
64
	}
65

    
66
        $syscfg = $config['system'];
67

    
68
        $fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
69
        if (!$fd) {
70
                printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
71
                return 1;
72
        }
73

    
74
        $resolvconf = "domain {$syscfg['domain']}\n";
75

    
76
        $havedns = false;
77

    
78
        if (isset($syscfg['dnsallowoverride'])) {
79
		/* get dynamically assigned DNS servers (if any) */
80
		$ns = array_unique(get_nameservers());
81
		foreach($ns as $nameserver) {
82
			if($nameserver) {
83
				$resolvconf .= "nameserver $nameserver\n";
84
				$havedns = true;
85
			}
86
		}
87
        }
88
        if (!$havedns && is_array($syscfg['dnsserver'])) {
89
		foreach ($syscfg['dnsserver'] as $ns) {
90
			if ($ns) {
91
				$resolvconf .= "nameserver $ns\n";
92
				$havedns = true;
93
			}
94
		}
95
	}
96

    
97
        fwrite($fd, $resolvconf);
98
        fclose($fd);
99

    
100
        if (!$g['booting']) {
101
		/* restart dhcpd (nameservers may have changed) */
102
		if (!$dynupdate)
103
			services_dhcpd_configure();
104
        }
105

    
106
	/* setup static routes for DNS servers. */
107
	for ($dnscounter=1; $dnscounter<5; $dnscounter++) {
108
		/* setup static routes for dns servers */
109
		$dnsgw = "dns{$dnscounter}gwint";
110
		if (isset($config['system'][$dnsgw])) {
111
			$interface = $config['system'][$dnsgw];
112
			if (($interface <> "") && ($interface <> "none")) {
113
				$gatewayip = get_interface_gateway($interface);
114
				if(is_ipaddr($gatewayip)) {
115
					/* dns server array starts at 0 */
116
					$dnscountermo = $dnscounter - 1;
117
					mwexec("route delete -host {$syscfg['dnsserver'][$dnscountermo]}");
118
					mwexec("route add -host {$syscfg['dnsserver'][$dnscountermo]} {$gatewayip}");
119
				}
120
			}
121
		}
122
	}
123
	
124
	return 0;
125
}
126

    
127
function get_nameservers() {
128
	global $config, $g;
129
	$master_list = array();
130
	$dns_lists = split("\n", `ls /var/etc/nameserver_* 2>/dev/null`);
131
	if(is_array($dns_lists)) {
132
		foreach($dns_lists as $dns) {
133
			if(!$dns) 
134
				continue;
135
			$items = split("\n", file_get_contents($dns));
136
			foreach($items as $item)
137
				if($item <> "")
138
					$master_list[] = $item;
139
		}
140
	}
141
	if(!file_exists("/var/etc/nameservers.conf"))
142
		return $master_list;
143
	$dns = `cat /var/etc/nameservers.conf`;
144
	$dns_s = split("\n", $dns);
145
	if(is_array($dns_s))
146
		foreach($dns_s as $dns)
147
			$master_list[] = $dns;
148
	return $master_list;
149
}
150

    
151
function system_hosts_generate() {
152
	global $config, $g;
153
	if(isset($config['system']['developerspew'])) {
154
		$mt = microtime();
155
		echo "system_hosts_generate() being called $mt\n";
156
	}
157

    
158
	$syscfg = $config['system'];
159
	$lancfg = $config['interfaces']['lan'];
160
	$lancfgip = get_interface_ip("lan");
161
	$dnsmasqcfg = $config['dnsmasq'];
162

    
163
	if (!is_array($dnsmasqcfg['hosts'])) {
164
		$dnsmasqcfg['hosts'] = array();
165
	}
166
	$hostscfg = $dnsmasqcfg['hosts'];
167

    
168
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
169
	if (!$fd) {
170
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
171
		return 1;
172
	}
173

    
174
	$hosts = <<<EOD
175
127.0.0.1	localhost localhost.{$syscfg['domain']}
176

    
177
EOD;
178
	if (is_ipaddr($lancfgip))
179
		$hosts .= <<<EOD
180
{$lancfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}
181

    
182
EOD;
183

    
184
	foreach ($hostscfg as $host) {
185
		if ($host['host'])
186
			$hosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
187
		else
188
			$hosts .= "{$host['ip']}	{$host['domain']}\n";
189
	}
190
	if (isset($dnsmasqcfg['regdhcpstatic'])) {
191
		foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf)
192
			if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
193
					foreach ($dhcpifconf['staticmap'] as $host)
194
						if ($host['ipaddr'] && $host['hostname'])
195
							$hosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
196
	}
197
	fwrite($fd, $hosts);
198
	fclose($fd);
199

    
200
	return 0;
201
}
202

    
203
function system_hostname_configure() {
204
	global $config, $g;
205
	if(isset($config['system']['developerspew'])) {
206
		$mt = microtime();
207
		echo "system_hostname_configure() being called $mt\n";
208
	}
209

    
210
	$syscfg = $config['system'];
211

    
212
	/* set hostname */
213
	return mwexec("/bin/hostname " .
214
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
215
}
216

    
217
function system_routing_configure() {
218
	global $config, $g;
219
	if(isset($config['system']['developerspew'])) {
220
		$mt = microtime();
221
		echo "system_routing_configure() being called $mt\n";
222
	}
223

    
224
	/* Enable fast routing, if enabled */
225
	if(isset($config['staticroutes']['enablefastrouting']))
226
		mwexec("/sbin/sysctl net.inet.ip.fastforwarding=1");
227

    
228
	$route_str = exec_command("/usr/bin/netstat -rn");
229

    
230
	/* clear out old routes, if necessary */
231
	if (file_exists("{$g['vardb_path']}/routes.db")) {
232
		$fd = fopen("{$g['vardb_path']}/routes.db", "r");
233
		if (!$fd) {
234
			printf("Error: cannot open routes DB file in system_routing_configure().\n");
235
			return 1;
236
		}
237
		while (!feof($fd)) {
238
			$oldrt = trim(fgets($fd));
239
			if (($oldrt) && (stristr($route_str, $oldrt)))
240
				mwexec("/sbin/route delete " . escapeshellarg($oldrt));
241
		}
242
		fclose($fd);
243
		unlink("{$g['vardb_path']}/routes.db");
244
	}
245

    
246
	/* if list */
247
	$iflist = get_configured_interface_list();
248

    
249
	$dont_remove_route = false;
250
	foreach ($iflist as $ifent => $ifname) {
251
		/* 
252
		 * XXX: The value of this is really when this function can take
253
		 * 	an interface as parameter.
254
		 */
255
		/* do not process interfaces that will end up with gateways */
256
		if (interface_has_gateway($ifent) || 
257
			$config['interfaces'][$ifent]['ipaddr'] == "carpdev-dhcp") {
258
			$dont_remove_route = true;
259
			break;
260
		}
261
	}
262

    
263
	if ($dont_remove_route == false) {
264
		/* remove default route */
265
		mwexec("/sbin/route delete default", true);
266
	}
267

    
268
	$dont_add_route = false;
269
	/* if OLSRD is enabled, allow WAN to house DHCP. */
270
	if($config['installedpackages']['olsrd']) {
271
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
272
			if($olsrd['enabledyngw'] == "on") {
273
				$dont_add_route = true;
274
				break;
275
			}
276
		}
277
	}
278

    
279
	if($dont_add_route == false) {
280
		if(is_array($config['gateways']['gateway_item'])) {
281
			foreach($config['gateways']['gateway_item'] as $gateway) {
282
		        	if(isset($gateway['defaultgw'])) {
283
					$gatewayip = $gateway['gateway'];
284
					$interfacegw = $gateway['interface'];
285
				}
286
			}
287
			if(($interfacegw <> "bgpd") && (is_ipaddr($gatewayip)))
288
				mwexec("/sbin/route add default " . escapeshellarg($gatewayip), true);
289
		} else {
290
			/* FIXME */
291
			/* adding gateway for 1.2-style configs without the new
292
			  gateway setup configured.
293
			  Force WAN to be default gateway because that is the
294
			  1.2 behavior.
295
			*/
296
			if (is_ipaddr($config['interfaces']['wan']['gateway'])) {
297
				$gatewayip = $config['interfaces']['wan']['gateway'];
298
				mwexec("/sbin/route add default " . escapeshellarg($gatewayip), true);
299
			}
300
		}
301
	}
302

    
303
	if (is_array($config['staticroutes']['route'])) {
304

    
305
		$fd = fopen("{$g['vardb_path']}/routes.db", "w");
306
		if (!$fd) {
307
			printf("Error: cannot open routes DB file in system_routing_configure().\n");
308
			return 1;
309
		}
310

    
311
		foreach ($config['staticroutes']['route'] as $rtent) {
312
			if(is_array($config['gateways']['gateway_item'])) {
313
				foreach($config['gateways']['gateway_item'] as $gateway) {
314
					if($rtent['gateway'] == $gateway['name']) {
315
						$gatewayip = $gateway['gateway'];
316
						$interfacegw = $gateway['interface'];
317
					}
318
				}
319
			}
320
			if((is_ipaddr($rtent['gateway'])) && ($gatewayip == ""))  {
321
				$gatewayip = $rtent['gateway'];
322
				$interfacegw = $rtent['interface'];
323
			}			
324
			if(isset($rtent['interfacegateway'])) {
325
				mwexec("/sbin/route add " . escapeshellarg($rtent['network']) .
326
					" -iface " . escapeshellarg(convert_friendly_interface_to_real_interface_name($interfacegw)));
327
			} else {
328
				mwexec("/sbin/route add " . escapeshellarg($rtent['network']) .
329
					" " . escapeshellarg($gatewayip));
330
			}
331
			/* record route so it can be easily removed later (if necessary) */
332
			fwrite($fd, $rtent['network'] . "\n");
333
		}
334
		fclose($fd);
335
	}
336

    
337
	return 0;
338
}
339

    
340

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

    
348
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
349
}
350

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

    
358
	$syslogcfg = $config['syslog'];
359

    
360
	if ($g['booting'])
361
		echo "Starting syslog...";
362
	else
363
		killbypid("{$g['varrun_path']}/syslog.pid");
364

    
365
	mwexec("/usr/bin/killall -9 syslogd");
366
	mwexec("/usr/bin/killall -9 fifolog_writer");
367
	
368
	// Define carious commands for logging
369
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
370
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
371
	$clog_create = "/usr/sbin/clog -i -s ";
372
	$clog_log = "%";
373

    
374
	// Which logging type are we using this week??
375
	if(isset($config['system']['usefifolog'])) {
376
		$log_directive = $fifolog_log;
377
		$log_create_directive = $fifolog_create;		
378
	} else { // Defaults to CLOG
379
		$log_directive = $clog_log;
380
		$log_create_directive = $clog_create;
381
	}
382
	
383
	if (isset($syslogcfg)) {
384
		$separatelogfacilities = array('ntpd','racoon','openvpn');
385
		if($config['installedpackages']['package']) {
386
			foreach($config['installedpackages']['package'] as $package) {
387
				if($package['logging']) {
388
					$pkgfacilities[] = $package['logging']['facilityname'];
389
					$separatelogfacilities = $separatelogfacilities + $pkgfacilities;
390
					$facilitylist = implode(',', $pkgfacilities);
391
					mwexec("{$log_create_directive} 10240 {$g['varlog_path']}/{$package['logging']['logfilename']}");
392
					$syslogconf .= "!{$facilitylist}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
393
				}
394
			}
395
		}
396
		$facilitylist = implode(',', array_unique($separatelogfacilities));
397
		/* write syslog.conf */		
398
		$fd = fopen("{$g['varetc_path']}/syslog.conf", "w");
399
		if (!$fd) {
400
			printf("Error: cannot open syslog.conf in system_syslogd_start().\n");
401
			return 1;
402
		}
403
		$syslogconf .= "!ntpdate,!ntpd\n";
404
		if (!isset($syslogcfg['disablelocallogging'])) 
405
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/ntpd.log\n";
406
		$syslogconf .= "!racoon\n";
407
		if (!isset($syslogcfg['disablelocallogging'])) 
408
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/ipsec.log\n";
409
		if (isset($syslogcfg['vpn'])) 
410
			$syslogconf .= "*.*					 @{$syslogcfg['remoteserver']}\n";
411
		$syslogconf .= "!openvpn\n";
412
		if (!isset($syslogcfg['disablelocallogging'])) 
413
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/openvpn.log\n";
414
		if (isset($syslogcfg['vpn'])) 
415
			$syslogconf .= "*.*					 @{$syslogcfg['remoteserver']}\n";
416
		$syslogconf .= "!-{$facilitylist}\n";
417
		if (!isset($syslogcfg['disablelocallogging'])) 
418
			$syslogconf .= <<<EOD
419
local0.*										 {$log_directive}{$g['varlog_path']}/filter.log
420
local3.*										 {$log_directive}{$g['varlog_path']}/vpn.log
421
local4.*										 {$log_directive}{$g['varlog_path']}/portalauth.log
422
local7.*										 {$log_directive}{$g['varlog_path']}/dhcpd.log
423
*.notice;kern.debug;lpr.info;mail.crit; 		 {$log_directive}{$g['varlog_path']}/system.log
424
news.err;local0.none;local3.none;local4.none; 	 {$log_directive}{$g['varlog_path']}/system.log
425
local7.none										 {$log_directive}{$g['varlog_path']}/system.log
426
security.*										 {$log_directive}{$g['varlog_path']}/system.log
427
auth.info;authpriv.info;daemon.info				 {$log_directive}{$g['varlog_path']}/system.log
428
local1.*										 {$log_directive}{$g['varlog_path']}/relayd.log
429
auth.info;authpriv.info 						 |exec /usr/local/sbin/sshlockout_pf
430
*.emerg											 *
431

    
432
EOD;
433
		if (isset($syslogcfg['filter'])) 
434
			$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver']}\n";
435
		if (isset($syslogcfg['vpn'])) 
436
			$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver']}\n";
437
		if (isset($syslogcfg['portalauth'])) 
438
			$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver']}\n";
439
		if (isset($syslogcfg['dhcp'])) 
440
			$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver']}\n";
441
		if (isset($syslogcfg['system'])) 
442
			$syslogconf .= <<<EOD
443
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver']}
444
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver']}
445
security.*										 @{$syslogcfg['remoteserver']}
446
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver']}
447
*.emerg											 @{$syslogcfg['remoteserver']}
448

    
449
EOD;
450
		fwrite($fd, $syslogconf);
451
		fclose($fd);
452
		// Are we logging to a least one remote server ?
453
		if(strpos($syslogconf, "@") != false)
454
			$retval = system("/usr/sbin/syslogd -f {$g['varetc_path']}/syslog.conf");
455
		else
456
			$retval = system("/usr/sbin/syslogd -f {$g['varetc_path']}/syslog.conf");
457

    
458
	} else {
459
		$retval = mwexec("/usr/sbin/syslogd");
460
	}
461

    
462
	if ($g['booting'])
463
		echo "done.\n";
464

    
465
	return $retval;
466
}
467

    
468
function system_pccard_start() {
469
	global $config, $g;
470
	if(isset($config['system']['developerspew'])) {
471
		$mt = microtime();
472
		echo "system_pccard_start() being called $mt\n";
473
	}
474

    
475
	if ($g['booting'])
476
		echo "Initializing PCMCIA...";
477

    
478
	/* kill any running pccardd */
479
	killbypid("{$g['varrun_path']}/pccardd.pid");
480

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

    
484
	if ($g['booting']) {
485
		if ($res == 0)
486
			echo "done.\n";
487
		else
488
			echo "failed!\n";
489
	}
490

    
491
	return $res;
492
}
493

    
494

    
495
function system_webgui_start() {
496
	global $config, $g;
497

    
498
	if ($g['booting'])
499
		echo "Starting webConfigurator...";
500

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

    
504
	sleep(1);
505

    
506
	chdir($g['www_path']);
507

    
508
	/* defaults */
509
	$portarg = "80";
510
	$crt = "";
511
	$key = "";
512

    
513
	/* non-standard port? */
514
	if ($config['system']['webgui']['port'])
515
		$portarg = "{$config['system']['webgui']['port']}";
516

    
517
	if ($config['system']['webgui']['protocol'] == "https") {
518

    
519
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
520
		if(is_array($cert) && $cert['crt'] && $cert['prv']) {
521
			$crt = base64_decode($cert['crt']);
522
			$key = base64_decode($cert['prv']);
523
			if(!$config['system']['webgui']['port'])
524
				$portarg = "443";
525
		} else
526
			log_error("Invalid webConfigurator https certificate, defaulting to http");
527
	}
528

    
529
	/* generate lighttpd configuration */
530
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
531
		$crt, $key, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/");
532

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

    
536
	if ($g['booting']) {
537
		if ($res == 0)
538
			echo "done.\n";
539
		else
540
			echo "failed!\n";
541
	}
542

    
543
	return $res;
544
}
545

    
546
function system_generate_lighty_config($filename,
547
	$cert,
548
	$key,
549
	$pid_file,
550
	$port = 80,
551
	$document_root = "/usr/local/www/",
552
	$cert_location = "cert.pem",
553
	$max_procs = 2,
554
	$max_requests = "1",
555
	$fast_cgi_enable = true,
556
	$captive_portal = false) {
557

    
558
	global $config, $g;
559

    
560
	if(isset($config['system']['developerspew'])) {
561
		$mt = microtime();
562
		echo "system_generate_lighty_config() being called $mt\n";
563
	}
564

    
565
	if($captive_portal == true)  {
566
		$captiveportal = ",\"mod_rewrite\"";
567
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?redirurl=$1\" )\n";
568
		$captive_portal_module = "\"mod_accesslog\", ";
569
		$maxprocperip = $config['captiveportal']['maxprocperip'];
570
		if(!$maxprocperip and $maxprocperip > 0)
571
			$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
572
		else
573
			$captive_portal_mod_evasive = "";
574
		$server_upload_dirs = "server.upload-dirs = ( \"/tmp/captiveportal/\" )\n";
575
		exec("mkdir -p /tmp/captiveportal");
576
		exec("chmod a-w /tmp/captiveportal");
577
		$server_max_request_size = "server.max-request-size    = 384";
578
	} else {
579
		$captive_portal_module = "";
580
		$captive_portal_mod_evasive = "";
581
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"/tmp/\", \"/var/\" )\n";
582
		$server_max_request_size = "server.max-request-size    = 2097152";
583
	}
584
	
585
	if($port <> "")
586
		$lighty_port = $port;
587
	else
588
		$lighty_port = "80";
589

    
590
	$memory = get_memory();
591
	$avail = $memory[0];
592

    
593
	if($avail > 0 and $avail < 98) {
594
		$max_procs = 1;
595
		$max_requests = 1;
596
	}
597

    
598
	if($avail > 97 and $avail < 128) {
599
		$max_procs = 1;
600
		$max_requests = 3;
601
	}
602

    
603
	if($avail > 127 and $avail < 256) {
604
		$max_procs = 1;
605
		$max_requests = 5;
606
	}
607

    
608
	if($avail > 255 and $avail < 384) {
609
		$max_procs = 3;
610
		$max_requests = 10;
611
	}
612

    
613
	if($avail > 383) {
614
		$max_procs = 4;
615
		$max_requests = 16;
616
	}
617

    
618
	if($captive_portal == true)  {	
619
		$bin_environment =  <<<EOC
620
        "bin-environment" => (
621
           "PHP_FCGI_CHILDREN" => "16",
622
           "PHP_FCGI_MAX_REQUESTS" => "{$max_requests}"
623
        ), 
624
EOC;
625

    
626
	} else if ($avail > 0 and $avail < 128) {
627
		$bin_environment = <<<EOC
628
	"bin-environment" => (
629
		"PHP_FCGI_CHILDREN" => "1",
630
		"PHP_FCGI_MAX_REQUESTS" => "{$max_requests}"
631
	),
632

    
633
EOC;
634
	} else
635
		$bin_environment = "";
636
		
637
	if($fast_cgi_enable == true) {
638
		$module = "\"mod_fastcgi\", \"mod_cgi\"";
639
		$cgi_config = "";
640
		$fastcgi_config = <<<EOD
641
#### fastcgi module
642
## read fastcgi.txt for more info
643
fastcgi.server = ( ".php" =>
644
	( "localhost" =>
645
		(
646
			"socket" => "/tmp/php-fastcgi.socket",
647
			"min-procs" => 1,
648
			"max-procs" => {$max_procs},
649
			{$bin_environment}			
650
			"bin-path" => "/usr/local/bin/php"
651
		)
652
	)
653
)
654

    
655
#### CGI module
656
cgi.assign                 = ( ".cgi" => "" )
657

    
658
EOD;
659
	} else {
660
		$fastcgi_config = "";
661
		$module = "\"mod_cgi\"";
662
		$cgi_config = <<<EOD
663
#### CGI module
664
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
665
                               ".cgi" => "" )
666

    
667
EOD;
668
	}
669

    
670
	$lighty_config .= <<<EOD
671
#
672
# lighttpd configuration file
673
#
674
# use a it as base for lighttpd 1.0.0 and above
675
#
676
############ Options you really have to take care of ####################
677

    
678
## FreeBSD!
679
server.event-handler	= "freebsd-kqueue"
680
server.network-backend 	= "writev"
681

    
682
## modules to load
683
server.modules              =   (
684
									{$captive_portal_module}
685
									"mod_access", "mod_accesslog", "mod_expire", "mod_compress",
686
									{$module}{$captiveportal}
687
								)
688

    
689
## Unused modules
690
#                               "mod_setenv",
691
#                               "mod_compress"
692
#				"mod_redirect",
693
#                               "mod_rewrite",
694
#                               "mod_ssi",
695
#                               "mod_usertrack",
696
#                               "mod_expire",
697
#                               "mod_secdownload",
698
#                               "mod_rrdtool",
699
#                               "mod_auth",
700
#                               "mod_status",
701
#                               "mod_alias",
702
#                               "mod_proxy",
703
#                               "mod_simple_vhost",
704
#                               "mod_evhost",
705
#                               "mod_userdir",
706
#                               "mod_cgi",
707
#                                "mod_accesslog"
708

    
709
server.max-keep-alive-requests = 15
710
server.max-keep-alive-idle = 30
711

    
712
## a static document-root, for virtual-hosting take look at the
713
## server.virtual-* options
714
server.document-root        = "{$document_root}"
715
{$captive_portal_rewrite}
716

    
717
# Maximum idle time with nothing being written (php downloading)
718
server.max-write-idle = 999
719

    
720
## where to send error-messages to
721
server.errorlog             = "/var/log/lighttpd.error.log"
722

    
723
# files to check for if .../ is requested
724
server.indexfiles           = ( "index.php", "index.html",
725
                                "index.htm", "default.htm" )
726

    
727
# mimetype mapping
728
mimetype.assign             = (
729
  ".pdf"          =>      "application/pdf",
730
  ".sig"          =>      "application/pgp-signature",
731
  ".spl"          =>      "application/futuresplash",
732
  ".class"        =>      "application/octet-stream",
733
  ".ps"           =>      "application/postscript",
734
  ".torrent"      =>      "application/x-bittorrent",
735
  ".dvi"          =>      "application/x-dvi",
736
  ".gz"           =>      "application/x-gzip",
737
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
738
  ".swf"          =>      "application/x-shockwave-flash",
739
  ".tar.gz"       =>      "application/x-tgz",
740
  ".tgz"          =>      "application/x-tgz",
741
  ".tar"          =>      "application/x-tar",
742
  ".zip"          =>      "application/zip",
743
  ".mp3"          =>      "audio/mpeg",
744
  ".m3u"          =>      "audio/x-mpegurl",
745
  ".wma"          =>      "audio/x-ms-wma",
746
  ".wax"          =>      "audio/x-ms-wax",
747
  ".ogg"          =>      "audio/x-wav",
748
  ".wav"          =>      "audio/x-wav",
749
  ".gif"          =>      "image/gif",
750
  ".jpg"          =>      "image/jpeg",
751
  ".jpeg"         =>      "image/jpeg",
752
  ".png"          =>      "image/png",
753
  ".xbm"          =>      "image/x-xbitmap",
754
  ".xpm"          =>      "image/x-xpixmap",
755
  ".xwd"          =>      "image/x-xwindowdump",
756
  ".css"          =>      "text/css",
757
  ".html"         =>      "text/html",
758
  ".htm"          =>      "text/html",
759
  ".js"           =>      "text/javascript",
760
  ".asc"          =>      "text/plain",
761
  ".c"            =>      "text/plain",
762
  ".conf"         =>      "text/plain",
763
  ".text"         =>      "text/plain",
764
  ".txt"          =>      "text/plain",
765
  ".dtd"          =>      "text/xml",
766
  ".xml"          =>      "text/xml",
767
  ".mpeg"         =>      "video/mpeg",
768
  ".mpg"          =>      "video/mpeg",
769
  ".mov"          =>      "video/quicktime",
770
  ".qt"           =>      "video/quicktime",
771
  ".avi"          =>      "video/x-msvideo",
772
  ".asf"          =>      "video/x-ms-asf",
773
  ".asx"          =>      "video/x-ms-asf",
774
  ".wmv"          =>      "video/x-ms-wmv",
775
  ".bz2"          =>      "application/x-bzip",
776
  ".tbz"          =>      "application/x-bzip-compressed-tar",
777
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
778
 )
779

    
780
# Use the "Content-Type" extended attribute to obtain mime type if possible
781
#mimetypes.use-xattr        = "enable"
782

    
783
#### accesslog module
784
#accesslog.filename          = "/dev/null"
785

    
786
## deny access the file-extensions
787
#
788
# ~    is for backupfiles from vi, emacs, joe, ...
789
# .inc is often used for code includes which should in general not be part
790
#      of the document-root
791
url.access-deny             = ( "~", ".inc" )
792

    
793

    
794
######### Options that are good to be but not neccesary to be changed #######
795

    
796
## bind to port (default: 80)
797
server.port                = {$lighty_port}
798

    
799
## error-handler for status 404
800
#server.error-handler-404   = "/error-handler.html"
801
#server.error-handler-404   = "/error-handler.php"
802

    
803
## to help the rc.scripts
804
server.pid-file            = "/var/run/{$pid_file}"
805

    
806
## virtual directory listings
807
server.dir-listing         = "disable"
808

    
809
## enable debugging
810
debug.log-request-header   = "disable"
811
debug.log-response-header  = "disable"
812
debug.log-request-handling = "disable"
813
debug.log-file-not-found   = "disable"
814

    
815
{$server_upload_dirs}
816

    
817
{$server_max_request_size}
818

    
819
{$fastcgi_config}
820

    
821
{$cgi_config}
822

    
823
{$captive_portal_mod_evasive}
824

    
825
# Turn on Lighty caching directives
826
compress.cache-dir         = "/tmp/"
827
compress.filetype          = ("text/plain", "text/html", "text/javascript", "text/css")
828

    
829
expire.url = (
830
				"" => "access 50 hours",	
831
        )
832

    
833
EOD;
834

    
835
	$cert = str_replace("\r", "", $cert);
836
	$key = str_replace("\r", "", $key);
837

    
838
	$cert = str_replace("\n\n", "\n", $cert);
839
	$key = str_replace("\n\n", "\n", $key);
840

    
841
	if($cert <> "" and $key <> "") {
842
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
843
		if (!$fd) {
844
			printf("Error: cannot open cert.pem in system_webgui_start().\n");
845
			return 1;
846
		}
847
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
848
		fwrite($fd, $cert);
849
		fwrite($fd, "\n");
850
		fwrite($fd, $key);
851
		fclose($fd);
852
		$lighty_config .= "\n";
853
		$lighty_config .= "## ssl configuration\n";
854
		$lighty_config .= "ssl.engine = \"enable\"\n";
855
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
856
	}
857

    
858
	$fd = fopen("{$filename}", "w");
859
	if (!$fd) {
860
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
861
		return 1;
862
	}
863
	fwrite($fd, $lighty_config);
864
	fclose($fd);
865

    
866
	return 0;
867

    
868
}
869

    
870
function system_timezone_configure() {
871
	global $config, $g;
872
	if(isset($config['system']['developerspew'])) {
873
		$mt = microtime();
874
		echo "system_timezone_configure() being called $mt\n";
875
	}
876

    
877
	$syscfg = $config['system'];
878

    
879
	if ($g['booting'])
880
		echo "Setting timezone...";
881

    
882
	/* extract appropriate timezone file */
883
	$timezone = $syscfg['timezone'];
884
	if (!$timezone)
885
		$timezone = "Etc/UTC";
886

    
887
	conf_mount_rw();
888

    
889
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
890
		escapeshellarg($timezone) . " > /etc/localtime");
891

    
892
	mwexec("sync");
893
	conf_mount_ro();
894

    
895
	if ($g['booting'])
896
		echo "done.\n";
897
}
898

    
899
function system_ntp_configure() {
900
	global $config, $g;
901

    
902
	$syscfg = $config['system'];
903

    
904
	/* open configuration for wrting or bail */
905
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
906
	if(!$fd) {
907
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
908
		return;
909
	}
910

    
911
	fwrite($fd, "# \n");
912
	fwrite($fd, "# pfSense OpenNTPD configuration file \n");
913
	fwrite($fd, "# \n\n");
914

    
915
	/* foreach through servers and write out to ntpd.conf */
916
	foreach (explode(' ', $syscfg['timeservers']) as $ts)
917
		fwrite($fd, "servers {$ts}\n");
918

    
919
	/* Setup listener(s) if the user has configured one */
920
        if ($config['installedpackages']['openntpd']) {
921
    		/* server config is in coregui1 */
922
		$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
923
		if ($xmlsettings['enable'] == 'on') {
924
			$ifaces = explode(',', $xmlsettings['interface']);
925
			$ifaces = array_map('convert_friendly_interface_to_real_interface_name', $ifaces);
926
			$ifaces = array_filter($ifaces, 'does_interface_exist');
927
			$ips = array_map('find_interface_ip', $ifaces);
928
			foreach ($ips as $ip) {
929
				if (is_ipaddr($ip))
930
					fwrite($fd, "listen on $ip\n");
931
			}
932
		}
933
	}
934

    
935
	fwrite($fd, "\n");
936

    
937
	/* slurp! */
938
	fclose($fd);
939

    
940
	/* if openntpd is running, kill it */
941
	while(is_process_running("ntpd")) {
942
		mwexec("/usr/bin/killall ntpd", true);
943
	}
944

    
945
	/* if /var/empty does not exist, create it */
946
	if(!is_dir("/var/empty"))
947
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
948

    
949
	if($g['booting'])
950
		return;
951
	
952
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
953
	exec("/usr/local/sbin/ntpd -s -f {$g['varetc_path']}/ntpd.conf");
954

    
955
}
956

    
957
function sync_system_time() {
958
	global $config, $g;
959

    
960
	$syscfg = $config['system'];
961

    
962
	if ($g['booting'])
963
		echo "Syncing system time before startup...";
964

    
965
	/* foreach through servers and write out to ntpd.conf */
966
	foreach (explode(' ', $syscfg['timeservers']) as $ts) {
967
		mwexec("/usr/sbin/ntpdate -s $ts");
968
	}
969
	
970
	if ($g['booting'])
971
		echo "done.\n";
972
	
973
}
974

    
975
function system_halt() {
976
	global $g;
977

    
978
	system_reboot_cleanup();
979

    
980
	mwexec("nohup /etc/rc.halt > /dev/null 2>&1 &");
981
}
982

    
983
function system_reboot() {
984
	global $g;
985

    
986
	system_reboot_cleanup();
987

    
988
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
989
}
990

    
991
function system_reboot_sync() {
992
	global $g;
993

    
994
	system_reboot_cleanup();
995

    
996
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
997
}
998

    
999
function system_reboot_cleanup() {
1000
	mwexec("/usr/local/bin/beep.sh stop");
1001
	captiveportal_radius_stop_all();
1002
}
1003

    
1004
function system_do_shell_commands($early = 0) {
1005
	global $config, $g;
1006
	if(isset($config['system']['developerspew'])) {
1007
		$mt = microtime();
1008
		echo "system_do_shell_commands() being called $mt\n";
1009
	}
1010

    
1011
	if ($early)
1012
		$cmdn = "earlyshellcmd";
1013
	else
1014
		$cmdn = "shellcmd";
1015

    
1016
	if (is_array($config['system'][$cmdn])) {
1017

    
1018
		/* *cmd is an array, loop through */
1019
		foreach ($config['system'][$cmdn] as $cmd) {
1020
			exec($cmd);
1021
		}
1022

    
1023
	} elseif($config['system'][$cmdn] <> "") {
1024

    
1025
		/* execute single item */
1026
		exec($config['system'][$cmdn]);
1027

    
1028
	}
1029
}
1030

    
1031
function system_console_configure() {
1032
	global $config, $g;
1033
	if(isset($config['system']['developerspew'])) {
1034
		$mt = microtime();
1035
		echo "system_console_configure() being called $mt\n";
1036
	}
1037

    
1038
	if (isset($config['system']['disableconsolemenu'])) {
1039
		touch("{$g['varetc_path']}/disableconsole");
1040
	} else {
1041
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1042
	}
1043
}
1044

    
1045
function system_dmesg_save() {
1046
	global $g;
1047
	if(isset($config['system']['developerspew'])) {
1048
		$mt = microtime();
1049
		echo "system_dmesg_save() being called $mt\n";
1050
	}
1051

    
1052
	$dmesg = "";
1053
	exec("/sbin/dmesg", $dmesg);
1054

    
1055
	/* find last copyright line (output from previous boots may be present) */
1056
	$lastcpline = 0;
1057

    
1058
	for ($i = 0; $i < count($dmesg); $i++) {
1059
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1060
			$lastcpline = $i;
1061
	}
1062

    
1063
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1064
	if (!$fd) {
1065
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1066
		return 1;
1067
	}
1068

    
1069
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1070
		fwrite($fd, $dmesg[$i] . "\n");
1071

    
1072
	fclose($fd);
1073

    
1074
	return 0;
1075
}
1076

    
1077
function system_set_harddisk_standby() {
1078
	global $g, $config;
1079
	if(isset($config['system']['developerspew'])) {
1080
		$mt = microtime();
1081
		echo "system_set_harddisk_standby() being called $mt\n";
1082
	}
1083

    
1084
	if (isset($config['system']['harddiskstandby'])) {
1085
		if ($g['booting']) {
1086
			echo 'Setting hard disk standby... ';
1087
		}
1088

    
1089
		$standby = $config['system']['harddiskstandby'];
1090
		// Check for a numeric value
1091
		if (is_numeric($standby)) {
1092
			// Sync the disk(s)
1093
			mwexec('/bin/sync');
1094
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1095
				// Reinitialize ATA-drives
1096
				mwexec('/usr/local/sbin/atareinit');
1097
				if ($g['booting']) {
1098
					echo "done.\n";
1099
				}
1100
			} else if ($g['booting']) {
1101
				echo "failed!\n";
1102
			}
1103
		} else if ($g['booting']) {
1104
			echo "failed!\n";
1105
		}
1106
	}
1107
}
1108

    
1109
function system_setup_sysctl() {
1110
	global $config;
1111
	if(isset($config['system']['developerspew'])) {
1112
		$mt = microtime();
1113
		echo "system_setup_sysctl() being called $mt\n";
1114
	}
1115

    
1116
	activate_sysctls();	
1117

    
1118
	if (isset($config['system']['sharednet'])) {
1119
		system_disable_arp_wrong_if();
1120
	}
1121
}
1122

    
1123
function system_disable_arp_wrong_if() {
1124
	global $config;
1125
	if(isset($config['system']['developerspew'])) {
1126
		$mt = microtime();
1127
		echo "system_disable_arp_wrong_if() being called $mt\n";
1128
	}
1129
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1130
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1131
}
1132

    
1133
function system_enable_arp_wrong_if() {
1134
	global $config;
1135
	if(isset($config['system']['developerspew'])) {
1136
		$mt = microtime();
1137
		echo "system_enable_arp_wrong_if() being called $mt\n";
1138
	}
1139
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1140
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1141
}
1142

    
1143
function enable_watchdog() {
1144
	global $config;
1145
	$install_watchdog = false;
1146
	$supported_watchdogs = array("Geode");
1147
	$file = file_get_contents("/var/log/dmesg.boot");
1148
	foreach($supported_watchdogs as $sd) {
1149
		if(stristr($file, "Geode")) {
1150
			$install_watchdog = true;
1151
		}
1152
	}
1153
	if($install_watchdog == true) {
1154
		if(is_process_running("watchdogd"))
1155
			mwexec("/usr/bin/killall watchdogd", true);
1156
		exec("/usr/sbin/watchdogd");
1157
	}
1158
}
1159

    
1160
?>
(32-32/40)