Project

General

Profile

Download (29.8 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/* $Id$ */
3
/*
4
	system.inc
5
	part of m0n0wall (http://m0n0.ch/wall)
6

    
7
	Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
8
	All rights reserved.
9

    
10
	Redistribution and use in source and binary forms, with or without
11
	modification, are permitted provided that the following conditions are met:
12

    
13
	1. Redistributions of source code must retain the above copyright notice,
14
	   this list of conditions and the following disclaimer.
15

    
16
	2. Redistributions in binary form must reproduce the above copyright
17
	   notice, this list of conditions and the following disclaimer in the
18
	   documentation and/or other materials provided with the distribution.
19

    
20
	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
21
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
22
	AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
23
	AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
24
	OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29
	POSSIBILITY OF SUCH DAMAGE.
30
*/
31

    
32
/* include all configuration functions */
33
require_once("functions.inc");
34

    
35
function system_resolvconf_generate($dynupdate = false) {
36
	global $config, $g;
37
	if(isset($config['system']['developerspew'])) {
38
		$mt = microtime();
39
		echo "system_resolvconf_generate() being called $mt\n";
40
	}	
41

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

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

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

    
52
        $havedns = false;
53

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

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

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

    
82
        return 0;
83
}
84

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

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

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

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

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

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

    
130
EOD;
131

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

    
141
	return 0;
142
}
143

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

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

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

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

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

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

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

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

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

    
201
		fclose($fd);
202
	}
203

    
204
	return 0;
205
}
206

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

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

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

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

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

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

    
265
EOD;
266
		}
267

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

    
272
EOD;
273
		}
274

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

    
279
EOD;
280
		}
281

    
282

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

    
287
EOD;
288
		}
289

    
290

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

    
295
EOD;
296
		}
297

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

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

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

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

    
319
	return $retval;
320
}
321

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

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

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

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

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

    
345
	return $res;
346
}
347

    
348

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

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

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

    
358
	sleep(1);
