Project

General

Profile

Download (32.1 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
	exec("/usr/bin/netstat -rn", $route_arr, $retval);
229
	$route_str = implode("\n", $route_arr);
230

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

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

    
250
	$dont_remove_route = false;
251
	foreach ($iflist as $ifent => $ifname) {
252
		/* do not process interfaces that will end up with gateways */
253
		if (interface_has_gateway($ifent))
254
			$dont_remove_route = true;
255
	}
256

    
257
	if($config['interfaces']['wan']['ipaddr'] == "carpdev-dhcp")
258
		$dont_remove_route = true;
259

    
260
	if($dont_remove_route == false) {
261
		/* remove default route */
262
		mwexec("/sbin/route delete default", true);
263
	}
264

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

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

    
299
	if (is_array($config['staticroutes']['route'])) {
300

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

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

    
333
	return 0;
334
}
335

    
336

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

    
344
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
345
}
346

    
347
function system_syslogd_start() {
348
	global $config, $g;
349
	if(isset($config['system']['developerspew'])) {
350
		$mt = microtime();
351
		echo "system_syslogd_start() being called $mt\n";
352
	}
353

    
354
	$syslogcfg = $config['syslog'];
355

    
356
	if ($g['booting'])
357
		echo "Starting syslog...";
358
	else
359
		killbypid("{$g['varrun_path']}/syslog.pid");
360

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

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

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

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

    
454
	} else {
455
		$retval = mwexec("/usr/sbin/syslogd");
456
	}
457

    
458
	if ($g['booting'])
459
		echo "done.\n";
460

    
461
	return $retval;
