Project

General

Profile

Download (36.2 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'])) 
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
	chdir($g['www_path']);
498

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

    
505
	if ($config['system']['webgui']['protocol'] == "https") {
506

    
507
	if(!$config['system']['webgui']['port'])
508
		$portarg = "443";
509

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

    
536
EOD;
537

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

    
555
EOD;
556
		}
557
	} else {
558
		$cert = "";
559
		$key = "";
560
	}
561

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

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

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

    
576
	return $res;
577
}
578

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

    
586
        if ($g['booting'])
587
                echo "Starting webConfigurator...";
588

    
589
        /* kill any running mini_httpd */
590
        killbypid("{$g['varrun_path']}/mini_httpd.pid");
591

    
592
        chdir($g['www_path']);
593

    
594
        /* non-standard port? */
595
        if ($config['system']['webgui']['port'])
596
                $portarg = "-p {$config['system']['webgui']['port']}";
597
        else
598
                $portarg = "";
599

    
600
        if ($config['system']['webgui']['protocol'] == "https") {
601

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

    
620
EOD;
621

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

    
639
EOD;
640
                }
641

    
642
				$cert = str_replace("\r", "", $cert);
643
				$key = str_replace("\r", "", $key);
644

    
645
                $fd = fopen("{$g['varetc_path']}/cert.pem", "w");
646
                if (!$fd) {
647
                        printf("Error: cannot open cert.pem in system_webgui_start().\n");
648
                        return 1;
649
                }
650
                chmod("{$g['varetc_path']}/cert.pem", 0600);
651
                fwrite($fd, $cert);
652
                fwrite($fd, "\n");
653
                fwrite($fd, $key);
654
                fclose($fd);
655

    
656
                $res = mwexec("/usr/local/sbin/mini_httpd -S -E {$g['varetc_path']}/cert.pem" .
657
                        " -c \"**.php|**.cgi\" -u root -maxproc 16 $portarg" .
658
                        " -i {$g['varrun_path']}/mini_httpd.pid");
659
        } else {
660
                $res = mwexec("/usr/local/sbin/mini_httpd -c \"**.php|**.cgi\" -u root" .
661
                        " -maxproc 16 $portarg -i {$g['varrun_path']}/mini_httpd.pid");
662
        }
663

    
664
        if ($g['booting']) {
665
                if ($res == 0)
666
                        echo "done\n";
667
                else
668
                        echo "failed\n";
669
        }
670

    
671
        return $res;
672
}
673

    
674
function system_generate_lighty_config($filename,
675
	$cert,
676
	$key,
677
	$pid_file,
678
	$port = 80,
679
	$document_root = "/usr/local/www/",
680
	$cert_location = "cert.pem",
681
	$max_procs = 2,
682
	$max_requests = "1",
683
	$fast_cgi_enable = true,
684
	$captive_portal = false) {
685

    
686
	global $config, $g;
687

    
688
	if(isset($config['system']['developerspew'])) {
689
		$mt = microtime();
690
		echo "system_generate_lighty_config() being called $mt\n";
691
	}
692

    
693
	if($captive_portal == true)  {
694
		$captiveportal = ",\"mod_rewrite\"";
695
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?redirurl=$1\" )\n";
696
		$captive_portal_module = "\"mod_accesslog\", ";
697
		$maxprocperip = $config['captiveportal']['maxprocperip'];
698
		if(!$maxprocperip and $maxprocperip > 0)
699
			$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
700
		else
701
			$captive_portal_mod_evasive = "";
702
		$server_upload_dirs = "server.upload-dirs = ( \"/tmp/captiveportal/\" )\n";
703
		exec("mkdir -p /tmp/captiveportal");
704
		exec("chmod a-w /tmp/captiveportal");
705
		$server_max_request_size = "server.max-request-size    = 384";
706
	} else {
707
		$captive_portal_module = "";
708
		$captive_portal_mod_evasive = "";
709
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"/tmp/\", \"/var/\" )\n";
710
		$server_max_request_size = "server.max-request-size    = 2097152";
711
	}
712
	
713
	if($port <> "")
714
		$lighty_port = $port;
715
	else
716
		$lighty_port = "80";
717

    
718
	$memory = get_memory();
719
	$avail = $memory[0];
720

    
721
	if($avail > 0 and $avail < 98) {
722
		$max_procs = 1;
723
		$max_requests = 1;
724
	}
725

    
726
	if($avail > 97 and $avail < 128) {
727
		$max_procs = 1;
728
		$max_requests = 3;
729
	}
730

    
731
	if($avail > 127 and $avail < 256) {
732
		$max_procs = 1;
733
		$max_requests = 5;
734
	}
735

    
736
	if($avail > 255 and $avail < 384) {
737
		$max_procs = 3;
738
		$max_requests = 10;
739
	}
740

    
741
	if($avail > 383 and $avail < 512) {
742
		$max_procs = 4;
743
		$max_requests = 16;
744
	}
745

    
746
	if($captive_portal == true)  {	
747
		$bin_environment =  <<<EOC
748
        "bin-environment" => (
749
           "PHP_FCGI_CHILDREN" => "16",
750
           "PHP_FCGI_MAX_REQUESTS" => "{$max_requests}"
751
        ), 
752
EOC;
753

    
754
	} else if ($avail > 0 and $avail < 128) {
755
		$bin_environment = <<<EOC
756
	"bin-environment" => (
757
		"PHP_FCGI_CHILDREN" => "1",
758
		"PHP_FCGI_MAX_REQUESTS" => "{$max_requests}"
759
	),
760

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

    
783
#### CGI module
784
cgi.assign                 = ( ".cgi" => "" )
785

    
786
EOD;
787
	} else {
788
		$fastcgi_config = "";
789
		$module = "\"mod_cgi\"";
790
		$cgi_config = <<<EOD
791
#### CGI module
792
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
793
                               ".cgi" => "" )
794

    
795
EOD;
796
	}
