Project

General

Profile

Download (35.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
/* 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 = 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
	return 0;
276
}
277

    
278
function system_routing_enable() {
279
	global $config, $g;
280
	if(isset($config['system']['developerspew'])) {
281
		$mt = microtime();
282
		echo "system_routing_enable() being called $mt\n";
283
	}
284

    
285
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
286
}
287

    
288
function system_syslogd_start() {
289
	global $config, $g;
290
	if(isset($config['system']['developerspew'])) {
291
		$mt = microtime();
292
		echo "system_syslogd_start() being called $mt\n";
293
	}
294

    
295
	$syslogcfg = $config['syslog'];
296

    
297
	if ($g['booting'])
298
		echo "Starting syslog...";
299
	else
300
		killbypid("{$g['varrun_path']}/syslog.pid");
301

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

    
327
EOD;
328
		}
329
		$syslogconf .= "!racoon\n";
330
		if (!isset($syslogcfg['disablelocallogging'])) {
331
			$syslogconf .= <<<EOD
332
*.*						%{$g['varlog_path']}/ipsec.log
333

    
334
EOD;
335
		}
336
		if (isset($syslogcfg['vpn'])) {
337
			$syslogconf .= <<<EOD
338
*.*						@{$syslogcfg['remoteserver']}
339

    
340
EOD;
341
		}
342
		$syslogconf .= "!openvpn\n";
343
		if (!isset($syslogcfg['disablelocallogging'])) {
344
			$syslogconf .= <<<EOD
345
*.*						%{$g['varlog_path']}/openvpn.log
346

    
347
EOD;
348
		}
349
		if (isset($syslogcfg['vpn'])) {
350
			$syslogconf .= <<<EOD
351
*.*						@{$syslogcfg['remoteserver']}
352

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

    
371
EOD;
372
		}
373

    
374
		if (isset($syslogcfg['filter'])) {
375
			$syslogconf .= <<<EOD
376
local0.*					@{$syslogcfg['remoteserver']}
377

    
378
EOD;
379
		}
380

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

    
385
EOD;
386
		}
387

    
388

    
389
		if (isset($syslogcfg['portalauth'])) {
390
			$syslogconf .= <<<EOD
391
local4.*					@{$syslogcfg['remoteserver']}
392

    
393
EOD;
394
		}
395

    
396

    
397
		if (isset($syslogcfg['dhcp'])) {
398
			$syslogconf .= <<<EOD
399
local7.*					@{$syslogcfg['remoteserver']}
400

    
401
EOD;
402
		}
403

    
404
		if (isset($syslogcfg['system'])) {
405
			$syslogconf .= <<<EOD
406
*.notice;kern.debug;lpr.info;mail.crit;		@{$syslogcfg['remoteserver']}
407
news.err;local0.none;local3.none;local7.none	@{$syslogcfg['remoteserver']}
408
security.*					@{$syslogcfg['remoteserver']}
409
auth.info;authpriv.info;daemon.info		@{$syslogcfg['remoteserver']}
410
*.emerg						@{$syslogcfg['remoteserver']}
411

    
412
EOD;
413
		}
414
		fwrite($fd, $syslogconf);
415
		fclose($fd);
416

    
417
		// Are we logging to a least one remote server ?
418
		if(strpos($syslogconf, "@") != false)
419
			$retval = mwexec("/usr/sbin/syslogd -s -f {$g['varetc_path']}/syslog.conf");
420
		else
421
			$retval = mwexec("/usr/sbin/syslogd -ss -f {$g['varetc_path']}/syslog.conf");
422

    
423
	} else {
424
		$retval = mwexec("/usr/sbin/syslogd -ss");
425
	}
426

    
427
	if ($g['booting'])
428
		echo "done.\n";
429

    
430
	return $retval;
431
}
432

    
433
function system_pccard_start() {
434
	global $config, $g;
435
	if(isset($config['system']['developerspew'])) {
436
		$mt = microtime();
437
		echo "system_pccard_start() being called $mt\n";
438
	}
439

    
440
	if ($g['booting'])
441
		echo "Initializing PCMCIA...";
442

    
443
	/* kill any running pccardd */
444
	killbypid("{$g['varrun_path']}/pccardd.pid");
445

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

    
449
	if ($g['booting']) {
450
		if ($res == 0)
451
			echo "done.\n";
452
		else
453
			echo "failed!\n";
454
	}
455

    
456
	return $res;
457
}
458

    
459

    
460
function system_webgui_start() {
461
	global $config, $g;
462

    
463
	if ($g['booting'])
464
		echo "Starting webConfigurator...";
465

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

    
469
	sleep(1);
470

    
471
	/* generate password file */
472
	system_password_configure();
473

    
474
	chdir($g['www_path']);
475

    
476
	/* non-standard port? */
477
	if ($config['system']['webgui']['port'])
478
		$portarg = "{$config['system']['webgui']['port']}";
479
	else
480
		$portarg = "";
481

    
482
	if ($config['system']['webgui']['protocol'] == "https") {
483

    
484
	if(!$config['system']['webgui']['port'])
485
		$portarg = "443";
486

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

    
513
EOD;
514

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

    
532
EOD;
533
		}
534
	} else {
535
		$cert = "";
536
		$key = "";
537
	}
