Project

General

Profile

Download (28.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 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
                $nfd = @fopen("{$g['varetc_path']}/nameservers.conf", "r");
57
                if ($nfd) {
58
                        while (!feof($nfd)) {
59
                                $dnss = trim(fgets($nfd));
60
                                if ($dnss) {
61
                                        $resolvconf .= "nameserver $dnss\n";
62
                                        $havedns = true;
63
                                }
64
                        }
65
                        fclose($nfd);
66
                }
67
        }
68
        if (!$havedns && is_array($syscfg['dnsserver'])) {
69
                foreach ($syscfg['dnsserver'] as $ns) {
70
                        if ($ns)
71
                                $resolvconf .= "nameserver $ns\n";
72
                        $havedns = true;
73
                }
74
        }
75

    
76
        fwrite($fd, $resolvconf);
77
        fclose($fd);
78

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

    
85
        return 0;
86
}
87

    
88
function system_hosts_generate() {
89
	global $config, $g;
90
	if(isset($config['system']['developerspew'])) {
91
		$mt = microtime();
92
		echo "system_hosts_generate() being called $mt\n";
93
	}
94

    
95
	$syscfg = $config['system'];
96
	$lancfg = $config['interfaces']['lan'];
97
	$dnsmasqcfg = $config['dnsmasq'];
98

    
99
	if (!is_array($dnsmasqcfg['hosts'])) {
100
		$dnsmasqcfg['hosts'] = array();
101
	}
102
	$hostscfg = $dnsmasqcfg['hosts'];
103

    
104
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
105
	if (!$fd) {
106
		printf("Error: cannot open hosts file in system_hosts_generate().\n");
107
		return 1;
108
	}
109

    
110
	$hosts = <<<EOD
111
127.0.0.1	localhost localhost.{$syscfg['domain']}
112
{$lancfg['ipaddr']}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}
113

    
114
EOD;
115

    
116
	foreach ($hostscfg as $host) {
117
		if ($host['host'])
118
			$hosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
119
		else
120
			$hosts .= "{$host['ip']}	{$host['domain']}\n";
121
	}
122
	fwrite($fd, $hosts);
123
	fclose($fd);
124

    
125
	return 0;
