Project

General

Profile

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
160
	unlock($dnslock);
161

    
162
	return 0;
163
}
164

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

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

    
184
	return $master_list;
185
}
186

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

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

    
215
	return $master_list;
216
}
217

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

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

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

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

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

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

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

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

    
294
	system_dhcpleases_configure();
295

    
296
	return 0;
297
}
298

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

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

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

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

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

    
334
	return $status;
335
}
336

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

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

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

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

    
430
	$static_routes = get_staticroutes();
431
	if (count($static_routes)) {
432
		$gateways_arr = return_gateways_array();
433

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

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

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

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

    
467
	return 0;
468
}
469

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
601
		$syslogconf .= "!relayd\n";
602
		if (!isset($syslogcfg['disablelocallogging']))
603
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/relayd.log\n";
604
		if (isset($syslogcfg['relayd']))
605
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
606

    
607
		$syslogconf .= "!hostapd\n";
608
		if (!isset($syslogcfg['disablelocallogging']))
609
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
610
		if (isset($syslogcfg['hostapd']))
611
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
612

    
613
		$syslogconf .= "!-{$facilitylist}\n";
614
		if (!isset($syslogcfg['disablelocallogging'])) 
615
			$syslogconf .= <<<EOD
616
local0.*							{$log_directive}{$g['varlog_path']}/filter.log
617
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
618
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
619
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
620
*.notice;kern.debug;lpr.info;mail.crit;				{$log_directive}{$g['varlog_path']}/system.log
621
news.err;local0.none;local3.none;local4.none;			{$log_directive}{$g['varlog_path']}/system.log
622
local7.none							{$log_directive}{$g['varlog_path']}/system.log
623
security.*							{$log_directive}{$g['varlog_path']}/system.log
624
auth.info;authpriv.info;daemon.info				{$log_directive}{$g['varlog_path']}/system.log
625
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
626
*.emerg								*
627

    
628
EOD;
629
		if (isset($syslogcfg['filter']))
630
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local0.*");
631
		if (isset($syslogcfg['vpn']))
632
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
633
		if (isset($syslogcfg['portalauth']))
634
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
635
		if (isset($syslogcfg['dhcp']))
636
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
637
		if (isset($syslogcfg['system'])) {
638
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.notice;kern.debug;lpr.info;mail.crit;");
639
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "news.err;local0.none;local3.none;local7.none");
640
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "security.*");
641
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "auth.info;authpriv.info;daemon.info");
642
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.emerg");
643
		}
644
		if (isset($syslogcfg['logall'])) {
645
			// Make everything mean everything, including facilities excluded above.
646
			$syslogconf .= "!*\n";
647
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
648
		}
649

    
650
		if (isset($syslogcfg['zmqserver'])) {
651
				$syslogconf .= <<<EOD
652
*.*								^{$syslogcfg['zmqserver']}
653

    
654
EOD;
655
		}
656
		fwrite($fd, $syslogconf);
657
		fclose($fd);
658

    
659
		// Ensure that the log directory exists
660
		if(!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
661
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
662

    
663
		// Are we logging to a least one remote server ?
664
		if(strpos($syslogconf, "@") != false)
665
			$retval = mwexec_bg("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log -f {$g['varetc_path']}/syslog.conf");
666
		else {
667
			$retval = mwexec_bg("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log -f {$g['varetc_path']}/syslog.conf");
668
		}
669

    
670
	} else {
671
		$retval = mwexec_bg("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log");
672
	}
673

    
674
	if ($g['booting'])
675
		echo gettext("done.") . "\n";
676

    
677
	return $retval;
