Project

General

Profile

Download (31.1 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
		log_error("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
		$syslogconf .= "!racoon\n";
253
		if (!isset($syslogcfg['disablelocallogging'])) {
254
			$syslogconf .= <<<EOD
255
*.*						%{$g['varlog_path']}/ipsec.log
256

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

    
263
EOD;
264
		}
265
		$syslogconf .= "!-racoon,{$facilitylist}\n!openvpn\n";
266
		if (!isset($syslogcfg['disablelocallogging'])) {
267
			$syslogconf .= <<<EOD
268
*.*						%{$g['varlog_path']}/openvpn.log
269

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

    
276
EOD;
277
		}
278
		$syslogconf .= "!-openvpn,{$facilitylist}\n";
279
		if (!isset($syslogcfg['disablelocallogging'])) {
280
		$syslogconf .= <<<EOD
281
local0.*					%{$g['varlog_path']}/filter.log
282
local3.*					%{$g['varlog_path']}/vpn.log
283
local4.*					%{$g['varlog_path']}/portalauth.log
284
local7.*					%{$g['varlog_path']}/dhcpd.log
285
*.notice;kern.debug;lpr.info;mail.crit;		%{$g['varlog_path']}/system.log
286
news.err;local0.none;local3.none;local4.none;	%{$g['varlog_path']}/system.log
287
local7.none					%{$g['varlog_path']}/system.log
288
security.*					%{$g['varlog_path']}/system.log
289
auth.info;authpriv.info;daemon.info		%{$g['varlog_path']}/system.log
290
local1.*					%{$g['varlog_path']}/slbd.log
291
*.emerg						*
292

    
293
EOD;
294
		}
295

    
296
		if (isset($syslogcfg['filter'])) {
297
			$syslogconf .= <<<EOD
298
local0.*					@{$syslogcfg['remoteserver']}
299

    
300
EOD;
301
		}
302

    
303
		if (isset($syslogcfg['vpn'])) {
304
			$syslogconf .= <<<EOD
305
local3.*					@{$syslogcfg['remoteserver']}
306

    
307
EOD;
308
		}
309

    
310

    
311
		if (isset($syslogcfg['portalauth'])) {
312
			$syslogconf .= <<<EOD
313
local4.*					@{$syslogcfg['remoteserver']}
314

    
315
EOD;
316
		}
317

    
318

    
319
		if (isset($syslogcfg['dhcp'])) {
320
			$syslogconf .= <<<EOD
321
local7.*					@{$syslogcfg['remoteserver']}
322

    
323
EOD;
324
		}
325

    
326
		if (isset($syslogcfg['system'])) {
327
			$syslogconf .= <<<EOD
328
*.notice;kern.debug;lpr.info;mail.crit;		@{$syslogcfg['remoteserver']}
329
news.err;local0.none;local3.none;local7.none	@{$syslogcfg['remoteserver']}
330
security.*					@{$syslogcfg['remoteserver']}
331
auth.info;authpriv.info;daemon.info		@{$syslogcfg['remoteserver']}
332
*.emerg						@{$syslogcfg['remoteserver']}
333
EOD;
334
		}
335
		fwrite($fd, $syslogconf);
336
		fclose($fd);
337

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

    
340
	} else {
341
		$retval = mwexec("/usr/sbin/syslogd -ss");
342
	}
343

    
344
	if ($g['booting'])
345
		echo "done.\n";
346

    
347
	return $retval;
348
}
349

    
350
function system_pccard_start() {
351
	global $config, $g;
352
	if(isset($config['system']['developerspew'])) {
353
		$mt = microtime();
354
		echo "system_pccard_start() being called $mt\n";
355
	}
356

    
357
	if ($g['booting'])
358
		echo "Initializing PCMCIA... ";
359

    
360
	/* kill any running pccardd */
361
	killbypid("{$g['varrun_path']}/pccardd.pid");
362

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

    
366
	if ($g['booting']) {
367
		if ($res == 0)
368
			echo "done.\n";
369
		else
370
			echo "failed!\n";
371
	}
372

    
373
	return $res;
374
}
375

    
376

    
377
function system_webgui_start() {
378
	global $config, $g;
379

    
380
	if ($g['booting'])
381
		echo "Starting webConfigurator... ";
382

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

    
386
	sleep(1);
387

    
388
	/* generate password file */
389
	system_password_configure();
390

    
391
	chdir($g['www_path']);
392

    
393
	/* non-standard port? */
394
	if ($config['system']['webgui']['port'])
395
		$portarg = "{$config['system']['webgui']['port']}";
396
	else
397
		$portarg = "";
398

    
399
	if ($config['system']['webgui']['protocol'] == "https") {
400

    
401
	if(!$config['system']['webgui']['port'])
402
		$portarg = "443";
403

    
404
		if ($config['system']['webgui']['certificate'] && $config['system']['webgui']['private-key']) {
405
			$cert = base64_decode($config['system']['webgui']['certificate']);
406
			$key = base64_decode($config['system']['webgui']['private-key']);
407
		} else {
408
			/* default certificate/key */
409
			$cert = <<<EOD
410
-----BEGIN CERTIFICATE-----
411
MIIDEzCCAnygAwIBAgIJAJM91W+s6qptMA0GCSqGSIb3DQEBBAUAMGUxCzAJBgNV
412
BAYTAlVTMQswCQYDVQQIEwJLWTETMBEGA1UEBxMKTG91aXN2aWxsZTEQMA4GA1UE
413
ChMHcGZTZW5zZTEQMA4GA1UECxMHcGZTZW5zZTEQMA4GA1UEAxMHcGZTZW5zZTAe
414
Fw0wNjAzMTAyMzQ1MTlaFw0xNjAzMDcyMzQ1MTlaMGUxCzAJBgNVBAYTAlVTMQsw
415
CQYDVQQIEwJLWTETMBEGA1UEBxMKTG91aXN2aWxsZTEQMA4GA1UEChMHcGZTZW5z
416
ZTEQMA4GA1UECxMHcGZTZW5zZTEQMA4GA1UEAxMHcGZTZW5zZTCBnzANBgkqhkiG
417
9w0BAQEFAAOBjQAwgYkCgYEA3lPNTFH6qge/ygaqe/BS4oH59O6KvAesWcRzSu5N
418
21lyVE5tBbL0zqOSXmlLyReMSbtAMZqt1P8EPYFoOcaEQHIWm2VQF80Z18+8Gh4O
419
UQGjHq88OeaLqyk3OLpSKzSpXuCFrSN7q9Kez8zp5dQEu7sIW30da3pAbdqYOimA
420
1VsCAwEAAaOByjCBxzAdBgNVHQ4EFgQUAnx+ggC4SzJ0CK+rhPhJ2ZpyunEwgZcG
421
A1UdIwSBjzCBjIAUAnx+ggC4SzJ0CK+rhPhJ2ZpyunGhaaRnMGUxCzAJBgNVBAYT
422
AlVTMQswCQYDVQQIEwJLWTETMBEGA1UEBxMKTG91aXN2aWxsZTEQMA4GA1UEChMH
423
cGZTZW5zZTEQMA4GA1UECxMHcGZTZW5zZTEQMA4GA1UEAxMHcGZTZW5zZYIJAJM9
424
1W+s6qptMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEEBQADgYEAAviQpdoeabL8
425
1HSZiD7Yjx82pdLpyQOdXvAu3jEAYz53ckx0zSMrzsQ5r7Vae6AE7Xd7Pj+1Yihs
426
AJZzOQujnmsuim7qu6YSxzP34xonKwd1C9tZUlyNRNnEmtXOEDupn05bih1ugtLG
427
kqfPIgDbDLXuPtEAA6QDUypaunI6+1E=
428
-----END CERTIFICATE-----
429

    
430
EOD;
431

    
432
			$key = <<<EOD
433
-----BEGIN RSA PRIVATE KEY-----
434
MIICXgIBAAKBgQDeU81MUfqqB7/KBqp78FLigfn07oq8B6xZxHNK7k3bWXJUTm0F
435
svTOo5JeaUvJF4xJu0Axmq3U/wQ9gWg5xoRAchabZVAXzRnXz7waHg5RAaMerzw5
436
5ourKTc4ulIrNKle4IWtI3ur0p7PzOnl1AS7uwhbfR1rekBt2pg6KYDVWwIDAQAB
437
AoGAP7E0VFP8Aq/7os3sE1uS8y8XQ7L+7cUo/AKKoQHKLjfeyAY7t3FALt6vdPqn
438
anGjkA/j4RIWELoKJfCnwj17703NDCPwB7klcmZvmTx5Om1ZrRyZdQ6RJs0pOOO1
439
r2wOnZNaNWStXE9Afpw3dj20Gh0V/Ioo5HXn3sHfxZm8dnkCQQDwv8OaUdp2Hl8t
440
FDfXB1CMvUG1hEAvbQvZK1ODkE7na2/ChKjVPddEI3DvfzG+nLrNuTrAyVWgRLte
441
r8qX5PQHAkEA7GlKx0S18LdiKo6wy2QeGu6HYkPncaHNFOWX8cTpvGGtQoWYSh0J
442
tjCt1/mz4/XkvZWuZyTNx2FdkVlNF5nHDQJBAIRWVTZqEjVlwpmsCHnp6mxCyHD4
443
DrRDNAUfnNuwIr9xPlDlzUzSnpc1CCqOd5C45LKbRGGfCrN7tKd66FmQoFcCQQCy
444
Kvw3R1pTCvHJnvYwoshphaC0dvaDVeyINiwYAk4hMf/wpVxLZqz+CJvLrB1dzOBR
445
3O+uPjdzbrakpweJpNQ1AkEA3ZtlgEj9eWsLAJP8aKlwB8VqD+EtG9OJSUMnCDiQ
446
WFFNj/t3Ze3IVuAyL/yMpiv3JNEnZhIxCta42eDFpIZAKw==
447
-----END RSA PRIVATE KEY-----
448

    
449
EOD;
450
		}
451
	} else {
452
		$cert = "";
453
		$key = "";
454
	}
455

    
456
	/* generate lighttpd configuration */
457
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
458
		$cert, $key, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/");
459

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

    
463
	if ($g['booting']) {
464
		if ($res == 0)
465
			echo "done.\n";
466
		else
467
			echo "failed!\n";
468
	}
469

    
470
	return $res;
471
}
472

    
473
function system_webgui_start_old() {
474
	global $config, $g;
475
	if(isset($config['system']['developerspew'])) {
476
		$mt = microtime();
477
		echo "system_webgui_start() being called $mt\n";
478
	}
479

    
480
        if ($g['booting'])
481
                echo "Starting webConfigurator... ";
482

    
483
        /* kill any running mini_httpd */
484
        killbypid("{$g['varrun_path']}/mini_httpd.pid");
485

    
486
        /* generate password file */
487
        system_password_configure();
488

    
489
        chdir($g['www_path']);
490

    
491
        /* non-standard port? */
492
        if ($config['system']['webgui']['port'])
493
                $portarg = "-p {$config['system']['webgui']['port']}";
494
        else
495
                $portarg = "";
496

    
497
        if ($config['system']['webgui']['protocol'] == "https") {
498

    
499
                if ($config['system']['webgui']['certificate'] && $config['system']['webgui']['private-key']) {
500
                        $cert = base64_decode($config['system']['webgui']['certificate']);
501
                        $key  = base64_decode($config['system']['webgui']['private-key']);
502
                } else {
503
                        /* default certificate/key */
504
                        $cert = <<<EOD
505
-----BEGIN CERTIFICATE-----
506
MIIBlDCB/gIBADANBgkqhkiG9w0BAQQFADATMREwDwYDVQQKEwhtMG4wd2FsbDAe
507
Fw0wNTA1MTAxMjI0NDRaFw0wNzA1MTAxMjI0NDRaMBMxETAPBgNVBAoTCG0wbjB3
508
YWxsMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDAShszhFz+o8lsMWTGgTxs
509
TMPR+v4+qL5jXDyY97MLTGFK7aqQOtpIQc+TcTc4jklgOVlHoR7oBXrsi8YrbCd+
510
83LPQmQoSPC0VqhfU3uYf3NzxiK8r97aPCsmWgwT2pQ6TcESTm6sF7nLprOf/zFP
511
C4jE2fvjkbzyVolPywBuewIDAQABMA0GCSqGSIb3DQEBBAUAA4GBAFR962c4R5tV
512
cTn0OQcszYoW6WC+ini9tQQh5ku5jYDAiC+00atawJEVLnL3lwAcpSKTIWlTkD20
513
tl3lz5br1qFgYky+Rd0kwS2nk9jRbkxSXxd6KJVnNRCKre28aw3ENzZfCSurPQsX
514
UPp5er+NtwMT1g7s/JDmKTC4w1rGr5/c
515
-----END CERTIFICATE-----
516

    
517
EOD;
518

    
519
                        $key = <<<EOD
520
-----BEGIN RSA PRIVATE KEY-----
521
MIICXQIBAAKBgQDAShszhFz+o8lsMWTGgTxsTMPR+v4+qL5jXDyY97MLTGFK7aqQ
522
OtpIQc+TcTc4jklgOVlHoR7oBXrsi8YrbCd+83LPQmQoSPC0VqhfU3uYf3NzxiK8
523
r97aPCsmWgwT2pQ6TcESTm6sF7nLprOf/zFPC4jE2fvjkbzyVolPywBuewIDAQAB
524
AoGAbJJrQW9fQrggJuLMz/hwsYW2m31oyOBmf5u463YQtjRuSuxe/gj87weZuNqY
525
H2rXq2k2K+ehl8hgW+egASyUL3L7kCkEAsVREujKTEyhSqqIRDPWTxo9S/YA9Gvn
526
2ZnJvkrcKjqCO9aHX3rvJOK/ErYI6akctgI3KmgkYw5XNmECQQDuZU97RTWH9rmP
527
aQr57ysNXxgFsyhetOOqeYkPtIVwpOiNbfwE1zi5RGdtO4Ku3fG1lV4J2UoWJ9yD
528
awdoyYIHAkEAzn0xJ90IjPsHk+8SODEj5JGdHSZPNu1tgtrbjEi9sfGWg4K7XTxr
529
QW90pWb1bKKU1uh5FzW6OhnFfuQXt1kC7QJAPSthqY+onKqCEnoxhtAHi/bKgyvl
530
P+fKQwPMV2tKkgy+XwvJjrRqqZ8TqsOKVLQ+QQmCh6RpjiXMPyxHSmvqIQJBAKLR
531
HF1ucDuaBROkwx0DwmWMW/KMLpIFDQDNSaiIAuu4rxHrl4mhBoGGPNffI04RtILw
532
s+qVNs5xW8T+XaT4ztECQQDFHPnZeoPWE5z+AX/UUQIUWaDExz3XRzmIxRbOrlFi
533
CsF1s0TdJLi/wzNQRAL37A8vqCeVFR/ng3Xpg96Yg+8Z
534
-----END RSA PRIVATE KEY-----
535

    
536
EOD;
537
                }
538
				
539
				$cert = str_replace("\r", "", $cert);
540
				$key = str_replace("\r", "", $key);
541
				
542
                $fd = fopen("{$g['varetc_path']}/cert.pem", "w");
543
                if (!$fd) {
544
                        printf("Error: cannot open cert.pem in system_webgui_start().\n");
545
                        return 1;
546
                }
547
                chmod("{$g['varetc_path']}/cert.pem", 0600);
548
                fwrite($fd, $cert);
549
                fwrite($fd, "\n");
550
                fwrite($fd, $key);
551
                fclose($fd);
552

    
553
                $res = mwexec("/usr/local/sbin/mini_httpd -S -E {$g['varetc_path']}/cert.pem" .
554
                        " -c \"**.php|**.cgi\" -u root -maxproc 16 $portarg" .
555
                        " -i {$g['varrun_path']}/mini_httpd.pid");
556
        } else {
557
                $res = mwexec("/usr/local/sbin/mini_httpd -c \"**.php|**.cgi\" -u root" .
558
                        " -maxproc 16 $portarg -i {$g['varrun_path']}/mini_httpd.pid");
559
        }
560

    
561
        if ($g['booting']) {
562
                if ($res == 0)
563
                        echo "done\n";
564
                else
565
                        echo "failed\n";
566
        }
567

    
568
        return $res;
569
}
570

    
571
function system_generate_lighty_config($filename,
572
	$cert,
573
	$key,
574
	$pid_file,
575
	$port = 80,
576
	$document_root = "/usr/local/www/",
577
	$cert_location = "cert.pem",
578
	$max_procs = 2,
579
	$max_requests = "1",
580
	$fast_cgi_enable = true,
581
	$captive_portal = false) {
582

    
583
	global $config, $g;
584

    
585
	if(isset($config['system']['developerspew'])) {
586
		$mt = microtime();
587
		echo "system_generate_lighty_config() being called $mt\n";
588
	}
589

    
590
	if($captive_portal == true)  {
591
		$captiveportal = ",\"mod_rewrite\"";
592
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*.[Gg][iI][fF]|.*.[Pp][nN][Gg]|.*.[Jj][Pp][Gg])\" => \"$1\", \"(.*)\" => \"/index.php?redirurl=$1\" )";
593
	}
