Project

General

Profile

Download (37 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 opcode_cache_configuration() {
43
		global $g;
44
        if($g['platform'] == "cdrom")
45
        	return;
46
        /* get system memory amount */
47
        $memory = get_memory();
48
        $avail = $memory[0];
49

    
50
		/* disable apc for platforms less than 90 megs of ram */
51
        if($memory > 90) {
52
        	$opcode_cacher = "extension=apc.so\n";
53
        	$opcode_cacher .= "apc.enabled=\"1\"\n";
54
			$opcode_cacher .= "apc.enable_cli=\"1\"\n";
55
			$opcode_cacher .= "apc.shm_size=\"8\"\n";
56
        } else {
57
			$opcode_cacher = "";
58
        }
59

    
60
		/* create a php.ini variable */
61
		$php_conf = file_get_contents("/usr/local/lib/php.ini");
62

    
63
$php_ini = <<<EOFF
64
output_buffering = "0"
65
implicit_flush = true
66
magic_quotes_gpc = Off
67
max_execution_time = 99999999
68
max_input_time = 99999999
69
register_argc_argv = On
70
file_uploads = On
71
extension_dir=/usr/local/lib/php/extensions/no-debug-non-zts-20020429/
72
upload_tmp_dir = /tmp
73
upload_max_filesize = 100M
74
post_max_size = 100M
75
html_errors = Off
76
include_path = ".:/etc/inc:/usr/local/www:/usr/local/captiveportal:/usr/local/pkg"
77
extension=radius.so
78
extension=ldap.so
79
{$opcode_cacher}
80

    
81
EOFF;
82

    
83
        config_lock();
84
		conf_mount_rw();
85

    
86
		/* open up php.ini and write back out contents */
87
		$fd = fopen("/usr/local/lib/php.ini","w");
88
		fwrite($fd, $php_ini);
89
		fclose($fd);
90

    
91
		conf_mount_ro();
92
		exec("sync");
93
		config_unlock();
94

    
95
}
96

    
97
function system_resolvconf_generate($dynupdate = false) {
98
		global $config, $g;
99
		if(isset($config['system']['developerspew'])) {
100
			$mt = microtime();
101
			echo "system_resolvconf_generate() being called $mt\n";
102
		}
103

    
104
        $syscfg = $config['system'];
105

    
106
        $fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
107
        if (!$fd) {
108
                printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
109
                return 1;
110
        }
111

    
112
        $resolvconf = "domain {$syscfg['domain']}\n";
113

    
114
        $havedns = false;
115

    
116
        if (isset($syscfg['dnsallowoverride'])) {
117
			/* get dynamically assigned DNS servers (if any) */
118
			$ns = array_unique(get_nameservers());
119
			foreach($ns as $nameserver) {
120
				if($nameserver) {
121
					$resolvconf .= "nameserver $nameserver\n";
122
					$havedns = true;
123
				}
124
			}
125
        }
126
        if (!$havedns && is_array($syscfg['dnsserver'])) {
127
			foreach ($syscfg['dnsserver'] as $ns) {
128
				if ($ns) {
129
					$resolvconf .= "nameserver $ns\n";
130
					$havedns = true;
131
				}
132
			}
133
		}
134

    
135
        fwrite($fd, $resolvconf);
136
        fclose($fd);
137

    
138
        if (!$g['booting']) {
139
			/* restart dhcpd (nameservers may have changed) */
140
			if (!$dynupdate)
141
				services_dhcpd_configure();
142
        }
143

    
144
		for($dnscounter=1; $dnscounter<5; $dnscounter++) {
145
			/* setup static routes for dns servers */
146
			if($config['system']['dns{$dnscounter}gwint']) {
147
				$if = $config['system']['dns{$dnscounter}gwint'];
148
				if($if) { 
149
					$gw = $config['interfaces'][$if]['if'];
150
					$dnscountermo = $dnscounter - 1;
151
					exec("route delete {$syscfg['dnsserver'][$dnscountermo]}");
152
					exec("route add {$syscfg['dnsserver'][$dnscountermo]} -gw {$gw}");
153
				}
154
			}
155
		}
156

    
157
        return 0;
158
}
159

    
160
function get_nameservers() {
161
	global $config, $g;
162
	$master_list = array();
163
	$dns_lists = split("\n", `ls /var/etc/nameserver_* 2>/dev/null`);
164
	foreach($dns_lists as $dns) {
165
		$items = split("\n", file_get_contents($dns));
166
		foreach($items as $item)
167
			if($item <> "")
168
				$master_list[] = $item;
169
	}
170
	if(!file_exists("/var/etc/nameservers.conf"))
171
		return $master_list;
172
	$dns = `cat /var/etc/nameservers.conf`;
173
	$dns_s = split("\n", $dns);
174
	if(is_array($dns_s))
175
		foreach($dns_s as $dns)
176
			$master_list[] = $dns;
177
	return $master_list;
178
}
179

    
180
function system_hosts_generate() {
181
	global $config, $g;
182
	if(isset($config['system']['developerspew'])) {
183
		$mt = microtime();
184
		echo "system_hosts_generate() being called $mt\n";
185
	}
186

    
187
	$syscfg = $config['system'];
188
	$lancfg = $config['interfaces']['lan'];
189
	$dnsmasqcfg = $config['dnsmasq'];
190

    
191
	if (!is_array($dnsmasqcfg['hosts'])) {
192
		$dnsmasqcfg['hosts'] = array();
193
	}
194
	$hostscfg = $dnsmasqcfg['hosts'];
195

    
196
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
197
	if (!$fd) {
198
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
199
		return 1;
200
	}
201

    
202
	$hosts = <<<EOD
203
127.0.0.1	localhost localhost.{$syscfg['domain']}
204
{$lancfg['ipaddr']}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}
205

    
206
EOD;
207

    
208
	foreach ($hostscfg as $host) {
209
		if ($host['host'])
210
			$hosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
211
		else
212
			$hosts .= "{$host['ip']}	{$host['domain']}\n";
213
	}
214
	if (isset($dnsmasqcfg['regdhcpstatic'])) {
215
		foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf)
216
			if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
217
					foreach ($dhcpifconf['staticmap'] as $host)
218
						if ($host['ipaddr'] && $host['hostname'])
219
							$hosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
220
	}