678
}
679

    
680
function system_pccard_start() {
681
	global $config, $g;
682
	if(isset($config['system']['developerspew'])) {
683
		$mt = microtime();
684
		echo "system_pccard_start() being called $mt\n";
685
	}
686

    
687
	if ($g['booting'])
688
		echo gettext("Initializing PCMCIA...");
689

    
690
	/* kill any running pccardd */
691
	killbypid("{$g['varrun_path']}/pccardd.pid");
692

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

    
696
	if ($g['booting']) {
697
		if ($res == 0)
698
			echo gettext("done.") . "\n";
699
		else
700
			echo gettext("failed!") . "\n";
701
	}
702

    
703
	return $res;
704
}
705

    
706

    
707
function system_webgui_start() {
708
	global $config, $g;
709

    
710
	if ($g['booting'])
711
		echo gettext("Starting webConfigurator...");
712

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

    
716
	sleep(1);
717

    
718
	chdir($g['www_path']);
719

    
720
	/* defaults */
721
	$portarg = "80";
722
	$crt = "";
723
	$key = "";
724
	$ca = "";
725

    
726
	/* non-standard port? */
727
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
728
		$portarg = "{$config['system']['webgui']['port']}";
729

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

    
766
	/* generate lighttpd configuration */
767
	$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
768
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
769
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
770
		"cert.pem", "ca.pem", $max_procs);
771

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

    
775
	/* fetch page to preload apc cache */
776
	$proto = "http";
777
	if ($config['system']['webgui']['protocol'])
778
		$proto = $config['system']['webgui']['protocol'];
779
	mwexec_bg("/usr/bin/fetch -o /dev/null -q {$proto}://localhost:{$portarg}/preload.php");
780

    
781
	if ($g['booting']) {
782
		if ($res == 0)
783
			echo gettext("done.") . "\n";
784
		else
785
			echo gettext("failed!") . "\n";
786
	}
787

    
788
	return $res;
789
}
790

    
791
function system_generate_lighty_config($filename,
792
	$cert,
793
	$key,
794
	$ca,
795
	$pid_file,
796
	$port = 80,
797
	$document_root = "/usr/local/www/",
798
	$cert_location = "cert.pem",
799
	$ca_location = "ca.pem",
800
	$max_procs = 1,
801
	$max_requests = "2",
802
	$fast_cgi_enable = true,
803
	$captive_portal = false) {
804

    
805
	global $config, $g;
806

    
807
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
808
		mkdir("{$g['tmp_path']}/lighttpdcompress");
809

    
810
	if(isset($config['system']['developerspew'])) {
811
		$mt = microtime();
812
		echo "system_generate_lighty_config() being called $mt\n";
813
	}
814

    
815
	if($captive_portal != false)  {
816
		$captiveportal = ",\"mod_rewrite\"";
817
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?zone={$captive_portal}&redirurl=$1\" )\n";
818
		$captive_portal_module = "";
819
		$maxprocperip = $config['captiveportal']['maxprocperip'];
820
		if($maxprocperip and $maxprocperip > 0)
821
			$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
822
		else
823
			$captive_portal_mod_evasive = "";
824
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
825
		exec("mkdir -p {$g['tmp_path']}/captiveportal");
826
		exec("chmod a-w {$g['tmp_path']}/captiveportal");
827
		$server_max_request_size = "server.max-request-size    = 384";
828
	} else {
829
		$captiveportal = "";
830
		$captive_portal_rewrite = "";
831
		$captive_portal_module = "";
832
		$captive_portal_mod_evasive = "";
833
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
834
		$server_max_request_size = "server.max-request-size    = 2097152";
835
	}
836
	
837
	if($port <> "")
838
		$lighty_port = $port;
839
	else
840
		$lighty_port = "80";
841

    
842
	$memory = get_memory();
843
	$avail = $memory[0];
844

    
845
	if($avail > 0 and $avail < 65) {
846
		$fast_cgi_enable = false;
847
	}
848

    
849
	// Ramp up captive portal max procs
850
	//  Work relative to the default of 2, for values that would be >2.
851
	if($captive_portal == true)  {
852
		if($avail > 65 and $avail < 98) {
853
			$max_procs = 1;
854
		}
855
		if($avail > 97 and $avail < 128) {
856
			$max_procs = 2;
857
		}
858
		if($avail > 127 and $avail < 256) {
859
			$max_procs += 1;
860
		}
861
		if($avail > 255 and $avail < 384) {
862
			$max_procs += 2;
863
		}
864
		if($avail > 383) {
865
			$max_procs += 3;
866
		}
867
	}
868

    
869
	if($captive_portal == true)  {	
870
		$bin_environment =  <<<EOC
871
			"bin-environment" => (
872
				"PHP_FCGI_CHILDREN" => "0",
873
				"PHP_FCGI_MAX_REQUESTS" => "500"
874
			),
875
EOC;
876

    
877
	} else if ($avail > 0 and $avail < 128) {
878
		$bin_environment = <<<EOC
879
			"bin-environment" => (
880
				"PHP_FCGI_CHILDREN" => "0",
881
				"PHP_FCGI_MAX_REQUESTS" => "2",
882
			),
883

    
884
EOC;
885
	} else
886
		$bin_environment =  <<<EOC
887
			"bin-environment" => (
888
				"PHP_FCGI_CHILDREN" => "0",
889
				"PHP_FCGI_MAX_REQUESTS" => "500"
890
			),
891
EOC;
892

    
893
	if($fast_cgi_enable == true) {
894
		$module = "\"mod_fastcgi\", \"mod_cgi\"";
895
		if ($captive_portal != false)
896
			$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi-{$captive_portal}.socket";
897
		else
898
			$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi.socket";
899
		$cgi_config = "";
900
		$fastcgi_config = <<<EOD
901
#### fastcgi module
902
## read fastcgi.txt for more info
903
fastcgi.server = ( ".php" =>
904
	( "localhost" =>
905
		(
906
			"socket" => "{$fast_cgi_path}",
907
			"min-procs" => 0,
908
			"max-procs" => {$max_procs},
909
{$bin_environment}
910
			"bin-path" => "/usr/local/bin/php"
911
		)
912
	)
913
)
914

    
915
#### CGI module
916
cgi.assign                 = ( ".cgi" => "" )
917

    
918
EOD;
919
	} else {
920
		$fastcgi_config = "";
921
		$module = "\"mod_cgi\"";
922
		$cgi_config = <<<EOD
923
#### CGI module
924
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
925
                               ".cgi" => "" )
926

    
927
EOD;
928
	}
