Project

General

Profile

Download (36.9 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
	/* 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 = 1;
742
		$max_requests = 3;
743
	}
744

    
745
	if($avail > 127 and $avail < 256) {
746
		$max_procs = 1;
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 if ($avail > 0 and $avail < 128) {
769
		$bin_environment = <<<EOC
770
	"bin-environment" => (
771
		"PHP_FCGI_CHILDREN" => "1",
772
		"PHP_FCGI_MAX_REQUESTS" => "{$max_requests}"
773
	),
774

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

    
797
#### CGI module
798
cgi.assign                 = ( ".cgi" => "" )
799

    
800
EOD;
801
	} else {
802
		$fastcgi_config = "";
803
		$module = "\"mod_cgi\"";
804
		$cgi_config = <<<EOD
805
#### CGI module
806
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
807
                               ".cgi" => "" )
808

    
809
EOD;
810
	}
811

    
812
	$lighty_config .= <<<EOD
813
#
814
# lighttpd configuration file
815
#
816
# use a it as base for lighttpd 1.0.0 and above
817
#
818
############ Options you really have to take care of ####################
819

    
820
## FreeBSD!
821
server.event-handler		= "freebsd-kqueue"
822

    
823
{$network_handler}
824

    
825
## modules to load
826
server.modules              =   (
827
				  {$captive_portal_module}
828
				  "mod_access", "mod_accesslog",
829
                                  {$module}{$captiveportal}
830
				)
831

    
832
## Unused modules
833
#                               "mod_setenv",
834
#                               "mod_compress"
835
#				"mod_redirect",
836
#                               "mod_rewrite",
837
#                               "mod_ssi",
838
#                               "mod_usertrack",
839
#                               "mod_expire",
840
#                               "mod_secdownload",
841
#                               "mod_rrdtool",
842
#                               "mod_auth",
843
#                               "mod_status",
844
#                               "mod_alias",
845
#                               "mod_proxy",
846
#                               "mod_simple_vhost",
847
#                               "mod_evhost",
848
#                               "mod_userdir",
849
#                               "mod_cgi",
850
#                                "mod_accesslog"
851

    
852
## a static document-root, for virtual-hosting take look at the
853
## server.virtual-* options
854
server.document-root        = "{$document_root}"
855
{$captive_portal_rewrite}
856

    
857
## where to send error-messages to
858
server.errorlog             = "/var/log/lighttpd.error.log"
859

    
860
# files to check for if .../ is requested
861
server.indexfiles           = ( "index.php", "index.html",
862
                                "index.htm", "default.htm" )
863

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

    
917
# Use the "Content-Type" extended attribute to obtain mime type if possible
918
#mimetypes.use-xattr        = "enable"
919

    
920
#### accesslog module
921
#accesslog.filename          = "/dev/null"
922

    
923
## deny access the file-extensions
924
#
925
# ~    is for backupfiles from vi, emacs, joe, ...
926
# .inc is often used for code includes which should in general not be part
927
#      of the document-root
928
url.access-deny             = ( "~", ".inc" )
929

    
930

    
931
######### Options that are good to be but not neccesary to be changed #######
932

    
933
## bind to port (default: 80)
934
server.port                = {$lighty_port}
935

    
936
## error-handler for status 404
937
#server.error-handler-404   = "/error-handler.html"
938
#server.error-handler-404   = "/error-handler.php"
939

    
940
## to help the rc.scripts
941
server.pid-file            = "/var/run/{$pid_file}"
942

    
943
## virtual directory listings
944
server.dir-listing         = "disable"
945

    
946
## enable debugging
947
debug.log-request-header   = "disable"
948
debug.log-response-header  = "disable"
949
debug.log-request-handling = "disable"
950
debug.log-file-not-found   = "disable"
951

    
952
#### compress module
953
#compress.cache-dir         = "/tmp/lighttpd/cache/compress/"
954
#compress.filetype          = ("text/plain", "text/html")
955

    
956
#server.network-backend = "writev"
957

    
958
{$server_upload_dirs}
959

    
960
{$server_max_request_size}
961

    
962
{$fastcgi_config}
963

    
964
{$cgi_config}
965

    
966
{$captive_portal_mod_evasive}
967

    
968
EOD;
969

    
970
	$cert = str_replace("\r", "", $cert);
971
	$key = str_replace("\r", "", $key);
972

    
973
	$cert = str_replace("\n\n", "\n", $cert);
974
	$key = str_replace("\n\n", "\n", $key);
975

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

    
993
	$fd = fopen("{$filename}", "w");
994
	if (!$fd) {
995
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
996
		return 1;
997
	}
998
	fwrite($fd, $lighty_config);
999
	fclose($fd);
1000

    
1001
	return 0;
1002

    
1003
}
1004

    
1005
function system_password_configure() {
1006
	global $config, $g;
1007
	if(isset($config['system']['developerspew'])) {
1008
		$mt = microtime();
1009
		echo "system_password_configure() being called $mt\n";
1010
	}
1011

    
1012
	/* sync passwords */
1013
	sync_webgui_passwords();
1014

    
1015
	/* !NOTE! conf_mount_ro is done by sync_webgui_passwords() */
1016

    
1017
	return 0;
1018
}
1019

    
1020
function system_timezone_configure() {
1021
	global $config, $g;
1022
	if(isset($config['system']['developerspew'])) {
1023
		$mt = microtime();
1024
		echo "system_timezone_configure() being called $mt\n";
1025
	}
1026

    
1027
	$syscfg = $config['system'];
1028

    
1029
	if ($g['booting'])
1030
		echo "Setting timezone...";
1031

    
1032
	/* extract appropriate timezone file */
1033
	$timezone = $syscfg['timezone'];
1034
	if (!$timezone)
1035
		$timezone = "Etc/UTC";
1036

    
1037
	conf_mount_rw();
1038

    
1039
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1040
		escapeshellarg($timezone) . " > /etc/localtime");