359

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

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

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

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

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

    
376
		if ($config['system']['webgui']['certificate'] && $config['system']['webgui']['private-key']) {
377
			$cert = base64_decode($config['system']['webgui']['certificate']);
378
			$key = base64_decode($config['system']['webgui']['private-key']);
379
		} else {
380
			/* default certificate/key */
381
			$cert = <<<EOD
382
-----BEGIN CERTIFICATE-----
383
MIIDEzCCAnygAwIBAgIJAJM91W+s6qptMA0GCSqGSIb3DQEBBAUAMGUxCzAJBgNV
384
BAYTAlVTMQswCQYDVQQIEwJLWTETMBEGA1UEBxMKTG91aXN2aWxsZTEQMA4GA1UE
385
ChMHcGZTZW5zZTEQMA4GA1UECxMHcGZTZW5zZTEQMA4GA1UEAxMHcGZTZW5zZTAe
386
Fw0wNjAzMTAyMzQ1MTlaFw0xNjAzMDcyMzQ1MTlaMGUxCzAJBgNVBAYTAlVTMQsw
387
CQYDVQQIEwJLWTETMBEGA1UEBxMKTG91aXN2aWxsZTEQMA4GA1UEChMHcGZTZW5z
388
ZTEQMA4GA1UECxMHcGZTZW5zZTEQMA4GA1UEAxMHcGZTZW5zZTCBnzANBgkqhkiG
389
9w0BAQEFAAOBjQAwgYkCgYEA3lPNTFH6qge/ygaqe/BS4oH59O6KvAesWcRzSu5N
390
21lyVE5tBbL0zqOSXmlLyReMSbtAMZqt1P8EPYFoOcaEQHIWm2VQF80Z18+8Gh4O
391
UQGjHq88OeaLqyk3OLpSKzSpXuCFrSN7q9Kez8zp5dQEu7sIW30da3pAbdqYOimA
392
1VsCAwEAAaOByjCBxzAdBgNVHQ4EFgQUAnx+ggC4SzJ0CK+rhPhJ2ZpyunEwgZcG
393
A1UdIwSBjzCBjIAUAnx+ggC4SzJ0CK+rhPhJ2ZpyunGhaaRnMGUxCzAJBgNVBAYT
394
AlVTMQswCQYDVQQIEwJLWTETMBEGA1UEBxMKTG91aXN2aWxsZTEQMA4GA1UEChMH
395
cGZTZW5zZTEQMA4GA1UECxMHcGZTZW5zZTEQMA4GA1UEAxMHcGZTZW5zZYIJAJM9
396
1W+s6qptMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEEBQADgYEAAviQpdoeabL8
397
1HSZiD7Yjx82pdLpyQOdXvAu3jEAYz53ckx0zSMrzsQ5r7Vae6AE7Xd7Pj+1Yihs
398
AJZzOQujnmsuim7qu6YSxzP34xonKwd1C9tZUlyNRNnEmtXOEDupn05bih1ugtLG
399
kqfPIgDbDLXuPtEAA6QDUypaunI6+1E=
400
-----END CERTIFICATE-----
401

    
402
EOD;
403

    
404
			$key = <<<EOD
405
-----BEGIN RSA PRIVATE KEY-----
406
MIICXgIBAAKBgQDeU81MUfqqB7/KBqp78FLigfn07oq8B6xZxHNK7k3bWXJUTm0F
407
svTOo5JeaUvJF4xJu0Axmq3U/wQ9gWg5xoRAchabZVAXzRnXz7waHg5RAaMerzw5
408
5ourKTc4ulIrNKle4IWtI3ur0p7PzOnl1AS7uwhbfR1rekBt2pg6KYDVWwIDAQAB
409
AoGAP7E0VFP8Aq/7os3sE1uS8y8XQ7L+7cUo/AKKoQHKLjfeyAY7t3FALt6vdPqn
410
anGjkA/j4RIWELoKJfCnwj17703NDCPwB7klcmZvmTx5Om1ZrRyZdQ6RJs0pOOO1
411
r2wOnZNaNWStXE9Afpw3dj20Gh0V/Ioo5HXn3sHfxZm8dnkCQQDwv8OaUdp2Hl8t
412
FDfXB1CMvUG1hEAvbQvZK1ODkE7na2/ChKjVPddEI3DvfzG+nLrNuTrAyVWgRLte
413
r8qX5PQHAkEA7GlKx0S18LdiKo6wy2QeGu6HYkPncaHNFOWX8cTpvGGtQoWYSh0J
414
tjCt1/mz4/XkvZWuZyTNx2FdkVlNF5nHDQJBAIRWVTZqEjVlwpmsCHnp6mxCyHD4
415
DrRDNAUfnNuwIr9xPlDlzUzSnpc1CCqOd5C45LKbRGGfCrN7tKd66FmQoFcCQQCy
416
Kvw3R1pTCvHJnvYwoshphaC0dvaDVeyINiwYAk4hMf/wpVxLZqz+CJvLrB1dzOBR
417
3O+uPjdzbrakpweJpNQ1AkEA3ZtlgEj9eWsLAJP8aKlwB8VqD+EtG9OJSUMnCDiQ
418
WFFNj/t3Ze3IVuAyL/yMpiv3JNEnZhIxCta42eDFpIZAKw==
419
-----END RSA PRIVATE KEY-----
420

    
421
EOD;
422
		}
423
	} else {
424
		$cert = "";
425
		$key = "";
426
	}
427

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

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

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

    
442
	return $res;
443
}
444

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

    
452
        if ($g['booting'])
453
                echo "Starting webConfigurator... ";
454

    
455
        /* kill any running mini_httpd */
456
        killbypid("{$g['varrun_path']}/mini_httpd.pid");
457

    
458
        /* generate password file */
459
        system_password_configure();
460

    
461
        chdir($g['www_path']);
462

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

    
469
        if ($config['system']['webgui']['protocol'] == "https") {
470

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

    
489
EOD;
490

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

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

    
525
                $res = mwexec("/usr/local/sbin/mini_httpd -S -E {$g['varetc_path']}/cert.pem" .
526
                        " -c \"**.php|**.cgi\" -u root -maxproc 16 $portarg" .
527
                        " -i {$g['varrun_path']}/mini_httpd.pid");
528
        } else {
529
                $res = mwexec("/usr/local/sbin/mini_httpd -c \"**.php|**.cgi\" -u root" .
530
                        " -maxproc 16 $portarg -i {$g['varrun_path']}/mini_httpd.pid");
531
        }
