Project

General

Profile

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

    
35
function activate_sysctls() {
36
	global $config, $g;
37
	
38
	exec("/sbin/sysctl net.enc.out.ipsec_bpf_mask=0x00000000");
39
	exec("/sbin/sysctl net.enc.out.ipsec_filter_mask=0x00000001");
40
	exec("/sbin/sysctl net.enc.in.ipsec_bpf_mask=0x00000000");
41
	exec("/sbin/sysctl net.enc.in.ipsec_filter_mask=0x00000002");
42

    
43
	if (is_array($config['sysctl'])) 
44
		foreach ($config['sysctl']['item'] as $tunable) 
45
			mwexec("sysctl " . $tunable['tunable'] . "=\"" 
46
				. $tunable['value'] .  "\"");
47
}
48

    
49
function system_resolvconf_generate($dynupdate = false) {
50
	global $config, $g;
51

    
52
	if(isset($config['system']['developerspew'])) {
53
		$mt = microtime();
54
		echo "system_resolvconf_generate() being called $mt\n";
55
	}
56

    
57
        $syscfg = $config['system'];
58

    
59
        $fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
60
        if (!$fd) {
61
                printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
62
                return 1;
63
        }
64

    
65
        $resolvconf = "domain {$syscfg['domain']}\n";
66

    
67
        $havedns = false;
68

    
69
        if (isset($syscfg['dnsallowoverride'])) {
70
		/* get dynamically assigned DNS servers (if any) */
71
		$ns = array_unique(get_nameservers());
72
		foreach($ns as $nameserver) {
73
			if($nameserver) {
74
				$resolvconf .= "nameserver $nameserver\n";
75
				$havedns = true;
76
			}
77
		}
78
        }
79
        if (!$havedns && is_array($syscfg['dnsserver'])) {
80
		foreach ($syscfg['dnsserver'] as $ns) {
81
			if ($ns) {
82
				$resolvconf .= "nameserver $ns\n";
83
				$havedns = true;
84
			}
85
		}
86
	}
87

    
88
        fwrite($fd, $resolvconf);
89
        fclose($fd);
90

    
91
        if (!$g['booting']) {
92
		/* restart dhcpd (nameservers may have changed) */
93
		if (!$dynupdate)
94
			services_dhcpd_configure();
95
        }
96

    
97
	/* setup static routes for DNS servers. */
98
	for ($dnscounter=1; $dnscounter<5; $dnscounter++) {
99
		/* setup static routes for dns servers */
100
		$dnsgw = "dns{$dnscounter}gwint";
101
		if (isset($config['system'][$dnsgw])) {
102
			$interface = $config['system'][$dnsgw];
103
			if (($interface <> "") && ($interface <> "none")) {
104
				$gatewayip = get_interface_gateway($interface);
105
				if(is_ipaddr($gatewayip)) {
106
					/* dns server array starts at 0 */
107
					$dnscountermo = $dnscounter - 1;
108
					mwexec("route delete -host {$syscfg['dnsserver'][$dnscountermo]}");
109
					mwexec("route add -host {$syscfg['dnsserver'][$dnscountermo]} {$gatewayip}");
110
				}
111
			}
112
		}
113
	}
114
	
115
	return 0;
116
}
117

    
118
function get_nameservers() {
119
	global $config, $g;
120
	$master_list = array();
121
	$dns_lists = split("\n", `ls /var/etc/nameserver_* 2>/dev/null`);
122
	if(is_array($dns_lists)) {
123
		foreach($dns_lists as $dns) {
124
			if(!$dns) 
125
				continue;
126
			$items = split("\n", file_get_contents($dns));
127
			foreach($items as $item)
128
				if($item <> "")
129
					$master_list[] = $item;
130
		}
131
	}
132
	if(!file_exists("/var/etc/nameservers.conf"))
133
		return $master_list;
134
	$dns = `cat /var/etc/nameservers.conf`;
135
	$dns_s = split("\n", $dns);
136
	if(is_array($dns_s))
137
		foreach($dns_s as $dns)
138
			$master_list[] = $dns;
139
	return $master_list;
140
}
141

    
142
function system_hosts_generate() {
143
	global $config, $g;
144
	if(isset($config['system']['developerspew'])) {
145
		$mt = microtime();
146
		echo "system_hosts_generate() being called $mt\n";
147
	}
148

    
149
	$syscfg = $config['system'];
150
	$lancfg = $config['interfaces']['lan'];
151
	$dnsmasqcfg = $config['dnsmasq'];
152

    
153
	if (!is_array($dnsmasqcfg['hosts'])) {
154
		$dnsmasqcfg['hosts'] = array();
155
	}
156
	$hostscfg = $dnsmasqcfg['hosts'];
157

    
158
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
159
	if (!$fd) {
160
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
161
		return 1;
162
	}
163

    
164
	$hosts = <<<EOD
165
127.0.0.1	localhost localhost.{$syscfg['domain']}
166
{$lancfg['ipaddr']}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}
167

    
168
EOD;
169

    
170
	foreach ($hostscfg as $host) {
171
		if ($host['host'])
172
			$hosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
173
		else
174
			$hosts .= "{$host['ip']}	{$host['domain']}\n";
175
	}
