Project

General

Profile

Download (30.6 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") && (is_ipaddr($gatewayip)))
253
				mwexec("/sbin/route add default " . escapeshellarg($gatewayip));
254
		} else {
255
			/* FIXME */
256
			/* adding gateway for 1.2-style configs without the new
257
			  gateway setup configured.
258
			  Force WAN to be default gateway because that is the
259
			  1.2 behavior.
260
			*/
261
			if (is_ipaddr($config['interfaces']['wan']['gateway'])) {
262
				$gatewayip = $config['interfaces']['wan']['gateway'];
263
				mwexec("/sbin/route add default " . escapeshellarg($gatewayip));
264
			}
265
		}
266
	}
267

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

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

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

    
302
	return 0;
303
}
304

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

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

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

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

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

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

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

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

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

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

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

    
398
EOD;
399
		}
400

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

    
405
EOD;
406
		}
407

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

    
412
EOD;
413
		}
414

    
415

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

    
420
EOD;
421
		}
422

    
423

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

    
428
EOD;
429
		}
430

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

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

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

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

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

    
457
	return $retval;
458
}
459

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

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

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

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

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

    
483
	return $res;
484
}
485

    
486

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

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

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

    
496
	sleep(1);
497

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

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

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

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

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

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

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

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

    
535
	return $res;
536
}
537

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

    
550
	global $config, $g;
551

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

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

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

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

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

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

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

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

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

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

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

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

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

    
659
EOD;
660
	}
661

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

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

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

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

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

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

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

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

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

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

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

    
779

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

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

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

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

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

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

    
801
{$server_upload_dirs}
802

    
803
{$server_max_request_size}
804

    
805
{$fastcgi_config}
806

    
807
{$cgi_config}
808

    
809
{$captive_portal_mod_evasive}
810

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

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

    
819
EOD;
820

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

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

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

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

    
852
	return 0;
853

    
854
}
855

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

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

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

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

    
873
	conf_mount_rw();
874

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
939
	sleep(1);
940

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

    
944
}
945

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

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

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

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

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

    
967
	system_reboot_cleanup();
968

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

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

    
975
	system_reboot_cleanup();
976

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

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

    
983
	system_reboot_cleanup();
984

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

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

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

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

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

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

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

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

    
1017
	}
1018
}
1019

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

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

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

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

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

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

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

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

    
1061
	fclose($fd);
1062

    
1063
	return 0;
1064
}
1065

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

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

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

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

    
1105
	activate_sysctls();	
1106

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

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

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

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

    
1149
?>
(30-30/37)