Project

General

Profile

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

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

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

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

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

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

    
32

    
33
function activate_powerd() {
34
	global $config, $g;
35
	if(isset($config['system']['powerd_enable'])) {
36
		exec("/usr/sbin/powerd -b adp -a adp");
37
	} else {
38
		exec("/usr/bin/killall powerd");
39
	}
40
}
41

    
42
function activate_sysctls() {
43
	global $config, $g;
44
	
45
	exec("/sbin/sysctl net.enc.out.ipsec_bpf_mask=0x00000000");
46
	exec("/sbin/sysctl net.enc.out.ipsec_filter_mask=0x00000001");
47
	exec("/sbin/sysctl net.enc.in.ipsec_bpf_mask=0x00000000");
48
	exec("/sbin/sysctl net.enc.in.ipsec_filter_mask=0x00000002");
49

    
50
	if (is_array($config['sysctl'])) 
51
		foreach ($config['sysctl']['item'] as $tunable) 
52
			mwexec("sysctl " . $tunable['tunable'] . "=\"" 
53
				. $tunable['value'] .  "\"");
54
}
55

    
56
function system_resolvconf_generate($dynupdate = false) {
57
	global $config, $g;
58

    
59
	if(isset($config['system']['developerspew'])) {
60
		$mt = microtime();
61
		echo "system_resolvconf_generate() being called $mt\n";
62
	}
63

    
64
        $syscfg = $config['system'];
65

    
66
        $fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
67
        if (!$fd) {
68
                printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
69
                return 1;
70
        }
71

    
72
        $resolvconf = "domain {$syscfg['domain']}\n";
73

    
74
        $havedns = false;
75

    
76
        if (isset($syscfg['dnsallowoverride'])) {
77
		/* get dynamically assigned DNS servers (if any) */
78
		$ns = array_unique(get_nameservers());
79
		foreach($ns as $nameserver) {
80
			if($nameserver) {
81
				$resolvconf .= "nameserver $nameserver\n";
82
				$havedns = true;
83
			}
84
		}
85
        }
86
        if (!$havedns && is_array($syscfg['dnsserver'])) {
87
		foreach ($syscfg['dnsserver'] as $ns) {
88
			if ($ns) {
89
				$resolvconf .= "nameserver $ns\n";
90
				$havedns = true;
91
			}
92
		}
93
	}
94

    
95
        fwrite($fd, $resolvconf);
96
        fclose($fd);
97

    
98
        if (!$g['booting']) {
99
		/* restart dhcpd (nameservers may have changed) */
100
		if (!$dynupdate)
101
			services_dhcpd_configure();
102
        }
103

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

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

    
149
function system_hosts_generate() {
150
	global $config, $g;
151
	if(isset($config['system']['developerspew'])) {
152
		$mt = microtime();
153
		echo "system_hosts_generate() being called $mt\n";
154
	}
155

    
156
	$syscfg = $config['system'];
157
	$lancfg = $config['interfaces']['lan'];
158
	$lancfgip = get_interface_ip("lan");
159
	$dnsmasqcfg = $config['dnsmasq'];
160

    
161
	if (!is_array($dnsmasqcfg['hosts'])) {
162
		$dnsmasqcfg['hosts'] = array();
163
	}
164
	$hostscfg = $dnsmasqcfg['hosts'];
165

    
166
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
167
	if (!$fd) {
168
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
169
		return 1;
170
	}
171

    
172
	$hosts = <<<EOD
173
127.0.0.1	localhost localhost.{$syscfg['domain']}
174

    
175
EOD;
176
	if (is_ipaddr($lancfgip))
177
		$hosts .= <<<EOD
178
{$lancfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}
179

    
180
EOD;
181

    
182
	foreach ($hostscfg as $host) {
183
		if ($host['host'])
184
			$hosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
185
		else
186
			$hosts .= "{$host['ip']}	{$host['domain']}\n";
187
	}
188
	if (isset($dnsmasqcfg['regdhcpstatic'])) {
189
		foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf)
190
			if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
191
					foreach ($dhcpifconf['staticmap'] as $host)
192
						if ($host['ipaddr'] && $host['hostname'])
193
							$hosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
194
	}
195
	fwrite($fd, $hosts);
196
	fclose($fd);
197

    
198
	return 0;
199
}
200

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

    
208
	$syscfg = $config['system'];
