Project

General

Profile

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

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

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

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

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

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

    
32
/*
33
	pfSense_BUILDER_BINARIES:	/usr/sbin/powerd	/usr/bin/killall	/sbin/sysctl	/sbin/route
34
	pfSense_BUILDER_BINARIES:	/bin/hostname	/bin/ls	/usr/sbin/syslogd	
35
	pfSense_BUILDER_BINARIES:	/usr/sbin/pccardd	/usr/local/sbin/lighttpd	/bin/chmod 	/bin/mkdir
36
	pfSense_BUILDER_BINARIES:	/usr/bin/tar		/usr/local/sbin/ntpd	/usr/sbin/ntpdate
37
	pfSense_BUILDER_BINARIES:	/usr/bin/nohup	/sbin/dmesg	/usr/local/sbin/atareinit	/sbin/kldload
38
	pfSense_MODULE:	utils
39
*/
40

    
41
function activate_powerd() {
42
	global $config, $g;
43
	if ($g['platform'] == 'jail')
44
		return;
45
	if(isset($config['system']['powerd_enable'])) {
46
		if ($g["platform"] == "nanobsd")
47
			exec("/sbin/kldload cpufreq");
48
		exec("/usr/sbin/powerd -b adp -a adp");
49
	} else {
50
		if(is_process_running("powerd"))
51
			exec("/usr/bin/killall powerd");
52
	}
53
}
54

    
55
function get_default_sysctl_value($id) {
56
	global $sysctls;
57

    
58
	if (isset($sysctls[$id]))
59
		return $sysctls[$id];
60
}
61

    
62
function activate_sysctls() {
63
	global $config, $g;
64
	if ($g['platform'] == 'jail')
65
		return;
66
	exec("/sbin/sysctl net.enc.out.ipsec_bpf_mask=0x00000001");
67
	exec("/sbin/sysctl net.enc.out.ipsec_filter_mask=0x00000001");
68
	exec("/sbin/sysctl net.enc.in.ipsec_bpf_mask=0x00000002");
69
	exec("/sbin/sysctl net.enc.in.ipsec_filter_mask=0x00000002");
70

    
71
	if(is_array($config['sysctl'])) {
72
		foreach($config['sysctl']['item'] as $tunable) {
73
			if($tunable['value'] == "default") {
74
				$value = get_default_sysctl_value($tunable['tunable']);
75
				mwexec("/sbin/sysctl " . $tunable['tunable'] . "=\"" . $value .  "\"");
76
			} else { 
77
				mwexec("/sbin/sysctl " . $tunable['tunable'] . "=\"" . $tunable['value'] .  "\"");
78
			}
79
		}
80
	}
81
}
82

    
83
function system_resolvconf_generate($dynupdate = false) {
84
	global $config, $g;
85

    
86
	if(isset($config['system']['developerspew'])) {
87
		$mt = microtime();
88
		echo "system_resolvconf_generate() being called $mt\n";
89
	}
90

    
91
	$syscfg = $config['system'];
92

    
93
	// Do not create blank domain lines, it breaks tools like dig.
94
	if($syscfg['domain'])
95
		$resolvconf = "domain {$syscfg['domain']}\n";
96

    
97
	if (isset($config['dnsmasq']['enable']) && !isset($config['system']['dnslocalhost']))
98
		$resolvconf .= "nameserver 127.0.0.1\n";
99

    
100
	if (isset($syscfg['dnsallowoverride'])) {
101
		/* get dynamically assigned DNS servers (if any) */
102
		$ns = array_unique(get_searchdomains());
103
		foreach($ns as $searchserver) {
104
			if($searchserver)
105
				$resolvconf .= "search {$searchserver}\n";
106
		}
107
		$ns = array_unique(get_nameservers());
108
		foreach($ns as $nameserver) {
109
			if($nameserver)
110
				$resolvconf .= "nameserver $nameserver\n";
111
		}
112
	}
113
	if (is_array($syscfg['dnsserver'])) {
114
		foreach ($syscfg['dnsserver'] as $ns) {
115
			if ($ns)
116
				$resolvconf .= "nameserver $ns\n";
117
		}
118
	}
119

    
120
	$dnslock = lock('resolvconf', LOCK_EX);
121

    
122
	$fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
123
	if (!$fd) {
124
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
125
		unlock($dnslock);
126
		return 1;
127
	}
128

    
129
	fwrite($fd, $resolvconf);
130
	fclose($fd);
131

    
132
	if (!$g['booting']) {
133
		/* restart dhcpd (nameservers may have changed) */
134
		if (!$dynupdate)
135
			services_dhcpd_configure();
136
	}
137

    
138
	/* setup static routes for DNS servers. */
139
	for ($dnscounter=1; $dnscounter<5; $dnscounter++) {
140
		/* setup static routes for dns servers */
141
		$dnsgw = "dns{$dnscounter}gw";
142
		if (isset($config['system'][$dnsgw])) {
143
			$gwname = $config['system'][$dnsgw];
144
			if (($gwname <> "") && ($gwname <> "none")) {
145
				$gatewayip = lookup_gateway_ip_by_name($gwname);
146
				if (is_ipaddrv4($gatewayip)) {
147
					/* dns server array starts at 0 */
148
					$dnscountermo = $dnscounter - 1;
149
					mwexec("route change -host " . $syscfg['dnsserver'][$dnscountermo] . " {$gatewayip}");
150
				}
151
				if (is_ipaddrv6($gatewayip)) {
152
					/* dns server array starts at 0 */
153
					$dnscountermo = $dnscounter - 1;
154
					mwexec("route change -host inet6 " . $syscfg['dnsserver'][$dnscountermo] . " {$gatewayip}");
155
				}
156
			}
157
		}
158
	}
159

    
160
	unlock($dnslock);
161

    
162
	return 0;
163
}
164

    
165
function get_searchdomains() {
166
	global $config, $g;
167

    
168
	$master_list = array();
169
	
170
	// Read in dhclient nameservers
171
	$search_list = glob("/var/etc/searchdomain_*");
172
	if (is_array($search_lists)) {
173
		foreach($search_lists as $fdns) {
174
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
175
			if (!is_array($contents))
176
				continue;
177
			foreach ($contents as $dns) {
178
				if(is_hostname($dns)) 
179
					$master_list[] = $dns;
180
			}
181
		}
182
	}
183

    
184
	return $master_list;
185
}
186

    
187
function get_nameservers() {
188
	global $config, $g;
189
	$master_list = array();
190
	
191
	// Read in dhclient nameservers
192
	$dns_lists = glob("/var/etc/nameserver_*");
193
	if (is_array($dns_lists)) {
194
		foreach($dns_lists as $fdns) {
195
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
196
			if (!is_array($contents))
197
				continue;
198
			foreach ($contents as $dns) {
199
				if(is_ipaddr($dns)) 
200
					$master_list[] = $dns;
201
			}
202
		}
203
	}
204

    
205
	// Read in any extra nameservers
206
	if(file_exists("/var/etc/nameservers.conf")) {
207
		$dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
208
		if(is_array($dns_s)) {
209
			foreach($dns_s as $dns)
210
				if (is_ipaddr($dns))
211
					$master_list[] = $dns;
212
		}
213
	}
214

    
215
	return $master_list;
216
}
217

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

    
225
	$syscfg = $config['system'];
