Project

General

Profile

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

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

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

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

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

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

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

    
35
function activate_sysctls() {
36
	global $config, $g;
37
	
38
	if (is_array($config['sysctl']['item'])) 
39
		foreach ($config['sysctl']['item'] as $tunable) 
40
			mwexec("sysctl " . $tunable['tunable'] . "=\"" 
41
				. $tunable['value'] .  "\"");
42
	
43
}
44

    
45
function system_resolvconf_generate($dynupdate = false) {
46
		global $config, $g;
47
		if(isset($config['system']['developerspew'])) {
48
			$mt = microtime();
49
			echo "system_resolvconf_generate() being called $mt\n";
50
		}
51

    
52
        $syscfg = $config['system'];
53

    
54
        $fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
55
        if (!$fd) {
56
                printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
57
                return 1;
58
        }
59

    
60
        $resolvconf = "domain {$syscfg['domain']}\n";
61

    
62
        $havedns = false;
63

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

    
83
        fwrite($fd, $resolvconf);
84
        fclose($fd);
85

    
86
        if (!$g['booting']) {
87
			/* restart dhcpd (nameservers may have changed) */
88
			if (!$dynupdate)
89
				services_dhcpd_configure();
90
        }
91

    
92
		for($dnscounter=1; $dnscounter<5; $dnscounter++) {
93
			/* setup static routes for dns servers */
94
			if($config['system']['dns{$dnscounter}gwint']) {
95
				$if = $config['system']['dns{$dnscounter}gwint'];
96
				if($if) { 
97
					$gw = $config['interfaces'][$if]['if'];
98
					$dnscountermo = $dnscounter - 1;
99
					exec("route delete {$syscfg['dnsserver'][$dnscountermo]}");
100
					exec("route add {$syscfg['dnsserver'][$dnscountermo]} -gw {$gw}");
101
				}
102
			}
103
		}
104

    
105
        return 0;
106
}
107

    
108
function get_nameservers() {
109
	global $config, $g;
110
	$master_list = array();
111
	$dns_lists = split("\n", `ls /var/etc/nameserver_* 2>/dev/null`);
112
	foreach($dns_lists as $dns) {
113
		$items = split("\n", file_get_contents($dns));
114
		foreach($items as $item)
115
			if($item <> "")
116
				$master_list[] = $item;
117
	}
118
	if(!file_exists("/var/etc/nameservers.conf"))
119
		return $master_list;
120
	$dns = `cat /var/etc/nameservers.conf`;
121
	$dns_s = split("\n", $dns);
122
	if(is_array($dns_s))
123
		foreach($dns_s as $dns)
124
			$master_list[] = $dns;
125
	return $master_list;
126
}
127

    
128
function system_hosts_generate() {
129
	global $config, $g;
130
	if(isset($config['system']['developerspew'])) {
131
		$mt = microtime();
132
		echo "system_hosts_generate() being called $mt\n";
133
	}
134

    
135
	$syscfg = $config['system'];
136
	$lancfg = $config['interfaces']['lan'];
137
	$dnsmasqcfg = $config['dnsmasq'];
138

    
139
	if (!is_array($dnsmasqcfg['hosts'])) {
140
		$dnsmasqcfg['hosts'] = array();
141
	}
142
	$hostscfg = $dnsmasqcfg['hosts'];
143

    
144
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
145
	if (!$fd) {
146
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
147
		return 1;
148
	}
149

    
150
	$hosts = <<<EOD
151
127.0.0.1	localhost localhost.{$syscfg['domain']}
152
{$lancfg['ipaddr']}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}
153

    
154
EOD;
155

    
156
	foreach ($hostscfg as $host) {
157
		if ($host['host'])
158
			$hosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
159
		else
160
			$hosts .= "{$host['ip']}	{$host['domain']}\n";
161
	}
162
	if (isset($dnsmasqcfg['regdhcpstatic'])) {
163
		foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf)
164
			if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
165
					foreach ($dhcpifconf['staticmap'] as $host)
166
						if ($host['ipaddr'] && $host['hostname'])
167
							$hosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
168
	}
169
	fwrite($fd, $hosts);
170
	fclose($fd);
171

    
172
	return 0;
173
}
174

    
175
function system_hostname_configure() {
176
	global $config, $g;
177
	if(isset($config['system']['developerspew'])) {
178
		$mt = microtime();
179
		echo "system_hostname_configure() being called $mt\n";
180
	}
181

    
182
	$syscfg = $config['system'];
183

    
184
	/* set hostname */
185
	return mwexec("/bin/hostname " .
186
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
187
}
188

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

    
196
	/* Enable fast routing, if enabled */
197
	if(isset($config['staticroutes']['enablefastrouting']))
198
		mwexec("/sbin/sysctl net.inet.ip.fastforwarding=1");
199

    
200
	/* clear out old routes, if necessary */
201
	if (file_exists("{$g['vardb_path']}/routes.db")) {
202
		$fd = fopen("{$g['vardb_path']}/routes.db", "r");
203
		if (!$fd) {
204
			printf("Error: cannot open routes DB file in system_routing_configure().\n");
205
			return 1;
206
		}
207
		while (!feof($fd)) {
208
			$oldrt = fgets($fd);
209
			if ($oldrt)
210
				mwexec("/sbin/route delete " . escapeshellarg($oldrt));
211
		}
212
		fclose($fd);
213
		unlink("{$g['vardb_path']}/routes.db");
214
	}
215

    
216
	/* if list */
217
	$iflist = get_configured_interface_list();
218

    
219
	$dont_remove_route = false;
220
	foreach ($iflist as $ifent => $ifname) {
221
		/* do not process interfaces that will end up with gateways */
222
		if (interface_has_gateway($ifent))
223
			$dont_remove_route = true;
224
	}
225

    
226
	if($config['interfaces']['wan']['ipaddr'] == "carpdev-dhcp")
227
		$dont_remove_route = true;
228

    
229
	if($dont_remove_route == false) {
230
		/* remove default route */
231
		mwexec("/sbin/route delete default");
232
	}
233

    
234
	$dont_add_route = false;
235
	/* if OLSRD is enabled, allow WAN to house DHCP. */
236
	if($config['installedpackages']['olsrd']) {
237
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
238
			if($olsrd['enabledyngw'] == "on") {
239
				$dont_add_route = true;
240
			}
241
		}
242
	}