532

    
533
        if ($g['booting']) {
534
                if ($res == 0)
535
                        echo "done\n";
536
                else
537
                        echo "failed\n";
538
        }
539

    
540
        return $res;
541
}
542

    
543
function system_generate_lighty_config($filename,
544
	$cert,
545
	$key,
546
	$pid_file,
547
	$port = 80,
548
	$document_root = "/usr/local/www/",
549
	$cert_location = "cert.pem",
550
	$max_procs = 2,
551
	$max_requests = "1",
552
	$fast_cgi_enable = true,
553
	$captive_portal = false) {
554

    
555
	global $config, $g;
556

    
557
	if(isset($config['system']['developerspew'])) {
558
		$mt = microtime();
559
		echo "system_generate_lighty_config() being called $mt\n";
560
	}
561

    
562
	if($captive_portal == true)  {
563
		$captiveportal = ",\"mod_rewrite\"";
564
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*)\" => \"/index.php?redirurl=$1\" )";
565
	}
566

    
567
	if($port <> "")
568
		$lighty_port = $port;
569
	else
570
		$lighty_port = "80";
571

    
572
	$memory = get_memory();
573
	$avail = $memory[0];
574

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

    
603
#### CGI module
604
cgi.assign                 = ( ".cgi" => "" )
605

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

    
626
# FreeBSD!
627
server.event-handler        = "freebsd-kqueue"
628

    
629
## modules to load
630
server.modules              =   (
631
				  "mod_access",
632
                                  {$module}{$captiveportal}
633
				)
634

    
635
## Unused modules
636
#                               "mod_setenv",
637
#                               "mod_compress"
638
#				"mod_redirect",
639
#                               "mod_rewrite",
640
#                               "mod_ssi",
641
#                               "mod_usertrack",
642
#                               "mod_expire",
643
#                               "mod_secdownload",
644
#                               "mod_rrdtool",
645
#                               "mod_auth",
646
#                               "mod_status",
647
#                               "mod_alias",
648
#                               "mod_proxy",
649
#                               "mod_simple_vhost",
650
#                               "mod_evhost",
651
#                               "mod_userdir",
652
#                               "mod_cgi",
653
#                                "mod_accesslog"
654

    
655
## a static document-root, for virtual-hosting take look at the
656
## server.virtual-* options
657
server.document-root        = "{$document_root}"
658
{$captive_portal_rewrite}
659

    
660
## where to send error-messages to
661
#server.errorlog             = "/var/log/lighttpd.error.log"
662

    
663
# files to check for if .../ is requested
664
server.indexfiles           = ( "index.php", "index.html",
665
                                "index.htm", "default.htm" )
666

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

    
720
# Use the "Content-Type" extended attribute to obtain mime type if possible
721
#mimetypes.use-xattr        = "enable"
722

    
723
#### accesslog module
724
#accesslog.filename          = "/dev/null"
725

    
726
## deny access the file-extensions
727
#
728
# ~    is for backupfiles from vi, emacs, joe, ...
729
# .inc is often used for code includes which should in general not be part
730
#      of the document-root
731
url.access-deny             = ( "~", ".inc" )
732

    
733

    
734
######### Options that are good to be but not neccesary to be changed #######
735

    
736
## bind to port (default: 80)
737
server.port                = {$lighty_port}
738

    
739
## error-handler for status 404
740
#server.error-handler-404   = "/error-handler.html"
741
#server.error-handler-404   = "/error-handler.php"
742

    
743
## to help the rc.scripts
744
server.pid-file            = "/var/run/{$pid_file}"
745

    
746
## virtual directory listings
747
server.dir-listing         = "disable"
748

    
749
## enable debugging
750
debug.log-request-header   = "disable"
751
debug.log-response-header  = "disable"
752
debug.log-request-handling = "disable"
753
debug.log-file-not-found   = "disable"
754

    
755
#### compress module
756
#compress.cache-dir         = "/tmp/lighttpd/cache/compress/"
757
#compress.filetype          = ("text/plain", "text/html")
758

    
759
{$fastcgi_config}
760

    
761
{$cgi_config}
762

    
763
EOD;
764

    
765
	$cert = str_replace("\r", "", $cert);