226
	$dnsmasqcfg = $config['dnsmasq'];
227

    
228
	if (!is_array($dnsmasqcfg['hosts'])) {
229
		$dnsmasqcfg['hosts'] = array();
230
	}
231
	$hostscfg = $dnsmasqcfg['hosts'];
232

    
233
	$hosts = "127.0.0.1	localhost localhost.{$syscfg['domain']}\n";
234
	$lhosts = "";
235
	$dhosts = "";
236

    
237
	if ($config['interfaces']['lan']) {
238
		$cfgip = get_interface_ip("lan");
239
		if (is_ipaddr($cfgip))
240
			$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
241
	} else {
242
		$sysiflist = get_configured_interface_list();
243
		foreach ($sysiflist as $sysif) {
244
			if (!interface_has_gateway($sysif)) {
245
				$cfgip = get_interface_ip($sysif);
246
				if (is_ipaddr($cfgip)) {
247
					$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
248
					break;
249
				}
250
			}
251
		}
252
	}
253

    
254
	foreach ($hostscfg as $host) {
255
		if ($host['host'])
256
			$lhosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
257
		else
258
			$lhosts .= "{$host['ip']}	{$host['domain']}\n";
259
	}
260
	if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpd'])) {
261
		foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf)
262
			if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
263
					foreach ($dhcpifconf['staticmap'] as $host)
264
						if ($host['ipaddr'] && $host['hostname'])
265
							$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
266
		foreach ($config['dhcpdv6'] as $dhcpif => $dhcpifconf)
267
			if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
268
					foreach ($dhcpifconf['staticmap'] as $host)
269
						if ($host['ipaddrv6'] && $host['hostname'])
270
							$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
271
	}
272

    
273
	if (isset($dnsmasqcfg['dhcpfirst']))
274
		$hosts .= $dhosts . $lhosts;
275
	else
276
		$hosts .= $lhosts . $dhosts;
277

    
278
	/*
279
	 * Do not remove this because dhcpleases monitors with kqueue it needs to be 
280
	 * killed before writing to hosts files.
281
	 */
282
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
283
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
284
                @unlink("{$g['varrun_path']}/dhcpleases.pid");
285
	}
286
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
287
	if (!$fd) {
288
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
289
		return 1;
290
	}
291
	fwrite($fd, $hosts);
292
	fclose($fd);
293

    
294
	system_dhcpleases_configure();
295

    
296
	return 0;
297
}
298

    
299
function system_dhcpleases_configure() {
300
	global $config, $g;
301
	
302
	if ($g['platform'] == 'jail')
303
		return;
304
	/* Start the monitoring process for dynamic dhcpclients. */
305
	if (isset($config['dnsmasq']['regdhcp'])) {
306
		/* Make sure we do not error out */
307
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
308
		if (file_exists("{$g['varrun_path']}/dhcpleases.pid"))
309
				sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "HUP");
310
		else
311
			mwexec("/usr/local/sbin/dhcpleases -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases -d {$config['system']['domain']} -p {$g['varrun_path']}/dnsmasq.pid -h {$g['varetc_path']}/hosts");
312
	} else {
313
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
314
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
315
	}
316
}
317

    
318
function system_hostname_configure() {
319
	global $config, $g;
320
	if(isset($config['system']['developerspew'])) {
321
		$mt = microtime();
322
		echo "system_hostname_configure() being called $mt\n";
323
	}
324

    
325
	$syscfg = $config['system'];
326

    
327
	/* set hostname */
328
	$status = mwexec("/bin/hostname " .
329
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
330

    
331
    /* Setup host GUID ID.  This is used by ZFS. */
332
	mwexec("/etc/rc.d/hostid start");
333

    
334
	return $status;
335
}
336

    
337
function system_routing_configure($interface = "") {
338
	global $config, $g;
339
	if ($g['platform'] == 'jail')
340
		return;
341
	if(isset($config['system']['developerspew'])) {
342
		$mt = microtime();
343
		echo "system_routing_configure() being called $mt\n";
344
	}
345

    
346
	$gatewayip = "";
347
	$interfacegw = "";
348
	$foundgw = false;
349
	$gatewayipv6 = "";
350
	$interfacegwv6 = "";
351
	$foundgwv6 = false;
352
	/* tack on all the hard defined gateways as well */
353
	if (is_array($config['gateways']['gateway_item'])) {
354
		mwexec("/bin/rm {$g['tmp_path']}/*_defaultgw", true);
355
		foreach	($config['gateways']['gateway_item'] as $gateway) {
356
			if (isset($gateway['defaultgw']) && (is_ipaddrv4($gateway['gateway']))) {
357
				if(strstr($gateway['gateway'], ":"))
358
					break;
359
				if ($gateway['gateway'] == "dynamic")
360
					$gateway['gateway'] = get_interface_gateway($gateway['interface']);
361
				$gatewayip = $gateway['gateway'];
362
				$interfacegw = $gateway['interface'];
363
				if (!empty($interfacegw)) {
364
					$defaultif = get_real_interface($gateway['interface']);
365
					if ($defaultif)
366
						@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gatewayip);
367
				}
368
				$foundgw = true;
369
				break;
370
			}
371
		}
372
		foreach	($config['gateways']['gateway_item'] as $gateway) {
373
			if (isset($gateway['defaultgw']) && (is_ipaddrv6($gateway['gateway']))) {
374
				if ($gateway['gateway'] == "dynamic6")
375
					$gateway['gateway'] = get_interface_gateway_v6($gateway['interface']);
376
				$gatewayipv6 = $gateway['gateway'];
377
				$interfacegwv6 = $gateway['interface'];
378
				if (!empty($interfacegwv6)) {
379
					$defaultifv6 = get_real_interface($gateway['interface']);
380
					if ($defaultifv6)
381
						@file_put_contents("{$g['tmp_path']}/{$defaultifv6}_defaultgwv6", $gatewayipv6);
382
				}
383
				$foundgwv6 = true;
384
				break;
385
			}
386
		}
387
	}
388
	if ($foundgw == false) {
389
		$defaultif = get_real_interface("wan");
390
		$interfacegw = "wan";
391
		$gatewayip = get_interface_gateway("wan");
392
		@touch("{$g['tmp_path']}/{$defaultif}_defaultgw");
393
	}	
394
	if ($foundgwv6 == false) {
395
		$defaultifv6 = get_real_interface("wan");
396
		$interfacegwv6 = "wan";
397
		$gatewayipv6 = get_interface_gateway_v6("wan");
398
		@touch("{$g['tmp_path']}/{$defaultif}_defaultgwv6");
399
	}
400
	$dont_add_route = false;
401
	/* if OLSRD is enabled, allow WAN to house DHCP. */
402
	if($config['installedpackages']['olsrd']) {
403
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
404
			if(($olsrd['enabledyngw'] == "on") && ($olsrd['enable'] == "on")) {
405
				$dont_add_route = true;
406
				log_error(sprintf(gettext("Not adding default route because OLSR dynamic gateway is enabled.")));
407
				break;
408
			}
409
		}
410
	}