243

    
244
	if($dont_add_route == false) {
245
		if(is_array($config['gateways']['gateway_item'])) {
246
			foreach($config['gateways']['gateway_item'] as $gateway) {
247
		        	if(isset($gateway['defaultgw'])) {
248
					$gatewayip = $gateway['gateway'];
249
					$interfacegw = $gateway['interface'];
250
				}
251
			}
252
			if($interfacegw <> "bgpd")
253
				mwexec("/sbin/route add default " . escapeshellarg($gatewayip));
254
		} else {
255
			/* adding gateway for 1.2-style configs without the new
256
			  gateway setup configured.
257
			  Force WAN to be default gateway because that is the
258
			  1.2 behavior.
259
			*/
260
			if (is_ipaddr($config['interfaces']['wan']['gateway'])) {
261
				$gatewayip = $config['interfaces']['wan']['gateway'];
262
				mwexec("/sbin/route add default " . escapeshellarg($gatewayip));
263
			}
264
		}
265
	}
266

    
267
	if (is_array($config['staticroutes']['route'])) {
268

    
269
		$fd = fopen("{$g['vardb_path']}/routes.db", "w");
270
		if (!$fd) {
271
			printf("Error: cannot open routes DB file in system_routing_configure().\n");
272
			return 1;
273
		}
274

    
275
		foreach ($config['staticroutes']['route'] as $rtent) {
276
			if(is_array($config['gateways']['gateway_item'])) {
277
				foreach($config['gateways']['gateway_item'] as $gateway) {
278
					if($rtent['gateway'] == $gateway['name']) {
279
						$gatewayip = $gateway['gateway'];
280
						$interfacegw = $gateway['interface'];
281
					}
282
				}
283
			}
284
			if((is_ipaddr($rtent['gateway'])) && ($gatewayip == ""))  {
285
				$gatewayip = $rtent['gateway'];
286
				$interfacegw = $rtent['interface'];
287
			}			
288
			if(isset($rtent['interfacegateway'])) {
289
				mwexec("/sbin/route add " . escapeshellarg($rtent['network']) .
290
					" -iface " . escapeshellarg(convert_friendly_interface_to_real_interface_name($interfacegw)));
291
			} else {
292
				mwexec("/sbin/route add " . escapeshellarg($rtent['network']) .
293
					" " . escapeshellarg($gatewayip));
294
			}
295
			/* record route so it can be easily removed later (if necessary) */
296
			fwrite($fd, $rtent['network'] . "\n");
297
		}
298
		fclose($fd);
299
	}
300

    
301
	return 0;
302
}
303

    
304
function system_routing_enable() {
305
	global $config, $g;
306
	if(isset($config['system']['developerspew'])) {
307
		$mt = microtime();
308
		echo "system_routing_enable() being called $mt\n";
309
	}
310

    
311
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
312
}
313

    
314
function system_syslogd_start() {
315
	global $config, $g;
316
	if(isset($config['system']['developerspew'])) {
317
		$mt = microtime();
318
		echo "system_syslogd_start() being called $mt\n";
319
	}
320

    
321
	$syslogcfg = $config['syslog'];
322

    
323
	if ($g['booting'])
324
		echo "Starting syslog...";
325
	else
326
		killbypid("{$g['varrun_path']}/syslog.pid");
327

    
328
	if (isset($syslogcfg)) {
329
		$separatelogfacilities = array('ntpd','racoon','openvpn');
330
		if($config['installedpackages']['package']) {
331
                        foreach($config['installedpackages']['package'] as $package) {
332
                                if($package['logging']) {
333
					$pkgfacilities[] = $package['logging']['facilityname'];
334
					$separatelogfacilities = $separatelogfacilities + $pkgfacilities;
335
					$facilitylist = implode(',', $pkgfacilities);
336
					mwexec("clog -i -s 10000 {$g['varlog_path']}/{$package['logging']['logfilename']}");
337
                                	$syslogconf .= "!{$facilitylist}\n*.*\t\t\t\t\t\t%{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
338
				}
339
                        }
340
                }
341
		$facilitylist = implode(',', array_unique($separatelogfacilities));
342
		/* write syslog.conf */
343
		$fd = fopen("{$g['varetc_path']}/syslog.conf", "w");
344
		if (!$fd) {
345
			printf("Error: cannot open syslog.conf in system_syslogd_start().\n");
346
			return 1;
347
		}
348
		$syslogconf .= "!ntpdate,!ntpd\n";
349
		if (!isset($syslogcfg['disablelocallogging'])) {
350
			$syslogconf .= <<<EOD
351
*.*						%{$g['varlog_path']}/ntpd.log
352

    
353
EOD;
354
		}
355
		$syslogconf .= "!racoon\n";
356
		if (!isset($syslogcfg['disablelocallogging'])) {
357
			$syslogconf .= <<<EOD
358
*.*						%{$g['varlog_path']}/ipsec.log
359

    
360
EOD;
361
		}
362
		if (isset($syslogcfg['vpn'])) {
363
			$syslogconf .= <<<EOD
364
*.*						@{$syslogcfg['remoteserver']}
365

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

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

    
379
EOD;
380
		}
381
		$syslogconf .= "!-{$facilitylist}\n";
382
		if (!isset($syslogcfg['disablelocallogging'])) {
383
		$syslogconf .= <<<EOD
384
local0.*					%{$g['varlog_path']}/filter.log
385
local3.*					%{$g['varlog_path']}/vpn.log
386
local4.*					%{$g['varlog_path']}/portalauth.log
387
local7.*					%{$g['varlog_path']}/dhcpd.log
388
*.notice;kern.debug;lpr.info;mail.crit; 	%{$g['varlog_path']}/system.log
389
news.err;local0.none;local3.none;local4.none; 	%{$g['varlog_path']}/system.log
390
local7.none					%{$g['varlog_path']}/system.log
391
security.*					%{$g['varlog_path']}/system.log
392
auth.info;authpriv.info;daemon.info		%{$g['varlog_path']}/system.log
393
local1.*					%{$g['varlog_path']}/relayd.log
394
auth.info;authpriv.info 			|exec /usr/local/sbin/sshlockout_pf
395
*.emerg						*
396

    
397
EOD;
398
		}
399

    
400
		if (isset($syslogcfg['filter'])) {
401
			$syslogconf .= <<<EOD
402
local0.*					@{$syslogcfg['remoteserver']}
403

    
404
EOD;
405
		}
406

    
407
		if (isset($syslogcfg['vpn'])) {
408
			$syslogconf .= <<<EOD
409
local3.*					@{$syslogcfg['remoteserver']}
410

    
411
EOD;
412
		}
413

    
414

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

    
419
EOD;
420
		}
421

    
422

    
423
		if (isset($syslogcfg['dhcp'])) {
424
			$syslogconf .= <<<EOD
425
local7.*					@{$syslogcfg['remoteserver']}
426

    
427
EOD;
428
		}
429

    
430
		if (isset($syslogcfg['system'])) {
431
			$syslogconf .= <<<EOD
432
*.notice;kern.debug;lpr.info;mail.crit;		@{$syslogcfg['remoteserver']}
433
news.err;local0.none;local3.none;local7.none	@{$syslogcfg['remoteserver']}
434
security.*					@{$syslogcfg['remoteserver']}
435
auth.info;authpriv.info;daemon.info		@{$syslogcfg['remoteserver']}
436
*.emerg						@{$syslogcfg['remoteserver']}
437

    
438
EOD;
439
		}
440
		fwrite($fd, $syslogconf);
441
		fclose($fd);
442

    
443
		// Are we logging to a least one remote server ?
444
		if(strpos($syslogconf, "@") != false)
445
			$retval = mwexec("/usr/sbin/syslogd -s -f {$g['varetc_path']}/syslog.conf");
446
		else
447
			$retval = mwexec("/usr/sbin/syslogd -ss -f {$g['varetc_path']}/syslog.conf");
448

    
449
	} else {
450
		$retval = mwexec("/usr/sbin/syslogd -ss");
451
	}