538

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

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

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

    
553
	return $res;
554
}
555

    
556
function system_webgui_start_old() {
557
	global $config, $g;
558
	if(isset($config['system']['developerspew'])) {
559
		$mt = microtime();
560
		echo "system_webgui_start() being called $mt\n";
561
	}
562

    
563
        if ($g['booting'])
564
                echo "Starting webConfigurator...";
565

    
566
        /* kill any running mini_httpd */
567
        killbypid("{$g['varrun_path']}/mini_httpd.pid");
568

    
569
        /* generate password file */
570
        system_password_configure();
571

    
572
        chdir($g['www_path']);
573

    
574
        /* non-standard port? */
575
        if ($config['system']['webgui']['port'])
576
                $portarg = "-p {$config['system']['webgui']['port']}";
577
        else
578
                $portarg = "";
579

    
580
        if ($config['system']['webgui']['protocol'] == "https") {
581

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

    
600
EOD;
601

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

    
619
EOD;
620
                }
621

    
622
				$cert = str_replace("\r", "", $cert);
623
				$key = str_replace("\r", "", $key);
624

    
625
                $fd = fopen("{$g['varetc_path']}/cert.pem", "w");
626
                if (!$fd) {
627
                        printf("Error: cannot open cert.pem in system_webgui_start().\n");
628
                        return 1;
629
                }
630
                chmod("{$g['varetc_path']}/cert.pem", 0600);
631
                fwrite($fd, $cert);
632
                fwrite($fd, "\n");
633
                fwrite($fd, $key);
634
                fclose($fd);
635

    
636
                $res = mwexec("/usr/local/sbin/mini_httpd -S -E {$g['varetc_path']}/cert.pem" .
637
                        " -c \"**.php|**.cgi\" -u root -maxproc 16 $portarg" .
638
                        " -i {$g['varrun_path']}/mini_httpd.pid");
639
        } else {
640
                $res = mwexec("/usr/local/sbin/mini_httpd -c \"**.php|**.cgi\" -u root" .
641
                        " -maxproc 16 $portarg -i {$g['varrun_path']}/mini_httpd.pid");
642
        }
643

    
644
        if ($g['booting']) {
645
                if ($res == 0)
646
                        echo "done\n";
647
                else
648
                        echo "failed\n";
649
        }
650

    
651
        return $res;
