Project

General

Profile

Download (30.5 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/* $Id$ */
3
/*
4
	system.inc
5
	part of m0n0wall (http://m0n0.ch/wall)
6

    
7
	Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
8
	All rights reserved.
9

    
10
	Redistribution and use in source and binary forms, with or without
11
	modification, are permitted provided that the following conditions are met:
12

    
13
	1. Redistributions of source code must retain the above copyright notice,
14
	   this list of conditions and the following disclaimer.
15

    
16
	2. Redistributions in binary form must reproduce the above copyright
17
	   notice, this list of conditions and the following disclaimer in the
18
	   documentation and/or other materials provided with the distribution.
19

    
20
	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
21
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
22
	AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
23
	AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
24
	OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29
	POSSIBILITY OF SUCH DAMAGE.
30
*/
31

    
32
/* include all configuration functions */
33
require_once("functions.inc");
34

    
35
function activate_sysctls() {
36
	global $config, $g;
37
	
38
	if (is_array($config['sysctl'])) 
39
		foreach ($config['sysctl']['item'] as $tunable) 
40
			mwexec("sysctl " . $tunable['tunable'] . "=\"" 
41
				. $tunable['value'] .  "\"");
42
	
43
}
44

    
45
function system_resolvconf_generate($dynupdate = false) {
46
		global $config, $g;
47
		if(isset($config['system']['developerspew'])) {
48
			$mt = microtime();
49
			echo "system_resolvconf_generate() being called $mt\n";
50
		}
51

    
52
        $syscfg = $config['system'];
53

    
54
        $fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
55
        if (!$fd) {
56
                printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
57
                return 1;
58
        }
59

    
60
        $resolvconf = "domain {$syscfg['domain']}\n";
61

    
62
        $havedns = false;
63

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

    
83
        fwrite($fd, $resolvconf);
84
        fclose($fd);
85

    
86
        if (!$g['booting']) {
87
			/* restart dhcpd (nameservers may have changed) */
88
			if (!$dynupdate)
89
				services_dhcpd_configure();
90
        }
91

    
92
		for($dnscounter=1; $dnscounter<5; $dnscounter++) {
93
			/* setup static routes for dns servers */
94
			if($config['system']['dns{$dnscounter}gwint']) {
95
				$if = $config['system']['dns{$dnscounter}gwint'];
96
				if($if) { 
97
					$gw = $config['interfaces'][$if]['if'];
98
					$dnscountermo = $dnscounter - 1;
99
					exec("route delete {$syscfg['dnsserver'][$dnscountermo]}");
100
					exec("route add {$syscfg['dnsserver'][$dnscountermo]} -gw {$gw}");
101
				}
102
			}
103
		}
104

    
105
        return 0;
106
}
107

    
108
function get_nameservers() {
109
	global $config, $g;
110
	$master_list = array();
111
	$dns_lists = split("\n", `ls /var/etc/nameserver_* 2>/dev/null`);
112
	foreach($dns_lists as $dns) {
113
		$items = split("\n", file_get_contents($dns));
114
		foreach($items as $item)
115
			if($item <> "")
116
				$master_list[] = $item;
117
	}
118
	if(!file_exists("/var/etc/nameservers.conf"))
119
		return $master_list;
120
	$dns = `cat /var/etc/nameservers.conf`;
121
	$dns_s = split("\n", $dns);
122
	if(is_array($dns_s))
123
		foreach($dns_s as $dns)
124
			$master_list[] = $dns;
125
	return $master_list;
126
}
127

    
128
function system_hosts_generate() {
129
	global $config, $g;
130
	if(isset($config['system']['developerspew'])) {
131
		$mt = microtime();
132
		echo "system_hosts_generate() being called $mt\n";
133
	}
134

    
135
	$syscfg = $config['system'];
136
	$lancfg = $config['interfaces']['lan'];
137
	$dnsmasqcfg = $config['dnsmasq'];
138

    
139
	if (!is_array($dnsmasqcfg['hosts'])) {
140
		$dnsmasqcfg['hosts'] = array();
141
	}
142
	$hostscfg = $dnsmasqcfg['hosts'];
143

    
144
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
145
	if (!$fd) {
146
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
147
		return 1;
148
	}
149

    
150
	$hosts = <<<EOD
151
127.0.0.1	localhost localhost.{$syscfg['domain']}
152
{$lancfg['ipaddr']}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}
153

    
154
EOD;
155

    
156
	foreach ($hostscfg as $host) {
157
		if ($host['host'])
158
			$hosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
159
		else
160
			$hosts .= "{$host['ip']}	{$host['domain']}\n";
161
	}
162
	if (isset($dnsmasqcfg['regdhcpstatic'])) {
163
		foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf)
164
			if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
165
					foreach ($dhcpifconf['staticmap'] as $host)
166
						if ($host['ipaddr'] && $host['hostname'])
167
							$hosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
168
	}