452

    
453
	if ($g['booting'])
454
		echo "done.\n";
455

    
456
	return $retval;
457
}
458

    
459
function system_pccard_start() {
460
	global $config, $g;
461
	if(isset($config['system']['developerspew'])) {
462
		$mt = microtime();
463
		echo "system_pccard_start() being called $mt\n";
464
	}
465

    
466
	if ($g['booting'])
467
		echo "Initializing PCMCIA...";
468

    
469
	/* kill any running pccardd */
470
	killbypid("{$g['varrun_path']}/pccardd.pid");
471

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

    
475
	if ($g['booting']) {
476
		if ($res == 0)
477
			echo "done.\n";
478
		else
479
			echo "failed!\n";
480
	}
481

    
482
	return $res;
483
}
484

    
485

    
486
function system_webgui_start() {
487
	global $config, $g;
488

    
489
	if ($g['booting'])
490
		echo "Starting webConfigurator...";
491

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

    
495
	sleep(1);
496

    
497
	/* generate password file */
498
	system_password_configure();
499

    
500
	chdir($g['www_path']);
501

    
502
	/* non-standard port? */
503
	if ($config['system']['webgui']['port'])
504
		$portarg = "{$config['system']['webgui']['port']}";
505
	else
506
		$portarg = "";
507

    
508
	if ($config['system']['webgui']['protocol'] == "https") {
509

    
510
	if(!$config['system']['webgui']['port'])
511
		$portarg = "443";
512

    
513
		if ($config['system']['webgui']['certificate'] && $config['system']['webgui']['private-key']) {
514
			$cert = base64_decode($config['system']['webgui']['certificate']);
515
			$key = base64_decode($config['system']['webgui']['private-key']);
516
		} else {
517
			/* default certificate/key */
518
			$cert = <<<EOD
519
-----BEGIN CERTIFICATE-----
520
MIIDEzCCAnygAwIBAgIJAJM91W+s6qptMA0GCSqGSIb3DQEBBAUAMGUxCzAJBgNV
521
BAYTAlVTMQswCQYDVQQIEwJLWTETMBEGA1UEBxMKTG91aXN2aWxsZTEQMA4GA1UE
522
ChMHcGZTZW5zZTEQMA4GA1UECxMHcGZTZW5zZTEQMA4GA1UEAxMHcGZTZW5zZTAe
523
Fw0wNjAzMTAyMzQ1MTlaFw0xNjAzMDcyMzQ1MTlaMGUxCzAJBgNVBAYTAlVTMQsw
524
CQYDVQQIEwJLWTETMBEGA1UEBxMKTG91aXN2aWxsZTEQMA4GA1UEChMHcGZTZW5z
525
ZTEQMA4GA1UECxMHcGZTZW5zZTEQMA4GA1UEAxMHcGZTZW5zZTCBnzANBgkqhkiG
526
9w0BAQEFAAOBjQAwgYkCgYEA3lPNTFH6qge/ygaqe/BS4oH59O6KvAesWcRzSu5N
527
21lyVE5tBbL0zqOSXmlLyReMSbtAMZqt1P8EPYFoOcaEQHIWm2VQF80Z18+8Gh4O
528
UQGjHq88OeaLqyk3OLpSKzSpXuCFrSN7q9Kez8zp5dQEu7sIW30da3pAbdqYOimA
529
1VsCAwEAAaOByjCBxzAdBgNVHQ4EFgQUAnx+ggC4SzJ0CK+rhPhJ2ZpyunEwgZcG
530
A1UdIwSBjzCBjIAUAnx+ggC4SzJ0CK+rhPhJ2ZpyunGhaaRnMGUxCzAJBgNVBAYT
531
AlVTMQswCQYDVQQIEwJLWTETMBEGA1UEBxMKTG91aXN2aWxsZTEQMA4GA1UEChMH
532
cGZTZW5zZTEQMA4GA1UECxMHcGZTZW5zZTEQMA4GA1UEAxMHcGZTZW5zZYIJAJM9
533
1W+s6qptMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEEBQADgYEAAviQpdoeabL8
534
1HSZiD7Yjx82pdLpyQOdXvAu3jEAYz53ckx0zSMrzsQ5r7Vae6AE7Xd7Pj+1Yihs
535
AJZzOQujnmsuim7qu6YSxzP34xonKwd1C9tZUlyNRNnEmtXOEDupn05bih1ugtLG
536
kqfPIgDbDLXuPtEAA6QDUypaunI6+1E=
537
-----END CERTIFICATE-----
538

    
539
EOD;
540

    
541
			$key = <<<EOD
542
-----BEGIN RSA PRIVATE KEY-----
543
MIICXgIBAAKBgQDeU81MUfqqB7/KBqp78FLigfn07oq8B6xZxHNK7k3bWXJUTm0F
544
svTOo5JeaUvJF4xJu0Axmq3U/wQ9gWg5xoRAchabZVAXzRnXz7waHg5RAaMerzw5
545
5ourKTc4ulIrNKle4IWtI3ur0p7PzOnl1AS7uwhbfR1rekBt2pg6KYDVWwIDAQAB
546
AoGAP7E0VFP8Aq/7os3sE1uS8y8XQ7L+7cUo/AKKoQHKLjfeyAY7t3FALt6vdPqn
547
anGjkA/j4RIWELoKJfCnwj17703NDCPwB7klcmZvmTx5Om1ZrRyZdQ6RJs0pOOO1
548
r2wOnZNaNWStXE9Afpw3dj20Gh0V/Ioo5HXn3sHfxZm8dnkCQQDwv8OaUdp2Hl8t
549
FDfXB1CMvUG1hEAvbQvZK1ODkE7na2/ChKjVPddEI3DvfzG+nLrNuTrAyVWgRLte
550
r8qX5PQHAkEA7GlKx0S18LdiKo6wy2QeGu6HYkPncaHNFOWX8cTpvGGtQoWYSh0J
551
tjCt1/mz4/XkvZWuZyTNx2FdkVlNF5nHDQJBAIRWVTZqEjVlwpmsCHnp6mxCyHD4
552
DrRDNAUfnNuwIr9xPlDlzUzSnpc1CCqOd5C45LKbRGGfCrN7tKd66FmQoFcCQQCy
553
Kvw3R1pTCvHJnvYwoshphaC0dvaDVeyINiwYAk4hMf/wpVxLZqz+CJvLrB1dzOBR
554
3O+uPjdzbrakpweJpNQ1AkEA3ZtlgEj9eWsLAJP8aKlwB8VqD+EtG9OJSUMnCDiQ
555
WFFNj/t3Ze3IVuAyL/yMpiv3JNEnZhIxCta42eDFpIZAKw==
556
-----END RSA PRIVATE KEY-----
557

    
558
EOD;
559
		}
560
	} else {
561
		$cert = "";
562
		$key = "";
563
	}
564

    
565
	/* generate lighttpd configuration */
566
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
567
		$cert, $key, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/");
568

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

    
572
	if ($g['booting']) {
573
		if ($res == 0)
574
			echo "done.\n";
575
		else
576
			echo "failed!\n";
577
	}
578

    
579
	return $res;
580
}
581

    
582
function system_webgui_start_old() {
583
	global $config, $g;
584
	if(isset($config['system']['developerspew'])) {
585
		$mt = microtime();
586
		echo "system_webgui_start() being called $mt\n";
587
	}
588

    
589
        if ($g['booting'])
590
                echo "Starting webConfigurator...";
591

    
592
        /* kill any running mini_httpd */
593
        killbypid("{$g['varrun_path']}/mini_httpd.pid");
594

    
595
        /* generate password file */
596
        system_password_configure();
597

    
598
        chdir($g['www_path']);
599

    
600
        /* non-standard port? */
601
        if ($config['system']['webgui']['port'])
602
                $portarg = "-p {$config['system']['webgui']['port']}";
603
        else
604
                $portarg = "";
605

    
606
        if ($config['system']['webgui']['protocol'] == "https") {
607

    
608
                if ($config['system']['webgui']['certificate'] && $config['system']['webgui']['private-key']) {
609
                        $cert = base64_decode($config['system']['webgui']['certificate']);
610
                        $key  = base64_decode($config['system']['webgui']['private-key']);
611
                } else {
612
                        /* default certificate/key */
613
                        $cert = <<<EOD
614
-----BEGIN CERTIFICATE-----
615
MIIBlDCB/gIBADANBgkqhkiG9w0BAQQFADATMREwDwYDVQQKEwhtMG4wd2FsbDAe
616
Fw0wNTA1MTAxMjI0NDRaFw0wNzA1MTAxMjI0NDRaMBMxETAPBgNVBAoTCG0wbjB3
617
YWxsMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDAShszhFz+o8lsMWTGgTxs
618
TMPR+v4+qL5jXDyY97MLTGFK7aqQOtpIQc+TcTc4jklgOVlHoR7oBXrsi8YrbCd+
619
83LPQmQoSPC0VqhfU3uYf3NzxiK8r97aPCsmWgwT2pQ6TcESTm6sF7nLprOf/zFP
620
C4jE2fvjkbzyVolPywBuewIDAQABMA0GCSqGSIb3DQEBBAUAA4GBAFR962c4R5tV
621
cTn0OQcszYoW6WC+ini9tQQh5ku5jYDAiC+00atawJEVLnL3lwAcpSKTIWlTkD20
622
tl3lz5br1qFgYky+Rd0kwS2nk9jRbkxSXxd6KJVnNRCKre28aw3ENzZfCSurPQsX
623
UPp5er+NtwMT1g7s/JDmKTC4w1rGr5/c
624
-----END CERTIFICATE-----
625

    
626
EOD;
627

    
628
                        $key = <<<EOD
629
-----BEGIN RSA PRIVATE KEY-----
630
MIICXQIBAAKBgQDAShszhFz+o8lsMWTGgTxsTMPR+v4+qL5jXDyY97MLTGFK7aqQ
631
OtpIQc+TcTc4jklgOVlHoR7oBXrsi8YrbCd+83LPQmQoSPC0VqhfU3uYf3NzxiK8
632
r97aPCsmWgwT2pQ6TcESTm6sF7nLprOf/zFPC4jE2fvjkbzyVolPywBuewIDAQAB
633
AoGAbJJrQW9fQrggJuLMz/hwsYW2m31oyOBmf5u463YQtjRuSuxe/gj87weZuNqY
634
H2rXq2k2K+ehl8hgW+egASyUL3L7kCkEAsVREujKTEyhSqqIRDPWTxo9S/YA9Gvn
635
2ZnJvkrcKjqCO9aHX3rvJOK/ErYI6akctgI3KmgkYw5XNmECQQDuZU97RTWH9rmP
636
aQr57ysNXxgFsyhetOOqeYkPtIVwpOiNbfwE1zi5RGdtO4Ku3fG1lV4J2UoWJ9yD
637
awdoyYIHAkEAzn0xJ90IjPsHk+8SODEj5JGdHSZPNu1tgtrbjEi9sfGWg4K7XTxr
638
QW90pWb1bKKU1uh5FzW6OhnFfuQXt1kC7QJAPSthqY+onKqCEnoxhtAHi/bKgyvl
639
P+fKQwPMV2tKkgy+XwvJjrRqqZ8TqsOKVLQ+QQmCh6RpjiXMPyxHSmvqIQJBAKLR
640
HF1ucDuaBROkwx0DwmWMW/KMLpIFDQDNSaiIAuu4rxHrl4mhBoGGPNffI04RtILw
641
s+qVNs5xW8T+XaT4ztECQQDFHPnZeoPWE5z+AX/UUQIUWaDExz3XRzmIxRbOrlFi
642
CsF1s0TdJLi/wzNQRAL37A8vqCeVFR/ng3Xpg96Yg+8Z
643
-----END RSA PRIVATE KEY-----
644

    
645
EOD;
646
                }
647

    
648
				$cert = str_replace("\r", "", $cert);
649
				$key = str_replace("\r", "", $key);
650

    
651
                $fd = fopen("{$g['varetc_path']}/cert.pem", "w");
652
                if (!$fd) {
653
                        printf("Error: cannot open cert.pem in system_webgui_start().\n");
654
                        return 1;
655
                }
656
                chmod("{$g['varetc_path']}/cert.pem", 0600);
657
                fwrite($fd, $cert);
658
                fwrite($fd, "\n");
659
                fwrite($fd, $key);
660
                fclose($fd);
661

    
662
                $res = mwexec("/usr/local/sbin/mini_httpd -S -E {$g['varetc_path']}/cert.pem" .
663
                        " -c \"**.php|**.cgi\" -u root -maxproc 16 $portarg" .
664
                        " -i {$g['varrun_path']}/mini_httpd.pid");
665
        } else {
666
                $res = mwexec("/usr/local/sbin/mini_httpd -c \"**.php|**.cgi\" -u root" .
667
                        " -maxproc 16 $portarg -i {$g['varrun_path']}/mini_httpd.pid");
668
        }
669

    
670
        if ($g['booting']) {
671
                if ($res == 0)
672
                        echo "done\n";
673
                else
674
                        echo "failed\n";
675
        }
676

    
677
        return $res;
678
}
679

    
680
function system_generate_lighty_config($filename,
681
	$cert,
682
	$key,
683
	$pid_file,
684
	$port = 80,
685
	$document_root = "/usr/local/www/",
686
	$cert_location = "cert.pem",
687
	$max_procs = 2,
688
	$max_requests = "1",
689
	$fast_cgi_enable = true,
690
	$captive_portal = false) {
691

    
692
	global $config, $g;
693

    
694
	/* only use freebsd-sendfile network handler on full installations
695
	 * tests have shown that it is actually slower on embedded.
696
	 */
697
	if(stristr("pfSense", $g['platform']))
698
		$network_handler = "server.network-backend		= \"freebsd-sendfile\"\n";
699
	else
700
		$network_handler = "";
701

    
702
	if(isset($config['system']['developerspew'])) {
703
		$mt = microtime();
704
		echo "system_generate_lighty_config() being called $mt\n";
705
	}
706

    
707
	if($captive_portal == true)  {
708
		$captiveportal = ",\"mod_rewrite\"";
709
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?redirurl=$1\" )\n";
710
		$captive_portal_module = "\"mod_accesslog\", ";
711
		$maxprocperip = $config['captiveportal']['maxprocperip'];
712
		if(!$maxprocperip and $maxprocperip > 0)
713
			$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
714
		else
715
			$captive_portal_mod_evasive = "";
716
		$server_upload_dirs = "server.upload-dirs = ( \"/tmp/captiveportal/\" )\n";
717
		exec("mkdir -p /tmp/captiveportal");
718
		exec("chmod a-w /tmp/captiveportal");
719
		$server_max_request_size = "server.max-request-size    = 384";
720
	} else {
721
		$captive_portal_module = "";
722
		$captive_portal_mod_evasive = "";
723
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"/tmp/\", \"/var/\" )\n";
724
		$server_max_request_size = "server.max-request-size    = 2097152";
725
	}
726
	
727
	if($port <> "")
728
		$lighty_port = $port;
729
	else
730
		$lighty_port = "80";
731

    
732
	$memory = get_memory();
733
	$avail = $memory[0];
734

    
735
	if($avail > 0 and $avail < 98) {
736
		$max_procs = 1;
737
		$max_requests = 1;
738
	}
739

    
740
	if($avail > 97 and $avail < 128) {
741
		$max_procs = 2;
742
		$max_requests = 1;
743
	}
744

    
745
	if($avail > 127 and $avail < 256) {
746
		$max_procs = 2;
747
		$max_requests = 5;
748
	}
749

    
750
	if($avail > 255 and $avail < 384) {
751
		$max_procs = 3;
752
		$max_requests = 10;
753
	}
754

    
755
	if($avail > 383 and $avail < 512) {
756
		$max_procs = 4;
757
		$max_requests = 16;
758
	}
759

    
760
	if($captive_portal == true)  {	
761
		$bin_environment =  <<<EOC
762
        "bin-environment" => (
763
           "PHP_FCGI_CHILDREN" => "16",
764
           "PHP_FCGI_MAX_REQUESTS" => "{$max_requests}"
765
        ), 
766
EOC;
767

    
768
	} else {
769
		$bin_environment = "";
770
	}
771
		
772
	if($fast_cgi_enable == true) {
773
		$module = "\"mod_fastcgi\", \"mod_cgi\"";
774
		$cgi_config = "";
775
		$fastcgi_config = <<<EOD
776
#### fastcgi module
777
## read fastcgi.txt for more info
778
fastcgi.server = ( ".php" =>
779
	( "localhost" =>
780
		(
781
			"socket" => "/tmp/php-fastcgi.socket",
782
			"min-procs" => 1,
783
			"max-procs" => {$max_procs},
784
			{$bin_environment}			
785
			"bin-path" => "/usr/local/bin/php"
786
		)
787
	)
788
)
789

    
790
#### CGI module
791
cgi.assign                 = ( ".cgi" => "" )
792

    
793
EOD;
794
	} else {
795
		$fastcgi_config = "";
796
		$module = "\"mod_cgi\"";
797
		$cgi_config = <<<EOD
798
#### CGI module
799
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
800
                               ".cgi" => "" )
801

    
802
EOD;
803
	}