126
}
127

    
128
function system_hostname_configure() {
129
	global $config, $g;
130
	if(isset($config['system']['developerspew'])) {
131
		$mt = microtime();
132
		echo "system_hostname_configure() being called $mt\n";
133
	}	
134

    
135
	$syscfg = $config['system'];
136

    
137
	/* set hostname */
138
	return mwexec("/bin/hostname " .
139
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
140
}
141

    
142
function system_routing_configure() {
143
	global $config, $g;
144
	if(isset($config['system']['developerspew'])) {
145
		$mt = microtime();
146
		echo "system_routing_configure() being called $mt\n";
147
	}
148
	
149
	/* Enable fast routing, if enabled */
150
	if(isset($config['staticroutes']['enablefastrouting']))
151
		mwexec("/sbin/sysctl net.inet.ip.fastforwarding=1");
152

    
153
	/* clear out old routes, if necessary */
154
	if (file_exists("{$g['vardb_path']}/routes.db")) {
155
		$fd = fopen("{$g['vardb_path']}/routes.db", "r");
156
		if (!$fd) {
157
			printf("Error: cannot open routes DB file in system_routing_configure().\n");
158
			return 1;
159
		}
160
		while (!feof($fd)) {
161
			$oldrt = fgets($fd);
162
			if ($oldrt)
163
				mwexec("/sbin/route delete " . escapeshellarg($oldrt));
164
		}
165
		fclose($fd);
166
		unlink("{$g['vardb_path']}/routes.db");
167
	}
168

    
169
	if (is_array($config['staticroutes']['route'])) {
170

    
171
		$fd = fopen("{$g['vardb_path']}/routes.db", "w");
172
		if (!$fd) {
173
			printf("Error: cannot open routes DB file in system_routing_configure().\n");
174
			return 1;
175
		}
176

    
177
		foreach ($config['staticroutes']['route'] as $rtent) {
178
			mwexec("/sbin/route add " . escapeshellarg($rtent['network']) .
179
				" " . escapeshellarg($rtent['gateway']));
180

    
181
			/* record route so it can be easily removed later (if necessary) */
182
			fwrite($fd, $rtent['network'] . "\n");
183
		}
184

    
185
		fclose($fd);
186
	}
187

    
188
	return 0;
189
}
190

    
191
function system_routing_enable() {
192
	global $config, $g;
193
	if(isset($config['system']['developerspew'])) {
194
		$mt = microtime();
195
		echo "system_routing_enable() being called $mt\n";
196
	}
197

    
198
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
199
}
200

    
201
function system_syslogd_start() {
202
	global $config, $g;
203
	if(isset($config['system']['developerspew'])) {
204
		$mt = microtime();
205
		echo "system_syslogd_start() being called $mt\n";
206
	}
207

    
208
	$syslogcfg = $config['syslog'];
209

    
210
	if ($g['booting'])
211
		echo "Starting syslog... ";
212
	else
213
		killbypid("{$g['varrun_path']}/syslog.pid");
214

    
215
	if (isset($syslogcfg)) {
216
		if($config['installedpackages']['package']) {
217
                        foreach($config['installedpackages']['package'] as $package) {
218
                                if($package['logging']) {	
219
					$pkgfacilities[] = $package['logging']['facilityname'];
220
					$facilitylist = implode(',', $pkgfacilities);
221
					mwexec("clog -i -s 10000 {$g['varlog_path']}/{$package['logging']['logfilename']}");
222
                                	$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t%{$g['varlog_path']}/{$package['logging']['logfilename']}\n!-{$facilitylist}\n";
223
				}
224
                        }
225
                }
226
		/* write syslog.conf */
227
		$fd = fopen("{$g['varetc_path']}/syslog.conf", "w");
228
		if (!$fd) {
229
			printf("Error: cannot open syslog.conf in system_syslogd_start().\n");
230
			return 1;
231
		}
232
		if (!isset($syslogcfg['disablelocallogging'])) {
233
		$syslogconf .= <<<EOD
234
!racoon
235
*.*						%{$g['varlog_path']}/ipsec.log
236
!-racoon,{$facilitylist}
237
local0.*					%{$g['varlog_path']}/filter.log
238
local3.*					%{$g['varlog_path']}/vpn.log
239
local4.*					%{$g['varlog_path']}/portalauth.log
240
local7.*					%{$g['varlog_path']}/dhcpd.log
241
*.notice;kern.debug;lpr.info;mail.crit;		%{$g['varlog_path']}/system.log
242
news.err;local0.none;local3.none;local4.none;	%{$g['varlog_path']}/system.log
243
local7.none					%{$g['varlog_path']}/system.log
244
security.*					%{$g['varlog_path']}/system.log
245
auth.info;authpriv.info;daemon.info		%{$g['varlog_path']}/system.log
246
local1.*					%{$g['varlog_path']}/slbd.log
247
*.emerg						*
248

    
249
EOD;
250
		}
251

    
252
		if (isset($syslogcfg['filter'])) {
253
			$syslogconf .= <<<EOD
254
local0.*					@{$syslogcfg['remoteserver']}
255

    
256
EOD;
257
		}
258

    
259
		if (isset($syslogcfg['vpn'])) {
260
			$syslogconf .= <<<EOD
261
local3.*					@{$syslogcfg['remoteserver']}
262

    
263
EOD;
264
		}
265

    
266

    
267
		if (isset($syslogcfg['portalauth'])) {
268
			$syslogconf .= <<<EOD
269
local4.*					@{$syslogcfg['remoteserver']}
270

    
271
EOD;
272
		}
273

    
274

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

    
279
EOD;
280
		}
281

    
282
		if (isset($syslogcfg['system'])) {
283
			$syslogconf .= <<<EOD
284
*.notice;kern.debug;lpr.info;mail.crit;		@{$syslogcfg['remoteserver']}
285
news.err;local0.none;local3.none;local7.none	@{$syslogcfg['remoteserver']}
286
security.*					@{$syslogcfg['remoteserver']}
287
auth.info;authpriv.info;daemon.info		@{$syslogcfg['remoteserver']}
288
*.emerg						@{$syslogcfg['remoteserver']}
289
EOD;
290
		}
291
		fwrite($fd, $syslogconf);
292
		fclose($fd);
293

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

    
296
	} else {
297
		$retval = mwexec("/usr/sbin/syslogd -ss");
298
	}
299

    
300
	if ($g['booting'])
301
		echo "done.\n";
302

    
303
	return $retval;
304
}
305

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

    
313
	if ($g['booting'])
314
		echo "Initializing PCMCIA... ";
315

    
316
	/* kill any running pccardd */
317
	killbypid("{$g['varrun_path']}/pccardd.pid");
318

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

    
322
	if ($g['booting']) {
323
		if ($res == 0)
324
			echo "done.\n";
325
		else
326
			echo "failed!\n";
327
	}
328

    
329
	return $res;