411

    
412
	if ($dont_add_route == false ) {
413
		if (!empty($interface) && $interface != $interfacegw)
414
			;
415
		else if (($interfacegw <> "bgpd") && (is_ipaddrv4($gatewayip))) {
416
			log_error("ROUTING: setting default route to $gatewayip");
417
			mwexec("/sbin/route change -inet default " . escapeshellarg($gatewayip));
418
		}
419

    
420
		if (!empty($interface) && $interface != $interfacegwv6)
421
			;
422
		else if (($interfacegwv6 <> "bgpd") && (is_ipaddrv6($gatewayipv6))) {
423
			if(preg_match("/fe80::/i", $gatewayipv6))
424
				$ifscope = "%{$defaultifv6}";
425
			log_error("ROUTING: setting IPv6 default route to {$gatewayipv6}{$ifscope}");
426
			mwexec("/sbin/route change -inet6 default " . escapeshellarg($gatewayipv6) ."{$ifscope}");
427
		}
428
	}
429

    
430
	if (is_array($config['staticroutes']['route'])) {
431
		$gateways_arr = return_gateways_array();
432

    
433
		foreach ($config['staticroutes']['route'] as $rtent) {
434
			$gatewayip = "";
435
			if (empty($gateways_arr[$rtent['gateway']])) {
436
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
437
				continue;
438
			}
439
			$gateway = $gateways_arr[$rtent['gateway']];
440
			if (!empty($interface) && $interface != $gateway['friendlyiface'])
441
				continue;
442

    
443
			if(isset($rtent['disabled'])) {
444
				mwexec("/sbin/route delete " . escapeshellarg($rtent['network']), true);
445
				continue;
446
			}
447

    
448
			$gatewayip = $gateway['gateway'];
449
			$interfacegw = $gateway['interface'];
450

    
451
			if(is_ipaddrv6($gatewayip)) {
452
				$inetfamily = "-inet6";
453
			} else {
454
				$inetfamily = "-inet";
455
			}
456
			if (is_ipaddr($gatewayip)) {
457
				mwexec("/sbin/route change {$inetfamily} " . escapeshellarg($rtent['network']) .
458
					" " . escapeshellarg($gatewayip));
459
			} else if (!empty($interfacegw)) {
460
				mwexec("/sbin/route change {$inetfamily} " . escapeshellarg($rtent['network']) .
461
					" -iface " . escapeshellarg($interfacegw));
462
			}
463
		}
464
	}
465

    
466
	return 0;
467
}
468

    
469
function system_routing_enable() {
470
	global $config, $g;
471
	if(isset($config['system']['developerspew'])) {
472
		$mt = microtime();
473
		echo "system_routing_enable() being called $mt\n";
474
	}
475

    
476
	mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
477
	mwexec("/sbin/sysctl net.inet6.ip6.forwarding=1");
478
	return;
479
}
480

    
481
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
482
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
483
	$facility .= " ".
484
	$remote_servers = "";
485
	$pad_to  = 56;
486
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
487
	if($syslogcfg['remoteserver'])
488
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@{$syslogcfg['remoteserver']}\n";
489
	if($syslogcfg['remoteserver2'])
490
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@{$syslogcfg['remoteserver2']}\n";
491
	if($syslogcfg['remoteserver3'])
492
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@{$syslogcfg['remoteserver3']}\n";
493
	return $remote_servers;
494
}
495

    
496
function system_syslogd_start() {
497
	global $config, $g;
498
	if(isset($config['system']['developerspew'])) {
499
		$mt = microtime();
500
		echo "system_syslogd_start() being called $mt\n";
501
	}
502

    
503
	mwexec("/etc/rc.d/hostid start");
504

    
505
	$syslogcfg = $config['syslog'];
506

    
507
	if ($g['booting'])
508
		echo gettext("Starting syslog...");
509
	else
510
		killbypid("{$g['varrun_path']}/syslog.pid");
511

    
512
	if(is_process_running("syslogd"))
513
		mwexec('/bin/pkill syslogd');
514
	if(is_process_running("fifolog_writer"))
515
		mwexec('/bin/pkill fifolog_writer');
516
	
517
	// Define carious commands for logging
518
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
519
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
520
	$clog_create = "/usr/sbin/clog -i -s ";
521
	$clog_log = "%";
522

    
523
	// Which logging type are we using this week??
524
	if(isset($config['system']['usefifolog'])) {
525
		$log_directive = $fifolog_log;
526
		$log_create_directive = $fifolog_create;
527
	} else { // Defaults to CLOG
528
		$log_directive = $clog_log;
529
		$log_create_directive = $clog_create;
530
	}
531
	
532
	if (isset($syslogcfg)) {
533
		$separatelogfacilities = array('ntpd','racoon','openvpn','pptps','poes','l2tps','relayd','hostapd');
534
		if($config['installedpackages']['package']) {
535
			foreach($config['installedpackages']['package'] as $package) {
536
				if($package['logging']) {
537
					array_push($separatelogfacilities, $package['logging']['facilityname']);
538
					mwexec("{$log_create_directive} 10240 {$g['varlog_path']}/{$package['logging']['logfilename']}");
539
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
540
				}
541
			}
542
		}
543
		$facilitylist = implode(',', array_unique($separatelogfacilities));
544
		/* write syslog.conf */		
545
		$fd = fopen("{$g['varetc_path']}/syslog.conf", "w");
546
		if (!$fd) {
547
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
548
			return 1;
549
		}
550
		$syslogconf .= "!ntpdate,ntpd\n";
551
		if (!isset($syslogcfg['disablelocallogging'])) 
552
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
553

    
554
		$syslogconf .= "!ppp\n";
555
		if (!isset($syslogcfg['disablelocallogging'])) 
556
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
557

    
558
		$syslogconf .= "!pptps\n";
559
		if (!isset($syslogcfg['disablelocallogging'])) 
560
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/pptps.log\n";
561

    
562
		$syslogconf .= "!poes\n";
563
		if (!isset($syslogcfg['disablelocallogging'])) 
564
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
565

    
566
		$syslogconf .= "!l2tps\n";
567
		if (!isset($syslogcfg['disablelocallogging'])) 
568
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/l2tps.log\n";
569

    
570
		$syslogconf .= "!racoon\n";
571
		if (!isset($syslogcfg['disablelocallogging'])) 
572
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ipsec.log\n";
573
		if (isset($syslogcfg['vpn']))
574
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
575

    
576
		$syslogconf .= "!openvpn\n";
577
		if (!isset($syslogcfg['disablelocallogging'])) 
578
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/openvpn.log\n";
579
		if (isset($syslogcfg['vpn']))
580
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
581

    
582
		$syslogconf .= "!apinger\n";
583
		if (!isset($syslogcfg['disablelocallogging']))
584
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/apinger.log\n";
585
		if (isset($syslogcfg['apinger']))
586
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
587

    
588
		$syslogconf .= "!relayd\n";
589
		if (!isset($syslogcfg['disablelocallogging']))
590
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/relayd.log\n";
591
		if (isset($syslogcfg['relayd']))
592
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
593

    
594
		$syslogconf .= "!hostapd\n";
595
		if (!isset($syslogcfg['disablelocallogging']))
596
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
597
		if (isset($syslogcfg['hostapd']))
598
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
599

    
600
		$syslogconf .= "!-{$facilitylist}\n";
601
		if (!isset($syslogcfg['disablelocallogging'])) 
602
			$syslogconf .= <<<EOD
603
local0.*							{$log_directive}{$g['varlog_path']}/filter.log
604
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
605
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
606
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
607
*.notice;kern.debug;lpr.info;mail.crit;				{$log_directive}{$g['varlog_path']}/system.log
608
news.err;local0.none;local3.none;local4.none;			{$log_directive}{$g['varlog_path']}/system.log
609
local7.none							{$log_directive}{$g['varlog_path']}/system.log
610
security.*							{$log_directive}{$g['varlog_path']}/system.log
611
auth.info;authpriv.info;daemon.info				{$log_directive}{$g['varlog_path']}/system.log
612
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
613
*.emerg								*
614

    
615
EOD;
616
		if (isset($syslogcfg['filter']))
617
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local0.*");
618
		if (isset($syslogcfg['vpn']))
619
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
620
		if (isset($syslogcfg['portalauth']))
621
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
622
		if (isset($syslogcfg['dhcp']))
623
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
624
		if (isset($syslogcfg['system'])) {
625
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.notice;kern.debug;lpr.info;mail.crit;");
626
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "news.err;local0.none;local3.none;local7.none");
627
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "security.*");
628
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "auth.info;authpriv.info;daemon.info");
629
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.emerg");
630
		}
