Project

General

Profile

Download (35.8 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 opcode_cache_configuration() {
36
		global $g;
37
        if($g['platform'] == "cdrom")
38
        	return;
39

    
40
        /* get system memory amount */
41
        $memory = get_memory();
42
        $avail = $memory[0];
43

    
44
		/* disable apc for platforms less than 90 megs of ram */
45
        if($memory > 90) {
46
        	$opcode_cacher = "extension=apc.so\n";
47
        	$opcode_cacher .= "apc.enabled=\"1\"\n";
48
			$opcode_cacher .= "apc.enable_cli=\"1\"\n";
49
			$opcode_cacher .= "apc.shm_size=\"8\"\n";
50
        } else {
51
			$opcode_cacher = "";
52
        }
53

    
54
		/* create a php.ini variable */
55
		$php_conf = file_get_contents("/usr/local/lib/php.ini");
56

    
57
$php_ini = <<<EOFF
58
output_buffering = "0"
59
implicit_flush = true
60
magic_quotes_gpc = Off
61
max_execution_time = 99999999
62
max_input_time = 99999999
63
memory_limit = 32M
64
register_argc_argv = On
65
file_uploads = On
66
extension_dir=/usr/local/lib/php/extensions/no-debug-non-zts-20020429/
67
upload_tmp_dir = /tmp
68
upload_max_filesize = 100M
69
post_max_size = 100M
70
html_errors = Off
71
include_path = ".:/etc/inc:/usr/local/www:/usr/local/captiveportal:/usr/local/pkg"
72
extension=radius.so
73
{$opcode_cacher}
74

    
75
EOFF;
76

    
77
        config_lock();
78
		conf_mount_rw();
79

    
80
		/* open up php.ini and write back out contents */
81
		$fd = fopen("/usr/local/lib/php.ini","w");
82
		fwrite($fd, $php_ini);
83
		fclose($fd);
84

    
85
		mwexec("sync");
86
		conf_mount_ro();
87
		exec("sync");
88
		config_unlock();
89
}
90

    
91
function system_resolvconf_generate($dynupdate = false) {
92
	global $config, $g;
93
	if(isset($config['system']['developerspew'])) {
94
		$mt = microtime();
95
		echo "system_resolvconf_generate() being called $mt\n";
96
	}
97

    
98
        $syscfg = $config['system'];
99

    
100
        $fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
101
        if (!$fd) {
102
                printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
103
                return 1;
104
        }
105

    
106
        $resolvconf = "domain {$syscfg['domain']}\n";
107

    
108
        $havedns = false;
109

    
110
        if (isset($syscfg['dnsallowoverride'])) {
111
                /* get dynamically assigned DNS servers (if any) */
112
		$ns = array_unique(get_nameservers());
113
		foreach($ns as $nameserver) {
114
			if($nameserver) {
115
				$resolvconf .= "nameserver $nameserver\n";
116
				$havedns = true;
117
			}
118
		}
119
        }
120
        if (!$havedns && is_array($syscfg['dnsserver'])) {
121
                foreach ($syscfg['dnsserver'] as $ns) {
122
                        if ($ns) {
123
                                $resolvconf .= "nameserver $ns\n";
124
				$havedns = true;
125
			}
126
                }
127
        }
128

    
129
        fwrite($fd, $resolvconf);
130
        fclose($fd);
131

    
132
        if (!$g['booting']) {
133
                /* restart dhcpd (nameservers may have changed) */
134
                if (!$dynupdate)
135
                        services_dhcpd_configure();
136
        }
137

    
138
        return 0;
139
}
140

    
141
function get_nameservers() {
142
	global $config, $g;
143
	$master_list = array();
144
	$dns_lists = split("\n", `ls /var/etc/nameserver_* 2>/dev/null`);
145
	foreach($dns_lists as $dns) {
146
		$items = split("\n", file_get_contents($dns));
147
		foreach($items as $item)
148
			if($item <> "")
149
				$master_list[] = $item;
150
	}
151
	if(!file_exists("/var/etc/nameservers.conf"))
152
		return $master_list;
153
	$dns = `cat /var/etc/nameservers.conf`;
154
	$dns_s = split("\n", $dns);
155
	if(is_array($dns_s))
156
		foreach($dns_s as $dns)
157
			$master_list[] = $dns;
158
	return $master_list;
159
}
160

    
161
function system_hosts_generate() {
162
	global $config, $g;
163
	if(isset($config['system']['developerspew'])) {
164
		$mt = microtime();
165
		echo "system_hosts_generate() being called $mt\n";
166
	}
167

    
168
	$syscfg = $config['system'];
169
	$lancfg = $config['interfaces']['lan'];
170
	$dnsmasqcfg = $config['dnsmasq'];
171

    
172
	if (!is_array($dnsmasqcfg['hosts'])) {
173
		$dnsmasqcfg['hosts'] = array();
174
	}
175
	$hostscfg = $dnsmasqcfg['hosts'];
176

    
177
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
178
	if (!$fd) {
179
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
180
		return 1;
181
	}
182

    
183
	$hosts = <<<EOD
184
127.0.0.1	localhost localhost.{$syscfg['domain']}
185
{$lancfg['ipaddr']}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}
186

    
187
EOD;
188

    
189
	foreach ($hostscfg as $host) {
190
		if ($host['host'])
191
			$hosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
192
		else
193
			$hosts .= "{$host['ip']}	{$host['domain']}\n";
194
	}
195
	if (isset($dnsmasqcfg['regdhcpstatic'])) {
196
		foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf)
197
			if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
198
					foreach ($dhcpifconf['staticmap'] as $host)
199
						if ($host['ipaddr'] && $host['hostname'])
200
							$hosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
201
	}
202
	fwrite($fd, $hosts);
203
	fclose($fd);
204

    
205
	return 0;