594

    
595
	if($port <> "")
596
		$lighty_port = $port;
597
	else
598
		$lighty_port = "80";
599

    
600
	$memory = get_memory();
601
	$avail = $memory[0];
602

    
603
	if($avail > 0 and $avail < 75) {
604
		$max_procs = 1;
605
		$max_requests = 1;
606
	}
607

    
608
	if($avail > 0 and $avail < 45) {
609
		$fast_cgi_enable = false;
610
	}
611
		
612
	if($fast_cgi_enable == true) {
613
		$module = "\"mod_fastcgi\", \"mod_cgi\"";
614
		$cgi_config = "";
615
		$fastcgi_config = <<<EOD
616
#### fastcgi module
617
## read fastcgi.txt for more info
618
fastcgi.server             = ( ".php" =>
619
                               ( "localhost" =>
620
                                 (
621
                                   "socket" => "/tmp/php-fastcgi.socket",
622
				   "min-procs" => 1,
623
				   "max-procs" => {$max_procs},
624
				   "max-load-per-proc" => 100,
625
				   "idle-timeout" => 1,
626
				   "bin-environment" => ( 
627
				      "PHP_FCGI_CHILDREN" => "{$max_procs}",
628
				      "PHP_FCGI_MAX_REQUESTS" => "{$max_requests}"
629
				   ),				   
630
                                   "bin-path" => "/usr/local/bin/php"
631
                                 )
632
                               )
633
                            )		
634

    
635
#### CGI module
636
cgi.assign                 = ( ".cgi" => "" )
637

    
638
EOD;
639
	} else {
640
		$fastcgi_config = "";
641
		$module = "\"mod_cgi\"";
642
		$cgi_config = <<<EOD
643
#### CGI module
644
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
645
                               ".cgi" => "" )
