Project

General

Profile

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

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

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

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

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

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

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

    
35
function activate_sysctls() {
36
	global $config, $g;
37
	
38
	exec("/sbin/sysctl net.enc.out.ipsec_bpf_mask=0x00000000");
39
	exec("/sbin/sysctl net.enc.out.ipsec_filter_mask=0x00000001");
40
	exec("/sbin/sysctl net.enc.in.ipsec_bpf_mask=0x00000000");
41
	exec("/sbin/sysctl net.enc.in.ipsec_filter_mask=0x00000002");
42

    
43
	if (is_array($config['sysctl'])) 
44
		foreach ($config['sysctl']['item'] as $tunable) 
45
			mwexec("sysctl " . $tunable['tunable'] . "=\"" 
46
				. $tunable['value'] .  "\"");
47
}
48

    
49
function system_resolvconf_generate($dynupdate = false) {
50
	global $config, $g;
51

    
52
	if(isset($config['system']['developerspew'])) {
53
		$mt = microtime();
54
		echo "system_resolvconf_generate() being called $mt\n";
55
	}
56

    
57
        $syscfg = $config['system'];
58

    
59
        $fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
60
        if (!$fd) {
61
                printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
62
                return 1;
63
        }
64

    
65
        $resolvconf = "domain {$syscfg['domain']}\n";
66

    
67
        $havedns = false;
68

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

    
88
        fwrite($fd, $resolvconf);
89
        fclose($fd);
90

    
91
        if (!$g['booting']) {
92
		/* restart dhcpd (nameservers may have changed) */
93
		if (!$dynupdate)
94
			services_dhcpd_configure();
95
        }
96

    
97
	/* setup static routes for DNS servers. */
98
	for ($dnscounter=1; $dnscounter<5; $dnscounter++) {
99
		/* setup static routes for dns servers */
100
		$dnsgw = "dns{$dnscounter}gwint";
101
		if (isset($config['system'][$dnsgw])) {
102
			$interface = $config['system'][$dnsgw];
103
			if (($interface <> "") && ($interface <> "none")) {
104
				$gatewayip = get_interface_gateway($interface);
105
				if(is_ipaddr($gatewayip)) {
106
					/* dns server array starts at 0 */
107
					$dnscountermo = $dnscounter - 1;
108
					mwexec("route delete -host {$syscfg['dnsserver'][$dnscountermo]}");
109
					mwexec("route add -host {$syscfg['dnsserver'][$dnscountermo]} {$gatewayip}");
110
				}
111
			}
112
		}
113
	}
114
	
115
	return 0;
116
}
117

    
118
function get_nameservers() {
119
	global $config, $g;
120
	$master_list = array();
121
	$dns_lists = split("\n", `ls /var/etc/nameserver_* 2>/dev/null`);
122
	if(is_array($dns_lists)) {
123
		foreach($dns_lists as $dns) {
124
			if(!$dns) 
125
				continue;
126
			$items = split("\n", file_get_contents($dns));
127
			foreach($items as $item)
128
				if($item <> "")
129
					$master_list[] = $item;
130
		}
131
	}
132
	if(!file_exists("/var/etc/nameservers.conf"))
133
		return $master_list;
134
	$dns = `cat /var/etc/nameservers.conf`;
135
	$dns_s = split("\n", $dns);
136
	if(is_array($dns_s))
137
		foreach($dns_s as $dns)
138
			$master_list[] = $dns;
139
	return $master_list;
140
}
141

    
142
function system_hosts_generate() {
143
	global $config, $g;
144
	if(isset($config['system']['developerspew'])) {
145
		$mt = microtime();
146
		echo "system_hosts_generate() being called $mt\n";
147
	}
148

    
149
	$syscfg = $config['system'];
150
	$lancfg = $config['interfaces']['lan'];
151
	$dnsmasqcfg = $config['dnsmasq'];
152

    
153
	if (!is_array($dnsmasqcfg['hosts'])) {
154
		$dnsmasqcfg['hosts'] = array();
155
	}
156
	$hostscfg = $dnsmasqcfg['hosts'];
157

    
158
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
159
	if (!$fd) {
160
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
161
		return 1;
162
	}
163

    
164
	$hosts = <<<EOD
165
127.0.0.1	localhost localhost.{$syscfg['domain']}
166
{$lancfg['ipaddr']}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}
167

    
168
EOD;
169

    
170
	foreach ($hostscfg as $host) {
171
		if ($host['host'])
172
			$hosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
173
		else
174
			$hosts .= "{$host['ip']}	{$host['domain']}\n";
175
	}
