Project

General

Profile

Download (29.5 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 system_resolvconf_generate($dynupdate = false) {
36
	global $config, $g;
37
	if(isset($config['system']['developerspew'])) {
38
		$mt = microtime();
39
		echo "system_resolvconf_generate() being called $mt\n";
40
	}	
41

    
42
        $syscfg = $config['system'];
43

    
44
        $fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
45
        if (!$fd) {
46
                printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
47
                return 1;
48
        }
49

    
50
        $resolvconf = "domain {$syscfg['domain']}\n";
51

    
52
        $havedns = false;
53

    
54
        if (isset($syscfg['dnsallowoverride'])) {
55
                /* get dynamically assigned DNS servers (if any) */
56
		$ns = array_unique(get_nameservers());
57
		foreach($ns as $nameserver) {
58
			if($nameserver) {
59
				$resolvconf .= "nameserver $nameserver\n";
60
				$havedns = true;
61
			}
62
		}
63
        }
64
        if (!$havedns && is_array($syscfg['dnsserver'])) {
65
                foreach ($syscfg['dnsserver'] as $ns) {
66
                        if ($ns) {
67
                                $resolvconf .= "nameserver $ns\n";
68
				$havedns = true;
69
			}
70
                }
71
        }
72

    
73
        fwrite($fd, $resolvconf);
74
        fclose($fd);
75

    
76
        if (!$g['booting']) {
77
                /* restart dhcpd (nameservers may have changed) */
78
                if (!$dynupdate)
79
                        services_dhcpd_configure();
80
        }
81

    
82
        return 0;
83
}
84

    
85
function get_nameservers() {
86
	global $config, $g;
87
	$master_list = array();
88
	$dns_lists = split("\n", `ls /var/etc/nameserver_* 2>/dev/null`);
89
	foreach($dns_lists as $dns) {
90
		$items = split("\n", file_get_contents($dns));
91
		foreach($items as $item)
92
			if($item <> "")
93
				$master_list[] = $item;
94
	}
95
	if(!file_exists("/var/etc/nameservers.conf"))
96
		return $master_list;
97
	$dns = `cat /var/etc/nameservers.conf`;
98
	$dns_s = split("\n", $dns);
99
	foreach($dns_s as $dns) 
100
		$master_list[] = $dns;	
101
	return $master_list;
102
}
103

    
104
function system_hosts_generate() {
105
	global $config, $g;
106
	if(isset($config['system']['developerspew'])) {
107
		$mt = microtime();
108
		echo "system_hosts_generate() being called $mt\n";
109
	}
110

    
111
	$syscfg = $config['system'];
112
	$lancfg = $config['interfaces']['lan'];
113
	$dnsmasqcfg = $config['dnsmasq'];
114

    
115
	if (!is_array($dnsmasqcfg['hosts'])) {
116
		$dnsmasqcfg['hosts'] = array();
117
	}
118
	$hostscfg = $dnsmasqcfg['hosts'];
119

    
120
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
121
	if (!$fd) {
122
		printf("Error: cannot open hosts file in system_hosts_generate().\n");
123
		return 1;
124
	}
125

    
126
	$hosts = <<<EOD
127
127.0.0.1	localhost localhost.{$syscfg['domain']}
128
{$lancfg['ipaddr']}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}
129

    
130
EOD;
131

    
132
	foreach ($hostscfg as $host) {
133
		if ($host['host'])
134
			$hosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
135
		else
136
			$hosts .= "{$host['ip']}	{$host['domain']}\n";
137
	}
138
	fwrite($fd, $hosts);
139
	fclose($fd);
140

    
141
	return 0;
142
}
143

    
144
function system_hostname_configure() {
145
	global $config, $g;
146
	if(isset($config['system']['developerspew'])) {
147
		$mt = microtime();
148
		echo "system_hostname_configure() being called $mt\n";
149
	}	
150

    
151
	$syscfg = $config['system'];
152

    
153
	/* set hostname */
154
	return mwexec("/bin/hostname " .
155
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
156
}
157

    
158
function system_routing_configure() {
159
	global $config, $g;
160
	if(isset($config['system']['developerspew'])) {
161
		$mt = microtime();
162
		echo "system_routing_configure() being called $mt\n";
163
	}
164
	
165
	/* Enable fast routing, if enabled */
166
	if(isset($config['staticroutes']['enablefastrouting']))
167
		mwexec("/sbin/sysctl net.inet.ip.fastforwarding=1");
168

    
169
	/* clear out old routes, if necessary */
170
	if (file_exists("{$g['vardb_path']}/routes.db")) {
171
		$fd = fopen("{$g['vardb_path']}/routes.db", "r");
172
		if (!$fd) {
173
			printf("Error: cannot open routes DB file in system_routing_configure().\n");
174
			return 1;
175
		}
176
		while (!feof($fd)) {
177
			$oldrt = fgets($fd);
178
			if ($oldrt)
179
				mwexec("/sbin/route delete " . escapeshellarg($oldrt));
180
		}
181
		fclose($fd);
182
		unlink("{$g['vardb_path']}/routes.db");
183
	}
184

    
185
	if (is_array($config['staticroutes']['route'])) {
186

    
187
		$fd = fopen("{$g['vardb_path']}/routes.db", "w");
188
		if (!$fd) {
189
			printf("Error: cannot open routes DB file in system_routing_configure().\n");
190
			return 1;
191
		}
192

    
193
		foreach ($config['staticroutes']['route'] as $rtent) {
194
			mwexec("/sbin/route add " . escapeshellarg($rtent['network']) .
195
				" " . escapeshellarg($rtent['gateway']));
196

    
197
			/* record route so it can be easily removed later (if necessary) */
198
			fwrite($fd, $rtent['network'] . "\n");
199
		}
200

    
201
		fclose($fd);
202
	}
203

    
204
	return 0;
205
}
206

    
207
function system_routing_enable() {
208
	global $config, $g;
209
	if(isset($config['system']['developerspew'])) {
210
		$mt = microtime();
211
		echo "system_routing_enable() being called $mt\n";
212
	}
213

    
214
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
215
}
216

    
217
function system_syslogd_start() {
218
	global $config, $g;
219
	if(isset($config['system']['developerspew'])) {
220
		$mt = microtime();
221
		echo "system_syslogd_start() being called $mt\n";
222
	}
223

    
224
	$syslogcfg = $config['syslog'];
225

    
226
	if ($g['booting'])
227
		echo "Starting syslog... ";
228
	else
229
		killbypid("{$g['varrun_path']}/syslog.pid");
230

    
231
	if (isset($syslogcfg)) {
232
		if($config['installedpackages']['package']) {
233
                        foreach($config['installedpackages']['package'] as $package) {
234
                                if($package['logging']) {	
235
					$pkgfacilities[] = $package['logging']['facilityname'];
236
					$facilitylist = implode(',', $pkgfacilities);
237
					mwexec("clog -i -s 10000 {$g['varlog_path']}/{$package['logging']['logfilename']}");
238
                                	$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t%{$g['varlog_path']}/{$package['logging']['logfilename']}\n!-{$facilitylist}\n";
239
				}
240
                        }
241
                }
242
		/* write syslog.conf */
243
		$fd = fopen("{$g['varetc_path']}/syslog.conf", "w");
244
		if (!$fd) {
245
			printf("Error: cannot open syslog.conf in system_syslogd_start().\n");
246
			return 1;
247
		}
248
		if (!isset($syslogcfg['disablelocallogging'])) {
249
		$syslogconf .= <<<EOD
250
!racoon
251
*.*						%{$g['varlog_path']}/ipsec.log
252
!-racoon,{$facilitylist}
253
local0.*					%{$g['varlog_path']}/filter.log
254
local3.*					%{$g['varlog_path']}/vpn.log
255
local4.*					%{$g['varlog_path']}/portalauth.log
256
local7.*					%{$g['varlog_path']}/dhcpd.log
257
*.notice;kern.debug;lpr.info;mail.crit;		%{$g['varlog_path']}/system.log
258
news.err;local0.none;local3.none;local4.none;	%{$g['varlog_path']}/system.log
259
local7.none					%{$g['varlog_path']}/system.log
260
security.*					%{$g['varlog_path']}/system.log
261
auth.info;authpriv.info;daemon.info		%{$g['varlog_path']}/system.log
262
local1.*					%{$g['varlog_path']}/slbd.log
263
*.emerg						*
264

    
265
EOD;
266
		}
267

    
268
		if (isset($syslogcfg['filter'])) {
269
			$syslogconf .= <<<EOD
270
local0.*					@{$syslogcfg['remoteserver']}
271

    
272
EOD;
273
		}
274

    
275
		if (isset($syslogcfg['vpn'])) {
276
			$syslogconf .= <<<EOD
277
local3.*					@{$syslogcfg['remoteserver']}
278

    
279
EOD;
280
		}
281

    
282

    
283
		if (isset($syslogcfg['portalauth'])) {
284
			$syslogconf .= <<<EOD
285
local4.*					@{$syslogcfg['remoteserver']}
286

    
287
EOD;
288
		}
289

    
290

    
291
		if (isset($syslogcfg['dhcp'])) {
292
			$syslogconf .= <<<EOD
293
local7.*					@{$syslogcfg['remoteserver']}
294

    
295
EOD;
296
		}
297

    
298
		if (isset($syslogcfg['system'])) {
299
			$syslogconf .= <<<EOD
300
*.notice;kern.debug;lpr.info;mail.crit;		@{$syslogcfg['remoteserver']}
301
news.err;local0.none;local3.none;local7.none	@{$syslogcfg['remoteserver']}
302
security.*					@{$syslogcfg['remoteserver']}
303
auth.info;authpriv.info;daemon.info		@{$syslogcfg['remoteserver']}
304
*.emerg						@{$syslogcfg['remoteserver']}
305
EOD;
306
		}
307
		fwrite($fd, $syslogconf);
308
		fclose($fd);
309

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

    
312
	} else {
313
		$retval = mwexec("/usr/sbin/syslogd -ss");
314
	}
315

    
316
	if ($g['booting'])
317
		echo "done.\n";
318

    
319
	return $retval;
320
}
321

    
322
function system_pccard_start() {
323
	global $config, $g;
324
	if(isset($config['system']['developerspew'])) {
325
		$mt = microtime();
326
		echo "system_pccard_start() being called $mt\n";
327
	}
328

    
329
	if ($g['booting'])
330
		echo "Initializing PCMCIA... ";
331

    
332
	/* kill any running pccardd */
333
	killbypid("{$g['varrun_path']}/pccardd.pid");
334

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

    
338
	if ($g['booting']) {
339
		if ($res == 0)
340
			echo "done.\n";
341
		else
342
			echo "failed!\n";
343
	}
344

    
345
	return $res;
346
}
347

    
348

    
349
function system_webgui_start() {
350
	global $config, $g;
351

    
352
	if ($g['booting'])
353
		echo "Starting webConfigurator... ";
354

    
355
	/* kill any running mini_httpd */
356
	killbypid("{$g['varrun_path']}/lighty-webConfigurator.pid");
357

    
358
	sleep(1);
359

    
360
	/* generate password file */
361
	system_password_configure();
362

    
363
	chdir($g['www_path']);
364

    
365
	/* non-standard port? */
366
	if ($config['system']['webgui']['port'])
367
		$portarg = "{$config['system']['webgui']['port']}";
368
	else
369
		$portarg = "";
370

    
371
	if ($config['system']['webgui']['protocol'] == "https") {
372

    
373
	if(!$config['system']['webgui']['port'])
374
		$portarg = "443";
375

    
376
		if ($config['system']['webgui']['certificate'] && $config['system']['webgui']['private-key']) {
377
			$cert = base64_decode($config['system']['webgui']['certificate']);
378
			$key = base64_decode($config['system']['webgui']['private-key']);
379
		} else {
380
			/* default certificate/key */
381
			$cert = <<<EOD
382
-----BEGIN CERTIFICATE-----
383
MIIC4zCCAkygAwIBAgIBADANBgkqhkiG9w0BAQQFADBbMQswCQYDVQQGEwJOQTEL
384
MAkGA1UECBMCTkExCzAJBgNVBAcTAk5BMQswCQYDVQQKEwJOQTELMAkGA1UECxMC
385
TkExCzAJBgNVBAMTAk5BMQswCQYDVQQGEwJVUzAeFw0wNTAzMDYwMDE1NDJaFw0x
386
NTAzMDQwMDE1NDJaMFsxCzAJBgNVBAYTAk5BMQswCQYDVQQIEwJOQTELMAkGA1UE
387
BxMCTkExCzAJBgNVBAoTAk5BMQswCQYDVQQLEwJOQTELMAkGA1UEAxMCTkExCzAJ
388
BgNVBAYTAlVTMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDF7luuy70OvHrl
389
xnW9ID6srsfxEFCF4d9LmlZ6XdW1rEUHQ6KTgz4iSD+pxEOxxlY+bCH6HTkAy5Sa
390
zt3eT7javvF+ILZgarwoY2x+NbDctd0VBJVkH0fEvBf1xqU7wpkOiWkw1RmfEvZI
391
6XnGi6VSjSmkm0UoQMKg9R7niRtE4QIDAQABo4G2MIGzMB0GA1UdDgQWBBTgvk9F
392
alPK6/OcZrkaE8BhBrRo2DCBgwYDVR0jBHwweoAU4L5PRWpTyuvznGa5GhPAYQa0
393
aNihX6RdMFsxCzAJBgNVBAYTAk5BMQswCQYDVQQIEwJOQTELMAkGA1UEBxMCTkEx
394
CzAJBgNVBAoTAk5BMQswCQYDVQQLEwJOQTELMAkGA1UEAxMCTkExCzAJBgNVBAYT
395
AlVTggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEEBQADgYEAv9+GXdYIWs2R
396
8B0zI4jAbHcaRsfohuzpNHD5re7ZK8H4fYbHIfmPY2UM3yOU7J2rLP8KGfKztay1
397
Z3RNW7SKJI/CagbdQOuYdMrlEyA4ZImM6NNzUbH6rNKtmDIDo1kHL3cXjzXEjBE+
398
ZZYTREFcdhtzUH5lYzJz1uVFeCSwozk=
399
-----END CERTIFICATE-----
400
EOD;
401

    
402
			$key = <<<EOD
403
-----BEGIN RSA PRIVATE KEY-----
404
MIICXAIBAAKBgQDF7luuy70OvHrlxnW9ID6srsfxEFCF4d9LmlZ6XdW1rEUHQ6KT
405
gz4iSD+pxEOxxlY+bCH6HTkAy5Sazt3eT7javvF+ILZgarwoY2x+NbDctd0VBJVk
406
H0fEvBf1xqU7wpkOiWkw1RmfEvZI6XnGi6VSjSmkm0UoQMKg9R7niRtE4QIDAQAB
407
AoGAF9dMJ9PWo+3EB+VNzUgTBI3Q+5JxgI7ibKLcg8TFtypW7jcRYB9Q3qRBNtuz
408
I7i2LrKrrQrUEOp0rej5BIwpwcjtEE2NsZwgYwDyywptoqt3WO86nPXYz2KhkQmP
409
YCDmPrff4vXCv6zgefb/AIgrOkgD3ViEoePhCAg+0l3fEIECQQD7C68Nb6KAWUND
410
Q9B0RxYrlgXikQ8yVHhlyM433APe/NCJ9kl5dLXpyjuvrWB+ml6TlLrcroLGejbd
411
tYXvIiyJAkEAydZVHqB4MpMtuY7VJoHNgl06YBoeTI+BJptPaOUNl4SlUKIYJMhX
412
oOXIGk9uDjfSNS7HvunZBjgz092GShWvmQJAQ8NhmwTZHj/58fwqFljh2R4DtKZn
413
LbSzUvYjA9z1holDWRoLtycTu2mFNuRbuZC9mqR40/ye/CgdCzdmUagt0QJBAKq1
414
00ySINd10Cive+yTwMPQIj2CGbpbbbq/hYyMntBWapQmZRFHOYZmkrZeFBGGeQ5u
415
QJdipiIyivNY2+nxKZECQCvumJPfZYxCeCAEC+G2xezrP6bC6FhzUOw6410UARTM
416
fuFjHpSfOiG62lfRdZgCPAr1L/1pJF+8RqjGlFfAuFA=
417
-----END RSA PRIVATE KEY-----
418
EOD;
419
		}
420
	} else {
421
		$cert = "";
422
		$key = "";
423
	}
424

    
425
	/* generate lighttpd configuration */
426
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
427
		$cert, $key, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/");
428

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

    
432
	if ($g['booting']) {
433
		if ($res == 0)
434
			echo "done.\n";
435
		else
436
			echo "failed!\n";
437
	}
438

    
439
	return $res;
440
}
441

    
442
function system_webgui_start_old() {
443
	global $config, $g;
444
	if(isset($config['system']['developerspew'])) {
445
		$mt = microtime();
446
		echo "system_webgui_start() being called $mt\n";
447
	}
448

    
449
        if ($g['booting'])
450
                echo "Starting webConfigurator... ";
451

    
452
        /* kill any running mini_httpd */
453
        killbypid("{$g['varrun_path']}/mini_httpd.pid");
454

    
455
        /* generate password file */
456
        system_password_configure();
457

    
458
        chdir($g['www_path']);
459

    
460
        /* non-standard port? */
461
        if ($config['system']['webgui']['port'])
462
                $portarg = "-p {$config['system']['webgui']['port']}";
463
        else
464
                $portarg = "";
465

    
466
        if ($config['system']['webgui']['protocol'] == "https") {
467

    
468
                if ($config['system']['webgui']['certificate'] && $config['system']['webgui']['private-key']) {
469
                        $cert = base64_decode($config['system']['webgui']['certificate']);
470
                        $key = base64_decode($config['system']['webgui']['private-key']);
471
                } else {
472
                        /* default certificate/key */
473
                        $cert = <<<EOD
474
-----BEGIN CERTIFICATE-----
475
MIIBlDCB/gIBADANBgkqhkiG9w0BAQQFADATMREwDwYDVQQKEwhtMG4wd2FsbDAe
476
Fw0wNTA1MTAxMjI0NDRaFw0wNzA1MTAxMjI0NDRaMBMxETAPBgNVBAoTCG0wbjB3
477
YWxsMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDAShszhFz+o8lsMWTGgTxs
478
TMPR+v4+qL5jXDyY97MLTGFK7aqQOtpIQc+TcTc4jklgOVlHoR7oBXrsi8YrbCd+
479
83LPQmQoSPC0VqhfU3uYf3NzxiK8r97aPCsmWgwT2pQ6TcESTm6sF7nLprOf/zFP
480
C4jE2fvjkbzyVolPywBuewIDAQABMA0GCSqGSIb3DQEBBAUAA4GBAFR962c4R5tV
481
cTn0OQcszYoW6WC+ini9tQQh5ku5jYDAiC+00atawJEVLnL3lwAcpSKTIWlTkD20
482
tl3lz5br1qFgYky+Rd0kwS2nk9jRbkxSXxd6KJVnNRCKre28aw3ENzZfCSurPQsX
483
UPp5er+NtwMT1g7s/JDmKTC4w1rGr5/c
484
-----END CERTIFICATE-----
485

    
486
EOD;
487

    
488
                        $key = <<<EOD
489
-----BEGIN RSA PRIVATE KEY-----
490
MIICXQIBAAKBgQDAShszhFz+o8lsMWTGgTxsTMPR+v4+qL5jXDyY97MLTGFK7aqQ
491
OtpIQc+TcTc4jklgOVlHoR7oBXrsi8YrbCd+83LPQmQoSPC0VqhfU3uYf3NzxiK8
492
r97aPCsmWgwT2pQ6TcESTm6sF7nLprOf/zFPC4jE2fvjkbzyVolPywBuewIDAQAB
493
AoGAbJJrQW9fQrggJuLMz/hwsYW2m31oyOBmf5u463YQtjRuSuxe/gj87weZuNqY
494
H2rXq2k2K+ehl8hgW+egASyUL3L7kCkEAsVREujKTEyhSqqIRDPWTxo9S/YA9Gvn
495
2ZnJvkrcKjqCO9aHX3rvJOK/ErYI6akctgI3KmgkYw5XNmECQQDuZU97RTWH9rmP
496
aQr57ysNXxgFsyhetOOqeYkPtIVwpOiNbfwE1zi5RGdtO4Ku3fG1lV4J2UoWJ9yD
497
awdoyYIHAkEAzn0xJ90IjPsHk+8SODEj5JGdHSZPNu1tgtrbjEi9sfGWg4K7XTxr
498
QW90pWb1bKKU1uh5FzW6OhnFfuQXt1kC7QJAPSthqY+onKqCEnoxhtAHi/bKgyvl
499
P+fKQwPMV2tKkgy+XwvJjrRqqZ8TqsOKVLQ+QQmCh6RpjiXMPyxHSmvqIQJBAKLR
500
HF1ucDuaBROkwx0DwmWMW/KMLpIFDQDNSaiIAuu4rxHrl4mhBoGGPNffI04RtILw
501
s+qVNs5xW8T+XaT4ztECQQDFHPnZeoPWE5z+AX/UUQIUWaDExz3XRzmIxRbOrlFi
502
CsF1s0TdJLi/wzNQRAL37A8vqCeVFR/ng3Xpg96Yg+8Z
503
-----END RSA PRIVATE KEY-----
504

    
505
EOD;
506
                }
507

    
508
                $fd = fopen("{$g['varetc_path']}/cert.pem", "w");
509
                if (!$fd) {
510
                        printf("Error: cannot open cert.pem in system_webgui_start().\n");
511
                        return 1;
512
                }
513
                chmod("{$g['varetc_path']}/cert.pem", 0600);
514
                fwrite($fd, $cert);
515
                fwrite($fd, "\n");
516
                fwrite($fd, $key);
517
                fclose($fd);
518

    
519
                $res = mwexec("/usr/local/sbin/mini_httpd -S -E {$g['varetc_path']}/cert.pem" .
520
                        " -c \"**.php|**.cgi\" -u root -maxproc 16 $portarg" .
521
                        " -i {$g['varrun_path']}/mini_httpd.pid");
522
        } else {
523
                $res = mwexec("/usr/local/sbin/mini_httpd -c \"**.php|**.cgi\" -u root" .
524
                        " -maxproc 16 $portarg -i {$g['varrun_path']}/mini_httpd.pid");
525
        }
526

    
527
        if ($g['booting']) {
528
                if ($res == 0)
529
                        echo "done\n";
530
                else
531
                        echo "failed\n";
532
        }
533

    
534
        return $res;
535
}
536

    
537
function system_generate_lighty_config($filename,
538
	$cert,
539
	$key,
540
	$pid_file,
541
	$port = 80,
542
	$document_root = "/usr/local/www/",
543
	$cert_location = "cert.pem",
544
	$max_procs = 2,
545
	$max_requests = "1",
546
	$fast_cgi_enable = true,
547
	$captive_portal = false) {
548

    
549
	global $config, $g;
550

    
551
	if(isset($config['system']['developerspew'])) {
552
		$mt = microtime();
553
		echo "system_generate_lighty_config() being called $mt\n";
554
	}
555

    
556
	if($captive_portal == true)  {
557
		$captiveportal = ",\"mod_rewrite\"";
558
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*)\" => \"/index.php?redirurl=$1\" )";
559
	}
560

    
561
	if($port <> "")
562
		$lighty_port = $port;
563
	else
564
		$lighty_port = "80";
565

    
566
	$memory = get_memory();
567
	$avail = $memory[0];
568

    
569
	if($avail > 0 and $avail < 65) {
570
		$max_procs = 1;
571
		$max_requests = 1;
572
	}
573
		
574
	if($fast_cgi_enable == true) {
575
		$module = "\"mod_fastcgi\", \"mod_cgi\"";
576
		$cgi_config = "";
577
		$fastcgi_config = <<<EOD
578
#### fastcgi module
579
## read fastcgi.txt for more info
580
fastcgi.server             = ( ".php" =>
581
                               ( "localhost" =>
582
                                 (
583
                                   "socket" => "/tmp/php-fastcgi.socket",
584
				   "min-procs" => 1,
585
				   "max-procs" => {$max_procs},
586
				   "max-load-per-proc" => 1,
587
				   "idle-timeout" => 1,
588
				   "bin-environment" => ( 
589
				      "PHP_FCGI_CHILDREN" => "{$max_procs}",
590
				      "PHP_FCGI_MAX_REQUESTS" => "{$max_requests}"
591
				   ),				   
592
                                   "bin-path" => "/usr/local/bin/php"
593
                                 )
594
                               )
595
                            )		
596

    
597
#### CGI module
598
cgi.assign                 = ( ".cgi" => "" )
599

    
600
EOD;
601
	} else {
602
		$fastcgi_config = "";
603
		$module = "\"mod_cgi\"";
604
		$cgi_config = <<<EOD
605
#### CGI module
606
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
607
                               ".cgi" => "" )
608
		
609
EOD;
610
	}
