Project

General

Profile

Download (46.5 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/bin/netstat	/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(isset($config['system']['powerd_enable'])) {
44
		if ($g["platform"] == "nanobsd")
45
			exec("/sbin/kldload cpufreq");
46
		exec("/usr/sbin/powerd -b adp -a adp");
47
	} else {
48
		if(is_process_running("powerd"))
49
			exec("/usr/bin/killall powerd");
50
	}
51
}
52

    
53
function get_default_sysctl_value($id) {
54
	global $sysctls;
55

    
56
	if (isset($sysctls[$id]))
57
		return $sysctls[$id];
58
}
59

    
60
function activate_sysctls() {
61
	global $config, $g;
62
	exec("/sbin/sysctl net.enc.out.ipsec_bpf_mask=0x00000001");
63
	exec("/sbin/sysctl net.enc.out.ipsec_filter_mask=0x00000001");
64
	exec("/sbin/sysctl net.enc.in.ipsec_bpf_mask=0x00000002");
65
	exec("/sbin/sysctl net.enc.in.ipsec_filter_mask=0x00000002");
66

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

    
79
function system_resolvconf_generate($dynupdate = false) {
80
	global $config, $g;
81

    
82
	if(isset($config['system']['developerspew'])) {
83
		$mt = microtime();
84
		echo "system_resolvconf_generate() being called $mt\n";
85
	}
86

    
87
	$syscfg = $config['system'];
88

    
89
	$resolvconf = "domain {$syscfg['domain']}\n";
90

    
91
	$havedns = false;
92

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

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

    
125
	fwrite($fd, $resolvconf);
126
	fclose($fd);
127

    
128
	if (!$g['booting']) {
129
		/* restart dhcpd (nameservers may have changed) */
130
		if (!$dynupdate)
131
			services_dhcpd_configure();
132
	}
133

    
134
	/* setup static routes for DNS servers. */
135
	for ($dnscounter=1; $dnscounter<5; $dnscounter++) {
136
		/* setup static routes for dns servers */
137
		$dnsgw = "dns{$dnscounter}gwint";
138
		if (isset($config['system'][$dnsgw])) {
139
			$interface = $config['system'][$dnsgw];
140
			if (($interface <> "") && ($interface <> "none")) {
141
				$gatewayip = get_interface_gateway($interface);
142
				if(is_ipaddr($gatewayip)) {
143
					/* dns server array starts at 0 */
144
					$dnscountermo = $dnscounter - 1;
145
					mwexec("route delete -host {$syscfg['dnsserver'][$dnscountermo]}", true);
146
					mwexec("route add -host {$syscfg['dnsserver'][$dnscountermo]} {$gatewayip}");
147
				}
148
			}
149
		}
150
	}
151
	
152
	return 0;
153
}
154

    
155
function get_searchdomains() {
156
	global $config, $g;
157

    
158
	$master_list = array();
159
	
160
	// Read in dhclient nameservers
161
	$search_list = glob("/var/etc/searchdomain_*");
162
	if (is_array($search_lists)) {
163
		foreach($search_lists as $fdns) {
164
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
165
			if (!is_array($contents))
166
				continue;
167
			foreach ($contents as $dns) {
168
				if(is_hostname($dns)) 
169
					$master_list[] = $dns;
170
			}
171
		}
172
	}
173

    
174
	return $master_list;
175
}
176

    
177
function get_nameservers() {
178
	global $config, $g;
179
	$master_list = array();
180
	
181
	// Read in dhclient nameservers
182
	$dns_lists = glob("/var/etc/nameserver_*");
183
	if (is_array($dns_lists)) {
184
		foreach($dns_lists as $fdns) {
185
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
186
			if (!is_array($contents))
187
				continue;
188
			foreach ($contents as $dns) {
189
				if(is_ipaddr($dns)) 
190
					$master_list[] = $dns;
191
			}
192
		}
193
	}
194

    
195
	// Read in any extra nameservers
196
	if(file_exists("/var/etc/nameservers.conf")) {
197
		$dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
198
		if(is_array($dns_s)) {
199
			foreach($dns_s as $dns)
200
				if (is_ipaddr($dns))
201
					$master_list[] = $dns;
202
		}
203
	}
204

    
205
	return $master_list;
206
}
207

    
208
function system_hosts_generate() {
209
	global $config, $g;
210
	if(isset($config['system']['developerspew'])) {
211
		$mt = microtime();
212
		echo "system_hosts_generate() being called $mt\n";
213
	}
214

    
215
	$syscfg = $config['system'];
216
	$dnsmasqcfg = $config['dnsmasq'];
217

    
218
	if (!is_array($dnsmasqcfg['hosts'])) {
219
		$dnsmasqcfg['hosts'] = array();
220
	}
221
	$hostscfg = $dnsmasqcfg['hosts'];
222

    
223
	$hosts = "127.0.0.1	localhost localhost.{$syscfg['domain']}\n";
224

    
225
	if ($config['interfaces']['lan']) {
226
		$cfgip = get_interface_ip("lan");
227
		if (is_ipaddr($cfgip))
228
			$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
229
	} else {
230
		$sysiflist = get_configured_interface_list();
231
		foreach ($sysiflist as $sysif) {
232
			if (!interface_has_gateway($sysif)) {
233
				$cfgip = get_interface_ip($sysif);
234
				if (is_ipaddr($cfgip)) {
235
					$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
236
					break;
237
				}
238
			}
239
		}
240
	}
241

    
242
	foreach ($hostscfg as $host) {
243
		if ($host['host'])
244
			$hosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
245
		else
246
			$hosts .= "{$host['ip']}	{$host['domain']}\n";
247
	}
248
	if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpd'])) {
249
		foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf)
250
			if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
251
					foreach ($dhcpifconf['staticmap'] as $host)
252
						if ($host['ipaddr'] && $host['hostname'])
253
							$hosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
254
	}