176
	if (isset($dnsmasqcfg['regdhcpstatic'])) {
177
		foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf)
178
			if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
179
					foreach ($dhcpifconf['staticmap'] as $host)
180
						if ($host['ipaddr'] && $host['hostname'])
181
							$hosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
182
	}
183
	fwrite($fd, $hosts);
184
	fclose($fd);
185

    
186
	return 0;
187
}
188

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

    
196
	$syscfg = $config['system'];
197

    
198
	/* set hostname */
199
	return mwexec("/bin/hostname " .
200
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
201
}
202

    
203
function system_routing_configure() {
204
	global $config, $g;
205
	if(isset($config['system']['developerspew'])) {
206
		$mt = microtime();
207
		echo "system_routing_configure() being called $mt\n";
208
	}
209

    
210
	/* Enable fast routing, if enabled */
211
	if(isset($config['staticroutes']['enablefastrouting']))
212
		mwexec("/sbin/sysctl net.inet.ip.fastforwarding=1");
213

    
214
	exec("/usr/bin/netstat -rn", $route_arr, $retval);
215
	$route_str = implode("\n", $route_arr);
216

    
217
	/* clear out old routes, if necessary */
218
	if (file_exists("{$g['vardb_path']}/routes.db")) {
219
		$fd = fopen("{$g['vardb_path']}/routes.db", "r");
220
		if (!$fd) {
221
			printf("Error: cannot open routes DB file in system_routing_configure().\n");
222
			return 1;
223
		}
224
		while (!feof($fd)) {
225
			$oldrt = trim(fgets($fd));
226
			if (($oldrt) && (stristr($route_str, $oldrt)))
227
				mwexec("/sbin/route delete " . escapeshellarg($oldrt));
228
		}
229
		fclose($fd);
230
		unlink("{$g['vardb_path']}/routes.db");
231
	}
232

    
233
	/* if list */
234
	$iflist = get_configured_interface_list();
235

    
236
	$dont_remove_route = false;
237
	foreach ($iflist as $ifent => $ifname) {
238
		/* do not process interfaces that will end up with gateways */
239
		if (interface_has_gateway($ifent))
240
			$dont_remove_route = true;
241
	}
242

    
243
	if($config['interfaces']['wan']['ipaddr'] == "carpdev-dhcp")
244
		$dont_remove_route = true;
245

    
246
	if($dont_remove_route == false) {
247
		/* remove default route */
248
		mwexec("/sbin/route delete default", true);
249
	}
250

    
251
	$dont_add_route = false;
252
	/* if OLSRD is enabled, allow WAN to house DHCP. */
253
	if($config['installedpackages']['olsrd']) {
254
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
255
			if($olsrd['enabledyngw'] == "on") {
256
				$dont_add_route = true;
257
			}
258
		}
259
	}