652
}
653

    
654
function system_generate_lighty_config($filename,
655
	$cert,
656
	$key,
657
	$pid_file,
658
	$port = 80,
659
	$document_root = "/usr/local/www/",
660
	$cert_location = "cert.pem",
661
	$max_procs = 2,
662
	$max_requests = "1",
663
	$fast_cgi_enable = true,
664
	$captive_portal = false) {
665

    
666
	global $config, $g;
667

    
668
	if(isset($config['system']['developerspew'])) {
669
		$mt = microtime();
670
		echo "system_generate_lighty_config() being called $mt\n";
671
	}
672

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

    
693
	if($port <> "")
694
		$lighty_port = $port;
695
	else
696
		$lighty_port = "80";
697

    
698
	$memory = get_memory();
699
	$avail = $memory[0];
700

    
701
	if($avail > 0 and $avail < 98) {
702
		$max_procs = 1;
703
		$max_requests = 1;
704
	}
705

    
706
	if($avail > 97 and $avail < 128) {
707
		$max_procs = 1;
708
		$max_requests = 3;
709
	}
710

    
711
	if($avail > 127 and $avail < 256) {
712
		$max_procs = 1;
713
		$max_requests = 5;
714
	}
715

    
716
	if($avail > 255 and $avail < 384) {
717
		$max_procs = 3;
718
		$max_requests = 10;
719
	}
720

    
721
	if($avail > 383 and $avail < 512) {
722
		$max_procs = 4;
723
		$max_requests = 16;
724
	}
725

    
726
		if($captive_portal == true)  {	
727
			$bin_environment =  <<<EOC
728
	        "bin-environment" => (
729
	           "PHP_FCGI_CHILDREN" => "16",
730
	           "PHP_FCGI_MAX_REQUESTS" => "{$max_requests}"
731
	        ), 
732
EOC;
733

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

    
756
#### CGI module
757
cgi.assign                 = ( ".cgi" => "" )
758

    
759
EOD;
760
	} else {
761
		$fastcgi_config = "";
762
		$module = "\"mod_cgi\"";
763
		$cgi_config = <<<EOD
764
#### CGI module
765
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
766
                               ".cgi" => "" )
767

    
768
EOD;
769
	}
770

    
771
	$lighty_config .= <<<EOD
772
#
773
# lighttpd configuration file
774
#
775
# use a it as base for lighttpd 1.0.0 and above
776
#
777
############ Options you really have to take care of ####################
778

    
779
## FreeBSD!
780
server.event-handler		= "freebsd-kqueue"
781
server.network-backend		= "writev"  ## Fixes 7.x upload issues
782

    
783
{$network_handler}
784

    
785
## modules to load
786
server.modules              =   (
787
				  {$captive_portal_module}
788
				  "mod_access", "mod_accesslog",
789
                                  {$module}{$captiveportal}
790
				)
791

    
792
## Unused modules
793
#                               "mod_setenv",
794
#                               "mod_compress"
795
#				"mod_redirect",
796
#                               "mod_rewrite",
797
#                               "mod_ssi",
798
#                               "mod_usertrack",
799
#                               "mod_expire",
800
#                               "mod_secdownload",
801
#                               "mod_rrdtool",
802
#                               "mod_auth",
803
#                               "mod_status",
804
#                               "mod_alias",
805
#                               "mod_proxy",
806
#                               "mod_simple_vhost",
807
#                               "mod_evhost",
808
#                               "mod_userdir",
809
#                               "mod_cgi",
810
#                                "mod_accesslog"
811

    
812
## a static document-root, for virtual-hosting take look at the
813
## server.virtual-* options
814
server.document-root        = "{$document_root}"
815
{$captive_portal_rewrite}
816

    
817
## where to send error-messages to
818
server.errorlog             = "/var/log/lighttpd.error.log"
819

    
820
# files to check for if .../ is requested
821
server.indexfiles           = ( "index.php", "index.html",
822
                                "index.htm", "default.htm" )
823

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

    
877
# Use the "Content-Type" extended attribute to obtain mime type if possible
878
#mimetypes.use-xattr        = "enable"
879

    
880
#### accesslog module
881
#accesslog.filename          = "/dev/null"
882

    
883
## deny access the file-extensions
884
#
885
# ~    is for backupfiles from vi, emacs, joe, ...
886
# .inc is often used for code includes which should in general not be part
887
#      of the document-root
888
url.access-deny             = ( "~", ".inc" )
889

    
890

    
891
######### Options that are good to be but not neccesary to be changed #######
892

    
893
## bind to port (default: 80)
894
server.port                = {$lighty_port}
895

    
896
## error-handler for status 404
897
#server.error-handler-404   = "/error-handler.html"
898
#server.error-handler-404   = "/error-handler.php"
899

    
900
## to help the rc.scripts
901
server.pid-file            = "/var/run/{$pid_file}"
902

    
903
## virtual directory listings
904
server.dir-listing         = "disable"
905

    
906
## enable debugging
907
debug.log-request-header   = "disable"
908
debug.log-response-header  = "disable"
909
debug.log-request-handling = "disable"
910
debug.log-file-not-found   = "disable"
911

    
912
#### compress module
913
#compress.cache-dir         = "/tmp/lighttpd/cache/compress/"
914
#compress.filetype          = ("text/plain", "text/html")
915

    
916
#server.network-backend = "writev"
917

    
918
{$server_upload_dirs}
919

    
920
{$server_max_request_size}
921

    
922
{$fastcgi_config}
923

    
924
{$cgi_config}
925

    
926
{$captive_portal_mod_evasive}
927

    
928
EOD;
929

    
930
	$cert = str_replace("\r", "", $cert);