255

    
256
	/*
257
	 * Do not remove this because dhcpleases monitors with kqueue it needs to be 
258
	 * killed before writing to hosts files.
259
	 */
260
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
261
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
262
                @unlink("{$g['varrun_path']}/dhcpleases.pid");
263
	}
264
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
265
	if (!$fd) {
266
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
267
		return 1;
268
	}
269
	fwrite($fd, $hosts);
270
	fclose($fd);
271

    
272
	system_dhcpleases_configure();
273

    
274
	return 0;
275
}
276

    
277
function system_dhcpleases_configure() {
278
	global $config, $g;
279
	
280
	/* Start the monitoring process for dynamic dhcpclients. */
281
	if (isset($config['dnsmasq']['regdhcp'])) {
282
		/* Make sure we do not error out */
283
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
284
		if (file_exists("{$g['varrun_path']}/dhcpleases.pid"))
285
				sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "HUP");
286
		else
287
			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");
288
	} else {
289
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
290
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
291
	}
292
}
293

    
294
function system_hostname_configure() {
295
	global $config, $g;
296
	if(isset($config['system']['developerspew'])) {
297
		$mt = microtime();
298
		echo "system_hostname_configure() being called $mt\n";
299
	}
300

    
301
	$syscfg = $config['system'];
302

    
303
	/* set hostname */
304
	$status = mwexec("/bin/hostname " .
305
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
306

    
307
    /* Setup host GUID ID.  This is used by ZFS. */
308
	mwexec("/etc/rc.d/hostid start");
309

    
310
	return $status;
311
}
312

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

    
320
	/* configure gif interfaces for ipv6 tunnels */
321
	interfaces_gif_configure();
322

    
323
	$gatewayip = "";
324
	$interfacegw = "";
325
	$foundgw = false;
326
	$gatewayipv6 = "";
327
	$interfacegwv6 = "";
328
	$foundgwv6 = false;
329
	/* tack on all the hard defined gateways as well */
330
	if (is_array($config['gateways']['gateway_item'])) {
331
		mwexec("/bin/rm {$g['tmp_path']}/*_defaultgw", true);
332
		foreach	($config['gateways']['gateway_item'] as $gateway) {
333
			if (isset($gateway['defaultgw']) && (is_ipaddrv4($gateway['gateway']))) {
334
				if(strstr($gateway['gateway'], ":"))
335
					break;
336
				if ($gateway['gateway'] == "dynamic")
337
					$gateway['gateway'] = get_interface_gateway($gateway['interface']);
338
				$gatewayip = $gateway['gateway'];
339
				$interfacegw = $gateway['interface'];
340
				if (!empty($interfacegw)) {
341
					$defaultif = get_real_interface($gateway['interface']);
342
					if ($defaultif)
343
						@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gatewayip);
344
				}
345
				$foundgw = true;
346
				break;
347
			}
348
		}
349
		foreach	($config['gateways']['gateway_item'] as $gateway) {
350
			if (isset($gateway['defaultgw']) && (is_ipaddrv6($gateway['gateway']))) {
351
				if ($gateway['gateway'] == "dynamic")
352
					$gateway['gateway'] = get_interface_gateway_v6($gateway['interface']);
353
				$gatewayipv6 = $gateway['gateway'];
354
				$interfacegwv6 = $gateway['interface'];
355
				if (!empty($interfacegwv6)) {
356
					$defaultifv6 = get_real_interface($gateway['interface']);
357
					if ($defaultifv6)
358
						@file_put_contents("{$g['tmp_path']}/{$defaultifv6}_defaultgwv6", $gatewayipv6);
359
				}
360
				$foundgwv6 = true;
361
				break;
362
			}
363
		}
364
	}