176
	if (isset($dnsmasqcfg['regdhcpstatic'])) {
177
		foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf)
178
			if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
179
					foreach ($dhcpifconf['staticmap'] as $host)
180
						if ($host['ipaddr'] && $host['hostname'])
181
							$hosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
182
	}
183
	fwrite($fd, $hosts);
184
	fclose($fd);
185

    
186
	return 0;
187
}
188

    
189
function system_hostname_configure() {
190
	global $config, $g;
191
	if(isset($config['system']['developerspew'])) {
192
		$mt = microtime();
193
		echo "system_hostname_configure() being called $mt\n";
194
	}
195

    
196
	$syscfg = $config['system'];
197

    
198
	/* set hostname */
199
	return mwexec("/bin/hostname " .
200
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
201
}
202

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

    
210
	/* Enable fast routing, if enabled */
211
	if(isset($config['staticroutes']['enablefastrouting']))
212
		mwexec("/sbin/sysctl net.inet.ip.fastforwarding=1");
213

    
214
	exec("/usr/bin/netstat -rn", $route_arr, $retval);
215
	$route_str = implode("\n", $route_arr);
216

    
217
	/* clear out old routes, if necessary */
218
	if (file_exists("{$g['vardb_path']}/routes.db")) {
219
		$fd = fopen("{$g['vardb_path']}/routes.db", "r");
220
		if (!$fd) {
221
			printf("Error: cannot open routes DB file in system_routing_configure().\n");
222
			return 1;
223
		}
224
		while (!feof($fd)) {
225
			$oldrt = trim(fgets($fd));
226
			if (($oldrt) && (stristr($route_str, $oldrt)))
227
				mwexec("/sbin/route delete " . escapeshellarg($oldrt));
228
		}
229
		fclose($fd);
230
		unlink("{$g['vardb_path']}/routes.db");
231
	}
232

    
233
	/* if list */
234
	$iflist = get_configured_interface_list();
235

    
236
	$dont_remove_route = false;
237
	foreach ($iflist as $ifent => $ifname) {
238
		/* do not process interfaces that will end up with gateways */
239
		if (interface_has_gateway($ifent))
240
			$dont_remove_route = true;
241
	}
242

    
243
	if($config['interfaces']['wan']['ipaddr'] == "carpdev-dhcp")
244
		$dont_remove_route = true;
245

    
246
	if($dont_remove_route == false) {
247
		/* remove default route */
248
		mwexec("/sbin/route delete default", true);
249
	}
250

    
251
	$dont_add_route = false;
252
	/* if OLSRD is enabled, allow WAN to house DHCP. */
253
	if($config['installedpackages']['olsrd']) {
254
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
255
			if($olsrd['enabledyngw'] == "on") {
256
				$dont_add_route = true;
257
			}
258
		}
259
	}
260

    
261
	if($dont_add_route == false) {
262
		if(is_array($config['gateways']['gateway_item'])) {
263
			foreach($config['gateways']['gateway_item'] as $gateway) {
264
		        	if(isset($gateway['defaultgw'])) {
265
					$gatewayip = $gateway['gateway'];
266
					$interfacegw = $gateway['interface'];
267
				}
268
			}
269
			if(($interfacegw <> "bgpd") && (is_ipaddr($gatewayip)))
270
				mwexec("/sbin/route add default " . escapeshellarg($gatewayip), true);
271
		} else {
272
			/* FIXME */
273
			/* adding gateway for 1.2-style configs without the new
274
			  gateway setup configured.
275
			  Force WAN to be default gateway because that is the
276
			  1.2 behavior.
277
			*/
278
			if (is_ipaddr($config['interfaces']['wan']['gateway'])) {
279
				$gatewayip = $config['interfaces']['wan']['gateway'];
280
				mwexec("/sbin/route add default " . escapeshellarg($gatewayip), true);
281
			}
282
		}
283
	}
