Project

General

Profile

Download (32.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_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
		$syslogconf .= "!apinger\n";
415
		if (!isset($syslogcfg['disablelocallogging'])) 
416
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/slbd.log\n";
417
		if (isset($syslogcfg['vpn'])) 
418
			$syslogconf .= "*.*					 @{$syslogcfg['remoteserver']}\n";
419
		$syslogconf .= "!openvpn\n";
420
		if (!isset($syslogcfg['disablelocallogging'])) 
421
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/openvpn.log\n";
422
		if (isset($syslogcfg['vpn'])) 
423
			$syslogconf .= "*.*					 @{$syslogcfg['remoteserver']}\n";
424
		$syslogconf .= "!-{$facilitylist}\n";
425
		if (!isset($syslogcfg['disablelocallogging'])) 
426
			$syslogconf .= <<<EOD
427
local0.*										 {$log_directive}{$g['varlog_path']}/filter.log
428
local3.*										 {$log_directive}{$g['varlog_path']}/vpn.log
429
local4.*										 {$log_directive}{$g['varlog_path']}/portalauth.log
430
local7.*										 {$log_directive}{$g['varlog_path']}/dhcpd.log
431
*.notice;kern.debug;lpr.info;mail.crit; 		 {$log_directive}{$g['varlog_path']}/system.log
432
news.err;local0.none;local3.none;local4.none; 	 {$log_directive}{$g['varlog_path']}/system.log
433
local7.none										 {$log_directive}{$g['varlog_path']}/system.log
434
security.*										 {$log_directive}{$g['varlog_path']}/system.log
435
auth.info;authpriv.info;daemon.info				 {$log_directive}{$g['varlog_path']}/system.log
436
local1.*										 {$log_directive}{$g['varlog_path']}/relayd.log
437
auth.info;authpriv.info 						 |exec /usr/local/sbin/sshlockout_pf
438
*.emerg											 *
439

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

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

    
466
	} else {
467
		$retval = mwexec("/usr/sbin/syslogd");
468
	}
469

    
470
	if ($g['booting'])
471
		echo "done.\n";
472

    
473
	return $retval;
474
}
475

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

    
483
	if ($g['booting'])
484
		echo "Initializing PCMCIA...";
485

    
486
	/* kill any running pccardd */
487
	killbypid("{$g['varrun_path']}/pccardd.pid");
488

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

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

    
499
	return $res;
500
}
501

    
502

    
503
function system_webgui_start() {
504
	global $config, $g;
505

    
506
	if ($g['booting'])
507
		echo "Starting webConfigurator...";
508

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

    
512
	sleep(1);
513

    
514
	chdir($g['www_path']);
515

    
516
	/* defaults */
517
	$portarg = "80";
518
	$crt = "";
519
	$key = "";
520

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

    
525
	if ($config['system']['webgui']['protocol'] == "https") {
526

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

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

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

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

    
551
	return $res;
552
}
553

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

    
566
	global $config, $g;
567

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

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

    
598
	$memory = get_memory();
599
	$avail = $memory[0];
600

    
601
	if($avail > 0 and $avail < 98) {
602
		$max_procs = 1;
603
		$max_requests = 1;
604
	}
605

    
606
	if($avail > 97 and $avail < 128) {
607
		$max_procs = 1;
608
		$max_requests = 3;
609
	}
610

    
611
	if($avail > 127 and $avail < 256) {
612
		$max_procs = 1;
613
		$max_requests = 5;
614
	}
615

    
616
	if($avail > 255 and $avail < 384) {
617
		$max_procs = 3;
618
		$max_requests = 10;
619
	}
620

    
621
	if($avail > 383) {
622
		$max_procs = 4;
623
		$max_requests = 16;
624
	}
625

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

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

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

    
663
#### CGI module
664
cgi.assign                 = ( ".cgi" => "" )
665

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

    
675
EOD;
676
	}
677

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

    
686
## FreeBSD!
687
server.event-handler	= "freebsd-kqueue"
688
server.network-backend 	= "writev"
689

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

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

    
717
server.max-keep-alive-requests = 15
718
server.max-keep-alive-idle = 30
719

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

    
725
# Maximum idle time with nothing being written (php downloading)
726
server.max-write-idle = 999
727

    
728
## where to send error-messages to
729
server.errorlog             = "/var/log/lighttpd.error.log"
730

    
731
# files to check for if .../ is requested
732
server.indexfiles           = ( "index.php", "index.html",
733
                                "index.htm", "default.htm" )
