Project

General

Profile

Download (49.1 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(is_process_running("powerd"))
46
		exec("/usr/bin/killall powerd");
47
	if(isset($config['system']['powerd_enable'])) {
48
		if ($g["platform"] == "nanobsd")
49
			exec("/sbin/kldload cpufreq");
50
		$mode = "hadp";
51
		if (!empty($config['system']['powerd_mode']))
52
			$mode = $config['system']['powerd_mode'];
53
		mwexec("/usr/sbin/powerd -b $mode -a $mode");
54
	}
55
}
56

    
57
function get_default_sysctl_value($id) {
58
	global $sysctls;
59

    
60
	if (isset($sysctls[$id]))
61
		return $sysctls[$id];
62
}
63

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

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

    
85
function system_resolvconf_generate($dynupdate = false) {
86
	global $config, $g;
87

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

    
93
	$syscfg = $config['system'];
94

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

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

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

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

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

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

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

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

    
162
	unlock($dnslock);
163

    
164
	return 0;
165
}
166

    
167
function get_searchdomains() {
168
	global $config, $g;
169

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

    
186
	return $master_list;
187
}
188

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

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

    
217
	return $master_list;
218
}
219

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

    
227
	$syscfg = $config['system'];
228
	$dnsmasqcfg = $config['dnsmasq'];
229

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

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

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

    
256
	foreach ($hostscfg as $host) {
257
		if ($host['host'])
258
			$lhosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
259
		else
260
			$lhosts .= "{$host['ip']}	{$host['domain']}\n";
261
		if (!is_array($host['aliases']) || !is_array($host['aliases']['item']))
262
			continue;
263
		foreach ($host['aliases']['item'] as $alias) {
264
			if ($alias['host'])
265
				$lhosts .= "{$host['ip']}	{$alias['host']}.{$alias['domain']} {$alias['host']}\n";
266
			else
267
				$lhosts .= "{$host['ip']}	{$alias['domain']}\n";
268
		}
269
	}
270
	if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpd'])) {
271
		foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf)
272
			if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
273
					foreach ($dhcpifconf['staticmap'] as $host)
274
						if ($host['ipaddr'] && $host['hostname'])
275
							$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
276
	}
277
	if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpdv6'])) {
278
		foreach ($config['dhcpdv6'] as $dhcpif => $dhcpifconf)
279
			if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
280
					foreach ($dhcpifconf['staticmap'] as $host)
281
						if ($host['ipaddrv6'] && $host['hostname'])
282
							$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
283
	}
284

    
285
	if (isset($dnsmasqcfg['dhcpfirst']))
286
		$hosts .= $dhosts . $lhosts;
287
	else
288
		$hosts .= $lhosts . $dhosts;
289

    
290
	/*
291
	 * Do not remove this because dhcpleases monitors with kqueue it needs to be 
292
	 * killed before writing to hosts files.
293
	 */
294
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
295
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
296
                @unlink("{$g['varrun_path']}/dhcpleases.pid");
297
	}
298
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
299
	if (!$fd) {
300
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
301
		return 1;
302
	}
303
	fwrite($fd, $hosts);
304
	fclose($fd);
305

    
306
	system_dhcpleases_configure();
307

    
308
	return 0;
309
}
310

    
311
function system_dhcpleases_configure() {
312
	global $config, $g;
313
	
314
	if ($g['platform'] == 'jail')
315
		return;
316
	/* Start the monitoring process for dynamic dhcpclients. */
317
	if (isset($config['dnsmasq']['regdhcp'])) {
318
		/* Make sure we do not error out */
319
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
320
		if (file_exists("{$g['varrun_path']}/dhcpleases.pid"))
321
				sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "HUP");
322
		else
323
			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");
324
	} else {
325
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
326
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
327
	}