766
	$key = str_replace("\r", "", $key);	
767

    
768
	$cert = str_replace("\n\n", "\n", $cert);
769
	$key = str_replace("\n\n", "\n", $key);	
770

    
771
	if($cert <> "" and $key <> "") {
772
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
773
		if (!$fd) {
774
			printf("Error: cannot open cert.pem in system_webgui_start().\n");
775
			return 1;
776
		}
777
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
778
		fwrite($fd, $cert);
779
		fwrite($fd, "\n");
780
		fwrite($fd, $key);
781
		fclose($fd);
782
		$lighty_config .= "\n";
783
		$lighty_config .= "## ssl configuration\n";
784
		$lighty_config .= "ssl.engine = \"enable\"\n";
785
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";	
786
	}
787

    
788
	$fd = fopen("{$filename}", "w");
789
	if (!$fd) {
790
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
791
		return 1;
792
	}
793
	fwrite($fd, $lighty_config);
794
	fclose($fd);
795

    
796
	return 0;
797

    
798
}
799

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

    
807
	/* sync passwords */
808
	sync_webgui_passwords();
809

    
810
	/* !NOTE! conf_mount_ro is done by sync_webgui_passwords() */
811

    
812
	return 0;
813
}
814

    
815
function system_timezone_configure() {
816
	global $config, $g;
817
	if(isset($config['system']['developerspew'])) {
818
		$mt = microtime();
819
		echo "system_timezone_configure() being called $mt\n";
820
	}	
821

    
822
	$syscfg = $config['system'];
823

    
824
	if ($g['booting'])
825
		echo "Setting timezone... ";
826

    
827
	/* extract appropriate timezone file */
828
	$timezone = $syscfg['timezone'];
829
	if (!$timezone)
830
		$timezone = "Etc/UTC";
831

    
832
	conf_mount_rw();
833

    
834
	exec("/usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
835
		escapeshellarg($timezone) . " > /etc/localtime");
836

    
837
	conf_mount_ro();
838

    
839
	if ($g['booting'])
840
		echo "done.\n";
841
}
842

    
843
function system_ntp_configure() {
844
	global $config, $g;
845
	if(isset($config['system']['developerspew'])) {
846
		$mt = microtime();
847
		echo "system_ntp_configure() being called $mt\n";
848
	}
849

    
850
	$syscfg = $config['system'];
851

    
852
	if ($g['booting'])
853
		echo "Starting NTP client... ";
854
	else {
855
		killbypid("{$g['varrun_path']}/runmsntp.pid");
856
		killbypid("{$g['varrun_path']}/msntp.pid");
857
	}
858

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

    
862
	if ($updateinterval > 0) {
863
		if ($updateinterval < 6)
864
			$updateinterval = 6;
865

    
866
		$timeservers = "";
867
		foreach (explode(' ', $syscfg['timeservers']) as $ts)
868
			$timeservers .= " " . $ts;
869

    
870
		mwexec_bg("/usr/local/bin/runmsntp.sh " .
871
			escapeshellarg("{$g['varrun_path']}/runmsntp.pid") . " " .
872
			escapeshellarg("{$g['varrun_path']}/msntp.pid") . " " .
873
			escapeshellarg($updateinterval) . " " .
874
			escapeshellarg($timeservers));
875
	}
876

    
877
	if ($g['booting'])
878
		echo "done.\n";
879
}
880

    
881
function system_halt() {
882
	global $g;
883

    
884
	system_reboot_cleanup();
885

    
886
	mwexec("nohup /etc/rc.halt > /dev/null 2>&1 &");
887
}
888

    
889
function system_reboot() {
890
	global $g;
891

    
892
	system_reboot_cleanup();
893

    
894
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
895
}
896

    
897
function system_reboot_sync() {
898
	global $g;
899

    
900
	system_reboot_cleanup();
901

    
902
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
903
}
904

    
905
function system_reboot_cleanup() {
906
	mwexec("/usr/local/bin/beep.sh stop");
907
	captiveportal_radius_stop_all();
908
}
909

    
910
function system_do_shell_commands($early = 0) {
911
	global $config, $g;
912
	if(isset($config['system']['developerspew'])) {
913
		$mt = microtime();
914
		echo "system_do_shell_commands() being called $mt\n";
915
	}
916

    
917
	if ($early)
918
		$cmdn = "earlyshellcmd";
919
	else
920
		$cmdn = "shellcmd";
921

    
922
	if (is_array($config['system'][$cmdn])) {
923
		
924
		/* *cmd is an array, loop through */
925
		foreach ($config['system'][$cmdn] as $cmd) {
926
			exec($cmd);
927
		}
928

    
929
	} elseif($config['system'][$cmdn] <> "") {
930
		
931
		/* execute single item */
932
		exec($config['system'][$cmdn]);
933

    
934
	}
935
}
936

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

    
944
	if (isset($config['system']['disableconsolemenu'])) {
945
		touch("{$g['varetc_path']}/disableconsole");
946
	} else {
947
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
948
	}
