Project

General

Profile

Download (31.2 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
	foreach($dns_lists as $dns) {
123
		$items = split("\n", file_get_contents($dns));
124
		foreach($items as $item)
125
			if($item <> "")
126
				$master_list[] = $item;
127
	}
128
	if(!file_exists("/var/etc/nameservers.conf"))
129
		return $master_list;
130
	$dns = `cat /var/etc/nameservers.conf`;
131
	$dns_s = split("\n", $dns);
132
	if(is_array($dns_s))
133
		foreach($dns_s as $dns)
134
			$master_list[] = $dns;
135
	return $master_list;
136
}
137

    
138
function system_hosts_generate() {
139
	global $config, $g;
140
	if(isset($config['system']['developerspew'])) {
141
		$mt = microtime();
142
		echo "system_hosts_generate() being called $mt\n";
143
	}
144

    
145
	$syscfg = $config['system'];
146
	$lancfg = $config['interfaces']['lan'];
147
	$dnsmasqcfg = $config['dnsmasq'];
148

    
149
	if (!is_array($dnsmasqcfg['hosts'])) {
150
		$dnsmasqcfg['hosts'] = array();
151
	}
152
	$hostscfg = $dnsmasqcfg['hosts'];
153

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

    
160
	$hosts = <<<EOD
161
127.0.0.1	localhost localhost.{$syscfg['domain']}
162
{$lancfg['ipaddr']}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}
163

    
164
EOD;
165

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

    
182
	return 0;
183
}
184

    
185
function system_hostname_configure() {
186
	global $config, $g;
187
	if(isset($config['system']['developerspew'])) {
188
		$mt = microtime();
189
		echo "system_hostname_configure() being called $mt\n";
190
	}
191

    
192
	$syscfg = $config['system'];
193

    
194
	/* set hostname */
195
	return mwexec("/bin/hostname " .
196
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
197
}
198

    
199
function system_routing_configure() {
200
	global $config, $g;
201
	if(isset($config['system']['developerspew'])) {
202
		$mt = microtime();
203
		echo "system_routing_configure() being called $mt\n";
204
	}
205

    
206
	/* Enable fast routing, if enabled */
207
	if(isset($config['staticroutes']['enablefastrouting']))
208
		mwexec("/sbin/sysctl net.inet.ip.fastforwarding=1");
209

    
210
	exec("/usr/bin/netstat -rn", $route_arr, $retval);
211
	$route_str = implode("\n", $route_arr);
212

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

    
229
	/* if list */
230
	$iflist = get_configured_interface_list();
231

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

    
239
	if($config['interfaces']['wan']['ipaddr'] == "carpdev-dhcp")
240
		$dont_remove_route = true;
241

    
242
	if($dont_remove_route == false) {
243
		/* remove default route */
244
		mwexec("/sbin/route delete default", true);
245
	}
246

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

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

    
281
	if (is_array($config['staticroutes']['route'])) {
282

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

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

    
315
	return 0;
316
}
317

    
318

    
319
function system_routing_enable() {
320
	global $config, $g;
321
	if(isset($config['system']['developerspew'])) {
322
		$mt = microtime();
323
		echo "system_routing_enable() being called $mt\n";
324
	}
325

    
326
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
327
}
328

    
329
function system_syslogd_start() {
330
	global $config, $g;
331
	if(isset($config['system']['developerspew'])) {
332
		$mt = microtime();
333
		echo "system_syslogd_start() being called $mt\n";
334
	}
335

    
336
	$syslogcfg = $config['syslog'];
337

    
338
	if ($g['booting'])
339
		echo "Starting syslog...";
340
	else
341
		killbypid("{$g['varrun_path']}/syslog.pid");
342

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

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

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

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

    
388
EOD;
389
		}
390
		if (isset($syslogcfg['vpn'])) {
391
			$syslogconf .= <<<EOD
392
*.*						@{$syslogcfg['remoteserver']}
393

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

    
412
EOD;
413
		}
414

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

    
419
EOD;
420
		}
421

    
422
		if (isset($syslogcfg['vpn'])) {
423
			$syslogconf .= <<<EOD
424
local3.*					@{$syslogcfg['remoteserver']}
425

    
426
EOD;
427
		}
428

    
429

    
430
		if (isset($syslogcfg['portalauth'])) {
431
			$syslogconf .= <<<EOD
432
local4.*					@{$syslogcfg['remoteserver']}
433

    
434
EOD;
435
		}
436

    
437

    
438
		if (isset($syslogcfg['dhcp'])) {
439
			$syslogconf .= <<<EOD
440
local7.*					@{$syslogcfg['remoteserver']}
441

    
442
EOD;
443
		}
444

    
445
		if (isset($syslogcfg['system'])) {
446
			$syslogconf .= <<<EOD
447
*.notice;kern.debug;lpr.info;mail.crit;		@{$syslogcfg['remoteserver']}
448
news.err;local0.none;local3.none;local7.none	@{$syslogcfg['remoteserver']}
449
security.*					@{$syslogcfg['remoteserver']}
450
auth.info;authpriv.info;daemon.info		@{$syslogcfg['remoteserver']}
451
*.emerg						@{$syslogcfg['remoteserver']}
452

    
453
EOD;
454
		}
455
		fwrite($fd, $syslogconf);
456
		fclose($fd);
457

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

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

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

    
471
	return $retval;
472
}
473

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

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

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

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

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

    
497
	return $res;