169
	fwrite($fd, $hosts);
170
	fclose($fd);
171

    
172
	return 0;
173
}
174

    
175
function system_hostname_configure() {
176
	global $config, $g;
177
	if(isset($config['system']['developerspew'])) {
178
		$mt = microtime();
179
		echo "system_hostname_configure() being called $mt\n";
180
	}
181

    
182
	$syscfg = $config['system'];
183

    
184
	/* set hostname */
185
	return mwexec("/bin/hostname " .
186
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
187
}
188

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

    
196
	/* Enable fast routing, if enabled */
197
	if(isset($config['staticroutes']['enablefastrouting']))
198
		mwexec("/sbin/sysctl net.inet.ip.fastforwarding=1");
199

    
200
	/* clear out old routes, if necessary */
201
	if (file_exists("{$g['vardb_path']}/routes.db")) {
202
		$fd = fopen("{$g['vardb_path']}/routes.db", "r");
203
		if (!$fd) {
204
			printf("Error: cannot open routes DB file in system_routing_configure().\n");
205
			return 1;
206
		}
207
		while (!feof($fd)) {
208
			$oldrt = fgets($fd);
209
			if ($oldrt)
210
				mwexec("/sbin/route delete " . escapeshellarg($oldrt));
211
		}
212
		fclose($fd);
213
		unlink("{$g['vardb_path']}/routes.db");
214
	}
215

    
216
	/* if list */
217
	$iflist = get_configured_interface_list();
218

    
219
	$dont_remove_route = false;
220
	foreach ($iflist as $ifent => $ifname) {
221
		/* do not process interfaces that will end up with gateways */
222
		if (interface_has_gateway($ifent))
223
			$dont_remove_route = true;
224
	}
225

    
226
	if($config['interfaces']['wan']['ipaddr'] == "carpdev-dhcp")
227
		$dont_remove_route = true;
228

    
229
	if($dont_remove_route == false) {
230
		/* remove default route */
231
		mwexec("/sbin/route delete default");
232
	}
233

    
234
	$dont_add_route = false;
235
	/* if OLSRD is enabled, allow WAN to house DHCP. */
236
	if($config['installedpackages']['olsrd']) {
237
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
238
			if($olsrd['enabledyngw'] == "on") {
239
				$dont_add_route = true;
240
			}
241
		}
242
	}
243

    
244
	if($dont_add_route == false) {
245
		if(is_array($config['gateways']['gateway_item'])) {
246
			foreach($config['gateways']['gateway_item'] as $gateway) {
247
		        	if(isset($gateway['defaultgw'])) {
248
					$gatewayip = $gateway['gateway'];
249
					$interfacegw = $gateway['interface'];
250
				}
251
			}
252
			if($interfacegw <> "bgpd")
253
				mwexec("/sbin/route add default " . escapeshellarg($gatewayip));
254
		} else {
255
			/* adding gateway for 1.2-style configs without the new
256
			  gateway setup configured.
257
			  Force WAN to be default gateway because that is the
258
			  1.2 behavior.
259
			*/
260
			if (is_ipaddr($config['interfaces']['wan']['gateway'])) {
261
				$gatewayip = $config['interfaces']['wan']['gateway'];
262
				mwexec("/sbin/route add default " . escapeshellarg($gatewayip));
263
			}
264
		}
265
	}