646
		
647
EOD;
648
	}
649
	
650
	$lighty_config .= <<<EOD
651
#
652
# lighttpd configuration file
653
#
654
# use a it as base for lighttpd 1.0.0 and above
655
#
656
############ Options you really have to take care of ####################
657

    
658
# FreeBSD!
659
server.event-handler        = "freebsd-kqueue"
660

    
661
## modules to load
662
server.modules              =   (
663
				  "mod_access",
664
                                  {$module}{$captiveportal}
665
				)
666

    
667
## Unused modules
668
#                               "mod_setenv",
669
#                               "mod_compress"
670
#				"mod_redirect",
671
#                               "mod_rewrite",
672
#                               "mod_ssi",
673
#                               "mod_usertrack",
674
#                               "mod_expire",
675
#                               "mod_secdownload",
676
#                               "mod_rrdtool",
677
#                               "mod_auth",
678
#                               "mod_status",
679
#                               "mod_alias",
680
#                               "mod_proxy",
681
#                               "mod_simple_vhost",
682
#                               "mod_evhost",
683
#                               "mod_userdir",
684
#                               "mod_cgi",
685
#                                "mod_accesslog"
686

    
687
## a static document-root, for virtual-hosting take look at the
688
## server.virtual-* options
689
server.document-root        = "{$document_root}"
690
{$captive_portal_rewrite}
691

    
692
## where to send error-messages to
693
#server.errorlog             = "/var/log/lighttpd.error.log"
694

    
695
# files to check for if .../ is requested
696
server.indexfiles           = ( "index.php", "index.html",
697
                                "index.htm", "default.htm" )
