Project

General

Profile

Download (47.9 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
	}
267

    
268
	if (isset($dnsmasqcfg['dhcpfirst']))
269
		$hosts .= $dhosts . $lhosts;
270
	else
271
		$hosts .= $lhosts . $dhosts;
272

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

    
289
	system_dhcpleases_configure();
290

    
291
	return 0;
292
}
293

    
294
function system_dhcpleases_configure() {
295
	global $config, $g;
296
	
297
	if ($g['platform'] == 'jail')
298
		return;
299
	/* Start the monitoring process for dynamic dhcpclients. */
300
	if (isset($config['dnsmasq']['regdhcp'])) {
301
		/* Make sure we do not error out */
302
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
303
		if (file_exists("{$g['varrun_path']}/dhcpleases.pid"))
304
				sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "HUP");
305
		else
306
			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");
307
	} else {
308
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
309
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
310
	}
311
}
312

    
313
function system_hostname_configure() {
314
	global $config, $g;
315
	if(isset($config['system']['developerspew'])) {
316
		$mt = microtime();
317
		echo "system_hostname_configure() being called $mt\n";
318
	}
319

    
320
	$syscfg = $config['system'];
321

    
322
	/* set hostname */
323
	$status = mwexec("/bin/hostname " .
324
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
325

    
326
    /* Setup host GUID ID.  This is used by ZFS. */
327
	mwexec("/etc/rc.d/hostid start");
328

    
329
	return $status;
330
}
331

    
332
function system_routing_configure($interface = "") {
333
	global $config, $g;
334
	if ($g['platform'] == 'jail')
335
		return;
336
	if(isset($config['system']['developerspew'])) {
337
		$mt = microtime();
338
		echo "system_routing_configure() being called $mt\n";
339
	}
340

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

    
406
	if ($dont_add_route == false ) {
407
		if (!empty($interface) && $interface != $interfacegw)
408
			;
409
		else if (($interfacegw <> "bgpd") && (is_ipaddrv4($gatewayip))) {
410
			log_error("ROUTING: setting default route to $gatewayip");
411
			mwexec("/sbin/route change -inet default " . escapeshellarg($gatewayip));
412
		}
413

    
414
		if (!empty($interface) && $interface != $interfacegwv6)
415
			;
416
		else if (($interfacegwv6 <> "bgpd") && (is_ipaddrv6($gatewayipv6))) {
417
			if(preg_match("/fe80::/i", $gatewayipv6))
418
				$ifscope = "%{$defaultifv6}";
419
			log_error("ROUTING: setting IPv6 default route to {$gatewayipv6}{$ifscope}");
420
			mwexec("/sbin/route change -inet6 default " . escapeshellarg($gatewayipv6) ."{$ifscope}");
421
		}
422
	}
423

    
424
	if (is_array($config['staticroutes']['route'])) {
425
		$gateways_arr = return_gateways_array();
426

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

    
437
			$gatewayip = $gateway['gateway'];
438
			$interfacegw = $gateway['interface'];
439

    
440
			if(is_ipaddrv6($gatewayip)) {
441
				$inetfamily = "-inet6";
442
			} else {
443
				$inetfamily = "-inet";
444
			}
445
			if (is_ipaddr($gatewayip)) {
446
				mwexec("/sbin/route change {$inetfamily} " . escapeshellarg($rtent['network']) .
447
					" " . escapeshellarg($gatewayip));
448
			} else if (!empty($interfacegw)) {
449
				mwexec("/sbin/route change {$inetfamily} " . escapeshellarg($rtent['network']) .
450
					" -iface " . escapeshellarg($interfacegw));
451
			}
452
		}
453
	}
454

    
455
	return 0;
456
}
457

    
458
function system_routing_enable() {
459
	global $config, $g;
460
	if(isset($config['system']['developerspew'])) {
461
		$mt = microtime();
462
		echo "system_routing_enable() being called $mt\n";
463
	}
464

    
465
	mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
466
	mwexec("/sbin/sysctl net.inet6.ip6.forwarding=1");
467
	return;
468
}
469

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

    
477
	mwexec("/etc/rc.d/hostid start");
478

    
479
	$syslogcfg = $config['syslog'];
480

    
481
	if ($g['booting'])
482
		echo gettext("Starting syslog...");
483
	else
484
		killbypid("{$g['varrun_path']}/syslog.pid");
485

    
486
	if(is_process_running("syslogd"))
487
		pkill("syslogd");
488
	if(is_process_running("fifolog_writer"))
489
		pkill("fifolog_writer");
490
	
491
	// Define carious commands for logging
492
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
493
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
494
	$clog_create = "/usr/sbin/clog -i -s ";
495
	$clog_log = "%";
496

    
497
	// Which logging type are we using this week??
498
	if(isset($config['system']['usefifolog'])) {
499
		$log_directive = $fifolog_log;
500
		$log_create_directive = $fifolog_create;		
501
	} else { // Defaults to CLOG
502
		$log_directive = $clog_log;
503
		$log_create_directive = $clog_create;
504
	}
505
	
