Project

General

Profile

Download (30 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
			if(isset($rtent['interfacegateway'])) {
195
				mwexec("/sbin/route add " . escapeshellarg($rtent['network']) .
196
					" -iface " . escapeshellarg(convert_friendly_interface_to_real_interface_name($rtent['interface'])));				
197
			} else {
198
				mwexec("/sbin/route add " . escapeshellarg($rtent['network']) .
199
					" " . escapeshellarg($rtent['gateway']));
200
			}
201
			/* record route so it can be easily removed later (if necessary) */
202
			fwrite($fd, $rtent['network'] . "\n");
203
		}
204

    
205
		fclose($fd);
206
	}
207

    
208
	return 0;
209
}
210

    
211
function system_routing_enable() {
212
	global $config, $g;
213
	if(isset($config['system']['developerspew'])) {
214
		$mt = microtime();
215
		echo "system_routing_enable() being called $mt\n";
216
	}
217

    
218
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
219
}
220

    
221
function system_syslogd_start() {
222
	global $config, $g;
223
	if(isset($config['system']['developerspew'])) {
224
		$mt = microtime();
225
		echo "system_syslogd_start() being called $mt\n";
226
	}
227

    
228
	$syslogcfg = $config['syslog'];
229

    
230
	if ($g['booting'])
231
		echo "Starting syslog... ";
232
	else
233
		killbypid("{$g['varrun_path']}/syslog.pid");
234

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

    
269
EOD;
270
		}
271

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

    
276
EOD;
277
		}
278

    
279
		if (isset($syslogcfg['vpn'])) {
280
			$syslogconf .= <<<EOD
281
local3.*					@{$syslogcfg['remoteserver']}
282

    
283
EOD;
284
		}
285

    
286

    
287
		if (isset($syslogcfg['portalauth'])) {
288
			$syslogconf .= <<<EOD
289
local4.*					@{$syslogcfg['remoteserver']}
290

    
291
EOD;
292
		}
293

    
294

    
295
		if (isset($syslogcfg['dhcp'])) {
296
			$syslogconf .= <<<EOD
297
local7.*					@{$syslogcfg['remoteserver']}
298

    
299
EOD;
300
		}
301

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

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

    
316
	} else {
317
		$retval = mwexec("/usr/sbin/syslogd -ss");
318
	}
319

    
320
	if ($g['booting'])
321
		echo "done.\n";
322

    
323
	return $retval;
324
}
325

    
326
function system_pccard_start() {
327
	global $config, $g;
328
	if(isset($config['system']['developerspew'])) {
329
		$mt = microtime();
330
		echo "system_pccard_start() being called $mt\n";
331
	}
332

    
333
	if ($g['booting'])
334
		echo "Initializing PCMCIA... ";
335

    
336
	/* kill any running pccardd */
337
	killbypid("{$g['varrun_path']}/pccardd.pid");
338

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

    
342
	if ($g['booting']) {
343
		if ($res == 0)
344
			echo "done.\n";
345
		else
346
			echo "failed!\n";
347
	}
348

    
349
	return $res;
350
}
351

    
352

    
353
function system_webgui_start() {
354
	global $config, $g;
355

    
356
	if ($g['booting'])
357
		echo "Starting webConfigurator... ";
358

    
359
	/* kill any running lighttpd */
360
	killbypid("{$g['varrun_path']}/lighty-webConfigurator.pid");
361

    
362
	sleep(1);
363

    
364
	/* generate password file */
365
	system_password_configure();
366

    
367
	chdir($g['www_path']);
368

    
369
	/* non-standard port? */
370
	if ($config['system']['webgui']['port'])
371
		$portarg = "{$config['system']['webgui']['port']}";
372
	else
373
		$portarg = "";
374

    
375
	if ($config['system']['webgui']['protocol'] == "https") {
376

    
377
	if(!$config['system']['webgui']['port'])
378
		$portarg = "443";
379

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

    
406
EOD;
407

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

    
425
EOD;
426
		}
427
	} else {
428
		$cert = "";
429
		$key = "";
430
	}
431

    
432
	/* generate lighttpd configuration */
433
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
434
		$cert, $key, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/");
435

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

    
439
	if ($g['booting']) {
440
		if ($res == 0)
441
			echo "done.\n";
442
		else
443
			echo "failed!\n";
444
	}
445

    
446
	return $res;
447
}
448

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

    
456
        if ($g['booting'])
457
                echo "Starting webConfigurator... ";