266

    
267
	if (is_array($config['staticroutes']['route'])) {
268

    
269
		$fd = fopen("{$g['vardb_path']}/routes.db", "w");
270
		if (!$fd) {
271
			printf("Error: cannot open routes DB file in system_routing_configure().\n");
272
			return 1;
273
		}
274

    
275
		foreach ($config['staticroutes']['route'] as $rtent) {
276
			if(is_array($config['gateways']['gateway_item'])) {
277
				foreach($config['gateways']['gateway_item'] as $gateway) {
278
					if($rtent['gateway'] == $gateway['name']) {
279
						$gatewayip = $gateway['gateway'];
280
						$interfacegw = $gateway['interface'];
281
					}
282
				}
283
			}
284
			if((is_ipaddr($rtent['gateway'])) && ($gatewayip == ""))  {
285
				$gatewayip = $rtent['gateway'];
286
				$interfacegw = $rtent['interface'];
287
			}			
288
			if(isset($rtent['interfacegateway'])) {
289
				mwexec("/sbin/route add " . escapeshellarg($rtent['network']) .
290
					" -iface " . escapeshellarg(convert_friendly_interface_to_real_interface_name($interfacegw)));
291
			} else {
292
				mwexec("/sbin/route add " . escapeshellarg($rtent['network']) .
293
					" " . escapeshellarg($gatewayip));
294
			}
295
			/* record route so it can be easily removed later (if necessary) */
296
			fwrite($fd, $rtent['network'] . "\n");
297
		}
298
		fclose($fd);
299
	}
300

    
301
	return 0;