631
		if (isset($syslogcfg['logall'])) {
632
			// Make everything mean everything, including facilities excluded above.
633
			$syslogconf .= "!*\n";
634
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
635
		}
636

    
637
		if (isset($syslogcfg['zmqserver'])) {
638
				$syslogconf .= <<<EOD
639
*.*								^{$syslogcfg['zmqserver']}
640

    
641
EOD;
642
		}
643
		fwrite($fd, $syslogconf);
644
		fclose($fd);
645

    
646
		// Ensure that the log directory exists
647
		if(!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
648
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
649

    
650
		// Are we logging to a least one remote server ?
651
		if(strpos($syslogconf, "@") != false)
652
			$retval = mwexec_bg("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log -f {$g['varetc_path']}/syslog.conf");
653
		else {
654
			$retval = mwexec_bg("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log -f {$g['varetc_path']}/syslog.conf");
655
		}
656

    
657
	} else {
658
		$retval = mwexec_bg("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log");
659
	}
660

    
661
	if ($g['booting'])
662
		echo gettext("done.") . "\n";
663

    
664
	return $retval;
665
}
666

    
667
function system_pccard_start() {
668
	global $config, $g;
669
	if(isset($config['system']['developerspew'])) {
670
		$mt = microtime();
671
		echo "system_pccard_start() being called $mt\n";
672
	}
673

    
674
	if ($g['booting'])
675
		echo gettext("Initializing PCMCIA...");
676

    
677
	/* kill any running pccardd */
678
	killbypid("{$g['varrun_path']}/pccardd.pid");
679

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

    
683
	if ($g['booting']) {
684
		if ($res == 0)
685
			echo gettext("done.") . "\n";
686
		else
687
			echo gettext("failed!") . "\n";
688
	}
689

    
690
	return $res;
691
}
692

    
693

    
694
function system_webgui_start() {
695
	global $config, $g;
696

    
697
	if ($g['booting'])
698
		echo gettext("Starting webConfigurator...");
699

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

    
703
	sleep(1);
704

    
705
	chdir($g['www_path']);
706

    
707
	/* defaults */
708
	$portarg = "80";
709
	$crt = "";
710
	$key = "";
711
	$ca = "";
712

    
713
	/* non-standard port? */
714
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
715
		$portarg = "{$config['system']['webgui']['port']}";
716

    
717
	if ($config['system']['webgui']['protocol'] == "https") {
718
		// Ensure that we have a webConfigurator CERT
719
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
720
		if(!is_array($cert) && !$cert['crt'] && !$cert['prv']) {
721
			if (!is_array($config['ca']))
722
				$config['ca'] = array();
723
			$a_ca =& $config['ca'];
724
			if (!is_array($config['cert']))
725
				$config['cert'] = array();
726
			$a_cert =& $config['cert'];
727
			log_error("Creating SSL Certificate for this host");
728
			$cert = array();
729
			$cert['refid'] = uniqid();
730
			$cert['descr'] = gettext("webConfigurator default");
731
			mwexec("/usr/bin/openssl genrsa 1024 > {$g['tmp_path']}/ssl.key");
732
			mwexec("/usr/bin/openssl req -new -x509 -nodes -sha1 -days 2000 -key {$g['tmp_path']}/ssl.key > {$g['tmp_path']}/ssl.crt");
733
			$crt = file_get_contents("{$g['tmp_path']}/ssl.crt");
734
			$key = file_get_contents("{$g['tmp_path']}/ssl.key");
735
			unlink("{$g['tmp_path']}/ssl.key");
736
			unlink("{$g['tmp_path']}/ssl.crt");
737
			cert_import($cert, $crt, $key);
738
			$a_cert[] = $cert;
739
			$config['system']['webgui']['ssl-certref'] = $cert['refid'];
740
			write_config(gettext("Importing HTTPS certificate"));
741
			if(!$config['system']['webgui']['port'])
742
				$portarg = "443";
743
			$ca = ca_chain($cert);
744
		} else {
745
			$crt = base64_decode($cert['crt']);
746
			$key = base64_decode($cert['prv']);
747
			if(!$config['system']['webgui']['port'])
748
				$portarg = "443";
749
			$ca = ca_chain($cert);
750
		}
751
	}
752

    
753
	/* generate lighttpd configuration */
754
	$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
755
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
756
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
757
		"cert.pem", "ca.pem", $max_procs);
758

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

    
762
	/* fetch page to preload apc cache */
763
	$proto = "http";
764
	if ($config['system']['webgui']['protocol'])
765
		$proto = $config['system']['webgui']['protocol'];
