Project

General

Profile

Download (29.4 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
	/* generate password file */
356
	system_password_configure();
357

    
358
	chdir($g['www_path']);
359

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

    
366
	if ($config['system']['webgui']['protocol'] == "https") {
367

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

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

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

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

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

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

    
434
	return $res;
435
}
436

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

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

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

    
450
        /* generate password file */
451
        system_password_configure();
452

    
453
        chdir($g['www_path']);
454

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

    
461
        if ($config['system']['webgui']['protocol'] == "https") {
462

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

    
481
EOD;
482

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

    
500
EOD;
501
                }
502

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

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

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

    
529
        return $res;
530
}
531

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

    
544
	global $config, $g;
545

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

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

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

    
561
	$memory = get_memory();
562
	$avail = $memory[0];
563

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

    
591
#### CGI module
592
cgi.assign                 = ( ".cgi" => "" )
593

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

    
614
## modules to load
615
server.modules              =   (
616
				  "mod_access",
617
                                  {$module}{$captiveportal}
618
				)
619

    
620
## Unused modules
621
#                               "mod_setenv",
622
#                               "mod_compress"
623
#				"mod_redirect",
624
#                               "mod_rewrite",
625
#                               "mod_ssi",
626
#                               "mod_usertrack",
627
#                               "mod_expire",
628
#                               "mod_secdownload",
629
#                               "mod_rrdtool",
630
#                               "mod_auth",
631
#                               "mod_status",
632
#                               "mod_alias",
633
#                               "mod_proxy",
634
#                               "mod_simple_vhost",
635
#                               "mod_evhost",
636
#                               "mod_userdir",
637
#                               "mod_cgi",
638
#                                "mod_accesslog"
639

    
640
## a static document-root, for virtual-hosting take look at the
641
## server.virtual-* options
642
server.document-root        = "{$document_root}"
643
{$captive_portal_rewrite}
644

    
645
## where to send error-messages to
646
#server.errorlog             = "/var/log/lighttpd.error.log"
647

    
648
# files to check for if .../ is requested
649
server.indexfiles           = ( "index.php", "index.html",
650
                                "index.htm", "default.htm" )
651

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

    
705
# Use the "Content-Type" extended attribute to obtain mime type if possible
706
#mimetypes.use-xattr        = "enable"
707

    
708
#### accesslog module
709
#accesslog.filename          = "/dev/null"
710

    
711
## deny access the file-extensions
712
#
713
# ~    is for backupfiles from vi, emacs, joe, ...
714
# .inc is often used for code includes which should in general not be part
715
#      of the document-root
716
url.access-deny             = ( "~", ".inc" )
717

    
718

    
719
######### Options that are good to be but not neccesary to be changed #######
720

    
721
## bind to port (default: 80)
722
server.port                = {$lighty_port}
723

    
724
## error-handler for status 404
725
#server.error-handler-404   = "/error-handler.html"
726
#server.error-handler-404   = "/error-handler.php"
727

    
728
## to help the rc.scripts
729
server.pid-file            = "/var/run/{$pid_file}"
730

    
731
## virtual directory listings
732
server.dir-listing         = "disable"
733

    
734
## enable debugging
735
debug.log-request-header   = "disable"
736
debug.log-response-header  = "disable"
737
debug.log-request-handling = "disable"
738
debug.log-file-not-found   = "disable"
739

    
740
#### compress module
741
#compress.cache-dir         = "/tmp/lighttpd/cache/compress/"
742
#compress.filetype          = ("text/plain", "text/html")
743

    
744
{$fastcgi_config}
745

    
746
{$cgi_config}
747

    
748
EOD;
749

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

    
767
	$fd = fopen("{$filename}", "w");
768
	if (!$fd) {
769
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
770
		return 1;
771
	}
772
	fwrite($fd, $lighty_config);
773
	fclose($fd);
774

    
775
	return 0;
776

    
777
}
778

    
779
function system_password_configure() {
780
	global $config, $g;
781
	if(isset($config['system']['developerspew'])) {
782
		$mt = microtime();
783
		echo "system_password_configure() being called $mt\n";
784
	}
785

    
786
	/* sync passwords */
787
	sync_webgui_passwords();
788

    
789
	/* !NOTE! conf_mount_ro is done by sync_webgui_passwords() */
790

    
791
	return 0;
792
}
793

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

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

    
803
	if ($g['booting'])
804
		echo "Setting timezone... ";
805

    
806
	/* extract appropriate timezone file */
807
	$timezone = $syscfg['timezone'];
808
	if (!$timezone)
809
		$timezone = "Etc/UTC";
810

    
811
	conf_mount_rw();
812

    
813
	exec("/usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
814
		escapeshellarg($timezone) . " > /etc/localtime");
815

    
816
	conf_mount_ro();
817

    
818
	if ($g['booting'])
819
		echo "done.\n";