328
}
329

    
330
function system_hostname_configure() {
331
	global $config, $g;
332
	if(isset($config['system']['developerspew'])) {
333
		$mt = microtime();
334
		echo "system_hostname_configure() being called $mt\n";
335
	}
336

    
337
	$syscfg = $config['system'];
338

    
339
	/* set hostname */
340
	$status = mwexec("/bin/hostname " .
341
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
342

    
343
    /* Setup host GUID ID.  This is used by ZFS. */
344
	mwexec("/etc/rc.d/hostid start");
345

    
346
	return $status;
347
}
348

    
349
function system_routing_configure($interface = "") {
350
	global $config, $g;
351
	if ($g['platform'] == 'jail')
352
		return;
353
	if(isset($config['system']['developerspew'])) {
354
		$mt = microtime();
355
		echo "system_routing_configure() being called $mt\n";
356
	}
357

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

    
424
	if ($dont_add_route == false ) {
425
		if (!empty($interface) && $interface != $interfacegw)
426
			;
427
		else if (($interfacegw <> "bgpd") && (is_ipaddrv4($gatewayip))) {
428
			log_error("ROUTING: setting default route to $gatewayip");
429
			mwexec("/sbin/route change -inet default " . escapeshellarg($gatewayip));
430
		}
431

    
432
		if (!empty($interface) && $interface != $interfacegwv6)
433
			;
434
		else if (($interfacegwv6 <> "bgpd") && (is_ipaddrv6($gatewayipv6))) {
435
			if(preg_match("/fe80::/i", $gatewayipv6))
436
				$ifscope = "%{$defaultifv6}";
437
			log_error("ROUTING: setting IPv6 default route to {$gatewayipv6}{$ifscope}");
438
			mwexec("/sbin/route change -inet6 default " . escapeshellarg($gatewayipv6) ."{$ifscope}");
439
		}
440
	}
441

    
442
	$static_routes = get_staticroutes();
443
	if (count($static_routes)) {
444
		$gateways_arr = return_gateways_array();
445

    
446
		foreach ($static_routes as $rtent) {
447
			$gatewayip = "";
448
			if (empty($gateways_arr[$rtent['gateway']])) {
449
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
450
				continue;
451
			}
452
			$gateway = $gateways_arr[$rtent['gateway']];
453
			if (!empty($interface) && $interface != $gateway['friendlyiface'])
454
				continue;
455

    
456
			if(isset($rtent['disabled'])) {
457
				mwexec("/sbin/route delete " . escapeshellarg($rtent['network']), true);
458
				continue;
459
			}
460

    
461
			$gatewayip = $gateway['gateway'];
462
			$interfacegw = $gateway['interface'];
463

    
464
			if(is_ipaddrv6($gatewayip)) {
465
				$inetfamily = "-inet6";
466
			} else {
467
				$inetfamily = "-inet";
468
			}
469
			if (is_ipaddr($gatewayip)) {
470
				mwexec("/sbin/route change {$inetfamily} " . escapeshellarg($rtent['network']) .
471
					" " . escapeshellarg($gatewayip));
472
			} else if (!empty($interfacegw)) {
473
				mwexec("/sbin/route change {$inetfamily} " . escapeshellarg($rtent['network']) .
474
					" -iface " . escapeshellarg($interfacegw));
475
			}
476
		}
477
	}
478

    
479
	return 0;
480
}
481

    
482
function system_routing_enable() {
483
	global $config, $g;
484
	if(isset($config['system']['developerspew'])) {
485
		$mt = microtime();
486
		echo "system_routing_enable() being called $mt\n";
487
	}
488

    
489
	mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
490
	mwexec("/sbin/sysctl net.inet6.ip6.forwarding=1");
491
	return;
492
}
493

    
494
function system_syslogd_fixup_server($server) {
495
	/* If it's an IPv6 IP alone, encase it in brackets */
496
	if (is_ipaddrv6($server))
497
		return "[$server]";
498
	else
499
		return $server;
500
}
501

    
502
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
503
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
504
	$facility .= " ".
505
	$remote_servers = "";
506
	$pad_to  = 56;
507
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
508
	if($syslogcfg['remoteserver'])
509
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
510
	if($syslogcfg['remoteserver2'])
511
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
512
	if($syslogcfg['remoteserver3'])
513
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
514
	return $remote_servers;
515
}
516

    
517
function system_syslogd_start() {
518
	global $config, $g;
519
	if(isset($config['system']['developerspew'])) {
520
		$mt = microtime();
521
		echo "system_syslogd_start() being called $mt\n";
522
	}
523

    
524
	mwexec("/etc/rc.d/hostid start");
525

    
526
	$syslogcfg = $config['syslog'];
527

    
528
	if ($g['booting'])
529
		echo gettext("Starting syslog...");
530
	else
531
		killbypid("{$g['varrun_path']}/syslog.pid");
532

    
533
	if(is_process_running("syslogd"))
534
		mwexec('/bin/pkill syslogd');
535
	if(is_process_running("fifolog_writer"))
536
		mwexec('/bin/pkill fifolog_writer');
537
	
538
	// Define carious commands for logging
539
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
540
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
541
	$clog_create = "/usr/sbin/clog -i -s ";
542
	$clog_log = "%";
543

    
544
	// Which logging type are we using this week??
545
	if(isset($config['system']['usefifolog'])) {
546
		$log_directive = $fifolog_log;
547
		$log_create_directive = $fifolog_create;
548
	} else { // Defaults to CLOG
549
		$log_directive = $clog_log;
550
		$log_create_directive = $clog_create;
551
	}
552
	
553
	if (isset($syslogcfg)) {
554
		$separatelogfacilities = array('ntp','ntpd','ntpdate','racoon','openvpn','pptps','poes','l2tps','relayd','hostapd','dnsmasq','unbound','dhcpd','dhcrelay','apinger','radvd','routed','olsrd','zebra','ospfd','bgpd');
555
		if($config['installedpackages']['package']) {
556
			foreach($config['installedpackages']['package'] as $package) {
557
				if($package['logging']) {
558
					array_push($separatelogfacilities, $package['logging']['facilityname']);
559
					mwexec("{$log_create_directive} 10240 {$g['varlog_path']}/{$package['logging']['logfilename']}");
560
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
561
				}
562
			}
563
		}
564
		$facilitylist = implode(',', array_unique($separatelogfacilities));
565
		/* write syslog.conf */		
566
		$fd = fopen("{$g['varetc_path']}/syslog.conf", "w");
567
		if (!$fd) {
568
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
569
			return 1;
570
		}
571
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd\n";
572
		if (!isset($syslogcfg['disablelocallogging']))
573
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
574

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

    
579
		$syslogconf .= "!ppp\n";
580
		if (!isset($syslogcfg['disablelocallogging'])) 
581
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
582

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

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

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

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

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

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

    
613
		$syslogconf .= "!dnsmasq,unbound\n";
614
		if (!isset($syslogcfg['disablelocallogging']))
615
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
616
		if (isset($syslogcfg['apinger']))
617
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
618

    
619
		$syslogconf .= "!dhcpd,dhcrelay\n";
620
		if (!isset($syslogcfg['disablelocallogging']))
621
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/dhcpd.log\n";
622
		if (isset($syslogcfg['apinger']))
623
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
624

    
625
		$syslogconf .= "!relayd\n";
626
		if (!isset($syslogcfg['disablelocallogging']))
627
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/relayd.log\n";
628
		if (isset($syslogcfg['relayd']))
629
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
630

    
631
		$syslogconf .= "!hostapd\n";
632
		if (!isset($syslogcfg['disablelocallogging']))
633
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
634
		if (isset($syslogcfg['hostapd']))
635
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
636

    
637
		$syslogconf .= "!-{$facilitylist}\n";
638
		if (!isset($syslogcfg['disablelocallogging'])) 
639
			$syslogconf .= <<<EOD
640
local0.*							{$log_directive}{$g['varlog_path']}/filter.log
641
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
642
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
643
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
644
*.notice;kern.debug;lpr.info;mail.crit;				{$log_directive}{$g['varlog_path']}/system.log
645
news.err;local0.none;local3.none;local4.none;			{$log_directive}{$g['varlog_path']}/system.log
646
local7.none							{$log_directive}{$g['varlog_path']}/system.log
647
security.*							{$log_directive}{$g['varlog_path']}/system.log
648
auth.info;authpriv.info;daemon.info				{$log_directive}{$g['varlog_path']}/system.log
649
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
650
*.emerg								*
651

    
652
EOD;
653
		if (isset($syslogcfg['filter']))
654
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local0.*");
655
		if (isset($syslogcfg['vpn']))
656
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
657
		if (isset($syslogcfg['portalauth']))
658
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
659
		if (isset($syslogcfg['dhcp']))
660
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
661
		if (isset($syslogcfg['system'])) {
662
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.notice;kern.debug;lpr.info;mail.crit;");
663
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "news.err;local0.none;local3.none;local7.none");
664
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "security.*");
665
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "auth.info;authpriv.info;daemon.info");
666
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.emerg");
667
		}