221
	fwrite($fd, $hosts);
222
	fclose($fd);
223

    
224
	return 0;
225
}
226

    
227
function system_hostname_configure() {
228
	global $config, $g;
229
	if(isset($config['system']['developerspew'])) {
230
		$mt = microtime();
231
		echo "system_hostname_configure() being called $mt\n";
232
	}
233

    
234
	$syscfg = $config['system'];
235

    
236
	/* set hostname */
237
	return mwexec("/bin/hostname " .
238
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
239
}
240

    
241
function system_routing_configure() {
242
	global $config, $g;
243
	if(isset($config['system']['developerspew'])) {
244
		$mt = microtime();
245
		echo "system_routing_configure() being called $mt\n";
246
	}
247

    
248
	/* Enable fast routing, if enabled */
249
	if(isset($config['staticroutes']['enablefastrouting']))
250
		mwexec("/sbin/sysctl net.inet.ip.fastforwarding=1");
251

    
252
	/* clear out old routes, if necessary */
253
	if (file_exists("{$g['vardb_path']}/routes.db")) {
254
		$fd = fopen("{$g['vardb_path']}/routes.db", "r");
255
		if (!$fd) {
256
			printf("Error: cannot open routes DB file in system_routing_configure().\n");
257
			return 1;
258
		}
259
		while (!feof($fd)) {
260
			$oldrt = fgets($fd);
261
			if ($oldrt)
262
				mwexec("/sbin/route delete " . escapeshellarg($oldrt));
263
		}
264
		fclose($fd);
265
		unlink("{$g['vardb_path']}/routes.db");
266
	}
267

    
268
	/* if list */
269
	$iflist = array("lan", "wan");
270
	for ($i = 1; isset($config['interfaces']['opt' . $i]['enable']); $i++)
271
		$iflist['opt' . $i] = "opt{$i}";
272

    
273
	$dont_remove_route = false;
274
	foreach ($iflist as $ifent => $ifname) {
275
		/* do not process interfaces that will end up with gateways */
276
		if($config['interfaces'][$ifname]['ipaddr'] == "dhcp" or
277
			$config['interfaces'][$ifname]['ipaddr'] == "bigpond" or
278
			$config['interfaces'][$ifname]['ipaddr'] == "pppoe" or
279
			$config['interfaces'][$ifname]['ipaddr'] == "pptp")
280
			$dont_remove_route = true;
281
	}
282

    
283
	if($dont_remove_route == false) {
284
		/* remove default route */
285
		mwexec("/sbin/route delete default");
286
	}
287

    
288
	$dont_add_route = false;
289
	/* if OLSRD is enabled, allow WAN to house DHCP. */
290
	if($config['installedpackages']['olsrd']) {
291
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
292
			if($olsrd['enabledyngw'] == "on") {
293
				$dont_add_route = true;
294
			}
295
		}
296
	}
297

    
298
	if($dont_add_route == false) {
299
		if(is_array($config['gateways'])) {
300
			foreach($config['gateways']['gateway_item'] as $gateway) {
301
		        	if(isset($gateway['defaultgw'])) {
302
					$gatewayip = $gateway['gateway'];
303
					$interfacegw = $gateway['interface'];
304
				}
305
			}
306
			mwexec("/sbin/route add default " . escapeshellarg($gatewayip));
307
		}
308
	}
309

    
310
	if (is_array($config['staticroutes']['route'])) {
311

    
312
		$fd = fopen("{$g['vardb_path']}/routes.db", "w");
313
		if (!$fd) {
314
			printf("Error: cannot open routes DB file in system_routing_configure().\n");
315
			return 1;
316
		}
317

    
318
		foreach ($config['staticroutes']['route'] as $rtent) {
319
			if(is_array($config['gateways'])) {
320
				foreach($config['gateways']['gateway_item'] as $gateway) {
321
					if($rtent['gateway'] == $gateway['name']) {
322
						$gatewayip = $gateway['gateway'];
323
						$interfacegw = $gateway['interface'];
324
					}
325
				}
326
				if(isset($rtent['interfacegateway'])) {
327
					mwexec("/sbin/route add " . escapeshellarg($rtent['network']) .
328
						" -iface " . escapeshellarg(convert_friendly_interface_to_real_interface_name($interfacegw)));
329
				} else {
330
					mwexec("/sbin/route add " . escapeshellarg($rtent['network']) .
331
						" " . escapeshellarg($gatewayip));
332
				}
333
				/* record route so it can be easily removed later (if necessary) */
334
				fwrite($fd, $rtent['network'] . "\n");
335
			}
336
		}
337

    
338
		fclose($fd);
339
	}
340

    
341
	return 0;
342
}
343

    
344
function system_routing_enable() {
345
	global $config, $g;
346
	if(isset($config['system']['developerspew'])) {
347
		$mt = microtime();
348
		echo "system_routing_enable() being called $mt\n";
349
	}
350

    
351
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
352
}
353

    
354
function system_syslogd_start() {
355
	global $config, $g;
356
	if(isset($config['system']['developerspew'])) {
357
		$mt = microtime();
358
		echo "system_syslogd_start() being called $mt\n";
359
	}
360

    
361
	$syslogcfg = $config['syslog'];
362

    
363
	if ($g['booting'])
364
		echo "Starting syslog...";
365
	else
366
		killbypid("{$g['varrun_path']}/syslog.pid");
367

    
368
	if (isset($syslogcfg)) {
369
		$separatelogfacilities = array('ntpd','racoon','openvpn');
370
		if($config['installedpackages']['package']) {
371
                        foreach($config['installedpackages']['package'] as $package) {
372
                                if($package['logging']) {
373
					$pkgfacilities[] = $package['logging']['facilityname'];
374
					$separatelogfacilities = $separatelogfacilities + $pkgfacilities;
375
					$facilitylist = implode(',', $pkgfacilities);
376
					mwexec("clog -i -s 10000 {$g['varlog_path']}/{$package['logging']['logfilename']}");
377
                                	$syslogconf .= "!{$facilitylist}\n*.*\t\t\t\t\t\t%{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
378
				}
379
                        }
380
                }
381
		$facilitylist = implode(',', array_unique($separatelogfacilities));
382
		/* write syslog.conf */
383
		$fd = fopen("{$g['varetc_path']}/syslog.conf", "w");
384
		if (!$fd) {
385
			printf("Error: cannot open syslog.conf in system_syslogd_start().\n");
386
			return 1;
387
		}
388
		$syslogconf .= "!ntpdate,!ntpd\n";
389
		if (!isset($syslogcfg['disablelocallogging'])) {
390
			$syslogconf .= <<<EOD
391
*.*						%{$g['varlog_path']}/ntpd.log
392

    
393
EOD;
394
		}
395
		$syslogconf .= "!racoon\n";
396
		if (!isset($syslogcfg['disablelocallogging'])) {
397
			$syslogconf .= <<<EOD
398
*.*						%{$g['varlog_path']}/ipsec.log
399

    
400
EOD;
401
		}
402
		if (isset($syslogcfg['vpn'])) {
403
			$syslogconf .= <<<EOD
404
*.*						@{$syslogcfg['remoteserver']}
405

    
406
EOD;
407
		}
408
		$syslogconf .= "!openvpn\n";
409
		if (!isset($syslogcfg['disablelocallogging'])) {
410
			$syslogconf .= <<<EOD
411
*.*						%{$g['varlog_path']}/openvpn.log
412

    
413
EOD;
414
		}
415
		if (isset($syslogcfg['vpn'])) {
416
			$syslogconf .= <<<EOD
417
*.*						@{$syslogcfg['remoteserver']}
418

    
419
EOD;
420
		}
421
		$syslogconf .= "!-{$facilitylist}\n";
422
		if (!isset($syslogcfg['disablelocallogging'])) {
423
		$syslogconf .= <<<EOD
424
local0.*					%{$g['varlog_path']}/filter.log
425
local3.*					%{$g['varlog_path']}/vpn.log
426
local4.*					%{$g['varlog_path']}/portalauth.log
427
local7.*					%{$g['varlog_path']}/dhcpd.log
428
*.notice;kern.debug;lpr.info;mail.crit; 	%{$g['varlog_path']}/system.log
429
news.err;local0.none;local3.none;local4.none; 	%{$g['varlog_path']}/system.log
430
local7.none					%{$g['varlog_path']}/system.log
431
security.*					%{$g['varlog_path']}/system.log
432
auth.info;authpriv.info;daemon.info		%{$g['varlog_path']}/system.log
433
local1.*					%{$g['varlog_path']}/slbd.log
434
auth.info;authpriv.info 			|exec /usr/local/sbin/sshlockout_pf
435
*.emerg						*
436

    
437
EOD;
438
		}
439

    
440
		if (isset($syslogcfg['filter'])) {
441
			$syslogconf .= <<<EOD
442
local0.*					@{$syslogcfg['remoteserver']}
443

    
444
EOD;
445
		}
446

    
447
		if (isset($syslogcfg['vpn'])) {
448
			$syslogconf .= <<<EOD
449
local3.*					@{$syslogcfg['remoteserver']}
450

    
451
EOD;
452
		}
453

    
454

    
455
		if (isset($syslogcfg['portalauth'])) {
456
			$syslogconf .= <<<EOD
457
local4.*					@{$syslogcfg['remoteserver']}
458

    
459
EOD;
460
		}
461

    
462

    
463
		if (isset($syslogcfg['dhcp'])) {
464
			$syslogconf .= <<<EOD
465
local7.*					@{$syslogcfg['remoteserver']}
466

    
467
EOD;
468
		}
469

    
470
		if (isset($syslogcfg['system'])) {
471
			$syslogconf .= <<<EOD
472
*.notice;kern.debug;lpr.info;mail.crit;		@{$syslogcfg['remoteserver']}
473
news.err;local0.none;local3.none;local7.none	@{$syslogcfg['remoteserver']}
474
security.*					@{$syslogcfg['remoteserver']}
475
auth.info;authpriv.info;daemon.info		@{$syslogcfg['remoteserver']}
476
*.emerg						@{$syslogcfg['remoteserver']}
477

    
478
EOD;
479
		}
480
		fwrite($fd, $syslogconf);
481
		fclose($fd);
482

    
483
		$retval = mwexec("/usr/sbin/syslogd -s -f {$g['varetc_path']}/syslog.conf");
484

    
485
	} else {
486
		$retval = mwexec("/usr/sbin/syslogd -ss");
487
	}
488

    
489
	if ($g['booting'])
490
		echo "done.\n";
491

    
492
	return $retval;
493
}
494

    
495
function system_pccard_start() {
496
	global $config, $g;
497
	if(isset($config['system']['developerspew'])) {
498
		$mt = microtime();
499
		echo "system_pccard_start() being called $mt\n";
500
	}
501

    
502
	if ($g['booting'])
503
		echo "Initializing PCMCIA...";
504

    
505
	/* kill any running pccardd */
506
	killbypid("{$g['varrun_path']}/pccardd.pid");
507

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

    
511
	if ($g['booting']) {
512
		if ($res == 0)
513
			echo "done.\n";
514
		else
515
			echo "failed!\n";
516
	}
517

    
518
	return $res;
519
}
520

    
521

    
522
function system_webgui_start() {
523
	global $config, $g;
524

    
525
	if ($g['booting'])
526
		echo "Starting webConfigurator...";
527

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

    
531
	sleep(1);
532

    
533
	/* generate password file */
534
	system_password_configure();
535

    
536
	chdir($g['www_path']);
537

    
538
	/* non-standard port? */
539
	if ($config['system']['webgui']['port'])
540
		$portarg = "{$config['system']['webgui']['port']}";
541
	else
542
		$portarg = "";
543

    
544
	if ($config['system']['webgui']['protocol'] == "https") {
545

    
546
	if(!$config['system']['webgui']['port'])
547
		$portarg = "443";
548

    
549
		if ($config['system']['webgui']['certificate'] && $config['system']['webgui']['private-key']) {
550
			$cert = base64_decode($config['system']['webgui']['certificate']);
551
			$key = base64_decode($config['system']['webgui']['private-key']);
552
		} else {
553
			/* default certificate/key */
554
			$cert = <<<EOD
555
-----BEGIN CERTIFICATE-----
556
MIIDEzCCAnygAwIBAgIJAJM91W+s6qptMA0GCSqGSIb3DQEBBAUAMGUxCzAJBgNV
557
BAYTAlVTMQswCQYDVQQIEwJLWTETMBEGA1UEBxMKTG91aXN2aWxsZTEQMA4GA1UE
558
ChMHcGZTZW5zZTEQMA4GA1UECxMHcGZTZW5zZTEQMA4GA1UEAxMHcGZTZW5zZTAe
559
Fw0wNjAzMTAyMzQ1MTlaFw0xNjAzMDcyMzQ1MTlaMGUxCzAJBgNVBAYTAlVTMQsw
560
CQYDVQQIEwJLWTETMBEGA1UEBxMKTG91aXN2aWxsZTEQMA4GA1UEChMHcGZTZW5z
561
ZTEQMA4GA1UECxMHcGZTZW5zZTEQMA4GA1UEAxMHcGZTZW5zZTCBnzANBgkqhkiG
562
9w0BAQEFAAOBjQAwgYkCgYEA3lPNTFH6qge/ygaqe/BS4oH59O6KvAesWcRzSu5N
563
21lyVE5tBbL0zqOSXmlLyReMSbtAMZqt1P8EPYFoOcaEQHIWm2VQF80Z18+8Gh4O
564
UQGjHq88OeaLqyk3OLpSKzSpXuCFrSN7q9Kez8zp5dQEu7sIW30da3pAbdqYOimA
565
1VsCAwEAAaOByjCBxzAdBgNVHQ4EFgQUAnx+ggC4SzJ0CK+rhPhJ2ZpyunEwgZcG
566
A1UdIwSBjzCBjIAUAnx+ggC4SzJ0CK+rhPhJ2ZpyunGhaaRnMGUxCzAJBgNVBAYT
567
AlVTMQswCQYDVQQIEwJLWTETMBEGA1UEBxMKTG91aXN2aWxsZTEQMA4GA1UEChMH
568
cGZTZW5zZTEQMA4GA1UECxMHcGZTZW5zZTEQMA4GA1UEAxMHcGZTZW5zZYIJAJM9
569
1W+s6qptMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEEBQADgYEAAviQpdoeabL8
570
1HSZiD7Yjx82pdLpyQOdXvAu3jEAYz53ckx0zSMrzsQ5r7Vae6AE7Xd7Pj+1Yihs
571
AJZzOQujnmsuim7qu6YSxzP34xonKwd1C9tZUlyNRNnEmtXOEDupn05bih1ugtLG
572
kqfPIgDbDLXuPtEAA6QDUypaunI6+1E=
573
-----END CERTIFICATE-----
574

    
575
EOD;
576

    
577
			$key = <<<EOD
578
-----BEGIN RSA PRIVATE KEY-----
579
MIICXgIBAAKBgQDeU81MUfqqB7/KBqp78FLigfn07oq8B6xZxHNK7k3bWXJUTm0F
580
svTOo5JeaUvJF4xJu0Axmq3U/wQ9gWg5xoRAchabZVAXzRnXz7waHg5RAaMerzw5
581
5ourKTc4ulIrNKle4IWtI3ur0p7PzOnl1AS7uwhbfR1rekBt2pg6KYDVWwIDAQAB
582
AoGAP7E0VFP8Aq/7os3sE1uS8y8XQ7L+7cUo/AKKoQHKLjfeyAY7t3FALt6vdPqn
583
anGjkA/j4RIWELoKJfCnwj17703NDCPwB7klcmZvmTx5Om1ZrRyZdQ6RJs0pOOO1
584
r2wOnZNaNWStXE9Afpw3dj20Gh0V/Ioo5HXn3sHfxZm8dnkCQQDwv8OaUdp2Hl8t
585
FDfXB1CMvUG1hEAvbQvZK1ODkE7na2/ChKjVPddEI3DvfzG+nLrNuTrAyVWgRLte
586
r8qX5PQHAkEA7GlKx0S18LdiKo6wy2QeGu6HYkPncaHNFOWX8cTpvGGtQoWYSh0J
587
tjCt1/mz4/XkvZWuZyTNx2FdkVlNF5nHDQJBAIRWVTZqEjVlwpmsCHnp6mxCyHD4
588
DrRDNAUfnNuwIr9xPlDlzUzSnpc1CCqOd5C45LKbRGGfCrN7tKd66FmQoFcCQQCy
589
Kvw3R1pTCvHJnvYwoshphaC0dvaDVeyINiwYAk4hMf/wpVxLZqz+CJvLrB1dzOBR
590
3O+uPjdzbrakpweJpNQ1AkEA3ZtlgEj9eWsLAJP8aKlwB8VqD+EtG9OJSUMnCDiQ
591
WFFNj/t3Ze3IVuAyL/yMpiv3JNEnZhIxCta42eDFpIZAKw==
592
-----END RSA PRIVATE KEY-----
593

    
594
EOD;
595
		}
596
	} else {
597
		$cert = "";
598
		$key = "";
599
	}
600

    
601
	/* generate lighttpd configuration */
602
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
603
		$cert, $key, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/");
604

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

    
608
	if ($g['booting']) {
609
		if ($res == 0)
610
			echo "done.\n";
611
		else
612
			echo "failed!\n";
613
	}
614

    
615
	return $res;
616
}
617

    
618
function system_webgui_start_old() {
619
	global $config, $g;
620
	if(isset($config['system']['developerspew'])) {
621
		$mt = microtime();
622
		echo "system_webgui_start() being called $mt\n";
623
	}
624

    
625
        if ($g['booting'])
626
                echo "Starting webConfigurator...";
627

    
628
        /* kill any running mini_httpd */
629
        killbypid("{$g['varrun_path']}/mini_httpd.pid");
630

    
631
        /* generate password file */
632
        system_password_configure();
633

    
634
        chdir($g['www_path']);
635

    
636
        /* non-standard port? */
637
        if ($config['system']['webgui']['port'])
638
                $portarg = "-p {$config['system']['webgui']['port']}";
639
        else
640
                $portarg = "";
641

    
642
        if ($config['system']['webgui']['protocol'] == "https") {
643

    
644
                if ($config['system']['webgui']['certificate'] && $config['system']['webgui']['private-key']) {
645
                        $cert = base64_decode($config['system']['webgui']['certificate']);
646
                        $key  = base64_decode($config['system']['webgui']['private-key']);
647
                } else {
648
                        /* default certificate/key */
649
                        $cert = <<<EOD
650
-----BEGIN CERTIFICATE-----
651
MIIBlDCB/gIBADANBgkqhkiG9w0BAQQFADATMREwDwYDVQQKEwhtMG4wd2FsbDAe
652
Fw0wNTA1MTAxMjI0NDRaFw0wNzA1MTAxMjI0NDRaMBMxETAPBgNVBAoTCG0wbjB3
653
YWxsMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDAShszhFz+o8lsMWTGgTxs
654
TMPR+v4+qL5jXDyY97MLTGFK7aqQOtpIQc+TcTc4jklgOVlHoR7oBXrsi8YrbCd+
655
83LPQmQoSPC0VqhfU3uYf3NzxiK8r97aPCsmWgwT2pQ6TcESTm6sF7nLprOf/zFP
656
C4jE2fvjkbzyVolPywBuewIDAQABMA0GCSqGSIb3DQEBBAUAA4GBAFR962c4R5tV
657
cTn0OQcszYoW6WC+ini9tQQh5ku5jYDAiC+00atawJEVLnL3lwAcpSKTIWlTkD20
658
tl3lz5br1qFgYky+Rd0kwS2nk9jRbkxSXxd6KJVnNRCKre28aw3ENzZfCSurPQsX
659
UPp5er+NtwMT1g7s/JDmKTC4w1rGr5/c
660
-----END CERTIFICATE-----
661

    
662
EOD;
663

    
664
                        $key = <<<EOD
665
-----BEGIN RSA PRIVATE KEY-----
666
MIICXQIBAAKBgQDAShszhFz+o8lsMWTGgTxsTMPR+v4+qL5jXDyY97MLTGFK7aqQ
667
OtpIQc+TcTc4jklgOVlHoR7oBXrsi8YrbCd+83LPQmQoSPC0VqhfU3uYf3NzxiK8
668
r97aPCsmWgwT2pQ6TcESTm6sF7nLprOf/zFPC4jE2fvjkbzyVolPywBuewIDAQAB
669
AoGAbJJrQW9fQrggJuLMz/hwsYW2m31oyOBmf5u463YQtjRuSuxe/gj87weZuNqY
670
H2rXq2k2K+ehl8hgW+egASyUL3L7kCkEAsVREujKTEyhSqqIRDPWTxo9S/YA9Gvn
671
2ZnJvkrcKjqCO9aHX3rvJOK/ErYI6akctgI3KmgkYw5XNmECQQDuZU97RTWH9rmP
672
aQr57ysNXxgFsyhetOOqeYkPtIVwpOiNbfwE1zi5RGdtO4Ku3fG1lV4J2UoWJ9yD
673
awdoyYIHAkEAzn0xJ90IjPsHk+8SODEj5JGdHSZPNu1tgtrbjEi9sfGWg4K7XTxr
674
QW90pWb1bKKU1uh5FzW6OhnFfuQXt1kC7QJAPSthqY+onKqCEnoxhtAHi/bKgyvl
675
P+fKQwPMV2tKkgy+XwvJjrRqqZ8TqsOKVLQ+QQmCh6RpjiXMPyxHSmvqIQJBAKLR
676
HF1ucDuaBROkwx0DwmWMW/KMLpIFDQDNSaiIAuu4rxHrl4mhBoGGPNffI04RtILw
677
s+qVNs5xW8T+XaT4ztECQQDFHPnZeoPWE5z+AX/UUQIUWaDExz3XRzmIxRbOrlFi
678
CsF1s0TdJLi/wzNQRAL37A8vqCeVFR/ng3Xpg96Yg+8Z
679
-----END RSA PRIVATE KEY-----
680

    
681
EOD;
682
                }
683

    
684
				$cert = str_replace("\r", "", $cert);
685
				$key = str_replace("\r", "", $key);
686

    
687
                $fd = fopen("{$g['varetc_path']}/cert.pem", "w");
688
                if (!$fd) {
689
                        printf("Error: cannot open cert.pem in system_webgui_start().\n");
690
                        return 1;
691
                }
692
                chmod("{$g['varetc_path']}/cert.pem", 0600);
693
                fwrite($fd, $cert);
694
                fwrite($fd, "\n");
695
                fwrite($fd, $key);
696
                fclose($fd);
697

    
698
                $res = mwexec("/usr/local/sbin/mini_httpd -S -E {$g['varetc_path']}/cert.pem" .
699
                        " -c \"**.php|**.cgi\" -u root -maxproc 16 $portarg" .
700
                        " -i {$g['varrun_path']}/mini_httpd.pid");
701
        } else {
702
                $res = mwexec("/usr/local/sbin/mini_httpd -c \"**.php|**.cgi\" -u root" .
703
                        " -maxproc 16 $portarg -i {$g['varrun_path']}/mini_httpd.pid");
704
        }
705

    
706
        if ($g['booting']) {
707
                if ($res == 0)
708
                        echo "done\n";
709
                else
710
                        echo "failed\n";
711
        }
712

    
713
        return $res;
714
}
715

    
716
function system_generate_lighty_config($filename,
717
	$cert,
718
	$key,
719
	$pid_file,
720
	$port = 80,
721
	$document_root = "/usr/local/www/",
722
	$cert_location = "cert.pem",
723
	$max_procs = 2,
724
	$max_requests = "1",
725
	$fast_cgi_enable = true,
726
	$captive_portal = false) {
727

    
728
	global $config, $g;
729

    
730
	/* only use freebsd-sendfile network handler on full installations
731
	 * tests have shown that it is actually slower on embedded.
732
	 */
733
	if(stristr("pfSense", $g['platform']))
734
		$network_handler = "server.network-backend		= \"freebsd-sendfile\"\n";
735
	else
736
		$network_handler = "";
737

    
738
	if(isset($config['system']['developerspew'])) {
739
		$mt = microtime();
740
		echo "system_generate_lighty_config() being called $mt\n";
741
	}
742

    
743
	if($captive_portal == true)  {
744
		$captiveportal = ",\"mod_rewrite\"";
745
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?redirurl=$1\" )\n";
746
		$captive_portal_module = "\"mod_accesslog\", ";
747
		$maxprocperip = $config['captiveportal']['maxprocperip'];
748
		if(!$maxprocperip and $maxprocperip > 0)
749
			$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
750
		else
751
			$captive_portal_mod_evasive = "";
752
		$server_upload_dirs = "server.upload-dirs = ( \"/tmp/captiveportal/\" )\n";
753
		exec("mkdir -p /tmp/captiveportal");
754
		exec("chmod a-w /tmp/captiveportal");
755
		$server_max_request_size = "server.max-request-size    = 384";
756
	} else {
757
		$captive_portal_module = "";
758
		$captive_portal_mod_evasive = "";
759
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"/tmp/\", \"/var/\" )\n";
760
		$server_max_request_size = "server.max-request-size    = 2097152";
761
	}
762
	
763
	if($port <> "")
764
		$lighty_port = $port;
765
	else
766
		$lighty_port = "80";
767

    
768
	$memory = get_memory();
769
	$avail = $memory[0];
770

    
771
	if($avail > 0 and $avail < 98) {
772
		$max_procs = 1;
773
		$max_requests = 1;
774
	}
775

    
776
	if($avail > 97 and $avail < 128) {
777
		$max_procs = 2;
778
		$max_requests = 1;
779
	}
780

    
781
	if($avail > 127 and $avail < 256) {
782
		$max_procs = 2;
783
		$max_requests = 1;
784
	}
785

    
786
	if($avail > 255 and $avail < 384) {
787
		$max_procs = 3;
788
		$max_requests = 1;
789
	}
790

    
791
	if($avail > 383 and $avail < 512) {
792
		$max_procs = 4;
793
		$max_requests = 1;
794
	}
795

    
796
	if($fast_cgi_enable == true) {
797
		$module = "\"mod_fastcgi\", \"mod_cgi\"";
798
		$cgi_config = "";
799
		$fastcgi_config = <<<EOD
800
#### fastcgi module
801
## read fastcgi.txt for more info
802
fastcgi.server = ( ".php" =>
803
	( "localhost" =>
804
		(
805
			"socket" => "/tmp/php-fastcgi.socket",
806
			"min-procs" => 1,
807
			"max-procs" => {$max_procs},
808
			"bin-path" => "/usr/local/bin/php"
809
		)
810
	)
811
)
812

    
813
#### CGI module
814
cgi.assign                 = ( ".cgi" => "" )
815

    
816
EOD;
817
	} else {
818
		$fastcgi_config = "";
819
		$module = "\"mod_cgi\"";
820
		$cgi_config = <<<EOD
821
#### CGI module
822
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
823
                               ".cgi" => "" )
824

    
825
EOD;
826
	}
