Project

General

Profile

Download (32.3 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
	$status = mwexec("/bin/hostname " .
214
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
215

    
216
    /* Setup host GUID ID.  This is used by ZFS. */
217
	mwexec("/etc/rc.d/hostid start");
218

    
219
	return $status;
220
}
221

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

    
229
	/* Enable fast routing, if enabled */
230
	if(isset($config['staticroutes']['enablefastrouting']))
231
		mwexec("/sbin/sysctl net.inet.ip.fastforwarding=1");
232

    
233
	$route_str = exec_command("/usr/bin/netstat -rn");
234

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

    
251
	/* if list */
252
	$iflist = get_configured_interface_list();
253

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

    
268
	if ($dont_remove_route == false) {
269
		/* remove default route */
270
		mwexec("/sbin/route delete default", true);
271
	}
272

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

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

    
308
	if (is_array($config['staticroutes']['route'])) {
309

    
310
		$fd = fopen("{$g['vardb_path']}/routes.db", "w");
311
		if (!$fd) {
312
			printf("Error: cannot open routes DB file in system_routing_configure().\n");
313
			return 1;
314
		}
315

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

    
342
	return 0;
343
}
344

    
345

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

    
353
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
354
}
355

    
356
function system_syslogd_start() {
357
	global $config, $g;
358
	if(isset($config['system']['developerspew'])) {
359
		$mt = microtime();
360
		echo "system_syslogd_start() being called $mt\n";
361
	}
362

    
363
	$syslogcfg = $config['syslog'];
364

    
365
	if ($g['booting'])
366
		echo "Starting syslog...";
367
	else
368
		killbypid("{$g['varrun_path']}/syslog.pid");
369

    
370
	mwexec("/usr/bin/killall -9 syslogd");
371
	mwexec("/usr/bin/killall -9 fifolog_writer");
372
	
373
	// Define carious commands for logging
374
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
375
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
376
	$clog_create = "/usr/sbin/clog -i -s ";
377
	$clog_log = "%";
378

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

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

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

    
463
	} else {
464
		$retval = mwexec("/usr/sbin/syslogd");
465
	}
466

    
467
	if ($g['booting'])
468
		echo "done.\n";
469

    
470
	return $retval;
471
}
472

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

    
480
	if ($g['booting'])
481
		echo "Initializing PCMCIA...";
482

    
483
	/* kill any running pccardd */
484
	killbypid("{$g['varrun_path']}/pccardd.pid");
485

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

    
489
	if ($g['booting']) {
490
		if ($res == 0)
491
			echo "done.\n";
492
		else
493
			echo "failed!\n";
494
	}
495

    
496
	return $res;