506
	if (isset($syslogcfg)) {
507
		$separatelogfacilities = array('ntpd','racoon','openvpn','pptps','poes','l2tps','relayd','hostapd');
508
		if($config['installedpackages']['package']) {
509
			foreach($config['installedpackages']['package'] as $package) {
510
				if($package['logging']) {
511
					array_push($separatelogfacilities, $package['logging']['facilityname']);
512
					mwexec("{$log_create_directive} 10240 {$g['varlog_path']}/{$package['logging']['logfilename']}");
513
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
514
				}
515
			}
516
		}
517
		$facilitylist = implode(',', array_unique($separatelogfacilities));
518
		/* write syslog.conf */		
519
		$fd = fopen("{$g['varetc_path']}/syslog.conf", "w");
520
		if (!$fd) {
521
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
522
			return 1;
523
		}
524
		$syslogconf .= "!ntpdate,!ntpd\n";
525
		if (!isset($syslogcfg['disablelocallogging'])) 
526
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/ntpd.log\n";
527
		$syslogconf .= "!ppp\n";
528
		if (!isset($syslogcfg['disablelocallogging'])) 
529
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/ppp.log\n";
530
		$syslogconf .= "!pptps\n";
531
		if (!isset($syslogcfg['disablelocallogging'])) 
532
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/pptps.log\n";
533
		$syslogconf .= "!poes\n";
534
		if (!isset($syslogcfg['disablelocallogging'])) 
535
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/poes.log\n";
536
		$syslogconf .= "!l2tps\n";
537
		if (!isset($syslogcfg['disablelocallogging'])) 
538
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/l2tps.log\n";
539
		$syslogconf .= "!racoon\n";
540
		if (!isset($syslogcfg['disablelocallogging'])) 
541
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/ipsec.log\n";
542
		if (isset($syslogcfg['vpn'])) {
543
			if($syslogcfg['remoteserver'])
544
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver']}\n";
545
			if($syslogcfg['remoteserver2'])
546
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver2']}\n";
547
			if($syslogcfg['remoteserver3'])
548
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver3']}\n";
549
		}
550
		$syslogconf .= "!openvpn\n";
551
		if (!isset($syslogcfg['disablelocallogging'])) 
552
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/openvpn.log\n";
553
		if (isset($syslogcfg['vpn'])) {
554
			if($syslogcfg['remoteserver'])
555
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver']}\n";
556
			if($syslogcfg['remoteserver2'])
557
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver3']}\n";
558
			if($syslogcfg['remoteserver3'])
559
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver3']}\n";
560
		}
561
		$syslogconf .= "!apinger\n";
562
		if (!isset($syslogcfg['disablelocallogging']))
563
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/apinger.log\n";
564
		$syslogconf .= "!relayd\n";
565
		$syslogconf .= "*.* 						{$log_directive}{$g['varlog_path']}/relayd.log\n";
566
		$syslogconf .= "!hostapd\n";
567
		$syslogconf .= "*.* 						{$log_directive}{$g['varlog_path']}/wireless.log\n";
568
		$syslogconf .= "!-{$facilitylist}\n";
569
		if (!isset($syslogcfg['disablelocallogging'])) 
570
			$syslogconf .= <<<EOD
571
local0.*										 {$log_directive}{$g['varlog_path']}/filter.log
572
local3.*										 {$log_directive}{$g['varlog_path']}/vpn.log
573
local4.*										 {$log_directive}{$g['varlog_path']}/portalauth.log
574
local7.*										 {$log_directive}{$g['varlog_path']}/dhcpd.log
575
*.notice;kern.debug;lpr.info;mail.crit; 		 {$log_directive}{$g['varlog_path']}/system.log
576
news.err;local0.none;local3.none;local4.none; 	 {$log_directive}{$g['varlog_path']}/system.log
577
local7.none										 {$log_directive}{$g['varlog_path']}/system.log
578
security.*										 {$log_directive}{$g['varlog_path']}/system.log
579
auth.info;authpriv.info;daemon.info				 {$log_directive}{$g['varlog_path']}/system.log
580
auth.info;authpriv.info 						 |exec /usr/local/sbin/sshlockout_pf 15
581
*.emerg											 *
582

    
583
EOD;
584
		if (isset($syslogcfg['filter'])) {
585
			if($syslogcfg['remoteserver'])
586
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver']}\n";
587
			if($syslogcfg['remoteserver2'])
588
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver2']}\n";
589
			if($syslogcfg['remoteserver3'])
590
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver3']}\n";
591

    
592
		}
593
		if (isset($syslogcfg['vpn'])) {
594
			if($syslogcfg['remoteserver'])
595
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver']}\n";
596
			if($syslogcfg['remoteserver2'])
597
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver2']}\n";
598
			if($syslogcfg['remoteserver3'])
599
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver3']}\n";
600
		}
601
		if (isset($syslogcfg['portalauth'])) {
602
			if($syslogcfg['remoteserver'])
603
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver']}\n";
604
			if($syslogcfg['remoteserver2'])
605
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver2']}\n";
606
			if($syslogcfg['remoteserver3'])
607
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver3']}\n";
608
		}
609
		if (isset($syslogcfg['dhcp'])) {
610
			if($syslogcfg['remoteserver'])
611
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver']}\n";
612
			if($syslogcfg['remoteserver2'])
613
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver2']}\n";
614
			if($syslogcfg['remoteserver3'])
615
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver3']}\n";
616
		}
617
		if (isset($syslogcfg['system'])) {
618
			if($syslogcfg['remoteserver'])
619
				$syslogconf .= <<<EOD
620
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver']}
621
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver']}
622
security.*										 @{$syslogcfg['remoteserver']}
623
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver']}
624
*.emerg											 @{$syslogcfg['remoteserver']}
625

    
626
EOD;
627

    
628
}
629

    
630
		if (isset($syslogcfg['system'])) {
631
			if($syslogcfg['remoteserver2'])
632
				$syslogconf .= <<<EOD
633
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver2']}
634
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver2']}
635
security.*										 @{$syslogcfg['remoteserver2']}
636
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver2']}
637
*.emerg											 @{$syslogcfg['remoteserver2']}
638

    
639
EOD;
640

    
641
}
642

    
643
		if (isset($syslogcfg['system'])) {
644
			if($syslogcfg['remoteserver3'])
645
				$syslogconf .= <<<EOD
646
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver3']}
647
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver3']}
648
security.*										 @{$syslogcfg['remoteserver3']}
649
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver3']}
650
*.emerg											 @{$syslogcfg['remoteserver3']}
651

    
652
EOD;
653

    
654
}
655
		if (isset($syslogcfg['logall'])) {
656
			if($syslogcfg['remoteserver'])
657
				$syslogconf .= <<<EOD
658
*.*								@{$syslogcfg['remoteserver']}
659

    
660
EOD;
661

    
662
			if($syslogcfg['remoteserver2'])
663
				$syslogconf .= <<<EOD
664
*.*								@{$syslogcfg['remoteserver2']}
665

    
666
EOD;
667

    
668
			if($syslogcfg['remoteserver3'])
669
				$syslogconf .= <<<EOD
670
*.*								@{$syslogcfg['remoteserver3']}
671

    
672
EOD;
673

    
674
}
675
		if (isset($syslogcfg['zmqserver'])) {
676
				$syslogconf .= <<<EOD
677
*.*								^{$syslogcfg['zmqserver']}
678

    
679
EOD;
680
		}
681
		fwrite($fd, $syslogconf);
682
		fclose($fd);
683

    
684
		// Ensure that the log directory exists
685
		if(!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
686
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
687

    
688
		// Are we logging to a least one remote server ?
689
		if(strpos($syslogconf, "@") != false)
690
			$retval = mwexec_bg("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log -f {$g['varetc_path']}/syslog.conf");
691
		else {
692
			$retval = mwexec_bg("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log -f {$g['varetc_path']}/syslog.conf");
693
		}
694

    
695
	} else {
696
		$retval = mwexec_bg("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log");
697
	}
698

    
699
	if ($g['booting'])
700
		echo gettext("done.") . "\n";
701

    
702
	return $retval;
703
}
704

    
705
function system_pccard_start() {
706
	global $config, $g;
707
	if(isset($config['system']['developerspew'])) {
708
		$mt = microtime();
709
		echo "system_pccard_start() being called $mt\n";
710
	}
711

    
712
	if ($g['booting'])
713
		echo gettext("Initializing PCMCIA...");
714

    
715
	/* kill any running pccardd */
716
	killbypid("{$g['varrun_path']}/pccardd.pid");
717

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

    
721
	if ($g['booting']) {
722
		if ($res == 0)
723
			echo gettext("done.") . "\n";
724
		else
725
			echo gettext("failed!") . "\n";
726
	}
727

    
728
	return $res;
729
}
730

    
731

    
732
function system_webgui_start() {
733
	global $config, $g;
734

    
735
	if ($g['booting'])
736
		echo gettext("Starting webConfigurator...");
737

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

    
741
	sleep(1);
742

    
743
	chdir($g['www_path']);
744

    
745
	/* defaults */
746
	$portarg = "80";
747
	$crt = "";
748
	$key = "";
749
	$ca = "";
750

    
751
	/* non-standard port? */
752
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
753
		$portarg = "{$config['system']['webgui']['port']}";
754

    
755
	if ($config['system']['webgui']['protocol'] == "https") {
756
		// Ensure that we have a webConfigurator CERT
757
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
758
		if(!is_array($cert) && !$cert['crt'] && !$cert['prv']) {
759
			if (!is_array($config['ca']))
760
				$config['ca'] = array();
761
			$a_ca =& $config['ca'];
762
			if (!is_array($config['cert']))
763
				$config['cert'] = array();
764
			$a_cert =& $config['cert'];
765
			log_error("Creating SSL Certificate for this host");
766
			$cert = array();
767
			$cert['refid'] = uniqid();
768
			$cert['descr'] = gettext("webConfigurator default");
769
			mwexec("/usr/bin/openssl genrsa 1024 > {$g['tmp_path']}/ssl.key");
770
			mwexec("/usr/bin/openssl req -new -x509 -nodes -sha1 -days 2000 -key {$g['tmp_path']}/ssl.key > {$g['tmp_path']}/ssl.crt");
771
			$crt = file_get_contents("{$g['tmp_path']}/ssl.crt");
772
			$key = file_get_contents("{$g['tmp_path']}/ssl.key");
773
			unlink("{$g['tmp_path']}/ssl.key");
774
			unlink("{$g['tmp_path']}/ssl.crt");
775
			cert_import($cert, $crt, $key);
776
			$a_cert[] = $cert;
777
			$config['system']['webgui']['ssl-certref'] = $cert['refid'];
778
			write_config(gettext("Importing HTTPS certificate"));
779
			if(!$config['system']['webgui']['port'])
780
				$portarg = "443";
781
			$ca = ca_chain($cert);
782
		} else {
783
			$crt = base64_decode($cert['crt']);
784
			$key = base64_decode($cert['prv']);
785
			if(!$config['system']['webgui']['port'])
786
				$portarg = "443";
787
			$ca = ca_chain($cert);
788
		}
789
	}
790

    
791
	/* generate lighttpd configuration */
792
	$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
793
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
794
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
795
		"cert.pem", "ca.pem", $max_procs);