827

    
828
	$lighty_config .= <<<EOD
829
#
830
# lighttpd configuration file
831
#
832
# use a it as base for lighttpd 1.0.0 and above
833
#
834
############ Options you really have to take care of ####################
835

    
836
## FreeBSD!
837
server.event-handler		= "freebsd-kqueue"
838

    
839
{$network_handler}
840

    
841
## modules to load
842
server.modules              =   (
843
				  {$captive_portal_module}
844
				  "mod_access", "mod_accesslog",
845
                                  {$module}{$captiveportal}
846
				)
847

    
848
## Unused modules
849
#                               "mod_setenv",
850
#                               "mod_compress"
851
#				"mod_redirect",
852
#                               "mod_rewrite",
853
#                               "mod_ssi",
854
#                               "mod_usertrack",
855
#                               "mod_expire",
856
#                               "mod_secdownload",
857
#                               "mod_rrdtool",
858
#                               "mod_auth",
859
#                               "mod_status",
860
#                               "mod_alias",
861
#                               "mod_proxy",
862
#                               "mod_simple_vhost",
863
#                               "mod_evhost",
864
#                               "mod_userdir",
865
#                               "mod_cgi",
866
#                                "mod_accesslog"
867

    
868
## a static document-root, for virtual-hosting take look at the
869
## server.virtual-* options
870
server.document-root        = "{$document_root}"
871
{$captive_portal_rewrite}
872

    
873
## where to send error-messages to
874
server.errorlog             = "/var/log/lighttpd.error.log"
875

    
876
# files to check for if .../ is requested
877
server.indexfiles           = ( "index.php", "index.html",
878
                                "index.htm", "default.htm" )