302
}
303

    
304
function system_routing_enable() {
305
	global $config, $g;
306
	if(isset($config['system']['developerspew'])) {
307
		$mt = microtime();
308
		echo "system_routing_enable() being called $mt\n";
309
	}
310

    
311
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
312
}
313

    
314
function system_syslogd_start() {
315
	global $config, $g;
316
	if(isset($config['system']['developerspew'])) {
317
		$mt = microtime();
318
		echo "system_syslogd_start() being called $mt\n";
319
	}
320

    
321
	$syslogcfg = $config['syslog'];
322

    
323
	if ($g['booting'])
324
		echo "Starting syslog...";
325
	else
326
		killbypid("{$g['varrun_path']}/syslog.pid");
327

    
328
	if (isset($syslogcfg)) {
329
		$separatelogfacilities = array('ntpd','racoon','openvpn');
330
		if($config['installedpackages']['package']) {
331
                        foreach($config['installedpackages']['package'] as $package) {
332
                                if($package['logging']) {
333
					$pkgfacilities[] = $package['logging']['facilityname'];
334
					$separatelogfacilities = $separatelogfacilities + $pkgfacilities;
335
					$facilitylist = implode(',', $pkgfacilities);
336
					mwexec("clog -i -s 10000 {$g['varlog_path']}/{$package['logging']['logfilename']}");
337
                                	$syslogconf .= "!{$facilitylist}\n*.*\t\t\t\t\t\t%{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
338
				}
339
                        }
340
                }
341
		$facilitylist = implode(',', array_unique($separatelogfacilities));
342
		/* write syslog.conf */
343
		$fd = fopen("{$g['varetc_path']}/syslog.conf", "w");
344
		if (!$fd) {
345
			printf("Error: cannot open syslog.conf in system_syslogd_start().\n");
346
			return 1;
347
		}
348
		$syslogconf .= "!ntpdate,!ntpd\n";
349
		if (!isset($syslogcfg['disablelocallogging'])) {
350
			$syslogconf .= <<<EOD
351
*.*						%{$g['varlog_path']}/ntpd.log
352

    
353
EOD;
354
		}
355
		$syslogconf .= "!racoon\n";
356
		if (!isset($syslogcfg['disablelocallogging'])) {
357
			$syslogconf .= <<<EOD
358
*.*						%{$g['varlog_path']}/ipsec.log
359

    
360
EOD;
361
		}
362
		if (isset($syslogcfg['vpn'])) {
363
			$syslogconf .= <<<EOD
364
*.*						@{$syslogcfg['remoteserver']}
365

    
366
EOD;
367
		}
368
		$syslogconf .= "!openvpn\n";
369
		if (!isset($syslogcfg['disablelocallogging'])) {
370
			$syslogconf .= <<<EOD
371
*.*						%{$g['varlog_path']}/openvpn.log
372

    
373
EOD;
374
		}
375
		if (isset($syslogcfg['vpn'])) {
376
			$syslogconf .= <<<EOD
377
*.*						@{$syslogcfg['remoteserver']}
378

    
379
EOD;
380
		}
381
		$syslogconf .= "!-{$facilitylist}\n";
382
		if (!isset($syslogcfg['disablelocallogging'])) {
383
		$syslogconf .= <<<EOD
384
local0.*					%{$g['varlog_path']}/filter.log
385
local3.*					%{$g['varlog_path']}/vpn.log
386
local4.*					%{$g['varlog_path']}/portalauth.log
387
local7.*					%{$g['varlog_path']}/dhcpd.log
388
*.notice;kern.debug;lpr.info;mail.crit; 	%{$g['varlog_path']}/system.log
389
news.err;local0.none;local3.none;local4.none; 	%{$g['varlog_path']}/system.log
390
local7.none					%{$g['varlog_path']}/system.log
391
security.*					%{$g['varlog_path']}/system.log
392
auth.info;authpriv.info;daemon.info		%{$g['varlog_path']}/system.log
393
local1.*					%{$g['varlog_path']}/relayd.log
394
auth.info;authpriv.info 			|exec /usr/local/sbin/sshlockout_pf
395
*.emerg						*
396

    
397
EOD;
398
		}
399

    
400
		if (isset($syslogcfg['filter'])) {
401
			$syslogconf .= <<<EOD
402
local0.*					@{$syslogcfg['remoteserver']}
403

    
404
EOD;
405
		}
406

    
407
		if (isset($syslogcfg['vpn'])) {
408
			$syslogconf .= <<<EOD
409
local3.*					@{$syslogcfg['remoteserver']}
410

    
411
EOD;
412
		}
413

    
414

    
415
		if (isset($syslogcfg['portalauth'])) {
416
			$syslogconf .= <<<EOD
417
local4.*					@{$syslogcfg['remoteserver']}
418

    
419
EOD;
420
		}
421

    
422

    
423
		if (isset($syslogcfg['dhcp'])) {
424
			$syslogconf .= <<<EOD
425
local7.*					@{$syslogcfg['remoteserver']}
426

    
427
EOD;
428
		}
429

    
430
		if (isset($syslogcfg['system'])) {
431
			$syslogconf .= <<<EOD
432
*.notice;kern.debug;lpr.info;mail.crit;		@{$syslogcfg['remoteserver']}
433
news.err;local0.none;local3.none;local7.none	@{$syslogcfg['remoteserver']}
434
security.*					@{$syslogcfg['remoteserver']}
435
auth.info;authpriv.info;daemon.info		@{$syslogcfg['remoteserver']}
436
*.emerg						@{$syslogcfg['remoteserver']}
437

    
438
EOD;
439
		}
440
		fwrite($fd, $syslogconf);
441
		fclose($fd);
442

    
443
		// Are we logging to a least one remote server ?
444
		if(strpos($syslogconf, "@") != false)
445
			$retval = mwexec("/usr/sbin/syslogd -s -f {$g['varetc_path']}/syslog.conf");
446
		else
447
			$retval = mwexec("/usr/sbin/syslogd -ss -f {$g['varetc_path']}/syslog.conf");
448

    
449
	} else {
450
		$retval = mwexec("/usr/sbin/syslogd -ss");
451
	}
452

    
453
	if ($g['booting'])
454
		echo "done.\n";
455

    
456
	return $retval;
457
}
458

    
459
function system_pccard_start() {
460
	global $config, $g;
461
	if(isset($config['system']['developerspew'])) {
462
		$mt = microtime();
463
		echo "system_pccard_start() being called $mt\n";
464
	}
465

    
466
	if ($g['booting'])
467
		echo "Initializing PCMCIA...";
468

    
469
	/* kill any running pccardd */
470
	killbypid("{$g['varrun_path']}/pccardd.pid");
471

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

    
475
	if ($g['booting']) {
476
		if ($res == 0)
477
			echo "done.\n";
478
		else
479
			echo "failed!\n";
480
	}
481

    
482
	return $res;
483
}
484

    
485

    
486
function system_webgui_start() {
487
	global $config, $g;
488

    
489
	if ($g['booting'])
490
		echo "Starting webConfigurator...";
491

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

    
495
	sleep(1);
496

    
497
	chdir($g['www_path']);
498

    
499
	/* defaults */
500
	$portarg = "80";
501
	$crt = "";
502
	$key = "";
503

    
504
	/* non-standard port? */
505
	if ($config['system']['webgui']['port'])
506
		$portarg = "{$config['system']['webgui']['port']}";
507

    
508
	if ($config['system']['webgui']['protocol'] == "https") {
509

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

    
520
	/* generate lighttpd configuration */
521
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
522
		$crt, $key, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/");
523

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

    
527
	if ($g['booting']) {
528
		if ($res == 0)
529
			echo "done.\n";
530
		else
531
			echo "failed!\n";
532
	}
533

    
534
	return $res;
535
}
536

    
537
function system_generate_lighty_config($filename,
538
	$cert,
539
	$key,
540
	$pid_file,
541
	$port = 80,
542
	$document_root = "/usr/local/www/",
543
	$cert_location = "cert.pem",
544
	$max_procs = 2,
545
	$max_requests = "1",
546
	$fast_cgi_enable = true,
547
	$captive_portal = false) {
548

    
549
	global $config, $g;
550

    
551
	if(isset($config['system']['developerspew'])) {
552
		$mt = microtime();
553
		echo "system_generate_lighty_config() being called $mt\n";
554
	}
555

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

    
581
	$memory = get_memory();
582
	$avail = $memory[0];
583

    
584
	if($avail > 0 and $avail < 98) {
585
		$max_procs = 1;
586
		$max_requests = 1;
587
	}
588

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

    
594
	if($avail > 127 and $avail < 256) {
595
		$max_procs = 1;
596
		$max_requests = 5;
597
	}
598

    
599
	if($avail > 255 and $avail < 384) {
600
		$max_procs = 3;
601
		$max_requests = 10;
602
	}
603

    
604
	if($avail > 383 and $avail < 512) {
605
		$max_procs = 4;
606
		$max_requests = 16;
607
	}
608

    
609
	if($captive_portal == true)  {	
610
		$bin_environment =  <<<EOC
611
        "bin-environment" => (
612
           "PHP_FCGI_CHILDREN" => "16",
613
           "PHP_FCGI_MAX_REQUESTS" => "{$max_requests}"
614
        ), 
615
EOC;
616

    
617
	} else if ($avail > 0 and $avail < 128) {
618
		$bin_environment = <<<EOC
619
	"bin-environment" => (
620
		"PHP_FCGI_CHILDREN" => "1",
621
		"PHP_FCGI_MAX_REQUESTS" => "{$max_requests}"
622
	),
623

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

    
646
#### CGI module
647
cgi.assign                 = ( ".cgi" => "" )
648

    
649
EOD;
650
	} else {
651
		$fastcgi_config = "";
652
		$module = "\"mod_cgi\"";
653
		$cgi_config = <<<EOD
654
#### CGI module
655
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
656
                               ".cgi" => "" )
657

    
658
EOD;
659
	}
660

    
661
	$lighty_config .= <<<EOD
662
#
663
# lighttpd configuration file
664
#
665
# use a it as base for lighttpd 1.0.0 and above
666
#
667
############ Options you really have to take care of ####################
668

    
669
## FreeBSD!
670
server.event-handler		= "freebsd-kqueue"
671
server.network-backend		= "writev"  ## Fixes 7.x upload issues
672

    
673
## modules to load
674
server.modules              =   (
675
									{$captive_portal_module}
676
									"mod_access", "mod_accesslog", "mod_expire", "mod_compress",
677
									{$module}{$captiveportal}
678
								)
679

    
680
## Unused modules
681
#                               "mod_setenv",
682
#                               "mod_compress"
683
#				"mod_redirect",
684
#                               "mod_rewrite",
685
#                               "mod_ssi",
686
#                               "mod_usertrack",
687
#                               "mod_expire",
688
#                               "mod_secdownload",
689
#                               "mod_rrdtool",
690
#                               "mod_auth",
691
#                               "mod_status",
692
#                               "mod_alias",
693
#                               "mod_proxy",
694
#                               "mod_simple_vhost",
695
#                               "mod_evhost",
696
#                               "mod_userdir",
697
#                               "mod_cgi",
698
#                                "mod_accesslog"
699

    
700
## a static document-root, for virtual-hosting take look at the
701
## server.virtual-* options
702
server.document-root        = "{$document_root}"
703
{$captive_portal_rewrite}
704

    
705
## where to send error-messages to
706
server.errorlog             = "/var/log/lighttpd.error.log"
707

    
708
# files to check for if .../ is requested
709
server.indexfiles           = ( "index.php", "index.html",
710
                                "index.htm", "default.htm" )
711

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

    
765
# Use the "Content-Type" extended attribute to obtain mime type if possible
766
#mimetypes.use-xattr        = "enable"
767

    
768
#### accesslog module
769
#accesslog.filename          = "/dev/null"
770

    
771
## deny access the file-extensions
772
#
773
# ~    is for backupfiles from vi, emacs, joe, ...
774
# .inc is often used for code includes which should in general not be part
775
#      of the document-root
776
url.access-deny             = ( "~", ".inc" )
777

    
778

    
779
######### Options that are good to be but not neccesary to be changed #######
780

    
781
## bind to port (default: 80)
782
server.port                = {$lighty_port}
783

    
784
## error-handler for status 404
785
#server.error-handler-404   = "/error-handler.html"
786
#server.error-handler-404   = "/error-handler.php"
787

    
788
## to help the rc.scripts
789
server.pid-file            = "/var/run/{$pid_file}"
790

    
791
## virtual directory listings
792
server.dir-listing         = "disable"
793

    
794
## enable debugging
795
debug.log-request-header   = "disable"
796
debug.log-response-header  = "disable"
797
debug.log-request-handling = "disable"
798
debug.log-file-not-found   = "disable"
799

    
800
{$server_upload_dirs}
801

    
802
{$server_max_request_size}
803

    
804
{$fastcgi_config}
805

    
806
{$cgi_config}
807

    
808
{$captive_portal_mod_evasive}
809

    
810
# Turn on Lighty caching directives
811
compress.cache-dir         = "/tmp/"
812
compress.filetype          = ("text/plain", "text/html", "text/javascript", "text/css")
813

    
814
expire.url = (
815
				"" => "access 50 hours",	
816
        )
817

    
818
EOD;
819

    
820
	$cert = str_replace("\r", "", $cert);
821
	$key = str_replace("\r", "", $key);
822

    
823
	$cert = str_replace("\n\n", "\n", $cert);
824
	$key = str_replace("\n\n", "\n", $key);
825

    
826
	if($cert <> "" and $key <> "") {
827
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
828
		if (!$fd) {
829
			printf("Error: cannot open cert.pem in system_webgui_start().\n");
830
			return 1;
831
		}
832
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
833
		fwrite($fd, $cert);
834
		fwrite($fd, "\n");
835
		fwrite($fd, $key);
836
		fclose($fd);
837
		$lighty_config .= "\n";
838
		$lighty_config .= "## ssl configuration\n";
839
		$lighty_config .= "ssl.engine = \"enable\"\n";
840
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
841
	}
842

    
843
	$fd = fopen("{$filename}", "w");
844
	if (!$fd) {
845
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
846
		return 1;
847
	}
848
	fwrite($fd, $lighty_config);
849
	fclose($fd);
850

    
851
	return 0;
852

    
853
}
854

    
855
function system_timezone_configure() {
856
	global $config, $g;
857
	if(isset($config['system']['developerspew'])) {
858
		$mt = microtime();
859
		echo "system_timezone_configure() being called $mt\n";
860
	}
861

    
862
	$syscfg = $config['system'];
863

    
864
	if ($g['booting'])
865
		echo "Setting timezone...";
866

    
867
	/* extract appropriate timezone file */
868
	$timezone = $syscfg['timezone'];
869
	if (!$timezone)
870
		$timezone = "Etc/UTC";
871

    
872
	conf_mount_rw();
873

    
874
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
875
		escapeshellarg($timezone) . " > /etc/localtime");