209

    
210
	/* set hostname */
211
	$status = mwexec("/bin/hostname " .
212
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
213

    
214
    /* Setup host GUID ID.  This is used by ZFS. */
215
	mwexec("/etc/rc.d/hostid start");
216

    
217
	return $status;
218
}
219

    
220
function system_routing_configure() {
221
	global $config, $g;
222
	if(isset($config['system']['developerspew'])) {
223
		$mt = microtime();
224
		echo "system_routing_configure() being called $mt\n";
225
	}
226

    
227
	/* Enable fast routing, if enabled */
228
	if(isset($config['staticroutes']['enablefastrouting']))
229
		mwexec("/sbin/sysctl net.inet.ip.fastforwarding=1");
230

    
231
	$route_str = exec_command("/usr/bin/netstat -rn");
232

    
233
	/* clear out old routes, if necessary */
234
	if (file_exists("{$g['vardb_path']}/routes.db")) {
235
		$fd = fopen("{$g['vardb_path']}/routes.db", "r");
236
		if (!$fd) {
237
			printf("Error: cannot open routes DB file in system_routing_configure().\n");
238
			return 1;
239
		}
240
		while (!feof($fd)) {
241
			$oldrt = trim(fgets($fd));
242
			if (($oldrt) && (stristr($route_str, $oldrt)))
243
				mwexec("/sbin/route delete " . escapeshellarg($oldrt));
244
		}
245
		fclose($fd);
246
		unlink("{$g['vardb_path']}/routes.db");
247
	}
248

    
249
	/* if list */
250
	$iflist = get_configured_interface_list();
251

    
252
	$dont_remove_route = false;
253
	foreach ($iflist as $ifent => $ifname) {
254
		/* 
255
		 * XXX: The value of this is really when this function can take
256
		 * 	an interface as parameter.
257
		 */
258
		/* do not process interfaces that will end up with gateways */
259
		if (interface_has_gateway($ifent) || 
260
			$config['interfaces'][$ifent]['ipaddr'] == "carpdev-dhcp") {
261
			$dont_remove_route = true;
262
			break;
263
		}
264
	}
265

    
266
	if ($dont_remove_route == false) {
267
		/* remove default route */
268
		mwexec("/sbin/route delete default", true);
269
	}
270

    
271
	$dont_add_route = false;
272
	/* if OLSRD is enabled, allow WAN to house DHCP. */
273
	if($config['installedpackages']['olsrd']) {
274
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
275
			if($olsrd['enabledyngw'] == "on") {
276
				$dont_add_route = true;
277
				break;
278
			}
279
		}
280
	}
281

    
282
	if($dont_add_route == false) {
283
		if(is_array($config['gateways']['gateway_item'])) {
284
			foreach($config['gateways']['gateway_item'] as $gateway) {
285
		        	if(isset($gateway['defaultgw'])) {
286
					$gatewayip = $gateway['gateway'];
287
					$interfacegw = $gateway['interface'];
288
				}
289
			}
290
			if(($interfacegw <> "bgpd") && (is_ipaddr($gatewayip)))
291
				mwexec("/sbin/route add default " . escapeshellarg($gatewayip), true);
292
		} else {
293
			/* FIXME */
294
			/* adding gateway for 1.2-style configs without the new
295
			  gateway setup configured.
296
			  Force WAN to be default gateway because that is the
297
			  1.2 behavior.
298
			*/
299
			if (is_ipaddr($config['interfaces']['wan']['gateway'])) {
300
				$gatewayip = $config['interfaces']['wan']['gateway'];
301
				mwexec("/sbin/route add default " . escapeshellarg($gatewayip), true);
302
			}
303
		}
304
	}