330
}
331

    
332

    
333
function system_webgui_start() {
334
	global $config, $g;
335

    
336
	if ($g['booting'])
337
		echo "Starting webConfigurator... ";
338

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

    
342
	/* generate password file */
343
	system_password_configure();
344

    
345
	chdir($g['www_path']);
346

    
347
	/* non-standard port? */
348
	if ($config['system']['webgui']['port'])
349
		$portarg = "{$config['system']['webgui']['port']}";
350
	else
351
		$portarg = "";
352

    
353
	if ($config['system']['webgui']['protocol'] == "https") {
354

    
355
		if ($config['system']['webgui']['certificate'] && $config['system']['webgui']['private-key']) {
356
			$cert = base64_decode($config['system']['webgui']['certificate']);
357
			$key = base64_decode($config['system']['webgui']['private-key']);
358
		} else {
359
			/* default certificate/key */
360
			$cert = <<<EOD
361
-----BEGIN CERTIFICATE-----
362
MIIC4zCCAkygAwIBAgIBADANBgkqhkiG9w0BAQQFADBbMQswCQYDVQQGEwJOQTEL
363
MAkGA1UECBMCTkExCzAJBgNVBAcTAk5BMQswCQYDVQQKEwJOQTELMAkGA1UECxMC
364
TkExCzAJBgNVBAMTAk5BMQswCQYDVQQGEwJVUzAeFw0wNTAzMDYwMDE1NDJaFw0x
365
NTAzMDQwMDE1NDJaMFsxCzAJBgNVBAYTAk5BMQswCQYDVQQIEwJOQTELMAkGA1UE
366
BxMCTkExCzAJBgNVBAoTAk5BMQswCQYDVQQLEwJOQTELMAkGA1UEAxMCTkExCzAJ
367
BgNVBAYTAlVTMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDF7luuy70OvHrl
368
xnW9ID6srsfxEFCF4d9LmlZ6XdW1rEUHQ6KTgz4iSD+pxEOxxlY+bCH6HTkAy5Sa
369
zt3eT7javvF+ILZgarwoY2x+NbDctd0VBJVkH0fEvBf1xqU7wpkOiWkw1RmfEvZI
370
6XnGi6VSjSmkm0UoQMKg9R7niRtE4QIDAQABo4G2MIGzMB0GA1UdDgQWBBTgvk9F
371
alPK6/OcZrkaE8BhBrRo2DCBgwYDVR0jBHwweoAU4L5PRWpTyuvznGa5GhPAYQa0
372
aNihX6RdMFsxCzAJBgNVBAYTAk5BMQswCQYDVQQIEwJOQTELMAkGA1UEBxMCTkEx
373
CzAJBgNVBAoTAk5BMQswCQYDVQQLEwJOQTELMAkGA1UEAxMCTkExCzAJBgNVBAYT
374
AlVTggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEEBQADgYEAv9+GXdYIWs2R
375
8B0zI4jAbHcaRsfohuzpNHD5re7ZK8H4fYbHIfmPY2UM3yOU7J2rLP8KGfKztay1
376
Z3RNW7SKJI/CagbdQOuYdMrlEyA4ZImM6NNzUbH6rNKtmDIDo1kHL3cXjzXEjBE+
377
ZZYTREFcdhtzUH5lYzJz1uVFeCSwozk=
378
-----END CERTIFICATE-----
379
EOD;
380

    
381
			$key = <<<EOD
382
-----BEGIN RSA PRIVATE KEY-----
383
MIICXAIBAAKBgQDF7luuy70OvHrlxnW9ID6srsfxEFCF4d9LmlZ6XdW1rEUHQ6KT
384
gz4iSD+pxEOxxlY+bCH6HTkAy5Sazt3eT7javvF+ILZgarwoY2x+NbDctd0VBJVk
385
H0fEvBf1xqU7wpkOiWkw1RmfEvZI6XnGi6VSjSmkm0UoQMKg9R7niRtE4QIDAQAB
386
AoGAF9dMJ9PWo+3EB+VNzUgTBI3Q+5JxgI7ibKLcg8TFtypW7jcRYB9Q3qRBNtuz
387
I7i2LrKrrQrUEOp0rej5BIwpwcjtEE2NsZwgYwDyywptoqt3WO86nPXYz2KhkQmP
388
YCDmPrff4vXCv6zgefb/AIgrOkgD3ViEoePhCAg+0l3fEIECQQD7C68Nb6KAWUND
389
Q9B0RxYrlgXikQ8yVHhlyM433APe/NCJ9kl5dLXpyjuvrWB+ml6TlLrcroLGejbd
390
tYXvIiyJAkEAydZVHqB4MpMtuY7VJoHNgl06YBoeTI+BJptPaOUNl4SlUKIYJMhX
391
oOXIGk9uDjfSNS7HvunZBjgz092GShWvmQJAQ8NhmwTZHj/58fwqFljh2R4DtKZn
392
LbSzUvYjA9z1holDWRoLtycTu2mFNuRbuZC9mqR40/ye/CgdCzdmUagt0QJBAKq1
393
00ySINd10Cive+yTwMPQIj2CGbpbbbq/hYyMntBWapQmZRFHOYZmkrZeFBGGeQ5u
394
QJdipiIyivNY2+nxKZECQCvumJPfZYxCeCAEC+G2xezrP6bC6FhzUOw6410UARTM
395
fuFjHpSfOiG62lfRdZgCPAr1L/1pJF+8RqjGlFfAuFA=
396
-----END RSA PRIVATE KEY-----
397
EOD;
398
		}
399
	} else {
400
		$cert = "";
401
		$key = "";
402
	}
403

    
404
	/* generate lighttpd configuration */
405
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
406
		$key, $cert, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/");
407

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

    
411
	if ($g['booting']) {
412
		if ($res == 0)
413
			echo "done.\n";
414
		else
415
			echo "failed!\n";
416
	}
417

    
418
	return $res;
419
}
420

    
421
function system_webgui_start_old() {
422
	global $config, $g;
423
	if(isset($config['system']['developerspew'])) {
424
		$mt = microtime();
425
		echo "system_webgui_start() being called $mt\n";
426
	}
427

    
428
        if ($g['booting'])
429
                echo "Starting webConfigurator... ";
430

    
431
        /* kill any running mini_httpd */
432
        killbypid("{$g['varrun_path']}/mini_httpd.pid");
433

    
434
        /* generate password file */
435
        system_password_configure();
436

    
437
        chdir($g['www_path']);
438

    
439
        /* non-standard port? */
440
        if ($config['system']['webgui']['port'])
441
                $portarg = "-p {$config['system']['webgui']['port']}";
442
        else
443
                $portarg = "";
444

    
445
        if ($config['system']['webgui']['protocol'] == "https") {
446

    
447
                if ($config['system']['webgui']['certificate'] && $config['system']['webgui']['private-key']) {
448
                        $cert = base64_decode($config['system']['webgui']['certificate']);
449
                        $key = base64_decode($config['system']['webgui']['private-key']);
450
                } else {
451
                        /* default certificate/key */
452
                        $cert = <<<EOD
453
-----BEGIN CERTIFICATE-----
454
MIIBlDCB/gIBADANBgkqhkiG9w0BAQQFADATMREwDwYDVQQKEwhtMG4wd2FsbDAe
455
Fw0wNTA1MTAxMjI0NDRaFw0wNzA1MTAxMjI0NDRaMBMxETAPBgNVBAoTCG0wbjB3
456
YWxsMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDAShszhFz+o8lsMWTGgTxs
457
TMPR+v4+qL5jXDyY97MLTGFK7aqQOtpIQc+TcTc4jklgOVlHoR7oBXrsi8YrbCd+
458
83LPQmQoSPC0VqhfU3uYf3NzxiK8r97aPCsmWgwT2pQ6TcESTm6sF7nLprOf/zFP
459
C4jE2fvjkbzyVolPywBuewIDAQABMA0GCSqGSIb3DQEBBAUAA4GBAFR962c4R5tV
460
cTn0OQcszYoW6WC+ini9tQQh5ku5jYDAiC+00atawJEVLnL3lwAcpSKTIWlTkD20
461
tl3lz5br1qFgYky+Rd0kwS2nk9jRbkxSXxd6KJVnNRCKre28aw3ENzZfCSurPQsX
462
UPp5er+NtwMT1g7s/JDmKTC4w1rGr5/c
463
-----END CERTIFICATE-----
464

    
465
EOD;
466

    
467
                        $key = <<<EOD
468
-----BEGIN RSA PRIVATE KEY-----
469
MIICXQIBAAKBgQDAShszhFz+o8lsMWTGgTxsTMPR+v4+qL5jXDyY97MLTGFK7aqQ
470
OtpIQc+TcTc4jklgOVlHoR7oBXrsi8YrbCd+83LPQmQoSPC0VqhfU3uYf3NzxiK8
471
r97aPCsmWgwT2pQ6TcESTm6sF7nLprOf/zFPC4jE2fvjkbzyVolPywBuewIDAQAB
472
AoGAbJJrQW9fQrggJuLMz/hwsYW2m31oyOBmf5u463YQtjRuSuxe/gj87weZuNqY
473
H2rXq2k2K+ehl8hgW+egASyUL3L7kCkEAsVREujKTEyhSqqIRDPWTxo9S/YA9Gvn
474
2ZnJvkrcKjqCO9aHX3rvJOK/ErYI6akctgI3KmgkYw5XNmECQQDuZU97RTWH9rmP
475
aQr57ysNXxgFsyhetOOqeYkPtIVwpOiNbfwE1zi5RGdtO4Ku3fG1lV4J2UoWJ9yD
476
awdoyYIHAkEAzn0xJ90IjPsHk+8SODEj5JGdHSZPNu1tgtrbjEi9sfGWg4K7XTxr
477
QW90pWb1bKKU1uh5FzW6OhnFfuQXt1kC7QJAPSthqY+onKqCEnoxhtAHi/bKgyvl
478
P+fKQwPMV2tKkgy+XwvJjrRqqZ8TqsOKVLQ+QQmCh6RpjiXMPyxHSmvqIQJBAKLR
479
HF1ucDuaBROkwx0DwmWMW/KMLpIFDQDNSaiIAuu4rxHrl4mhBoGGPNffI04RtILw
480
s+qVNs5xW8T+XaT4ztECQQDFHPnZeoPWE5z+AX/UUQIUWaDExz3XRzmIxRbOrlFi
481
CsF1s0TdJLi/wzNQRAL37A8vqCeVFR/ng3Xpg96Yg+8Z
482
-----END RSA PRIVATE KEY-----
483

    
484
EOD;
485
                }
486

    
487
                $fd = fopen("{$g['varetc_path']}/cert.pem", "w");
488
                if (!$fd) {
489
                        printf("Error: cannot open cert.pem in system_webgui_start().\n");
490
                        return 1;
491
                }
492
                chmod("{$g['varetc_path']}/cert.pem", 0600);
493
                fwrite($fd, $cert);
494
                fwrite($fd, "\n");
495
                fwrite($fd, $key);
496
                fclose($fd);
497

    
498
                $res = mwexec("/usr/local/sbin/mini_httpd -S -E {$g['varetc_path']}/cert.pem" .
499
                        " -c \"**.php|**.cgi\" -u root -maxproc 16 $portarg" .
500
                        " -i {$g['varrun_path']}/mini_httpd.pid");
501
        } else {
502
                $res = mwexec("/usr/local/sbin/mini_httpd -c \"**.php|**.cgi\" -u root" .
503
                        " -maxproc 16 $portarg -i {$g['varrun_path']}/mini_httpd.pid");
504
        }
505

    
506
        if ($g['booting']) {
507
                if ($res == 0)
508
                        echo "done\n";
509
                else
510
                        echo "failed\n";
511
        }
512

    
513
        return $res;
514
}
515

    
516
function system_generate_lighty_config($filename, $cert, $key, $pid_file,
517
	$port = 80, $document_root = "/usr/local/www/",
518
	$cert_location = "cert.pem", $max_procs = 2,
519
	$max_requests = "1", $fast_cgi_enable = true) {
520

    
521
	global $config, $g;
522

    
523
	if(isset($config['system']['developerspew'])) {
524
		$mt = microtime();
525
		echo "system_generate_lighty_config() being called $mt\n";
526
	}
527

    
528
	if($port <> "")
529
		$lighty_port = $port;
530
	else
531
		$lighty_port = "80";
532

    
533
	$memory = get_memory();
534
	$avail = $memory[0];
535

    
536
	if($avail > 0 and $avail < 72) {
537
		$fast_cgi_enable = false;
538
	}
539
		
540
	if($fast_cgi_enable == true) {
541
		$module = "\"mod_fastcgi\", \"mod_cgi\"";
542
		$cgi_config = "";
543
		$fastcgi_config = <<<EOD
544
#### fastcgi module
545
## read fastcgi.txt for more info
546
fastcgi.server             = ( ".php" =>
547
                               ( "localhost" =>
548
                                 (
549
                                   "socket" => "/tmp/php-fastcgi.socket",
550
				   "min-procs" => 1,
551
				   "max-procs" => {$max_procs},
552
				   "max-load-per-proc" => 1,
553
				   "idle-timeout" => 1,
554
				   "bin-environment" => ( 
555
				      "PHP_FCGI_CHILDREN" => "{$max_procs}",
556
				      "PHP_FCGI_MAX_REQUESTS" => "{$max_requests}"
557
				   ),				   
558
                                   "bin-path" => "/usr/local/bin/php"
559
                                 )
560
                               )
561
                            )		
562

    
563
#### CGI module
564
cgi.assign                 = ( ".cgi" => "" )
565

    
566
EOD;
567
	} else {
568
		$fastcgi_config = "";
569
		$module = "\"mod_cgi\"";
570
		$cgi_config = <<<EOD
571
#### CGI module
572
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
573
                               ".cgi" => "" )
574
		
575
EOD;
576
	}
