Project

General

Profile

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
89
	// Do not create blank domain lines, it breaks tools like dig.
90
	if($syscfg['domain'])
91
		$resolvconf = "domain {$syscfg['domain']}\n";
92

    
93
	$havedns = false;
94

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

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

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

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

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

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

    
157
	unlock($dnslock);
158

    
159
	return 0;
160
}
161

    
162
function get_searchdomains() {
163
	global $config, $g;
164

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

    
181
	return $master_list;
182
}
183

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

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

    
212
	return $master_list;
213
}
214

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

    
222
	$syscfg = $config['system'];
223
	$dnsmasqcfg = $config['dnsmasq'];
224

    
225
	if (!is_array($dnsmasqcfg['hosts'])) {
226
		$dnsmasqcfg['hosts'] = array();
227
	}
228
	$hostscfg = $dnsmasqcfg['hosts'];
229

    
230
	$hosts = "127.0.0.1	localhost localhost.{$syscfg['domain']}\n";
231
	$lhosts = "";
232
	$dhosts = "";
233

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

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

    
265
	if (isset($dnsmasqcfg['dhcpfirst']))
266
		$hosts .= $dhosts . $lhosts;
267
	else
268
		$hosts .= $lhosts . $dhosts;
269

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

    
286
	system_dhcpleases_configure();
287

    
288
	return 0;
289
}
290

    
291
function system_dhcpleases_configure() {
292
	global $config, $g;
293
	
294
	/* Start the monitoring process for dynamic dhcpclients. */
295
	if (isset($config['dnsmasq']['regdhcp'])) {
296
		/* Make sure we do not error out */
297
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
298
		if (file_exists("{$g['varrun_path']}/dhcpleases.pid"))
299
				sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "HUP");
300
		else
301
			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");
302
	} else {
303
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
304
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
305
	}
306
}
307

    
308
function system_hostname_configure() {
309
	global $config, $g;
310
	if(isset($config['system']['developerspew'])) {
311
		$mt = microtime();
312
		echo "system_hostname_configure() being called $mt\n";
313
	}
314

    
315
	$syscfg = $config['system'];
316

    
317
	/* set hostname */
318
	$status = mwexec("/bin/hostname " .
319
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
320

    
321
    /* Setup host GUID ID.  This is used by ZFS. */
322
	mwexec("/etc/rc.d/hostid start");
323

    
324
	return $status;
325
}
326

    
327
function system_routing_configure($interface = "") {
328
	global $config, $g;
329
	if(isset($config['system']['developerspew'])) {
330
		$mt = microtime();
331
		echo "system_routing_configure() being called $mt\n";
332
	}
333

    
334
	/* configure gif interfaces for ipv6 tunnels */
335
	// interfaces_gif_configure();
336

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

    
413
	if ($dont_add_route == false ) {
414
		if (!empty($interface) && $interface != $interfacegw)
415
			;
416
		else if (($interfacegw <> "bgpd") && (is_ipaddrv4($gatewayip))) {
417
			$action = "add";
418
			if(isset($route_arr['default'])) {
419
				$action = "change";
420
			}
421
			log_error("ROUTING: $action default route to $gatewayip");
422
			mwexec("/sbin/route {$action} -inet default " . escapeshellarg($gatewayip));
423
		}
424
	}
425

    
426
	/* Create a array from the existing inet6 route table */
427
	exec("/usr/bin/netstat -rnf inet6", $routev6_str);
428
	array_shift($routev6_str);
429
	array_shift($routev6_str);
430
	array_shift($routev6_str);
431
	array_shift($routev6_str);
432
	$routev6_arr = array();
433
	foreach($routev6_str as $routeline) {
434
		$items = preg_split("/[ ]+/i", $routeline);
435
		$routev6_arr[$items[0]] = array($items[0], $items[1], $items[5]);
436
	}
437

    
438
	if ($dont_add_route == false ) {
439
		if (!empty($interface) && $interface != $interfacegwv6)
440
			;
441
		else if (($interfacegwv6 <> "bgpd") && (is_ipaddrv6($gatewayipv6))) {
442
			$action = "add";
443
			if(isset($routev6_arr['default'])) {
444
				$action = "change";
445
			}
446
			log_error("ROUTING: $action IPv6 default route to $gatewayipv6");
447
			mwexec("/sbin/route {$action} -inet6 default " . escapeshellarg($gatewayipv6));
448
		}
449
	}
450

    
451
	if (is_array($config['staticroutes']['route'])) {
452
		$gateways_arr = return_gateways_array();
453

    
454
		foreach ($config['staticroutes']['route'] as $rtent) {
455
			$gatewayip = "";
456
			if (empty($gateways_arr[$rtent['gateway']])) {
457
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
458
				continue;
459
			}
460
			$gateway = $gateways_arr[$rtent['gateway']];
461
			if (!empty($interface) && $interface != $gateway['friendlyiface'])
462
				continue;
463

    
464
			$gatewayip = $gateway['gateway'];
465
			$interfacegw = $gateway['interface'];
466
			$action = "add";
467
			if (isset($route_arr[$rtent['network']]))
468
				$action = "change";
469

    
470
			if(is_ipaddrv6($gatewayip)) {
471
				$inetfamily = "-inet6";
472
			} else {
473
				$inetfamily = "-inet";
474
			}
475
			if (is_ipaddr($gatewayip)) {
476
				mwexec("/sbin/route {$action} {$inetfamily} " . escapeshellarg($rtent['network']) .
477
					" " . escapeshellarg($gatewayip));
478
			} else if (!empty($interfacegw)) {
479
				mwexec("/sbin/route {$action} {$inetfamily} " . escapeshellarg($rtent['network']) .
480
					" -iface " . escapeshellarg($interfacegw));
481
			}
482
		}
483
	}
484

    
485
	return 0;
486
}
487

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

    
495
	mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
496
	mwexec("/sbin/sysctl net.inet6.ip6.forwarding=1");
497
	return;
498
}
499

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

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

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

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

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

    
609
EOD;
610
		if (isset($syslogcfg['filter'])) {
611
			if($syslogcfg['remoteserver'])
612
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver']}\n";
613
			if($syslogcfg['remoteserver2'])
614
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver2']}\n";
615
			if($syslogcfg['remoteserver3'])
616
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver3']}\n";
617

    
618
		}