260

    
261
	if($dont_add_route == false) {
262
		if(is_array($config['gateways']['gateway_item'])) {
263
			foreach($config['gateways']['gateway_item'] as $gateway) {
264
		        	if(isset($gateway['defaultgw'])) {
265
					$gatewayip = $gateway['gateway'];
266
					$interfacegw = $gateway['interface'];
267
				}
268
			}
269
			if(($interfacegw <> "bgpd") && (is_ipaddr($gatewayip)))
270
				mwexec("/sbin/route add default " . escapeshellarg($gatewayip), true);
271
		} else {
272
			/* FIXME */
273
			/* adding gateway for 1.2-style configs without the new
274
			  gateway setup configured.
275
			  Force WAN to be default gateway because that is the
276
			  1.2 behavior.
277
			*/
278
			if (is_ipaddr($config['interfaces']['wan']['gateway'])) {
279
				$gatewayip = $config['interfaces']['wan']['gateway'];
280
				mwexec("/sbin/route add default " . escapeshellarg($gatewayip), true);
281
			}
282
		}
283
	}
284

    
285
	if (is_array($config['staticroutes']['route'])) {
286

    
287
		$fd = fopen("{$g['vardb_path']}/routes.db", "w");
288
		if (!$fd) {
289
			printf("Error: cannot open routes DB file in system_routing_configure().\n");
290
			return 1;
291
		}
292

    
293
		foreach ($config['staticroutes']['route'] as $rtent) {
294
			if(is_array($config['gateways']['gateway_item'])) {
295
				foreach($config['gateways']['gateway_item'] as $gateway) {
296
					if($rtent['gateway'] == $gateway['name']) {
297
						$gatewayip = $gateway['gateway'];
298
						$interfacegw = $gateway['interface'];
299
					}
300
				}
301
			}
302
			if((is_ipaddr($rtent['gateway'])) && ($gatewayip == ""))  {
303
				$gatewayip = $rtent['gateway'];
304
				$interfacegw = $rtent['interface'];
305
			}			
306
			if(isset($rtent['interfacegateway'])) {
307
				mwexec("/sbin/route add " . escapeshellarg($rtent['network']) .
308
					" -iface " . escapeshellarg(convert_friendly_interface_to_real_interface_name($interfacegw)));
309
			} else {
310
				mwexec("/sbin/route add " . escapeshellarg($rtent['network']) .
311
					" " . escapeshellarg($gatewayip));
312
			}
313
			/* record route so it can be easily removed later (if necessary) */
314
			fwrite($fd, $rtent['network'] . "\n");
315
		}
316
		fclose($fd);
317
	}
318

    
319
	return 0;