879

    
880
# mimetype mapping
881
mimetype.assign             = (
882
  ".pdf"          =>      "application/pdf",
883
  ".sig"          =>      "application/pgp-signature",
884
  ".spl"          =>      "application/futuresplash",
885
  ".class"        =>      "application/octet-stream",
886
  ".ps"           =>      "application/postscript",
887
  ".torrent"      =>      "application/x-bittorrent",
888
  ".dvi"          =>      "application/x-dvi",
889
  ".gz"           =>      "application/x-gzip",
890
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
891
  ".swf"          =>      "application/x-shockwave-flash",
892
  ".tar.gz"       =>      "application/x-tgz",
893
  ".tgz"          =>      "application/x-tgz",
894
  ".tar"          =>      "application/x-tar",
895
  ".zip"          =>      "application/zip",
896
  ".mp3"          =>      "audio/mpeg",
897
  ".m3u"          =>      "audio/x-mpegurl",
898
  ".wma"          =>      "audio/x-ms-wma",
899
  ".wax"          =>      "audio/x-ms-wax",
900
  ".ogg"          =>      "audio/x-wav",
901
  ".wav"          =>      "audio/x-wav",
902
  ".gif"          =>      "image/gif",
903
  ".jpg"          =>      "image/jpeg",
904
  ".jpeg"         =>      "image/jpeg",
905
  ".png"          =>      "image/png",
906
  ".xbm"          =>      "image/x-xbitmap",
907
  ".xpm"          =>      "image/x-xpixmap",
908
  ".xwd"          =>      "image/x-xwindowdump",
909
  ".css"          =>      "text/css",
910
  ".html"         =>      "text/html",
911
  ".htm"          =>      "text/html",
912
  ".js"           =>      "text/javascript",
913
  ".asc"          =>      "text/plain",
914
  ".c"            =>      "text/plain",
915
  ".conf"         =>      "text/plain",
916
  ".text"         =>      "text/plain",
917
  ".txt"          =>      "text/plain",
918
  ".dtd"          =>      "text/xml",
919
  ".xml"          =>      "text/xml",
920
  ".mpeg"         =>      "video/mpeg",
921
  ".mpg"          =>      "video/mpeg",
922
  ".mov"          =>      "video/quicktime",
923
  ".qt"           =>      "video/quicktime",
924
  ".avi"          =>      "video/x-msvideo",
925
  ".asf"          =>      "video/x-ms-asf",
926
  ".asx"          =>      "video/x-ms-asf",
927
  ".wmv"          =>      "video/x-ms-wmv",
928
  ".bz2"          =>      "application/x-bzip",
929
  ".tbz"          =>      "application/x-bzip-compressed-tar",
930
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
931
 )