577
	
578
	$lighty_config .= <<<EOD
579
#
580
# lighttpd configuration file
581
#
582
# use a it as base for lighttpd 1.0.0 and above
583
#
584
############ Options you really have to take care of ####################
585

    
586
## modules to load
587
server.modules              =   (
588
				  "mod_access",
589
                                  {$module}
590
				)
591

    
592
## Unused modules
593
#                               "mod_setenv",
594
#                               "mod_compress"
595
#				"mod_redirect",
596
#                               "mod_rewrite",
597
#                               "mod_ssi",
598
#                               "mod_usertrack",
599
#                               "mod_expire",
600
#                               "mod_secdownload",
601
#                               "mod_rrdtool",
602
#                               "mod_auth",
603
#                               "mod_status",
604
#                               "mod_alias",
605
#                               "mod_proxy",
606
#                               "mod_simple_vhost",
607
#                               "mod_evhost",
608
#                               "mod_userdir",
609
#                               "mod_cgi",
610
#                                "mod_accesslog"
611

    
612
## a static document-root, for virtual-hosting take look at the
613
## server.virtual-* options
614
server.document-root        = "{$document_root}"
615

    
616
## where to send error-messages to
617
#server.errorlog             = "/var/log/lighttpd.error.log"
618

    
619
# files to check for if .../ is requested
620
server.indexfiles           = ( "index.php", "index.html",
621
                                "index.htm", "default.htm" )