619
		if (isset($syslogcfg['vpn'])) {
620
			if($syslogcfg['remoteserver'])
621
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver']}\n";
622
			if($syslogcfg['remoteserver2'])
623
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver2']}\n";
624
			if($syslogcfg['remoteserver3'])
625
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver3']}\n";
626
		}
627
		if (isset($syslogcfg['portalauth'])) {
628
			if($syslogcfg['remoteserver'])
629
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver']}\n";
630
			if($syslogcfg['remoteserver2'])
631
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver2']}\n";
632
			if($syslogcfg['remoteserver3'])
633
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver3']}\n";
634
		}
635
		if (isset($syslogcfg['dhcp'])) {
636
			if($syslogcfg['remoteserver'])
637
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver']}\n";
638
			if($syslogcfg['remoteserver2'])
639
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver2']}\n";
640
			if($syslogcfg['remoteserver3'])
641
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver3']}\n";
642
		}
643
		if (isset($syslogcfg['system'])) {
644
			if($syslogcfg['remoteserver'])
645
				$syslogconf .= <<<EOD
646
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver']}
647
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver']}
648
security.*										 @{$syslogcfg['remoteserver']}
649
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver']}
650
*.emerg											 @{$syslogcfg['remoteserver']}
651

    
652
EOD;
653

    
654
}
655

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

    
665
EOD;
666

    
667
}
668

    
669
		if (isset($syslogcfg['system'])) {
670
			if($syslogcfg['remoteserver3'])
671
				$syslogconf .= <<<EOD
672
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver3']}
673
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver3']}
674
security.*										 @{$syslogcfg['remoteserver3']}
675
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver3']}
676
*.emerg											 @{$syslogcfg['remoteserver3']}
677

    
678
EOD;
679

    
680
}
681
		if (isset($syslogcfg['logall'])) {
682
			if($syslogcfg['remoteserver'])
683
				$syslogconf .= <<<EOD
684
*.*								@{$syslogcfg['remoteserver']}
685

    
686
EOD;
687

    
688
			if($syslogcfg['remoteserver2'])
689
				$syslogconf .= <<<EOD
690
*.*								@{$syslogcfg['remoteserver2']}
691

    
692
EOD;
693

    
694
			if($syslogcfg['remoteserver3'])
695
				$syslogconf .= <<<EOD
696
*.*								@{$syslogcfg['remoteserver3']}
697

    
698
EOD;
699

    
700
}
701
		if (isset($syslogcfg['zmqserver'])) {
702
				$syslogconf .= <<<EOD
703
*.*								^{$syslogcfg['zmqserver']}
704

    
705
EOD;
706
		}
707
		fwrite($fd, $syslogconf);
708
		fclose($fd);
709

    
710
		// Ensure that the log directory exists
711
		if(!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
712
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
713

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

    
720
	} else {
721
		$retval = mwexec("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log");
722
	}
723

    
724
	if ($g['booting'])
725
		echo gettext("done.") . "\n";
726

    
727
	return $retval;