932

    
933
# Use the "Content-Type" extended attribute to obtain mime type if possible
934
#mimetypes.use-xattr        = "enable"
935

    
936
#### accesslog module
937
#accesslog.filename          = "/dev/null"
938

    
939
## deny access the file-extensions
940
#
941
# ~    is for backupfiles from vi, emacs, joe, ...
942
# .inc is often used for code includes which should in general not be part
943
#      of the document-root
944
url.access-deny             = ( "~", ".inc" )
945

    
946

    
947
######### Options that are good to be but not neccesary to be changed #######
948

    
949
## bind to port (default: 80)
950
server.port                = {$lighty_port}
951

    
952
## error-handler for status 404
953
#server.error-handler-404   = "/error-handler.html"
954
#server.error-handler-404   = "/error-handler.php"
955

    
956
## to help the rc.scripts
957
server.pid-file            = "/var/run/{$pid_file}"
958

    
959
## virtual directory listings
960
server.dir-listing         = "disable"
961

    
962
## enable debugging
963
debug.log-request-header   = "disable"
964
debug.log-response-header  = "disable"
965
debug.log-request-handling = "disable"
966
debug.log-file-not-found   = "disable"
967

    
968
#### compress module
969
#compress.cache-dir         = "/tmp/lighttpd/cache/compress/"
970
#compress.filetype          = ("text/plain", "text/html")
971

    
972
#server.network-backend = "writev"
973

    
974
{$server_upload_dirs}
975

    
976
{$server_max_request_size}
977

    
978
{$fastcgi_config}
979

    
980
{$cgi_config}
981

    
982
{$captive_portal_mod_evasive}
983

    
984
EOD;
985

    
986
	$cert = str_replace("\r", "", $cert);