1041

    
1042
	mwexec("sync");
1043
	conf_mount_ro();
1044

    
1045
	if ($g['booting'])
1046
		echo "done.\n";
1047
}
1048

    
1049
function system_ntp_configure() {
1050
	global $config, $g;
1051

    
1052
	$syscfg = $config['system'];
1053

    
1054
	if (!$config['installedpackages']['openntpd'])
1055
		return;
1056

    
1057
	/* open configuration for wrting or bail */
1058
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1059
	if(!$fd) {
1060
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1061
		return;
1062
	}
1063

    
1064
	fwrite($fd, "# \n");
1065
	fwrite($fd, "# pfSense OpenNTPD configuration file \n");
1066
	fwrite($fd, "# \n\n");
1067

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

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

    
1088
	fwrite($fd, "\n");
1089

    
1090
	/* slurp! */
1091
	fclose($fd);
1092

    
1093
	/* if openntpd is running, kill it */
1094
	while(is_process_running("ntpd")) {
1095
		exec("/usr/bin/killall ntpd");
1096
		sleep(3);
1097
	}
1098

    
1099
	/* if /var/empty does not exist, create it */
1100
	if(!is_dir("/var/empty"))
1101
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1102

    
1103
	sleep(1);
1104

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

    
1108
}
1109

    
1110
function sync_system_time() {
1111
	global $config, $g;
1112

    
1113
	$syscfg = $config['system'];
1114

    
1115
	if ($g['booting'])
1116
		echo "Syncing system time before startup...";
1117

    
1118
	/* foreach through servers and write out to ntpd.conf */
1119
	foreach (explode(' ', $syscfg['timeservers']) as $ts) {
1120
		mwexec("/usr/sbin/ntpdate -s $ts");
1121
	}
1122
	
1123
	if ($g['booting'])
1124
		echo "done.\n";
1125
	
1126
}
1127

    
1128
function system_halt() {
1129
	global $g;
1130

    
1131
	system_reboot_cleanup();
1132

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

    
1136
function system_reboot() {
1137
	global $g;
1138

    
1139
	system_reboot_cleanup();
1140

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

    
1144
function system_reboot_sync() {
1145
	global $g;
1146

    
1147
	system_reboot_cleanup();
1148

    
1149
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1150
}
1151

    
1152
function system_reboot_cleanup() {
1153
	mwexec("/usr/local/bin/beep.sh stop");
1154
	captiveportal_radius_stop_all();
1155
}
1156

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

    
1164
	if ($early)
1165
		$cmdn = "earlyshellcmd";
1166
	else
1167
		$cmdn = "shellcmd";
1168

    
1169
	if (is_array($config['system'][$cmdn])) {
1170

    
1171
		/* *cmd is an array, loop through */
1172
		foreach ($config['system'][$cmdn] as $cmd) {
1173
			exec($cmd);
1174
		}
1175

    
1176
	} elseif($config['system'][$cmdn] <> "") {
1177

    
1178
		/* execute single item */
1179
		exec($config['system'][$cmdn]);
1180

    
1181
	}
1182
}
1183

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

    
1191
	if (isset($config['system']['disableconsolemenu'])) {
1192
		touch("{$g['varetc_path']}/disableconsole");
1193
	} else {
1194
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1195
	}
1196
}
1197

    
1198
function system_dmesg_save() {
1199
	global $g;
1200
	if(isset($config['system']['developerspew'])) {
1201
		$mt = microtime();
1202
		echo "system_dmesg_save() being called $mt\n";
1203
	}
1204

    
1205
	$dmesg = "";
1206
	exec("/sbin/dmesg", $dmesg);
1207

    
1208
	/* find last copyright line (output from previous boots may be present) */
1209
	$lastcpline = 0;
1210

    
1211
	for ($i = 0; $i < count($dmesg); $i++) {
1212
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1213
			$lastcpline = $i;
1214
	}
1215

    
1216
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1217
	if (!$fd) {
1218
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1219
		return 1;
1220
	}
1221

    
1222
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1223
		fwrite($fd, $dmesg[$i] . "\n");
1224

    
1225
	fclose($fd);
1226

    
1227
	return 0;
1228
}
1229

    
1230
function system_set_harddisk_standby() {
1231
	global $g, $config;
1232
	if(isset($config['system']['developerspew'])) {
1233
		$mt = microtime();
1234
		echo "system_set_harddisk_standby() being called $mt\n";
1235
	}
1236

    
1237
	if (isset($config['system']['harddiskstandby'])) {
1238
		if ($g['booting']) {
1239
			echo 'Setting hard disk standby... ';
1240
		}
1241

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

    
1262
function system_setup_sysctl() {
1263
	global $config;
1264
	if(isset($config['system']['developerspew'])) {
1265
		$mt = microtime();
1266
		echo "system_setup_sysctl() being called $mt\n";
1267
	}
1268

    
1269
	activate_sysctls();	
1270

    
1271
	if (isset($config['system']['sharednet'])) {
1272
		system_disable_arp_wrong_if();
1273
	}
1274
}
1275

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

    
1286
function system_enable_arp_wrong_if() {
1287
	global $config;
1288
	if(isset($config['system']['developerspew'])) {
1289
		$mt = microtime();
1290
		echo "system_enable_arp_wrong_if() being called $mt\n";
1291
	}
1292
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1293
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1294
}
1295

    
1296
function enable_watchdog() {
1297
	global $config;
1298
	$install_watchdog = false;
1299
	$supported_watchdogs = array("Geode");
1300
	$file = file_get_contents("/var/log/dmesg.boot");
1301
	foreach($supported_watchdogs as $sd) {
1302
		if(stristr($file, "Geode")) {
1303
			$install_watchdog = true;
1304
		}
1305
	}
1306
	if($install_watchdog == true) {
1307
		if(is_process_running("watchdogd"))
1308
			exec("/usr/bin/killall watchdogd");
1309
		exec("/usr/sbin/watchdogd");
1310
	}
1311
}
1312

    
1313
?>
(24-24/31)