698

    
699
# mimetype mapping
700
mimetype.assign             = (
701
  ".pdf"          =>      "application/pdf",
702
  ".sig"          =>      "application/pgp-signature",
703
  ".spl"          =>      "application/futuresplash",
704
  ".class"        =>      "application/octet-stream",
705
  ".ps"           =>      "application/postscript",
706
  ".torrent"      =>      "application/x-bittorrent",
707
  ".dvi"          =>      "application/x-dvi",
708
  ".gz"           =>      "application/x-gzip",
709
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
710
  ".swf"          =>      "application/x-shockwave-flash",
711
  ".tar.gz"       =>      "application/x-tgz",
712
  ".tgz"          =>      "application/x-tgz",
713
  ".tar"          =>      "application/x-tar",
714
  ".zip"          =>      "application/zip",
715
  ".mp3"          =>      "audio/mpeg",
716
  ".m3u"          =>      "audio/x-mpegurl",
717
  ".wma"          =>      "audio/x-ms-wma",
718
  ".wax"          =>      "audio/x-ms-wax",
719
  ".ogg"          =>      "audio/x-wav",
720
  ".wav"          =>      "audio/x-wav",
721
  ".gif"          =>      "image/gif",
722
  ".jpg"          =>      "image/jpeg",
723
  ".jpeg"         =>      "image/jpeg",
724
  ".png"          =>      "image/png",
725
  ".xbm"          =>      "image/x-xbitmap",
726
  ".xpm"          =>      "image/x-xpixmap",
727
  ".xwd"          =>      "image/x-xwindowdump",
728
  ".css"          =>      "text/css",
729
  ".html"         =>      "text/html",
730
  ".htm"          =>      "text/html",
731
  ".js"           =>      "text/javascript",
732
  ".asc"          =>      "text/plain",
733
  ".c"            =>      "text/plain",
734
  ".conf"         =>      "text/plain",
735
  ".text"         =>      "text/plain",
736
  ".txt"          =>      "text/plain",
737
  ".dtd"          =>      "text/xml",
738
  ".xml"          =>      "text/xml",
739
  ".mpeg"         =>      "video/mpeg",
740
  ".mpg"          =>      "video/mpeg",
741
  ".mov"          =>      "video/quicktime",
742
  ".qt"           =>      "video/quicktime",
743
  ".avi"          =>      "video/x-msvideo",
744
  ".asf"          =>      "video/x-ms-asf",
745
  ".asx"          =>      "video/x-ms-asf",
746
  ".wmv"          =>      "video/x-ms-wmv",
747
  ".bz2"          =>      "application/x-bzip",
748
  ".tbz"          =>      "application/x-bzip-compressed-tar",
749
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
750
 )