206
}
207

    
208
function system_hostname_configure() {
209
	global $config, $g;
210
	if(isset($config['system']['developerspew'])) {
211
		$mt = microtime();
212
		echo "system_hostname_configure() being called $mt\n";
213
	}
214

    
215
	$syscfg = $config['system'];
216

    
217
	/* set hostname */
218
	return mwexec("/bin/hostname " .
219
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
220
}
221

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

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

    
233
	/* clear out old routes, if necessary */
234
	exec("/usr/bin/netstat -rn", $route_arr, $retval);
235
	$route_str = implode("\n", $route_arr);
236

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

    
252
	if (is_array($config['staticroutes']['route'])) {
253

    
254
		$fd = fopen("{$g['vardb_path']}/routes.db", "w");
255
		if (!$fd) {
256
			printf("Error: cannot open routes DB file in system_routing_configure().\n");
257
			return 1;
258
		}
259

    
260
		foreach ($config['staticroutes']['route'] as $rtent) {
261
			if(isset($rtent['interfacegateway'])) {
262
				mwexec("/sbin/route add " . escapeshellarg($rtent['network']) .
263
					" -iface " . escapeshellarg(convert_friendly_interface_to_real_interface_name($rtent['interface'])));
264
			} else {
265
				mwexec("/sbin/route add " . escapeshellarg($rtent['network']) .
266
					" " . escapeshellarg($rtent['gateway']));
267
			}
268
			/* record route so it can be easily removed later (if necessary) */
269
			fwrite($fd, $rtent['network'] . "\n");
270
		}
271

    
272
		fclose($fd);
273
	}
274

    
275
	/* Make sure default gateway is present */
276
	$result = `/usr/bin/netstat -rn | grep default`;
277
	if(!$result)
278
		if($config['interfaces']['wan']['gateway'])
279
			mwexec("/sbin/route add default " . escapeshellarg($config['interfaces']['wan']['gateway']));
280

    
281
	return 0;
282
}
283

    
284
function system_routing_enable() {
285
	global $config, $g;
286
	if(isset($config['system']['developerspew'])) {
287
		$mt = microtime();
288
		echo "system_routing_enable() being called $mt\n";
289
	}
290

    
291
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
292
}
293

    
294
function system_syslogd_start() {
295
	global $config, $g;
296
	if(isset($config['system']['developerspew'])) {
297
		$mt = microtime();
298
		echo "system_syslogd_start() being called $mt\n";
299
	}
300

    
301
	$syslogcfg = $config['syslog'];
302

    
303
	if ($g['booting'])
304
		echo "Starting syslog...";
305
	else
306
		killbypid("{$g['varrun_path']}/syslog.pid");
307

    
308
	if (isset($syslogcfg)) {
309
		$separatelogfacilities = array('ntpd','racoon','openvpn');
310
		if($config['installedpackages']['package']) {
311
                        foreach($config['installedpackages']['package'] as $package) {
312
                                if($package['logging']) {
313
					$pkgfacilities[] = $package['logging']['facilityname'];
314
					$separatelogfacilities = $separatelogfacilities + $pkgfacilities;
315
					$facilitylist = implode(',', $pkgfacilities);
316
					mwexec("clog -i -s 10000 {$g['varlog_path']}/{$package['logging']['logfilename']}");
317
                                	$syslogconf .= "!{$facilitylist}\n*.*\t\t\t\t\t\t%{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
318
				}
319
                        }
320
                }
321
		$facilitylist = implode(',', array_unique($separatelogfacilities));
322
		/* write syslog.conf */
323
		$fd = fopen("{$g['varetc_path']}/syslog.conf", "w");
324
		if (!$fd) {
325
			printf("Error: cannot open syslog.conf in system_syslogd_start().\n");
326
			return 1;
327
		}
328
		$syslogconf .= "!ntpdate,!ntpd\n";
329
		if (!isset($syslogcfg['disablelocallogging'])) {
330
			$syslogconf .= <<<EOD
331
*.*						%{$g['varlog_path']}/ntpd.log
332

    
333
EOD;
334
		}
335
		$syslogconf .= "!racoon\n";
336
		if (!isset($syslogcfg['disablelocallogging'])) {
337
			$syslogconf .= <<<EOD
338
*.*						%{$g['varlog_path']}/ipsec.log
339

    
340
EOD;
341
		}
342
		if (isset($syslogcfg['vpn'])) {
343
			$syslogconf .= <<<EOD
344
*.*						@{$syslogcfg['remoteserver']}
345

    
346
EOD;
347
		}
348
		$syslogconf .= "!openvpn\n";
349
		if (!isset($syslogcfg['disablelocallogging'])) {
350
			$syslogconf .= <<<EOD
351
*.*						%{$g['varlog_path']}/openvpn.log
352

    
353
EOD;
354
		}
355
		if (isset($syslogcfg['vpn'])) {
356
			$syslogconf .= <<<EOD
357
*.*						@{$syslogcfg['remoteserver']}
358

    
359
EOD;
360
		}
361
		$syslogconf .= "!-{$facilitylist}\n";
362
		if (!isset($syslogcfg['disablelocallogging'])) {
363
		$syslogconf .= <<<EOD
364
local0.*					%{$g['varlog_path']}/filter.log
365
local3.*					%{$g['varlog_path']}/vpn.log
366
local4.*					%{$g['varlog_path']}/portalauth.log
367
local7.*					%{$g['varlog_path']}/dhcpd.log
368
*.notice;kern.debug;lpr.info;mail.crit; 	%{$g['varlog_path']}/system.log
369
news.err;local0.none;local3.none;local4.none; 	%{$g['varlog_path']}/system.log
370
local7.none					%{$g['varlog_path']}/system.log
371
security.*					%{$g['varlog_path']}/system.log
372
auth.info;authpriv.info;daemon.info		%{$g['varlog_path']}/system.log
373
local1.*					%{$g['varlog_path']}/slbd.log
374
auth.info;authpriv.info 			|exec /usr/local/sbin/sshlockout_pf
375
*.emerg						*
376

    
377
EOD;
378
		}
379

    
380
		if (isset($syslogcfg['filter'])) {
381
			$syslogconf .= <<<EOD
382
local0.*					@{$syslogcfg['remoteserver']}
383

    
384
EOD;
385
		}
386

    
387
		if (isset($syslogcfg['vpn'])) {
388
			$syslogconf .= <<<EOD
389
local3.*					@{$syslogcfg['remoteserver']}
390

    
391
EOD;
392
		}
393

    
394

    
395
		if (isset($syslogcfg['portalauth'])) {
396
			$syslogconf .= <<<EOD
397
local4.*					@{$syslogcfg['remoteserver']}
398

    
399
EOD;
400
		}
401

    
402

    
403
		if (isset($syslogcfg['dhcp'])) {
404
			$syslogconf .= <<<EOD
405
local7.*					@{$syslogcfg['remoteserver']}
406

    
407
EOD;
408
		}
409

    
410
		if (isset($syslogcfg['system'])) {
411
			$syslogconf .= <<<EOD
412
*.notice;kern.debug;lpr.info;mail.crit;		@{$syslogcfg['remoteserver']}
413
news.err;local0.none;local3.none;local7.none	@{$syslogcfg['remoteserver']}
414
security.*					@{$syslogcfg['remoteserver']}
415
auth.info;authpriv.info;daemon.info		@{$syslogcfg['remoteserver']}
416
*.emerg						@{$syslogcfg['remoteserver']}
417

    
418
EOD;
419
		}
420
		fwrite($fd, $syslogconf);
421
		fclose($fd);
422

    
423
		// Are we logging to a least one remote server ?
424
		if(strpos($syslogconf, "@") != false)
425
			$retval = mwexec("/usr/sbin/syslogd -s -f {$g['varetc_path']}/syslog.conf");
426
		else
427
			$retval = mwexec("/usr/sbin/syslogd -ss -f {$g['varetc_path']}/syslog.conf");
428

    
429
	} else {
430
		$retval = mwexec("/usr/sbin/syslogd -ss");
431
	}
432

    
433
	if ($g['booting'])
434
		echo "done.\n";
435

    
436
	return $retval;
437
}
438

    
439
function system_pccard_start() {
440
	global $config, $g;
441
	if(isset($config['system']['developerspew'])) {
442
		$mt = microtime();
443
		echo "system_pccard_start() being called $mt\n";
444
	}
445

    
446
	if ($g['booting'])
447
		echo "Initializing PCMCIA...";
448

    
449
	/* kill any running pccardd */
450
	killbypid("{$g['varrun_path']}/pccardd.pid");
451

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

    
455
	if ($g['booting']) {
456
		if ($res == 0)
457
			echo "done.\n";
458
		else
459
			echo "failed!\n";
460
	}
461

    
462
	return $res;
463
}
464

    
465

    
466
function system_webgui_start() {
467
	global $config, $g;
468

    
469
	if ($g['booting'])
470
		echo "Starting webConfigurator...";
471

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

    
475
	sleep(1);
476

    
477
	/* generate password file */
478
	system_password_configure();
479

    
480
	chdir($g['www_path']);
481

    
482
	/* non-standard port? */
483
	if ($config['system']['webgui']['port'])
484
		$portarg = "{$config['system']['webgui']['port']}";
485
	else
486
		$portarg = "";
487

    
488
	if ($config['system']['webgui']['protocol'] == "https") {
489

    
490
	if(!$config['system']['webgui']['port'])
491
		$portarg = "443";
492

    
493
		if ($config['system']['webgui']['certificate'] && $config['system']['webgui']['private-key']) {
494
			$cert = base64_decode($config['system']['webgui']['certificate']);
495
			$key = base64_decode($config['system']['webgui']['private-key']);
496
		} else {
497
			/* default certificate/key */
498
			$cert = <<<EOD
499
-----BEGIN CERTIFICATE-----
500
MIIDEzCCAnygAwIBAgIJAJM91W+s6qptMA0GCSqGSIb3DQEBBAUAMGUxCzAJBgNV
501
BAYTAlVTMQswCQYDVQQIEwJLWTETMBEGA1UEBxMKTG91aXN2aWxsZTEQMA4GA1UE
502
ChMHcGZTZW5zZTEQMA4GA1UECxMHcGZTZW5zZTEQMA4GA1UEAxMHcGZTZW5zZTAe
503
Fw0wNjAzMTAyMzQ1MTlaFw0xNjAzMDcyMzQ1MTlaMGUxCzAJBgNVBAYTAlVTMQsw
504
CQYDVQQIEwJLWTETMBEGA1UEBxMKTG91aXN2aWxsZTEQMA4GA1UEChMHcGZTZW5z
505
ZTEQMA4GA1UECxMHcGZTZW5zZTEQMA4GA1UEAxMHcGZTZW5zZTCBnzANBgkqhkiG
506
9w0BAQEFAAOBjQAwgYkCgYEA3lPNTFH6qge/ygaqe/BS4oH59O6KvAesWcRzSu5N
507
21lyVE5tBbL0zqOSXmlLyReMSbtAMZqt1P8EPYFoOcaEQHIWm2VQF80Z18+8Gh4O
508
UQGjHq88OeaLqyk3OLpSKzSpXuCFrSN7q9Kez8zp5dQEu7sIW30da3pAbdqYOimA
509
1VsCAwEAAaOByjCBxzAdBgNVHQ4EFgQUAnx+ggC4SzJ0CK+rhPhJ2ZpyunEwgZcG
510
A1UdIwSBjzCBjIAUAnx+ggC4SzJ0CK+rhPhJ2ZpyunGhaaRnMGUxCzAJBgNVBAYT
511
AlVTMQswCQYDVQQIEwJLWTETMBEGA1UEBxMKTG91aXN2aWxsZTEQMA4GA1UEChMH
512
cGZTZW5zZTEQMA4GA1UECxMHcGZTZW5zZTEQMA4GA1UEAxMHcGZTZW5zZYIJAJM9
513
1W+s6qptMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEEBQADgYEAAviQpdoeabL8
514
1HSZiD7Yjx82pdLpyQOdXvAu3jEAYz53ckx0zSMrzsQ5r7Vae6AE7Xd7Pj+1Yihs
515
AJZzOQujnmsuim7qu6YSxzP34xonKwd1C9tZUlyNRNnEmtXOEDupn05bih1ugtLG
516
kqfPIgDbDLXuPtEAA6QDUypaunI6+1E=
517
-----END CERTIFICATE-----
518

    
519
EOD;
520

    
521
			$key = <<<EOD
522
-----BEGIN RSA PRIVATE KEY-----
523
MIICXgIBAAKBgQDeU81MUfqqB7/KBqp78FLigfn07oq8B6xZxHNK7k3bWXJUTm0F
524
svTOo5JeaUvJF4xJu0Axmq3U/wQ9gWg5xoRAchabZVAXzRnXz7waHg5RAaMerzw5
525
5ourKTc4ulIrNKle4IWtI3ur0p7PzOnl1AS7uwhbfR1rekBt2pg6KYDVWwIDAQAB
526
AoGAP7E0VFP8Aq/7os3sE1uS8y8XQ7L+7cUo/AKKoQHKLjfeyAY7t3FALt6vdPqn
527
anGjkA/j4RIWELoKJfCnwj17703NDCPwB7klcmZvmTx5Om1ZrRyZdQ6RJs0pOOO1
528
r2wOnZNaNWStXE9Afpw3dj20Gh0V/Ioo5HXn3sHfxZm8dnkCQQDwv8OaUdp2Hl8t
529
FDfXB1CMvUG1hEAvbQvZK1ODkE7na2/ChKjVPddEI3DvfzG+nLrNuTrAyVWgRLte
530
r8qX5PQHAkEA7GlKx0S18LdiKo6wy2QeGu6HYkPncaHNFOWX8cTpvGGtQoWYSh0J
531
tjCt1/mz4/XkvZWuZyTNx2FdkVlNF5nHDQJBAIRWVTZqEjVlwpmsCHnp6mxCyHD4
532
DrRDNAUfnNuwIr9xPlDlzUzSnpc1CCqOd5C45LKbRGGfCrN7tKd66FmQoFcCQQCy
533
Kvw3R1pTCvHJnvYwoshphaC0dvaDVeyINiwYAk4hMf/wpVxLZqz+CJvLrB1dzOBR
534
3O+uPjdzbrakpweJpNQ1AkEA3ZtlgEj9eWsLAJP8aKlwB8VqD+EtG9OJSUMnCDiQ
535
WFFNj/t3Ze3IVuAyL/yMpiv3JNEnZhIxCta42eDFpIZAKw==
536
-----END RSA PRIVATE KEY-----
537

    
538
EOD;
539
		}
540
	} else {
541
		$cert = "";
542
		$key = "";
543
	}
544

    
545
	/* generate lighttpd configuration */
546
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
547
		$cert, $key, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/");
548

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

    
552
	if ($g['booting']) {
553
		if ($res == 0)
554
			echo "done.\n";
555
		else
556
			echo "failed!\n";
557
	}
558

    
559
	return $res;
560
}
561

    
562
function system_webgui_start_old() {
563
	global $config, $g;
564
	if(isset($config['system']['developerspew'])) {
565
		$mt = microtime();
566
		echo "system_webgui_start() being called $mt\n";
567
	}
568

    
569
        if ($g['booting'])
570
                echo "Starting webConfigurator...";
571

    
572
        /* kill any running mini_httpd */
573
        killbypid("{$g['varrun_path']}/mini_httpd.pid");
574

    
575
        /* generate password file */
576
        system_password_configure();
577

    
578
        chdir($g['www_path']);
579

    
580
        /* non-standard port? */
581
        if ($config['system']['webgui']['port'])
582
                $portarg = "-p {$config['system']['webgui']['port']}";
583
        else
584
                $portarg = "";
585

    
586
        if ($config['system']['webgui']['protocol'] == "https") {
587

    
588
                if ($config['system']['webgui']['certificate'] && $config['system']['webgui']['private-key']) {
589
                        $cert = base64_decode($config['system']['webgui']['certificate']);
590
                        $key  = base64_decode($config['system']['webgui']['private-key']);
591
                } else {
592
                        /* default certificate/key */
593
                        $cert = <<<EOD
594
-----BEGIN CERTIFICATE-----
595
MIIBlDCB/gIBADANBgkqhkiG9w0BAQQFADATMREwDwYDVQQKEwhtMG4wd2FsbDAe
596
Fw0wNTA1MTAxMjI0NDRaFw0wNzA1MTAxMjI0NDRaMBMxETAPBgNVBAoTCG0wbjB3
597
YWxsMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDAShszhFz+o8lsMWTGgTxs
598
TMPR+v4+qL5jXDyY97MLTGFK7aqQOtpIQc+TcTc4jklgOVlHoR7oBXrsi8YrbCd+
599
83LPQmQoSPC0VqhfU3uYf3NzxiK8r97aPCsmWgwT2pQ6TcESTm6sF7nLprOf/zFP
600
C4jE2fvjkbzyVolPywBuewIDAQABMA0GCSqGSIb3DQEBBAUAA4GBAFR962c4R5tV
601
cTn0OQcszYoW6WC+ini9tQQh5ku5jYDAiC+00atawJEVLnL3lwAcpSKTIWlTkD20
602
tl3lz5br1qFgYky+Rd0kwS2nk9jRbkxSXxd6KJVnNRCKre28aw3ENzZfCSurPQsX
603
UPp5er+NtwMT1g7s/JDmKTC4w1rGr5/c
604
-----END CERTIFICATE-----
605

    
606
EOD;
607

    
608
                        $key = <<<EOD
609
-----BEGIN RSA PRIVATE KEY-----
610
MIICXQIBAAKBgQDAShszhFz+o8lsMWTGgTxsTMPR+v4+qL5jXDyY97MLTGFK7aqQ
611
OtpIQc+TcTc4jklgOVlHoR7oBXrsi8YrbCd+83LPQmQoSPC0VqhfU3uYf3NzxiK8
612
r97aPCsmWgwT2pQ6TcESTm6sF7nLprOf/zFPC4jE2fvjkbzyVolPywBuewIDAQAB
613
AoGAbJJrQW9fQrggJuLMz/hwsYW2m31oyOBmf5u463YQtjRuSuxe/gj87weZuNqY
614
H2rXq2k2K+ehl8hgW+egASyUL3L7kCkEAsVREujKTEyhSqqIRDPWTxo9S/YA9Gvn
615
2ZnJvkrcKjqCO9aHX3rvJOK/ErYI6akctgI3KmgkYw5XNmECQQDuZU97RTWH9rmP
616
aQr57ysNXxgFsyhetOOqeYkPtIVwpOiNbfwE1zi5RGdtO4Ku3fG1lV4J2UoWJ9yD
617
awdoyYIHAkEAzn0xJ90IjPsHk+8SODEj5JGdHSZPNu1tgtrbjEi9sfGWg4K7XTxr
618
QW90pWb1bKKU1uh5FzW6OhnFfuQXt1kC7QJAPSthqY+onKqCEnoxhtAHi/bKgyvl
619
P+fKQwPMV2tKkgy+XwvJjrRqqZ8TqsOKVLQ+QQmCh6RpjiXMPyxHSmvqIQJBAKLR
620
HF1ucDuaBROkwx0DwmWMW/KMLpIFDQDNSaiIAuu4rxHrl4mhBoGGPNffI04RtILw
621
s+qVNs5xW8T+XaT4ztECQQDFHPnZeoPWE5z+AX/UUQIUWaDExz3XRzmIxRbOrlFi
622
CsF1s0TdJLi/wzNQRAL37A8vqCeVFR/ng3Xpg96Yg+8Z
623
-----END RSA PRIVATE KEY-----
624

    
625
EOD;
626
                }
627

    
628
				$cert = str_replace("\r", "", $cert);
629
				$key = str_replace("\r", "", $key);
630

    
631
                $fd = fopen("{$g['varetc_path']}/cert.pem", "w");
632
                if (!$fd) {
633
                        printf("Error: cannot open cert.pem in system_webgui_start().\n");
634
                        return 1;
635
                }
636
                chmod("{$g['varetc_path']}/cert.pem", 0600);
637
                fwrite($fd, $cert);
638
                fwrite($fd, "\n");
639
                fwrite($fd, $key);
640
                fclose($fd);
641

    
642
                $res = mwexec("/usr/local/sbin/mini_httpd -S -E {$g['varetc_path']}/cert.pem" .
643
                        " -c \"**.php|**.cgi\" -u root -maxproc 16 $portarg" .
644
                        " -i {$g['varrun_path']}/mini_httpd.pid");
645
        } else {
646
                $res = mwexec("/usr/local/sbin/mini_httpd -c \"**.php|**.cgi\" -u root" .
647
                        " -maxproc 16 $portarg -i {$g['varrun_path']}/mini_httpd.pid");
648
        }
649

    
650
        if ($g['booting']) {
651
                if ($res == 0)
652
                        echo "done\n";
653
                else
654
                        echo "failed\n";
655
        }
656

    
657
        return $res;
658
}
659

    
660
function system_generate_lighty_config($filename,
661
	$cert,
662
	$key,
663
	$pid_file,
664
	$port = 80,
665
	$document_root = "/usr/local/www/",
666
	$cert_location = "cert.pem",
667
	$max_procs = 2,
668
	$max_requests = "1",
669
	$fast_cgi_enable = true,
670
	$captive_portal = false) {
671

    
672
	global $config, $g;
673

    
674
	if(isset($config['system']['developerspew'])) {
675
		$mt = microtime();
676
		echo "system_generate_lighty_config() being called $mt\n";
677
	}
678

    
679
	if($captive_portal == true)  {
680
		$captiveportal = ",\"mod_rewrite\"";
681
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?redirurl=$1\" )\n";
682
		$captive_portal_module = "\"mod_accesslog\", ";
683
		$maxprocperip = $config['captiveportal']['maxprocperip'];
684
		if(!$maxprocperip and $maxprocperip > 0)
685
			$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
686
		else
687
			$captive_portal_mod_evasive = "";
688
		$server_upload_dirs = "server.upload-dirs = ( \"/tmp/captiveportal/\" )\n";
689
		exec("mkdir -p /tmp/captiveportal");
690
		exec("chmod a-w /tmp/captiveportal");
691
		$server_max_request_size = "server.max-request-size    = 384";
692
	} else {
693
		$captive_portal_module = "";
694
		$captive_portal_mod_evasive = "";
695
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"/tmp/\", \"/var/\" )\n";
696
		$server_max_request_size = "server.max-request-size    = 2097152";
697
	}
698

    
699
	if($port <> "")
700
		$lighty_port = $port;
701
	else
702
		$lighty_port = "80";
703

    
704
	$memory = get_memory();
705
	$avail = $memory[0];
706

    
707
	if($avail > 0 and $avail < 98) {
708
		$max_procs = 1;
709
		$max_requests = 1;
710
	}
711

    
712
	if($avail > 97 and $avail < 128) {
713
		$max_procs = 1;
714
		$max_requests = 3;
715
	}
716

    
717
	if($avail > 127 and $avail < 256) {
718
		$max_procs = 1;
719
		$max_requests = 5;
720
	}
721

    
722
	if($avail > 255 and $avail < 384) {
723
		$max_procs = 3;
724
		$max_requests = 10;
725
	}
726

    
727
	if($avail > 383 and $avail < 512) {
728
		$max_procs = 4;
729
		$max_requests = 16;
730
	}
731

    
732
		if($captive_portal == true)  {	
733
			$bin_environment =  <<<EOC
734
	        "bin-environment" => (
735
	           "PHP_FCGI_CHILDREN" => "16",
736
	           "PHP_FCGI_MAX_REQUESTS" => "{$max_requests}"
737
	        ), 
738
EOC;
739

    
740
		} else {
741
			$bin_environment = "";
742
		}
743
		
744
	if($fast_cgi_enable == true) {
745
		$module = "\"mod_fastcgi\", \"mod_cgi\"";
746
		$cgi_config = "";
747
		$fastcgi_config = <<<EOD
748
#### fastcgi module
749
## read fastcgi.txt for more info
750
fastcgi.server = ( ".php" =>
751
	( "localhost" =>
752
		(
753
			"socket" => "/tmp/php-fastcgi.socket",
754
			"min-procs" => 1,
755
			"max-procs" => {$max_procs},
756
			{$bin_environment}			
757
			"bin-path" => "/usr/local/bin/php"
758
		)
759
	)
760
)
761

    
762
#### CGI module
763
cgi.assign                 = ( ".cgi" => "" )
764

    
765
EOD;
766
	} else {
767
		$fastcgi_config = "";
768
		$module = "\"mod_cgi\"";
769
		$cgi_config = <<<EOD
770
#### CGI module
771
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
772
                               ".cgi" => "" )
773

    
774
EOD;
775
	}