320
}
321

    
322

    
323
function system_routing_enable() {
324
	global $config, $g;
325
	if(isset($config['system']['developerspew'])) {
326
		$mt = microtime();
327
		echo "system_routing_enable() being called $mt\n";
328
	}
329

    
330
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
331
}
332

    
333
function system_syslogd_start() {
334
	global $config, $g;
335
	if(isset($config['system']['developerspew'])) {
336
		$mt = microtime();
337
		echo "system_syslogd_start() being called $mt\n";
338
	}
339

    
340
	$syslogcfg = $config['syslog'];
341

    
342
	if ($g['booting'])
343
		echo "Starting syslog...";
344
	else
345
		killbypid("{$g['varrun_path']}/syslog.pid");
346

    
347
	if (isset($syslogcfg)) {
348
		$separatelogfacilities = array('ntpd','racoon','openvpn');
349
		if($config['installedpackages']['package']) {
350
                        foreach($config['installedpackages']['package'] as $package) {
351
                                if($package['logging']) {
352
					$pkgfacilities[] = $package['logging']['facilityname'];
353
					$separatelogfacilities = $separatelogfacilities + $pkgfacilities;
354
					$facilitylist = implode(',', $pkgfacilities);
355
					mwexec("clog -i -s 10000 {$g['varlog_path']}/{$package['logging']['logfilename']}");
356
                                	$syslogconf .= "!{$facilitylist}\n*.*\t\t\t\t\t\t%{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
357
				}
358
                        }
359
                }
360
		$facilitylist = implode(',', array_unique($separatelogfacilities));
361
		/* write syslog.conf */
362
		$fd = fopen("{$g['varetc_path']}/syslog.conf", "w");
363
		if (!$fd) {
364
			printf("Error: cannot open syslog.conf in system_syslogd_start().\n");
365
			return 1;
366
		}
367
		$syslogconf .= "!ntpdate,!ntpd\n";
368
		if (!isset($syslogcfg['disablelocallogging'])) {
369
			$syslogconf .= <<<EOD
370
*.*						%{$g['varlog_path']}/ntpd.log
371

    
372
EOD;
373
		}
374
		$syslogconf .= "!racoon\n";
375
		if (!isset($syslogcfg['disablelocallogging'])) {
376
			$syslogconf .= <<<EOD
377
*.*						%{$g['varlog_path']}/ipsec.log
378

    
379
EOD;
380
		}
381
		if (isset($syslogcfg['vpn'])) {
382
			$syslogconf .= <<<EOD
383
*.*						@{$syslogcfg['remoteserver']}
384

    
385
EOD;
386
		}
387
		$syslogconf .= "!openvpn\n";
388
		if (!isset($syslogcfg['disablelocallogging'])) {
389
			$syslogconf .= <<<EOD
390
*.*						%{$g['varlog_path']}/openvpn.log
391

    
392
EOD;
393
		}
394
		if (isset($syslogcfg['vpn'])) {
395
			$syslogconf .= <<<EOD
396
*.*						@{$syslogcfg['remoteserver']}
397

    
398
EOD;
399
		}
400
		$syslogconf .= "!-{$facilitylist}\n";
401
		if (!isset($syslogcfg['disablelocallogging'])) {
402
		$syslogconf .= <<<EOD
403
local0.*					%{$g['varlog_path']}/filter.log
404
local3.*					%{$g['varlog_path']}/vpn.log
405
local4.*					%{$g['varlog_path']}/portalauth.log
406
local7.*					%{$g['varlog_path']}/dhcpd.log
407
*.notice;kern.debug;lpr.info;mail.crit; 	%{$g['varlog_path']}/system.log
408
news.err;local0.none;local3.none;local4.none; 	%{$g['varlog_path']}/system.log
409
local7.none					%{$g['varlog_path']}/system.log
410
security.*					%{$g['varlog_path']}/system.log
411
auth.info;authpriv.info;daemon.info		%{$g['varlog_path']}/system.log
412
local1.*					%{$g['varlog_path']}/relayd.log
413
auth.info;authpriv.info 			|exec /usr/local/sbin/sshlockout_pf
414
*.emerg						*
415

    
416
EOD;
417
		}
418

    
419
		if (isset($syslogcfg['filter'])) {
420
			$syslogconf .= <<<EOD
421
local0.*					@{$syslogcfg['remoteserver']}
422

    
423
EOD;
424
		}
425

    
426
		if (isset($syslogcfg['vpn'])) {
427
			$syslogconf .= <<<EOD
428
local3.*					@{$syslogcfg['remoteserver']}
429

    
430
EOD;
431
		}
432

    
433

    
434
		if (isset($syslogcfg['portalauth'])) {
435
			$syslogconf .= <<<EOD
436
local4.*					@{$syslogcfg['remoteserver']}
437

    
438
EOD;
439
		}
440

    
441

    
442
		if (isset($syslogcfg['dhcp'])) {
443
			$syslogconf .= <<<EOD
444
local7.*					@{$syslogcfg['remoteserver']}
445

    
446
EOD;
447
		}
448

    
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
		}
459
		fwrite($fd, $syslogconf);
460
		fclose($fd);
461

    
462
		// Are we logging to a least one remote server ?
463
		if(strpos($syslogconf, "@") != false)
464
			$retval = mwexec("/usr/sbin/syslogd -s -f {$g['varetc_path']}/syslog.conf");
465
		else
466
			$retval = mwexec("/usr/sbin/syslogd -ss -f {$g['varetc_path']}/syslog.conf");
467

    
468
	} else {
469
		$retval = mwexec("/usr/sbin/syslogd -ss");
470
	}