497
}
498

    
499

    
500
function system_webgui_start() {
501
	global $config, $g;
502

    
503
	if ($g['booting'])
504
		echo "Starting webConfigurator...";
505

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

    
509
	sleep(1);
510

    
511
	chdir($g['www_path']);
512

    
513
	/* defaults */
514
	$portarg = "80";
515
	$crt = "";
516
	$key = "";
517

    
518
	/* non-standard port? */
519
	if ($config['system']['webgui']['port'])
520
		$portarg = "{$config['system']['webgui']['port']}";
521

    
522
	if ($config['system']['webgui']['protocol'] == "https") {
523

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

    
534
	/* generate lighttpd configuration */
535
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
536
		$crt, $key, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/");
537

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

    
541
	if ($g['booting']) {
542
		if ($res == 0)
543
			echo "done.\n";
544
		else
545
			echo "failed!\n";
546
	}
547

    
548
	return $res;
549
}
550

    
551
function system_generate_lighty_config($filename,
552
	$cert,
553
	$key,
554
	$pid_file,
555
	$port = 80,
556
	$document_root = "/usr/local/www/",
557
	$cert_location = "cert.pem",
558
	$max_procs = 2,
559
	$max_requests = "1",
560
	$fast_cgi_enable = true,
561
	$captive_portal = false) {
562

    
563
	global $config, $g;
564

    
565
	if(isset($config['system']['developerspew'])) {
566
		$mt = microtime();
567
		echo "system_generate_lighty_config() being called $mt\n";
568
	}
569

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

    
595
	$memory = get_memory();
596
	$avail = $memory[0];
597

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

    
603
	if($avail > 97 and $avail < 128) {
604
		$max_procs = 1;
605
		$max_requests = 3;
606
	}
607

    
608
	if($avail > 127 and $avail < 256) {
609
		$max_procs = 1;
610
		$max_requests = 5;
611
	}
612

    
613
	if($avail > 255 and $avail < 384) {
614
		$max_procs = 3;
615
		$max_requests = 10;
616
	}
617

    
618
	if($avail > 383) {
619
		$max_procs = 4;
620
		$max_requests = 16;
621
	}
622

    
623
	if($captive_portal == true)  {	
624
		$bin_environment =  <<<EOC
625
        "bin-environment" => (
626
           "PHP_FCGI_CHILDREN" => "16",
627
           "PHP_FCGI_MAX_REQUESTS" => "{$max_requests}"
628
        ), 
629
EOC;
630

    
631
	} else if ($avail > 0 and $avail < 128) {
632
		$bin_environment = <<<EOC
633
	"bin-environment" => (
634
		"PHP_FCGI_CHILDREN" => "1",
635
		"PHP_FCGI_MAX_REQUESTS" => "{$max_requests}"
636
	),
637

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

    
660
#### CGI module
661
cgi.assign                 = ( ".cgi" => "" )
662

    
663
EOD;
664
	} else {
665
		$fastcgi_config = "";
666
		$module = "\"mod_cgi\"";
667
		$cgi_config = <<<EOD
668
#### CGI module
669
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
670
                               ".cgi" => "" )
671

    
672
EOD;
673
	}
674

    
675
	$lighty_config .= <<<EOD
676
#
677
# lighttpd configuration file
678
#
679
# use a it as base for lighttpd 1.0.0 and above
680
#
681
############ Options you really have to take care of ####################
682

    
683
## FreeBSD!
684
server.event-handler	= "freebsd-kqueue"
685
server.network-backend 	= "writev"
686

    
687
## modules to load
688
server.modules              =   (
689
									{$captive_portal_module}
690
									"mod_access", "mod_accesslog", "mod_expire", "mod_compress",
691
									{$module}{$captiveportal}
692
								)
693

    
694
## Unused modules
695
#                               "mod_setenv",
696
#                               "mod_compress"
697
#				"mod_redirect",
698
#                               "mod_rewrite",
699
#                               "mod_ssi",
700
#                               "mod_usertrack",
701
#                               "mod_expire",
702
#                               "mod_secdownload",
703
#                               "mod_rrdtool",
704
#                               "mod_auth",
705
#                               "mod_status",
706
#                               "mod_alias",
707
#                               "mod_proxy",
708
#                               "mod_simple_vhost",
709
#                               "mod_evhost",
710
#                               "mod_userdir",
711
#                               "mod_cgi",
712
#                                "mod_accesslog"
713

    
714
server.max-keep-alive-requests = 15
715
server.max-keep-alive-idle = 30
716

    
717
## a static document-root, for virtual-hosting take look at the
718
## server.virtual-* options
719
server.document-root        = "{$document_root}"
720
{$captive_portal_rewrite}
721

    
722
# Maximum idle time with nothing being written (php downloading)
723
server.max-write-idle = 999
724

    
725
## where to send error-messages to
726
server.errorlog             = "/var/log/lighttpd.error.log"
727

    
728
# files to check for if .../ is requested
729
server.indexfiles           = ( "index.php", "index.html",
730
                                "index.htm", "default.htm" )
731

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

    
785
# Use the "Content-Type" extended attribute to obtain mime type if possible
786
#mimetypes.use-xattr        = "enable"
787

    
788
#### accesslog module
789
#accesslog.filename          = "/dev/null"
790

    
791
## deny access the file-extensions
792
#
793
# ~    is for backupfiles from vi, emacs, joe, ...
794
# .inc is often used for code includes which should in general not be part
795
#      of the document-root
796
url.access-deny             = ( "~", ".inc" )
797

    
798

    
799
######### Options that are good to be but not neccesary to be changed #######
800

    
801
## bind to port (default: 80)
802
server.port                = {$lighty_port}
803

    
804
## error-handler for status 404
805
#server.error-handler-404   = "/error-handler.html"
806
#server.error-handler-404   = "/error-handler.php"
807

    
808
## to help the rc.scripts
809
server.pid-file            = "/var/run/{$pid_file}"
810

    
811
## virtual directory listings
812
server.dir-listing         = "disable"
813

    
814
## enable debugging
815
debug.log-request-header   = "disable"
816
debug.log-response-header  = "disable"
817
debug.log-request-handling = "disable"
818
debug.log-file-not-found   = "disable"
819

    
820
{$server_upload_dirs}
821

    
822
{$server_max_request_size}
823

    
824
{$fastcgi_config}
825

    
826
{$cgi_config}
827

    
828
{$captive_portal_mod_evasive}
829

    
830
# Turn on Lighty caching directives
831
compress.cache-dir         = "/tmp/"
832
compress.filetype          = ("text/plain", "text/html", "text/javascript", "text/css")
833

    
834
expire.url = (
835
				"" => "access 50 hours",	
836
        )
837

    
838
EOD;
839

    
840
	$cert = str_replace("\r", "", $cert);
841
	$key = str_replace("\r", "", $key);
842

    
843
	$cert = str_replace("\n\n", "\n", $cert);
844
	$key = str_replace("\n\n", "\n", $key);
845

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

    
863
	$fd = fopen("{$filename}", "w");
864
	if (!$fd) {
865
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
866
		return 1;
867
	}
868
	fwrite($fd, $lighty_config);
869
	fclose($fd);
870

    
871
	return 0;
872

    
873
}
874

    
875
function system_timezone_configure() {
876
	global $config, $g;
877
	if(isset($config['system']['developerspew'])) {
878
		$mt = microtime();
879
		echo "system_timezone_configure() being called $mt\n";
880
	}
881

    
882
	$syscfg = $config['system'];
883

    
884
	if ($g['booting'])
885
		echo "Setting timezone...";
886

    
887
	/* extract appropriate timezone file */
888
	$timezone = $syscfg['timezone'];
889
	if (!$timezone)
890
		$timezone = "Etc/UTC";
891

    
892
	conf_mount_rw();
893

    
894
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
895
		escapeshellarg($timezone) . " > /etc/localtime");