804

    
805
	$lighty_config .= <<<EOD
806
#
807
# lighttpd configuration file
808
#
809
# use a it as base for lighttpd 1.0.0 and above
810
#
811
############ Options you really have to take care of ####################
812

    
813
## FreeBSD!
814
server.event-handler		= "freebsd-kqueue"
815

    
816
{$network_handler}
817

    
818
## modules to load
819
server.modules              =   (
820
				  {$captive_portal_module}
821
				  "mod_access", "mod_accesslog",
822
                                  {$module}{$captiveportal}
823
				)
824

    
825
## Unused modules
826
#                               "mod_setenv",
827
#                               "mod_compress"
828
#				"mod_redirect",
829
#                               "mod_rewrite",
830
#                               "mod_ssi",
831
#                               "mod_usertrack",
832
#                               "mod_expire",
833
#                               "mod_secdownload",
834
#                               "mod_rrdtool",
835
#                               "mod_auth",
836
#                               "mod_status",
837
#                               "mod_alias",
838
#                               "mod_proxy",
839
#                               "mod_simple_vhost",
840
#                               "mod_evhost",
841
#                               "mod_userdir",
842
#                               "mod_cgi",
843
#                                "mod_accesslog"
844

    
845
## a static document-root, for virtual-hosting take look at the
846
## server.virtual-* options
847
server.document-root        = "{$document_root}"
848
{$captive_portal_rewrite}
849

    
850
## where to send error-messages to
851
server.errorlog             = "/var/log/lighttpd.error.log"
852

    
853
# files to check for if .../ is requested
854
server.indexfiles           = ( "index.php", "index.html",
855
                                "index.htm", "default.htm" )