776

    
777
	$lighty_config .= <<<EOD
778
#
779
# lighttpd configuration file
780
#
781
# use a it as base for lighttpd 1.0.0 and above
782
#
783
############ Options you really have to take care of ####################
784

    
785
## FreeBSD!
786
server.event-handler		= "freebsd-kqueue"
787
server.network-backend		= "writev"  ## Fixes 7.x upload issues
788

    
789
{$network_handler}
790

    
791
## modules to load
792
server.modules              =   (
793
				  {$captive_portal_module}
794
				  "mod_access", "mod_accesslog",
795
                                  {$module}{$captiveportal}
796
				)
797

    
798
## Unused modules
799
#                               "mod_setenv",
800
#                               "mod_compress"
801
#				"mod_redirect",
802
#                               "mod_rewrite",
803
#                               "mod_ssi",
804
#                               "mod_usertrack",
805
#                               "mod_expire",
806
#                               "mod_secdownload",
807
#                               "mod_rrdtool",
808
#                               "mod_auth",
809
#                               "mod_status",
810
#                               "mod_alias",
811
#                               "mod_proxy",
812
#                               "mod_simple_vhost",
813
#                               "mod_evhost",
814
#                               "mod_userdir",
815
#                               "mod_cgi",
816
#                                "mod_accesslog"
817

    
818
## a static document-root, for virtual-hosting take look at the
819
## server.virtual-* options
820
server.document-root        = "{$document_root}"
821
{$captive_portal_rewrite}
822

    
823
## where to send error-messages to
824
server.errorlog             = "/var/log/lighttpd.error.log"
825

    
826
# files to check for if .../ is requested
827
server.indexfiles           = ( "index.php", "index.html",
828
                                "index.htm", "default.htm" )