987
	$key = str_replace("\r", "", $key);
988

    
989
	$cert = str_replace("\n\n", "\n", $cert);
990
	$key = str_replace("\n\n", "\n", $key);
991

    
992
	if($cert <> "" and $key <> "") {
993
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
994
		if (!$fd) {
995
			printf("Error: cannot open cert.pem in system_webgui_start().\n");
996
			return 1;
997
		}
998
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
999
		fwrite($fd, $cert);
1000
		fwrite($fd, "\n");
1001
		fwrite($fd, $key);
1002
		fclose($fd);
1003
		$lighty_config .= "\n";
1004
		$lighty_config .= "## ssl configuration\n";
1005
		$lighty_config .= "ssl.engine = \"enable\"\n";
1006
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1007
	}
1008

    
1009
	$fd = fopen("{$filename}", "w");
1010
	if (!$fd) {
1011
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
1012
		return 1;
1013
	}
1014
	fwrite($fd, $lighty_config);
1015
	fclose($fd);
1016

    
1017
	return 0;
1018

    
1019
}
1020

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

    
1028
	/* sync passwords */
1029
	sync_webgui_passwords();
1030

    
1031
	/* !NOTE! conf_mount_ro is done by sync_webgui_passwords() */
1032

    
1033
	return 0;
1034
}
1035

    
1036
function system_timezone_configure() {
1037
	global $config, $g;
1038
	if(isset($config['system']['developerspew'])) {
1039
		$mt = microtime();
1040
		echo "system_timezone_configure() being called $mt\n";
1041
	}
1042

    
1043
	$syscfg = $config['system'];
1044

    
1045
	if ($g['booting'])
1046
		echo "Setting timezone...";
1047

    
1048
	/* extract appropriate timezone file */
1049
	$timezone = $syscfg['timezone'];
1050
	if (!$timezone)
1051
		$timezone = "Etc/UTC";
1052

    
1053
	conf_mount_rw();
1054

    
1055
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1056
		escapeshellarg($timezone) . " > /etc/localtime");