734

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

    
788
# Use the "Content-Type" extended attribute to obtain mime type if possible
789
#mimetypes.use-xattr        = "enable"
790

    
791
#### accesslog module
792
#accesslog.filename          = "/dev/null"
793

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

    
801

    
802
######### Options that are good to be but not neccesary to be changed #######
803

    
804
## bind to port (default: 80)
805
server.port                = {$lighty_port}
806

    
807
## error-handler for status 404
808
#server.error-handler-404   = "/error-handler.html"
809
#server.error-handler-404   = "/error-handler.php"
810

    
811
## to help the rc.scripts
812
server.pid-file            = "/var/run/{$pid_file}"
813

    
814
## virtual directory listings
815
server.dir-listing         = "disable"
816

    
817
## enable debugging
818
debug.log-request-header   = "disable"
819
debug.log-response-header  = "disable"
820
debug.log-request-handling = "disable"
821
debug.log-file-not-found   = "disable"
822

    
823
{$server_upload_dirs}
824

    
825
{$server_max_request_size}
826

    
827
{$fastcgi_config}
828

    
829
{$cgi_config}
830

    
831
{$captive_portal_mod_evasive}
832

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

    
837
expire.url = (
838
				"" => "access 50 hours",	
839
        )
840

    
841
EOD;
842

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

    
846
	$cert = str_replace("\n\n", "\n", $cert);
847
	$key = str_replace("\n\n", "\n", $key);
848

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

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

    
874
	return 0;
875

    
876
}
877

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

    
885
	$syscfg = $config['system'];
886

    
887
	if ($g['booting'])
888
		echo "Setting timezone...";
889

    
890
	/* extract appropriate timezone file */
891
	$timezone = $syscfg['timezone'];
892
	if (!$timezone)
893
		$timezone = "Etc/UTC";
894

    
895
	conf_mount_rw();
896

    
897
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
898
		escapeshellarg($timezone) . " > /etc/localtime");
899

    
900
	mwexec("sync");
901
	conf_mount_ro();
902

    
903
	if ($g['booting'])
904
		echo "done.\n";
905
}
906

    
907
function system_ntp_configure() {
908
	global $config, $g;
909

    
910
	$syscfg = $config['system'];
911

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

    
919
	fwrite($fd, "# \n");
920
	fwrite($fd, "# pfSense OpenNTPD configuration file \n");
921
	fwrite($fd, "# \n\n");
922

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

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

    
943
	fwrite($fd, "\n");
944

    
945
	/* slurp! */
946
	fclose($fd);
947

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

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

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

    
963
}
964

    
965
function sync_system_time() {
966
	global $config, $g;
967

    
968
	$syscfg = $config['system'];
969

    
970
	if ($g['booting'])
971
		echo "Syncing system time before startup...";
972

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

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

    
986
	system_reboot_cleanup();
987

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

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

    
994
	system_reboot_cleanup();
995

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

    
999
function system_reboot_sync() {
1000
	global $g;
1001

    
1002
	system_reboot_cleanup();
1003

    
1004
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1005
}
1006

    
1007
function system_reboot_cleanup() {
1008
	mwexec("/usr/local/bin/beep.sh stop");
1009
	captiveportal_radius_stop_all();
1010
}
1011

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

    
1019
	if ($early)
1020
		$cmdn = "earlyshellcmd";
1021
	else
1022
		$cmdn = "shellcmd";
1023

    
1024
	if (is_array($config['system'][$cmdn])) {
1025

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

    
1031
	} elseif($config['system'][$cmdn] <> "") {
1032

    
1033
		/* execute single item */
1034
		exec($config['system'][$cmdn]);
1035

    
1036
	}
1037
}
1038

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

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

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

    
1060
	$dmesg = "";
1061
	exec("/sbin/dmesg", $dmesg);
1062

    
1063
	/* find last copyright line (output from previous boots may be present) */
1064
	$lastcpline = 0;
1065

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

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

    
1077
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1078
		fwrite($fd, $dmesg[$i] . "\n");
1079

    
1080
	fclose($fd);
1081

    
1082
	return 0;
1083
}
1084

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

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

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

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

    
1124
	activate_sysctls();	
1125

    
1126
	if (isset($config['system']['sharednet'])) {
1127
		system_disable_arp_wrong_if();
1128
	}
1129
}
1130

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

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

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

    
1168
?>
(32-32/40)