Project

General

Profile

Download (36.6 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
	foreach ($config['sysctl']['item'] as $tunable) {
38
		mwexec("sysctl " . $tunable['tunable'] . "=\"" . $tunable['value'] .  "\"");
39
	}
40
}
41

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

    
49
        $syscfg = $config['system'];
50

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

    
57
        $resolvconf = "domain {$syscfg['domain']}\n";
58

    
59
        $havedns = false;
60

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

    
80
        fwrite($fd, $resolvconf);
81
        fclose($fd);
82

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

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

    
102
        return 0;
103
}
104

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

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

    
132
	$syscfg = $config['system'];
133
	$lancfg = $config['interfaces']['lan'];
134
	$dnsmasqcfg = $config['dnsmasq'];
135

    
136
	if (!is_array($dnsmasqcfg['hosts'])) {
137
		$dnsmasqcfg['hosts'] = array();
138
	}
139
	$hostscfg = $dnsmasqcfg['hosts'];
140

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

    
147
	$hosts = <<<EOD
148
127.0.0.1	localhost localhost.{$syscfg['domain']}
149
{$lancfg['ipaddr']}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}
150

    
151
EOD;
152

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

    
169
	return 0;
170
}
171

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

    
179
	$syscfg = $config['system'];
180

    
181
	/* set hostname */
182
	return mwexec("/bin/hostname " .
183
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
184
}
185

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

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

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

    
213
	/* if list */
214
	if ($config['interfaces']['lan']) {
215
		$iflist = array("lan", "wan");	
216
	} else {
217
		$iflist = array("wan");
218
	}
219
	
220
	for ($i = 1; isset($config['interfaces']['opt' . $i]['enable']); $i++)
221
		$iflist['opt' . $i] = "opt{$i}";
222

    
223
	$dont_remove_route = false;
224
	foreach ($iflist as $ifent => $ifname) {
225
		/* do not process interfaces that will end up with gateways */
226
		if($config['interfaces'][$ifname]['ipaddr'] == "dhcp" or
227
			$config['interfaces'][$ifname]['ipaddr'] == "bigpond" or
228
			$config['interfaces'][$ifname]['ipaddr'] == "pppoe" or
229
			$config['interfaces'][$ifname]['ipaddr'] == "pptp")
230
			$dont_remove_route = true;
231
	}
232

    
233
	if($dont_remove_route == false) {
234
		/* remove default route */
235
		mwexec("/sbin/route delete default");
236
	}
237

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

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

    
271
	if (is_array($config['staticroutes']['route'])) {
272

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

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

    
299
		fclose($fd);
300
	}
301

    
302
	return 0;
303
}
304

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

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

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

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

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

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

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

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

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

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

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

    
398
EOD;
399
		}
400

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

    
405
EOD;
406
		}
407

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

    
412
EOD;
413
		}
414

    
415

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

    
420
EOD;
421
		}
422

    
423

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

    
428
EOD;
429
		}
430

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

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

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

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

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

    
457
	return $retval;
458
}
459

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

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

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

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

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

    
483
	return $res;
484
}
485

    
486

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

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

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

    
496
	sleep(1);
497

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

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

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

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

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

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

    
540
EOD;
541

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

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

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

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

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

    
580
	return $res;
581
}
582

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

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

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

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

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

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

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

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

    
627
EOD;
628

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

    
646
EOD;
647
                }
648

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

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

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

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

    
678
        return $res;
679
}
680

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

    
693
	global $config, $g;
694

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

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

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

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

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

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

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

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

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

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

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

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

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

    
803
EOD;
804
	}
805

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

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

    
817
{$network_handler}
818

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

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

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

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

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

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

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

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

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

    
924

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

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

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

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

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

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

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

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

    
952
{$server_upload_dirs}
953

    
954
{$server_max_request_size}
955

    
956
{$fastcgi_config}
957

    
958
{$cgi_config}
959

    
960
{$captive_portal_mod_evasive}
961

    
962
EOD;
963

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

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

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

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

    
995
	return 0;
996

    
997
}
998

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

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

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

    
1011
	return 0;
1012
}
1013

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

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

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

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

    
1031
	conf_mount_rw();
1032

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

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

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

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

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

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

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

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

    
1063
    /* server config is in coregui1 */
1064
	$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