728
}
729

    
730
function system_pccard_start() {
731
	global $config, $g;
732
	if(isset($config['system']['developerspew'])) {
733
		$mt = microtime();
734
		echo "system_pccard_start() being called $mt\n";
735
	}
736

    
737
	if ($g['booting'])
738
		echo gettext("Initializing PCMCIA...");
739

    
740
	/* kill any running pccardd */
741
	killbypid("{$g['varrun_path']}/pccardd.pid");
742

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

    
746
	if ($g['booting']) {
747
		if ($res == 0)
748
			echo gettext("done.") . "\n";
749
		else
750
			echo gettext("failed!") . "\n";
751
	}
752

    
753
	return $res;
754
}
755

    
756

    
757
function system_webgui_start() {
758
	global $config, $g;
759

    
760
	if ($g['booting'])
761
		echo gettext("Starting webConfigurator...");
762

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

    
766
	sleep(1);
767

    
768
	chdir($g['www_path']);
769

    
770
	/* defaults */
771
	$portarg = "80";
772
	$crt = "";
773
	$key = "";
774
	$ca = "";
775

    
776
	/* non-standard port? */
777
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
778
		$portarg = "{$config['system']['webgui']['port']}";
779

    
780
	if ($config['system']['webgui']['protocol'] == "https") {
781
		// Ensure that we have a webConfigurator CERT
782
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
783
		if(!is_array($cert) && !$cert['crt'] && !$cert['prv']) {
784
			if (!is_array($config['ca']))
785
				$config['ca'] = array();
786
			$a_ca =& $config['ca'];
787
			if (!is_array($config['cert']))
788
				$config['cert'] = array();
789
			$a_cert =& $config['cert'];
790
			log_error("Creating SSL Certificate for this host");
791
			$cert = array();
792
			$cert['refid'] = uniqid();
793
			$cert['descr'] = gettext("webConfigurator default");
794
			mwexec("/usr/bin/openssl genrsa 1024 > {$g['tmp_path']}/ssl.key");
795
			mwexec("/usr/bin/openssl req -new -x509 -nodes -sha1 -days 2000 -key {$g['tmp_path']}/ssl.key > {$g['tmp_path']}/ssl.crt");
796
			$crt = file_get_contents("{$g['tmp_path']}/ssl.crt");
797
			$key = file_get_contents("{$g['tmp_path']}/ssl.key");
798
			unlink("{$g['tmp_path']}/ssl.key");
799
			unlink("{$g['tmp_path']}/ssl.crt");
800
			cert_import($cert, $crt, $key);
801
			$a_cert[] = $cert;
802
			$config['system']['webgui']['ssl-certref'] = $cert['refid'];
803
			write_config(gettext("Importing HTTPS certificate"));
804
			if(!$config['system']['webgui']['port'])
805
				$portarg = "443";
806
			$ca = ca_chain($cert);
807
		} else {
808
			$crt = base64_decode($cert['crt']);
809
			$key = base64_decode($cert['prv']);
810
			if(!$config['system']['webgui']['port'])
811
				$portarg = "443";
812
			$ca = ca_chain($cert);
813
		}
814
	}
815

    
816
	/* generate lighttpd configuration */
817
	$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
818
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
819
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
820
		"cert.pem", "ca.pem", $max_procs);
821

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

    
825
	/* fetch page to preload apc cache */
826
	$proto = "http";
827
	if ($config['system']['webgui']['protocol'])
828
		$proto = $config['system']['webgui']['protocol'];
829
	mwexec_bg("/usr/bin/fetch -o /dev/null -q {$proto}://localhost:{$portarg}/preload.php");
830

    
831
	if ($g['booting']) {
832
		if ($res == 0)
833
			echo gettext("done.") . "\n";
834
		else
835
			echo gettext("failed!") . "\n";
836
	}
837

    
838
	return $res;