284

    
285
	if (is_array($config['staticroutes']['route'])) {
286

    
287
		$fd = fopen("{$g['vardb_path']}/routes.db", "w");
288
		if (!$fd) {
289
			printf("Error: cannot open routes DB file in system_routing_configure().\n");
290
			return 1;
291
		}
292

    
293
		foreach ($config['staticroutes']['route'] as $rtent) {
294
			if(is_array($config['gateways']['gateway_item'])) {
295
				foreach($config['gateways']['gateway_item'] as $gateway) {
296
					if($rtent['gateway'] == $gateway['name']) {
297
						$gatewayip = $gateway['gateway'];
298
						$interfacegw = $gateway['interface'];
299
					}
300
				}
301
			}
302
			if((is_ipaddr($rtent['gateway'])) && ($gatewayip == ""))  {
303
				$gatewayip = $rtent['gateway'];
304
				$interfacegw = $rtent['interface'];
305
			}			
306
			if(isset($rtent['interfacegateway'])) {
307
				mwexec("/sbin/route add " . escapeshellarg($rtent['network']) .
308
					" -iface " . escapeshellarg(convert_friendly_interface_to_real_interface_name($interfacegw)));
309
			} else {
310
				mwexec("/sbin/route add " . escapeshellarg($rtent['network']) .
311
					" " . escapeshellarg($gatewayip));
312
			}
313
			/* record route so it can be easily removed later (if necessary) */
314
			fwrite($fd, $rtent['network'] . "\n");
315
		}
316
		fclose($fd);
317
	}
318

    
319
	return 0;