931
	$key = str_replace("\r", "", $key);
932

    
933
	$cert = str_replace("\n\n", "\n", $cert);
934
	$key = str_replace("\n\n", "\n", $key);
935

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

    
953
	$fd = fopen("{$filename}", "w");
954
	if (!$fd) {
955
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
956
		return 1;
957
	}
958
	fwrite($fd, $lighty_config);
959
	fclose($fd);
960

    
961
	return 0;
962

    
963
}
964

    
965
function system_password_configure() {
966
	global $config, $g;
967
	if(isset($config['system']['developerspew'])) {
968
		$mt = microtime();
969
		echo "system_password_configure() being called $mt\n";
970
	}
971

    
972
	/* sync passwords */
973
	sync_webgui_passwords();
974

    
975
	/* !NOTE! conf_mount_ro is done by sync_webgui_passwords() */
976

    
977
	return 0;
978
}
979

    
980
function system_timezone_configure() {
981
	global $config, $g;
982
	if(isset($config['system']['developerspew'])) {
983
		$mt = microtime();
984
		echo "system_timezone_configure() being called $mt\n";
985
	}
986

    
987
	$syscfg = $config['system'];
988

    
989
	if ($g['booting'])
990
		echo "Setting timezone...";
991

    
992
	/* extract appropriate timezone file */
993
	$timezone = $syscfg['timezone'];
994
	if (!$timezone)
995
		$timezone = "Etc/UTC";
996

    
997
	conf_mount_rw();
998

    
999
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1000
		escapeshellarg($timezone) . " > /etc/localtime");
1001

    
1002
	mwexec("sync");
1003
	conf_mount_ro();
1004

    
1005
	if ($g['booting'])
1006
		echo "done.\n";