839
}
840

    
841
function system_generate_lighty_config($filename,
842
	$cert,
843
	$key,
844
	$ca,
845
	$pid_file,
846
	$port = 80,
847
	$document_root = "/usr/local/www/",
848
	$cert_location = "cert.pem",
849
	$ca_location = "ca.pem",
850
	$max_procs = 2,
851
	$max_requests = "2",
852
	$fast_cgi_enable = true,
853
	$captive_portal = false) {
854

    
855
	global $config, $g;
856

    
857
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
858
		mkdir("{$g['tmp_path']}/lighttpdcompress");
859

    
860
	if(isset($config['system']['developerspew'])) {
861
		$mt = microtime();
862
		echo "system_generate_lighty_config() being called $mt\n";
863
	}
864

    
865
	if($captive_portal == true)  {
866
		$captiveportal = ",\"mod_rewrite\"";
867
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?redirurl=$1\" )\n";
868
		$captive_portal_module = "";
869
		$maxprocperip = $config['captiveportal']['maxprocperip'];
870
		if(!$maxprocperip and $maxprocperip > 0)
871
			$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
872
		else
873
			$captive_portal_mod_evasive = "";
874
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
875
		exec("mkdir -p {$g['tmp_path']}/captiveportal");
876
		exec("chmod a-w {$g['tmp_path']}/captiveportal");
877
		$server_max_request_size = "server.max-request-size    = 384";
878
	} else {
879
		$captiveportal = "";
880
		$captive_portal_rewrite = "";
881
		$captive_portal_module = "";
882
		$captive_portal_mod_evasive = "";
883
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
884
		$server_max_request_size = "server.max-request-size    = 2097152";
885
	}
886
	
887
	if($port <> "")
888
		$lighty_port = $port;
889
	else
890
		$lighty_port = "80";
891

    
892
	$memory = get_memory();
893
	$avail = $memory[0];
894

    
895
	if($avail > 0 and $avail < 65) {
896
		$fast_cgi_enable = false;
897
	}
898

    
899
	// Ramp up captive portal max procs
900
	//  Work relative to the default of 2, for values that would be >2.
901
	if($captive_portal == true)  {
902
		if($avail > 65 and $avail < 98) {
903
			$max_procs = 1;
904
		}
905
		if($avail > 97 and $avail < 128) {
906
			$max_procs = 2;
907
		}
908
		if($avail > 127 and $avail < 256) {
909
			$max_procs += 1;
910
		}
911
		if($avail > 255 and $avail < 384) {
912
			$max_procs += 2;
913
		}
914
		if($avail > 383) {
915
			$max_procs += 3;
916
		}
917
	}
918

    
919
	if($captive_portal == true)  {	
920
		$bin_environment =  <<<EOC
921
			"bin-environment" => (
922
				"PHP_FCGI_CHILDREN" => "$max_procs",
923
				"PHP_FCGI_MAX_REQUESTS" => "500"
924
			),
925
EOC;
926

    
927
	} else if ($avail > 0 and $avail < 128) {
928
		$bin_environment = <<<EOC
929
			"bin-environment" => (
930
				"PHP_FCGI_CHILDREN" => "$max_procs",
931
				"PHP_FCGI_MAX_REQUESTS" => "2",
932
			),
933

    
934
EOC;
935
	} else
936
		$bin_environment =  <<<EOC
937
			"bin-environment" => (
938
				"PHP_FCGI_CHILDREN" => "$max_procs",
939
				"PHP_FCGI_MAX_REQUESTS" => "500"
940
			),
941
EOC;
942

    
943
	if($fast_cgi_enable == true) {
944
		$module = "\"mod_fastcgi\", \"mod_cgi\"";
945
		$cgi_config = "";
946
		$fastcgi_config = <<<EOD
947
#### fastcgi module
948
## read fastcgi.txt for more info
949
fastcgi.server = ( ".php" =>
950
	( "localhost" =>
951
		(
952
			"socket" => "{$g['tmp_path']}/php-fastcgi.socket",
953
			"min-procs" => 0,
954
			"max-procs" => {$max_procs},
955
{$bin_environment}
956
			"bin-path" => "/usr/local/bin/php"
957
		)
958
	)
959
)
960

    
961
#### CGI module
962
cgi.assign                 = ( ".cgi" => "" )
963

    
964
EOD;
965
	} else {
966
		$fastcgi_config = "";
967
		$module = "\"mod_cgi\"";
968
		$cgi_config = <<<EOD
969
#### CGI module
970
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
971
                               ".cgi" => "" )
972

    
973
EOD;
974
	}
975

    
976
	$lighty_config = "";
977
	$lighty_config .= <<<EOD
978
#
979
# lighttpd configuration file
980
#
981
# use a it as base for lighttpd 1.0.0 and above
982
#
983
############ Options you really have to take care of ####################
984

    
985
## FreeBSD!
986
server.event-handler	= "freebsd-kqueue"
987
server.network-backend 	= "writev"
988
#server.use-ipv6 = "enable"
989

    
990
## modules to load
991
server.modules              =   (
992
	{$captive_portal_module}
993
	"mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect",
994
	{$module}{$captiveportal}
995
)
996

    
997
## Unused modules
998
#                               "mod_setenv",
999
#                               "mod_rewrite",
1000
#                               "mod_ssi",
1001
#                               "mod_usertrack",
1002
#                               "mod_expire",
1003
#                               "mod_secdownload",
1004
#                               "mod_rrdtool",
1005
#                               "mod_auth",
1006
#                               "mod_status",
1007
#                               "mod_alias",
1008
#                               "mod_proxy",
1009
#                               "mod_simple_vhost",
1010
#                               "mod_evhost",
1011
#                               "mod_userdir",
1012
#                               "mod_cgi",
1013

    
1014
server.max-keep-alive-requests = 15
1015
server.max-keep-alive-idle = 30
1016

    
1017
## a static document-root, for virtual-hosting take look at the
1018
## server.virtual-* options
1019
server.document-root        = "{$document_root}"
1020
{$captive_portal_rewrite}
1021

    
1022
# Maximum idle time with nothing being written (php downloading)
1023
server.max-write-idle = 999
1024

    
1025
## where to send error-messages to
1026
server.errorlog             = "/var/log/lighttpd.error.log"
1027

    
1028
# files to check for if .../ is requested
1029
server.indexfiles           = ( "index.php", "index.html",
1030
                                "index.htm", "default.htm" )