622

    
623
# mimetype mapping
624
mimetype.assign             = (
625
  ".pdf"          =>      "application/pdf",
626
  ".sig"          =>      "application/pgp-signature",
627
  ".spl"          =>      "application/futuresplash",
628
  ".class"        =>      "application/octet-stream",
629
  ".ps"           =>      "application/postscript",
630
  ".torrent"      =>      "application/x-bittorrent",
631
  ".dvi"          =>      "application/x-dvi",
632
  ".gz"           =>      "application/x-gzip",
633
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
634
  ".swf"          =>      "application/x-shockwave-flash",
635
  ".tar.gz"       =>      "application/x-tgz",
636
  ".tgz"          =>      "application/x-tgz",
637
  ".tar"          =>      "application/x-tar",
638
  ".zip"          =>      "application/zip",
639
  ".mp3"          =>      "audio/mpeg",
640
  ".m3u"          =>      "audio/x-mpegurl",
641
  ".wma"          =>      "audio/x-ms-wma",
642
  ".wax"          =>      "audio/x-ms-wax",
643
  ".ogg"          =>      "audio/x-wav",
644
  ".wav"          =>      "audio/x-wav",
645
  ".gif"          =>      "image/gif",
646
  ".jpg"          =>      "image/jpeg",
647
  ".jpeg"         =>      "image/jpeg",
648
  ".png"          =>      "image/png",
649
  ".xbm"          =>      "image/x-xbitmap",
650
  ".xpm"          =>      "image/x-xpixmap",
651
  ".xwd"          =>      "image/x-xwindowdump",
652
  ".css"          =>      "text/css",
653
  ".html"         =>      "text/html",
654
  ".htm"          =>      "text/html",
655
  ".js"           =>      "text/javascript",
656
  ".asc"          =>      "text/plain",
657
  ".c"            =>      "text/plain",
658
  ".conf"         =>      "text/plain",
659
  ".text"         =>      "text/plain",
660
  ".txt"          =>      "text/plain",
661
  ".dtd"          =>      "text/xml",
662
  ".xml"          =>      "text/xml",
663
  ".mpeg"         =>      "video/mpeg",
664
  ".mpg"          =>      "video/mpeg",
665
  ".mov"          =>      "video/quicktime",
666
  ".qt"           =>      "video/quicktime",
667
  ".avi"          =>      "video/x-msvideo",
668
  ".asf"          =>      "video/x-ms-asf",
669
  ".asx"          =>      "video/x-ms-asf",
670
  ".wmv"          =>      "video/x-ms-wmv",
671
  ".bz2"          =>      "application/x-bzip",
672
  ".tbz"          =>      "application/x-bzip-compressed-tar",
673
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
674
 )