929

    
930
	$lighty_config = "";
931
	$lighty_config .= <<<EOD
932
#
933
# lighttpd configuration file
934
#
935
# use a it as base for lighttpd 1.0.0 and above
936
#
937
############ Options you really have to take care of ####################
938

    
939
## FreeBSD!
940
server.event-handler	= "freebsd-kqueue"
941
server.network-backend 	= "writev"
942
#server.use-ipv6 = "enable"
943

    
944
## modules to load
945
server.modules              =   (
946
	{$captive_portal_module}
947
	"mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect",
948
	{$module}{$captiveportal}
949
)
950

    
951
## Unused modules
952
#                               "mod_setenv",
953
#                               "mod_rewrite",
954
#                               "mod_ssi",
955
#                               "mod_usertrack",
956
#                               "mod_expire",
957
#                               "mod_secdownload",
958
#                               "mod_rrdtool",
959
#                               "mod_auth",
960
#                               "mod_status",
961
#                               "mod_alias",
962
#                               "mod_proxy",
963
#                               "mod_simple_vhost",
964
#                               "mod_evhost",
965
#                               "mod_userdir",
966
#                               "mod_cgi",
967

    
968
server.max-keep-alive-requests = 15
969
server.max-keep-alive-idle = 30
970

    
971
## a static document-root, for virtual-hosting take look at the
972
## server.virtual-* options
973
server.document-root        = "{$document_root}"
974
{$captive_portal_rewrite}
975

    
976
# Maximum idle time with nothing being written (php downloading)
977
server.max-write-idle = 999
978

    
979
## where to send error-messages to
980
server.errorlog             = "/var/log/lighttpd.error.log"
981

    
982
# files to check for if .../ is requested
983
server.indexfiles           = ( "index.php", "index.html",
984
                                "index.htm", "default.htm" )