751

    
752
# Use the "Content-Type" extended attribute to obtain mime type if possible
753
#mimetypes.use-xattr        = "enable"
754

    
755
#### accesslog module
756
#accesslog.filename          = "/dev/null"
757

    
758
## deny access the file-extensions
759
#
760
# ~    is for backupfiles from vi, emacs, joe, ...
761
# .inc is often used for code includes which should in general not be part
762
#      of the document-root
763
url.access-deny             = ( "~", ".inc" )
764

    
765

    
766
######### Options that are good to be but not neccesary to be changed #######
767

    
768
## bind to port (default: 80)
769
server.port                = {$lighty_port}
770

    
771
## error-handler for status 404
772
#server.error-handler-404   = "/error-handler.html"
773
#server.error-handler-404   = "/error-handler.php"
774

    
775
## to help the rc.scripts
776
server.pid-file            = "/var/run/{$pid_file}"
777

    
778
## virtual directory listings
779
server.dir-listing         = "disable"
780

    
781
## enable debugging
782
debug.log-request-header   = "disable"
783
debug.log-response-header  = "disable"
784
debug.log-request-handling = "disable"
785
debug.log-file-not-found   = "disable"
786

    
787
#### compress module
788
#compress.cache-dir         = "/tmp/lighttpd/cache/compress/"
789
#compress.filetype          = ("text/plain", "text/html")
790

    
791
{$fastcgi_config}
792

    
793
{$cgi_config}
794

    
795
EOD;
796

    
797
	$cert = str_replace("\r", "", $cert);