820
}
821

    
822
function system_ntp_configure() {
823
	global $config, $g;
824
	if(isset($config['system']['developerspew'])) {
825
		$mt = microtime();
826
		echo "system_ntp_configure() being called $mt\n";
827
	}
828

    
829
	$syscfg = $config['system'];
830

    
831
	if ($g['booting'])
832
		echo "Starting NTP client... ";
833
	else {
834
		killbypid("{$g['varrun_path']}/runmsntp.pid");
835
		killbypid("{$g['varrun_path']}/msntp.pid");
836
	}
837

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

    
841
	if ($updateinterval > 0) {
842
		if ($updateinterval < 6)
843
			$updateinterval = 6;
844

    
845
		$timeservers = "";
846
		foreach (explode(' ', $syscfg['timeservers']) as $ts)
847
			$timeservers .= " " . $ts;
848

    
849
		mwexec_bg("/usr/local/bin/runmsntp.sh " .
850
			escapeshellarg("{$g['varrun_path']}/runmsntp.pid") . " " .
851
			escapeshellarg("{$g['varrun_path']}/msntp.pid") . " " .
852
			escapeshellarg($updateinterval) . " " .
853
			escapeshellarg($timeservers));
854
	}
855

    
856
	if ($g['booting'])
857
		echo "done.\n";
858
}
859

    
860
function system_halt() {
861
	global $g;
862

    
863
	system_reboot_cleanup();
864

    
865
	mwexec("nohup /etc/rc.halt > /dev/null 2>&1 &");
866
}
867

    
868
function system_reboot() {
869
	global $g;
870

    
871
	system_reboot_cleanup();
872

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

    
876
function system_reboot_sync() {
877
	global $g;
878

    
879
	system_reboot_cleanup();
880

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

    
884
function system_reboot_cleanup() {
885
	mwexec("/usr/local/bin/beep.sh stop");
886
	captiveportal_radius_stop_all();
887
}
888

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

    
896
	if ($early)
897
		$cmdn = "earlyshellcmd";
898
	else
899
		$cmdn = "shellcmd";
900

    
901
	if (is_array($config['system'][$cmdn])) {
902
		
903
		/* *cmd is an array, loop through */
904
		foreach ($config['system'][$cmdn] as $cmd) {
905
			exec($cmd);
906
		}
907

    
908
	} elseif($config['system'][$cmdn] <> "") {
909
		
910
		/* execute single item */
911
		exec($config['system'][$cmdn]);
912

    
913
	}
914
}
915

    
916
function system_console_configure() {
917
	global $config, $g;
918
	if(isset($config['system']['developerspew'])) {
919
		$mt = microtime();
920
		echo "system_console_configure() being called $mt\n";
921
	}	
922

    
923
	if (isset($config['system']['disableconsolemenu'])) {
924
		touch("{$g['varetc_path']}/disableconsole");
925
	} else {
926
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
927
	}
928
}
929

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

    
937
	exec("/sbin/dmesg", $dmesg);
938

    
939
	/* find last copyright line (output from previous boots may be present) */
940
	$lastcpline = 0;
941

    
942
	for ($i = 0; $i < count($dmesg); $i++) {
943
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
944
			$lastcpline = $i;
945
	}
946

    
947
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
948
	if (!$fd) {
949
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
950
		return 1;
951
	}
952

    
953
	for ($i = $lastcpline; $i < count($dmesg); $i++)
954
		fwrite($fd, $dmesg[$i] . "\n");
955

    
956
	fclose($fd);
957

    
958
	return 0;
959
}
960

    
961
function system_set_harddisk_standby() {
962
	global $g, $config;
963
	if(isset($config['system']['developerspew'])) {
964
		$mt = microtime();
965
		echo "system_set_harddisk_standby() being called $mt\n";
966
	}
967

    
968
	if (isset($config['system']['harddiskstandby'])) {
969
		if ($g['booting']) {
970
			echo 'Setting hard disk standby... ';
971
		}
972

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

    
993
function system_setup_sysctl() {
994
	global $config;
995
	if(isset($config['system']['developerspew'])) {
996
		$mt = microtime();
997
		echo "system_setup_sysctl() being called $mt\n";
998
	}
999

    
1000
	$sysctl = return_filename_as_array("/etc/sysctl.conf");
1001
	foreach($sysctl as $sysc) {
1002
		if($sysc <> "")
1003
			mwexec("sysctl {$sysc}");
1004
	}
1005
	if (isset($config['system']['sharednet'])) {
1006
		system_disable_arp_wrong_if();
1007
	}
1008
}
1009

    
1010
function system_disable_arp_wrong_if() {
1011
	global $config;
1012
	if(isset($config['system']['developerspew'])) {
1013
		$mt = microtime();
1014
		echo "system_disable_arp_wrong_if() being called $mt\n";
1015
	}	
1016
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1017
}
1018

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

    
1028

    
1029
?>
(19-19/26)