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/sbin/syslogd	
35
	pfSense_BUILDER_BINARIES:	/usr/sbin/pccardd	/usr/local/sbin/lighttpd	/bin/chmod 	/bin/mkdir
36
	pfSense_BUILDER_BINARIES:	/usr/bin/tar		/usr/local/sbin/ntpd	/usr/sbin/ntpdate
37
	pfSense_BUILDER_BINARIES:	/usr/bin/nohup	/sbin/dmesg	/usr/local/sbin/atareinit	/sbin/kldload
38
	pfSense_MODULE:	utils
39
*/
40

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
160
	unlock($dnslock);
161

    
162
	return 0;
163
}
164

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

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

    
184
	return $master_list;
185
}
186

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

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

    
215
	return $master_list;
216
}
217

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

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

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

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

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

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

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

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

    
294
	system_dhcpleases_configure();
295

    
296
	return 0;
297
}
298

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

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

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

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

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

    
334
	return $status;
335
}
336

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

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

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

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

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

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

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

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

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

    
467
	return 0;
468
}
469

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

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

    
482
function system_syslogd_fixup_server($server) {
483
	/* If it's an IPv6 IP alone, encase it in brackets */
484
	if (is_ipaddrv6($server))
485
		return "[$server]";
486
	else
487
		return $server;
488
}
489

    
490
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
491
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
492
	$facility .= " ".
493
	$remote_servers = "";
494
	$pad_to  = 56;
495
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
496
	if($syslogcfg['remoteserver'])
497
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
498
	if($syslogcfg['remoteserver2'])
499
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
500
	if($syslogcfg['remoteserver3'])
501
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
502
	return $remote_servers;
503
}
504

    
505
function system_syslogd_start() {
506
	global $config, $g;
507
	if(isset($config['system']['developerspew'])) {
508
		$mt = microtime();
509
		echo "system_syslogd_start() being called $mt\n";
510
	}
511

    
512
	mwexec("/etc/rc.d/hostid start");
513

    
514
	$syslogcfg = $config['syslog'];
515

    
516
	if ($g['booting'])
517
		echo gettext("Starting syslog...");
518
	else
519
		killbypid("{$g['varrun_path']}/syslog.pid");
520

    
521
	if(is_process_running("syslogd"))
522
		mwexec('/bin/pkill syslogd');
523
	if(is_process_running("fifolog_writer"))
524
		mwexec('/bin/pkill fifolog_writer');
525
	
526
	// Define carious commands for logging
527
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
528
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
529
	$clog_create = "/usr/sbin/clog -i -s ";
530
	$clog_log = "%";
531

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

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

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

    
571
		$syslogconf .= "!poes\n";
572
		if (!isset($syslogcfg['disablelocallogging'])) 
573
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
574

    
575
		$syslogconf .= "!l2tps\n";
576
		if (!isset($syslogcfg['disablelocallogging'])) 
577
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/l2tps.log\n";
578

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

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

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

    
597
		$syslogconf .= "!dnsmasq,unbound\n";
598
		if (!isset($syslogcfg['disablelocallogging']))
599
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
600
		if (isset($syslogcfg['apinger']))
601
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
602

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

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

    
615
		$syslogconf .= "!hostapd\n";
616
		if (!isset($syslogcfg['disablelocallogging']))
617
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
618
		if (isset($syslogcfg['hostapd']))
619
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
620

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

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

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

    
662
EOD;
663
		}
664
		fwrite($fd, $syslogconf);
665
		fclose($fd);
666

    
667
		// Ensure that the log directory exists
668
		if(!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
669
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
670

    
671
		// Are we logging to a least one remote server ?
672
		if(strpos($syslogconf, "@") != false)
673
			$retval = mwexec_bg("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log -f {$g['varetc_path']}/syslog.conf");
674
		else {
675
			$retval = mwexec_bg("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log -f {$g['varetc_path']}/syslog.conf");
676
		}
677

    
678
	} else {
679
		$retval = mwexec_bg("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log");
680
	}
681

    
682
	if ($g['booting'])
683
		echo gettext("done.") . "\n";
684

    
685
	return $retval;