876

    
877
	mwexec("sync");
878
	conf_mount_ro();
879

    
880
	if ($g['booting'])
881
		echo "done.\n";
882
}
883

    
884
function system_ntp_configure() {
885
	global $config, $g;
886

    
887
	$syscfg = $config['system'];
888

    
889
	if (!$config['installedpackages']['openntpd'])
890
		return;
891

    
892
	/* open configuration for wrting or bail */
893
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
894
	if(!$fd) {
895
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
896
		return;
897
	}
898

    
899
	fwrite($fd, "# \n");
900
	fwrite($fd, "# pfSense OpenNTPD configuration file \n");
901
	fwrite($fd, "# \n\n");
902

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

    
907
	/* Setup listener(s) if the user has configured one */
908
        if ($config['installedpackages']['openntpd']) {
909
    		/* server config is in coregui1 */
910
		$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
911
		if ($xmlsettings['enable'] == 'on') {
912
			$ifaces = explode(',', $xmlsettings['interface']);
913
			$ifaces = array_map('convert_friendly_interface_to_real_interface_name', $ifaces);
914
			$ifaces = array_filter($ifaces, 'does_interface_exist');
915
			$ips = array_map('find_interface_ip', $ifaces);
916
			foreach ($ips as $ip) {
917
				if (is_ipaddr($ip))
918
					fwrite($fd, "listen on $ip\n");
919
			}
920
		}
921
	}
922

    
923
	fwrite($fd, "\n");
924

    
925
	/* slurp! */
926
	fclose($fd);
927

    
928
	/* if openntpd is running, kill it */
929
	while(is_process_running("ntpd")) {
930
		exec("/usr/bin/killall ntpd");
931
		sleep(3);
932
	}
933

    
934
	/* if /var/empty does not exist, create it */
935
	if(!is_dir("/var/empty"))
936
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
937

    
938
	sleep(1);
939

    
940
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
941
	exec("/usr/local/sbin/ntpd -s -f {$g['varetc_path']}/ntpd.conf");
942

    
943
}
944

    
945
function sync_system_time() {
946
	global $config, $g;
947

    
948
	$syscfg = $config['system'];
949

    
950
	if ($g['booting'])
951
		echo "Syncing system time before startup...";
952

    
953
	/* foreach through servers and write out to ntpd.conf */
954
	foreach (explode(' ', $syscfg['timeservers']) as $ts) {
955
		mwexec("/usr/sbin/ntpdate -s $ts");
956
	}
957
	
958
	if ($g['booting'])
959
		echo "done.\n";
960
	
961
}
962

    
963
function system_halt() {
964
	global $g;
965

    
966
	system_reboot_cleanup();
967

    
968
	mwexec("nohup /etc/rc.halt > /dev/null 2>&1 &");
969
}
970

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

    
974
	system_reboot_cleanup();