796

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

    
800
	/* fetch page to preload apc cache */
801
	$proto = "http";
802
	if ($config['system']['webgui']['protocol'])
803
		$proto = $config['system']['webgui']['protocol'];
804
	mwexec_bg("/usr/bin/fetch -o /dev/null -q {$proto}://localhost:{$portarg}/preload.php");
805

    
806
	if ($g['booting']) {
807
		if ($res == 0)
808
			echo gettext("done.") . "\n";
809
		else
810
			echo gettext("failed!") . "\n";
811
	}
812

    
813
	return $res;
814
}
815

    
816
function system_generate_lighty_config($filename,
817
	$cert,
818
	$key,
819
	$ca,
820
	$pid_file,
821
	$port = 80,
822
	$document_root = "/usr/local/www/",
823
	$cert_location = "cert.pem",
824
	$ca_location = "ca.pem",
825
	$max_procs = 1,
826
	$max_requests = "2",
827
	$fast_cgi_enable = true,
828
	$captive_portal = false) {
829

    
830
	global $config, $g;
831

    
832
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
833
		mkdir("{$g['tmp_path']}/lighttpdcompress");
834

    
835
	if(isset($config['system']['developerspew'])) {
836
		$mt = microtime();
837
		echo "system_generate_lighty_config() being called $mt\n";
838
	}
839

    
840
	if($captive_portal != false)  {
841
		$captiveportal = ",\"mod_rewrite\"";
842
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?zone={$captive_portal}&redirurl=$1\" )\n";
843
		$captive_portal_module = "";
844
		$maxprocperip = $config['captiveportal']['maxprocperip'];
845
		if($maxprocperip and $maxprocperip > 0)
846
			$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
847
		else
848
			$captive_portal_mod_evasive = "";
849
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
850
		exec("mkdir -p {$g['tmp_path']}/captiveportal");
851
		exec("chmod a-w {$g['tmp_path']}/captiveportal");
852
		$server_max_request_size = "server.max-request-size    = 384";
853
	} else {
854
		$captiveportal = "";
855
		$captive_portal_rewrite = "";
856
		$captive_portal_module = "";
857
		$captive_portal_mod_evasive = "";
858
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
859
		$server_max_request_size = "server.max-request-size    = 2097152";
860
	}
861
	
862
	if($port <> "")
863
		$lighty_port = $port;
864
	else
865
		$lighty_port = "80";
866

    
867
	$memory = get_memory();
868
	$avail = $memory[0];
869

    
870
	if($avail > 0 and $avail < 65) {
871
		$fast_cgi_enable = false;
872
	}
873

    
874
	// Ramp up captive portal max procs
875
	//  Work relative to the default of 2, for values that would be >2.
876
	if($captive_portal == true)  {
877
		if($avail > 65 and $avail < 98) {
878
			$max_procs = 1;
879
		}
880
		if($avail > 97 and $avail < 128) {
881
			$max_procs = 2;
882
		}
883
		if($avail > 127 and $avail < 256) {
884
			$max_procs += 1;
885
		}
886
		if($avail > 255 and $avail < 384) {
887
			$max_procs += 2;
888
		}
889
		if($avail > 383) {
890
			$max_procs += 3;
891
		}
892
	}
893

    
894
	if($captive_portal == true)  {	
895
		$bin_environment =  <<<EOC
896
			"bin-environment" => (
897
				"PHP_FCGI_CHILDREN" => "$max_procs",
898
				"PHP_FCGI_MAX_REQUESTS" => "500"
899
			),
900
EOC;
901

    
902
	} else if ($avail > 0 and $avail < 128) {
903
		$bin_environment = <<<EOC
904
			"bin-environment" => (
905
				"PHP_FCGI_CHILDREN" => "$max_procs",
906
				"PHP_FCGI_MAX_REQUESTS" => "2",
907
			),
908

    
909
EOC;
910
	} else
911
		$bin_environment =  <<<EOC
912
			"bin-environment" => (
913
				"PHP_FCGI_CHILDREN" => "$max_procs",
914
				"PHP_FCGI_MAX_REQUESTS" => "500"
915
			),
916
EOC;
917

    
918
	if($fast_cgi_enable == true) {
919
		$module = "\"mod_fastcgi\", \"mod_cgi\"";
920
		if ($captive_portal != false)
921
			$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi-{$captive_portal}.socket";
922
		else
923
			$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi.socket";
924
		$cgi_config = "";
925
		$fastcgi_config = <<<EOD
926
#### fastcgi module
927
## read fastcgi.txt for more info
928
fastcgi.server = ( ".php" =>
929
	( "localhost" =>
930
		(
931
			"socket" => "{$fast_cgi_path}",
932
			"min-procs" => 0,
933
			"max-procs" => {$max_procs},
934
{$bin_environment}
935
			"bin-path" => "/usr/local/bin/php"
936
		)
937
	)
938
)
939

    
940
#### CGI module
941
cgi.assign                 = ( ".cgi" => "" )
942

    
943
EOD;
944
	} else {
945
		$fastcgi_config = "";
946
		$module = "\"mod_cgi\"";
947
		$cgi_config = <<<EOD
948
#### CGI module
949
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
950
                               ".cgi" => "" )
951

    
952
EOD;
953
	}