896

    
897
	mwexec("sync");
898
	conf_mount_ro();
899

    
900
	if ($g['booting'])
901
		echo "done.\n";
902
}
903

    
904
function system_ntp_configure() {
905
	global $config, $g;
906

    
907
	$syscfg = $config['system'];
908

    
909
	/* open configuration for wrting or bail */
910
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
911
	if(!$fd) {
912
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
913
		return;
914
	}
915

    
916
	fwrite($fd, "# \n");
917
	fwrite($fd, "# pfSense OpenNTPD configuration file \n");
918
	fwrite($fd, "# \n\n");
919

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

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

    
940
	fwrite($fd, "\n");
941

    
942
	/* slurp! */
943
	fclose($fd);
944

    
945
	/* if openntpd is running, kill it */
946
	while(is_process_running("ntpd")) {
947
		mwexec("/usr/bin/killall ntpd", true);
948
	}
949

    
950
	/* if /var/empty does not exist, create it */
951
	if(!is_dir("/var/empty"))
952
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
953

    
954
	if($g['booting'])
955
		return;
956
	
957
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
958
	exec("/usr/local/sbin/ntpd -s -f {$g['varetc_path']}/ntpd.conf");
959

    
960
}
961

    
962
function sync_system_time() {
963
	global $config, $g;
964

    
965
	$syscfg = $config['system'];
966

    
967
	if ($g['booting'])
968
		echo "Syncing system time before startup...";
969

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

    
980
function system_halt() {
981
	global $g;
982

    
983
	system_reboot_cleanup();
984

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

    
988
function system_reboot() {
989
	global $g;
990

    
991
	system_reboot_cleanup();
992

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

    
996
function system_reboot_sync() {
997
	global $g;
998

    
999
	system_reboot_cleanup();
1000

    
1001
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1002
}
1003

    
1004
function system_reboot_cleanup() {
1005
	mwexec("/usr/local/bin/beep.sh stop");
1006
	captiveportal_radius_stop_all();
1007
}
1008

    
1009
function system_do_shell_commands($early = 0) {
1010
	global $config, $g;
1011
	if(isset($config['system']['developerspew'])) {
1012
		$mt = microtime();
1013
		echo "system_do_shell_commands() being called $mt\n";
1014
	}
1015

    
1016
	if ($early)
1017
		$cmdn = "earlyshellcmd";
1018
	else
1019
		$cmdn = "shellcmd";
1020

    
1021
	if (is_array($config['system'][$cmdn])) {
1022

    
1023
		/* *cmd is an array, loop through */
1024
		foreach ($config['system'][$cmdn] as $cmd) {
1025
			exec($cmd);
1026
		}
1027

    
1028
	} elseif($config['system'][$cmdn] <> "") {
1029

    
1030
		/* execute single item */
1031
		exec($config['system'][$cmdn]);
1032

    
1033
	}
1034
}
1035

    
1036
function system_console_configure() {
1037
	global $config, $g;
1038
	if(isset($config['system']['developerspew'])) {
1039
		$mt = microtime();
1040
		echo "system_console_configure() being called $mt\n";
1041
	}
1042

    
1043
	if (isset($config['system']['disableconsolemenu'])) {
1044
		touch("{$g['varetc_path']}/disableconsole");
1045
	} else {
1046
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1047
	}
1048
}
1049

    
1050
function system_dmesg_save() {
1051
	global $g;
1052
	if(isset($config['system']['developerspew'])) {
1053
		$mt = microtime();
1054
		echo "system_dmesg_save() being called $mt\n";
1055
	}
1056

    
1057
	$dmesg = "";
1058
	exec("/sbin/dmesg", $dmesg);
1059

    
1060
	/* find last copyright line (output from previous boots may be present) */
1061
	$lastcpline = 0;
1062

    
1063
	for ($i = 0; $i < count($dmesg); $i++) {
1064
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1065
			$lastcpline = $i;
1066
	}
1067

    
1068
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1069
	if (!$fd) {
1070
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1071
		return 1;
1072
	}
1073

    
1074
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1075
		fwrite($fd, $dmesg[$i] . "\n");
1076

    
1077
	fclose($fd);
1078

    
1079
	return 0;
1080
}
1081

    
1082
function system_set_harddisk_standby() {
1083
	global $g, $config;
1084
	if(isset($config['system']['developerspew'])) {
1085
		$mt = microtime();
1086
		echo "system_set_harddisk_standby() being called $mt\n";
1087
	}
1088

    
1089
	if (isset($config['system']['harddiskstandby'])) {
1090
		if ($g['booting']) {
1091
			echo 'Setting hard disk standby... ';
1092
		}
1093

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

    
1114
function system_setup_sysctl() {
1115
	global $config;
1116
	if(isset($config['system']['developerspew'])) {
1117
		$mt = microtime();
1118
		echo "system_setup_sysctl() being called $mt\n";
1119
	}
1120

    
1121
	activate_sysctls();	
1122

    
1123
	if (isset($config['system']['sharednet'])) {
1124
		system_disable_arp_wrong_if();
1125
	}
1126
}
1127

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

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

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

    
1165
?>
(32-32/40)