798
	$key = str_replace("\r", "", $key);	
799

    
800
	$cert = str_replace("\n\n", "\n", $cert);
801
	$key = str_replace("\n\n", "\n", $key);	
802

    
803
	if($cert <> "" and $key <> "") {
804
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
805
		if (!$fd) {
806
			printf("Error: cannot open cert.pem in system_webgui_start().\n");
807
			return 1;
808
		}
809
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
810
		fwrite($fd, $cert);
811
		fwrite($fd, "\n");
812
		fwrite($fd, $key);
813
		fclose($fd);
814
		$lighty_config .= "\n";
815
		$lighty_config .= "## ssl configuration\n";
816
		$lighty_config .= "ssl.engine = \"enable\"\n";
817
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";	
818
	}
819

    
820
	$fd = fopen("{$filename}", "w");
821
	if (!$fd) {
822
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
823
		return 1;
824
	}
825
	fwrite($fd, $lighty_config);
826
	fclose($fd);
827

    
828
	return 0;
829

    
830
}
831

    
832
function system_password_configure() {
833
	global $config, $g;
834
	if(isset($config['system']['developerspew'])) {
835
		$mt = microtime();
836
		echo "system_password_configure() being called $mt\n";
837
	}
838

    
839
	/* sync passwords */
840
	sync_webgui_passwords();
841

    
842
	/* !NOTE! conf_mount_ro is done by sync_webgui_passwords() */
843

    
844
	return 0;
845
}
846

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

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

    
856
	if ($g['booting'])