954

    
955
	$lighty_config = "";
956
	$lighty_config .= <<<EOD
957
#
958
# lighttpd configuration file
959
#
960
# use a it as base for lighttpd 1.0.0 and above
961
#
962
############ Options you really have to take care of ####################
963

    
964
## FreeBSD!
965
server.event-handler	= "freebsd-kqueue"
966
server.network-backend 	= "writev"
967
#server.use-ipv6 = "enable"
968

    
969
## modules to load
970
server.modules              =   (
971
	{$captive_portal_module}
972
	"mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect",
973
	{$module}{$captiveportal}
974
)
975

    
976
## Unused modules
977
#                               "mod_setenv",
978
#                               "mod_rewrite",
979
#                               "mod_ssi",
980
#                               "mod_usertrack",
981
#                               "mod_expire",
982
#                               "mod_secdownload",
983
#                               "mod_rrdtool",
984
#                               "mod_auth",
985
#                               "mod_status",
986
#                               "mod_alias",
987
#                               "mod_proxy",
988
#                               "mod_simple_vhost",
989
#                               "mod_evhost",
990
#                               "mod_userdir",
991
#                               "mod_cgi",
992

    
993
server.max-keep-alive-requests = 15
994
server.max-keep-alive-idle = 30
995

    
996
## a static document-root, for virtual-hosting take look at the
997
## server.virtual-* options
998
server.document-root        = "{$document_root}"
999
{$captive_portal_rewrite}
1000

    
1001
# Maximum idle time with nothing being written (php downloading)
1002
server.max-write-idle = 999
1003

    
1004
## where to send error-messages to
1005
server.errorlog             = "/var/log/lighttpd.error.log"
1006

    
1007
# files to check for if .../ is requested
1008
server.indexfiles           = ( "index.php", "index.html",
1009
                                "index.htm", "default.htm" )