675

    
676
# Use the "Content-Type" extended attribute to obtain mime type if possible
677
#mimetypes.use-xattr        = "enable"
678

    
679
#### accesslog module
680
#accesslog.filename          = "/dev/null"
681

    
682
## deny access the file-extensions
683
#
684
# ~    is for backupfiles from vi, emacs, joe, ...
685
# .inc is often used for code includes which should in general not be part
686
#      of the document-root
687
url.access-deny             = ( "~", ".inc" )
688

    
689

    
690
######### Options that are good to be but not neccesary to be changed #######
691

    
692
## bind to port (default: 80)
693
server.port                = {$lighty_port}
694

    
695
## error-handler for status 404
696
#server.error-handler-404   = "/error-handler.html"
697
#server.error-handler-404   = "/error-handler.php"
698

    
699
## to help the rc.scripts
700
server.pid-file            = "/var/run/{$pid_file}"
701

    
702
## virtual directory listings
703
server.dir-listing         = "disable"
704

    
705
## enable debugging
706
debug.log-request-header   = "disable"
707
debug.log-response-header  = "disable"
708
debug.log-request-handling = "disable"
709
debug.log-file-not-found   = "disable"
710

    
711
#### compress module
712
#compress.cache-dir         = "/tmp/lighttpd/cache/compress/"
713
#compress.filetype          = ("text/plain", "text/html")
714

    
715
{$fastcgi_config}
716

    
717
{$cgi_config}
718

    
719
EOD;
720

    
721
	if($cert <> "" and $key <> "") {
722
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
723
		if (!$fd) {
724
			printf("Error: cannot open cert.pem in system_webgui_start().\n");
725
			return 1;
726
		}
727
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
728
		fwrite($fd, $cert);
729
		fwrite($fd, "\n");
730
		fwrite($fd, $key);
731
		fclose($fd);
732
		$lighty_config .= "\n";
733
		$lighty_config .= "## ssl configuration\n";
734
		$lighty_config .= "ssl.engine = \"enable\"\n";
735
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";	
736
	}