365
	if ($foundgw == false) {
366
		$defaultif = get_real_interface("wan");
367
		$interfacegw = "wan";
368
		$gatewayip = get_interface_gateway("wan");
369
		@touch("{$g['tmp_path']}/{$defaultif}_defaultgw");
370
	}	
371
	if ($foundgwv6 == false) {
372
		$defaultifv6 = get_real_interface("wan");
373
		$interfacegwv6 = "wan";
374
		$gatewayipv6 = get_interface_gateway_v6("wan");
375
		@touch("{$g['tmp_path']}/{$defaultif}_defaultgwv6");
376
	}
377
	$dont_add_route = false;
378
	/* if OLSRD is enabled, allow WAN to house DHCP. */
379
	if($config['installedpackages']['olsrd']) {
380
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
381
			if($olsrd['enabledyngw'] == "on") {
382
				$dont_add_route = true;
383
				break;
384
			}
385
		}
386
	}
387
	/* Create a array from the existing inet route table */
388
	exec("/usr/bin/netstat -rnf inet", $route_str);
389
	array_shift($route_str);
390
	array_shift($route_str);
391
	array_shift($route_str);
392
	array_shift($route_str);
393
	$route_arr = array();
394
	foreach($route_str as $routeline) {
395
		$items = preg_split("/[ ]+/i", $routeline);
396
		$route_arr[$items[0]] = array($items[0], $items[1], $items[5]);
397
	}
398

    
399
	if ($dont_add_route == false ) {
400
		if (!empty($interface) && $interface != $interfacegw)
401
			;
402
		else if (($interfacegw <> "bgpd") && (is_ipaddrv4($gatewayip))) {
403
			$action = "add";
404
			if(isset($route_arr['default'])) {
405
				$action = "change";
406
			}
407
			log_error("ROUTING: $action default route to $gatewayip");
408
			mwexec("/sbin/route {$action} -inet default " . escapeshellarg($gatewayip));
409
		}
410
	}
411

    
412
	/* Create a array from the existing inet6 route table */
413
	exec("/usr/bin/netstat -rnf inet6", $routev6_str);
414
	array_shift($routev6_str);
415
	array_shift($routev6_str);
416
	array_shift($routev6_str);
417
	array_shift($routev6_str);
418
	$routev6_arr = array();
419
	foreach($routev6_str as $routeline) {
420
		$items = preg_split("/[ ]+/i", $routeline);
421
		$routev6_arr[$items[0]] = array($items[0], $items[1], $items[5]);
422
	}
423

    
424
	if ($dont_add_route == false ) {
425
		if (!empty($interface) && $interface != $interfacegwv6)
426
			;
427
		else if (($interfacegwv6 <> "bgpd") && (is_ipaddrv6($gatewayipv6))) {
428
			$action = "add";
429
			if(isset($routev6_arr['default'])) {
430
				$action = "change";
431
			}
432
			log_error("ROUTING: $action IPv6 default route to $gatewayipv6");
433
			mwexec("/sbin/route {$action} -inet6 default " . escapeshellarg($gatewayipv6));
434
		}
435
	}