1031

    
1032
# mimetype mapping
1033
mimetype.assign             = (
1034
  ".pdf"          =>      "application/pdf",
1035
  ".sig"          =>      "application/pgp-signature",
1036
  ".spl"          =>      "application/futuresplash",
1037
  ".class"        =>      "application/octet-stream",
1038
  ".ps"           =>      "application/postscript",
1039
  ".torrent"      =>      "application/x-bittorrent",
1040
  ".dvi"          =>      "application/x-dvi",
1041
  ".gz"           =>      "application/x-gzip",
1042
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
1043
  ".swf"          =>      "application/x-shockwave-flash",
1044
  ".tar.gz"       =>      "application/x-tgz",
1045
  ".tgz"          =>      "application/x-tgz",
1046
  ".tar"          =>      "application/x-tar",
1047
  ".zip"          =>      "application/zip",
1048
  ".mp3"          =>      "audio/mpeg",
1049
  ".m3u"          =>      "audio/x-mpegurl",
1050
  ".wma"          =>      "audio/x-ms-wma",
1051
  ".wax"          =>      "audio/x-ms-wax",
1052
  ".ogg"          =>      "audio/x-wav",
1053
  ".wav"          =>      "audio/x-wav",
1054
  ".gif"          =>      "image/gif",
1055
  ".jpg"          =>      "image/jpeg",
1056
  ".jpeg"         =>      "image/jpeg",
1057
  ".png"          =>      "image/png",
1058
  ".xbm"          =>      "image/x-xbitmap",
1059
  ".xpm"          =>      "image/x-xpixmap",
1060
  ".xwd"          =>      "image/x-xwindowdump",
1061
  ".css"          =>      "text/css",
1062
  ".html"         =>      "text/html",
1063
  ".htm"          =>      "text/html",
1064
  ".js"           =>      "text/javascript",
1065
  ".asc"          =>      "text/plain",
1066
  ".c"            =>      "text/plain",
1067
  ".conf"         =>      "text/plain",
1068
  ".text"         =>      "text/plain",
1069
  ".txt"          =>      "text/plain",
1070
  ".dtd"          =>      "text/xml",
1071
  ".xml"          =>      "text/xml",
1072
  ".mpeg"         =>      "video/mpeg",
1073
  ".mpg"          =>      "video/mpeg",
1074
  ".mov"          =>      "video/quicktime",
1075
  ".qt"           =>      "video/quicktime",
1076
  ".avi"          =>      "video/x-msvideo",
1077
  ".asf"          =>      "video/x-ms-asf",
1078
  ".asx"          =>      "video/x-ms-asf",
1079
  ".wmv"          =>      "video/x-ms-wmv",
1080
  ".bz2"          =>      "application/x-bzip",
1081
  ".tbz"          =>      "application/x-bzip-compressed-tar",
1082
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
1083
 )
1084

    
1085
# Use the "Content-Type" extended attribute to obtain mime type if possible
1086
#mimetypes.use-xattr        = "enable"
1087

    
1088
#### accesslog module
1089
#accesslog.filename          = "/dev/null"
1090

    
1091
## deny access the file-extensions
1092
#
1093
# ~    is for backupfiles from vi, emacs, joe, ...
1094
# .inc is often used for code includes which should in general not be part
1095
#      of the document-root
1096
url.access-deny             = ( "~", ".inc" )
1097

    
1098

    
1099
######### Options that are good to be but not neccesary to be changed #######
1100

    
1101
## bind to port (default: 80)
1102

    
1103
EOD;
1104

    
1105
	if($captive_portal == true) {
1106
		$lighty_config .= "server.bind	= \"127.0.0.1\"\n";
1107
		$lighty_config .= "server.port  = {$lighty_port}\n";
1108
		$lighty_config .= "\$SERVER[\"socket\"]  == \"127.0.0.1:{$lighty_port}\" { }\n";
1109
		$lighty_config .= "\$SERVER[\"socket\"]  == \"[::1]:{$lighty_port}\" { \n";
1110
		if($cert <> "" and $key <> "") {
1111
			$lighty_config .= "\n";
1112
			$lighty_config .= "## ssl configuration\n";
1113
			$lighty_config .= "ssl.engine = \"enable\"\n";
1114
			$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1115
			if($ca <> "")
1116
				$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1117
		}
1118
		$lighty_config .= " }\n";
1119
	} else {
1120
		$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1121
		$lighty_config .= "server.port  = {$lighty_port}\n";
1122
		$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1123
		$lighty_config .= "\$SERVER[\"socket\"]  == \"[::]:{$lighty_port}\" { \n";
1124
		if($cert <> "" and $key <> "") {
1125
			$lighty_config .= "\n";
1126
			$lighty_config .= "## ssl configuration\n";
1127
			$lighty_config .= "ssl.engine = \"enable\"\n";
1128
			$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1129
			if($ca <> "")
1130
				$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1131
		}
1132
		$lighty_config .= " }\n";
1133
	}
1134

    
1135

    
1136
	$lighty_config .= <<<EOD