668
		if (isset($syslogcfg['logall'])) {
669
			// Make everything mean everything, including facilities excluded above.
670
			$syslogconf .= "!*\n";
671
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
672
		}
673

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

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

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

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

    
694
	} else {
695
		$retval = mwexec_bg("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log");
696
	}
697

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

    
701
	return $retval;
702
}
703

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

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

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

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

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

    
727
	return $res;
728
}
729

    
730

    
731
function system_webgui_start() {
732
	global $config, $g;
733

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

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

    
740
	sleep(1);
741

    
742
	chdir($g['www_path']);
743

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

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

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

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

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

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

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

    
812
	return $res;
813
}
814

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

    
829
	global $config, $g;
830

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

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

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

    
866
	$memory = get_memory();
867
	$avail = $memory[0];
868

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

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

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

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

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

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

    
939
#### CGI module
940
cgi.assign                 = ( ".cgi" => "" )
941

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

    
951
EOD;
952
	}
953

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

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

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

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

    
992
server.max-keep-alive-requests = 15
993
server.max-keep-alive-idle = 30
994

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

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

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

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

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

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

    
1066
#### accesslog module
1067
#accesslog.filename          = "/dev/null"
1068

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

    
1076

    
1077
######### Options that are good to be but not neccesary to be changed #######
1078

    
1079
## bind to port (default: 80)
1080

    
1081
EOD;
1082

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

    
1113

    
1114
	$lighty_config .= <<<EOD