436

    
437
	if (is_array($config['staticroutes']['route'])) {
438
		$gateways_arr = return_gateways_array();
439

    
440
		foreach ($config['staticroutes']['route'] as $rtent) {
441
			$gatewayip = "";
442
			if (empty($gateways_arr[$rtent['gateway']])) {
443
				log_error("Static Routes: Gateway IP could not be found for {$rtent['network']}");
444
				continue;
445
			}
446
			$gateway = $gateways_arr[$rtent['gateway']];
447
			if (!empty($interface) && $interface != $gateway['friendlyiface'])
448
				continue;
449

    
450
			$gatewayip = $gateway['gateway'];
451
			$interfacegw = $gateway['interface'];
452
			$action = "add";
453
			if (isset($route_arr[$rtent['network']]))
454
				$action = "change";
455

    
456
			if(is_ipaddrv6($gatewayip)) {
457
				$inetfamily = "-inet6";
458
			} else {
459
				$inetfamily = "-inet";
460
			}
461
			if (is_ipaddr($gatewayip)) {
462
				mwexec("/sbin/route {$action} {$inetfamily} " . escapeshellarg($rtent['network']) .
463
					" " . escapeshellarg($gatewayip));
464
			} else if (!empty($interfacegw)) {
465
				mwexec("/sbin/route {$action} {$inetfamily} " . escapeshellarg($rtent['network']) .
466
					" -iface " . escapeshellarg($interfacegw));
467
			}
468
		}
469
	}
470

    
471
	return 0;
472
}
473

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

    
481
	mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
482
	mwexec("/sbin/sysctl net.inet6.ip6.forwarding=1");
483
	return;
484
}
485

    
486
function system_syslogd_start() {
487
	global $config, $g;
488
	if(isset($config['system']['developerspew'])) {
489
		$mt = microtime();
490
		echo "system_syslogd_start() being called $mt\n";
491
	}
492

    
493
	$syslogcfg = $config['syslog'];
494

    
495
	if ($g['booting'])
496
		echo "Starting syslog...";
497
	else
498
		killbypid("{$g['varrun_path']}/syslog.pid");
499

    
500
	if(is_process_running("syslogd"))
501
		mwexec("/usr/bin/killall -9 syslogd");
502
	if(is_process_running("fifolog_writer"))
503
		mwexec("/usr/bin/killall -9 fifolog_writer");
504
	
505
	// Define carious commands for logging
506
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
507
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
508
	$clog_create = "/usr/sbin/clog -i -s ";
509
	$clog_log = "%";
510

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

    
595
EOD;
596
		if (isset($syslogcfg['filter'])) {
597
			if($syslogcfg['remoteserver'])
598
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver']}\n";
599
			if($syslogcfg['remoteserver2'])
600
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver2']}\n";
601
			if($syslogcfg['remoteserver3'])
602
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver3']}\n";
603

    
604
		}
605
		if (isset($syslogcfg['vpn'])) {
606
			if($syslogcfg['remoteserver'])
607
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver']}\n";
608
			if($syslogcfg['remoteserver2'])
609
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver2']}\n";
610
			if($syslogcfg['remoteserver3'])
611
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver3']}\n";
612
		}
613
		if (isset($syslogcfg['portalauth'])) {
614
			if($syslogcfg['remoteserver'])
615
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver']}\n";
616
			if($syslogcfg['remoteserver2'])
617
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver2']}\n";
618
			if($syslogcfg['remoteserver3'])
619
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver3']}\n";
620
		}
621
		if (isset($syslogcfg['dhcp'])) {
622
			if($syslogcfg['remoteserver'])
623
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver']}\n";
624
			if($syslogcfg['remoteserver2'])
625
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver2']}\n";
626
			if($syslogcfg['remoteserver3'])
627
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver3']}\n";
628
		}
629
		if (isset($syslogcfg['system'])) {
630
			if($syslogcfg['remoteserver'])
631
				$syslogconf .= <<<EOD
632
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver']}
633
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver']}
634
security.*										 @{$syslogcfg['remoteserver']}
635
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver']}
636
*.emerg											 @{$syslogcfg['remoteserver']}
637

    
638
EOD;
639

    
640
}
641

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

    
651
EOD;
652

    
653
}
654

    
655
		if (isset($syslogcfg['system'])) {
656
			if($syslogcfg['remoteserver3'])
657
				$syslogconf .= <<<EOD
658
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver3']}
659
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver3']}
660
security.*										 @{$syslogcfg['remoteserver3']}
661
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver3']}
662
*.emerg											 @{$syslogcfg['remoteserver3']}
663

    
664
EOD;
665

    
666
}
667
		if (isset($syslogcfg['logall'])) {
668
			if($syslogcfg['remoteserver'])
669
				$syslogconf .= <<<EOD
670
*.*								@{$syslogcfg['remoteserver']}
671

    
672
EOD;
673

    
674
			if($syslogcfg['remoteserver2'])
675
				$syslogconf .= <<<EOD
676
*.*								@{$syslogcfg['remoteserver2']}
677

    
678
EOD;
679

    
680
			if($syslogcfg['remoteserver3'])
681
				$syslogconf .= <<<EOD
682
*.*								@{$syslogcfg['remoteserver3']}
683

    
684
EOD;
685

    
686
}
687
		fwrite($fd, $syslogconf);