686
}
687

    
688
function system_pccard_start() {
689
	global $config, $g;
690
	if(isset($config['system']['developerspew'])) {
691
		$mt = microtime();
692
		echo "system_pccard_start() being called $mt\n";
693
	}
694

    
695
	if ($g['booting'])
696
		echo gettext("Initializing PCMCIA...");
697

    
698
	/* kill any running pccardd */
699
	killbypid("{$g['varrun_path']}/pccardd.pid");
700

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

    
704
	if ($g['booting']) {
705
		if ($res == 0)
706
			echo gettext("done.") . "\n";
707
		else
708
			echo gettext("failed!") . "\n";
709
	}
710

    
711
	return $res;
712
}
713

    
714

    
715
function system_webgui_start() {
716
	global $config, $g;
717

    
718
	if ($g['booting'])
719
		echo gettext("Starting webConfigurator...");
720

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

    
724
	sleep(1);
725

    
726
	chdir($g['www_path']);
727

    
728
	/* defaults */
729
	$portarg = "80";
730
	$crt = "";
731
	$key = "";
732
	$ca = "";
733

    
734
	/* non-standard port? */
735
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
736
		$portarg = "{$config['system']['webgui']['port']}";
737

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

    
774
	/* generate lighttpd configuration */
775
	$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
776
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
777
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
778
		"cert.pem", "ca.pem", $max_procs);
779

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

    
783
	/* fetch page to preload apc cache */
784
	$proto = "http";
785
	if ($config['system']['webgui']['protocol'])
786
		$proto = $config['system']['webgui']['protocol'];
787
	mwexec_bg("/usr/bin/fetch -o /dev/null -q {$proto}://localhost:{$portarg}/preload.php");
788

    
789
	if ($g['booting']) {
790
		if ($res == 0)
791
			echo gettext("done.") . "\n";
792
		else
793
			echo gettext("failed!") . "\n";
794
	}
795

    
796
	return $res;
797
}
798

    
799
function system_generate_lighty_config($filename,
800
	$cert,
801
	$key,
802
	$ca,
803
	$pid_file,
804
	$port = 80,
805
	$document_root = "/usr/local/www/",
806
	$cert_location = "cert.pem",
807
	$ca_location = "ca.pem",
808
	$max_procs = 1,
809
	$max_requests = "2",
810
	$fast_cgi_enable = true,
811
	$captive_portal = false) {
812

    
813
	global $config, $g;
814

    
815
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
816
		mkdir("{$g['tmp_path']}/lighttpdcompress");
817

    
818
	if(isset($config['system']['developerspew'])) {
819
		$mt = microtime();
820
		echo "system_generate_lighty_config() being called $mt\n";
821
	}
822

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

    
850
	$memory = get_memory();
851
	$avail = $memory[0];
852

    
853
	if($avail > 0 and $avail < 65) {
854
		$fast_cgi_enable = false;
855
	}
856

    
857
	// Ramp up captive portal max procs
858
	//  Work relative to the default of 2, for values that would be >2.
859
	if($captive_portal == true)  {
860
		if($avail > 65 and $avail < 98) {
861
			$max_procs = 1;
862
		}
863
		if($avail > 97 and $avail < 128) {
864
			$max_procs = 2;
865
		}
866
		if($avail > 127 and $avail < 256) {
867
			$max_procs += 1;
868
		}
869
		if($avail > 255 and $avail < 384) {
870
			$max_procs += 2;
871
		}
872
		if($avail > 383) {
873
			$max_procs += 3;
874
		}
875
	}
876

    
877
	if($captive_portal == true)  {	
878
		$bin_environment =  <<<EOC
879
			"bin-environment" => (
880
				"PHP_FCGI_CHILDREN" => "0",
881
				"PHP_FCGI_MAX_REQUESTS" => "500"
882
			),
883
EOC;
884

    
885
	} else if ($avail > 0 and $avail < 128) {
886
		$bin_environment = <<<EOC
887
			"bin-environment" => (
888
				"PHP_FCGI_CHILDREN" => "0",
889
				"PHP_FCGI_MAX_REQUESTS" => "2",
890
			),
891

    
892
EOC;
893
	} else
894
		$bin_environment =  <<<EOC
895
			"bin-environment" => (
896
				"PHP_FCGI_CHILDREN" => "0",
897
				"PHP_FCGI_MAX_REQUESTS" => "500"
898
			),
899
EOC;
900

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

    
923
#### CGI module
924
cgi.assign                 = ( ".cgi" => "" )
925

    
926
EOD;
927
	} else {
928
		$fastcgi_config = "";
929
		$module = "\"mod_cgi\"";
930
		$cgi_config = <<<EOD
931
#### CGI module
932
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
933
                               ".cgi" => "" )
934

    
935
EOD;
936
	}
937

    
938
	$lighty_config = "";