766
	mwexec_bg("/usr/bin/fetch -o /dev/null -q {$proto}://localhost:{$portarg}/preload.php");
767

    
768
	if ($g['booting']) {
769
		if ($res == 0)
770
			echo gettext("done.") . "\n";
771
		else
772
			echo gettext("failed!") . "\n";
773
	}
774

    
775
	return $res;
776
}
777

    
778
function system_generate_lighty_config($filename,
779
	$cert,
780
	$key,
781
	$ca,
782
	$pid_file,
783
	$port = 80,
784
	$document_root = "/usr/local/www/",
785
	$cert_location = "cert.pem",
786
	$ca_location = "ca.pem",
787
	$max_procs = 1,
788
	$max_requests = "2",
789
	$fast_cgi_enable = true,
790
	$captive_portal = false) {
791

    
792
	global $config, $g;
793

    
794
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
795
		mkdir("{$g['tmp_path']}/lighttpdcompress");
796

    
797
	if(isset($config['system']['developerspew'])) {
798
		$mt = microtime();
799
		echo "system_generate_lighty_config() being called $mt\n";
800
	}
801

    
802
	if($captive_portal != false)  {
803
		$captiveportal = ",\"mod_rewrite\"";
804
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?zone={$captive_portal}&redirurl=$1\" )\n";
805
		$captive_portal_module = "";
806
		$maxprocperip = $config['captiveportal']['maxprocperip'];
807
		if($maxprocperip and $maxprocperip > 0)
808
			$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
809
		else
810
			$captive_portal_mod_evasive = "";
811
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
812
		exec("mkdir -p {$g['tmp_path']}/captiveportal");
813
		exec("chmod a-w {$g['tmp_path']}/captiveportal");
814
		$server_max_request_size = "server.max-request-size    = 384";
815
	} else {
816
		$captiveportal = "";
817
		$captive_portal_rewrite = "";
818
		$captive_portal_module = "";
819
		$captive_portal_mod_evasive = "";
820
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
821
		$server_max_request_size = "server.max-request-size    = 2097152";
822
	}
823
	
824
	if($port <> "")
825
		$lighty_port = $port;
826
	else
827
		$lighty_port = "80";
828

    
829
	$memory = get_memory();
830
	$avail = $memory[0];
831

    
832
	if($avail > 0 and $avail < 65) {
833
		$fast_cgi_enable = false;
834
	}
835

    
836
	// Ramp up captive portal max procs
837
	//  Work relative to the default of 2, for values that would be >2.
838
	if($captive_portal == true)  {
839
		if($avail > 65 and $avail < 98) {
840
			$max_procs = 1;
841
		}
842
		if($avail > 97 and $avail < 128) {
843
			$max_procs = 2;
844
		}
845
		if($avail > 127 and $avail < 256) {
846
			$max_procs += 1;
847
		}
848
		if($avail > 255 and $avail < 384) {
849
			$max_procs += 2;
850
		}
851
		if($avail > 383) {
852
			$max_procs += 3;
853
		}
854
	}
855

    
856
	if($captive_portal == true)  {	
857
		$bin_environment =  <<<EOC
858
			"bin-environment" => (
859
				"PHP_FCGI_CHILDREN" => "0",
860
				"PHP_FCGI_MAX_REQUESTS" => "500"
861
			),
862
EOC;
863

    
864
	} else if ($avail > 0 and $avail < 128) {
865
		$bin_environment = <<<EOC
866
			"bin-environment" => (
867
				"PHP_FCGI_CHILDREN" => "0",
868
				"PHP_FCGI_MAX_REQUESTS" => "2",
869
			),
870

    
871
EOC;
872
	} else
873
		$bin_environment =  <<<EOC
874
			"bin-environment" => (
875
				"PHP_FCGI_CHILDREN" => "0",
876
				"PHP_FCGI_MAX_REQUESTS" => "500"
877
			),
878
EOC;
879

    
880
	if($fast_cgi_enable == true) {
881
		$module = "\"mod_fastcgi\", \"mod_cgi\"";
882
		if ($captive_portal != false)
883
			$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi-{$captive_portal}.socket";
884
		else
885
			$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi.socket";
886
		$cgi_config = "";
887
		$fastcgi_config = <<<EOD
888
#### fastcgi module
889
## read fastcgi.txt for more info
890
fastcgi.server = ( ".php" =>
891
	( "localhost" =>
892
		(
893
			"socket" => "{$fast_cgi_path}",
894
			"min-procs" => 0,
895
			"max-procs" => {$max_procs},
896
{$bin_environment}
897
			"bin-path" => "/usr/local/bin/php"
898
		)
899
	)
900
)
901

    
902
#### CGI module
903
cgi.assign                 = ( ".cgi" => "" )
904

    
905
EOD;
906
	} else {
907
		$fastcgi_config = "";
908
		$module = "\"mod_cgi\"";
909
		$cgi_config = <<<EOD
910
#### CGI module
911
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
912
                               ".cgi" => "" )
913

    
914
EOD;
915
	}
916

    
917
	$lighty_config = "";
918
	$lighty_config .= <<<EOD
919
#
920
# lighttpd configuration file
921
#
922
# use a it as base for lighttpd 1.0.0 and above
923
#
924
############ Options you really have to take care of ####################
925

    
926
## FreeBSD!
927
server.event-handler	= "freebsd-kqueue"
928
server.network-backend 	= "writev"
929
#server.use-ipv6 = "enable"
930

    
931
## modules to load
932
server.modules              =   (
933
	{$captive_portal_module}
934
	"mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect",
935
	{$module}{$captiveportal}
936
)
937

    
938
## Unused modules
939
#                               "mod_setenv",
940
#                               "mod_rewrite",
941
#                               "mod_ssi",
942
#                               "mod_usertrack",
943
#                               "mod_expire",
944
#                               "mod_secdownload",
945
#                               "mod_rrdtool",
946
#                               "mod_auth",
947
#                               "mod_status",
948
#                               "mod_alias",
949
#                               "mod_proxy",
950
#                               "mod_simple_vhost",
951
#                               "mod_evhost",
952
#                               "mod_userdir",
953
#                               "mod_cgi",
954

    
955
server.max-keep-alive-requests = 15
956
server.max-keep-alive-idle = 30
957

    
958
## a static document-root, for virtual-hosting take look at the
959
## server.virtual-* options
960
server.document-root        = "{$document_root}"
961
{$captive_portal_rewrite}
962

    
963
# Maximum idle time with nothing being written (php downloading)
964
server.max-write-idle = 999
965

    
966
## where to send error-messages to
967
server.errorlog             = "/var/log/lighttpd.error.log"
968

    
969
# files to check for if .../ is requested
970
server.indexfiles           = ( "index.php", "index.html",
971
                                "index.htm", "default.htm" )