688
		fclose($fd);
689

    
690
		// Ensure that the log directory exists
691
		if(!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
692
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
693

    
694
		// Are we logging to a least one remote server ?
695
		if(strpos($syslogconf, "@") != false)
696
			$retval = system("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log -f {$g['varetc_path']}/syslog.conf");
697
		else
698
			$retval = system("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log -f {$g['varetc_path']}/syslog.conf");
699

    
700
	} else {
701
		$retval = mwexec("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log");
702
	}
703

    
704
	if ($g['booting'])
705
		echo "done.\n";
706

    
707
	return $retval;
708
}
709

    
710
function system_pccard_start() {
711
	global $config, $g;
712
	if(isset($config['system']['developerspew'])) {
713
		$mt = microtime();
714
		echo "system_pccard_start() being called $mt\n";
715
	}
716

    
717
	if ($g['booting'])
718
		echo "Initializing PCMCIA...";
719

    
720
	/* kill any running pccardd */
721
	killbypid("{$g['varrun_path']}/pccardd.pid");
722

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

    
726
	if ($g['booting']) {
727
		if ($res == 0)
728
			echo "done.\n";
729
		else
730
			echo "failed!\n";
731
	}
732

    
733
	return $res;
734
}
735

    
736

    
737
function system_webgui_start() {
738
	global $config, $g;
739

    
740
	if ($g['booting'])
741
		echo "Starting webConfigurator...";
742

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

    
746
	sleep(1);
747

    
748
	chdir($g['www_path']);
749

    
750
	/* defaults */
751
	$portarg = "80";
752
	$crt = "";
753
	$key = "";
754
	$ca = "";
755

    
756
	/* non-standard port? */
757
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
758
		$portarg = "{$config['system']['webgui']['port']}";
759

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

    
796
	/* generate lighttpd configuration */
797
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
798
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/");
799

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

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

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

    
816
	return $res;
817
}
818

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

    
833
	global $config, $g;
834

    
835
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
836
		mkdir("{$g['tmp_path']}/lighttpdcompress");
837

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

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

    
870
	$memory = get_memory();
871
	$avail = $memory[0];
872

    
873
	if($avail > 0 and $avail < 65) {
874
		$fast_cgi_enable = false;
875
	}
876

    
877
	// Ramp up captive portal max procs
878
	if($captive_portal == true)  {
879
		if($avail > 65 and $avail < 98) {
880
			$max_procs = 1;
881
		}
882
		if($avail > 97 and $avail < 128) {
883
			$max_procs = 2;
884
		}
885
		if($avail > 127 and $avail < 256) {
886
			$max_procs = 3;
887
		}
888
		if($avail > 255 and $avail < 384) {
889
			$max_procs = 4;
890
		}
891
		if($avail > 383) {
892
			$max_procs = 5;
893
		}
894
	}
895

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

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

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

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

    
938
#### CGI module
939
cgi.assign                 = ( ".cgi" => "" )
940

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

    
950
EOD;
951
	}
952

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

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

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

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

    
991
server.max-keep-alive-requests = 15
992
server.max-keep-alive-idle = 30
993

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

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

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

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

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

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

    
1065
#### accesslog module
1066
#accesslog.filename          = "/dev/null"
1067

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

    
1075

    
1076
######### Options that are good to be but not neccesary to be changed #######
1077

    
1078
## bind to port (default: 80)
1079

    
1080
EOD;
1081

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

    
1112

    
1113
	$lighty_config .= <<<EOD