737

    
738
	$fd = fopen("{$filename}", "w");
739
	if (!$fd) {
740
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
741
		return 1;
742
	}
743
	fwrite($fd, $lighty_config);
744
	fclose($fd);
745

    
746
	return 0;
747

    
748
}
749

    
750
function system_password_configure() {
751
	global $config, $g;
752
	if(isset($config['system']['developerspew'])) {
753
		$mt = microtime();
754
		echo "system_password_configure() being called $mt\n";
755
	}
756

    
757
	/* sync passwords */
758
	sync_webgui_passwords();
759

    
760
	/* !NOTE! conf_mount_ro is done by sync_webgui_passwords() */
761

    
762
	return 0;
763
}
764

    
765
function system_timezone_configure() {
766
	global $config, $g;
767
	if(isset($config['system']['developerspew'])) {
768
		$mt = microtime();
769
		echo "system_timezone_configure() being called $mt\n";
770
	}	
771

    
772
	$syscfg = $config['system'];
773

    
774
	if ($g['booting'])
775
		echo "Setting timezone... ";
776

    
777
	/* extract appropriate timezone file */
778
	$timezone = $syscfg['timezone'];
779
	if (!$timezone)
780
		$timezone = "Etc/UTC";
781

    
782
	conf_mount_rw();
783

    
784
	exec("/usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
785
		escapeshellarg($timezone) . " > /etc/localtime");
786

    
787
	conf_mount_ro();
788

    
789
	if ($g['booting'])
790
		echo "done.\n";
791
}
792

    
793
function system_ntp_configure() {
794
	global $config, $g;
795
	if(isset($config['system']['developerspew'])) {
796
		$mt = microtime();
797
		echo "system_ntp_configure() being called $mt\n";
798
	}
799

    
800
	$syscfg = $config['system'];
801

    
802
	if ($g['booting'])
803
		echo "Starting NTP client... ";
804
	else {
805
		killbypid("{$g['varrun_path']}/runmsntp.pid");
806
		killbypid("{$g['varrun_path']}/msntp.pid");
807
	}
808

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

    
812
	if ($updateinterval > 0) {
813
		if ($updateinterval < 6)
814
			$updateinterval = 6;
815

    
816
		$timeservers = "";
817
		foreach (explode(' ', $syscfg['timeservers']) as $ts)
818
			$timeservers .= " " . $ts;
819

    
820
		mwexec_bg("/usr/local/bin/runmsntp.sh " .
821
			escapeshellarg("{$g['varrun_path']}/runmsntp.pid") . " " .
822
			escapeshellarg("{$g['varrun_path']}/msntp.pid") . " " .
823
			escapeshellarg($updateinterval) . " " .
824
			escapeshellarg($timeservers));
825
	}
826

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

    
831
function system_halt() {
832
	global $g;
833

    
834
	system_reboot_cleanup();
835

    
836
	mwexec("nohup /etc/rc.halt > /dev/null 2>&1 &");
837
}
838

    
839
function system_reboot() {
840
	global $g;
841

    
842
	system_reboot_cleanup();
843

    
844
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
845
}
846

    
847
function system_reboot_sync() {
848
	global $g;
849

    
850
	system_reboot_cleanup();
851

    
852
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
853
}
854

    
855
function system_reboot_cleanup() {
856
	mwexec("/usr/local/bin/beep.sh stop");
857
	captiveportal_radius_stop_all();
858
}
859

    
860
function system_do_shell_commands($early = 0) {
861
	global $config, $g;
862
	if(isset($config['system']['developerspew'])) {
863
		$mt = microtime();
864
		echo "system_do_shell_commands() being called $mt\n";
865
	}
866

    
867
	if ($early)
868
		$cmdn = "earlyshellcmd";
869
	else
870
		$cmdn = "shellcmd";
871

    
872
	if (is_array($config['system'][$cmdn])) {
873
		
874
		/* *cmd is an array, loop through */
875
		foreach ($config['system'][$cmdn] as $cmd) {
876
			exec($cmd);
877
		}
878

    
879
	} elseif($config['system'][$cmdn] <> "") {
880
		
881
		/* execute single item */
882
		exec($config['system'][$cmdn]);
883

    
884
	}
885
}
886

    
887
function system_console_configure() {
888
	global $config, $g;
889
	if(isset($config['system']['developerspew'])) {
890
		$mt = microtime();
891
		echo "system_console_configure() being called $mt\n";
892
	}	
893

    
894
	if (isset($config['system']['disableconsolemenu'])) {
895
		touch("{$g['varetc_path']}/disableconsole");
896
	} else {
897
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
898
	}
899
}
900

    
901
function system_dmesg_save() {
902
	global $g;
903
	if(isset($config['system']['developerspew'])) {
904
		$mt = microtime();
905
		echo "system_dmesg_save() being called $mt\n";
906
	}
907

    
908
	exec("/sbin/dmesg", $dmesg);
909

    
910
	/* find last copyright line (output from previous boots may be present) */
911
	$lastcpline = 0;
912

    
913
	for ($i = 0; $i < count($dmesg); $i++) {
914
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
915
			$lastcpline = $i;
916
	}
917

    
918
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
919
	if (!$fd) {
920
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
921
		return 1;
922
	}
923

    
924
	for ($i = $lastcpline; $i < count($dmesg); $i++)
925
		fwrite($fd, $dmesg[$i] . "\n");
926

    
927
	fclose($fd);
928

    
929
	return 0;
930
}
931

    
932
function system_set_harddisk_standby() {
933
	global $g, $config;
934
	if(isset($config['system']['developerspew'])) {
935
		$mt = microtime();
936
		echo "system_set_harddisk_standby() being called $mt\n";
937
	}
938

    
939
	if (isset($config['system']['harddiskstandby'])) {
940
		if ($g['booting']) {
941
			echo 'Setting hard disk standby... ';
942
		}
943

    
944
		$standby = $config['system']['harddiskstandby'];
945
		// Check for a numeric value
946
		if (is_numeric($standby)) {
947
			// Sync the disk(s)
948
			mwexec('/bin/sync');
949
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
950
				// Reinitialize ATA-drives
951
				mwexec('/usr/local/sbin/atareinit');
952
				if ($g['booting']) {
953
					echo "done.\n";
954
				}
955
			} else if ($g['booting']) {
956
				echo "failed!\n";
957
			}
958
		} else if ($g['booting']) {
959
			echo "failed!\n";
960
		}
961
	}
962
}
963

    
964
function system_setup_sysctl() {
965
	global $config;
966
	if(isset($config['system']['developerspew'])) {
967
		$mt = microtime();
968
		echo "system_setup_sysctl() being called $mt\n";
969
	}
970

    
971
	$sysctl = return_filename_as_array("/etc/sysctl.conf");
972
	foreach($sysctl as $sysc) {
973
		if($sysc <> "")
974
			mwexec("sysctl {$sysc}");
975
	}
976
	if (isset($config['system']['sharednet'])) {
977
		system_disable_arp_wrong_if();
978
	}
979
}
980

    
981
function system_disable_arp_wrong_if() {
982
	global $config;
983
	if(isset($config['system']['developerspew'])) {
984
		$mt = microtime();
985
		echo "system_disable_arp_wrong_if() being called $mt\n";
986
	}	
987
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
988
}
989

    
990
function system_enable_arp_wrong_if() {
991
	global $config;
992
	if(isset($config['system']['developerspew'])) {
993
		$mt = microtime();
994
		echo "system_enable_arp_wrong_if() being called $mt\n";
995
	}
996
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
997
}
998

    
999

    
1000
?>
(18-18/25)