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 = get_nameservers();
57
		foreach($ns as $nameserver) {
58
			$resolvconf .= "nameserver $nameserver\n";
59
			$havedns = true;			
60
		}
61
        }
62
        if (!$havedns && is_array($syscfg['dnsserver'])) {
63
                foreach ($syscfg['dnsserver'] as $ns) {
64
                        if ($ns)
65
                                $resolvconf .= "nameserver $ns\n";
66
                        $havedns = true;
67
                }
68
        }
69

    
70
        fwrite($fd, $resolvconf);
71
        fclose($fd);
72

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

    
79
        return 0;
80
}
81

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

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

    
108
	$syscfg = $config['system'];
109
	$lancfg = $config['interfaces']['lan'];
110
	$dnsmasqcfg = $config['dnsmasq'];
111

    
112
	if (!is_array($dnsmasqcfg['hosts'])) {
113
		$dnsmasqcfg['hosts'] = array();
114
	}
115
	$hostscfg = $dnsmasqcfg['hosts'];
116

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

    
123
	$hosts = <<<EOD
124
127.0.0.1	localhost localhost.{$syscfg['domain']}
125
{$lancfg['ipaddr']}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}
126

    
127
EOD;
128

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

    
138
	return 0;
139
}
140

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

    
148
	$syscfg = $config['system'];
149

    
150
	/* set hostname */
151
	return mwexec("/bin/hostname " .
152
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
153
}
154

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

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

    
182
	if (is_array($config['staticroutes']['route'])) {
183

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

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

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

    
198
		fclose($fd);
199
	}
200

    
201
	return 0;
202
}
203

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

    
211
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
212
}
213

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

    
221
	$syslogcfg = $config['syslog'];
222

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

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

    
262
EOD;
263
		}
264

    
265
		if (isset($syslogcfg['filter'])) {
266
			$syslogconf .= <<<EOD
267
local0.*					@{$syslogcfg['remoteserver']}
268

    
269
EOD;
270
		}
271

    
272
		if (isset($syslogcfg['vpn'])) {
273
			$syslogconf .= <<<EOD
274
local3.*					@{$syslogcfg['remoteserver']}
275

    
276
EOD;
277
		}
278

    
279

    
280
		if (isset($syslogcfg['portalauth'])) {
281
			$syslogconf .= <<<EOD
282
local4.*					@{$syslogcfg['remoteserver']}
283

    
284
EOD;
285
		}
286

    
287

    
288
		if (isset($syslogcfg['dhcp'])) {
289
			$syslogconf .= <<<EOD
290
local7.*					@{$syslogcfg['remoteserver']}
291

    
292
EOD;
293
		}
294

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

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

    
309
	} else {
310
		$retval = mwexec("/usr/sbin/syslogd -ss");
311
	}
312

    
313
	if ($g['booting'])
314
		echo "done.\n";
315

    
316
	return $retval;
317
}
318

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

    
326
	if ($g['booting'])
327
		echo "Initializing PCMCIA... ";
328

    
329
	/* kill any running pccardd */
330
	killbypid("{$g['varrun_path']}/pccardd.pid");
331

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

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

    
342
	return $res;
343
}
344

    
345

    
346
function system_webgui_start() {
347
	global $config, $g;
348

    
349
	if ($g['booting'])
350
		echo "Starting webConfigurator... ";
351

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

    
355
	sleep(1);
356

    
357
	/* generate password file */
358
	system_password_configure();
359

    
360
	chdir($g['www_path']);
361

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

    
368
	if ($config['system']['webgui']['protocol'] == "https") {
369

    
370
	if(!$config['system']['webgui']['port'])
371
		$portarg = "443";
372

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

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

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

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

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

    
436
	return $res;
437
}
438

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

    
446
        if ($g['booting'])
447
                echo "Starting webConfigurator... ";
448

    
449
        /* kill any running mini_httpd */
450
        killbypid("{$g['varrun_path']}/mini_httpd.pid");
451

    
452
        /* generate password file */
453
        system_password_configure();
454

    
455
        chdir($g['www_path']);
456

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

    
463
        if ($config['system']['webgui']['protocol'] == "https") {
464

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

    
483
EOD;
484

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

    
502
EOD;
503
                }
504

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

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

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

    
531
        return $res;
532
}
533

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

    
546
	global $config, $g;
547

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

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

    
558
	if($port <> "")
559
		$lighty_port = $port;
560
	else
561
		$lighty_port = "80";
562

    
563
	$memory = get_memory();
564
	$avail = $memory[0];