939
	$lighty_config .= <<<EOD
940
#
941
# lighttpd configuration file
942
#
943
# use a it as base for lighttpd 1.0.0 and above
944
#
945
############ Options you really have to take care of ####################
946

    
947
## FreeBSD!
948
server.event-handler	= "freebsd-kqueue"
949
server.network-backend 	= "writev"
950
#server.use-ipv6 = "enable"
951

    
952
## modules to load
953
server.modules              =   (
954
	{$captive_portal_module}
955
	"mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect",
956
	{$module}{$captiveportal}
957
)
958

    
959
## Unused modules
960
#                               "mod_setenv",
961
#                               "mod_rewrite",
962
#                               "mod_ssi",
963
#                               "mod_usertrack",
964
#                               "mod_expire",
965
#                               "mod_secdownload",
966
#                               "mod_rrdtool",
967
#                               "mod_auth",
968
#                               "mod_status",
969
#                               "mod_alias",
970
#                               "mod_proxy",
971
#                               "mod_simple_vhost",
972
#                               "mod_evhost",
973
#                               "mod_userdir",
974
#                               "mod_cgi",
975

    
976
server.max-keep-alive-requests = 15
977
server.max-keep-alive-idle = 30
978

    
979
## a static document-root, for virtual-hosting take look at the
980
## server.virtual-* options
981
server.document-root        = "{$document_root}"
982
{$captive_portal_rewrite}
983

    
984
# Maximum idle time with nothing being written (php downloading)
985
server.max-write-idle = 999
986

    
987
## where to send error-messages to
988
server.errorlog             = "/var/log/lighttpd.error.log"
989

    
990
# files to check for if .../ is requested
991
server.indexfiles           = ( "index.php", "index.html",
992
                                "index.htm", "default.htm" )
993

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

    
1047
# Use the "Content-Type" extended attribute to obtain mime type if possible
1048
#mimetypes.use-xattr        = "enable"
1049

    
1050
#### accesslog module
1051
#accesslog.filename          = "/dev/null"
1052

    
1053
## deny access the file-extensions
1054
#
1055
# ~    is for backupfiles from vi, emacs, joe, ...
1056
# .inc is often used for code includes which should in general not be part
1057
#      of the document-root
1058
url.access-deny             = ( "~", ".inc" )
1059

    
1060

    
1061
######### Options that are good to be but not neccesary to be changed #######
1062

    
1063
## bind to port (default: 80)
1064

    
1065
EOD;
1066

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

    
1097

    
1098
	$lighty_config .= <<<EOD
1099

    
1100
## error-handler for status 404
1101
#server.error-handler-404   = "/error-handler.html"
1102
#server.error-handler-404   = "/error-handler.php"
1103

    
1104
## to help the rc.scripts
1105
server.pid-file            = "/var/run/{$pid_file}"
1106

    
1107
## virtual directory listings
1108
server.dir-listing         = "disable"
1109

    
1110
## enable debugging
1111
debug.log-request-header   = "disable"
1112
debug.log-response-header  = "disable"
1113
debug.log-request-handling = "disable"
1114
debug.log-file-not-found   = "disable"
1115

    
1116
# gzip compression
1117
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1118
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1119

    
1120
{$server_upload_dirs}
1121

    
1122
{$server_max_request_size}
1123

    
1124
{$fastcgi_config}
1125

    
1126
{$cgi_config}
1127

    
1128
{$captive_portal_mod_evasive}
1129

    
1130
expire.url = (
1131
				"" => "access 50 hours",	
1132
        )
1133

    
1134
EOD;
1135

    
1136
	$cert = str_replace("\r", "", $cert);
1137
	$key = str_replace("\r", "", $key);
1138
	$ca = str_replace("\r", "", $ca);
1139

    
1140
	$cert = str_replace("\n\n", "\n", $cert);
1141
	$key = str_replace("\n\n", "\n", $key);
1142
	$ca = str_replace("\n\n", "\n", $ca);
1143

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

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

    
1174
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1175
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1176
	}
1177

    
1178
	// Add HTTP to HTTPS redirect	
1179
	if ($captive_portal == false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1180
		if($lighty_port != "443") 
1181
			$redirectport = ":{$lighty_port}";
1182
		$lighty_config .= <<<EOD
1183
\$SERVER["socket"] == ":80" {
1184
	\$HTTP["host"] =~ "(.*)" {
1185
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1186
	}
1187
}
1188
EOD;
1189
	}
1190

    
1191
	$fd = fopen("{$filename}", "w");