458

    
459
        /* kill any running mini_httpd */
460
        killbypid("{$g['varrun_path']}/mini_httpd.pid");
461

    
462
        /* generate password file */
463
        system_password_configure();
464

    
465
        chdir($g['www_path']);
466

    
467
        /* non-standard port? */
468
        if ($config['system']['webgui']['port'])
469
                $portarg = "-p {$config['system']['webgui']['port']}";
470
        else
471
                $portarg = "";
472

    
473
        if ($config['system']['webgui']['protocol'] == "https") {
474

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

    
493
EOD;
494

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

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

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

    
537
        if ($g['booting']) {
538
                if ($res == 0)
539
                        echo "done\n";
540
                else
541
                        echo "failed\n";
542
        }
543

    
544
        return $res;
545
}
546

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

    
559
	global $config, $g;
560

    
561
	if(isset($config['system']['developerspew'])) {
562
		$mt = microtime();
563
		echo "system_generate_lighty_config() being called $mt\n";
564
	}
565

    
566
	if($captive_portal == true)  {
567
		$captiveportal = ",\"mod_rewrite\"";
568
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*)\" => \"/index.php?redirurl=$1\" )";
569
	}
570

    
571
	if($port <> "")
572
		$lighty_port = $port;
573
	else
574
		$lighty_port = "80";
575

    
576
	$memory = get_memory();
577
	$avail = $memory[0];
578

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

    
607
#### CGI module
608
cgi.assign                 = ( ".cgi" => "" )
609

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

    
630
# FreeBSD!
631
server.event-handler        = "freebsd-kqueue"
632

    
633
## modules to load
634
server.modules              =   (
635
				  "mod_access",
636
                                  {$module}{$captiveportal}
637
				)
638

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

    
659
## a static document-root, for virtual-hosting take look at the
660
## server.virtual-* options
661
server.document-root        = "{$document_root}"
662
{$captive_portal_rewrite}
663

    
664
## where to send error-messages to
665
#server.errorlog             = "/var/log/lighttpd.error.log"
666

    
667
# files to check for if .../ is requested
668
server.indexfiles           = ( "index.php", "index.html",
669
                                "index.htm", "default.htm" )
670

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

    
724
# Use the "Content-Type" extended attribute to obtain mime type if possible
725
#mimetypes.use-xattr        = "enable"
726

    
727
#### accesslog module
728
#accesslog.filename          = "/dev/null"
729

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

    
737

    
738
######### Options that are good to be but not neccesary to be changed #######
739

    
740
## bind to port (default: 80)
741
server.port                = {$lighty_port}
742

    
743
## error-handler for status 404
744
#server.error-handler-404   = "/error-handler.html"
745
#server.error-handler-404   = "/error-handler.php"
746

    
747
## to help the rc.scripts
748
server.pid-file            = "/var/run/{$pid_file}"
749

    
750
## virtual directory listings
751
server.dir-listing         = "disable"
752

    
753
## enable debugging
754
debug.log-request-header   = "disable"
755
debug.log-response-header  = "disable"
756
debug.log-request-handling = "disable"
757
debug.log-file-not-found   = "disable"
758

    
759
#### compress module
760
#compress.cache-dir         = "/tmp/lighttpd/cache/compress/"
761
#compress.filetype          = ("text/plain", "text/html")
762

    
763
{$fastcgi_config}
764

    
765
{$cgi_config}
766

    
767
EOD;
768

    
769
	$cert = str_replace("\r", "", $cert);
770
	$key = str_replace("\r", "", $key);	
771

    
772
	$cert = str_replace("\n\n", "\n", $cert);
773
	$key = str_replace("\n\n", "\n", $key);	
774

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

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

    
800
	return 0;
801

    
802
}
803

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

    
811
	/* sync passwords */
812
	sync_webgui_passwords();
813

    
814
	/* !NOTE! conf_mount_ro is done by sync_webgui_passwords() */
815

    
816
	return 0;