856

    
857
# mimetype mapping
858
mimetype.assign             = (
859
  ".pdf"          =>      "application/pdf",
860
  ".sig"          =>      "application/pgp-signature",
861
  ".spl"          =>      "application/futuresplash",
862
  ".class"        =>      "application/octet-stream",
863
  ".ps"           =>      "application/postscript",
864
  ".torrent"      =>      "application/x-bittorrent",
865
  ".dvi"          =>      "application/x-dvi",
866
  ".gz"           =>      "application/x-gzip",
867
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
868
  ".swf"          =>      "application/x-shockwave-flash",
869
  ".tar.gz"       =>      "application/x-tgz",
870
  ".tgz"          =>      "application/x-tgz",
871
  ".tar"          =>      "application/x-tar",
872
  ".zip"          =>      "application/zip",
873
  ".mp3"          =>      "audio/mpeg",
874
  ".m3u"          =>      "audio/x-mpegurl",
875
  ".wma"          =>      "audio/x-ms-wma",
876
  ".wax"          =>      "audio/x-ms-wax",
877
  ".ogg"          =>      "audio/x-wav",
878
  ".wav"          =>      "audio/x-wav",
879
  ".gif"          =>      "image/gif",
880
  ".jpg"          =>      "image/jpeg",
881
  ".jpeg"         =>      "image/jpeg",
882
  ".png"          =>      "image/png",
883
  ".xbm"          =>      "image/x-xbitmap",
884
  ".xpm"          =>      "image/x-xpixmap",
885
  ".xwd"          =>      "image/x-xwindowdump",
886
  ".css"          =>      "text/css",
887
  ".html"         =>      "text/html",
888
  ".htm"          =>      "text/html",
889
  ".js"           =>      "text/javascript",
890
  ".asc"          =>      "text/plain",
891
  ".c"            =>      "text/plain",
892
  ".conf"         =>      "text/plain",
893
  ".text"         =>      "text/plain",
894
  ".txt"          =>      "text/plain",
895
  ".dtd"          =>      "text/xml",
896
  ".xml"          =>      "text/xml",
897
  ".mpeg"         =>      "video/mpeg",
898
  ".mpg"          =>      "video/mpeg",
899
  ".mov"          =>      "video/quicktime",
900
  ".qt"           =>      "video/quicktime",
901
  ".avi"          =>      "video/x-msvideo",
902
  ".asf"          =>      "video/x-ms-asf",
903
  ".asx"          =>      "video/x-ms-asf",
904
  ".wmv"          =>      "video/x-ms-wmv",
905
  ".bz2"          =>      "application/x-bzip",
906
  ".tbz"          =>      "application/x-bzip-compressed-tar",
907
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
908
 )