1192
	if (!$fd) {
1193
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1194
		return 1;
1195
	}
1196
	fwrite($fd, $lighty_config);
1197
	fclose($fd);
1198

    
1199
	return 0;
1200

    
1201
}
1202

    
1203
function system_timezone_configure() {
1204
	global $config, $g;
1205
	if(isset($config['system']['developerspew'])) {
1206
		$mt = microtime();
1207
		echo "system_timezone_configure() being called $mt\n";
1208
	}
1209

    
1210
	$syscfg = $config['system'];
1211

    
1212
	if ($g['booting'])
1213
		echo gettext("Setting timezone...");
1214

    
1215
	/* extract appropriate timezone file */
1216
	$timezone = $syscfg['timezone'];
1217
	if (!$timezone)
1218
		$timezone = "Etc/UTC";
1219

    
1220
	conf_mount_rw();
1221

    
1222
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1223
		escapeshellarg($timezone) . " > /etc/localtime");
1224

    
1225
	mwexec("sync");
1226
	conf_mount_ro();
1227

    
1228
	if ($g['booting'])
1229
		echo gettext("done.") . "\n";
1230
}
1231

    
1232
function system_ntp_configure() {
1233
	global $config, $g;
1234

    
1235
	if ($g['platform'] == 'jail')
1236
		return;
1237

    
1238
	$ntpcfg = "# \n";
1239
	$ntpcfg .= "# pfSense OpenNTPD configuration file \n";
1240
	$ntpcfg .= "# \n\n";
1241

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

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

    
1270
	/* open configuration for wrting or bail */
1271
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1272
	if(!$fd) {
1273
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1274
		return;
1275
	}
1276
	fwrite($fd, $ntpcfg);
1277

    
1278
	/* slurp! */
1279
	fclose($fd);
1280

    
1281
	/* if openntpd is running, kill it */
1282
	while(is_process_running("ntpd")) {
1283
		killbyname("ntpd");
1284
	}
1285

    
1286
	/* if /var/empty does not exist, create it */
1287
	if(!is_dir("/var/empty"))
1288
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1289

    
1290
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1291
	exec("/usr/local/sbin/ntpd -v -s -f {$g['varetc_path']}/ntpd.conf");
1292
	
1293
	// Note that we are starting up
1294
	log_error("OpenNTPD is starting up.");
1295

    
1296
}
1297

    
1298
function sync_system_time() {
1299
	global $config, $g;
1300

    
1301
	if ($g['booting'])
1302
		echo gettext("Syncing system time before startup...");
1303

    
1304
	/* foreach through servers and write out to ntpd.conf */
1305
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1306
		mwexec("/usr/sbin/ntpdate -s $ts");
1307
	}
1308
	
1309
	if ($g['booting'])
1310
		echo gettext("done.") . "\n";
1311
	
1312
}
1313

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

    
1317
	system_reboot_cleanup();
1318

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

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

    
1325
	system_reboot_cleanup();
1326

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

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

    
1333
	system_reboot_cleanup();
1334

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

    
1338
function system_reboot_cleanup() {
1339
	mwexec("/usr/local/bin/beep.sh stop");
1340
	require_once("captiveportal.inc");
1341
	captiveportal_radius_stop_all();
1342
	require_once("voucher.inc");
1343
	voucher_save_db_to_config();
1344
	mwexec("/etc/rc.stop_packages");
1345
}
1346

    
1347
function system_do_shell_commands($early = 0) {
1348
	global $config, $g;
1349
	if(isset($config['system']['developerspew'])) {
1350
		$mt = microtime();
1351
		echo "system_do_shell_commands() being called $mt\n";
1352
	}
1353

    
1354
	if ($early)
1355
		$cmdn = "earlyshellcmd";
1356
	else
1357
		$cmdn = "shellcmd";
1358

    
1359
	if (is_array($config['system'][$cmdn])) {
1360

    
1361
		/* *cmd is an array, loop through */
1362
		foreach ($config['system'][$cmdn] as $cmd) {
1363
			exec($cmd);
1364
		}
1365

    
1366
	} elseif($config['system'][$cmdn] <> "") {
1367

    
1368
		/* execute single item */
1369
		exec($config['system'][$cmdn]);
1370

    
1371
	}
1372
}
1373

    
1374
function system_console_configure() {
1375
	global $config, $g;
1376
	if(isset($config['system']['developerspew'])) {
1377
		$mt = microtime();
1378
		echo "system_console_configure() being called $mt\n";
1379
	}
1380

    
1381
	if (isset($config['system']['disableconsolemenu'])) {
1382
		touch("{$g['varetc_path']}/disableconsole");
1383
	} else {
1384
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1385
	}
1386
}
1387

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

    
1395
	$dmesg = "";
