Project

General

Profile

Download (47.6 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
			log_error("ROUTING: setting IPv6 default route to {$gatewayipv6}%{$defaultifv6}");
418
			mwexec("/sbin/route change -inet6 default " . escapeshellarg($gatewayipv6) ."%". escapeshellarg($defaultifv6));
419
		}
420
	}
421

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

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

    
435
			$gatewayip = $gateway['gateway'];
436
			$interfacegw = $gateway['interface'];
437

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

    
453
	return 0;
454
}
455

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

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

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

    
475
	mwexec("/etc/rc.d/hostid start");
476

    
477
	$syslogcfg = $config['syslog'];
478

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

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

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

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

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

    
622
EOD;
623

    
624
}
625

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

    
635
EOD;
636

    
637
}
638

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

    
648
EOD;
649

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

    
656
EOD;
657

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

    
662
EOD;
663

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

    
668
EOD;
669

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

    
675
EOD;
676
		}
677
		fwrite($fd, $syslogconf);
678
		fclose($fd);
679

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

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

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

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

    
697
	return $retval;
698
}
699

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

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

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

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

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

    
723
	return $res;
724
}
725

    
726

    
727
function system_webgui_start() {
728
	global $config, $g;
729

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

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

    
736
	sleep(1);
737

    
738
	chdir($g['www_path']);
739

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

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

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

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

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

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

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

    
808
	return $res;
809
}
810

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

    
825
	global $config, $g;
826

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

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

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

    
862
	$memory = get_memory();
863
	$avail = $memory[0];
864

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

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

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

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

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

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

    
931
#### CGI module
932
cgi.assign                 = ( ".cgi" => "" )
933

    
934
EOD;
935
	} else {
936
		$fastcgi_config = "";
937
		$module = "\"mod_cgi\"";
938
		$cgi_config = <<<EOD
939
#### CGI module
940
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
941
                               ".cgi" => "" )
942

    
943
EOD;
944
	}
945

    
946
	$lighty_config = "";
947
	$lighty_config .= <<<EOD
948
#
949
# lighttpd configuration file
950
#
951
# use a it as base for lighttpd 1.0.0 and above
952
#
953
############ Options you really have to take care of ####################
954

    
955
## FreeBSD!
956
server.event-handler	= "freebsd-kqueue"
957
server.network-backend 	= "writev"
958
#server.use-ipv6 = "enable"
959

    
960
## modules to load
961
server.modules              =   (
962
	{$captive_portal_module}
963
	"mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect",
964
	{$module}{$captiveportal}
965
)
966

    
967
## Unused modules
968
#                               "mod_setenv",
969
#                               "mod_rewrite",
970
#                               "mod_ssi",
971
#                               "mod_usertrack",
972
#                               "mod_expire",
973
#                               "mod_secdownload",
974
#                               "mod_rrdtool",
975
#                               "mod_auth",
976
#                               "mod_status",
977
#                               "mod_alias",
978
#                               "mod_proxy",
979
#                               "mod_simple_vhost",
980
#                               "mod_evhost",
981
#                               "mod_userdir",
982
#                               "mod_cgi",
983

    
984
server.max-keep-alive-requests = 15
985
server.max-keep-alive-idle = 30
986

    
987
## a static document-root, for virtual-hosting take look at the
988
## server.virtual-* options
989
server.document-root        = "{$document_root}"
990
{$captive_portal_rewrite}
991

    
992
# Maximum idle time with nothing being written (php downloading)
993
server.max-write-idle = 999
994

    
995
## where to send error-messages to
996
server.errorlog             = "/var/log/lighttpd.error.log"
997

    
998
# files to check for if .../ is requested
999
server.indexfiles           = ( "index.php", "index.html",
1000
                                "index.htm", "default.htm" )
1001

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

    
1055
# Use the "Content-Type" extended attribute to obtain mime type if possible
1056
#mimetypes.use-xattr        = "enable"
1057

    
1058
#### accesslog module
1059
#accesslog.filename          = "/dev/null"
1060

    
1061
## deny access the file-extensions
1062
#
1063
# ~    is for backupfiles from vi, emacs, joe, ...
1064
# .inc is often used for code includes which should in general not be part
1065
#      of the document-root
1066
url.access-deny             = ( "~", ".inc" )
1067

    
1068

    
1069
######### Options that are good to be but not neccesary to be changed #######
1070

    
1071
## bind to port (default: 80)
1072

    
1073
EOD;
1074

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

    
1105

    
1106
	$lighty_config .= <<<EOD