611
	
612
	$lighty_config .= <<<EOD
613
#
614
# lighttpd configuration file
615
#
616
# use a it as base for lighttpd 1.0.0 and above
617
#
618
############ Options you really have to take care of ####################
619

    
620
# FreeBSD!
621
server.event-handler        = "freebsd-kqueue"
622

    
623
## modules to load
624
server.modules              =   (
625
				  "mod_access",
626
                                  {$module}{$captiveportal}
627
				)
628

    
629
## Unused modules
630
#                               "mod_setenv",
631
#                               "mod_compress"
632
#				"mod_redirect",
633
#                               "mod_rewrite",
634
#                               "mod_ssi",
635
#                               "mod_usertrack",
636
#                               "mod_expire",
637
#                               "mod_secdownload",
638
#                               "mod_rrdtool",
639
#                               "mod_auth",
640
#                               "mod_status",
641
#                               "mod_alias",
642
#                               "mod_proxy",
643
#                               "mod_simple_vhost",
644
#                               "mod_evhost",
645
#                               "mod_userdir",
646
#                               "mod_cgi",
647
#                                "mod_accesslog"
648

    
649
## a static document-root, for virtual-hosting take look at the
650
## server.virtual-* options
651
server.document-root        = "{$document_root}"
652
{$captive_portal_rewrite}
653

    
654
## where to send error-messages to
655
#server.errorlog             = "/var/log/lighttpd.error.log"
656

    
657
# files to check for if .../ is requested
658
server.indexfiles           = ( "index.php", "index.html",
659
                                "index.htm", "default.htm" )