1065
	if ($xmlsettings['enable'] == 'on') {
1066
		$ifaces = explode(',', $xmlsettings['interface']);
1067
		$ifaces = array_map('convert_friendly_interface_to_real_interface_name', $ifaces);
1068
		$ifaces = array_filter($ifaces, 'does_interface_exist');
1069
		$ips = array_map('find_interface_ip', $ifaces);
1070
		foreach ($ips as $ip) {
1071
			if (is_ipaddr($ip))
1072
				fwrite($fd, "listen on $ip\n");
1073
		}
1074
	}
1075

    
1076
	fwrite($fd, "\n");
1077

    
1078
	/* slurp! */
1079
	fclose($fd);
1080

    
1081
	/* if openntpd is running, kill it */
1082
	while(is_process_running("ntpd")) {
1083
		exec("/usr/bin/killall ntpd");
1084
		sleep(3);
1085
	}
1086

    
1087
	/* if /var/empty does not exist, create it */
1088
	if(!is_dir("/var/empty"))
1089
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1090

    
1091
	sleep(1);
1092

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

    
1096
}
1097

    
1098
function sync_system_time() {
1099
	global $config, $g;
1100

    
1101
	$syscfg = $config['system'];
1102

    
1103
	if ($g['booting'])
1104
		echo "Syncing system time before startup...";
1105

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

    
1116
function system_halt() {
1117
	global $g;
1118

    
1119
	system_reboot_cleanup();
1120

    
1121
	mwexec("nohup /etc/rc.halt > /dev/null 2>&1 &");
1122
}
1123

    
1124
function system_reboot() {
1125
	global $g;
1126

    
1127
	system_reboot_cleanup();
1128

    
1129
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1130
}
1131

    
1132
function system_reboot_sync() {
1133
	global $g;
1134

    
1135
	system_reboot_cleanup();
1136

    
1137
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1138
}
1139

    
1140
function system_reboot_cleanup() {
1141
	mwexec("/usr/local/bin/beep.sh stop");
1142
	captiveportal_radius_stop_all();
1143
}
1144

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

    
1152
	if ($early)
1153
		$cmdn = "earlyshellcmd";
1154
	else
1155
		$cmdn = "shellcmd";
1156

    
1157
	if (is_array($config['system'][$cmdn])) {
1158

    
1159
		/* *cmd is an array, loop through */
1160
		foreach ($config['system'][$cmdn] as $cmd) {
1161
			exec($cmd);
1162
		}
1163

    
1164
	} elseif($config['system'][$cmdn] <> "") {
1165

    
1166
		/* execute single item */
1167
		exec($config['system'][$cmdn]);
1168

    
1169
	}
1170
}
1171

    
1172
function system_console_configure() {
1173
	global $config, $g;
1174
	if(isset($config['system']['developerspew'])) {
1175
		$mt = microtime();
1176
		echo "system_console_configure() being called $mt\n";
1177
	}
1178

    
1179
	if (isset($config['system']['disableconsolemenu'])) {
1180
		touch("{$g['varetc_path']}/disableconsole");
1181
	} else {
1182
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1183
	}
1184
}
1185

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

    
1193
	$dmesg = "";
1194
	exec("/sbin/dmesg", $dmesg);
1195

    
1196
	/* find last copyright line (output from previous boots may be present) */
1197
	$lastcpline = 0;
1198

    
1199
	for ($i = 0; $i < count($dmesg); $i++) {
1200
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1201
			$lastcpline = $i;
1202
	}
1203

    
1204
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1205
	if (!$fd) {
1206
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1207
		return 1;
1208
	}
1209

    
1210
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1211
		fwrite($fd, $dmesg[$i] . "\n");
1212

    
1213
	fclose($fd);
1214

    
1215
	return 0;
1216
}
1217

    
1218
function system_set_harddisk_standby() {
1219
	global $g, $config;
1220
	if(isset($config['system']['developerspew'])) {
1221
		$mt = microtime();
1222
		echo "system_set_harddisk_standby() being called $mt\n";
1223
	}
1224

    
1225
	if (isset($config['system']['harddiskstandby'])) {
1226
		if ($g['booting']) {
1227
			echo 'Setting hard disk standby... ';
1228
		}
1229

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

    
1250
function system_setup_sysctl() {
1251
	global $config;
1252
	if(isset($config['system']['developerspew'])) {
1253
		$mt = microtime();
1254
		echo "system_setup_sysctl() being called $mt\n";
1255
	}
1256

    
1257
	activate_sysctls();	
1258

    
1259
	if (isset($config['system']['sharednet'])) {
1260
		system_disable_arp_wrong_if();
1261
	}
1262
}
1263

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

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

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

    
1301
?>
(22-22/29)