1007
}
1008

    
1009
function system_ntp_configure() {
1010
	global $config, $g;
1011

    
1012
	$syscfg = $config['system'];
1013

    
1014
	/* open configuration for wrting or bail */
1015
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1016
	if(!$fd) {
1017
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1018
		return;
1019
	}
1020

    
1021
	fwrite($fd, "# \n");
1022
	fwrite($fd, "# pfSense OpenNTPD configuration file \n");
1023
	fwrite($fd, "# \n\n");
1024

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

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

    
1042
	fwrite($fd, "\n");
1043

    
1044
	/* slurp! */
1045
	fclose($fd);
1046

    
1047
	/* if openntpd is running, kill it */
1048
	while(is_process_running("ntpd")) {
1049
		mwexec("/usr/bin/killall ntpd", true);
1050
		sleep(3);
1051
	}
1052

    
1053
	/* if /var/empty does not exist, create it */
1054
	if(!is_dir("/var/empty"))
1055
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1056

    
1057
	sleep(1);
1058

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

    
1062
}
1063

    
1064
function sync_system_time() {
1065
	global $config, $g;
1066

    
1067
	$syscfg = $config['system'];
1068

    
1069
	if ($g['booting'])
1070
		echo "Syncing system time before startup...";
1071

    
1072
	/* foreach through servers and write out to ntpd.conf */
1073
	foreach (explode(' ', $syscfg['timeservers']) as $ts) {
1074
		mwexec("/usr/sbin/ntpdate -s $ts");
1075
	}
1076
	
1077
	if ($g['booting'])
1078
		echo "done.\n";
1079
	
1080
}
1081

    
1082
function system_halt() {
1083
	global $g;
1084

    
1085
	system_reboot_cleanup();
1086

    
1087
	mwexec("nohup /etc/rc.halt > /dev/null 2>&1 &");
1088
}
1089

    
1090
function system_reboot() {
1091
	global $g;
1092

    
1093
	system_reboot_cleanup();
1094

    
1095
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1096
}
1097

    
1098
function system_reboot_sync() {
1099
	global $g;
1100

    
1101
	system_reboot_cleanup();
1102

    
1103
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1104
}
1105

    
1106
function system_reboot_cleanup() {
1107
	mwexec("/usr/local/bin/beep.sh stop");
1108
	captiveportal_radius_stop_all();
1109
}
1110

    
1111
function system_do_shell_commands($early = 0) {
1112
	global $config, $g;
1113
	if(isset($config['system']['developerspew'])) {
1114
		$mt = microtime();
1115
		echo "system_do_shell_commands() being called $mt\n";
1116
	}
1117

    
1118
	if ($early)
1119
		$cmdn = "earlyshellcmd";
1120
	else
1121
		$cmdn = "shellcmd";
1122

    
1123
	if (is_array($config['system'][$cmdn])) {
1124

    
1125
		/* *cmd is an array, loop through */
1126
		foreach ($config['system'][$cmdn] as $cmd) {
1127
			exec($cmd);
1128
		}
1129

    
1130
	} elseif($config['system'][$cmdn] <> "") {
1131

    
1132
		/* execute single item */
1133
		exec($config['system'][$cmdn]);
1134

    
1135
	}
1136
}
1137

    
1138
function system_console_configure() {
1139
	global $config, $g;
1140
	if(isset($config['system']['developerspew'])) {
1141
		$mt = microtime();
1142
		echo "system_console_configure() being called $mt\n";
1143
	}
1144

    
1145
	if (isset($config['system']['disableconsolemenu'])) {
1146
		touch("{$g['varetc_path']}/disableconsole");
1147
	} else {
1148
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1149
	}
1150
}
1151

    
1152
function system_dmesg_save() {
1153
	global $g;
1154
	if(isset($config['system']['developerspew'])) {
1155
		$mt = microtime();
1156
		echo "system_dmesg_save() being called $mt\n";
1157
	}
1158

    
1159
	$dmesg = "";
1160
	exec("/sbin/dmesg", $dmesg);
1161

    
1162
	/* find last copyright line (output from previous boots may be present) */
1163
	$lastcpline = 0;
1164

    
1165
	for ($i = 0; $i < count($dmesg); $i++) {
1166
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1167
			$lastcpline = $i;
1168
	}
1169

    
1170
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1171
	if (!$fd) {
1172
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1173
		return 1;
1174
	}
1175

    
1176
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1177
		fwrite($fd, $dmesg[$i] . "\n");
1178

    
1179
	fclose($fd);
1180

    
1181
	return 0;
1182
}
1183

    
1184
function system_set_harddisk_standby() {
1185
	global $g, $config;
1186
	if(isset($config['system']['developerspew'])) {
1187
		$mt = microtime();
1188
		echo "system_set_harddisk_standby() being called $mt\n";
1189
	}
1190

    
1191
	if (isset($config['system']['harddiskstandby'])) {
1192
		if ($g['booting']) {
1193
			echo 'Setting hard disk standby... ';
1194
		}
1195

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

    
1216
function system_setup_sysctl() {
1217
	global $config;
1218
	if(isset($config['system']['developerspew'])) {
1219
		$mt = microtime();
1220
		echo "system_setup_sysctl() being called $mt\n";
1221
	}
1222

    
1223
	$sysctl = return_filename_as_array("/etc/sysctl.conf");
1224
	foreach($sysctl as $sysc) {
1225
		$sysc = rtrim($sysc);
1226
		if($sysc <> "")
1227
			mwexec("sysctl {$sysc} 2>/dev/null");
1228
	}
1229
	if (isset($config['system']['sharednet'])) {
1230
		system_disable_arp_wrong_if();
1231
	}
1232
}
1233

    
1234
function system_disable_arp_wrong_if() {
1235
	global $config;
1236
	if(isset($config['system']['developerspew'])) {
1237
		$mt = microtime();
1238
		echo "system_disable_arp_wrong_if() being called $mt\n";
1239
	}
1240
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1241
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1242
}
1243

    
1244
function system_enable_arp_wrong_if() {
1245
	global $config;
1246
	if(isset($config['system']['developerspew'])) {
1247
		$mt = microtime();
1248
		echo "system_enable_arp_wrong_if() being called $mt\n";
1249
	}
1250
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1251
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1252
}
1253

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

    
1271
?>
(20-20/27)