320
}
321

    
322

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

    
330
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
331
}
332

    
333
function system_syslogd_start() {
334
	global $config, $g;
335
	if(isset($config['system']['developerspew'])) {
336
		$mt = microtime();
337
		echo "system_syslogd_start() being called $mt\n";
338
	}
339

    
340
	$syslogcfg = $config['syslog'];
341

    
342
	if ($g['booting'])
343
		echo "Starting syslog...";
344
	else
345
		killbypid("{$g['varrun_path']}/syslog.pid");
346

    
347
	exec("/usr/bin/killall -9 syslogd");
348
	exec("/usr/bin/killall -9 fifolog_writer");
349

    
350
	if (isset($syslogcfg)) {
351
		$separatelogfacilities = array('ntpd','racoon','openvpn');
352
		if($config['installedpackages']['package']) {
353
			foreach($config['installedpackages']['package'] as $package) {
354
				if($package['logging']) {
355
					$pkgfacilities[] = $package['logging']['facilityname'];
356
					$separatelogfacilities = $separatelogfacilities + $pkgfacilities;
357
					$facilitylist = implode(',', $pkgfacilities);
358
					mwexec("fifolog_create -s 10240 {$g['varlog_path']}/{$package['logging']['logfilename']}");
359
					$syslogconf .= "!{$facilitylist}\n*.*\t\t\t\t\t\t |/usr/sbin/fifolog_writer {$g['varlog_path']}/{$package['logging']['logfilename']}\n";
360
				}
361
			}
362
		}
363
		$facilitylist = implode(',', array_unique($separatelogfacilities));
364
		/* write syslog.conf */		
365
		$fd = fopen("{$g['varetc_path']}/syslog.conf", "w");
366
		if (!$fd) {
367
			printf("Error: cannot open syslog.conf in system_syslogd_start().\n");
368
			return 1;
369
		}
370
		$syslogconf .= "!ntpdate,!ntpd\n";
371
		if (!isset($syslogcfg['disablelocallogging'])) 
372
			$syslogconf .= "*.*					 |/usr/sbin/fifolog_writer {$g['varlog_path']}/ntpd.log\n";
373
		$syslogconf .= "!racoon\n";
374
		if (!isset($syslogcfg['disablelocallogging'])) 
375
			$syslogconf .= "*.*					 |/usr/sbin/fifolog_writer {$g['varlog_path']}/ipsec.log\n";
376
		if (isset($syslogcfg['vpn'])) 
377
			$syslogconf .= "*.*					 @{$syslogcfg['remoteserver']}\n";
378
		$syslogconf .= "!openvpn\n";
379
		if (!isset($syslogcfg['disablelocallogging'])) 
380
			$syslogconf .= "*.*					 |/usr/sbin/fifolog_writer {$g['varlog_path']}/openvpn.log\n";
381
		if (isset($syslogcfg['vpn'])) 
382
			$syslogconf .= "*.*					 @{$syslogcfg['remoteserver']}\n";
383
		$syslogconf .= "!-{$facilitylist}\n";
384
		if (!isset($syslogcfg['disablelocallogging'])) 
385
			$syslogconf .= <<<EOD
386
local0.*										 |/usr/sbin/fifolog_writer {$g['varlog_path']}/filter.log
387
local3.*										 |/usr/sbin/fifolog_writer {$g['varlog_path']}/vpn.log
388
local4.*										 |/usr/sbin/fifolog_writer {$g['varlog_path']}/portalauth.log
389
local7.*										 |/usr/sbin/fifolog_writer {$g['varlog_path']}/dhcpd.log
390
*.notice;kern.debug;lpr.info;mail.crit; 		 |/usr/sbin/fifolog_writer {$g['varlog_path']}/system.log
391
news.err;local0.none;local3.none;local4.none; 	 |/usr/sbin/fifolog_writer {$g['varlog_path']}/system.log
392
local7.none										 |/usr/sbin/fifolog_writer {$g['varlog_path']}/system.log
393
security.*										 |/usr/sbin/fifolog_writer {$g['varlog_path']}/system.log
394
auth.info;authpriv.info;daemon.info				 |/usr/sbin/fifolog_writer {$g['varlog_path']}/system.log
395
local1.*										 |/usr/sbin/fifolog_writer {$g['varlog_path']}/relayd.log
396
auth.info;authpriv.info 						 |exec /usr/local/sbin/sshlockout_pf
397
*.emerg											 *
398

    
399
EOD;
400
		if (isset($syslogcfg['filter'])) 
401
			$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver']}\n";
402
		if (isset($syslogcfg['vpn'])) 
403
			$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver']}\n";
404
		if (isset($syslogcfg['portalauth'])) 
405
			$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver']}\n";
406
		if (isset($syslogcfg['dhcp'])) 
407
			$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver']}\n";
408
		if (isset($syslogcfg['system'])) 
409
			$syslogconf .= <<<EOD
410
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver']}
411
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver']}
412
security.*										 @{$syslogcfg['remoteserver']}
413
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver']}
414
*.emerg											 @{$syslogcfg['remoteserver']}
415

    
416
EOD;
417
		fwrite($fd, $syslogconf);
418
		fclose($fd);
419
		// Are we logging to a least one remote server ?
420
		if(strpos($syslogconf, "@") != false)
421
			$retval = system("/usr/sbin/syslogd -f {$g['varetc_path']}/syslog.conf");
422
		else
423
			$retval = system("/usr/sbin/syslogd -f {$g['varetc_path']}/syslog.conf");
424

    
425
	} else {
426
		$retval = mwexec("/usr/sbin/syslogd");
427
	}
428

    
429
	if ($g['booting'])
430
		echo "done.\n";
431

    
432
	return $retval;
433
}
434

    
435
function system_pccard_start() {
436
	global $config, $g;
437
	if(isset($config['system']['developerspew'])) {
438
		$mt = microtime();
439
		echo "system_pccard_start() being called $mt\n";
440
	}
441

    
442
	if ($g['booting'])
443
		echo "Initializing PCMCIA...";
444

    
445
	/* kill any running pccardd */
446
	killbypid("{$g['varrun_path']}/pccardd.pid");
447

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

    
451
	if ($g['booting']) {
452
		if ($res == 0)
453
			echo "done.\n";
454
		else
455
			echo "failed!\n";
456
	}
457

    
458
	return $res;
459
}
460

    
461

    
462
function system_webgui_start() {
463
	global $config, $g;
464

    
465
	if ($g['booting'])
466
		echo "Starting webConfigurator...";
467

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

    
471
	sleep(1);
472

    
473
	chdir($g['www_path']);
474

    
475
	/* defaults */
476
	$portarg = "80";
477
	$crt = "";
478
	$key = "";
479

    
480
	/* non-standard port? */
481
	if ($config['system']['webgui']['port'])
482
		$portarg = "{$config['system']['webgui']['port']}";
483

    
484
	if ($config['system']['webgui']['protocol'] == "https") {
485

    
486
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
487
		if(is_array($cert) && $cert['crt'] && $cert['prv']) {
488
			$crt = base64_decode($cert['crt']);
489
			$key = base64_decode($cert['prv']);
490
			if(!$config['system']['webgui']['port'])
491
				$portarg = "443";
492
		} else
493
			log_error("Invalid webConfigurator https certificate, defaulting to http");
494
	}
495

    
496
	/* generate lighttpd configuration */
497
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
498
		$crt, $key, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/");
499

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

    
503
	if ($g['booting']) {
504
		if ($res == 0)
505
			echo "done.\n";
506
		else
507
			echo "failed!\n";
508
	}
509

    
510
	return $res;
511
}
512

    
513
function system_generate_lighty_config($filename,
514
	$cert,
515
	$key,
516
	$pid_file,
517
	$port = 80,
518
	$document_root = "/usr/local/www/",
519
	$cert_location = "cert.pem",
520
	$max_procs = 2,
521
	$max_requests = "1",
522
	$fast_cgi_enable = true,
523
	$captive_portal = false) {
524

    
525
	global $config, $g;
526

    
527
	if(isset($config['system']['developerspew'])) {
528
		$mt = microtime();
529
		echo "system_generate_lighty_config() being called $mt\n";
530
	}
531

    
532
	if($captive_portal == true)  {
533
		$captiveportal = ",\"mod_rewrite\"";
534
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?redirurl=$1\" )\n";
535
		$captive_portal_module = "\"mod_accesslog\", ";
536
		$maxprocperip = $config['captiveportal']['maxprocperip'];
537
		if(!$maxprocperip and $maxprocperip > 0)
538
			$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
539
		else
540
			$captive_portal_mod_evasive = "";
541
		$server_upload_dirs = "server.upload-dirs = ( \"/tmp/captiveportal/\" )\n";
542
		exec("mkdir -p /tmp/captiveportal");
543
		exec("chmod a-w /tmp/captiveportal");
544
		$server_max_request_size = "server.max-request-size    = 384";
545
	} else {
546
		$captive_portal_module = "";
547
		$captive_portal_mod_evasive = "";
548
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"/tmp/\", \"/var/\" )\n";
549
		$server_max_request_size = "server.max-request-size    = 2097152";
550
	}
551
	
552
	if($port <> "")
553
		$lighty_port = $port;
554
	else
555
		$lighty_port = "80";
556

    
557
	$memory = get_memory();
558
	$avail = $memory[0];
559

    
560
	if($avail > 0 and $avail < 98) {
561
		$max_procs = 1;
562
		$max_requests = 1;
563
	}
564

    
565
	if($avail > 97 and $avail < 128) {
566
		$max_procs = 1;
567
		$max_requests = 3;
568
	}
569

    
570
	if($avail > 127 and $avail < 256) {
571
		$max_procs = 1;
572
		$max_requests = 5;
573
	}
574

    
575
	if($avail > 255 and $avail < 384) {
576
		$max_procs = 3;
577
		$max_requests = 10;
578
	}
579

    
580
	if($avail > 383) {
581
		$max_procs = 4;
582
		$max_requests = 16;
583
	}
584

    
585
	if($captive_portal == true)  {	
586
		$bin_environment =  <<<EOC
587
        "bin-environment" => (
588
           "PHP_FCGI_CHILDREN" => "16",
589
           "PHP_FCGI_MAX_REQUESTS" => "{$max_requests}"
590
        ), 
591
EOC;
592

    
593
	} else if ($avail > 0 and $avail < 128) {
594
		$bin_environment = <<<EOC
595
	"bin-environment" => (
596
		"PHP_FCGI_CHILDREN" => "1",
597
		"PHP_FCGI_MAX_REQUESTS" => "{$max_requests}"
598
	),
599

    
600
EOC;
601
	} else
602
		$bin_environment = "";
603
		
604
	if($fast_cgi_enable == true) {
605
		$module = "\"mod_fastcgi\", \"mod_cgi\"";
606
		$cgi_config = "";
607
		$fastcgi_config = <<<EOD
608
#### fastcgi module
609
## read fastcgi.txt for more info
610
fastcgi.server = ( ".php" =>
611
	( "localhost" =>
612
		(
613
			"socket" => "/tmp/php-fastcgi.socket",
614
			"min-procs" => 1,
615
			"max-procs" => {$max_procs},
616
			{$bin_environment}			
617
			"bin-path" => "/usr/local/bin/php"
618
		)
619
	)
620
)
621

    
622
#### CGI module
623
cgi.assign                 = ( ".cgi" => "" )
624

    
625
EOD;
626
	} else {
627
		$fastcgi_config = "";
628
		$module = "\"mod_cgi\"";
629
		$cgi_config = <<<EOD
630
#### CGI module
631
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
632
                               ".cgi" => "" )
633

    
634
EOD;
635
	}