829

    
830
# mimetype mapping
831
mimetype.assign             = (
832
  ".pdf"          =>      "application/pdf",
833
  ".sig"          =>      "application/pgp-signature",
834
  ".spl"          =>      "application/futuresplash",
835
  ".class"        =>      "application/octet-stream",
836
  ".ps"           =>      "application/postscript",
837
  ".torrent"      =>      "application/x-bittorrent",
838
  ".dvi"          =>      "application/x-dvi",
839
  ".gz"           =>      "application/x-gzip",
840
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
841
  ".swf"          =>      "application/x-shockwave-flash",
842
  ".tar.gz"       =>      "application/x-tgz",
843
  ".tgz"          =>      "application/x-tgz",
844
  ".tar"          =>      "application/x-tar",
845
  ".zip"          =>      "application/zip",
846
  ".mp3"          =>      "audio/mpeg",
847
  ".m3u"          =>      "audio/x-mpegurl",
848
  ".wma"          =>      "audio/x-ms-wma",
849
  ".wax"          =>      "audio/x-ms-wax",
850
  ".ogg"          =>      "audio/x-wav",
851
  ".wav"          =>      "audio/x-wav",
852
  ".gif"          =>      "image/gif",
853
  ".jpg"          =>      "image/jpeg",
854
  ".jpeg"         =>      "image/jpeg",
855
  ".png"          =>      "image/png",
856
  ".xbm"          =>      "image/x-xbitmap",
857
  ".xpm"          =>      "image/x-xpixmap",
858
  ".xwd"          =>      "image/x-xwindowdump",
859
  ".css"          =>      "text/css",
860
  ".html"         =>      "text/html",
861
  ".htm"          =>      "text/html",
862
  ".js"           =>      "text/javascript",
863
  ".asc"          =>      "text/plain",
864
  ".c"            =>      "text/plain",
865
  ".conf"         =>      "text/plain",
866
  ".text"         =>      "text/plain",
867
  ".txt"          =>      "text/plain",
868
  ".dtd"          =>      "text/xml",
869
  ".xml"          =>      "text/xml",
870
  ".mpeg"         =>      "video/mpeg",
871
  ".mpg"          =>      "video/mpeg",
872
  ".mov"          =>      "video/quicktime",
873
  ".qt"           =>      "video/quicktime",
874
  ".avi"          =>      "video/x-msvideo",
875
  ".asf"          =>      "video/x-ms-asf",
876
  ".asx"          =>      "video/x-ms-asf",
877
  ".wmv"          =>      "video/x-ms-wmv",
878
  ".bz2"          =>      "application/x-bzip",
879
  ".tbz"          =>      "application/x-bzip-compressed-tar",
880
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
881
 )