797

    
798
	$lighty_config .= <<<EOD
799
#
800
# lighttpd configuration file
801
#
802
# use a it as base for lighttpd 1.0.0 and above
803
#
804
############ Options you really have to take care of ####################
805

    
806
## FreeBSD!
807
server.event-handler		= "freebsd-kqueue"
808
server.network-backend		= "writev"  ## Fixes 7.x upload issues
809

    
810
## modules to load
811
server.modules              =   (
812
									{$captive_portal_module}
813
									"mod_access", "mod_accesslog", "mod_expire", "mod_compress",
814
									{$module}{$captiveportal}
815
								)
816

    
817
## Unused modules
818
#                               "mod_setenv",
819
#                               "mod_compress"
820
#				"mod_redirect",
821
#                               "mod_rewrite",
822
#                               "mod_ssi",
823
#                               "mod_usertrack",
824
#                               "mod_expire",
825
#                               "mod_secdownload",
826
#                               "mod_rrdtool",
827
#                               "mod_auth",
828
#                               "mod_status",
829
#                               "mod_alias",
830
#                               "mod_proxy",
831
#                               "mod_simple_vhost",
832
#                               "mod_evhost",
833
#                               "mod_userdir",
834
#                               "mod_cgi",
835
#                                "mod_accesslog"
836

    
837
## a static document-root, for virtual-hosting take look at the
838
## server.virtual-* options
839
server.document-root        = "{$document_root}"
840
{$captive_portal_rewrite}
841

    
842
## where to send error-messages to
843
server.errorlog             = "/var/log/lighttpd.error.log"
844

    
845
# files to check for if .../ is requested
846
server.indexfiles           = ( "index.php", "index.html",
847
                                "index.htm", "default.htm" )
848

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

    
902
# Use the "Content-Type" extended attribute to obtain mime type if possible
903
#mimetypes.use-xattr        = "enable"
904

    
905
#### accesslog module
906
#accesslog.filename          = "/dev/null"
907

    
908
## deny access the file-extensions
909
#
910
# ~    is for backupfiles from vi, emacs, joe, ...
911
# .inc is often used for code includes which should in general not be part
912
#      of the document-root
913
url.access-deny             = ( "~", ".inc" )
914

    
915

    
916
######### Options that are good to be but not neccesary to be changed #######
917

    
918
## bind to port (default: 80)
919
server.port                = {$lighty_port}
920

    
921
## error-handler for status 404
922
#server.error-handler-404   = "/error-handler.html"
923
#server.error-handler-404   = "/error-handler.php"
924

    
925
## to help the rc.scripts
926
server.pid-file            = "/var/run/{$pid_file}"
927

    
928
## virtual directory listings
929
server.dir-listing         = "disable"
930

    
931
## enable debugging
932
debug.log-request-header   = "disable"
933
debug.log-response-header  = "disable"
934
debug.log-request-handling = "disable"
935
debug.log-file-not-found   = "disable"
936

    
937
{$server_upload_dirs}
938

    
939
{$server_max_request_size}
940

    
941
{$fastcgi_config}
942

    
943
{$cgi_config}
944

    
945
{$captive_portal_mod_evasive}
946

    
947
# Turn on Lighty caching directives
948
compress.cache-dir         = "/tmp/"
949
compress.filetype          = ("text/plain", "text/html", "text/javascript", "text/css")
950

    
951
expire.url = (
952
				"" => "access 50 hours",	
953
        )