1137

    
1138
## error-handler for status 404
1139
#server.error-handler-404   = "/error-handler.html"
1140
#server.error-handler-404   = "/error-handler.php"
1141

    
1142
## to help the rc.scripts
1143
server.pid-file            = "/var/run/{$pid_file}"
1144

    
1145
## virtual directory listings
1146
server.dir-listing         = "disable"
1147

    
1148
## enable debugging
1149
debug.log-request-header   = "disable"
1150
debug.log-response-header  = "disable"
1151
debug.log-request-handling = "disable"
1152
debug.log-file-not-found   = "disable"
1153

    
1154
# gzip compression
1155
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1156
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1157

    
1158
{$server_upload_dirs}
1159

    
1160
{$server_max_request_size}
1161

    
1162
{$fastcgi_config}
1163

    
1164
{$cgi_config}
1165

    
1166
{$captive_portal_mod_evasive}
1167

    
1168
expire.url = (
1169
				"" => "access 50 hours",	
1170
        )
1171

    
1172
EOD;
1173

    
1174
	$cert = str_replace("\r", "", $cert);
1175
	$key = str_replace("\r", "", $key);
1176
	$ca = str_replace("\r", "", $ca);
1177

    
1178
	$cert = str_replace("\n\n", "\n", $cert);
1179
	$key = str_replace("\n\n", "\n", $key);
1180
	$ca = str_replace("\n\n", "\n", $ca);
1181

    
1182
	if($cert <> "" and $key <> "") {
1183
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1184
		if (!$fd) {
1185
			printf(gettext("Error: cannot open cert.pem in system_webgui_start().%s"), "\n");
1186
			return 1;
1187
		}
1188
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1189
		fwrite($fd, $cert);
1190
		fwrite($fd, "\n");
1191
		fwrite($fd, $key);
1192
		fclose($fd);
1193
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
1194
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1195
			if (!$fd) {
1196
				printf(gettext("Error: cannot open ca.pem in system_webgui_start().%s"), "\n");
1197
				return 1;
1198
			}
1199
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1200
			fwrite($fd, $ca);
1201
			fclose($fd);
1202
		}
1203
		$lighty_config .= "\n";
1204
		$lighty_config .= "## " . gettext("ssl configuration") . "\n";
1205
		$lighty_config .= "ssl.engine = \"enable\"\n";
1206
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1207

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

    
1212
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1213
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1214
	}
1215

    
1216
	// Add HTTP to HTTPS redirect	
1217
	if ($captive_portal == false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1218
		if($lighty_port != "443") 
1219
			$redirectport = ":{$lighty_port}";
1220
		$lighty_config .= <<<EOD
1221
\$SERVER["socket"] == ":80" {
1222
	\$HTTP["host"] =~ "(.*)" {
1223
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1224
	}
1225
}
1226
EOD;
1227
	}
1228

    
1229
	$fd = fopen("{$filename}", "w");
1230
	if (!$fd) {
1231
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1232
		return 1;
1233
	}
1234
	fwrite($fd, $lighty_config);
1235
	fclose($fd);
1236

    
1237
	return 0;
1238

    
1239
}
1240

    
1241
function system_timezone_configure() {
1242
	global $config, $g;
1243
	if(isset($config['system']['developerspew'])) {
1244
		$mt = microtime();
1245
		echo "system_timezone_configure() being called $mt\n";
1246
	}
1247

    
1248
	$syscfg = $config['system'];
1249

    
1250
	if ($g['booting'])
1251
		echo gettext("Setting timezone...");
1252

    
1253
	/* extract appropriate timezone file */
1254
	$timezone = $syscfg['timezone'];
1255
	if (!$timezone)
1256
		$timezone = "Etc/UTC";
1257

    
1258
	conf_mount_rw();
1259

    
1260
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1261
		escapeshellarg($timezone) . " > /etc/localtime");
1262

    
1263
	mwexec("sync");
1264
	conf_mount_ro();
1265

    
1266
	if ($g['booting'])
1267
		echo gettext("done.") . "\n";