1114

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

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

    
1122
## virtual directory listings
1123
server.dir-listing         = "disable"
1124

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

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

    
1135
{$server_upload_dirs}
1136

    
1137
{$server_max_request_size}
1138

    
1139
{$fastcgi_config}
1140

    
1141
{$cgi_config}
1142

    
1143
{$captive_portal_mod_evasive}
1144

    
1145
expire.url = (
1146
				"" => "access 50 hours",	
1147
        )
1148

    
1149
EOD;
1150

    
1151
	$cert = str_replace("\r", "", $cert);
1152
	$key = str_replace("\r", "", $key);
1153
	$ca = str_replace("\r", "", $ca);
1154

    
1155
	$cert = str_replace("\n\n", "\n", $cert);
1156
	$key = str_replace("\n\n", "\n", $key);
1157
	$ca = str_replace("\n\n", "\n", $ca);
1158

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

    
1188
	// Add HTTP to HTTPS redirect	
1189
	if ($captive_portal == false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1190
		if($lighty_port != "443") 
1191
			$redirectport = ":{$lighty_port}";
1192
		$lighty_config .= <<<EOD
1193
\$SERVER["socket"] == ":80" {
1194
	\$HTTP["host"] =~ "(.*)" {
1195
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1196
	}
1197
}
1198
EOD;
1199
	}
1200

    
1201
	$fd = fopen("{$filename}", "w");
1202
	if (!$fd) {
1203
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
1204
		return 1;
1205
	}
1206
	fwrite($fd, $lighty_config);
1207
	fclose($fd);
1208

    
1209
	return 0;
1210

    
1211
}
1212

    
1213
function system_timezone_configure() {
1214
	global $config, $g;
1215
	if(isset($config['system']['developerspew'])) {
1216
		$mt = microtime();
1217
		echo "system_timezone_configure() being called $mt\n";
1218
	}
1219

    
1220
	$syscfg = $config['system'];
1221

    
1222
	if ($g['booting'])
1223
		echo "Setting timezone...";
1224

    
1225
	/* extract appropriate timezone file */
1226
	$timezone = $syscfg['timezone'];
1227
	if (!$timezone)
1228
		$timezone = "Etc/UTC";
1229

    
1230
	conf_mount_rw();
1231

    
1232
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1233
		escapeshellarg($timezone) . " > /etc/localtime");
1234

    
1235
	mwexec("sync");
1236
	conf_mount_ro();
1237

    
1238
	if ($g['booting'])
1239
		echo "done.\n";