954

    
955
EOD;
956

    
957
	$cert = str_replace("\r", "", $cert);
958
	$key = str_replace("\r", "", $key);
959

    
960
	$cert = str_replace("\n\n", "\n", $cert);
961
	$key = str_replace("\n\n", "\n", $key);
962

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

    
980
	$fd = fopen("{$filename}", "w");
981
	if (!$fd) {
982
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
983
		return 1;
984
	}
985
	fwrite($fd, $lighty_config);
986
	fclose($fd);
987

    
988
	return 0;
989

    
990
}
991

    
992
function system_timezone_configure() {
993
	global $config, $g;
994
	if(isset($config['system']['developerspew'])) {
995
		$mt = microtime();
996
		echo "system_timezone_configure() being called $mt\n";
997
	}
998

    
999
	$syscfg = $config['system'];
1000

    
1001
	if ($g['booting'])
1002
		echo "Setting timezone...";
1003

    
1004
	/* extract appropriate timezone file */
1005
	$timezone = $syscfg['timezone'];
1006
	if (!$timezone)
1007
		$timezone = "Etc/UTC";
1008

    
1009
	conf_mount_rw();
1010

    
1011
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1012
		escapeshellarg($timezone) . " > /etc/localtime");
1013

    
1014
	mwexec("sync");
1015
	conf_mount_ro();
1016

    
1017
	if ($g['booting'])
1018
		echo "done.\n";
1019
}
1020

    
1021
function system_ntp_configure() {
1022
	global $config, $g;
1023

    
1024
	$syscfg = $config['system'];
1025

    
1026
	if (!$config['installedpackages']['openntpd'])
1027
		return;
1028

    
1029
	/* open configuration for wrting or bail */
1030
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1031
	if(!$fd) {
1032
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1033
		return;
1034
	}
1035

    
1036
	fwrite($fd, "# \n");
1037
	fwrite($fd, "# pfSense OpenNTPD configuration file \n");
1038
	fwrite($fd, "# \n\n");
1039

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

    
1044
	/* Setup listener(s) if the user has configured one */
1045
        if ($config['installedpackages']['openntpd']) {
1046
    		/* server config is in coregui1 */
1047
		$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
1048
		if ($xmlsettings['enable'] == 'on') {
1049
			$ifaces = explode(',', $xmlsettings['interface']);
1050
			$ifaces = array_map('convert_friendly_interface_to_real_interface_name', $ifaces);
1051
			$ifaces = array_filter($ifaces, 'does_interface_exist');
1052
			$ips = array_map('find_interface_ip', $ifaces);
1053
			foreach ($ips as $ip) {
1054
				if (is_ipaddr($ip))
1055
					fwrite($fd, "listen on $ip\n");
1056
			}
1057
		}
1058
	}
1059

    
1060
	fwrite($fd, "\n");
1061

    
1062
	/* slurp! */
1063
	fclose($fd);
1064

    
1065
	/* if openntpd is running, kill it */
1066
	while(is_process_running("ntpd")) {
1067
		exec("/usr/bin/killall ntpd");
1068
		sleep(3);
1069
	}
1070

    
1071
	/* if /var/empty does not exist, create it */
1072
	if(!is_dir("/var/empty"))
1073
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1074

    
1075
	sleep(1);
1076

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

    
1080
}
1081

    
1082
function sync_system_time() {
1083
	global $config, $g;
1084

    
1085
	$syscfg = $config['system'];
1086

    
1087
	if ($g['booting'])
1088
		echo "Syncing system time before startup...";
1089

    
1090
	/* foreach through servers and write out to ntpd.conf */
1091
	foreach (explode(' ', $syscfg['timeservers']) as $ts) {
1092
		mwexec("/usr/sbin/ntpdate -s $ts");
1093
	}
1094
	
1095
	if ($g['booting'])
1096
		echo "done.\n";
1097
	
1098
}
1099

    
1100
function system_halt() {
1101
	global $g;
1102

    
1103
	system_reboot_cleanup();
1104

    
1105
	mwexec("nohup /etc/rc.halt > /dev/null 2>&1 &");
1106
}
1107

    
1108
function system_reboot() {
1109
	global $g;
1110

    
1111
	system_reboot_cleanup();
1112

    
1113
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1114
}
1115

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

    
1119
	system_reboot_cleanup();