636

    
637
	$lighty_config .= <<<EOD
638
#
639
# lighttpd configuration file
640
#
641
# use a it as base for lighttpd 1.0.0 and above
642
#
643
############ Options you really have to take care of ####################
644

    
645
## FreeBSD!
646
server.event-handler	= "freebsd-kqueue"
647
server.network-backend 	= "writev"
648

    
649
## modules to load
650
server.modules              =   (
651
									{$captive_portal_module}
652
									"mod_access", "mod_accesslog", "mod_expire", "mod_compress",
653
									{$module}{$captiveportal}
654
								)
655

    
656
## Unused modules
657
#                               "mod_setenv",
658
#                               "mod_compress"
659
#				"mod_redirect",
660
#                               "mod_rewrite",
661
#                               "mod_ssi",
662
#                               "mod_usertrack",
663
#                               "mod_expire",
664
#                               "mod_secdownload",
665
#                               "mod_rrdtool",
666
#                               "mod_auth",
667
#                               "mod_status",
668
#                               "mod_alias",
669
#                               "mod_proxy",
670
#                               "mod_simple_vhost",
671
#                               "mod_evhost",
672
#                               "mod_userdir",
673
#                               "mod_cgi",
674
#                                "mod_accesslog"
675

    
676
server.max-keep-alive-requests = 15
677
server.max-keep-alive-idle = 30
678

    
679
## a static document-root, for virtual-hosting take look at the
680
## server.virtual-* options
681
server.document-root        = "{$document_root}"
682
{$captive_portal_rewrite}
683

    
684
# Maximum idle time with nothing being written (php downloading)
685
server.max-write-idle = 999
686

    
687
## where to send error-messages to
688
server.errorlog             = "/var/log/lighttpd.error.log"
689

    
690
# files to check for if .../ is requested
691
server.indexfiles           = ( "index.php", "index.html",
692
                                "index.htm", "default.htm" )