1010

    
1011
# mimetype mapping
1012
mimetype.assign             = (
1013
  ".pdf"          =>      "application/pdf",
1014
  ".sig"          =>      "application/pgp-signature",
1015
  ".spl"          =>      "application/futuresplash",
1016
  ".class"        =>      "application/octet-stream",
1017
  ".ps"           =>      "application/postscript",
1018
  ".torrent"      =>      "application/x-bittorrent",
1019
  ".dvi"          =>      "application/x-dvi",
1020
  ".gz"           =>      "application/x-gzip",
1021
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
1022
  ".swf"          =>      "application/x-shockwave-flash",
1023
  ".tar.gz"       =>      "application/x-tgz",
1024
  ".tgz"          =>      "application/x-tgz",
1025
  ".tar"          =>      "application/x-tar",
1026
  ".zip"          =>      "application/zip",
1027
  ".mp3"          =>      "audio/mpeg",
1028
  ".m3u"          =>      "audio/x-mpegurl",
1029
  ".wma"          =>      "audio/x-ms-wma",
1030
  ".wax"          =>      "audio/x-ms-wax",
1031
  ".ogg"          =>      "audio/x-wav",
1032
  ".wav"          =>      "audio/x-wav",
1033
  ".gif"          =>      "image/gif",
1034
  ".jpg"          =>      "image/jpeg",
1035
  ".jpeg"         =>      "image/jpeg",
1036
  ".png"          =>      "image/png",
1037
  ".xbm"          =>      "image/x-xbitmap",
1038
  ".xpm"          =>      "image/x-xpixmap",
1039
  ".xwd"          =>      "image/x-xwindowdump",
1040
  ".css"          =>      "text/css",
1041
  ".html"         =>      "text/html",
1042
  ".htm"          =>      "text/html",
1043
  ".js"           =>      "text/javascript",
1044
  ".asc"          =>      "text/plain",
1045
  ".c"            =>      "text/plain",
1046
  ".conf"         =>      "text/plain",
1047
  ".text"         =>      "text/plain",
1048
  ".txt"          =>      "text/plain",
1049
  ".dtd"          =>      "text/xml",
1050
  ".xml"          =>      "text/xml",
1051
  ".mpeg"         =>      "video/mpeg",
1052
  ".mpg"          =>      "video/mpeg",
1053
  ".mov"          =>      "video/quicktime",
1054
  ".qt"           =>      "video/quicktime",
1055
  ".avi"          =>      "video/x-msvideo",
1056
  ".asf"          =>      "video/x-ms-asf",
1057
  ".asx"          =>      "video/x-ms-asf",
1058
  ".wmv"          =>      "video/x-ms-wmv",
1059
  ".bz2"          =>      "application/x-bzip",
1060
  ".tbz"          =>      "application/x-bzip-compressed-tar",
1061
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
1062
 )
