Project

General

Profile

Download (31.3 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
auth.info;authpriv.info 						|exec /usr/local/sbin/sshlockout_pf
292
*.emerg						*
293

    
294

    
295
EOD;
296
		}
297

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

    
302
EOD;
303
		}
304

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

    
309
EOD;
310
		}
311

    
312

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

    
317
EOD;
318
		}
319

    
320

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

    
325
EOD;
326
		}
327

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

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

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

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

    
349
	return $retval;
350
}
351

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

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

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

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

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

    
375
	return $res;
376
}
377

    
378

    
379
function system_webgui_start() {
380
	global $config, $g;
381

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

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

    
388
	sleep(1);
389

    
390
	/* generate password file */
391
	system_password_configure();
392

    
393
	chdir($g['www_path']);
394

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

    
401
	if ($config['system']['webgui']['protocol'] == "https") {
402

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

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

    
432
EOD;
433

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

    
451
EOD;
452
		}
453
	} else {
454
		$cert = "";
455
		$key = "";
456
	}
457

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

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

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

    
472
	return $res;
473
}
474

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

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

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

    
488
        /* generate password file */
489
        system_password_configure();
490

    
491
        chdir($g['www_path']);
492

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

    
499
        if ($config['system']['webgui']['protocol'] == "https") {
500

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

    
519
EOD;
520

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

    
538
EOD;
539
                }
540

    
541
				$cert = str_replace("\r", "", $cert);
542
				$key = str_replace("\r", "", $key);
543

    
544
                $fd = fopen("{$g['varetc_path']}/cert.pem", "w");
545
                if (!$fd) {
546
                        printf("Error: cannot open cert.pem in system_webgui_start().\n");
547
                        return 1;
548
                }
549
                chmod("{$g['varetc_path']}/cert.pem", 0600);
550
                fwrite($fd, $cert);
551
                fwrite($fd, "\n");
552
                fwrite($fd, $key);
553
                fclose($fd);
554

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

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

    
570
        return $res;
571
}
572

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

    
585
	global $config, $g;
586

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

    
592
	if($captive_portal == true)  {
593
		$captiveportal = ",\"mod_rewrite\"";
594
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?redirurl=$1\" )\n";
595
	}
596

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

    
602
	$memory = get_memory();
603
	$avail = $memory[0];
604

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

    
610
	/* we told you that 64 megs would be slow */
611
	if ($avail > 0 and $avail < 65)
612
		$fast_cgi_enable = false;
613

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

    
637
#### CGI module
638
cgi.assign                 = ( ".cgi" => "" )
639

    
640
EOD;
641
	} else {
642
		$fastcgi_config = "";
643
		$module = "\"mod_cgi\"";
644
		$cgi_config = <<<EOD
645
#### CGI module
646
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
647
                               ".cgi" => "" )
648

    
649
EOD;
650
	}
651

    
652
	$lighty_config .= <<<EOD
653
#
654
# lighttpd configuration file
655
#
656
# use a it as base for lighttpd 1.0.0 and above
657
#
658
############ Options you really have to take care of ####################
659

    
660
# FreeBSD!
661
server.event-handler        = "freebsd-kqueue"
662

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

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

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

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

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

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

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

    
757
#### accesslog module
758
#accesslog.filename          = "/dev/null"
759

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

    
767

    
768
######### Options that are good to be but not neccesary to be changed #######
769

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

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

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

    
780
## virtual directory listings
781
server.dir-listing         = "disable"
782

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

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

    
793
server.upload-dirs = ( "{$g['upload_path']}", "/tmp" )
794

    
795
#server.network-backend = "writev"
796

    
797
server.upload-dirs = ( "{$g['upload_path']}" )
798

    
799
server.max-request-size = 2097152
800

    
801
{$fastcgi_config}
802

    
803
{$cgi_config}
804

    
805
EOD;
806

    
807
	$cert = str_replace("\r", "", $cert);
808
	$key = str_replace("\r", "", $key);
809

    
810
	$cert = str_replace("\n\n", "\n", $cert);
811
	$key = str_replace("\n\n", "\n", $key);