565

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

    
594
#### CGI module
595
cgi.assign                 = ( ".cgi" => "" )
596

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

    
617
# FreeBSD!
618
server.event-handler        = "freebsd-kqueue"
619

    
620
## modules to load
621
server.modules              =   (
622
				  "mod_access",
623
                                  {$module}{$captiveportal}
624
				)
625

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

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

    
651
## where to send error-messages to
652
#server.errorlog             = "/var/log/lighttpd.error.log"
653

    
654
# files to check for if .../ is requested
655
server.indexfiles           = ( "index.php", "index.html",
656
                                "index.htm", "default.htm" )
657

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

    
711
# Use the "Content-Type" extended attribute to obtain mime type if possible
712
#mimetypes.use-xattr        = "enable"
713

    
714
#### accesslog module
715
#accesslog.filename          = "/dev/null"
716

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

    
724

    
725
######### Options that are good to be but not neccesary to be changed #######
726

    
727
## bind to port (default: 80)
728
server.port                = {$lighty_port}
729

    
730
## error-handler for status 404
731
#server.error-handler-404   = "/error-handler.html"
732
#server.error-handler-404   = "/error-handler.php"
733

    
734
## to help the rc.scripts
735
server.pid-file            = "/var/run/{$pid_file}"
736

    
737
## virtual directory listings
738
server.dir-listing         = "disable"
739

    
740
## enable debugging
741
debug.log-request-header   = "disable"
742
debug.log-response-header  = "disable"
743
debug.log-request-handling = "disable"
744
debug.log-file-not-found   = "disable"
745

    
746
#### compress module
747
#compress.cache-dir         = "/tmp/lighttpd/cache/compress/"
748
#compress.filetype          = ("text/plain", "text/html")
749

    
750
{$fastcgi_config}
751

    
752
{$cgi_config}
753

    
754
EOD;
755

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

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

    
781
	return 0;
782

    
783
}
784

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

    
792
	/* sync passwords */
793
	sync_webgui_passwords();
794

    
795
	/* !NOTE! conf_mount_ro is done by sync_webgui_passwords() */
796

    
797
	return 0;
798
}
799

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

    
807
	$syscfg = $config['system'];
808

    
809
	if ($g['booting'])
810
		echo "Setting timezone... ";
811

    
812
	/* extract appropriate timezone file */
813
	$timezone = $syscfg['timezone'];
814
	if (!$timezone)
815
		$timezone = "Etc/UTC";
816

    
817
	conf_mount_rw();
818

    
819
	exec("/usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
820
		escapeshellarg($timezone) . " > /etc/localtime");
821

    
822
	conf_mount_ro();
823

    
824
	if ($g['booting'])
825
		echo "done.\n";
826
}
827

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

    
835
	$syscfg = $config['system'];
836

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

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

    
847
	if ($updateinterval > 0) {
848
		if ($updateinterval < 6)
849
			$updateinterval = 6;
850

    
851
		$timeservers = "";
852
		foreach (explode(' ', $syscfg['timeservers']) as $ts)
853
			$timeservers .= " " . $ts;
854

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

    
862
	if ($g['booting'])
863
		echo "done.\n";
864
}
865

    
866
function system_halt() {
867
	global $g;
868

    
869
	system_reboot_cleanup();
870

    
871
	mwexec("nohup /etc/rc.halt > /dev/null 2>&1 &");
872
}
873

    
874
function system_reboot() {
875
	global $g;
876

    
877
	system_reboot_cleanup();
878

    
879
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
880
}
881

    
882
function system_reboot_sync() {
883
	global $g;
884

    
885
	system_reboot_cleanup();
886

    
887
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
888
}
889

    
890
function system_reboot_cleanup() {
891
	mwexec("/usr/local/bin/beep.sh stop");
892
	captiveportal_radius_stop_all();
893
}
894

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

    
902
	if ($early)
903
		$cmdn = "earlyshellcmd";
904
	else
905
		$cmdn = "shellcmd";
906

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

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

    
919
	}
920
}
921

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

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

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

    
943
	$dmesg = "";
944
	exec("/sbin/dmesg", $dmesg);
945

    
946
	/* find last copyright line (output from previous boots may be present) */
947
	$lastcpline = 0;
948

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

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

    
960
	for ($i = $lastcpline; $i < count($dmesg); $i++)
961
		fwrite($fd, $dmesg[$i] . "\n");
962

    
963
	fclose($fd);
964

    
965
	return 0;
966
}
967

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

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

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

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

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

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

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

    
1035

    
1036
?>
(20-20/27)