985

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

    
1039
# Use the "Content-Type" extended attribute to obtain mime type if possible
1040
#mimetypes.use-xattr        = "enable"
1041

    
1042
#### accesslog module
1043
#accesslog.filename          = "/dev/null"
1044

    
1045
## deny access the file-extensions
1046
#
1047
# ~    is for backupfiles from vi, emacs, joe, ...
1048
# .inc is often used for code includes which should in general not be part
1049
#      of the document-root
1050
url.access-deny             = ( "~", ".inc" )
1051

    
1052

    
1053
######### Options that are good to be but not neccesary to be changed #######
1054

    
1055
## bind to port (default: 80)
1056

    
1057
EOD;
1058

    
1059
	if($captive_portal == true) {
1060
		$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1061
		$lighty_config .= "server.port  = {$lighty_port}\n";
1062
		$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1063
		$lighty_config .= "\$SERVER[\"socket\"]  == \"[::1]:{$lighty_port}\" { \n";
1064
		if($cert <> "" and $key <> "") {
1065
			$lighty_config .= "\n";
1066
			$lighty_config .= "## ssl configuration\n";
1067
			$lighty_config .= "ssl.engine = \"enable\"\n";
1068
			$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1069
			if($ca <> "")
1070
				$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1071
		}
1072
		$lighty_config .= " }\n";
1073
	} else {
1074
		$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1075
		$lighty_config .= "server.port  = {$lighty_port}\n";
1076
		$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1077
		$lighty_config .= "\$SERVER[\"socket\"]  == \"[::]:{$lighty_port}\" { \n";
1078
		if($cert <> "" and $key <> "") {
1079
			$lighty_config .= "\n";
1080
			$lighty_config .= "## ssl configuration\n";
1081
			$lighty_config .= "ssl.engine = \"enable\"\n";
1082
			$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1083
			if($ca <> "")
1084
				$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1085
		}
1086
		$lighty_config .= " }\n";
1087
	}
1088

    
1089

    
1090
	$lighty_config .= <<<EOD
1091

    
1092
## error-handler for status 404
1093
#server.error-handler-404   = "/error-handler.html"
1094
#server.error-handler-404   = "/error-handler.php"
1095

    
1096
## to help the rc.scripts
1097
server.pid-file            = "/var/run/{$pid_file}"
1098

    
1099
## virtual directory listings
1100
server.dir-listing         = "disable"
1101

    
1102
## enable debugging
1103
debug.log-request-header   = "disable"
1104
debug.log-response-header  = "disable"
1105
debug.log-request-handling = "disable"
1106
debug.log-file-not-found   = "disable"
1107

    
1108
# gzip compression
1109
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1110
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1111

    
1112
{$server_upload_dirs}
1113

    
1114
{$server_max_request_size}
1115

    
1116
{$fastcgi_config}
1117

    
1118
{$cgi_config}
1119

    
1120
{$captive_portal_mod_evasive}
1121

    
1122
expire.url = (
1123
				"" => "access 50 hours",	
1124
        )
1125

    
1126
EOD;
1127

    
1128
	$cert = str_replace("\r", "", $cert);
1129
	$key = str_replace("\r", "", $key);
1130
	$ca = str_replace("\r", "", $ca);
1131

    
1132
	$cert = str_replace("\n\n", "\n", $cert);
1133
	$key = str_replace("\n\n", "\n", $key);
1134
	$ca = str_replace("\n\n", "\n", $ca);
1135

    
1136
	if($cert <> "" and $key <> "") {
1137
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1138
		if (!$fd) {
1139
			printf(gettext("Error: cannot open cert.pem in system_webgui_start().%s"), "\n");
1140
			return 1;
1141
		}
1142
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1143
		fwrite($fd, $cert);
1144
		fwrite($fd, "\n");
1145
		fwrite($fd, $key);
1146
		fclose($fd);
1147
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
1148
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1149
			if (!$fd) {
1150
				printf(gettext("Error: cannot open ca.pem in system_webgui_start().%s"), "\n");
1151
				return 1;
1152
			}
1153
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1154
			fwrite($fd, $ca);
1155
			fclose($fd);
1156
		}
1157
		$lighty_config .= "\n";
1158
		$lighty_config .= "## " . gettext("ssl configuration") . "\n";
1159
		$lighty_config .= "ssl.engine = \"enable\"\n";
1160
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1161

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

    
1166
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1167
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1168
	}