949
}
950

    
951
function system_dmesg_save() {
952
	global $g;
953
	if(isset($config['system']['developerspew'])) {
954
		$mt = microtime();
955
		echo "system_dmesg_save() being called $mt\n";
956
	}
957

    
958
	$dmesg = "";
959
	exec("/sbin/dmesg", $dmesg);
960

    
961
	/* find last copyright line (output from previous boots may be present) */
962
	$lastcpline = 0;
963

    
964
	for ($i = 0; $i < count($dmesg); $i++) {
965
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
966
			$lastcpline = $i;
967
	}
968

    
969
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
970
	if (!$fd) {
971
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
972
		return 1;
973
	}
974

    
975
	for ($i = $lastcpline; $i < count($dmesg); $i++)
976
		fwrite($fd, $dmesg[$i] . "\n");
977

    
978
	fclose($fd);
979

    
980
	return 0;
981
}
982

    
983
function system_set_harddisk_standby() {
984
	global $g, $config;
985
	if(isset($config['system']['developerspew'])) {
986
		$mt = microtime();
987
		echo "system_set_harddisk_standby() being called $mt\n";
988
	}
989

    
990
	if (isset($config['system']['harddiskstandby'])) {
991
		if ($g['booting']) {
992
			echo 'Setting hard disk standby... ';
993
		}
994

    
995
		$standby = $config['system']['harddiskstandby'];
996
		// Check for a numeric value
997
		if (is_numeric($standby)) {
998
			// Sync the disk(s)
999
			mwexec('/bin/sync');
1000
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1001
				// Reinitialize ATA-drives
1002
				mwexec('/usr/local/sbin/atareinit');
1003
				if ($g['booting']) {
1004
					echo "done.\n";
1005
				}
1006
			} else if ($g['booting']) {
1007
				echo "failed!\n";
1008
			}
1009
		} else if ($g['booting']) {
1010
			echo "failed!\n";
1011
		}
1012
	}
1013
}
1014

    
1015
function system_setup_sysctl() {
1016
	global $config;
1017
	if(isset($config['system']['developerspew'])) {
1018
		$mt = microtime();
1019
		echo "system_setup_sysctl() being called $mt\n";
1020
	}
1021

    
1022
	$sysctl = return_filename_as_array("/etc/sysctl.conf");
1023
	foreach($sysctl as $sysc) {
1024
		if($sysc <> "")
1025
			mwexec("sysctl {$sysc}");
1026
	}
1027
	if (isset($config['system']['sharednet'])) {
1028
		system_disable_arp_wrong_if();
1029
	}
1030
}
1031

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

    
1041
function system_enable_arp_wrong_if() {
1042
	global $config;
1043
	if(isset($config['system']['developerspew'])) {
1044
		$mt = microtime();
1045
		echo "system_enable_arp_wrong_if() being called $mt\n";
1046
	}
1047
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1048
}
1049

    
1050

    
1051
?>
(20-20/27)