1107

    
1108
## error-handler for status 404
1109
#server.error-handler-404   = "/error-handler.html"
1110
#server.error-handler-404   = "/error-handler.php"
1111

    
1112
## to help the rc.scripts
1113
server.pid-file            = "/var/run/{$pid_file}"
1114

    
1115
## virtual directory listings
1116
server.dir-listing         = "disable"
1117

    
1118
## enable debugging
1119
debug.log-request-header   = "disable"
1120
debug.log-response-header  = "disable"
1121
debug.log-request-handling = "disable"
1122
debug.log-file-not-found   = "disable"
1123

    
1124
# gzip compression
1125
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1126
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1127

    
1128
{$server_upload_dirs}
1129

    
1130
{$server_max_request_size}
1131

    
1132
{$fastcgi_config}
1133

    
1134
{$cgi_config}
1135

    
1136
{$captive_portal_mod_evasive}
1137

    
1138
expire.url = (
1139
				"" => "access 50 hours",	
1140
        )
1141

    
1142
EOD;
1143

    
1144
	$cert = str_replace("\r", "", $cert);
1145
	$key = str_replace("\r", "", $key);
1146
	$ca = str_replace("\r", "", $ca);
1147

    
1148
	$cert = str_replace("\n\n", "\n", $cert);
1149
	$key = str_replace("\n\n", "\n", $key);
1150
	$ca = str_replace("\n\n", "\n", $ca);
1151

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

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

    
1182
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1183
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1184
	}
1185

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

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

    
1207
	return 0;
1208

    
1209
}
1210

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

    
1218
	$syscfg = $config['system'];
1219

    
1220
	if ($g['booting'])
1221
		echo gettext("Setting timezone...");
1222

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

    
1228
	conf_mount_rw();
1229

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

    
1233
	mwexec("sync");
1234
	conf_mount_ro();
1235

    
1236
	if ($g['booting'])
1237
		echo gettext("done.") . "\n";
1238
}
1239

    
1240
function system_ntp_configure() {
1241
	global $config, $g;
1242

    
1243
	if ($g['platform'] == 'jail')
1244
		return;
1245

    
1246
	$ntpcfg = "# \n";
1247
	$ntpcfg .= "# pfSense OpenNTPD configuration file \n";
1248
	$ntpcfg .= "# \n\n";
1249

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

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

    
1278
	/* open configuration for wrting or bail */
1279
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1280
	if(!$fd) {
1281
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1282
		return;
1283
	}
1284
	fwrite($fd, $ntpcfg);
1285

    
1286
	/* slurp! */
1287
	fclose($fd);
1288

    
1289
	/* if openntpd is running, kill it */
1290
	while(is_process_running("ntpd")) {
1291
		killbyname("ntpd");
1292
	}
1293

    
1294
	/* if /var/empty does not exist, create it */
1295
	if(!is_dir("/var/empty"))
1296
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1297

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

    
1304
}
1305

    
1306
function sync_system_time() {
1307
	global $config, $g;
1308

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

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

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

    
1325
	system_reboot_cleanup();
1326

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

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

    
1333
	system_reboot_cleanup();
1334

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

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

    
1341
	system_reboot_cleanup();
1342

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

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

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

    
1362
	if ($early)
1363
		$cmdn = "earlyshellcmd";
1364
	else
1365
		$cmdn = "shellcmd";
1366

    
1367
	if (is_array($config['system'][$cmdn])) {
1368

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

    
1374
	} elseif($config['system'][$cmdn] <> "") {
1375

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

    
1379
	}
1380
}
1381

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

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

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

    
1403
	$dmesg = "";
1404
	exec("/sbin/dmesg", $dmesg);
1405

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

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

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

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

    
1423
	fclose($fd);
1424

    
1425
	return 0;
1426
}
1427

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

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

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

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

    
1467
	activate_sysctls();	
1468

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

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

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

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

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

    
1517
	$specplatform = system_identify_specific_platform();
1518

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

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

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

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

    
1534

    
1535
EOD;
1536
		
1537
		reset_factory_defaults();
1538
		system_reboot_sync();
1539
		exit(0);
1540
	}
1541

    
1542
	return 0;
1543
}
1544

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

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

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

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