1057

    
1058
	conf_mount_ro();
1059

    
1060
	if ($g['booting'])
1061
		echo "done.\n";
1062
}
1063

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

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

    
1069
	/* open configuration for wrting or bail */
1070
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1071
	if(!$fd) {
1072
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1073
		return;
1074
	}
1075

    
1076
	fwrite($fd, "# \n");
1077
	fwrite($fd, "# pfSense OpenNTPD configuration file \n");
1078
	fwrite($fd, "# \n\n");
1079

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

    
1084
    /* server config is in coregui1 */
1085
	$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
1086
	if ($xmlsettings['enable'] == 'on') {
1087
		$ifaces = explode(',', $xmlsettings['interface']);
1088
		$ifaces = array_map('convert_friendly_interface_to_real_interface_name', $ifaces);
1089
		$ifaces = array_filter($ifaces, 'does_interface_exist');
1090
		$ips = array_map('find_interface_ip', $ifaces);
1091
		foreach ($ips as $ip) {
1092
			if (is_ipaddr($ip))
1093
				fwrite($fd, "listen on $ip\n");
1094
		}
1095
	}
1096

    
1097
	fwrite($fd, "\n");
1098

    
1099
	/* slurp! */
1100
	fclose($fd);
1101

    
1102
	/* if openntpd is running, kill it */