857
		echo "Setting timezone... ";
858

    
859
	/* extract appropriate timezone file */
860
	$timezone = $syscfg['timezone'];
861
	if (!$timezone)
862
		$timezone = "Etc/UTC";
863

    
864
	conf_mount_rw();
865

    
866
	exec("/usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
867
		escapeshellarg($timezone) . " > /etc/localtime");
868

    
869
	conf_mount_ro();
870

    
871
	if ($g['booting'])
872
		echo "done.\n";
873
}
874

    
875
function system_ntp_configure() {
876
	global $config, $g;
877
	if(isset($config['system']['developerspew'])) {
878
		$mt = microtime();
879
		echo "system_ntp_configure() being called $mt\n";
880
	}
881

    
882
	$syscfg = $config['system'];
883

    
884
	if ($g['booting'])
885
		echo "Starting NTP client... ";
886
	else {
887
		killbypid("{$g['varrun_path']}/runmsntp.pid");
888
		killbypid("{$g['varrun_path']}/msntp.pid");
889
	}
890

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

    
894
	if ($updateinterval > 0) {
895
		if ($updateinterval < 6)
896
			$updateinterval = 6;
897

    
898
		$timeservers = "";
899
		foreach (explode(' ', $syscfg['timeservers']) as $ts)
900
			$timeservers .= " " . $ts;
901

    
902
		mwexec_bg("/usr/local/bin/runmsntp.sh " .
903
			escapeshellarg("{$g['varrun_path']}/runmsntp.pid") . " " .
904
			escapeshellarg("{$g['varrun_path']}/msntp.pid") . " " .
905
			escapeshellarg($updateinterval) . " " .
906
			escapeshellarg($timeservers));
907
	}
908

    
909
	if ($g['booting'])
910
		echo "done.\n";
911
}
912

    
913
function system_halt() {
914
	global $g;
915

    
916
	system_reboot_cleanup();
917

    
918
	mwexec("nohup /etc/rc.halt > /dev/null 2>&1 &");
919
}
920

    
921
function system_reboot() {
922
	global $g;
923

    
924
	system_reboot_cleanup();
925

    
926
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
927
}
928

    
929
function system_reboot_sync() {
930
	global $g;
931

    
932
	system_reboot_cleanup();
933

    
934
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
935
}
936

    
937
function system_reboot_cleanup() {
938
	mwexec("/usr/local/bin/beep.sh stop");
939
	captiveportal_radius_stop_all();
940
}
941

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

    
949
	if ($early)
