Project

General

Profile

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
160
	unlock($dnslock);
161

    
162
	return 0;
163
}
164

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

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

    
184
	return $master_list;
185
}
186

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

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

    
215
	return $master_list;
216
}
217

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

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

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

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

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

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

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

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

    
289
	system_dhcpleases_configure();
290

    
291
	return 0;
292
}
293

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

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

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

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

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

    
329
	return $status;
330
}
331

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

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

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

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

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

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

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

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

    
455
	return 0;
456
}
457

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

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

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

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

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

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

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

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

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

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

    
624
EOD;
625

    
626
}
627

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

    
637
EOD;
638

    
639
}
640

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

    
650
EOD;
651

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

    
658
EOD;
659

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

    
664
EOD;
665

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

    
670
EOD;
671

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

    
677
EOD;
678
		}
679
		fwrite($fd, $syslogconf);
680
		fclose($fd);
681

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

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

    
692
	} else {
693
		$retval = mwexec("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log");
694
	}
695

    
696
	if ($g['booting'])
697
		echo gettext("done.") . "\n";
698

    
699
	return $retval;
700
}
701

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

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

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

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

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

    
725
	return $res;
726
}
727

    
728

    
729
function system_webgui_start() {
730
	global $config, $g;
731

    
732
	if ($g['booting'])
733
		echo gettext("Starting webConfigurator...");
734

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

    
738
	sleep(1);
739

    
740
	chdir($g['www_path']);
741

    
742
	/* defaults */
743
	$portarg = "80";
744
	$crt = "";
745
	$key = "";
746
	$ca = "";
747

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

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

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

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

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

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

    
810
	return $res;
811
}
812

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

    
827
	global $config, $g;
828

    
829
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
830
		mkdir("{$g['tmp_path']}/lighttpdcompress");
831

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

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

    
864
	$memory = get_memory();
865
	$avail = $memory[0];
866

    
867
	if($avail > 0 and $avail < 65) {
868
		$fast_cgi_enable = false;
869
	}
870

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

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

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

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

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

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

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

    
949
EOD;
950
	}
951

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1074

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

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

    
1079
EOD;
1080

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

    
1111

    
1112
	$lighty_config .= <<<EOD
1113

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

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

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

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

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

    
1134
{$server_upload_dirs}
1135

    
1136
{$server_max_request_size}
1137

    
1138
{$fastcgi_config}
1139

    
1140
{$cgi_config}
1141

    
1142
{$captive_portal_mod_evasive}
1143

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

    
1148
EOD;
1149

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

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

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

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

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

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

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

    
1213
	return 0;
1214

    
1215
}
1216

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

    
1224
	$syscfg = $config['system'];
1225

    
1226
	if ($g['booting'])
1227
		echo gettext("Setting timezone...");
1228

    
1229
	/* extract appropriate timezone file */
1230
	$timezone = $syscfg['timezone'];
1231
	if (!$timezone)
1232
		$timezone = "Etc/UTC";
1233

    
1234
	conf_mount_rw();
1235

    
1236
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1237
		escapeshellarg($timezone) . " > /etc/localtime");
1238

    
1239
	mwexec("sync");
1240
	conf_mount_ro();
1241

    
1242
	if ($g['booting'])
1243
		echo gettext("done.") . "\n";
1244
}
1245

    
1246
function system_ntp_configure() {
1247
	global $config, $g;
1248

    
1249
	if ($g['platform'] == 'jail')
1250
		return;
1251

    
1252
	$ntpcfg = "# \n";
1253
	$ntpcfg .= "# pfSense OpenNTPD configuration file \n";
1254
	$ntpcfg .= "# \n\n";
1255

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

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

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

    
1292
	/* slurp! */
1293
	fclose($fd);
1294

    
1295
	/* if openntpd is running, kill it */
1296
	while(is_process_running("ntpd")) {
1297
		killbyname("ntpd");
1298
	}
1299

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

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

    
1310
}
1311

    
1312
function sync_system_time() {
1313
	global $config, $g;
1314

    
1315
	if ($g['booting'])
1316
		echo gettext("Syncing system time before startup...");
1317

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

    
1328
function system_halt() {
1329
	global $g;
1330

    
1331
	system_reboot_cleanup();
1332

    
1333
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1334
}
1335

    
1336
function system_reboot() {
1337
	global $g;
1338

    
1339
	system_reboot_cleanup();
1340

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

    
1344
function system_reboot_sync() {
1345
	global $g;
1346

    
1347
	system_reboot_cleanup();
1348

    
1349
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1350
}
1351

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

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

    
1368
	if ($early)
1369
		$cmdn = "earlyshellcmd";
1370
	else
1371
		$cmdn = "shellcmd";
1372

    
1373
	if (is_array($config['system'][$cmdn])) {
1374

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

    
1380
	} elseif($config['system'][$cmdn] <> "") {
1381

    
1382
		/* execute single item */
1383
		exec($config['system'][$cmdn]);
1384

    
1385
	}
1386
}
1387

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

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

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

    
1409
	$dmesg = "";
1410
	exec("/sbin/dmesg", $dmesg);
1411

    
1412
	/* find last copyright line (output from previous boots may be present) */
1413
	$lastcpline = 0;
1414

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

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

    
1426
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1427
		fwrite($fd, $dmesg[$i] . "\n");
1428

    
1429
	fclose($fd);
1430

    
1431
	return 0;
1432
}
1433

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

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

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

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

    
1473
	activate_sysctls();	
1474

    
1475
	if (isset($config['system']['sharednet'])) {
1476
		system_disable_arp_wrong_if();
1477
	}
1478
}
1479

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

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

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

    
1518
function system_check_reset_button() {
1519
	global $g;
1520
	if($g['platform'] != "nanobsd")
1521
		return 0;
1522

    
1523
	$specplatform = system_identify_specific_platform();
1524

    
1525
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1526
		return 0;
1527

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

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

    
1535
***********************************************************************
1536
* Reset button pressed - resetting configuration to factory defaults. *
1537
* The system will reboot after this completes.                        *
1538
***********************************************************************
1539

    
1540

    
1541
EOD;
1542
		
1543
		reset_factory_defaults();
1544
		system_reboot_sync();
1545
		exit(0);
1546
	}
1547

    
1548
	return 0;
1549
}
1550

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

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

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

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