498
}
499

    
500

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

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

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

    
510
	sleep(1);
511

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

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

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

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

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

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

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

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

    
549
	return $res;
550
}
551

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

    
564
	global $config, $g;
565

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

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

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

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

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

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

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

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

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

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

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

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

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

    
673
EOD;
674
	}
675

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

    
684
## FreeBSD!
685
server.event-handler		= "freebsd-kqueue"
686
server.network-backend		= "freebsd-sendfile"  ## was writev - Fixes 7.x upload issues
687

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

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

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

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

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

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

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

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

    
786
#### accesslog module
787
#accesslog.filename          = "/dev/null"
788

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

    
796

    
797
######### Options that are good to be but not neccesary to be changed #######
798

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

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

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

    
809
## virtual directory listings
810
server.dir-listing         = "disable"
811

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

    
818
{$server_upload_dirs}
819

    
820
{$server_max_request_size}
821

    
822
{$fastcgi_config}
823

    
824
{$cgi_config}
825

    
826
{$captive_portal_mod_evasive}
827

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

    
832
expire.url = (
833
				"" => "access 50 hours",	
834
        )
835

    
836
EOD;
837

    
838
	$cert = str_replace("\r", "", $cert);
839
	$key = str_replace("\r", "", $key);
840

    
841
	$cert = str_replace("\n\n", "\n", $cert);
842
	$key = str_replace("\n\n", "\n", $key);
843

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

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

    
869
	return 0;
870

    
871
}
872

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

    
880
	$syscfg = $config['system'];
881

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

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

    
890
	conf_mount_rw();
891

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

    
895
	mwexec("sync");
896
	conf_mount_ro();
897

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

    
902
function system_ntp_configure() {
903
	global $config, $g;
904

    
905
	$syscfg = $config['system'];
906

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

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

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

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

    
938
	fwrite($fd, "\n");
939

    
940
	/* slurp! */
941
	fclose($fd);
942

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

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

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

    
958
}
959

    
960
function sync_system_time() {
961
	global $config, $g;
962

    
963
	$syscfg = $config['system'];
964

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

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

    
978
function system_halt() {
979
	global $g;
980

    
981
	system_reboot_cleanup();
982

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

    
986
function system_reboot() {
987
	global $g;
988

    
989
	system_reboot_cleanup();
990

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

    
994
function system_reboot_sync() {
995
	global $g;
996

    
997
	system_reboot_cleanup();
998

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

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

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

    
1014
	if ($early)
1015
		$cmdn = "earlyshellcmd";
1016
	else
1017
		$cmdn = "shellcmd";
1018

    
1019
	if (is_array($config['system'][$cmdn])) {
1020

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

    
1026
	} elseif($config['system'][$cmdn] <> "") {
1027

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

    
1031
	}
1032
}
1033

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

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

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

    
1055
	$dmesg = "";
1056
	exec("/sbin/dmesg", $dmesg);
1057

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

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

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

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

    
1075
	fclose($fd);
1076

    
1077
	return 0;
1078
}
1079

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

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

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

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

    
1119
	activate_sysctls();	
1120

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

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

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

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

    
1163
?>
(32-32/39)