1063

    
1064
# Use the "Content-Type" extended attribute to obtain mime type if possible
1065
#mimetypes.use-xattr        = "enable"
1066

    
1067
#### accesslog module
1068
#accesslog.filename          = "/dev/null"
1069

    
1070
## deny access the file-extensions
1071
#
1072
# ~    is for backupfiles from vi, emacs, joe, ...
1073
# .inc is often used for code includes which should in general not be part
1074
#      of the document-root
1075
url.access-deny             = ( "~", ".inc" )
1076

    
1077

    
1078
######### Options that are good to be but not neccesary to be changed #######
1079

    
1080
## bind to port (default: 80)
1081

    
1082
EOD;
1083

    
1084
	if($captive_portal == true) {
1085
		$lighty_config .= "server.bind	= \"127.0.0.1\"\n";
1086
		$lighty_config .= "server.port  = {$lighty_port}\n";
1087
		$lighty_config .= "\$SERVER[\"socket\"]  == \"127.0.0.1:{$lighty_port}\" { }\n";
1088
		$lighty_config .= "\$SERVER[\"socket\"]  == \"[::1]:{$lighty_port}\" { \n";
1089
		if($cert <> "" and $key <> "") {
1090
			$lighty_config .= "\n";
1091
			$lighty_config .= "## ssl configuration\n";
1092
			$lighty_config .= "ssl.engine = \"enable\"\n";
1093
			$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1094
			if($ca <> "")
1095
				$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1096
		}
1097
		$lighty_config .= " }\n";
1098
	} else {
1099
		$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1100
		$lighty_config .= "server.port  = {$lighty_port}\n";
1101
		$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1102
		$lighty_config .= "\$SERVER[\"socket\"]  == \"[::]:{$lighty_port}\" { \n";
1103
		if($cert <> "" and $key <> "") {
1104
			$lighty_config .= "\n";
1105
			$lighty_config .= "## ssl configuration\n";
1106
			$lighty_config .= "ssl.engine = \"enable\"\n";
1107
			$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1108
			if($ca <> "")
1109
				$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1110
		}
1111
		$lighty_config .= " }\n";
1112
	}
1113

    
1114

    
1115
	$lighty_config .= <<<EOD
1116

    
1117
## error-handler for status 404
1118
#server.error-handler-404   = "/error-handler.html"
1119
#server.error-handler-404   = "/error-handler.php"
1120

    
1121
## to help the rc.scripts
1122
server.pid-file            = "/var/run/{$pid_file}"
1123

    
1124
## virtual directory listings
1125
server.dir-listing         = "disable"
1126

    
1127
## enable debugging
1128
debug.log-request-header   = "disable"
1129
debug.log-response-header  = "disable"
1130
debug.log-request-handling = "disable"
1131
debug.log-file-not-found   = "disable"
1132

    
1133
# gzip compression
1134
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1135
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1136

    
1137
{$server_upload_dirs}
1138

    
1139
{$server_max_request_size}
1140

    
1141
{$fastcgi_config}
1142

    
1143
{$cgi_config}
1144

    
1145
{$captive_portal_mod_evasive}
1146

    
1147
expire.url = (
1148
				"" => "access 50 hours",	
1149
        )
1150

    
1151
EOD;
1152

    
1153
	$cert = str_replace("\r", "", $cert);
1154
	$key = str_replace("\r", "", $key);
1155
	$ca = str_replace("\r", "", $ca);
1156

    
1157
	$cert = str_replace("\n\n", "\n", $cert);
1158
	$key = str_replace("\n\n", "\n", $key);
1159
	$ca = str_replace("\n\n", "\n", $ca);
1160

    
1161
	if($cert <> "" and $key <> "") {
1162
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1163
		if (!$fd) {
1164
			printf(gettext("Error: cannot open cert.pem in system_webgui_start().%s"), "\n");
1165
			return 1;
1166
		}
1167
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1168
		fwrite($fd, $cert);
1169
		fwrite($fd, "\n");
1170
		fwrite($fd, $key);
1171
		fclose($fd);
1172
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
1173
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1174
			if (!$fd) {
1175
				printf(gettext("Error: cannot open ca.pem in system_webgui_start().%s"), "\n");
1176
				return 1;
1177
			}
1178
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1179
			fwrite($fd, $ca);
1180
			fclose($fd);
1181
		}
1182
		$lighty_config .= "\n";
1183
		$lighty_config .= "## " . gettext("ssl configuration") . "\n";
1184
		$lighty_config .= "ssl.engine = \"enable\"\n";
1185
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1186

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

    
1191
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1192
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1193
	}
1194

    
1195
	// Add HTTP to HTTPS redirect	
1196
	if ($captive_portal == false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1197
		if($lighty_port != "443") 
1198
			$redirectport = ":{$lighty_port}";
1199
		$lighty_config .= <<<EOD
1200
\$SERVER["socket"] == ":80" {
1201
	\$HTTP["host"] =~ "(.*)" {
1202
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1203
	}
1204
}
1205
EOD;
1206
	}
1207

    
1208
	$fd = fopen("{$filename}", "w");
1209
	if (!$fd) {
1210
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1211
		return 1;
1212
	}
1213
	fwrite($fd, $lighty_config);
1214
	fclose($fd);
1215

    
1216
	return 0;
1217

    
1218
}
1219

    
1220
function system_timezone_configure() {
1221
	global $config, $g;
1222
	if(isset($config['system']['developerspew'])) {
1223
		$mt = microtime();
1224
		echo "system_timezone_configure() being called $mt\n";
1225
	}
1226

    
1227
	$syscfg = $config['system'];
1228

    
1229
	if ($g['booting'])
1230
		echo gettext("Setting timezone...");
1231

    
1232
	/* extract appropriate timezone file */
1233
	$timezone = $syscfg['timezone'];
1234
	if (!$timezone)
1235
		$timezone = "Etc/UTC";
1236

    
1237
	conf_mount_rw();
1238

    
1239
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1240
		escapeshellarg($timezone) . " > /etc/localtime");
1241

    
1242
	mwexec("sync");
1243
	conf_mount_ro();
1244

    
1245
	if ($g['booting'])
1246
		echo gettext("done.") . "\n";