462
}
463

    
464
function system_pccard_start() {
465
	global $config, $g;
466
	if(isset($config['system']['developerspew'])) {
467
		$mt = microtime();
468
		echo "system_pccard_start() being called $mt\n";
469
	}
470

    
471
	if ($g['booting'])
472
		echo "Initializing PCMCIA...";
473

    
474
	/* kill any running pccardd */
475
	killbypid("{$g['varrun_path']}/pccardd.pid");
476

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

    
480
	if ($g['booting']) {
481
		if ($res == 0)
482
			echo "done.\n";
483
		else
484
			echo "failed!\n";
485
	}
486

    
487
	return $res;
488
}
489

    
490

    
491
function system_webgui_start() {
492
	global $config, $g;
493

    
494
	if ($g['booting'])
495
		echo "Starting webConfigurator...";
496

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

    
500
	sleep(1);
501

    
502
	chdir($g['www_path']);
503

    
504
	/* defaults */
505
	$portarg = "80";
506
	$crt = "";
507
	$key = "";
508

    
509
	/* non-standard port? */
510
	if ($config['system']['webgui']['port'])
511
		$portarg = "{$config['system']['webgui']['port']}";
512

    
513
	if ($config['system']['webgui']['protocol'] == "https") {
514

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

    
525
	/* generate lighttpd configuration */
526
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
527
		$crt, $key, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/");
528

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

    
532
	if ($g['booting']) {
533
		if ($res == 0)
534
			echo "done.\n";
535
		else
536
			echo "failed!\n";
537
	}
538

    
539
	return $res;
540
}
541

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

    
554
	global $config, $g;
555

    
556
	if(isset($config['system']['developerspew'])) {
557
		$mt = microtime();
558
		echo "system_generate_lighty_config() being called $mt\n";
559
	}
560

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

    
586
	$memory = get_memory();
587
	$avail = $memory[0];
588

    
589
	if($avail > 0 and $avail < 98) {
590
		$max_procs = 1;
591
		$max_requests = 1;
592
	}
593

    
594
	if($avail > 97 and $avail < 128) {
595
		$max_procs = 1;
596
		$max_requests = 3;
597
	}
598

    
599
	if($avail > 127 and $avail < 256) {
600
		$max_procs = 1;
601
		$max_requests = 5;
602
	}
603

    
604
	if($avail > 255 and $avail < 384) {
605
		$max_procs = 3;
606
		$max_requests = 10;
607
	}
608

    
609
	if($avail > 383) {
610
		$max_procs = 4;
611
		$max_requests = 16;
612
	}
613

    
614
	if($captive_portal == true)  {	
615
		$bin_environment =  <<<EOC
616
        "bin-environment" => (
617
           "PHP_FCGI_CHILDREN" => "16",
618
           "PHP_FCGI_MAX_REQUESTS" => "{$max_requests}"
619
        ), 
620
EOC;
621

    
622
	} else if ($avail > 0 and $avail < 128) {
623
		$bin_environment = <<<EOC
624
	"bin-environment" => (
625
		"PHP_FCGI_CHILDREN" => "1",
626
		"PHP_FCGI_MAX_REQUESTS" => "{$max_requests}"
627
	),
628

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

    
651
#### CGI module
652
cgi.assign                 = ( ".cgi" => "" )
653

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

    
663
EOD;
664
	}
665

    
666
	$lighty_config .= <<<EOD
667
#
668
# lighttpd configuration file
669
#
670
# use a it as base for lighttpd 1.0.0 and above
671
#
672
############ Options you really have to take care of ####################
673

    
674
## FreeBSD!
675
server.event-handler	= "freebsd-kqueue"
676
server.network-backend 	= "writev"
677

    
678
## modules to load
679
server.modules              =   (
680
									{$captive_portal_module}
681
									"mod_access", "mod_accesslog", "mod_expire", "mod_compress",
682
									{$module}{$captiveportal}
683
								)
684

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

    
705
server.max-keep-alive-requests = 15
706
server.max-keep-alive-idle = 30
707

    
708
## a static document-root, for virtual-hosting take look at the
709
## server.virtual-* options
710
server.document-root        = "{$document_root}"
711
{$captive_portal_rewrite}
712

    
713
# Maximum idle time with nothing being written (php downloading)
714
server.max-write-idle = 999
715

    
716
## where to send error-messages to
717
server.errorlog             = "/var/log/lighttpd.error.log"
718

    
719
# files to check for if .../ is requested
720
server.indexfiles           = ( "index.php", "index.html",
721
                                "index.htm", "default.htm" )
722

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

    
776
# Use the "Content-Type" extended attribute to obtain mime type if possible
777
#mimetypes.use-xattr        = "enable"
778

    
779
#### accesslog module
780
#accesslog.filename          = "/dev/null"
781

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

    
789

    
790
######### Options that are good to be but not neccesary to be changed #######
791

    
792
## bind to port (default: 80)
793
server.port                = {$lighty_port}
794

    
795
## error-handler for status 404
796
#server.error-handler-404   = "/error-handler.html"
797
#server.error-handler-404   = "/error-handler.php"
798

    
799
## to help the rc.scripts
800
server.pid-file            = "/var/run/{$pid_file}"
801

    
802
## virtual directory listings
803
server.dir-listing         = "disable"
804

    
805
## enable debugging
806
debug.log-request-header   = "disable"
807
debug.log-response-header  = "disable"
808
debug.log-request-handling = "disable"
809
debug.log-file-not-found   = "disable"
810

    
811
{$server_upload_dirs}
812

    
813
{$server_max_request_size}
814

    
815
{$fastcgi_config}
816

    
817
{$cgi_config}
818

    
819
{$captive_portal_mod_evasive}
820

    
821
# Turn on Lighty caching directives
822
compress.cache-dir         = "/tmp/"
823
compress.filetype          = ("text/plain", "text/html", "text/javascript", "text/css")
824

    
825
expire.url = (
826
				"" => "access 50 hours",	
827
        )
828

    
829
EOD;
830

    
831
	$cert = str_replace("\r", "", $cert);
832
	$key = str_replace("\r", "", $key);
833

    
834
	$cert = str_replace("\n\n", "\n", $cert);
835
	$key = str_replace("\n\n", "\n", $key);
836

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

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

    
862
	return 0;
863

    
864
}
865

    
866
function system_timezone_configure() {
867
	global $config, $g;
868
	if(isset($config['system']['developerspew'])) {
869
		$mt = microtime();
870
		echo "system_timezone_configure() being called $mt\n";
871
	}
872

    
873
	$syscfg = $config['system'];
874

    
875
	if ($g['booting'])
876
		echo "Setting timezone...";
877

    
878
	/* extract appropriate timezone file */
879
	$timezone = $syscfg['timezone'];
880
	if (!$timezone)
881
		$timezone = "Etc/UTC";
882

    
883
	conf_mount_rw();
884

    
885
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
886
		escapeshellarg($timezone) . " > /etc/localtime");
887

    
888
	mwexec("sync");
889
	conf_mount_ro();
890

    
891
	if ($g['booting'])
892
		echo "done.\n";