882

    
883
# Use the "Content-Type" extended attribute to obtain mime type if possible
884
#mimetypes.use-xattr        = "enable"
885

    
886
#### accesslog module
887
#accesslog.filename          = "/dev/null"
888

    
889
## deny access the file-extensions
890
#
891
# ~    is for backupfiles from vi, emacs, joe, ...
892
# .inc is often used for code includes which should in general not be part
893
#      of the document-root
894
url.access-deny             = ( "~", ".inc" )
895

    
896

    
897
######### Options that are good to be but not neccesary to be changed #######
898

    
899
## bind to port (default: 80)
900
server.port                = {$lighty_port}
901

    
902
## error-handler for status 404
903
#server.error-handler-404   = "/error-handler.html"
904
#server.error-handler-404   = "/error-handler.php"
905

    
906
## to help the rc.scripts
907
server.pid-file            = "/var/run/{$pid_file}"
908

    
909
## virtual directory listings
910
server.dir-listing         = "disable"
911

    
912
## enable debugging
913
debug.log-request-header   = "disable"
914
debug.log-response-header  = "disable"
915
debug.log-request-handling = "disable"
916
debug.log-file-not-found   = "disable"
917

    
918
#### compress module
919
#compress.cache-dir         = "/tmp/lighttpd/cache/compress/"
920
#compress.filetype          = ("text/plain", "text/html")
921

    
922
#server.network-backend = "writev"
923

    
924
{$server_upload_dirs}
925

    
926
{$server_max_request_size}
927

    
928
{$fastcgi_config}
929

    
930
{$cgi_config}
931

    
932
{$captive_portal_mod_evasive}
933

    
934
EOD;
935

    
936
	$cert = str_replace("\r", "", $cert);