660

    
661
# mimetype mapping
662
mimetype.assign             = (
663
  ".pdf"          =>      "application/pdf",
664
  ".sig"          =>      "application/pgp-signature",
665
  ".spl"          =>      "application/futuresplash",
666
  ".class"        =>      "application/octet-stream",
667
  ".ps"           =>      "application/postscript",
668
  ".torrent"      =>      "application/x-bittorrent",
669
  ".dvi"          =>      "application/x-dvi",
670
  ".gz"           =>      "application/x-gzip",
671
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
672
  ".swf"          =>      "application/x-shockwave-flash",
673
  ".tar.gz"       =>      "application/x-tgz",
674
  ".tgz"          =>      "application/x-tgz",
675
  ".tar"          =>      "application/x-tar",
676
  ".zip"          =>      "application/zip",
677
  ".mp3"          =>      "audio/mpeg",
678
  ".m3u"          =>      "audio/x-mpegurl",
679
  ".wma"          =>      "audio/x-ms-wma",
680
  ".wax"          =>      "audio/x-ms-wax",
681
  ".ogg"          =>      "audio/x-wav",
682
  ".wav"          =>      "audio/x-wav",
683
  ".gif"          =>      "image/gif",
684
  ".jpg"          =>      "image/jpeg",
685
  ".jpeg"         =>      "image/jpeg",
686
  ".png"          =>      "image/png",
687
  ".xbm"          =>      "image/x-xbitmap",
688
  ".xpm"          =>      "image/x-xpixmap",
689
  ".xwd"          =>      "image/x-xwindowdump",
690
  ".css"          =>      "text/css",
691
  ".html"         =>      "text/html",
692
  ".htm"          =>      "text/html",
693
  ".js"           =>      "text/javascript",
694
  ".asc"          =>      "text/plain",
695
  ".c"            =>      "text/plain",
696
  ".conf"         =>      "text/plain",
697
  ".text"         =>      "text/plain",
698
  ".txt"          =>      "text/plain",
699
  ".dtd"          =>      "text/xml",
700
  ".xml"          =>      "text/xml",
701
  ".mpeg"         =>      "video/mpeg",
702
  ".mpg"          =>      "video/mpeg",
703
  ".mov"          =>      "video/quicktime",
704
  ".qt"           =>      "video/quicktime",
705
  ".avi"          =>      "video/x-msvideo",
706
  ".asf"          =>      "video/x-ms-asf",
707
  ".asx"          =>      "video/x-ms-asf",
708
  ".wmv"          =>      "video/x-ms-wmv",
709
  ".bz2"          =>      "application/x-bzip",
710
  ".tbz"          =>      "application/x-bzip-compressed-tar",
711
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
712
 )