972

    
973
# mimetype mapping
974
mimetype.assign             = (
975
  ".pdf"          =>      "application/pdf",
976
  ".sig"          =>      "application/pgp-signature",
977
  ".spl"          =>      "application/futuresplash",
978
  ".class"        =>      "application/octet-stream",
979
  ".ps"           =>      "application/postscript",
980
  ".torrent"      =>      "application/x-bittorrent",
981
  ".dvi"          =>      "application/x-dvi",
982
  ".gz"           =>      "application/x-gzip",
983
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
984
  ".swf"          =>      "application/x-shockwave-flash",
985
  ".tar.gz"       =>      "application/x-tgz",
986
  ".tgz"          =>      "application/x-tgz",
987
  ".tar"          =>      "application/x-tar",
988
  ".zip"          =>      "application/zip",
989
  ".mp3"          =>      "audio/mpeg",
990
  ".m3u"          =>      "audio/x-mpegurl",
991
  ".wma"          =>      "audio/x-ms-wma",
992
  ".wax"          =>      "audio/x-ms-wax",
993
  ".ogg"          =>      "audio/x-wav",
994
  ".wav"          =>      "audio/x-wav",
995
  ".gif"          =>      "image/gif",
996
  ".jpg"          =>      "image/jpeg",
997
  ".jpeg"         =>      "image/jpeg",
998
  ".png"          =>      "image/png",
999
  ".xbm"          =>      "image/x-xbitmap",
1000
  ".xpm"          =>      "image/x-xpixmap",
1001
  ".xwd"          =>      "image/x-xwindowdump",
1002
  ".css"          =>      "text/css",
1003
  ".html"         =>      "text/html",
1004
  ".htm"          =>      "text/html",
1005
  ".js"           =>      "text/javascript",
1006
  ".asc"          =>      "text/plain",
1007
  ".c"            =>      "text/plain",
1008
  ".conf"         =>      "text/plain",
1009
  ".text"         =>      "text/plain",
1010
  ".txt"          =>      "text/plain",
1011
  ".dtd"          =>      "text/xml",
1012
  ".xml"          =>      "text/xml",
1013
  ".mpeg"         =>      "video/mpeg",
1014
  ".mpg"          =>      "video/mpeg",
1015
  ".mov"          =>      "video/quicktime",
1016
  ".qt"           =>      "video/quicktime",
1017
  ".avi"          =>      "video/x-msvideo",
1018
  ".asf"          =>      "video/x-ms-asf",
1019
  ".asx"          =>      "video/x-ms-asf",
1020
  ".wmv"          =>      "video/x-ms-wmv",
1021
  ".bz2"          =>      "application/x-bzip",
1022
  ".tbz"          =>      "application/x-bzip-compressed-tar",
1023
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
1024
 )
1025

    
1026
# Use the "Content-Type" extended attribute to obtain mime type if possible
1027
#mimetypes.use-xattr        = "enable"
1028

    
1029
#### accesslog module
1030
#accesslog.filename          = "/dev/null"
1031

    
1032
## deny access the file-extensions
1033
#
1034
# ~    is for backupfiles from vi, emacs, joe, ...
1035
# .inc is often used for code includes which should in general not be part
1036
#      of the document-root
1037
url.access-deny             = ( "~", ".inc" )
1038

    
1039

    
1040
######### Options that are good to be but not neccesary to be changed #######
1041

    
1042
## bind to port (default: 80)
1043

    
1044
EOD;
1045

    
1046
	if($captive_portal == true) {
1047
		$lighty_config .= "server.bind	= \"127.0.0.1\"\n";
1048
		$lighty_config .= "server.port  = {$lighty_port}\n";
1049
		$lighty_config .= "\$SERVER[\"socket\"]  == \"127.0.0.1:{$lighty_port}\" { }\n";
1050
		$lighty_config .= "\$SERVER[\"socket\"]  == \"[::1]:{$lighty_port}\" { \n";
1051
		if($cert <> "" and $key <> "") {
1052
			$lighty_config .= "\n";
1053
			$lighty_config .= "## ssl configuration\n";
1054
			$lighty_config .= "ssl.engine = \"enable\"\n";
1055
			$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1056
			if($ca <> "")
1057
				$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1058
		}
1059
		$lighty_config .= " }\n";
1060
	} else {
1061
		$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1062
		$lighty_config .= "server.port  = {$lighty_port}\n";
1063
		$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1064
		$lighty_config .= "\$SERVER[\"socket\"]  == \"[::]:{$lighty_port}\" { \n";
1065
		if($cert <> "" and $key <> "") {
1066
			$lighty_config .= "\n";
1067
			$lighty_config .= "## ssl configuration\n";
1068
			$lighty_config .= "ssl.engine = \"enable\"\n";
1069
			$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1070
			if($ca <> "")
1071
				$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1072
		}
1073
		$lighty_config .= " }\n";
1074
	}
1075

    
1076

    
1077
	$lighty_config .= <<<EOD
1078

    
1079
## error-handler for status 404
1080
#server.error-handler-404   = "/error-handler.html"
1081
#server.error-handler-404   = "/error-handler.php"
1082

    
1083
## to help the rc.scripts
1084
server.pid-file            = "/var/run/{$pid_file}"
1085

    
1086
## virtual directory listings
1087
server.dir-listing         = "disable"
1088

    
1089
## enable debugging
1090
debug.log-request-header   = "disable"
1091
debug.log-response-header  = "disable"
1092
debug.log-request-handling = "disable"
1093
debug.log-file-not-found   = "disable"
1094

    
1095
# gzip compression
1096
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1097
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1098

    
1099
{$server_upload_dirs}
1100

    
1101
{$server_max_request_size}
1102

    
1103
{$fastcgi_config}
1104

    
1105
{$cgi_config}
1106

    
1107
{$captive_portal_mod_evasive}
1108

    
1109
expire.url = (
1110
				"" => "access 50 hours",	
1111
        )
1112

    
1113
EOD;
1114

    
1115
	$cert = str_replace("\r", "", $cert);
1116
	$key = str_replace("\r", "", $key);
1117
	$ca = str_replace("\r", "", $ca);
1118

    
1119
	$cert = str_replace("\n\n", "\n", $cert);
1120
	$key = str_replace("\n\n", "\n", $key);
1121
	$ca = str_replace("\n\n", "\n", $ca);
1122

    
1123
	if($cert <> "" and $key <> "") {
1124
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1125
		if (!$fd) {
1126
			printf(gettext("Error: cannot open cert.pem in system_webgui_start().%s"), "\n");
1127
			return 1;
1128
		}
1129
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1130
		fwrite($fd, $cert);
1131
		fwrite($fd, "\n");
1132
		fwrite($fd, $key);
1133
		fclose($fd);
1134
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
1135
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1136
			if (!$fd) {
1137
				printf(gettext("Error: cannot open ca.pem in system_webgui_start().%s"), "\n");
1138
				return 1;
1139
			}
1140
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1141
			fwrite($fd, $ca);
1142
			fclose($fd);
1143
		}