693

    
694
# mimetype mapping
695
mimetype.assign             = (
696
  ".pdf"          =>      "application/pdf",
697
  ".sig"          =>      "application/pgp-signature",
698
  ".spl"          =>      "application/futuresplash",
699
  ".class"        =>      "application/octet-stream",
700
  ".ps"           =>      "application/postscript",
701
  ".torrent"      =>      "application/x-bittorrent",
702
  ".dvi"          =>      "application/x-dvi",
703
  ".gz"           =>      "application/x-gzip",
704
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
705
  ".swf"          =>      "application/x-shockwave-flash",
706
  ".tar.gz"       =>      "application/x-tgz",
707
  ".tgz"          =>      "application/x-tgz",
708
  ".tar"          =>      "application/x-tar",
709
  ".zip"          =>      "application/zip",
710
  ".mp3"          =>      "audio/mpeg",
711
  ".m3u"          =>      "audio/x-mpegurl",
712
  ".wma"          =>      "audio/x-ms-wma",
713
  ".wax"          =>      "audio/x-ms-wax",
714
  ".ogg"          =>      "audio/x-wav",
715
  ".wav"          =>      "audio/x-wav",
716
  ".gif"          =>      "image/gif",
717
  ".jpg"          =>      "image/jpeg",
718
  ".jpeg"         =>      "image/jpeg",
719
  ".png"          =>      "image/png",
720
  ".xbm"          =>      "image/x-xbitmap",
721
  ".xpm"          =>      "image/x-xpixmap",
722
  ".xwd"          =>      "image/x-xwindowdump",
723
  ".css"          =>      "text/css",
724
  ".html"         =>      "text/html",
725
  ".htm"          =>      "text/html",
726
  ".js"           =>      "text/javascript",
727
  ".asc"          =>      "text/plain",
728
  ".c"            =>      "text/plain",
729
  ".conf"         =>      "text/plain",
730
  ".text"         =>      "text/plain",
731
  ".txt"          =>      "text/plain",
732
  ".dtd"          =>      "text/xml",
733
  ".xml"          =>      "text/xml",
734
  ".mpeg"         =>      "video/mpeg",
735
  ".mpg"          =>      "video/mpeg",
736
  ".mov"          =>      "video/quicktime",
737
  ".qt"           =>      "video/quicktime",
738
  ".avi"          =>      "video/x-msvideo",
739
  ".asf"          =>      "video/x-ms-asf",
740
  ".asx"          =>      "video/x-ms-asf",
741
  ".wmv"          =>      "video/x-ms-wmv",
742
  ".bz2"          =>      "application/x-bzip",
743
  ".tbz"          =>      "application/x-bzip-compressed-tar",
744
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
745
 )
746

    
747
# Use the "Content-Type" extended attribute to obtain mime type if possible
748
#mimetypes.use-xattr        = "enable"
749

    
750
#### accesslog module
751
#accesslog.filename          = "/dev/null"
752

    
753
## deny access the file-extensions
754
#
755
# ~    is for backupfiles from vi, emacs, joe, ...
756
# .inc is often used for code includes which should in general not be part
757
#      of the document-root
758
url.access-deny             = ( "~", ".inc" )
759

    
760

    
761
######### Options that are good to be but not neccesary to be changed #######
762

    
763
## bind to port (default: 80)
764
server.port                = {$lighty_port}
765

    
766
## error-handler for status 404
767
#server.error-handler-404   = "/error-handler.html"
768
#server.error-handler-404   = "/error-handler.php"
769

    
770
## to help the rc.scripts
771
server.pid-file            = "/var/run/{$pid_file}"
772

    
773
## virtual directory listings
774
server.dir-listing         = "disable"
775

    
776
## enable debugging
777
debug.log-request-header   = "disable"
778
debug.log-response-header  = "disable"
779
debug.log-request-handling = "disable"
780
debug.log-file-not-found   = "disable"
781

    
782
{$server_upload_dirs}
783

    
784
{$server_max_request_size}
785

    
786
{$fastcgi_config}
787

    
788
{$cgi_config}
789

    
790
{$captive_portal_mod_evasive}
791

    
792
# Turn on Lighty caching directives
793
compress.cache-dir         = "/tmp/"
794
compress.filetype          = ("text/plain", "text/html", "text/javascript", "text/css")
795

    
796
expire.url = (
797
				"" => "access 50 hours",	
798
        )