1396
	exec("/sbin/dmesg", $dmesg);
1397

    
1398
	/* find last copyright line (output from previous boots may be present) */
1399
	$lastcpline = 0;
1400

    
1401
	for ($i = 0; $i < count($dmesg); $i++) {
1402
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1403
			$lastcpline = $i;
1404
	}
1405

    
1406
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1407
	if (!$fd) {
1408
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1409
		return 1;
1410
	}
1411

    
1412
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1413
		fwrite($fd, $dmesg[$i] . "\n");
1414

    
1415
	fclose($fd);
1416

    
1417
	return 0;
1418
}
1419

    
1420
function system_set_harddisk_standby() {
1421
	global $g, $config;
1422
	if(isset($config['system']['developerspew'])) {
1423
		$mt = microtime();
1424
		echo "system_set_harddisk_standby() being called $mt\n";
1425
	}
1426

    
1427
	if (isset($config['system']['harddiskstandby'])) {
1428
		if ($g['booting']) {
1429
			echo gettext('Setting hard disk standby... ');
1430
		}
1431

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

    
1452
function system_setup_sysctl() {
1453
	global $config;
1454
	if(isset($config['system']['developerspew'])) {
1455
		$mt = microtime();
1456
		echo "system_setup_sysctl() being called $mt\n";
1457
	}
1458

    
1459
	activate_sysctls();	
1460

    
1461
	if (isset($config['system']['sharednet'])) {
1462
		system_disable_arp_wrong_if();
1463
	}
1464
}
1465

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

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

    
1486
function enable_watchdog() {
1487
	global $config;
1488
	return;
1489
	$install_watchdog = false;
1490
	$supported_watchdogs = array("Geode");
1491
	$file = file_get_contents("/var/log/dmesg.boot");
1492
	foreach($supported_watchdogs as $sd) {
1493
		if(stristr($file, "Geode")) {
1494
			$install_watchdog = true;
1495
		}
1496
	}
1497
	if($install_watchdog == true) {
1498
		if(is_process_running("watchdogd"))
1499
			mwexec("/usr/bin/killall watchdogd", true);
1500
		exec("/usr/sbin/watchdogd");
1501
	}
1502
}
1503

    
1504
function system_check_reset_button() {
1505
	global $g;
1506
	if($g['platform'] != "nanobsd")
1507
		return 0;
1508

    
1509
	$specplatform = system_identify_specific_platform();
1510

    
1511
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1512
		return 0;
1513

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

    
1516
	if ($retval == 99) {
1517
		/* user has pressed reset button for 2 seconds - 
1518
		   reset to factory defaults */
1519
		echo <<<EOD
1520

    
1521
***********************************************************************
1522
* Reset button pressed - resetting configuration to factory defaults. *
1523
* The system will reboot after this completes.                        *
1524
***********************************************************************
1525

    
1526

    
1527
EOD;
1528
		
1529
		reset_factory_defaults();
1530
		system_reboot_sync();
1531
		exit(0);
1532
	}
1533

    
1534
	return 0;
1535
}
1536

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

    
1563
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1564
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1565
	
1566
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1567
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1568
		
1569
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1570
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1571
	
1572
	/* unknown embedded platform */
1573
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
1574
}
1575

    
1576
function system_get_dmesg_boot() {
1577
	global $g;
1578
		
1579
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1580
}
1581

    
1582
function get_possible_listen_ips() {
1583
	$interfaces = get_configured_interface_with_descr();
1584
	$carplist = get_configured_carp_interface_list();
1585
	$listenips = array();
1586
	foreach ($carplist as $cif => $carpip)
1587
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1588
	$aliaslist = get_configured_ip_aliases_list();
1589
	foreach ($aliaslist as $aliasip => $aliasif)
1590
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1591
	foreach ($interfaces as $iface => $ifacename) {
1592
		$tmp["name"]  = $ifacename;
1593
		$tmp["value"] = $iface;
1594
		$listenips[] = $tmp;
1595
	}
1596
	$tmp["name"]  = "Localhost";
1597
	$tmp["value"] = "lo0";
1598
	$listenips[] = $tmp;
1599
	return $listenips;
1600
}
1601

    
1602
?>
(50-50/65)