1268
}
1269

    
1270
function system_ntp_configure() {
1271
	global $config, $g;
1272

    
1273
	$ntpcfg = "# \n";
1274
	$ntpcfg .= "# pfSense OpenNTPD configuration file \n";
1275
	$ntpcfg .= "# \n\n";
1276

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

    
1281
	/* Setup listener(s) if the user has configured one */
1282
        if ($config['installedpackages']['openntpd']) {
1283
    		/* server config is in coregui1 */
1284
		$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
1285
		if ($xmlsettings['enable'] == 'on') {
1286
			$ifaces = explode(',', $xmlsettings['interface']);
1287
			$ips = array();
1288
			foreach ($ifaces as $if) {
1289
				if (is_ipaddr($if)) {
1290
					$ips[] = $if;
1291
				} else {
1292
					$if = get_real_interface($if);
1293
					if (does_interface_exist($if))
1294
						$ips[] = find_interface_ip($if);
1295
				}
1296
			}
1297
			foreach ($ips as $ip) {
1298
				if (is_ipaddr($ip))
1299
					$ntpcfg .= "listen on $ip\n";
1300
			}
1301
		}
1302
	}
1303
	$ntpcfg .= "\n";
1304

    
1305
	/* open configuration for wrting or bail */
1306
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1307
	if(!$fd) {
1308
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1309
		return;
1310
	}
1311
	fwrite($fd, $ntpcfg);
1312

    
1313
	/* slurp! */
1314
	fclose($fd);
1315

    
1316
	/* if openntpd is running, kill it */
1317
	while(is_process_running("ntpd")) {
1318
		killbyname("ntpd");
1319
	}
1320

    
1321
	/* if /var/empty does not exist, create it */
1322
	if(!is_dir("/var/empty"))
1323
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1324

    
1325
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1326
	exec("/usr/local/sbin/ntpd -s -f {$g['varetc_path']}/ntpd.conf");
1327
	
1328
	// Note that we are starting up
1329
	log_error("OpenNTPD is starting up.");
1330

    
1331
}
1332

    
1333
function sync_system_time() {
1334
	global $config, $g;
1335

    
1336
	if ($g['booting'])
1337
		echo gettext("Syncing system time before startup...");
1338

    
1339
	/* foreach through servers and write out to ntpd.conf */
1340
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1341
		mwexec("/usr/sbin/ntpdate -s $ts");
1342
	}
1343
	
1344
	if ($g['booting'])
1345
		echo gettext("done.") . "\n";
1346
	
1347
}
1348

    
1349
function system_halt() {
1350
	global $g;
1351

    
1352
	system_reboot_cleanup();
1353

    
1354
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1355
}
1356

    
1357
function system_reboot() {
1358
	global $g;
1359

    
1360
	system_reboot_cleanup();
1361

    
1362
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1363
}
1364

    
1365
function system_reboot_sync() {
1366
	global $g;
1367

    
1368
	system_reboot_cleanup();
1369

    
1370
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1371
}
1372

    
1373
function system_reboot_cleanup() {
1374
	mwexec("/usr/local/bin/beep.sh stop");
1375
	require_once("captiveportal.inc");
1376
	captiveportal_radius_stop_all();
1377
	require_once("voucher.inc");
1378
	voucher_save_db_to_config();
1379
	// mwexec("/etc/rc.stop_packages");
1380
}
1381

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

    
1389
	if ($early)
1390
		$cmdn = "earlyshellcmd";
1391
	else
1392
		$cmdn = "shellcmd";
1393

    
1394
	if (is_array($config['system'][$cmdn])) {
1395

    
1396
		/* *cmd is an array, loop through */
1397
		foreach ($config['system'][$cmdn] as $cmd) {
1398
			exec($cmd);
1399
		}
1400

    
1401
	} elseif($config['system'][$cmdn] <> "") {
1402

    
1403
		/* execute single item */
1404
		exec($config['system'][$cmdn]);
1405

    
1406
	}
1407
}
1408

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

    
1416
	if (isset($config['system']['disableconsolemenu'])) {
1417
		touch("{$g['varetc_path']}/disableconsole");
1418
	} else {
1419
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1420
	}
1421
}
1422

    
1423
function system_dmesg_save() {
1424
	global $g;
1425
	if(isset($config['system']['developerspew'])) {
1426
		$mt = microtime();
1427
		echo "system_dmesg_save() being called $mt\n";
1428
	}
1429

    
1430
	$dmesg = "";
1431
	exec("/sbin/dmesg", $dmesg);
1432

    
1433
	/* find last copyright line (output from previous boots may be present) */
1434
	$lastcpline = 0;
1435

    
1436
	for ($i = 0; $i < count($dmesg); $i++) {
1437
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1438
			$lastcpline = $i;
1439
	}
1440

    
1441
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1442
	if (!$fd) {
1443
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1444
		return 1;
1445
	}
1446

    
1447
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1448
		fwrite($fd, $dmesg[$i] . "\n");
1449

    
1450
	fclose($fd);
1451

    
1452
	return 0;
1453
}
1454

    
1455
function system_set_harddisk_standby() {
1456
	global $g, $config;
1457
	if(isset($config['system']['developerspew'])) {
1458
		$mt = microtime();
1459
		echo "system_set_harddisk_standby() being called $mt\n";
1460
	}
1461

    
1462
	if (isset($config['system']['harddiskstandby'])) {
1463
		if ($g['booting']) {
1464
			echo gettext('Setting hard disk standby... ');
1465
		}
1466

    
1467
		$standby = $config['system']['harddiskstandby'];
1468
		// Check for a numeric value
1469
		if (is_numeric($standby)) {
1470
			// Sync the disk(s)
1471
			pfSense_sync();
1472
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1473
				// Reinitialize ATA-drives
1474
				mwexec('/usr/local/sbin/atareinit');
1475
				if ($g['booting']) {
1476
					echo gettext("done.") . "\n";
1477
				}
1478
			} else if ($g['booting']) {
1479
				echo gettext("failed!") . "\n";
1480
			}
1481
		} else if ($g['booting']) {
1482
			echo gettext("failed!") . "\n";
1483
		}
1484
	}