1144
		$lighty_config .= "\n";
1145
		$lighty_config .= "## " . gettext("ssl configuration") . "\n";
1146
		$lighty_config .= "ssl.engine = \"enable\"\n";
1147
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1148

    
1149
		// Harden SSL a bit for PCI conformance testing
1150
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
1151
		$lighty_config .= "ssl.cipher-list = \"TLSv1+HIGH !SSLv2 RC4+MEDIUM !aNULL !eNULL !3DES @STRENGTH\"\n";
1152

    
1153
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1154
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1155
	}
1156

    
1157
	// Add HTTP to HTTPS redirect	
1158
	if ($captive_portal == false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1159
		if($lighty_port != "443") 
1160
			$redirectport = ":{$lighty_port}";
1161
		$lighty_config .= <<<EOD
1162
\$SERVER["socket"] == ":80" {
1163
	\$HTTP["host"] =~ "(.*)" {
1164
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1165
	}
1166
}
1167
EOD;
1168
	}
1169

    
1170
	$fd = fopen("{$filename}", "w");
1171
	if (!$fd) {
1172
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1173
		return 1;
1174
	}
1175
	fwrite($fd, $lighty_config);
1176
	fclose($fd);
1177

    
1178
	return 0;
1179

    
1180
}
1181

    
1182
function system_timezone_configure() {
1183
	global $config, $g;
1184
	if(isset($config['system']['developerspew'])) {
1185
		$mt = microtime();
1186
		echo "system_timezone_configure() being called $mt\n";
1187
	}
1188

    
1189
	$syscfg = $config['system'];
1190

    
1191
	if ($g['booting'])
1192
		echo gettext("Setting timezone...");
1193

    
1194
	/* extract appropriate timezone file */
1195
	$timezone = $syscfg['timezone'];
1196
	if (!$timezone)
1197
		$timezone = "Etc/UTC";
1198

    
1199
	conf_mount_rw();
1200

    
1201
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1202
		escapeshellarg($timezone) . " > /etc/localtime");
1203

    
1204
	mwexec("sync");
1205
	conf_mount_ro();
1206

    
1207
	if ($g['booting'])
1208
		echo gettext("done.") . "\n";
1209
}
1210

    
1211
function system_ntp_configure() {
1212
	global $config, $g;
1213

    
1214
	if ($g['platform'] == 'jail')
1215
		return;
1216

    
1217
	$ntpcfg = "# \n";
1218
	$ntpcfg .= "# pfSense OpenNTPD configuration file \n";
1219
	$ntpcfg .= "# \n\n";
1220

    
1221
	/* foreach through servers and write out to ntpd.conf */
1222
	foreach (explode(' ', $config['system']['timeservers']) as $ts)
1223
		$ntpcfg .= "servers {$ts}\n";
1224

    
1225
	/* Setup listener(s) if the user has configured one */
1226
        if ($config['installedpackages']['openntpd']) {
1227
    		/* server config is in coregui1 */
1228
		$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
1229
		if ($xmlsettings['enable'] == 'on') {
1230
			$ifaces = explode(',', $xmlsettings['interface']);
1231
			$ips = array();
1232
			foreach ($ifaces as $if) {
1233
				if (is_ipaddr($if)) {
1234
					$ips[] = $if;
1235
				} else {
1236
					$if = get_real_interface($if);
1237
					if (does_interface_exist($if))
1238
						$ips[] = find_interface_ip($if);
1239
				}
1240
			}
1241
			foreach ($ips as $ip) {
1242
				if (is_ipaddr($ip))
1243
					$ntpcfg .= "listen on $ip\n";
1244
			}
1245
		}
1246
	}
1247
	$ntpcfg .= "\n";
1248

    
1249
	/* open configuration for wrting or bail */
1250
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1251
	if(!$fd) {
1252
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1253
		return;
1254
	}
1255
	fwrite($fd, $ntpcfg);
1256

    
1257
	/* slurp! */
1258
	fclose($fd);
1259

    
1260
	/* if openntpd is running, kill it */
1261
	while(is_process_running("ntpd")) {
1262
		killbyname("ntpd");
1263
	}
1264

    
1265
	/* if /var/empty does not exist, create it */
1266
	if(!is_dir("/var/empty"))
1267
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1268

    
1269
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1270
	exec("/usr/local/sbin/ntpd -s -f {$g['varetc_path']}/ntpd.conf");
1271
	
1272
	// Note that we are starting up
1273
	log_error("OpenNTPD is starting up.");
1274

    
1275
}
1276

    
1277
function sync_system_time() {
1278
	global $config, $g;
1279

    
1280
	if ($g['booting'])
1281
		echo gettext("Syncing system time before startup...");
1282

    
1283
	/* foreach through servers and write out to ntpd.conf */
1284
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1285
		mwexec("/usr/sbin/ntpdate -s $ts");
1286
	}
1287
	
1288
	if ($g['booting'])
1289
		echo gettext("done.") . "\n";
1290
	