975

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

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

    
982
	system_reboot_cleanup();
983

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

    
987
function system_reboot_cleanup() {
988
	mwexec("/usr/local/bin/beep.sh stop");
989
	captiveportal_radius_stop_all();
990
}
991

    
992
function system_do_shell_commands($early = 0) {
993
	global $config, $g;
994
	if(isset($config['system']['developerspew'])) {
995
		$mt = microtime();
996
		echo "system_do_shell_commands() being called $mt\n";
997
	}
998

    
999
	if ($early)
1000
		$cmdn = "earlyshellcmd";
1001
	else
1002
		$cmdn = "shellcmd";
1003

    
1004
	if (is_array($config['system'][$cmdn])) {
1005

    
1006
		/* *cmd is an array, loop through */
1007
		foreach ($config['system'][$cmdn] as $cmd) {
1008
			exec($cmd);
1009
		}
1010

    
1011
	} elseif($config['system'][$cmdn] <> "") {
1012

    
1013
		/* execute single item */
1014
		exec($config['system'][$cmdn]);
1015

    
1016
	}
1017
}
1018

    
1019
function system_console_configure() {
1020
	global $config, $g;
1021
	if(isset($config['system']['developerspew'])) {
1022
		$mt = microtime();
1023
		echo "system_console_configure() being called $mt\n";
1024
	}
1025

    
1026
	if (isset($config['system']['disableconsolemenu'])) {
1027
		touch("{$g['varetc_path']}/disableconsole");
1028
	} else {
1029
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1030
	}
1031
}
1032

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

    
1040
	$dmesg = "";