1485
}
1486

    
1487
function system_setup_sysctl() {
1488
	global $config;
1489
	if(isset($config['system']['developerspew'])) {
1490
		$mt = microtime();
1491
		echo "system_setup_sysctl() being called $mt\n";
1492
	}
1493

    
1494
	activate_sysctls();	
1495

    
1496
	if (isset($config['system']['sharednet'])) {
1497
		system_disable_arp_wrong_if();
1498
	}
1499
}
1500

    
1501
function system_disable_arp_wrong_if() {
1502
	global $config;
1503
	if(isset($config['system']['developerspew'])) {
1504
		$mt = microtime();
1505
		echo "system_disable_arp_wrong_if() being called $mt\n";
1506
	}
1507
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1508
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1509
}
1510

    
1511
function system_enable_arp_wrong_if() {
1512
	global $config;
1513
	if(isset($config['system']['developerspew'])) {
1514
		$mt = microtime();
1515
		echo "system_enable_arp_wrong_if() being called $mt\n";
1516
	}
1517
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1518
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1519
}
1520

    
1521
function enable_watchdog() {
1522
	global $config;
1523
	return;
1524
	$install_watchdog = false;
1525
	$supported_watchdogs = array("Geode");
1526
	$file = file_get_contents("/var/log/dmesg.boot");
1527
	foreach($supported_watchdogs as $sd) {
1528
		if(stristr($file, "Geode")) {
1529
			$install_watchdog = true;
1530
		}
1531
	}
1532
	if($install_watchdog == true) {
1533
		if(is_process_running("watchdogd"))
1534
			mwexec("/usr/bin/killall watchdogd", true);
1535
		exec("/usr/sbin/watchdogd");
1536
	}
1537
}
1538

    
1539
function system_check_reset_button() {
1540
	global $g;
1541
	if($g['platform'] != "nanobsd")
1542
		return 0;
1543

    
1544
	$specplatform = system_identify_specific_platform();
1545

    
1546
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1547
		return 0;
1548

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

    
1551
	if ($retval == 99) {
1552
		/* user has pressed reset button for 2 seconds - 
1553
		   reset to factory defaults */
1554
		echo <<<EOD
1555

    
1556
***********************************************************************
1557
* Reset button pressed - resetting configuration to factory defaults. *
1558
* The system will reboot after this completes.                        *
1559
***********************************************************************
1560

    
1561

    
1562
EOD;
1563
		
1564
		reset_factory_defaults();
1565
		system_reboot_sync();
1566
		exit(0);
1567
	}
1568

    
1569
	return 0;
1570
}
1571

    
1572
/* attempt to identify the specific platform (for embedded systems)
1573
   Returns an array with two elements:
1574
	name => platform string (e.g. 'wrap', 'alix' etc.)
1575
	descr => human-readable description (e.g. "PC Engines WRAP")
1576
*/
1577
function system_identify_specific_platform() {
1578
	global $g;
1579
	
1580
	if ($g['platform'] == 'generic-pc')
1581
		return array('name' => 'generic-pc', 'descr' => gettext("Generic PC"));
1582
	
1583
	if ($g['platform'] == 'generic-pc-cdrom')
1584
		return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)"));
1585
	
1586
	/* the rest of the code only deals with 'embedded' platforms */
1587
	if ($g['platform'] != 'nanobsd')
1588
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1589
	
1590
	$dmesg = system_get_dmesg_boot();
1591
	
1592
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1593
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
1594
	
1595
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1596
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
1597

    
1598
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1599
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1600
	
1601
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1602
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1603
		
1604
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1605
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1606
	
1607
	/* unknown embedded platform */
1608
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
1609
}
1610

    
1611
function system_get_dmesg_boot() {
1612
	global $g;
1613
		
1614
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1615
}
1616

    
1617
function openntpd_get_listen_ips() {
1618
	$interfaces = get_configured_interface_with_descr();
1619
	$carplist = get_configured_carp_interface_list();
1620
	$listenips = array();
1621
	foreach ($carplist as $cif => $carpip)
1622
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1623
	$aliaslist = get_configured_ip_aliases_list();
1624
	foreach ($aliaslist as $aliasip => $aliasif)
1625
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1626
	foreach ($interfaces as $iface => $ifacename) {
1627
		$tmp["name"]  = $ifacename;
1628
		$tmp["value"] = $iface;
1629
		$listenips[] = $tmp;
1630
	}
1631
	$tmp["name"]  = "Localhost";
1632
	$tmp["value"] = "lo0";
1633
	$listenips[] = $tmp;
1634
	return $listenips;
1635
}
1636
?>
(47-47/61)