909

    
910
# Use the "Content-Type" extended attribute to obtain mime type if possible
911
#mimetypes.use-xattr        = "enable"
912

    
913
#### accesslog module
914
#accesslog.filename          = "/dev/null"
915

    
916
## deny access the file-extensions
917
#
918
# ~    is for backupfiles from vi, emacs, joe, ...
919
# .inc is often used for code includes which should in general not be part
920
#      of the document-root
921
url.access-deny             = ( "~", ".inc" )
922

    
923

    
924
######### Options that are good to be but not neccesary to be changed #######
925

    
926
## bind to port (default: 80)
927
server.port                = {$lighty_port}
928

    
929
## error-handler for status 404
930
#server.error-handler-404   = "/error-handler.html"
931
#server.error-handler-404   = "/error-handler.php"
932

    
933
## to help the rc.scripts
934
server.pid-file            = "/var/run/{$pid_file}"
935

    
936
## virtual directory listings
937
server.dir-listing         = "disable"
938

    
939
## enable debugging
940
debug.log-request-header   = "disable"
941
debug.log-response-header  = "disable"
942
debug.log-request-handling = "disable"
943
debug.log-file-not-found   = "disable"
944

    
945
#### compress module
946
#compress.cache-dir         = "/tmp/lighttpd/cache/compress/"
947
#compress.filetype          = ("text/plain", "text/html")
948

    
949
#server.network-backend = "writev"
950

    
951
{$server_upload_dirs}
952

    
953
{$server_max_request_size}
954

    
955
{$fastcgi_config}
956

    
957
{$cgi_config}
958

    
959
{$captive_portal_mod_evasive}
960

    
961
EOD;
962

    
963
	$cert = str_replace("\r", "", $cert);