1169

    
1170
	// Add HTTP to HTTPS redirect	
1171
	if ($captive_portal == false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1172
		if($lighty_port != "443") 
1173
			$redirectport = ":{$lighty_port}";
1174
		$lighty_config .= <<<EOD
1175
\$SERVER["socket"] == ":80" {
1176
	\$HTTP["host"] =~ "(.*)" {
1177
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1178
	}
1179
}
1180
EOD;
1181
	}
1182

    
1183
	$fd = fopen("{$filename}", "w");
1184
	if (!$fd) {
1185
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1186
		return 1;
1187
	}
1188
	fwrite($fd, $lighty_config);
1189
	fclose($fd);
1190

    
1191
	return 0;
1192

    
1193
}
1194

    
1195
function system_timezone_configure() {
1196
	global $config, $g;
1197
	if(isset($config['system']['developerspew'])) {
1198
		$mt = microtime();
1199
		echo "system_timezone_configure() being called $mt\n";
1200
	}
1201

    
1202
	$syscfg = $config['system'];
1203

    
1204
	if ($g['booting'])
1205
		echo gettext("Setting timezone...");
1206

    
1207
	/* extract appropriate timezone file */
1208
	$timezone = $syscfg['timezone'];
1209
	if (!$timezone)
1210
		$timezone = "Etc/UTC";
1211

    
1212
	conf_mount_rw();
1213

    
1214
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1215
		escapeshellarg($timezone) . " > /etc/localtime");
1216

    
1217
	mwexec("sync");
1218
	conf_mount_ro();
1219

    
1220
	if ($g['booting'])
1221
		echo gettext("done.") . "\n";
1222
}
1223

    
1224
function system_ntp_configure() {
1225
	global $config, $g;
1226

    
1227
	if ($g['platform'] == 'jail')
1228
		return;
1229

    
1230
	$ntpcfg = "# \n";
1231
	$ntpcfg .= "# pfSense OpenNTPD configuration file \n";
1232
	$ntpcfg .= "# \n\n";
1233

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

    
1238
	/* Setup listener(s) if the user has configured one */
1239
        if ($config['installedpackages']['openntpd']) {
1240
    		/* server config is in coregui1 */
1241
		$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
1242
		if ($xmlsettings['enable'] == 'on') {
1243
			$ifaces = explode(',', $xmlsettings['interface']);
1244
			$ips = array();
1245
			foreach ($ifaces as $if) {
1246
				if (is_ipaddr($if)) {
1247
					$ips[] = $if;
1248
				} else {
1249
					$if = get_real_interface($if);
1250
					if (does_interface_exist($if))
1251
						$ips[] = find_interface_ip($if);
1252
				}
1253
			}
1254
			foreach ($ips as $ip) {
1255
				if (is_ipaddr($ip))
1256
					$ntpcfg .= "listen on $ip\n";
1257
			}
1258
		}
1259
	}
1260
	$ntpcfg .= "\n";
1261

    
1262
	/* open configuration for wrting or bail */
1263
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1264
	if(!$fd) {
1265
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1266
		return;
1267
	}
1268
	fwrite($fd, $ntpcfg);
1269

    
1270
	/* slurp! */
1271
	fclose($fd);
1272

    
1273
	/* if openntpd is running, kill it */
1274
	while(is_process_running("ntpd")) {
1275
		killbyname("ntpd");
1276
	}
1277

    
1278
	/* if /var/empty does not exist, create it */
1279
	if(!is_dir("/var/empty"))
1280
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1281

    
1282
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1283
	exec("/usr/local/sbin/ntpd -s -f {$g['varetc_path']}/ntpd.conf");
1284
	
1285
	// Note that we are starting up
1286
	log_error("OpenNTPD is starting up.");
1287

    
1288
}
1289

    
1290
function sync_system_time() {
1291
	global $config, $g;
1292

    
1293
	if ($g['booting'])
1294
		echo gettext("Syncing system time before startup...");
1295

    
1296
	/* foreach through servers and write out to ntpd.conf */
1297
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1298
		mwexec("/usr/sbin/ntpdate -s $ts");
1299
	}