1247
}
1248

    
1249
function system_ntp_configure() {
1250
	global $config, $g;
1251

    
1252
	if ($g['platform'] == 'jail')
1253
		return;
1254

    
1255
	$ntpcfg = "# \n";
1256
	$ntpcfg .= "# pfSense OpenNTPD configuration file \n";
1257
	$ntpcfg .= "# \n\n";
1258

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

    
1263
	/* Setup listener(s) if the user has configured one */
1264
        if ($config['installedpackages']['openntpd']) {
1265
    		/* server config is in coregui1 */
1266
		$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
1267
		if ($xmlsettings['enable'] == 'on') {
1268
			$ifaces = explode(',', $xmlsettings['interface']);
1269
			$ips = array();
1270
			foreach ($ifaces as $if) {
1271
				if (is_ipaddr($if)) {
1272
					$ips[] = $if;
1273
				} else {
1274
					$if = get_real_interface($if);
1275
					if (does_interface_exist($if))
1276
						$ips[] = find_interface_ip($if);
1277
				}
1278
			}
1279
			foreach ($ips as $ip) {
1280
				if (is_ipaddr($ip))
1281
					$ntpcfg .= "listen on $ip\n";
1282
			}
1283
		}
1284
	}
1285
	$ntpcfg .= "\n";
1286

    
1287
	/* open configuration for wrting or bail */
1288
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1289
	if(!$fd) {
1290
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1291
		return;
1292
	}
1293
	fwrite($fd, $ntpcfg);
1294

    
1295
	/* slurp! */
1296
	fclose($fd);
1297

    
1298
	/* if openntpd is running, kill it */
1299
	while(is_process_running("ntpd")) {
1300
		killbyname("ntpd");
1301
	}
1302

    
1303
	/* if /var/empty does not exist, create it */
1304
	if(!is_dir("/var/empty"))
1305
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1306

    
1307
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1308
	exec("/usr/local/sbin/ntpd -s -f {$g['varetc_path']}/ntpd.conf");
1309
	
1310
	// Note that we are starting up
1311
	log_error("OpenNTPD is starting up.");
1312

    
1313
}
1314

    
1315
function sync_system_time() {
1316
	global $config, $g;
1317

    
1318
	if ($g['booting'])
1319
		echo gettext("Syncing system time before startup...");
1320

    
1321
	/* foreach through servers and write out to ntpd.conf */
1322
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1323
		mwexec("/usr/sbin/ntpdate -s $ts");
1324
	}
1325
	
1326
	if ($g['booting'])
1327
		echo gettext("done.") . "\n";
1328
	
1329
}
1330

    
1331
function system_halt() {
1332
	global $g;
1333

    
1334
	system_reboot_cleanup();
1335

    
1336
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1337
}
1338

    
1339
function system_reboot() {
1340
	global $g;
1341

    
1342
	system_reboot_cleanup();
1343

    
1344
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1345
}
1346

    
1347
function system_reboot_sync() {
1348
	global $g;
1349

    
1350
	system_reboot_cleanup();
1351

    
1352
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1353
}
1354

    
1355
function system_reboot_cleanup() {
1356
	mwexec("/usr/local/bin/beep.sh stop");
1357
	require_once("captiveportal.inc");
1358
	captiveportal_radius_stop_all();
1359
	require_once("voucher.inc");
1360
	voucher_save_db_to_config();
1361
	mwexec("/etc/rc.stop_packages");
1362
}
1363

    
1364
function system_do_shell_commands($early = 0) {
1365
	global $config, $g;
1366
	if(isset($config['system']['developerspew'])) {
1367
		$mt = microtime();
1368
		echo "system_do_shell_commands() being called $mt\n";
1369
	}
1370

    
1371
	if ($early)
1372
		$cmdn = "earlyshellcmd";
1373
	else
1374
		$cmdn = "shellcmd";
1375

    
1376
	if (is_array($config['system'][$cmdn])) {
1377

    
1378
		/* *cmd is an array, loop through */
1379
		foreach ($config['system'][$cmdn] as $cmd) {
1380
			exec($cmd);
1381
		}
1382

    
1383
	} elseif($config['system'][$cmdn] <> "") {
1384

    
1385
		/* execute single item */
1386
		exec($config['system'][$cmdn]);
1387

    
1388
	}
1389
}
1390

    
1391
function system_console_configure() {
1392
	global $config, $g;
1393
	if(isset($config['system']['developerspew'])) {
1394
		$mt = microtime();
1395
		echo "system_console_configure() being called $mt\n";
1396
	}
1397

    
1398
	if (isset($config['system']['disableconsolemenu'])) {
1399
		touch("{$g['varetc_path']}/disableconsole");
1400
	} else {
1401
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1402
	}
1403
}
1404

    
1405
function system_dmesg_save() {
1406
	global $g;
1407
	if(isset($config['system']['developerspew'])) {
1408
		$mt = microtime();
1409
		echo "system_dmesg_save() being called $mt\n";
1410
	}
1411

    
1412
	$dmesg = "";
1413
	exec("/sbin/dmesg", $dmesg);
1414

    
1415
	/* find last copyright line (output from previous boots may be present) */
1416
	$lastcpline = 0;
1417

    
1418
	for ($i = 0; $i < count($dmesg); $i++) {
1419
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1420
			$lastcpline = $i;
1421
	}
1422

    
1423
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1424
	if (!$fd) {
1425
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1426
		return 1;
1427
	}
1428

    
1429
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1430
		fwrite($fd, $dmesg[$i] . "\n");
1431

    
1432
	fclose($fd);
1433

    
1434
	return 0;
1435
}
1436

    
1437
function system_set_harddisk_standby() {
1438
	global $g, $config;
1439
	if(isset($config['system']['developerspew'])) {
1440
		$mt = microtime();
1441
		echo "system_set_harddisk_standby() being called $mt\n";
1442
	}
1443

    
1444
	if (isset($config['system']['harddiskstandby'])) {
1445
		if ($g['booting']) {
1446
			echo gettext('Setting hard disk standby... ');
1447
		}
1448

    
1449
		$standby = $config['system']['harddiskstandby'];
1450
		// Check for a numeric value
1451
		if (is_numeric($standby)) {
1452
			// Sync the disk(s)
1453
			pfSense_sync();
1454
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1455
				// Reinitialize ATA-drives
1456
				mwexec('/usr/local/sbin/atareinit');
1457
				if ($g['booting']) {
1458
					echo gettext("done.") . "\n";
1459
				}
1460
			} else if ($g['booting']) {
1461
				echo gettext("failed!") . "\n";
1462
			}
1463
		} else if ($g['booting']) {
1464
			echo gettext("failed!") . "\n";
1465
		}
1466
	}