713

    
714
# Use the "Content-Type" extended attribute to obtain mime type if possible
715
#mimetypes.use-xattr        = "enable"
716

    
717
#### accesslog module
718
#accesslog.filename          = "/dev/null"
719

    
720
## deny access the file-extensions
721
#
722
# ~    is for backupfiles from vi, emacs, joe, ...
723
# .inc is often used for code includes which should in general not be part
724
#      of the document-root
725
url.access-deny             = ( "~", ".inc" )
726

    
727

    
728
######### Options that are good to be but not neccesary to be changed #######
729

    
730
## bind to port (default: 80)
731
server.port                = {$lighty_port}
732

    
733
## error-handler for status 404
734
#server.error-handler-404   = "/error-handler.html"
735
#server.error-handler-404   = "/error-handler.php"
736

    
737
## to help the rc.scripts
738
server.pid-file            = "/var/run/{$pid_file}"
739

    
740
## virtual directory listings
741
server.dir-listing         = "disable"
742

    
743
## enable debugging
744
debug.log-request-header   = "disable"
745
debug.log-response-header  = "disable"
746
debug.log-request-handling = "disable"
747
debug.log-file-not-found   = "disable"
748

    
749
#### compress module
750
#compress.cache-dir         = "/tmp/lighttpd/cache/compress/"
751
#compress.filetype          = ("text/plain", "text/html")
752

    
753
{$fastcgi_config}
754

    
755
{$cgi_config}
756

    
757
EOD;
758

    
759
	if($cert <> "" and $key <> "") {
760
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
761
		if (!$fd) {
762
			printf("Error: cannot open cert.pem in system_webgui_start().\n");
763
			return 1;
764
		}
765
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
766
		fwrite($fd, $cert);
767
		fwrite($fd, "\n");
768
		fwrite($fd, $key);
769
		fclose($fd);
770
		$lighty_config .= "\n";
771
		$lighty_config .= "## ssl configuration\n";
772
		$lighty_config .= "ssl.engine = \"enable\"\n";
773
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";	
774
	}