305

    
306
	if (is_array($config['staticroutes']['route'])) {
307

    
308
		$fd = fopen("{$g['vardb_path']}/routes.db", "w");
309
		if (!$fd) {
310
			printf("Error: cannot open routes DB file in system_routing_configure().\n");
311
			return 1;
312
		}
313

    
314
		foreach ($config['staticroutes']['route'] as $rtent) {
315
			unset($gatewayip);
316
			unset($interfacegw);
317
			if(is_array($config['gateways']['gateway_item'])) {
318
				foreach($config['gateways']['gateway_item'] as $gateway) {
319
					if($rtent['gateway'] == $gateway['name']) {
320
						$gatewayip = $gateway['gateway'];
321
						$interfacegw = $gateway['interface'];
322
					}
323
				}
324
			}
325
			if((is_ipaddr($rtent['gateway'])) && ($gatewayip == ""))  {
326
				$gatewayip = $rtent['gateway'];
327
				$interfacegw = $rtent['interface'];
328
			}			
329
			if((isset($rtent['interfacegateway'])) && (! is_ipaddr($gatewayip))){
330
				mwexec("/sbin/route add " . escapeshellarg($rtent['network']) .
331
					" -iface " . escapeshellarg(convert_friendly_interface_to_real_interface_name($interfacegw)));
332
			} else {
333
				mwexec("/sbin/route add " . escapeshellarg($rtent['network']) .
334
					" " . escapeshellarg($gatewayip));
335
			}
336
			/* record route so it can be easily removed later (if necessary) */
337
			fwrite($fd, $rtent['network'] . "\n");
338
		}
339
		fclose($fd);
340
	}
341

    
342
	return 0;
343
}
344

    
345

    
346
function system_routing_enable() {
347
	global $config, $g;
348
	if(isset($config['system']['developerspew'])) {
349
		$mt = microtime();
350
		echo "system_routing_enable() being called $mt\n";
351
	}
352

    
353
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
354
}
355

    
356
function system_syslogd_start() {
357
	global $config, $g;
358
	if(isset($config['system']['developerspew'])) {
359
		$mt = microtime();
360
		echo "system_syslogd_start() being called $mt\n";
361
	}
362

    
363
	$syslogcfg = $config['syslog'];
364

    
365
	if ($g['booting'])
366
		echo "Starting syslog...";
367
	else
368
		killbypid("{$g['varrun_path']}/syslog.pid");
369

    
370
	mwexec("/usr/bin/killall -9 syslogd");
371
	mwexec("/usr/bin/killall -9 fifolog_writer");
372
	
373
	// Define carious commands for logging
374
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
375
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
376
	$clog_create = "/usr/sbin/clog -i -s ";
377
	$clog_log = "%";
378

    
379
	// Which logging type are we using this week??
380
	if(isset($config['system']['usefifolog'])) {
381
		$log_directive = $fifolog_log;
382
		$log_create_directive = $fifolog_create;		
383
	} else { // Defaults to CLOG
384
		$log_directive = $clog_log;
385
		$log_create_directive = $clog_create;
386
	}
387
	
388
	if (isset($syslogcfg)) {
389
		$separatelogfacilities = array('ntpd','racoon','openvpn');
390
		if($config['installedpackages']['package']) {
391
			foreach($config['installedpackages']['package'] as $package) {
392
				if($package['logging']) {
393
					$pkgfacilities[] = $package['logging']['facilityname'];
394
					$separatelogfacilities = $separatelogfacilities + $pkgfacilities;
395
					$facilitylist = implode(',', $pkgfacilities);
396
					mwexec("{$log_create_directive} 10240 {$g['varlog_path']}/{$package['logging']['logfilename']}");
397
					$syslogconf .= "!{$facilitylist}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
398
				}
399
			}
400
		}
401
		$facilitylist = implode(',', array_unique($separatelogfacilities));
402
		/* write syslog.conf */		
403
		$fd = fopen("{$g['varetc_path']}/syslog.conf", "w");
404
		if (!$fd) {
405
			printf("Error: cannot open syslog.conf in system_syslogd_start().\n");
406
			return 1;
407
		}
408
		$syslogconf .= "!ntpdate,!ntpd\n";
409
		if (!isset($syslogcfg['disablelocallogging'])) 
410
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/ntpd.log\n";
411
		$syslogconf .= "!racoon\n";
412
		if (!isset($syslogcfg['disablelocallogging'])) 
413
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/ipsec.log\n";
414
		$syslogconf .= "!apinger\n";
415
		if (!isset($syslogcfg['disablelocallogging'])) 
416
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/slbd.log\n";
417
		if (isset($syslogcfg['vpn'])) 
418
			$syslogconf .= "*.*					 @{$syslogcfg['remoteserver']}\n";
419
		$syslogconf .= "!openvpn\n";
420
		if (!isset($syslogcfg['disablelocallogging'])) 
421
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/openvpn.log\n";
422
		if (isset($syslogcfg['vpn'])) 
423
			$syslogconf .= "*.*					 @{$syslogcfg['remoteserver']}\n";
424
		$syslogconf .= "!-{$facilitylist}\n";
425
		if (!isset($syslogcfg['disablelocallogging'])) 
426
			$syslogconf .= <<<EOD
427
local0.*										 {$log_directive}{$g['varlog_path']}/filter.log
428
local3.*										 {$log_directive}{$g['varlog_path']}/vpn.log
429
local4.*										 {$log_directive}{$g['varlog_path']}/portalauth.log
430
local7.*										 {$log_directive}{$g['varlog_path']}/dhcpd.log
431
*.notice;kern.debug;lpr.info;mail.crit; 		 {$log_directive}{$g['varlog_path']}/system.log
432
news.err;local0.none;local3.none;local4.none; 	 {$log_directive}{$g['varlog_path']}/system.log
433
local7.none										 {$log_directive}{$g['varlog_path']}/system.log
434
security.*										 {$log_directive}{$g['varlog_path']}/system.log
435
auth.info;authpriv.info;daemon.info				 {$log_directive}{$g['varlog_path']}/system.log
436
local1.*										 {$log_directive}{$g['varlog_path']}/relayd.log
437
auth.info;authpriv.info 						 |exec /usr/local/sbin/sshlockout_pf
438
*.emerg											 *
439

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

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

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

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

    
473
	return $retval;
474
}
475

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

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

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

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

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

    
499
	return $res;
500
}
501

    
502

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

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

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

    
512
	sleep(1);