893
}
894

    
895
function system_ntp_configure() {
896
	global $config, $g;
897

    
898
	$syscfg = $config['system'];
899

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

    
907
	fwrite($fd, "# \n");
908
	fwrite($fd, "# pfSense OpenNTPD configuration file \n");
909
	fwrite($fd, "# \n\n");
910

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

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

    
931
	fwrite($fd, "\n");
932

    
933
	/* slurp! */
934
	fclose($fd);
935

    
936
	/* if openntpd is running, kill it */
937
	while(is_process_running("ntpd")) {
938
		mwexec("/usr/bin/killall ntpd", true);
939
	}
940

    
941
	/* if /var/empty does not exist, create it */
942
	if(!is_dir("/var/empty"))
943
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
944

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

    
951
}
952

    
953
function sync_system_time() {
954
	global $config, $g;
955

    
956
	$syscfg = $config['system'];
957

    
958
	if ($g['booting'])
959
		echo "Syncing system time before startup...";
960

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

    
971
function system_halt() {
972
	global $g;
973

    
974
	system_reboot_cleanup();
975

    
976
	mwexec("nohup /etc/rc.halt > /dev/null 2>&1 &");
977
}
978

    
979
function system_reboot() {
980
	global $g;
981

    
982
	system_reboot_cleanup();
983

    
984
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
985
}
986

    
987
function system_reboot_sync() {
988
	global $g;
989

    
990
	system_reboot_cleanup();
991

    
992
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
993
}
994

    
995
function system_reboot_cleanup() {
996
	mwexec("/usr/local/bin/beep.sh stop");
997
	captiveportal_radius_stop_all();
998
}
999

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

    
1007
	if ($early)
1008
		$cmdn = "earlyshellcmd";
1009
	else
1010
		$cmdn = "shellcmd";
1011

    
1012
	if (is_array($config['system'][$cmdn])) {
1013

    
1014
		/* *cmd is an array, loop through */
1015
		foreach ($config['system'][$cmdn] as $cmd) {
1016
			exec($cmd);
1017
		}
1018

    
1019
	} elseif($config['system'][$cmdn] <> "") {
1020

    
1021
		/* execute single item */
1022
		exec($config['system'][$cmdn]);
1023

    
1024
	}
1025
}
1026

    
1027
function system_console_configure() {
1028
	global $config, $g;
1029
	if(isset($config['system']['developerspew'])) {
1030
		$mt = microtime();
1031
		echo "system_console_configure() being called $mt\n";
1032
	}
1033

    
1034
	if (isset($config['system']['disableconsolemenu'])) {
1035
		touch("{$g['varetc_path']}/disableconsole");
1036
	} else {
1037
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1038
	}
1039
}
1040

    
1041
function system_dmesg_save() {
1042
	global $g;
1043
	if(isset($config['system']['developerspew'])) {
1044
		$mt = microtime();
1045
		echo "system_dmesg_save() being called $mt\n";
1046
	}
1047

    
1048
	$dmesg = "";
1049
	exec("/sbin/dmesg", $dmesg);
1050

    
1051
	/* find last copyright line (output from previous boots may be present) */
1052
	$lastcpline = 0;
1053

    
1054
	for ($i = 0; $i < count($dmesg); $i++) {
1055
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1056
			$lastcpline = $i;
1057
	}
1058

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

    
1065
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1066
		fwrite($fd, $dmesg[$i] . "\n");
1067

    
1068
	fclose($fd);
1069

    
1070
	return 0;
1071
}
1072

    
1073
function system_set_harddisk_standby() {
1074
	global $g, $config;
1075
	if(isset($config['system']['developerspew'])) {
1076
		$mt = microtime();
1077
		echo "system_set_harddisk_standby() being called $mt\n";
1078
	}
1079

    
1080
	if (isset($config['system']['harddiskstandby'])) {
1081
		if ($g['booting']) {
1082
			echo 'Setting hard disk standby... ';
1083
		}
1084

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

    
1105
function system_setup_sysctl() {
1106
	global $config;
1107
	if(isset($config['system']['developerspew'])) {
1108
		$mt = microtime();
1109
		echo "system_setup_sysctl() being called $mt\n";
1110
	}
1111

    
1112
	activate_sysctls();	
1113

    
1114
	if (isset($config['system']['sharednet'])) {
1115
		system_disable_arp_wrong_if();
1116
	}
1117
}
1118

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

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

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

    
1156
?>
(32-32/40)