775

    
776
	$fd = fopen("{$filename}", "w");
777
	if (!$fd) {
778
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
779
		return 1;
780
	}
781
	fwrite($fd, $lighty_config);
782
	fclose($fd);
783

    
784
	return 0;
785

    
786
}
787

    
788
function system_password_configure() {
789
	global $config, $g;
790
	if(isset($config['system']['developerspew'])) {
791
		$mt = microtime();
792
		echo "system_password_configure() being called $mt\n";
793
	}
794

    
795
	/* sync passwords */
796
	sync_webgui_passwords();
797

    
798
	/* !NOTE! conf_mount_ro is done by sync_webgui_passwords() */
799

    
800
	return 0;
801
}
802

    
803
function system_timezone_configure() {
804
	global $config, $g;
805
	if(isset($config['system']['developerspew'])) {
806
		$mt = microtime();
807
		echo "system_timezone_configure() being called $mt\n";
808
	}	
809

    
810
	$syscfg = $config['system'];
811

    
812
	if ($g['booting'])
813
		echo "Setting timezone... ";
814

    
815
	/* extract appropriate timezone file */
816
	$timezone = $syscfg['timezone'];
817
	if (!$timezone)
818
		$timezone = "Etc/UTC";
819

    
820
	conf_mount_rw();
821

    
822
	exec("/usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
823
		escapeshellarg($timezone) . " > /etc/localtime");
824

    
825
	conf_mount_ro();
826

    
827
	if ($g['booting'])
828
		echo "done.\n";
829
}
830

    
831
function system_ntp_configure() {
832
	global $config, $g;
833
	if(isset($config['system']['developerspew'])) {
834
		$mt = microtime();
835
		echo "system_ntp_configure() being called $mt\n";
836
	}
837

    
838
	$syscfg = $config['system'];
839

    
840
	if ($g['booting'])
841
		echo "Starting NTP client... ";
842
	else {
843
		killbypid("{$g['varrun_path']}/runmsntp.pid");
844
		killbypid("{$g['varrun_path']}/msntp.pid");
845
	}
846

    
847
	/* start ntp client if needed - needs to be forced into background */
848
	$updateinterval = $syscfg['time-update-interval'];
849

    
850
	if ($updateinterval > 0) {
851
		if ($updateinterval < 6)
852
			$updateinterval = 6;
853

    
854
		$timeservers = "";
855
		foreach (explode(' ', $syscfg['timeservers']) as $ts)
856
			$timeservers .= " " . $ts;
857

    
858
		mwexec_bg("/usr/local/bin/runmsntp.sh " .
859
			escapeshellarg("{$g['varrun_path']}/runmsntp.pid") . " " .
860
			escapeshellarg("{$g['varrun_path']}/msntp.pid") . " " .
861
			escapeshellarg($updateinterval) . " " .
862
			escapeshellarg($timeservers));
863
	}
864

    
865
	if ($g['booting'])
866
		echo "done.\n";
867
}
868

    
869
function system_halt() {
870
	global $g;
871

    
872
	system_reboot_cleanup();
873

    
874
	mwexec("nohup /etc/rc.halt > /dev/null 2>&1 &");
875
}
876

    
877
function system_reboot() {
878
	global $g;
879

    
880
	system_reboot_cleanup();
881

    
882
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
883
}
884

    
885
function system_reboot_sync() {
886
	global $g;
887

    
888
	system_reboot_cleanup();
889

    
890
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
891
}
892

    
893
function system_reboot_cleanup() {
894
	mwexec("/usr/local/bin/beep.sh stop");
895
	captiveportal_radius_stop_all();
896
}
897

    
898
function system_do_shell_commands($early = 0) {
899
	global $config, $g;
900
	if(isset($config['system']['developerspew'])) {
901
		$mt = microtime();
902
		echo "system_do_shell_commands() being called $mt\n";
903
	}
904

    
905
	if ($early)
906
		$cmdn = "earlyshellcmd";
907
	else
908
		$cmdn = "shellcmd";
909

    
910
	if (is_array($config['system'][$cmdn])) {
911
		
912
		/* *cmd is an array, loop through */
913
		foreach ($config['system'][$cmdn] as $cmd) {
914
			exec($cmd);
915
		}
916

    
917
	} elseif($config['system'][$cmdn] <> "") {
918
		
919
		/* execute single item */
920
		exec($config['system'][$cmdn]);
921

    
922
	}
923
}
924

    
925
function system_console_configure() {
926
	global $config, $g;
927
	if(isset($config['system']['developerspew'])) {
928
		$mt = microtime();
929
		echo "system_console_configure() being called $mt\n";
930
	}	
931

    
932
	if (isset($config['system']['disableconsolemenu'])) {
933
		touch("{$g['varetc_path']}/disableconsole");
934
	} else {
935
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
936
	}
937
}
938

    
939
function system_dmesg_save() {
940
	global $g;
941
	if(isset($config['system']['developerspew'])) {
942
		$mt = microtime();
943
		echo "system_dmesg_save() being called $mt\n";
944
	}
945

    
946
	$dmesg = "";
947
	exec("/sbin/dmesg", $dmesg);
948

    
949
	/* find last copyright line (output from previous boots may be present) */
950
	$lastcpline = 0;
951

    
952
	for ($i = 0; $i < count($dmesg); $i++) {
953
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
954
			$lastcpline = $i;
955
	}
956

    
957
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
958
	if (!$fd) {
959
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
960
		return 1;
961
	}
962

    
963
	for ($i = $lastcpline; $i < count($dmesg); $i++)
964
		fwrite($fd, $dmesg[$i] . "\n");
965

    
966
	fclose($fd);
967

    
968
	return 0;
969
}
970

    
971
function system_set_harddisk_standby() {
972
	global $g, $config;
973
	if(isset($config['system']['developerspew'])) {
974
		$mt = microtime();
975
		echo "system_set_harddisk_standby() being called $mt\n";
976
	}
977

    
978
	if (isset($config['system']['harddiskstandby'])) {
979
		if ($g['booting']) {
980
			echo 'Setting hard disk standby... ';
981
		}
982

    
983
		$standby = $config['system']['harddiskstandby'];
984
		// Check for a numeric value
985
		if (is_numeric($standby)) {
986
			// Sync the disk(s)
987
			mwexec('/bin/sync');
988
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
989
				// Reinitialize ATA-drives
990
				mwexec('/usr/local/sbin/atareinit');
991
				if ($g['booting']) {
992
					echo "done.\n";
993
				}
994
			} else if ($g['booting']) {
995
				echo "failed!\n";
996
			}
997
		} else if ($g['booting']) {
998
			echo "failed!\n";
999
		}
1000
	}
1001
}
1002

    
1003
function system_setup_sysctl() {
1004
	global $config;
1005
	if(isset($config['system']['developerspew'])) {
1006
		$mt = microtime();
1007
		echo "system_setup_sysctl() being called $mt\n";
1008
	}
1009

    
1010
	$sysctl = return_filename_as_array("/etc/sysctl.conf");
1011
	foreach($sysctl as $sysc) {
1012
		if($sysc <> "")
1013
			mwexec("sysctl {$sysc}");
1014
	}
1015
	if (isset($config['system']['sharednet'])) {
1016
		system_disable_arp_wrong_if();
1017
	}
1018
}
1019

    
1020
function system_disable_arp_wrong_if() {
1021
	global $config;
1022
	if(isset($config['system']['developerspew'])) {
1023
		$mt = microtime();
1024
		echo "system_disable_arp_wrong_if() being called $mt\n";
1025
	}	
1026
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1027
}
1028

    
1029
function system_enable_arp_wrong_if() {
1030
	global $config;
1031
	if(isset($config['system']['developerspew'])) {
1032
		$mt = microtime();
1033
		echo "system_enable_arp_wrong_if() being called $mt\n";
1034
	}
1035
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1036
}
1037

    
1038

    
1039
?>
(20-20/27)