513

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

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

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

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

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

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

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

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

    
551
	return $res;
552
}
553

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

    
566
	global $config, $g;
567

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

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

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

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

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

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

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

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

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

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

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

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

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

    
675
EOD;
676
	}
677

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

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

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

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

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

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

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

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

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

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

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

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

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

    
801

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

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

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

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

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

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

    
823
{$server_upload_dirs}
824

    
825
{$server_max_request_size}
826

    
827
{$fastcgi_config}
828

    
829
{$cgi_config}
830

    
831
{$captive_portal_mod_evasive}
832

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

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

    
841
EOD;
842

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

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

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

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

    
874
	return 0;
875

    
876
}
877

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

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

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

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

    
895
	conf_mount_rw();
896

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
963
}
964

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

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

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

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

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

    
986
	system_reboot_cleanup();
987

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

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

    
994
	system_reboot_cleanup();
995

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

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

    
1002
	system_reboot_cleanup();
1003

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

    
1007
function system_reboot_cleanup() {
1008
	mwexec("/usr/local/bin/beep.sh stop");
1009
	captiveportal_radius_stop_all();
1010
	require_once("voucher.inc");
1011
	voucher_save_db_to_config();
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
	return;
1156
	$install_watchdog = false;
1157
	$supported_watchdogs = array("Geode");
1158
	$file = file_get_contents("/var/log/dmesg.boot");
1159
	foreach($supported_watchdogs as $sd) {
1160
		if(stristr($file, "Geode")) {
1161
			$install_watchdog = true;
1162
		}
1163
	}
1164
	if($install_watchdog == true) {
1165
		if(is_process_running("watchdogd"))
1166
			mwexec("/usr/bin/killall watchdogd", true);
1167
		exec("/usr/sbin/watchdogd");
1168
	}
1169
}
1170

    
1171
?>
(34-34/43)