471

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

    
475
	return $retval;
476
}
477

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

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

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

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

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

    
501
	return $res;
502
}
503

    
504

    
505
function system_webgui_start() {
506
	global $config, $g;
507

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

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

    
514
	sleep(1);
515

    
516
	chdir($g['www_path']);
517

    
518
	/* defaults */
519
	$portarg = "80";
520
	$crt = "";
521
	$key = "";
522

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

    
527
	if ($config['system']['webgui']['protocol'] == "https") {
528

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

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

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

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

    
553
	return $res;
554
}
555

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

    
568
	global $config, $g;
569

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

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

    
600
	$memory = get_memory();
601
	$avail = $memory[0];
602

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

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

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

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

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

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

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

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

    
665
#### CGI module
666
cgi.assign                 = ( ".cgi" => "" )
667

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

    
677
EOD;
678
	}
679

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

    
688
## FreeBSD!
689
server.event-handler		= "freebsd-kqueue"
690
server.network-backend		= "freebsd-sendfile"  ## was writev - Fixes 7.x upload issues
691

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

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

    
719
server.max-keep-alive-requests = 15
720
server.max-keep-alive-idle = 30
721

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

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

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

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

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

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

    
793
#### accesslog module
794
#accesslog.filename          = "/dev/null"
795

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

    
803

    
804
######### Options that are good to be but not neccesary to be changed #######
805

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

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

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

    
816
## virtual directory listings
817
server.dir-listing         = "disable"
818

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

    
825
{$server_upload_dirs}
826

    
827
{$server_max_request_size}
828

    
829
{$fastcgi_config}
830

    
831
{$cgi_config}
832

    
833
{$captive_portal_mod_evasive}
834

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

    
839
expire.url = (
840
				"" => "access 50 hours",	
841
        )
842

    
843
EOD;
844

    
845
	$cert = str_replace("\r", "", $cert);
846
	$key = str_replace("\r", "", $key);
847

    
848
	$cert = str_replace("\n\n", "\n", $cert);
849
	$key = str_replace("\n\n", "\n", $key);
850

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

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

    
876
	return 0;
877

    
878
}
879

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

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

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

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

    
897
	conf_mount_rw();
898

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

    
902
	mwexec("sync");
903
	conf_mount_ro();
904

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

    
909
function system_ntp_configure() {
910
	global $config, $g;
911

    
912
	$syscfg = $config['system'];
913

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

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

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

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

    
945
	fwrite($fd, "\n");
946

    
947
	/* slurp! */
948
	fclose($fd);
949

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

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

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

    
965
}
966

    
967
function sync_system_time() {
968
	global $config, $g;
969

    
970
	$syscfg = $config['system'];
971

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

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

    
985
function system_halt() {
986
	global $g;
987

    
988
	system_reboot_cleanup();
989

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

    
993
function system_reboot() {
994
	global $g;
995

    
996
	system_reboot_cleanup();
997

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

    
1001
function system_reboot_sync() {
1002
	global $g;
1003

    
1004
	system_reboot_cleanup();
1005

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

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

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

    
1021
	if ($early)
1022
		$cmdn = "earlyshellcmd";
1023
	else
1024
		$cmdn = "shellcmd";
1025

    
1026
	if (is_array($config['system'][$cmdn])) {
1027

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

    
1033
	} elseif($config['system'][$cmdn] <> "") {
1034

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

    
1038
	}
1039
}
1040

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

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

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

    
1062
	$dmesg = "";
1063
	exec("/sbin/dmesg", $dmesg);
1064

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

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

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

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

    
1082
	fclose($fd);
1083

    
1084
	return 0;
1085
}
1086

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

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

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

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

    
1126
	activate_sysctls();	
1127

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

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

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

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

    
1170
?>
(32-32/39)