1120

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

    
1124
function system_reboot_cleanup() {
1125
	mwexec("/usr/local/bin/beep.sh stop");
1126
	captiveportal_radius_stop_all();
1127
}
1128

    
1129
function system_do_shell_commands($early = 0) {
1130
	global $config, $g;
1131
	if(isset($config['system']['developerspew'])) {
1132
		$mt = microtime();
1133
		echo "system_do_shell_commands() being called $mt\n";
1134
	}
1135

    
1136
	if ($early)
1137
		$cmdn = "earlyshellcmd";
1138
	else
1139
		$cmdn = "shellcmd";
1140

    
1141
	if (is_array($config['system'][$cmdn])) {
1142

    
1143
		/* *cmd is an array, loop through */
1144
		foreach ($config['system'][$cmdn] as $cmd) {
1145
			exec($cmd);
1146
		}
1147

    
1148
	} elseif($config['system'][$cmdn] <> "") {
1149

    
1150
		/* execute single item */
1151
		exec($config['system'][$cmdn]);
1152

    
1153
	}
1154
}
1155

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

    
1163
	if (isset($config['system']['disableconsolemenu'])) {
1164
		touch("{$g['varetc_path']}/disableconsole");
1165
	} else {
1166
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1167
	}
1168
}
1169

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

    
1177
	$dmesg = "";
1178
	exec("/sbin/dmesg", $dmesg);
1179

    
1180
	/* find last copyright line (output from previous boots may be present) */
1181
	$lastcpline = 0;
1182

    
1183
	for ($i = 0; $i < count($dmesg); $i++) {
1184
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1185
			$lastcpline = $i;
1186
	}
1187

    
1188
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1189
	if (!$fd) {
1190
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1191
		return 1;
1192
	}
1193

    
1194
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1195
		fwrite($fd, $dmesg[$i] . "\n");
1196

    
1197
	fclose($fd);
1198

    
1199
	return 0;
1200
}
1201

    
1202
function system_set_harddisk_standby() {
1203
	global $g, $config;
1204
	if(isset($config['system']['developerspew'])) {
1205
		$mt = microtime();
1206
		echo "system_set_harddisk_standby() being called $mt\n";
1207
	}
1208

    
1209
	if (isset($config['system']['harddiskstandby'])) {
1210
		if ($g['booting']) {
1211
			echo 'Setting hard disk standby... ';
1212
		}
1213

    
1214
		$standby = $config['system']['harddiskstandby'];
1215
		// Check for a numeric value
1216
		if (is_numeric($standby)) {
1217
			// Sync the disk(s)
1218
			mwexec('/bin/sync');
1219
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1220
				// Reinitialize ATA-drives
1221
				mwexec('/usr/local/sbin/atareinit');
1222
				if ($g['booting']) {
1223
					echo "done.\n";
1224
				}
1225
			} else if ($g['booting']) {
1226
				echo "failed!\n";
1227
			}
1228
		} else if ($g['booting']) {
1229
			echo "failed!\n";
1230
		}
1231
	}
1232
}
1233

    
1234
function system_setup_sysctl() {
1235
	global $config;
1236
	if(isset($config['system']['developerspew'])) {
1237
		$mt = microtime();
1238
		echo "system_setup_sysctl() being called $mt\n";
1239
	}
1240

    
1241
	activate_sysctls();	
1242

    
1243
	if (isset($config['system']['sharednet'])) {
1244
		system_disable_arp_wrong_if();
1245
	}
1246
}
1247

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

    
1258
function system_enable_arp_wrong_if() {
1259
	global $config;
1260
	if(isset($config['system']['developerspew'])) {
1261
		$mt = microtime();
1262
		echo "system_enable_arp_wrong_if() being called $mt\n";
1263
	}
1264
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1265
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1266
}
1267

    
1268
function enable_watchdog() {
1269
	global $config;
1270
	$install_watchdog = false;
1271
	$supported_watchdogs = array("Geode");
1272
	$file = file_get_contents("/var/log/dmesg.boot");
1273
	foreach($supported_watchdogs as $sd) {
1274
		if(stristr($file, "Geode")) {
1275
			$install_watchdog = true;
1276
		}
1277
	}
1278
	if($install_watchdog == true) {
1279
		if(is_process_running("watchdogd"))
1280
			exec("/usr/bin/killall watchdogd");
1281
		exec("/usr/sbin/watchdogd");
1282
	}
1283
}
1284

    
1285
?>
(30-30/37)