812

    
813
	if($cert <> "" and $key <> "") {
814
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
815
		if (!$fd) {
816
			printf("Error: cannot open cert.pem in system_webgui_start().\n");
817
			return 1;
818
		}
819
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
820
		fwrite($fd, $cert);
821
		fwrite($fd, "\n");
822
		fwrite($fd, $key);
823
		fclose($fd);
824
		$lighty_config .= "\n";
825
		$lighty_config .= "## ssl configuration\n";
826
		$lighty_config .= "ssl.engine = \"enable\"\n";
827
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
828
	}
829

    
830
	$fd = fopen("{$filename}", "w");
831
	if (!$fd) {
832
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
833
		return 1;
834
	}
835
	fwrite($fd, $lighty_config);
836
	fclose($fd);
837

    
838
	return 0;
839

    
840
}
841

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

    
849
	/* sync passwords */
850
	sync_webgui_passwords();
851

    
852
	/* !NOTE! conf_mount_ro is done by sync_webgui_passwords() */
853

    
854
	return 0;
855
}
856

    
857
function system_timezone_configure() {
858
	global $config, $g;
859
	if(isset($config['system']['developerspew'])) {
860
		$mt = microtime();
861
		echo "system_timezone_configure() being called $mt\n";
862
	}
863

    
864
	$syscfg = $config['system'];
865

    
866
	if ($g['booting'])
867
		echo "Setting timezone... ";
868

    
869
	/* extract appropriate timezone file */
870
	$timezone = $syscfg['timezone'];
871
	if (!$timezone)
872
		$timezone = "Etc/UTC";
873

    
874
	conf_mount_rw();
875

    
876
	exec("/usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
877
		escapeshellarg($timezone) . " > /etc/localtime");
878

    
879
	conf_mount_ro();
880

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

    
885
function system_ntp_configure() {
886
	global $config, $g;
887
	if(isset($config['system']['developerspew'])) {
888
		$mt = microtime();
889
		echo "system_ntp_configure() being called $mt\n";
890
	}
891

    
892
	$syscfg = $config['system'];
893

    
894
	if ($g['booting'])
895
		echo "Starting NTP client... ";
896
	else {
897
		killbypid("{$g['varrun_path']}/runmsntp.pid");
898
		killbypid("{$g['varrun_path']}/msntp.pid");
899
	}
900

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

    
904
	if ($updateinterval > 0) {
905
		if ($updateinterval < 6)
906
			$updateinterval = 6;
907

    
908
		$timeservers = "";
909
		foreach (explode(' ', $syscfg['timeservers']) as $ts)
910
			$timeservers .= " " . gethostbyname($ts);
911

    
912
		mwexec_bg("/usr/local/bin/runmsntp.sh " .
913
			escapeshellarg("{$g['varrun_path']}/runmsntp.pid") . " " .
914
			escapeshellarg("{$g['varrun_path']}/msntp.pid") . " " .
915
			escapeshellarg($updateinterval) . " " .
916
			escapeshellarg($timeservers));
917
	}
918

    
919
	if ($g['booting'])
920
		echo "done.\n";
921
}
922

    
923
function system_halt() {
924
	global $g;
925

    
926
	system_reboot_cleanup();
927

    
928
	mwexec("nohup /etc/rc.halt > /dev/null 2>&1 &");
929
}
930

    
931
function system_reboot() {
932
	global $g;
933

    
934
	system_reboot_cleanup();
935

    
936
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
937
}
938

    
939
function system_reboot_sync() {
940
	global $g;
941

    
942
	system_reboot_cleanup();
943

    
944
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
945
}
946

    
947
function system_reboot_cleanup() {
948
	mwexec("/usr/local/bin/beep.sh stop");
949
	captiveportal_radius_stop_all();
950
}
951

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

    
959
	if ($early)
960
		$cmdn = "earlyshellcmd";
961
	else
962
		$cmdn = "shellcmd";
963

    
964
	if (is_array($config['system'][$cmdn])) {
965

    
966
		/* *cmd is an array, loop through */
967
		foreach ($config['system'][$cmdn] as $cmd) {
968
			exec($cmd);
969
		}
970

    
971
	} elseif($config['system'][$cmdn] <> "") {
972

    
973
		/* execute single item */
974
		exec($config['system'][$cmdn]);
975

    
976
	}
977
}
978

    
979
function system_console_configure() {
980
	global $config, $g;
981
	if(isset($config['system']['developerspew'])) {
982
		$mt = microtime();
983
		echo "system_console_configure() being called $mt\n";
984
	}
985

    
986
	if (isset($config['system']['disableconsolemenu'])) {
987
		touch("{$g['varetc_path']}/disableconsole");
988
	} else {
989
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
990
	}
991
}
992

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

    
1000
	$dmesg = "";