1467
}
1468

    
1469
function system_setup_sysctl() {
1470
	global $config;
1471
	if(isset($config['system']['developerspew'])) {
1472
		$mt = microtime();
1473
		echo "system_setup_sysctl() being called $mt\n";
1474
	}
1475

    
1476
	activate_sysctls();	
1477

    
1478
	if (isset($config['system']['sharednet'])) {
1479
		system_disable_arp_wrong_if();
1480
	}
1481
}
1482

    
1483
function system_disable_arp_wrong_if() {
1484
	global $config;
1485
	if(isset($config['system']['developerspew'])) {
1486
		$mt = microtime();
1487
		echo "system_disable_arp_wrong_if() being called $mt\n";
1488
	}
1489
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1490
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1491
}
1492

    
1493
function system_enable_arp_wrong_if() {
1494
	global $config;
1495
	if(isset($config['system']['developerspew'])) {
1496
		$mt = microtime();
1497
		echo "system_enable_arp_wrong_if() being called $mt\n";
1498
	}
1499
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1500
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1501
}
1502

    
1503
function enable_watchdog() {
1504
	global $config;
1505
	return;
1506
	$install_watchdog = false;
1507
	$supported_watchdogs = array("Geode");
1508
	$file = file_get_contents("/var/log/dmesg.boot");
1509
	foreach($supported_watchdogs as $sd) {
1510
		if(stristr($file, "Geode")) {
1511
			$install_watchdog = true;
1512
		}
1513
	}
1514
	if($install_watchdog == true) {
1515
		if(is_process_running("watchdogd"))
1516
			mwexec("/usr/bin/killall watchdogd", true);
1517
		exec("/usr/sbin/watchdogd");
1518
	}
1519
}
1520

    
1521
function system_check_reset_button() {
1522
	global $g;
1523
	if($g['platform'] != "nanobsd")
1524
		return 0;
1525

    
1526
	$specplatform = system_identify_specific_platform();
1527

    
1528
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1529
		return 0;
1530

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

    
1533
	if ($retval == 99) {
1534
		/* user has pressed reset button for 2 seconds - 
1535
		   reset to factory defaults */
1536
		echo <<<EOD
1537

    
1538
***********************************************************************
1539
* Reset button pressed - resetting configuration to factory defaults. *
1540
* The system will reboot after this completes.                        *
1541
***********************************************************************
1542

    
1543

    
1544
EOD;
1545
		
1546
		reset_factory_defaults();
1547
		system_reboot_sync();
1548
		exit(0);
1549
	}
1550

    
1551
	return 0;
1552
}
1553

    
1554
/* attempt to identify the specific platform (for embedded systems)
1555
   Returns an array with two elements:
1556
	name => platform string (e.g. 'wrap', 'alix' etc.)
1557
	descr => human-readable description (e.g. "PC Engines WRAP")
1558
*/
1559
function system_identify_specific_platform() {
1560
	global $g;
1561
	
1562
	if ($g['platform'] == 'generic-pc')
1563
		return array('name' => 'generic-pc', 'descr' => gettext("Generic PC"));
1564
	
1565
	if ($g['platform'] == 'generic-pc-cdrom')
1566
		return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)"));
1567
	
1568
	/* the rest of the code only deals with 'embedded' platforms */
1569
	if ($g['platform'] != 'nanobsd')
1570
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1571
	
1572
	$dmesg = system_get_dmesg_boot();
1573
	
1574
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1575
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
1576
	
1577
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1578
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
1579

    
1580
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1581
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1582
	
1583
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1584
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1585
		
1586
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1587
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1588
	
1589
	/* unknown embedded platform */
1590
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
1591
}
1592

    
1593
function system_get_dmesg_boot() {
1594
	global $g;
1595
		
1596
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1597
}
1598

    
1599
function openntpd_get_listen_ips() {
1600
	$interfaces = get_configured_interface_with_descr();
1601
	$carplist = get_configured_carp_interface_list();
1602
	$listenips = array();
1603
	foreach ($carplist as $cif => $carpip)
1604
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1605
	$aliaslist = get_configured_ip_aliases_list();
1606
	foreach ($aliaslist as $aliasip => $aliasif)
1607
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1608
	foreach ($interfaces as $iface => $ifacename) {
1609
		$tmp["name"]  = $ifacename;
1610
		$tmp["value"] = $iface;
1611
		$listenips[] = $tmp;
1612
	}
1613
	$tmp["name"]  = "Localhost";
1614
	$tmp["value"] = "lo0";
1615
	$listenips[] = $tmp;
1616
	return $listenips;
1617
}
1618
?>
(47-47/62)