1041
	exec("/sbin/dmesg", $dmesg);
1042

    
1043
	/* find last copyright line (output from previous boots may be present) */
1044
	$lastcpline = 0;
1045

    
1046
	for ($i = 0; $i < count($dmesg); $i++) {
1047
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1048
			$lastcpline = $i;
1049
	}
1050

    
1051
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1052
	if (!$fd) {
1053
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1054
		return 1;
1055
	}
1056

    
1057
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1058
		fwrite($fd, $dmesg[$i] . "\n");
1059

    
1060
	fclose($fd);
1061

    
1062
	return 0;
1063
}
1064

    
1065
function system_set_harddisk_standby() {
1066
	global $g, $config;
1067
	if(isset($config['system']['developerspew'])) {
1068
		$mt = microtime();
1069
		echo "system_set_harddisk_standby() being called $mt\n";
1070
	}
1071

    
1072
	if (isset($config['system']['harddiskstandby'])) {
1073
		if ($g['booting']) {
1074
			echo 'Setting hard disk standby... ';
1075
		}
1076

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

    
1097
function system_setup_sysctl() {
1098
	global $config;
1099
	if(isset($config['system']['developerspew'])) {
1100
		$mt = microtime();
1101
		echo "system_setup_sysctl() being called $mt\n";
1102
	}
1103

    
1104
	activate_sysctls();	
1105

    
1106
	if (isset($config['system']['sharednet'])) {
1107
		system_disable_arp_wrong_if();
1108
	}
1109
}
1110

    
1111
function system_disable_arp_wrong_if() {
1112
	global $config;
1113
	if(isset($config['system']['developerspew'])) {
1114
		$mt = microtime();
1115
		echo "system_disable_arp_wrong_if() being called $mt\n";
1116
	}
1117
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1118
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1119
}
1120

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

    
1131
function enable_watchdog() {
1132
	global $config;
1133
	$install_watchdog = false;
1134
	$supported_watchdogs = array("Geode");
1135
	$file = file_get_contents("/var/log/dmesg.boot");
1136
	foreach($supported_watchdogs as $sd) {
1137
		if(stristr($file, "Geode")) {
1138
			$install_watchdog = true;
1139
		}
1140
	}
1141
	if($install_watchdog == true) {
1142
		if(is_process_running("watchdogd"))
1143
			exec("/usr/bin/killall watchdogd");
1144
		exec("/usr/sbin/watchdogd");
1145
	}
1146
}
1147

    
1148
?>
(30-30/37)