1001
	exec("/sbin/dmesg", $dmesg);
1002

    
1003
	/* find last copyright line (output from previous boots may be present) */
1004
	$lastcpline = 0;
1005

    
1006
	for ($i = 0; $i < count($dmesg); $i++) {
1007
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1008
			$lastcpline = $i;
1009
	}
1010

    
1011
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1012
	if (!$fd) {
1013
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1014
		return 1;
1015
	}
1016

    
1017
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1018
		fwrite($fd, $dmesg[$i] . "\n");
1019

    
1020
	fclose($fd);
1021

    
1022
	return 0;
1023
}
1024

    
1025
function system_set_harddisk_standby() {
1026
	global $g, $config;
1027
	if(isset($config['system']['developerspew'])) {
1028
		$mt = microtime();
1029
		echo "system_set_harddisk_standby() being called $mt\n";
1030
	}
1031

    
1032
	if (isset($config['system']['harddiskstandby'])) {
1033
		if ($g['booting']) {
1034
			echo 'Setting hard disk standby... ';
1035
		}
1036

    
1037
		$standby = $config['system']['harddiskstandby'];
1038
		// Check for a numeric value
1039
		if (is_numeric($standby)) {
1040
			// Sync the disk(s)
1041
			mwexec('/bin/sync');
1042
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1043
				// Reinitialize ATA-drives
1044
				mwexec('/usr/local/sbin/atareinit');
1045
				if ($g['booting']) {
1046
					echo "done.\n";
1047
				}
1048
			} else if ($g['booting']) {
1049
				echo "failed!\n";
1050
			}
1051
		} else if ($g['booting']) {
1052
			echo "failed!\n";
1053
		}
1054
	}
1055
}
1056

    
1057
function system_setup_sysctl() {
1058
	global $config;
1059
	if(isset($config['system']['developerspew'])) {
1060
		$mt = microtime();
1061
		echo "system_setup_sysctl() being called $mt\n";
1062
	}
1063

    
1064
	$sysctl = return_filename_as_array("/etc/sysctl.conf");
1065
	foreach($sysctl as $sysc) {
1066
		if($sysc <> "")
1067
			mwexec("sysctl {$sysc} 2>/dev/null");
1068
	}
1069
	if (isset($config['system']['sharednet'])) {
1070
		system_disable_arp_wrong_if();
1071
	}
1072
}
1073

    
1074
function system_disable_arp_wrong_if() {
1075
	global $config;
1076
	if(isset($config['system']['developerspew'])) {
1077
		$mt = microtime();
1078
		echo "system_disable_arp_wrong_if() being called $mt\n";
1079
	}
1080
	system("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0 2>/dev/null");
1081
}
1082

    
1083
function system_enable_arp_wrong_if() {
1084
	global $config;
1085
	if(isset($config['system']['developerspew'])) {
1086
		$mt = microtime();
1087
		echo "system_enable_arp_wrong_if() being called $mt\n";
1088
	}
1089
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1090
}
1091

    
1092
function enable_watchdog() {
1093
	global $config;
1094
	$install_watchdog = false;
1095
	$supported_watchdogs = array("Geode");
1096
	$file = file_get_contents("/var/log/dmesg.boot");
1097
	foreach($supported_watchdogs as $sd) {
1098
		if(stristr($file, "Geode")) {
1099
			$install_watchdog = true;
1100
		}
1101
	}
1102
	if($install_watchdog == true) {
1103
		exec("/usr/bin/killall watchdogd");
1104
		exec("/usr/sbin/watchdogd");
1105
	}
1106
}
1107

    
1108
?>
(20-20/27)