964
	$key = str_replace("\r", "", $key);
965

    
966
	$cert = str_replace("\n\n", "\n", $cert);
967
	$key = str_replace("\n\n", "\n", $key);
968

    
969
	if($cert <> "" and $key <> "") {
970
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
971
		if (!$fd) {
972
			printf("Error: cannot open cert.pem in system_webgui_start().\n");
973
			return 1;
974
		}
975
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
976
		fwrite($fd, $cert);
977
		fwrite($fd, "\n");
978
		fwrite($fd, $key);
979
		fclose($fd);
980
		$lighty_config .= "\n";
981
		$lighty_config .= "## ssl configuration\n";
982
		$lighty_config .= "ssl.engine = \"enable\"\n";
983
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
984
	}
985

    
986
	$fd = fopen("{$filename}", "w");
987
	if (!$fd) {
988
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
989
		return 1;
990
	}
991
	fwrite($fd, $lighty_config);
992
	fclose($fd);
993

    
994
	return 0;
995

    
996
}
997

    
998
function system_password_configure() {
999
	global $config, $g;
1000
	if(isset($config['system']['developerspew'])) {
1001
		$mt = microtime();
1002
		echo "system_password_configure() being called $mt\n";
1003
	}
1004

    
1005
	/* sync passwords */
1006
	sync_webgui_passwords();
1007

    
1008
	/* !NOTE! conf_mount_ro is done by sync_webgui_passwords() */
1009

    
1010
	return 0;
1011
}
1012

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

    
1020
	$syscfg = $config['system'];
1021

    
1022
	if ($g['booting'])
1023
		echo "Setting timezone...";
1024

    
1025
	/* extract appropriate timezone file */
1026
	$timezone = $syscfg['timezone'];
1027
	if (!$timezone)
1028
		$timezone = "Etc/UTC";
1029

    
1030
	conf_mount_rw();
1031

    
1032
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1033
		escapeshellarg($timezone) . " > /etc/localtime");
1034

    
1035
	mwexec("sync");
1036
	conf_mount_ro();
1037

    
1038
	if ($g['booting'])
1039
		echo "done.\n";