1300
	
1301
	if ($g['booting'])
1302
		echo gettext("done.") . "\n";
1303
	
1304
}
1305

    
1306
function system_halt() {
1307
	global $g;
1308

    
1309
	system_reboot_cleanup();
1310

    
1311
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1312
}
1313

    
1314
function system_reboot() {
1315
	global $g;
1316

    
1317
	system_reboot_cleanup();
1318

    
1319
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1320
}
1321

    
1322
function system_reboot_sync() {
1323
	global $g;
1324

    
1325
	system_reboot_cleanup();
1326

    
1327
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1328
}
1329

    
1330
function system_reboot_cleanup() {
1331
	mwexec("/usr/local/bin/beep.sh stop");
1332
	require_once("captiveportal.inc");
1333
	captiveportal_radius_stop_all();
1334
	require_once("voucher.inc");
1335
	voucher_save_db_to_config();
1336
	mwexec("/etc/rc.stop_packages");
1337
}
1338

    
1339
function system_do_shell_commands($early = 0) {
1340
	global $config, $g;
1341
	if(isset($config['system']['developerspew'])) {
1342
		$mt = microtime();
1343
		echo "system_do_shell_commands() being called $mt\n";
1344
	}
1345

    
1346
	if ($early)
1347
		$cmdn = "earlyshellcmd";
1348
	else
1349
		$cmdn = "shellcmd";
1350

    
1351
	if (is_array($config['system'][$cmdn])) {
1352

    
1353
		/* *cmd is an array, loop through */
1354
		foreach ($config['system'][$cmdn] as $cmd) {
1355
			exec($cmd);
1356
		}
1357

    
1358
	} elseif($config['system'][$cmdn] <> "") {
1359

    
1360
		/* execute single item */
1361
		exec($config['system'][$cmdn]);
1362

    
1363
	}
1364
}
1365

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

    
1373
	if (isset($config['system']['disableconsolemenu'])) {
1374
		touch("{$g['varetc_path']}/disableconsole");
1375
	} else {
1376
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1377
	}
1378
}
1379

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

    
1387
	$dmesg = "";
1388
	exec("/sbin/dmesg", $dmesg);
1389

    
1390
	/* find last copyright line (output from previous boots may be present) */
1391
	$lastcpline = 0;
1392

    
1393
	for ($i = 0; $i < count($dmesg); $i++) {
1394
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1395
			$lastcpline = $i;
1396
	}
1397

    
1398
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1399
	if (!$fd) {
1400
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1401
		return 1;
1402
	}
1403

    
1404
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1405
		fwrite($fd, $dmesg[$i] . "\n");
1406

    
1407
	fclose($fd);
1408

    
1409
	return 0;
1410
}
1411

    
1412
function system_set_harddisk_standby() {
1413
	global $g, $config;
1414
	if(isset($config['system']['developerspew'])) {
1415
		$mt = microtime();
1416
		echo "system_set_harddisk_standby() being called $mt\n";
1417
	}
1418

    
1419
	if (isset($config['system']['harddiskstandby'])) {
1420
		if ($g['booting']) {
1421
			echo gettext('Setting hard disk standby... ');
1422
		}
1423

    
1424
		$standby = $config['system']['harddiskstandby'];
1425
		// Check for a numeric value
1426
		if (is_numeric($standby)) {
1427
			// Sync the disk(s)
1428
			pfSense_sync();
1429
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1430
				// Reinitialize ATA-drives
1431
				mwexec('/usr/local/sbin/atareinit');
1432
				if ($g['booting']) {
1433
					echo gettext("done.") . "\n";
1434
				}
1435
			} else if ($g['booting']) {
1436
				echo gettext("failed!") . "\n";
1437
			}
1438
		} else if ($g['booting']) {
1439
			echo gettext("failed!") . "\n";
1440
		}
1441
	}