937
	$key = str_replace("\r", "", $key);
938

    
939
	$cert = str_replace("\n\n", "\n", $cert);
940
	$key = str_replace("\n\n", "\n", $key);
941

    
942
	if($cert <> "" and $key <> "") {
943
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
944
		if (!$fd) {
945
			printf("Error: cannot open cert.pem in system_webgui_start().\n");
946
			return 1;
947
		}
948
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
949
		fwrite($fd, $cert);
950
		fwrite($fd, "\n");
951
		fwrite($fd, $key);
952
		fclose($fd);
953
		$lighty_config .= "\n";
954
		$lighty_config .= "## ssl configuration\n";
955
		$lighty_config .= "ssl.engine = \"enable\"\n";
956
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
957
	}
958

    
959
	$fd = fopen("{$filename}", "w");
960
	if (!$fd) {
961
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
962
		return 1;
963
	}
964
	fwrite($fd, $lighty_config);
965
	fclose($fd);
966

    
967
	return 0;
968

    
969
}
970

    
971
function system_password_configure() {
972
	global $config, $g;
973
	if(isset($config['system']['developerspew'])) {
974
		$mt = microtime();
975
		echo "system_password_configure() being called $mt\n";
976
	}
977

    
978
	/* sync passwords */
979
	sync_webgui_passwords();
980

    
981
	/* !NOTE! conf_mount_ro is done by sync_webgui_passwords() */
982

    
983
	return 0;
984
}
985

    
986
function system_timezone_configure() {
987
	global $config, $g;
988
	if(isset($config['system']['developerspew'])) {
989
		$mt = microtime();
990
		echo "system_timezone_configure() being called $mt\n";
991
	}
992

    
993
	$syscfg = $config['system'];
994

    
995
	if ($g['booting'])
996
		echo "Setting timezone...";
997

    
998
	/* extract appropriate timezone file */
999
	$timezone = $syscfg['timezone'];
1000
	if (!$timezone)
1001
		$timezone = "Etc/UTC";
1002

    
1003
	conf_mount_rw();
1004

    
1005
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1006
		escapeshellarg($timezone) . " > /etc/localtime");