1291
}
1292

    
1293
function system_halt() {
1294
	global $g;
1295

    
1296
	system_reboot_cleanup();
1297

    
1298
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1299
}
1300

    
1301
function system_reboot() {
1302
	global $g;
1303

    
1304
	system_reboot_cleanup();
1305

    
1306
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1307
}
1308

    
1309
function system_reboot_sync() {
1310
	global $g;
1311

    
1312
	system_reboot_cleanup();
1313

    
1314
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1315
}
1316

    
1317
function system_reboot_cleanup() {
1318
	mwexec("/usr/local/bin/beep.sh stop");
1319
	require_once("captiveportal.inc");
1320
	captiveportal_radius_stop_all();
1321
	require_once("voucher.inc");
1322
	voucher_save_db_to_config();
1323
	mwexec("/etc/rc.stop_packages");
1324
}
1325

    
1326
function system_do_shell_commands($early = 0) {
1327
	global $config, $g;
1328
	if(isset($config['system']['developerspew'])) {
1329
		$mt = microtime();
1330
		echo "system_do_shell_commands() being called $mt\n";
1331
	}
1332

    
1333
	if ($early)
1334
		$cmdn = "earlyshellcmd";
1335
	else
1336
		$cmdn = "shellcmd";
1337

    
1338
	if (is_array($config['system'][$cmdn])) {
1339

    
1340
		/* *cmd is an array, loop through */
1341
		foreach ($config['system'][$cmdn] as $cmd) {
1342
			exec($cmd);
1343
		}
1344

    
1345
	} elseif($config['system'][$cmdn] <> "") {
1346

    
1347
		/* execute single item */
1348
		exec($config['system'][$cmdn]);
1349

    
1350
	}
1351
}
1352

    
1353
function system_console_configure() {
1354
	global $config, $g;
1355
	if(isset($config['system']['developerspew'])) {
1356
		$mt = microtime();
1357
		echo "system_console_configure() being called $mt\n";
1358
	}
1359

    
1360
	if (isset($config['system']['disableconsolemenu'])) {
1361
		touch("{$g['varetc_path']}/disableconsole");
1362
	} else {
1363
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1364
	}
1365
}
1366

    
1367
function system_dmesg_save() {
1368
	global $g;
1369
	if(isset($config['system']['developerspew'])) {
1370
		$mt = microtime();
1371
		echo "system_dmesg_save() being called $mt\n";
1372
	}
1373

    
1374
	$dmesg = "";
1375
	exec("/sbin/dmesg", $dmesg);
1376

    
1377
	/* find last copyright line (output from previous boots may be present) */
1378
	$lastcpline = 0;
1379

    
1380
	for ($i = 0; $i < count($dmesg); $i++) {
1381
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1382
			$lastcpline = $i;
1383
	}
1384

    
1385
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1386
	if (!$fd) {
1387
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1388
		return 1;
1389
	}
1390

    
1391
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1392
		fwrite($fd, $dmesg[$i] . "\n");
1393

    
1394
	fclose($fd);
1395

    
1396
	return 0;
1397
}
1398

    
1399
function system_set_harddisk_standby() {
1400
	global $g, $config;
1401
	if(isset($config['system']['developerspew'])) {
1402
		$mt = microtime();
1403
		echo "system_set_harddisk_standby() being called $mt\n";
1404
	}
1405

    
1406
	if (isset($config['system']['harddiskstandby'])) {
1407
		if ($g['booting']) {
1408
			echo gettext('Setting hard disk standby... ');
1409
		}
1410

    
1411
		$standby = $config['system']['harddiskstandby'];
1412
		// Check for a numeric value
1413
		if (is_numeric($standby)) {
1414
			// Sync the disk(s)
1415
			pfSense_sync();
1416
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1417
				// Reinitialize ATA-drives
1418
				mwexec('/usr/local/sbin/atareinit');
1419
				if ($g['booting']) {
1420
					echo gettext("done.") . "\n";
1421
				}
1422
			} else if ($g['booting']) {
1423
				echo gettext("failed!") . "\n";
1424
			}
1425
		} else if ($g['booting']) {
1426
			echo gettext("failed!") . "\n";
1427
		}
1428
	}
1429
}
1430

    
1431
function system_setup_sysctl() {
1432
	global $config;
1433
	if(isset($config['system']['developerspew'])) {
1434
		$mt = microtime();
1435
		echo "system_setup_sysctl() being called $mt\n";
1436
	}
1437

    
1438
	activate_sysctls();	
1439

    
1440
	if (isset($config['system']['sharednet'])) {
1441
		system_disable_arp_wrong_if();
1442
	}
1443
}
1444

    
1445
function system_disable_arp_wrong_if() {
1446
	global $config;
1447
	if(isset($config['system']['developerspew'])) {
1448
		$mt = microtime();
1449
		echo "system_disable_arp_wrong_if() being called $mt\n";
1450
	}
1451
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1452
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1453
}
1454

    
1455
function system_enable_arp_wrong_if() {
1456
	global $config;
1457
	if(isset($config['system']['developerspew'])) {
1458
		$mt = microtime();
1459
		echo "system_enable_arp_wrong_if() being called $mt\n";
1460
	}
1461
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1462
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1463
}
1464

    
1465
function enable_watchdog() {
1466
	global $config;
1467
	return;
1468
	$install_watchdog = false;
1469
	$supported_watchdogs = array("Geode");
1470
	$file = file_get_contents("/var/log/dmesg.boot");
1471
	foreach($supported_watchdogs as $sd) {
1472
		if(stristr($file, "Geode")) {
1473
			$install_watchdog = true;
1474
		}
1475
	}
1476
	if($install_watchdog == true) {
1477
		if(is_process_running("watchdogd"))
1478
			mwexec("/usr/bin/killall watchdogd", true);
1479
		exec("/usr/sbin/watchdogd");
1480
	}
1481
}
1482

    
1483
function system_check_reset_button() {
1484
	global $g;
1485
	if($g['platform'] != "nanobsd")
1486
		return 0;
1487

    
1488
	$specplatform = system_identify_specific_platform();
1489

    
1490
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1491
		return 0;
1492

    
1493
	$retval = mwexec("/usr/local/sbin/" . $specplatform['name'] . "resetbtn");
1494

    
1495
	if ($retval == 99) {
1496
		/* user has pressed reset button for 2 seconds - 
1497
		   reset to factory defaults */
1498
		echo <<<EOD
1499

    
1500
***********************************************************************
1501
* Reset button pressed - resetting configuration to factory defaults. *
1502
* The system will reboot after this completes.                        *
1503
***********************************************************************
1504

    
1505

    
1506
EOD;
1507
		
1508
		reset_factory_defaults();
1509
		system_reboot_sync();
1510
		exit(0);
1511
	}
1512

    
1513
	return 0;
1514
}
1515

    
1516
/* attempt to identify the specific platform (for embedded systems)
1517
   Returns an array with two elements:
1518
	name => platform string (e.g. 'wrap', 'alix' etc.)
1519
	descr => human-readable description (e.g. "PC Engines WRAP")
1520
*/
1521
function system_identify_specific_platform() {
1522
	global $g;
1523
	
1524
	if ($g['platform'] == 'generic-pc')
1525
		return array('name' => 'generic-pc', 'descr' => gettext("Generic PC"));
1526
	
1527
	if ($g['platform'] == 'generic-pc-cdrom')
1528
		return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)"));
1529
	
1530
	/* the rest of the code only deals with 'embedded' platforms */
1531
	if ($g['platform'] != 'nanobsd')
1532
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1533
	
1534
	$dmesg = system_get_dmesg_boot();
1535
	
1536
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1537
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
1538
	
1539
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1540
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
1541

    
1542
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1543
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1544
	
1545
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1546
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1547
		
1548
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1549
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1550
	
1551
	/* unknown embedded platform */
1552
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
1553
}
1554

    
1555
function system_get_dmesg_boot() {
1556
	global $g;
1557
		
1558
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1559
}
1560

    
1561
function get_possible_listen_ips() {
1562
	$interfaces = get_configured_interface_with_descr();
1563
	$carplist = get_configured_carp_interface_list();
1564
	$listenips = array();
1565
	foreach ($carplist as $cif => $carpip)
1566
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1567
	$aliaslist = get_configured_ip_aliases_list();
1568
	foreach ($aliaslist as $aliasip => $aliasif)
1569
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1570
	foreach ($interfaces as $iface => $ifacename) {
1571
		$tmp["name"]  = $ifacename;
1572
		$tmp["value"] = $iface;
1573
		$listenips[] = $tmp;
1574
	}
1575
	$tmp["name"]  = "Localhost";
1576
	$tmp["value"] = "lo0";
1577
	$listenips[] = $tmp;
1578
	return $listenips;
1579
}
1580

    
1581
?>
(49-49/64)