799

    
800
EOD;
801

    
802
	$cert = str_replace("\r", "", $cert);
803
	$key = str_replace("\r", "", $key);
804

    
805
	$cert = str_replace("\n\n", "\n", $cert);
806
	$key = str_replace("\n\n", "\n", $key);
807

    
808
	if($cert <> "" and $key <> "") {
809
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
810
		if (!$fd) {
811
			printf("Error: cannot open cert.pem in system_webgui_start().\n");
812
			return 1;
813
		}
814
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
815
		fwrite($fd, $cert);
816
		fwrite($fd, "\n");
817
		fwrite($fd, $key);
818
		fclose($fd);
819
		$lighty_config .= "\n";
820
		$lighty_config .= "## ssl configuration\n";
821
		$lighty_config .= "ssl.engine = \"enable\"\n";
822
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
823
	}
824

    
825
	$fd = fopen("{$filename}", "w");
826
	if (!$fd) {
827
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
828
		return 1;
829
	}
830
	fwrite($fd, $lighty_config);
831
	fclose($fd);
832

    
833
	return 0;
834

    
835
}
836

    
837
function system_timezone_configure() {
838
	global $config, $g;
839
	if(isset($config['system']['developerspew'])) {
840
		$mt = microtime();
841
		echo "system_timezone_configure() being called $mt\n";
842
	}
843

    
844
	$syscfg = $config['system'];
845

    
846
	if ($g['booting'])
847
		echo "Setting timezone...";
848

    
849
	/* extract appropriate timezone file */
850
	$timezone = $syscfg['timezone'];
851
	if (!$timezone)
852
		$timezone = "Etc/UTC";
853

    
854
	conf_mount_rw();
855

    
856
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
857
		escapeshellarg($timezone) . " > /etc/localtime");
858

    
859
	mwexec("sync");
860
	conf_mount_ro();
861

    
862
	if ($g['booting'])
863
		echo "done.\n";