1103
	while(is_process_running("ntpd")) {
1104
		exec("/usr/bin/killall ntpd");
1105
		sleep(3);
1106
	}
1107

    
1108
	/* if /var/empty does not exist, create it */
1109
	if(!is_dir("/var/empty"))
1110
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1111

    
1112
	sleep(1);
1113

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

    
1117
}
1118

    
1119
function sync_system_time() {
1120
	global $config, $g;
1121

    
1122
	$syscfg = $config['system'];
1123

    
1124
	if ($g['booting'])
1125
		echo "Syncing system time before startup...";
1126

    
1127
	/* foreach through servers and write out to ntpd.conf */
1128
	foreach (explode(' ', $syscfg['timeservers']) as $ts) {
1129
		mwexec("/usr/sbin/ntpdate -s $ts");
1130
	}
1131
	
1132
	if ($g['booting'])
1133
		echo "done.\n";
1134
	
1135
}
1136

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

    
1140
	system_reboot_cleanup();
1141

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

    
1145
function system_reboot() {
1146
	global $g;
1147

    
1148
	system_reboot_cleanup();
1149

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

    
1153
function system_reboot_sync() {
1154
	global $g;
1155

    
1156
	system_reboot_cleanup();
1157

    
1158
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1159
}
1160

    
1161
function system_reboot_cleanup() {
1162
	mwexec("/usr/local/bin/beep.sh stop");
1163
	captiveportal_radius_stop_all();
1164
}
1165

    
1166
function system_do_shell_commands($early = 0) {
1167
	global $config, $g;
1168
	if(isset($config['system']['developerspew'])) {
1169
		$mt = microtime();
1170
		echo "system_do_shell_commands() being called $mt\n";
1171
	}
1172

    
1173
	if ($early)
1174
		$cmdn = "earlyshellcmd";
1175
	else
1176
		$cmdn = "shellcmd";
1177

    
1178
	if (is_array($config['system'][$cmdn])) {
1179

    
1180
		/* *cmd is an array, loop through */
1181
		foreach ($config['system'][$cmdn] as $cmd) {
1182
			exec($cmd);
1183
		}
1184

    
1185
	} elseif($config['system'][$cmdn] <> "") {
1186

    
1187
		/* execute single item */
1188
		exec($config['system'][$cmdn]);
1189

    
1190
	}
1191
}
1192

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

    
1200
	if (isset($config['system']['disableconsolemenu'])) {
1201
		touch("{$g['varetc_path']}/disableconsole");
1202
	} else {
1203
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1204
	}
1205
}
1206

    
1207
function system_dmesg_save() {
1208
	global $g;
1209
	if(isset($config['system']['developerspew'])) {
1210
		$mt = microtime();
1211
		echo "system_dmesg_save() being called $mt\n";
1212
	}
1213

    
1214
	$dmesg = "";
1215
	exec("/sbin/dmesg", $dmesg);
1216

    
1217
	/* find last copyright line (output from previous boots may be present) */
1218
	$lastcpline = 0;
1219

    
1220
	for ($i = 0; $i < count($dmesg); $i++) {
1221
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1222
			$lastcpline = $i;
1223
	}
1224

    
1225
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1226
	if (!$fd) {
1227
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1228
		return 1;
1229
	}
1230

    
1231
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1232
		fwrite($fd, $dmesg[$i] . "\n");
1233

    
1234
	fclose($fd);
1235

    
1236
	return 0;
1237
}
1238

    
1239
function system_set_harddisk_standby() {
1240
	global $g, $config;
1241
	if(isset($config['system']['developerspew'])) {
1242
		$mt = microtime();
1243
		echo "system_set_harddisk_standby() being called $mt\n";
1244
	}
1245

    
1246
	if (isset($config['system']['harddiskstandby'])) {
1247
		if ($g['booting']) {
1248
			echo 'Setting hard disk standby... ';
1249
		}
1250

    
1251
		$standby = $config['system']['harddiskstandby'];
1252
		// Check for a numeric value
1253
		if (is_numeric($standby)) {
1254
			// Sync the disk(s)
1255
			mwexec('/bin/sync');
1256
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1257
				// Reinitialize ATA-drives
1258
				mwexec('/usr/local/sbin/atareinit');
1259
				if ($g['booting']) {
1260
					echo "done.\n";
1261
				}
1262
			} else if ($g['booting']) {
1263
				echo "failed!\n";
1264
			}
1265
		} else if ($g['booting']) {
1266
			echo "failed!\n";
1267
		}
1268
	}
1269
}
1270

    
1271
function system_setup_sysctl() {
1272
	global $config;
1273
	if(isset($config['system']['developerspew'])) {
1274
		$mt = microtime();
1275
		echo "system_setup_sysctl() being called $mt\n";
1276
	}
1277

    
1278
	activate_sysctls();	
1279

    
1280
	if (isset($config['system']['sharednet'])) {
1281
		system_disable_arp_wrong_if();
1282
	}
1283
}
1284

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

    
1295
function system_enable_arp_wrong_if() {
1296
	global $config;
1297
	if(isset($config['system']['developerspew'])) {
1298
		$mt = microtime();
1299
		echo "system_enable_arp_wrong_if() being called $mt\n";
1300
	}
1301
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1302
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1303
}
1304

    
1305
function enable_watchdog() {
1306
	global $config;
1307
	$install_watchdog = false;
1308
	$supported_watchdogs = array("Geode");
1309
	$file = file_get_contents("/var/log/dmesg.boot");
1310
	foreach($supported_watchdogs as $sd) {
1311
		if(stristr($file, "Geode")) {
1312
			$install_watchdog = true;
1313
		}
1314
	}
1315
	if($install_watchdog == true) {
1316
		if(is_process_running("watchdogd"))
1317
			exec("/usr/bin/killall watchdogd");
1318
		exec("/usr/sbin/watchdogd");
1319
	}
1320
}
1321

    
1322
?>
(22-22/29)