950
		$cmdn = "earlyshellcmd";
951
	else
952
		$cmdn = "shellcmd";
953

    
954
	if (is_array($config['system'][$cmdn])) {
955
		
956
		/* *cmd is an array, loop through */
957
		foreach ($config['system'][$cmdn] as $cmd) {
958
			exec($cmd);
959
		}
960

    
961
	} elseif($config['system'][$cmdn] <> "") {
962
		
963
		/* execute single item */
964
		exec($config['system'][$cmdn]);
965

    
966
	}
967
}
968

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

    
976
	if (isset($config['system']['disableconsolemenu'])) {
977
		touch("{$g['varetc_path']}/disableconsole");
978
	} else {
979
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
980
	}
981
}
982

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

    
990
	$dmesg = "";
991
	exec("/sbin/dmesg", $dmesg);
992

    
993
	/* find last copyright line (output from previous boots may be present) */
994
	$lastcpline = 0;
995

    
996
	for ($i = 0; $i < count($dmesg); $i++) {
997
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
998
			$lastcpline = $i;
999
	}
1000

    
1001
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1002
	if (!$fd) {
1003
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1004
		return 1;
1005
	}
1006

    
1007
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1008
		fwrite($fd, $dmesg[$i] . "\n");
1009

    
1010
	fclose($fd);
1011

    
1012
	return 0;
1013
}
1014

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

    
1022
	if (isset($config['system']['harddiskstandby'])) {
1023
		if ($g['booting']) {
1024
			echo 'Setting hard disk standby... ';
1025
		}
1026

    
1027
		$standby = $config['system']['harddiskstandby'];
1028
		// Check for a numeric value
1029
		if (is_numeric($standby)) {
1030
			// Sync the disk(s)
1031
			mwexec('/bin/sync');
1032
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1033
				// Reinitialize ATA-drives
1034
				mwexec('/usr/local/sbin/atareinit');
1035
				if ($g['booting']) {
1036
					echo "done.\n";
1037
				}
1038
			} else if ($g['booting']) {
1039
				echo "failed!\n";
1040
			}
1041
		} else if ($g['booting']) {
1042
			echo "failed!\n";
1043
		}
1044
	}
1045
}
1046

    
1047
function system_setup_sysctl() {
1048
	global $config;
1049
	if(isset($config['system']['developerspew'])) {
1050
		$mt = microtime();
1051
		echo "system_setup_sysctl() being called $mt\n";
1052
	}
1053

    
1054
	$sysctl = return_filename_as_array("/etc/sysctl.conf");
1055
	foreach($sysctl as $sysc) {
1056
		if($sysc <> "")
1057
			mwexec("sysctl {$sysc} 2>/dev/null");
1058
	}
1059
	if (isset($config['system']['sharednet'])) {
1060
		system_disable_arp_wrong_if();
1061
	}
1062
}
1063

    
1064
function system_disable_arp_wrong_if() {
1065
	global $config;
1066
	if(isset($config['system']['developerspew'])) {
1067
		$mt = microtime();
1068
		echo "system_disable_arp_wrong_if() being called $mt\n";
1069
	}	
1070
	system("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0 2>/dev/null");
1071
}
1072

    
1073
function system_enable_arp_wrong_if() {
1074
	global $config;
1075
	if(isset($config['system']['developerspew'])) {
1076
		$mt = microtime();
1077
		echo "system_enable_arp_wrong_if() being called $mt\n";
1078
	}
1079
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1080
}
1081

    
1082
function enable_watchdog() {
1083
	global $config;
1084
	$install_watchdog = false;
1085
	$supported_watchdogs = array("Geode");
1086
	$file = file_get_contents("/var/log/dmesg.boot");
1087
	foreach($supported_watchdogs as $sd) {
1088
		if(stristr($file, "Geode")) {
1089
			$install_watchdog = true;
1090
		}
1091
	}
1092
	if($install_watchdog == true) {
1093
		exec("/usr/bin/killall watchdogd");
1094
		exec("/usr/sbin/watchdogd");		
1095
	}
1096
}
1097

    
1098
?>
(20-20/27)