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
	if (is_array($config['staticroutes']['route'])) {
431
		$gateways_arr = return_gateways_array();
432

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

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

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

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

    
466
	return 0;
467
}
468

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
676
	return $retval;
677
}
678

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

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

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

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

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

    
702
	return $res;
703
}
704

    
705

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

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

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

    
715
	sleep(1);
716

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

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

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

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

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

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

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

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

    
787
	return $res;
788
}
789

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

    
804
	global $config, $g;
805

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

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

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

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

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

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

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

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

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

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

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

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

    
926
EOD;
927
	}
928

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1051

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

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

    
1056
EOD;
1057

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

    
1088

    
1089
	$lighty_config .= <<<EOD
1090

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

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

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

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

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

    
1111
{$server_upload_dirs}
1112

    
1113
{$server_max_request_size}
1114

    
1115
{$fastcgi_config}
1116

    
1117
{$cgi_config}
1118

    
1119
{$captive_portal_mod_evasive}
1120

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

    
1125
EOD;
1126

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

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

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

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

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

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

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

    
1190
	return 0;
1191

    
1192
}
1193

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

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

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

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

    
1211
	conf_mount_rw();
1212

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1287
}
1288

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

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

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

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

    
1308
	system_reboot_cleanup();
1309

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

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

    
1316
	system_reboot_cleanup();
1317

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

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

    
1324
	system_reboot_cleanup();
1325

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

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

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

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

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

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

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

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

    
1362
	}
1363
}
1364

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

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

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

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

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

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

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

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

    
1406
	fclose($fd);
1407

    
1408
	return 0;
1409
}
1410

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

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

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

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

    
1450
	activate_sysctls();	
1451

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

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

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

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

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

    
1500
	$specplatform = system_identify_specific_platform();
1501

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

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

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

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

    
1517

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

    
1525
	return 0;
1526
}
1527

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

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

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

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

    
1593
?>
(50-50/65)