1240
}
1241

    
1242
function system_ntp_configure() {
1243
	global $config, $g;
1244

    
1245
	$syscfg =& $config['system'];
1246

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

    
1254
	fwrite($fd, "# \n");
1255
	fwrite($fd, "# pfSense OpenNTPD configuration file \n");
1256
	fwrite($fd, "# \n\n");
1257

    
1258
	/* foreach through servers and write out to ntpd.conf */
1259
	foreach (explode(' ', $syscfg['timeservers']) as $ts)
1260
		fwrite($fd, "servers {$ts}\n");
1261

    
1262
	/* Setup listener(s) if the user has configured one */
1263
        if ($config['installedpackages']['openntpd']) {
1264
    		/* server config is in coregui1 */
1265
		$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
1266
		if ($xmlsettings['enable'] == 'on') {
1267
			$ifaces = explode(',', $xmlsettings['interface']);
1268
			$ifaces = array_map('get_real_interface', $ifaces);
1269
			$ifaces = array_filter($ifaces, 'does_interface_exist');
1270
			$ips = array_map('find_interface_ip', $ifaces);
1271
			foreach ($ips as $ip) {
1272
				if (is_ipaddr($ip))
1273
					fwrite($fd, "listen on $ip\n");
1274
			}
1275
		}
1276
	}
1277

    
1278
	fwrite($fd, "\n");
1279

    
1280
	/* slurp! */
1281
	fclose($fd);
1282

    
1283
	/* if openntpd is running, kill it */
1284
	while(is_process_running("ntpd")) {
1285
		killbyname("ntpd");
1286
	}
1287

    
1288
	/* if /var/empty does not exist, create it */
1289
	if(!is_dir("/var/empty"))
1290
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1291

    
1292
	if ($g['booting'])
1293
		return;
1294

    
1295
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1296
	exec("/usr/local/sbin/ntpd -s -f {$g['varetc_path']}/ntpd.conf");
1297
	
1298
	// Note that we are starting up
1299
	exec("echo 'OpenNTPD is starting up' >> {$g['varlog_path']}/ntpd.log");
1300

    
1301
}
1302

    
1303
function sync_system_time() {
1304
	global $config, $g;
1305

    
1306
	$syscfg = $config['system'];
1307

    
1308
	if ($g['booting'])
1309
		echo "Syncing system time before startup...";
1310

    
1311
	/* foreach through servers and write out to ntpd.conf */
1312
	foreach (explode(' ', $syscfg['timeservers']) as $ts) {
1313
		mwexec("/usr/sbin/ntpdate -s $ts");
1314
	}
1315
	
1316
	if ($g['booting'])
1317
		echo "done.\n";
1318
	
1319
}
1320

    
1321
function system_halt() {
1322
	global $g;
1323

    
1324
	system_reboot_cleanup();
1325

    
1326
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1327
}
1328

    
1329
function system_reboot() {
1330
	global $g;
1331

    
1332
	system_reboot_cleanup();
1333

    
1334
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1335
}
1336

    
1337
function system_reboot_sync() {
1338
	global $g;
1339

    
1340
	system_reboot_cleanup();
1341

    
1342
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1343
}
1344

    
1345
function system_reboot_cleanup() {
1346
	mwexec("/usr/local/bin/beep.sh stop");
1347
	require_once("captiveportal.inc");
1348
	captiveportal_radius_stop_all();
1349
	require_once("voucher.inc");
1350
	voucher_save_db_to_config();
1351
}
1352

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

    
1360
	if ($early)
1361
		$cmdn = "earlyshellcmd";
1362
	else
1363
		$cmdn = "shellcmd";
1364

    
1365
	if (is_array($config['system'][$cmdn])) {
1366

    
1367
		/* *cmd is an array, loop through */
1368
		foreach ($config['system'][$cmdn] as $cmd) {
1369
			exec($cmd);
1370
		}
1371

    
1372
	} elseif($config['system'][$cmdn] <> "") {
1373

    
1374
		/* execute single item */
1375
		exec($config['system'][$cmdn]);
1376

    
1377
	}
1378
}
1379

    
1380
function system_console_configure() {
1381
	global $config, $g;
1382
	if(isset($config['system']['developerspew'])) {
1383
		$mt = microtime();
1384
		echo "system_console_configure() being called $mt\n";
1385
	}
1386

    
1387
	if (isset($config['system']['disableconsolemenu'])) {
1388
		touch("{$g['varetc_path']}/disableconsole");
1389
	} else {
1390
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1391
	}
1392
}
1393

    
1394
function system_dmesg_save() {
1395
	global $g;
1396
	if(isset($config['system']['developerspew'])) {
1397
		$mt = microtime();
1398
		echo "system_dmesg_save() being called $mt\n";
1399
	}
1400

    
1401
	$dmesg = "";
1402
	exec("/sbin/dmesg", $dmesg);
1403

    
1404
	/* find last copyright line (output from previous boots may be present) */
1405
	$lastcpline = 0;
1406

    
1407
	for ($i = 0; $i < count($dmesg); $i++) {
1408
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1409
			$lastcpline = $i;
1410
	}
1411

    
1412
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1413
	if (!$fd) {
1414
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1415
		return 1;
1416
	}
1417

    
1418
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1419
		fwrite($fd, $dmesg[$i] . "\n");
1420

    
1421
	fclose($fd);
1422

    
1423
	return 0;
1424
}
1425

    
1426
function system_set_harddisk_standby() {
1427
	global $g, $config;
1428
	if(isset($config['system']['developerspew'])) {
1429
		$mt = microtime();
1430
		echo "system_set_harddisk_standby() being called $mt\n";
1431
	}
1432

    
1433
	if (isset($config['system']['harddiskstandby'])) {
1434
		if ($g['booting']) {
1435
			echo 'Setting hard disk standby... ';
1436
		}
1437

    
1438
		$standby = $config['system']['harddiskstandby'];
1439
		// Check for a numeric value
1440
		if (is_numeric($standby)) {
1441
			// Sync the disk(s)
1442
			pfSense_sync();
1443
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1444
				// Reinitialize ATA-drives
1445
				mwexec('/usr/local/sbin/atareinit');
1446
				if ($g['booting']) {
1447
					echo "done.\n";
1448
				}
1449
			} else if ($g['booting']) {
1450
				echo "failed!\n";
1451
			}
1452
		} else if ($g['booting']) {
1453
			echo "failed!\n";
1454
		}
1455
	}