1040
}
1041

    
1042
function system_ntp_configure() {
1043
	global $config, $g;
1044

    
1045
	$syscfg = $config['system'];
1046

    
1047
	if (!$config['installedpackages']['openntpd'])
1048
		return;
1049

    
1050
	/* open configuration for wrting or bail */
1051
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1052
	if(!$fd) {
1053
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1054
		return;
1055
	}
1056

    
1057
	fwrite($fd, "# \n");
1058
	fwrite($fd, "# pfSense OpenNTPD configuration file \n");
1059
	fwrite($fd, "# \n\n");
1060

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

    
1065
	/* Setup listener(s) if the user has configured one */
1066
        if ($config['installedpackages']['openntpd']) {
1067
    		/* server config is in coregui1 */
1068
		$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
1069
		if ($xmlsettings['enable'] == 'on') {
1070
			$ifaces = explode(',', $xmlsettings['interface']);
1071
			$ifaces = array_map('convert_friendly_interface_to_real_interface_name', $ifaces);
1072
			$ifaces = array_filter($ifaces, 'does_interface_exist');
1073
			$ips = array_map('find_interface_ip', $ifaces);
1074
			foreach ($ips as $ip) {
1075
				if (is_ipaddr($ip))
1076
					fwrite($fd, "listen on $ip\n");
1077
			}
1078
		}
1079
	}
1080

    
1081
	fwrite($fd, "\n");
1082

    
1083
	/* slurp! */
1084
	fclose($fd);
1085

    
1086
	/* if openntpd is running, kill it */
1087
	while(is_process_running("ntpd")) {
1088
		exec("/usr/bin/killall ntpd");
1089
		sleep(3);
1090
	}
1091

    
1092
	/* if /var/empty does not exist, create it */
1093
	if(!is_dir("/var/empty"))
1094
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1095

    
1096
	sleep(1);
1097

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

    
1101
}
1102

    
1103
function sync_system_time() {
1104
	global $config, $g;
1105

    
1106
	$syscfg = $config['system'];
1107

    
1108
	if ($g['booting'])
1109
		echo "Syncing system time before startup...";
1110

    
1111
	/* foreach through servers and write out to ntpd.conf */
1112
	foreach (explode(' ', $syscfg['timeservers']) as $ts) {
1113
		mwexec("/usr/sbin/ntpdate -s $ts");
1114
	}
1115
	
1116
	if ($g['booting'])
1117
		echo "done.\n";
1118
	
1119
}
1120

    
1121
function system_halt() {
1122
	global $g;
1123

    
1124
	system_reboot_cleanup();
1125

    
1126
	mwexec("nohup /etc/rc.halt > /dev/null 2>&1 &");
1127
}
1128

    
1129
function system_reboot() {
1130
	global $g;
1131

    
1132
	system_reboot_cleanup();
1133

    
1134
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1135
}
1136

    
1137
function system_reboot_sync() {
1138
	global $g;
1139

    
1140
	system_reboot_cleanup();
1141

    
1142
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1143
}
1144

    
1145
function system_reboot_cleanup() {
1146
	mwexec("/usr/local/bin/beep.sh stop");
1147
	captiveportal_radius_stop_all();
1148
}
1149

    
1150
function system_do_shell_commands($early = 0) {
1151
	global $config, $g;
1152
	if(isset($config['system']['developerspew'])) {
1153
		$mt = microtime();
1154
		echo "system_do_shell_commands() being called $mt\n";
1155
	}
1156

    
1157
	if ($early)
1158
		$cmdn = "earlyshellcmd";
1159
	else
1160
		$cmdn = "shellcmd";
1161

    
1162
	if (is_array($config['system'][$cmdn])) {
1163

    
1164
		/* *cmd is an array, loop through */
1165
		foreach ($config['system'][$cmdn] as $cmd) {
1166
			exec($cmd);
1167
		}
1168

    
1169
	} elseif($config['system'][$cmdn] <> "") {
1170

    
1171
		/* execute single item */
1172
		exec($config['system'][$cmdn]);
1173

    
1174
	}
1175
}
1176

    
1177
function system_console_configure() {
1178
	global $config, $g;
1179
	if(isset($config['system']['developerspew'])) {
1180
		$mt = microtime();
1181
		echo "system_console_configure() being called $mt\n";
1182
	}
1183

    
1184
	if (isset($config['system']['disableconsolemenu'])) {
1185
		touch("{$g['varetc_path']}/disableconsole");
1186
	} else {
1187
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1188
	}
1189
}
1190

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

    
1198
	$dmesg = "";
1199
	exec("/sbin/dmesg", $dmesg);
1200

    
1201
	/* find last copyright line (output from previous boots may be present) */
1202
	$lastcpline = 0;
1203

    
1204
	for ($i = 0; $i < count($dmesg); $i++) {
1205
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1206
			$lastcpline = $i;
1207
	}
1208

    
1209
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1210
	if (!$fd) {
1211
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1212
		return 1;
1213
	}
1214

    
1215
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1216
		fwrite($fd, $dmesg[$i] . "\n");
1217

    
1218
	fclose($fd);
1219

    
1220
	return 0;
1221
}
1222

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

    
1230
	if (isset($config['system']['harddiskstandby'])) {
1231
		if ($g['booting']) {
1232
			echo 'Setting hard disk standby... ';
1233
		}
1234

    
1235
		$standby = $config['system']['harddiskstandby'];
1236
		// Check for a numeric value
1237
		if (is_numeric($standby)) {
1238
			// Sync the disk(s)
1239
			mwexec('/bin/sync');
1240
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1241
				// Reinitialize ATA-drives
1242
				mwexec('/usr/local/sbin/atareinit');
1243
				if ($g['booting']) {
1244
					echo "done.\n";
1245
				}
1246
			} else if ($g['booting']) {
1247
				echo "failed!\n";
1248
			}
1249
		} else if ($g['booting']) {
1250
			echo "failed!\n";
1251
		}
1252
	}
1253
}
1254

    
1255
function system_setup_sysctl() {
1256
	global $config;
1257
	if(isset($config['system']['developerspew'])) {
1258
		$mt = microtime();
1259
		echo "system_setup_sysctl() being called $mt\n";
1260
	}
1261

    
1262
	activate_sysctls();	
1263

    
1264
	if (isset($config['system']['sharednet'])) {
1265
		system_disable_arp_wrong_if();
1266
	}
1267
}
1268

    
1269
function system_disable_arp_wrong_if() {
1270
	global $config;
1271
	if(isset($config['system']['developerspew'])) {
1272
		$mt = microtime();
1273
		echo "system_disable_arp_wrong_if() being called $mt\n";
1274
	}
1275
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1276
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1277
}
1278

    
1279
function system_enable_arp_wrong_if() {
1280
	global $config;
1281
	if(isset($config['system']['developerspew'])) {
1282
		$mt = microtime();
1283
		echo "system_enable_arp_wrong_if() being called $mt\n";
1284
	}
1285
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1286
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1287
}
1288

    
1289
function enable_watchdog() {
1290
	global $config;
1291
	$install_watchdog = false;
1292
	$supported_watchdogs = array("Geode");
1293
	$file = file_get_contents("/var/log/dmesg.boot");
1294
	foreach($supported_watchdogs as $sd) {
1295
		if(stristr($file, "Geode")) {
1296
			$install_watchdog = true;
1297
		}
1298
	}
1299
	if($install_watchdog == true) {
1300
		if(is_process_running("watchdogd"))
1301
			exec("/usr/bin/killall watchdogd");
1302
		exec("/usr/sbin/watchdogd");
1303
	}
1304
}
1305

    
1306
?>
(24-24/31)