864
}
865

    
866
function system_ntp_configure() {
867
	global $config, $g;
868

    
869
	$syscfg = $config['system'];
870

    
871
	/* open configuration for wrting or bail */
872
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
873
	if(!$fd) {
874
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
875
		return;
876
	}
877

    
878
	fwrite($fd, "# \n");
879
	fwrite($fd, "# pfSense OpenNTPD configuration file \n");
880
	fwrite($fd, "# \n\n");
881

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

    
886
	/* Setup listener(s) if the user has configured one */
887
        if ($config['installedpackages']['openntpd']) {
888
    		/* server config is in coregui1 */
889
		$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
890
		if ($xmlsettings['enable'] == 'on') {
891
			$ifaces = explode(',', $xmlsettings['interface']);
892
			$ifaces = array_map('convert_friendly_interface_to_real_interface_name', $ifaces);
893
			$ifaces = array_filter($ifaces, 'does_interface_exist');
894
			$ips = array_map('find_interface_ip', $ifaces);
895
			foreach ($ips as $ip) {
896
				if (is_ipaddr($ip))
897
					fwrite($fd, "listen on $ip\n");
898
			}
899
		}
900
	}
901

    
902
	fwrite($fd, "\n");
903

    
904
	/* slurp! */
905
	fclose($fd);
906

    
907
	/* if openntpd is running, kill it */
908
	while(is_process_running("ntpd")) {
909
		mwexec("/usr/bin/killall ntpd", true);
910
	}
911

    
912
	/* if /var/empty does not exist, create it */
913
	if(!is_dir("/var/empty"))
914
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
915

    
916
	if($g['booting'])
917
		return;
918
	
919
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
920
	exec("/usr/local/sbin/ntpd -s -f {$g['varetc_path']}/ntpd.conf");
921

    
922
}
923

    
924
function sync_system_time() {
925
	global $config, $g;
926

    
927
	$syscfg = $config['system'];
928

    
929
	if ($g['booting'])
930
		echo "Syncing system time before startup...";
931

    
932
	/* foreach through servers and write out to ntpd.conf */
933
	foreach (explode(' ', $syscfg['timeservers']) as $ts) {
934
		mwexec("/usr/sbin/ntpdate -s $ts");
935
	}
936
	
937
	if ($g['booting'])
938
		echo "done.\n";
939
	
940
}
941

    
942
function system_halt() {
943
	global $g;
944

    
945
	system_reboot_cleanup();
946

    
947
	mwexec("nohup /etc/rc.halt > /dev/null 2>&1 &");
948
}
949

    
950
function system_reboot() {
951
	global $g;
952

    
953
	system_reboot_cleanup();
954

    
955
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
956
}
957

    
958
function system_reboot_sync() {
959
	global $g;
960

    
961
	system_reboot_cleanup();
962

    
963
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
964
}
965

    
966
function system_reboot_cleanup() {
967
	mwexec("/usr/local/bin/beep.sh stop");
968
	captiveportal_radius_stop_all();
969
}
970

    
971
function system_do_shell_commands($early = 0) {
972
	global $config, $g;
973
	if(isset($config['system']['developerspew'])) {
974
		$mt = microtime();
975
		echo "system_do_shell_commands() being called $mt\n";
976
	}
977

    
978
	if ($early)
979
		$cmdn = "earlyshellcmd";
980
	else
981
		$cmdn = "shellcmd";
982

    
983
	if (is_array($config['system'][$cmdn])) {
984

    
985
		/* *cmd is an array, loop through */
986
		foreach ($config['system'][$cmdn] as $cmd) {
987
			exec($cmd);
988
		}
989

    
990
	} elseif($config['system'][$cmdn] <> "") {
991

    
992
		/* execute single item */
993
		exec($config['system'][$cmdn]);
994

    
995
	}
996
}
997

    
998
function system_console_configure() {
999
	global $config, $g;
1000
	if(isset($config['system']['developerspew'])) {
1001
		$mt = microtime();
1002
		echo "system_console_configure() being called $mt\n";
1003
	}
1004

    
1005
	if (isset($config['system']['disableconsolemenu'])) {
1006
		touch("{$g['varetc_path']}/disableconsole");
1007
	} else {
1008
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1009
	}
1010
}
1011

    
1012
function system_dmesg_save() {
1013
	global $g;
1014
	if(isset($config['system']['developerspew'])) {
1015
		$mt = microtime();
1016
		echo "system_dmesg_save() being called $mt\n";
1017
	}
1018

    
1019
	$dmesg = "";
1020
	exec("/sbin/dmesg", $dmesg);
1021

    
1022
	/* find last copyright line (output from previous boots may be present) */
1023
	$lastcpline = 0;
1024

    
1025
	for ($i = 0; $i < count($dmesg); $i++) {
1026
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1027
			$lastcpline = $i;
1028
	}
1029

    
1030
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1031
	if (!$fd) {
1032
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1033
		return 1;
1034
	}
1035

    
1036
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1037
		fwrite($fd, $dmesg[$i] . "\n");
1038

    
1039
	fclose($fd);
1040

    
1041
	return 0;
1042
}
1043

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

    
1051
	if (isset($config['system']['harddiskstandby'])) {
1052
		if ($g['booting']) {
1053
			echo 'Setting hard disk standby... ';
1054
		}
1055

    
1056
		$standby = $config['system']['harddiskstandby'];
1057
		// Check for a numeric value
1058
		if (is_numeric($standby)) {
1059
			// Sync the disk(s)
1060
			mwexec('/bin/sync');
1061
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1062
				// Reinitialize ATA-drives
1063
				mwexec('/usr/local/sbin/atareinit');
1064
				if ($g['booting']) {
1065
					echo "done.\n";
1066
				}
1067
			} else if ($g['booting']) {
1068
				echo "failed!\n";
1069
			}
1070
		} else if ($g['booting']) {
1071
			echo "failed!\n";
1072
		}
1073
	}
1074
}
1075

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

    
1083
	activate_sysctls();	
1084

    
1085
	if (isset($config['system']['sharednet'])) {
1086
		system_disable_arp_wrong_if();
1087
	}
1088
}
1089

    
1090
function system_disable_arp_wrong_if() {
1091
	global $config;
1092
	if(isset($config['system']['developerspew'])) {
1093
		$mt = microtime();
1094
		echo "system_disable_arp_wrong_if() being called $mt\n";
1095
	}
1096
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1097
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1098
}
1099

    
1100
function system_enable_arp_wrong_if() {
1101
	global $config;
1102
	if(isset($config['system']['developerspew'])) {
1103
		$mt = microtime();
1104
		echo "system_enable_arp_wrong_if() being called $mt\n";
1105
	}
1106
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1107
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1108
}
1109

    
1110
function enable_watchdog() {
1111
	global $config;
1112
	$install_watchdog = false;
1113
	$supported_watchdogs = array("Geode");
1114
	$file = file_get_contents("/var/log/dmesg.boot");
1115
	foreach($supported_watchdogs as $sd) {
1116
		if(stristr($file, "Geode")) {
1117
			$install_watchdog = true;
1118
		}
1119
	}
1120
	if($install_watchdog == true) {
1121
		if(is_process_running("watchdogd"))
1122
			mwexec("/usr/bin/killall watchdogd", true);
1123
		exec("/usr/sbin/watchdogd");
1124
	}
1125
}
1126

    
1127
?>
(32-32/40)