1456
}
1457

    
1458
function system_setup_sysctl() {
1459
	global $config;
1460
	if(isset($config['system']['developerspew'])) {
1461
		$mt = microtime();
1462
		echo "system_setup_sysctl() being called $mt\n";
1463
	}
1464

    
1465
	activate_sysctls();	
1466

    
1467
	if (isset($config['system']['sharednet'])) {
1468
		system_disable_arp_wrong_if();
1469
	}
1470
}
1471

    
1472
function system_disable_arp_wrong_if() {
1473
	global $config;
1474
	if(isset($config['system']['developerspew'])) {
1475
		$mt = microtime();
1476
		echo "system_disable_arp_wrong_if() being called $mt\n";
1477
	}
1478
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1479
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1480
}
1481

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

    
1492
function enable_watchdog() {
1493
	global $config;
1494
	return;
1495
	$install_watchdog = false;
1496
	$supported_watchdogs = array("Geode");
1497
	$file = file_get_contents("/var/log/dmesg.boot");
1498
	foreach($supported_watchdogs as $sd) {
1499
		if(stristr($file, "Geode")) {
1500
			$install_watchdog = true;
1501
		}
1502
	}
1503
	if($install_watchdog == true) {
1504
		if(is_process_running("watchdogd"))
1505
			mwexec("/usr/bin/killall watchdogd", true);
1506
		exec("/usr/sbin/watchdogd");
1507
	}
1508
}
1509

    
1510
function system_check_reset_button() {
1511
	global $g;
1512
	if($g['platform'] != "nanobsd")
1513
		return 0;
1514

    
1515
	$specplatform = system_identify_specific_platform();
1516

    
1517
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1518
		return 0;
1519

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

    
1522
	if ($retval == 99) {
1523
		/* user has pressed reset button for 2 seconds - 
1524
		   reset to factory defaults */
1525
		echo <<<EOD
1526

    
1527
***********************************************************************
1528
* Reset button pressed - resetting configuration to factory defaults. *
1529
* The system will reboot after this completes.                        *
1530
***********************************************************************
1531

    
1532

    
1533
EOD;
1534
		
1535
		reset_factory_defaults();
1536
		system_reboot_sync();
1537
		exit(0);
1538
	}
1539

    
1540
	return 0;
1541
}
1542

    
1543
/* attempt to identify the specific platform (for embedded systems)
1544
   Returns an array with two elements:
1545
	name => platform string (e.g. 'wrap', 'alix' etc.)
1546
	descr => human-readable description (e.g. "PC Engines WRAP")
1547
*/
1548
function system_identify_specific_platform() {
1549
	global $g;
1550
	
1551
	if ($g['platform'] == 'generic-pc')
1552
		return array('name' => 'generic-pc', 'descr' => "Generic PC");
1553
	
1554
	if ($g['platform'] == 'generic-pc-cdrom')
1555
		return array('name' => 'generic-pc-cdrom', 'descr' => "Generic PC (CD-ROM)");
1556
	
1557
	/* the rest of the code only deals with 'embedded' platforms */
1558
	if ($g['platform'] != 'nanobsd')
1559
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1560
	
1561
	$dmesg = system_get_dmesg_boot();
1562
	
1563
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1564
		return array('name' => 'wrap', 'descr' => 'PC Engines WRAP');
1565
	
1566
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1567
		return array('name' => 'alix', 'descr' => 'PC Engines ALIX');
1568

    
1569
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1570
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1571
	
1572
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1573
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1574
		
1575
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1576
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1577
	
1578
	/* unknown embedded platform */
1579
	return array('name' => 'embedded', 'descr' => 'embedded (unknown)');
1580
}
1581

    
1582
function system_get_dmesg_boot() {
1583
	global $g;
1584
		
1585
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1586
}
1587

    
1588
?>
(47-47/61)