1007

    
1008
	mwexec("sync");
1009
	conf_mount_ro();
1010

    
1011
	if ($g['booting'])
1012
		echo "done.\n";
1013
}
1014

    
1015
function system_ntp_configure() {
1016
	global $config, $g;
1017

    
1018
	$syscfg = $config['system'];
1019

    
1020
	/* open configuration for wrting or bail */
1021
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1022
	if(!$fd) {
1023
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1024
		return;
1025
	}
1026

    
1027
	fwrite($fd, "# \n");
1028
	fwrite($fd, "# pfSense OpenNTPD configuration file \n");
1029
	fwrite($fd, "# \n\n");
1030

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

    
1035
    /* server config is in coregui1 */
1036
	$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
1037
	if ($xmlsettings['enable'] == 'on') {
1038
		$ifaces = explode(',', $xmlsettings['interface']);
1039
		$ifaces = array_map('convert_friendly_interface_to_real_interface_name', $ifaces);
1040
		$ifaces = array_filter($ifaces, 'does_interface_exist');
1041
		$ips = array_map('find_interface_ip', $ifaces);
1042
		foreach ($ips as $ip) {
1043
			if (is_ipaddr($ip))
1044
				fwrite($fd, "listen on $ip\n");
1045
		}
1046
	}
1047

    
1048
	fwrite($fd, "\n");
1049

    
1050
	/* slurp! */
1051
	fclose($fd);
1052

    
1053
	/* if openntpd is running, kill it */
1054
	while(is_process_running("ntpd")) {
1055
		mwexec("/usr/bin/killall ntpd", true);
1056
	}
1057

    
1058
	/* if /var/empty does not exist, create it */
1059
	if(!is_dir("/var/empty"))
1060
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1061

    
1062
	if($g['booting'])
1063
		return;
1064

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

    
1068
}
1069

    
1070
function sync_system_time() {
1071
	global $config, $g;
1072

    
1073
	$syscfg = $config['system'];
1074

    
1075
	if ($g['booting'])
1076
		echo "Syncing system time before startup...";
1077

    
1078
	/* foreach through servers and write out to ntpd.conf */
1079
	foreach (explode(' ', $syscfg['timeservers']) as $ts) {
1080
		mwexec("/usr/sbin/ntpdate -s $ts");
1081
	}
1082
	
1083
	if ($g['booting'])
1084
		echo "done.\n";
1085
	
1086
}
1087

    
1088
function system_halt() {
1089
	global $g;
1090

    
1091
	system_reboot_cleanup();
1092

    
1093
	mwexec("nohup /etc/rc.halt > /dev/null 2>&1 &");
1094
}
1095

    
1096
function system_reboot() {
1097
	global $g;
1098

    
1099
	system_reboot_cleanup();
1100

    
1101
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1102
}
1103

    
1104
function system_reboot_sync() {
1105
	global $g;
1106

    
1107
	system_reboot_cleanup();
1108

    
1109
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1110
}
1111

    
1112
function system_reboot_cleanup() {
1113
	mwexec("/usr/local/bin/beep.sh stop");
1114
	captiveportal_radius_stop_all();
1115
}
1116

    
1117
function system_do_shell_commands($early = 0) {
1118
	global $config, $g;
1119
	if(isset($config['system']['developerspew'])) {
1120
		$mt = microtime();
1121
		echo "system_do_shell_commands() being called $mt\n";
1122
	}
1123

    
1124
	if ($early)
1125
		$cmdn = "earlyshellcmd";
1126
	else
1127
		$cmdn = "shellcmd";
1128

    
1129
	if (is_array($config['system'][$cmdn])) {
1130

    
1131
		/* *cmd is an array, loop through */
1132
		foreach ($config['system'][$cmdn] as $cmd) {
1133
			exec($cmd);
1134
		}
1135

    
1136
	} elseif($config['system'][$cmdn] <> "") {
1137

    
1138
		/* execute single item */
1139
		exec($config['system'][$cmdn]);
1140

    
1141
	}
1142
}
1143

    
1144
function system_console_configure() {
1145
	global $config, $g;
1146
	if(isset($config['system']['developerspew'])) {
1147
		$mt = microtime();
1148
		echo "system_console_configure() being called $mt\n";
1149
	}
1150

    
1151
	if (isset($config['system']['disableconsolemenu'])) {
1152
		touch("{$g['varetc_path']}/disableconsole");
1153
	} else {
1154
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1155
	}
1156
}
1157

    
1158
function system_dmesg_save() {
1159
	global $g;
1160
	if(isset($config['system']['developerspew'])) {
1161
		$mt = microtime();
1162
		echo "system_dmesg_save() being called $mt\n";
1163
	}
1164

    
1165
	$dmesg = "";
1166
	exec("/sbin/dmesg", $dmesg);
1167

    
1168
	/* find last copyright line (output from previous boots may be present) */
1169
	$lastcpline = 0;
1170

    
1171
	for ($i = 0; $i < count($dmesg); $i++) {
1172
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1173
			$lastcpline = $i;
1174
	}
1175

    
1176
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1177
	if (!$fd) {
1178
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1179
		return 1;
1180
	}
1181

    
1182
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1183
		fwrite($fd, $dmesg[$i] . "\n");
1184

    
1185
	fclose($fd);
1186

    
1187
	return 0;
1188
}
1189

    
1190
function system_set_harddisk_standby() {
1191
	global $g, $config;
1192
	if(isset($config['system']['developerspew'])) {
1193
		$mt = microtime();
1194
		echo "system_set_harddisk_standby() being called $mt\n";
1195
	}
1196

    
1197
	if (isset($config['system']['harddiskstandby'])) {
1198
		if ($g['booting']) {
1199
			echo 'Setting hard disk standby... ';
1200
		}
1201

    
1202
		$standby = $config['system']['harddiskstandby'];
1203
		// Check for a numeric value
1204
		if (is_numeric($standby)) {
1205
			// Sync the disk(s)
1206
			mwexec('/bin/sync');
1207
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1208
				// Reinitialize ATA-drives
1209
				mwexec('/usr/local/sbin/atareinit');
1210
				if ($g['booting']) {
1211
					echo "done.\n";
1212
				}
1213
			} else if ($g['booting']) {
1214
				echo "failed!\n";
1215
			}
1216
		} else if ($g['booting']) {
1217
			echo "failed!\n";
1218
		}
1219
	}