1115

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

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

    
1123
## virtual directory listings
1124
server.dir-listing         = "disable"
1125

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

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

    
1136
{$server_upload_dirs}
1137

    
1138
{$server_max_request_size}
1139

    
1140
{$fastcgi_config}
1141

    
1142
{$cgi_config}
1143

    
1144
{$captive_portal_mod_evasive}
1145

    
1146
expire.url = (
1147
				"" => "access 50 hours",	
1148
        )
1149

    
1150
EOD;
1151

    
1152
	$cert = str_replace("\r", "", $cert);
1153
	$key = str_replace("\r", "", $key);
1154
	$ca = str_replace("\r", "", $ca);
1155

    
1156
	$cert = str_replace("\n\n", "\n", $cert);
1157
	$key = str_replace("\n\n", "\n", $key);
1158
	$ca = str_replace("\n\n", "\n", $ca);
1159

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

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

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

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

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

    
1215
	return 0;
1216

    
1217
}
1218

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

    
1226
	$syscfg = $config['system'];
1227

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

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

    
1236
	conf_mount_rw();
1237

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

    
1241
	mwexec("sync");
1242
	conf_mount_ro();
1243

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

    
1248
function system_ntp_configure() {
1249
	global $config, $g;
1250

    
1251
	if ($g['platform'] == 'jail')
1252
		return;
1253

    
1254
	$ntpcfg = "# \n";
1255
	$ntpcfg .= "# pfSense OpenNTPD configuration file \n";
1256
	$ntpcfg .= "# \n\n";
1257

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

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

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

    
1294
	/* slurp! */
1295
	fclose($fd);
1296

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

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

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

    
1312
}
1313

    
1314
function sync_system_time() {
1315
	global $config, $g;
1316

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

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

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

    
1333
	system_reboot_cleanup();
1334

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

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

    
1341
	system_reboot_cleanup();
1342

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

    
1346
function system_reboot_sync() {
1347
	global $g;
1348

    
1349
	system_reboot_cleanup();
1350

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

    
1354
function system_reboot_cleanup() {
1355
	mwexec("/usr/local/bin/beep.sh stop");
1356
	require_once("captiveportal.inc");
1357
	captiveportal_radius_stop_all();
1358
	require_once("voucher.inc");
1359
	voucher_save_db_to_config();
1360
	require_once("pkg-utils.inc");
1361
	stop_packages();
1362
}
1363

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

    
1371
	if ($early)
1372
		$cmdn = "earlyshellcmd";
1373
	else
1374
		$cmdn = "shellcmd";
1375

    
1376
	if (is_array($config['system'][$cmdn])) {
1377

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

    
1383
	} elseif($config['system'][$cmdn] <> "") {
1384

    
1385
		/* execute single item */
1386
		exec($config['system'][$cmdn]);
1387

    
1388
	}
1389
}
1390

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

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

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

    
1412
	$dmesg = "";
1413
	exec("/sbin/dmesg", $dmesg);
1414

    
1415
	/* find last copyright line (output from previous boots may be present) */
1416
	$lastcpline = 0;
1417

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

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

    
1429
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1430
		fwrite($fd, $dmesg[$i] . "\n");
1431

    
1432
	fclose($fd);
1433

    
1434
	return 0;
1435
}
1436

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

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

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

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

    
1476
	activate_sysctls();	
1477

    
1478
	if (isset($config['system']['sharednet'])) {
1479
		system_disable_arp_wrong_if();
1480
	}
1481
}
1482

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

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

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

    
1521
function system_check_reset_button() {
1522
	global $g;
1523
	if($g['platform'] != "nanobsd")
1524
		return 0;
1525

    
1526
	$specplatform = system_identify_specific_platform();
1527

    
1528
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1529
		return 0;
1530

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

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

    
1538
***********************************************************************
1539
* Reset button pressed - resetting configuration to factory defaults. *
1540
* The system will reboot after this completes.                        *
1541
***********************************************************************
1542

    
1543

    
1544
EOD;
1545
		
1546
		reset_factory_defaults();
1547
		system_reboot_sync();
1548
		exit(0);
1549
	}
1550

    
1551
	return 0;
1552
}
1553

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

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

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

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

    
1619
?>
(50-50/65)