1442
}
1443

    
1444
function system_setup_sysctl() {
1445
	global $config;
1446
	if(isset($config['system']['developerspew'])) {
1447
		$mt = microtime();
1448
		echo "system_setup_sysctl() being called $mt\n";
1449
	}
1450

    
1451
	activate_sysctls();	
1452

    
1453
	if (isset($config['system']['sharednet'])) {
1454
		system_disable_arp_wrong_if();
1455
	}
1456
}
1457

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

    
1468
function system_enable_arp_wrong_if() {
1469
	global $config;
1470
	if(isset($config['system']['developerspew'])) {
1471
		$mt = microtime();
1472
		echo "system_enable_arp_wrong_if() being called $mt\n";
1473
	}
1474
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1475
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1476
}
1477

    
1478
function enable_watchdog() {
1479
	global $config;
1480
	return;
1481
	$install_watchdog = false;
1482
	$supported_watchdogs = array("Geode");
1483
	$file = file_get_contents("/var/log/dmesg.boot");
1484
	foreach($supported_watchdogs as $sd) {
1485
		if(stristr($file, "Geode")) {
1486
			$install_watchdog = true;
1487
		}
1488
	}
1489
	if($install_watchdog == true) {
1490
		if(is_process_running("watchdogd"))
1491
			mwexec("/usr/bin/killall watchdogd", true);
1492
		exec("/usr/sbin/watchdogd");
1493
	}
1494
}
1495

    
1496
function system_check_reset_button() {
1497
	global $g;
1498
	if($g['platform'] != "nanobsd")
1499
		return 0;
1500

    
1501
	$specplatform = system_identify_specific_platform();
1502

    
1503
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1504
		return 0;
1505

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

    
1508
	if ($retval == 99) {
1509
		/* user has pressed reset button for 2 seconds - 
1510
		   reset to factory defaults */
1511
		echo <<<EOD
1512

    
1513
***********************************************************************
1514
* Reset button pressed - resetting configuration to factory defaults. *
1515
* The system will reboot after this completes.                        *
1516
***********************************************************************
1517

    
1518

    
1519
EOD;
1520
		
1521
		reset_factory_defaults();
1522
		system_reboot_sync();
1523
		exit(0);
1524
	}
1525

    
1526
	return 0;
1527
}
1528

    
1529
/* attempt to identify the specific platform (for embedded systems)
1530
   Returns an array with two elements:
1531
	name => platform string (e.g. 'wrap', 'alix' etc.)
1532
	descr => human-readable description (e.g. "PC Engines WRAP")
1533
*/
1534
function system_identify_specific_platform() {
1535
	global $g;
1536
	
1537
	if ($g['platform'] == 'generic-pc')
1538
		return array('name' => 'generic-pc', 'descr' => gettext("Generic PC"));
1539
	
1540
	if ($g['platform'] == 'generic-pc-cdrom')
1541
		return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)"));
1542
	
1543
	/* the rest of the code only deals with 'embedded' platforms */
1544
	if ($g['platform'] != 'nanobsd')
1545
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1546
	
1547
	$dmesg = system_get_dmesg_boot();
1548
	
1549
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1550
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
1551
	
1552
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1553
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
1554

    
1555
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1556
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1557
	
1558
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1559
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1560
		
1561
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1562
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1563
	
1564
	/* unknown embedded platform */
1565
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
1566
}
1567

    
1568
function system_get_dmesg_boot() {
1569
	global $g;
1570
		
1571
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1572
}
1573

    
1574
function get_possible_listen_ips() {
1575
	$interfaces = get_configured_interface_with_descr();
1576
	$carplist = get_configured_carp_interface_list();
1577
	$listenips = array();
1578
	foreach ($carplist as $cif => $carpip)
1579
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1580
	$aliaslist = get_configured_ip_aliases_list();
1581
	foreach ($aliaslist as $aliasip => $aliasif)
1582
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1583
	foreach ($interfaces as $iface => $ifacename) {
1584
		$tmp["name"]  = $ifacename;
1585
		$tmp["value"] = $iface;
1586
		$listenips[] = $tmp;
1587
	}
1588
	$tmp["name"]  = "Localhost";
1589
	$tmp["value"] = "lo0";
1590
	$listenips[] = $tmp;
1591
	return $listenips;
1592
}
1593

    
1594
?>
(50-50/65)