1220
}
1221

    
1222
function system_setup_sysctl() {
1223
	global $config;
1224
	if(isset($config['system']['developerspew'])) {
1225
		$mt = microtime();
1226
		echo "system_setup_sysctl() being called $mt\n";
1227
	}
1228

    
1229
	$sysctl = return_filename_as_array("/etc/sysctl.conf");
1230
	foreach($sysctl as $sysc) {
1231
		$sysc = rtrim($sysc);
1232
		if($sysc <> "")
1233
			mwexec("sysctl {$sysc} 2>/dev/null");
1234
	}
1235
	if (isset($config['system']['sharednet'])) {
1236
		system_disable_arp_wrong_if();
1237
	}
1238
}
1239

    
1240
function system_disable_arp_wrong_if() {
1241
	global $config;
1242
	if(isset($config['system']['developerspew'])) {
1243
		$mt = microtime();
1244
		echo "system_disable_arp_wrong_if() being called $mt\n";
1245
	}
1246
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1247
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1248
}
1249

    
1250
function system_enable_arp_wrong_if() {
1251
	global $config;
1252
	if(isset($config['system']['developerspew'])) {
1253
		$mt = microtime();
1254
		echo "system_enable_arp_wrong_if() being called $mt\n";
1255
	}
1256
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1257
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1258
}
1259

    
1260
function enable_watchdog() {
1261
	global $config;
1262
	$install_watchdog = false;
1263
	$supported_watchdogs = array("Geode");
1264
	$file = file_get_contents("/var/log/dmesg.boot");
1265
	foreach($supported_watchdogs as $sd) {
1266
		if(stristr($file, "Geode")) {
1267
			$install_watchdog = true;
1268
		}
1269
	}
1270
	if($install_watchdog == true) {
1271
		if(is_process_running("watchdogd"))
1272
			mwexec("/usr/bin/killall watchdogd", true);
1273
		exec("/usr/sbin/watchdogd");
1274
	}
1275
}
1276

    
1277
?>
(20-20/27)