817
}
818

    
819
function system_timezone_configure() {
820
	global $config, $g;
821
	if(isset($config['system']['developerspew'])) {
822
		$mt = microtime();
823
		echo "system_timezone_configure() being called $mt\n";
824
	}	
825

    
826
	$syscfg = $config['system'];
827

    
828
	if ($g['booting'])
829
		echo "Setting timezone... ";
830

    
831
	/* extract appropriate timezone file */
832
	$timezone = $syscfg['timezone'];
833
	if (!$timezone)
834
		$timezone = "Etc/UTC";
835

    
836
	conf_mount_rw();
837

    
838
	exec("/usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
839
		escapeshellarg($timezone) . " > /etc/localtime");
840

    
841
	conf_mount_ro();
842

    
843
	if ($g['booting'])
844
		echo "done.\n";
845
}
846

    
847
function system_ntp_configure() {
848
	global $config, $g;
849
	if(isset($config['system']['developerspew'])) {
850
		$mt = microtime();
851
		echo "system_ntp_configure() being called $mt\n";
852
	}
853

    
854
	$syscfg = $config['system'];
855

    
856
	if ($g['booting'])
857
		echo "Starting NTP client... ";
858
	else {
859
		killbypid("{$g['varrun_path']}/runmsntp.pid");
860
		killbypid("{$g['varrun_path']}/msntp.pid");
861
	}
862

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

    
866
	if ($updateinterval > 0) {
867
		if ($updateinterval < 6)
868
			$updateinterval = 6;
869

    
870
		$timeservers = "";
871
		foreach (explode(' ', $syscfg['timeservers']) as $ts)
872
			$timeservers .= " " . $ts;
873

    
874
		mwexec_bg("/usr/local/bin/runmsntp.sh " .
875
			escapeshellarg("{$g['varrun_path']}/runmsntp.pid") . " " .
876
			escapeshellarg("{$g['varrun_path']}/msntp.pid") . " " .
877
			escapeshellarg($updateinterval) . " " .
878
			escapeshellarg($timeservers));
879
	}
880

    
881
	if ($g['booting'])
882
		echo "done.\n";
883
}
884

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

    
888
	system_reboot_cleanup();
889

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

    
893
function system_reboot() {
894
	global $g;
895

    
896
	system_reboot_cleanup();
897

    
898
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
899
}
900

    
901
function system_reboot_sync() {
902
	global $g;
903

    
904
	system_reboot_cleanup();
905

    
906
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
907
}
908

    
909
function system_reboot_cleanup() {
910
	mwexec("/usr/local/bin/beep.sh stop");
911
	captiveportal_radius_stop_all();
912
}
913

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

    
921
	if ($early)
922
		$cmdn = "earlyshellcmd";
923
	else
924
		$cmdn = "shellcmd";
925

    
926
	if (is_array($config['system'][$cmdn])) {
927
		
928
		/* *cmd is an array, loop through */
929
		foreach ($config['system'][$cmdn] as $cmd) {
930
			exec($cmd);
931
		}
932

    
933
	} elseif($config['system'][$cmdn] <> "") {
934
		
935
		/* execute single item */
936
		exec($config['system'][$cmdn]);
937

    
938
	}
939
}
940

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

    
948
	if (isset($config['system']['disableconsolemenu'])) {
949
		touch("{$g['varetc_path']}/disableconsole");
950
	} else {
951
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
952
	}
953
}
954

    
955
function system_dmesg_save() {
956
	global $g;
957
	if(isset($config['system']['developerspew'])) {
958
		$mt = microtime();
959
		echo "system_dmesg_save() being called $mt\n";
960
	}
961

    
962
	$dmesg = "";
963
	exec("/sbin/dmesg", $dmesg);
964

    
965
	/* find last copyright line (output from previous boots may be present) */
966
	$lastcpline = 0;
967

    
968
	for ($i = 0; $i < count($dmesg); $i++) {
969
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
970
			$lastcpline = $i;
971
	}
972

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

    
979
	for ($i = $lastcpline; $i < count($dmesg); $i++)
980
		fwrite($fd, $dmesg[$i] . "\n");
981

    
982
	fclose($fd);
983

    
984
	return 0;
985
}
986

    
987
function system_set_harddisk_standby() {
988
	global $g, $config;
989
	if(isset($config['system']['developerspew'])) {
990
		$mt = microtime();
991
		echo "system_set_harddisk_standby() being called $mt\n";
992
	}
993

    
994
	if (isset($config['system']['harddiskstandby'])) {
995
		if ($g['booting']) {
996
			echo 'Setting hard disk standby... ';
997
		}
998

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

    
1019
function system_setup_sysctl() {
1020
	global $config;
1021
	if(isset($config['system']['developerspew'])) {
1022
		$mt = microtime();
1023
		echo "system_setup_sysctl() being called $mt\n";
1024
	}
1025

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

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

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

    
1054

    
1055
?>
(20-20/27)