Project

General

Profile

Download (47.2 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']))) {
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']))) {
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
	if (is_array($config['staticroutes']['route'])) {
431
		$gateways_arr = return_gateways_array();
432

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

    
443
			$gatewayip = $gateway['gateway'];
444
			$interfacegw = $gateway['interface'];
445

    
446
			if(is_ipaddrv6($gatewayip)) {
447
				$inetfamily = "-inet6";
448
			} else {
449
				$inetfamily = "-inet";
450
			}
451
			if (is_ipaddr($gatewayip)) {
452
				mwexec("/sbin/route change {$inetfamily} " . escapeshellarg($rtent['network']) .
453
					" " . escapeshellarg($gatewayip));
454
			} else if (!empty($interfacegw)) {
455
				mwexec("/sbin/route change {$inetfamily} " . escapeshellarg($rtent['network']) .
456
					" -iface " . escapeshellarg($interfacegw));
457
			}
458
		}
459
	}
460

    
461
	return 0;
462
}
463

    
464
function system_routing_enable() {
465
	global $config, $g;
466
	if(isset($config['system']['developerspew'])) {
467
		$mt = microtime();
468
		echo "system_routing_enable() being called $mt\n";
469
	}
470

    
471
	mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
472
	mwexec("/sbin/sysctl net.inet6.ip6.forwarding=1");
473
	return;
474
}
475

    
476
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
477
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
478
	$facility .= " ".
479
	$remote_servers = "";
480
	$pad_to  = 56;
481
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
482
	if($syslogcfg['remoteserver'])
483
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@{$syslogcfg['remoteserver']}\n";
484
	if($syslogcfg['remoteserver2'])
485
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@{$syslogcfg['remoteserver2']}\n";
486
	if($syslogcfg['remoteserver3'])
487
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@{$syslogcfg['remoteserver3']}\n";
488
	return $remote_servers;
489
}
490

    
491
function system_syslogd_start() {
492
	global $config, $g;
493
	if(isset($config['system']['developerspew'])) {
494
		$mt = microtime();
495
		echo "system_syslogd_start() being called $mt\n";
496
	}
497

    
498
	mwexec("/etc/rc.d/hostid start");
499

    
500
	$syslogcfg = $config['syslog'];
501

    
502
	if ($g['booting'])
503
		echo gettext("Starting syslog...");
504
	else
505
		killbypid("{$g['varrun_path']}/syslog.pid");
506

    
507
	if(is_process_running("syslogd"))
508
		mwexec('/bin/pkill syslogd');
509
	if(is_process_running("fifolog_writer"))
510
		mwexec('/bin/pkill fifolog_writer');
511
	
512
	// Define carious commands for logging
513
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
514
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
515
	$clog_create = "/usr/sbin/clog -i -s ";
516
	$clog_log = "%";
517

    
518
	// Which logging type are we using this week??
519
	if(isset($config['system']['usefifolog'])) {
520
		$log_directive = $fifolog_log;
521
		$log_create_directive = $fifolog_create;
522
	} else { // Defaults to CLOG
523
		$log_directive = $clog_log;
524
		$log_create_directive = $clog_create;
525
	}
526
	
527
	if (isset($syslogcfg)) {
528
		$separatelogfacilities = array('ntpd','racoon','openvpn','pptps','poes','l2tps','relayd','hostapd');
529
		if($config['installedpackages']['package']) {
530
			foreach($config['installedpackages']['package'] as $package) {
531
				if($package['logging']) {
532
					array_push($separatelogfacilities, $package['logging']['facilityname']);
533
					mwexec("{$log_create_directive} 10240 {$g['varlog_path']}/{$package['logging']['logfilename']}");
534
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
535
				}
536
			}
537
		}
538
		$facilitylist = implode(',', array_unique($separatelogfacilities));
539
		/* write syslog.conf */		
540
		$fd = fopen("{$g['varetc_path']}/syslog.conf", "w");
541
		if (!$fd) {
542
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
543
			return 1;
544
		}
545
		$syslogconf .= "!ntpdate,ntpd\n";
546
		if (!isset($syslogcfg['disablelocallogging'])) 
547
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
548

    
549
		$syslogconf .= "!ppp\n";
550
		if (!isset($syslogcfg['disablelocallogging'])) 
551
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
552

    
553
		$syslogconf .= "!pptps\n";
554
		if (!isset($syslogcfg['disablelocallogging'])) 
555
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/pptps.log\n";
556

    
557
		$syslogconf .= "!poes\n";
558
		if (!isset($syslogcfg['disablelocallogging'])) 
559
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
560

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

    
565
		$syslogconf .= "!racoon\n";
566
		if (!isset($syslogcfg['disablelocallogging'])) 
567
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ipsec.log\n";
568
		if (isset($syslogcfg['vpn']))
569
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
570

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

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

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

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

    
595
		$syslogconf .= "!-{$facilitylist}\n";
596
		if (!isset($syslogcfg['disablelocallogging'])) 
597
			$syslogconf .= <<<EOD
598
local0.*							{$log_directive}{$g['varlog_path']}/filter.log
599
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
600
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
601
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
602
*.notice;kern.debug;lpr.info;mail.crit;				{$log_directive}{$g['varlog_path']}/system.log
603
news.err;local0.none;local3.none;local4.none;			{$log_directive}{$g['varlog_path']}/system.log
604
local7.none							{$log_directive}{$g['varlog_path']}/system.log
605
security.*							{$log_directive}{$g['varlog_path']}/system.log
606
auth.info;authpriv.info;daemon.info				{$log_directive}{$g['varlog_path']}/system.log
607
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
608
*.emerg								*
609

    
610
EOD;
611
		if (isset($syslogcfg['filter']))
612
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local0.*");
613
		if (isset($syslogcfg['vpn']))
614
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
615
		if (isset($syslogcfg['portalauth']))
616
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
617
		if (isset($syslogcfg['dhcp']))
618
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
619
		if (isset($syslogcfg['system'])) {
620
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.notice;kern.debug;lpr.info;mail.crit;");
621
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "news.err;local0.none;local3.none;local7.none");
622
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "security.*");
623
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "auth.info;authpriv.info;daemon.info");
624
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.emerg");
625
		}
626
		if (isset($syslogcfg['logall'])) {
627
			// Make everything mean everything, including facilities excluded above.
628
			$syslogconf .= "!*\n";
629
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
630
		}
631

    
632
		if (isset($syslogcfg['zmqserver'])) {
633
				$syslogconf .= <<<EOD
634
*.*								^{$syslogcfg['zmqserver']}
635

    
636
EOD;
637
		}
638
		fwrite($fd, $syslogconf);
639
		fclose($fd);
640

    
641
		// Ensure that the log directory exists
642
		if(!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
643
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
644

    
645
		// Are we logging to a least one remote server ?
646
		if(strpos($syslogconf, "@") != false)
647
			$retval = mwexec_bg("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log -f {$g['varetc_path']}/syslog.conf");
648
		else {
649
			$retval = mwexec_bg("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log -f {$g['varetc_path']}/syslog.conf");
650
		}
651

    
652
	} else {
653
		$retval = mwexec_bg("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log");
654
	}
655

    
656
	if ($g['booting'])
657
		echo gettext("done.") . "\n";
658

    
659
	return $retval;
660
}
661

    
662
function system_pccard_start() {
663
	global $config, $g;
664
	if(isset($config['system']['developerspew'])) {
665
		$mt = microtime();
666
		echo "system_pccard_start() being called $mt\n";
667
	}
668

    
669
	if ($g['booting'])
670
		echo gettext("Initializing PCMCIA...");
671

    
672
	/* kill any running pccardd */
673
	killbypid("{$g['varrun_path']}/pccardd.pid");
674

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

    
678
	if ($g['booting']) {
679
		if ($res == 0)
680
			echo gettext("done.") . "\n";
681
		else
682
			echo gettext("failed!") . "\n";
683
	}
684

    
685
	return $res;
686
}
687

    
688

    
689
function system_webgui_start() {
690
	global $config, $g;
691

    
692
	if ($g['booting'])
693
		echo gettext("Starting webConfigurator...");
694

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

    
698
	sleep(1);
699

    
700
	chdir($g['www_path']);
701

    
702
	/* defaults */
703
	$portarg = "80";
704
	$crt = "";
705
	$key = "";
706
	$ca = "";
707

    
708
	/* non-standard port? */
709
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
710
		$portarg = "{$config['system']['webgui']['port']}";
711

    
712
	if ($config['system']['webgui']['protocol'] == "https") {
713
		// Ensure that we have a webConfigurator CERT
714
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
715
		if(!is_array($cert) && !$cert['crt'] && !$cert['prv']) {
716
			if (!is_array($config['ca']))
717
				$config['ca'] = array();
718
			$a_ca =& $config['ca'];
719
			if (!is_array($config['cert']))
720
				$config['cert'] = array();
721
			$a_cert =& $config['cert'];
722
			log_error("Creating SSL Certificate for this host");
723
			$cert = array();
724
			$cert['refid'] = uniqid();
725
			$cert['descr'] = gettext("webConfigurator default");
726
			mwexec("/usr/bin/openssl genrsa 1024 > {$g['tmp_path']}/ssl.key");
727
			mwexec("/usr/bin/openssl req -new -x509 -nodes -sha1 -days 2000 -key {$g['tmp_path']}/ssl.key > {$g['tmp_path']}/ssl.crt");
728
			$crt = file_get_contents("{$g['tmp_path']}/ssl.crt");
729
			$key = file_get_contents("{$g['tmp_path']}/ssl.key");
730
			unlink("{$g['tmp_path']}/ssl.key");
731
			unlink("{$g['tmp_path']}/ssl.crt");
732
			cert_import($cert, $crt, $key);
733
			$a_cert[] = $cert;
734
			$config['system']['webgui']['ssl-certref'] = $cert['refid'];
735
			write_config(gettext("Importing HTTPS certificate"));
736
			if(!$config['system']['webgui']['port'])
737
				$portarg = "443";
738
			$ca = ca_chain($cert);
739
		} else {
740
			$crt = base64_decode($cert['crt']);
741
			$key = base64_decode($cert['prv']);
742
			if(!$config['system']['webgui']['port'])
743
				$portarg = "443";
744
			$ca = ca_chain($cert);
745
		}
746
	}
747

    
748
	/* generate lighttpd configuration */
749
	$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
750
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
751
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
752
		"cert.pem", "ca.pem", $max_procs);
753

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

    
757
	/* fetch page to preload apc cache */
758
	$proto = "http";
759
	if ($config['system']['webgui']['protocol'])
760
		$proto = $config['system']['webgui']['protocol'];
761
	mwexec_bg("/usr/bin/fetch -o /dev/null -q {$proto}://localhost:{$portarg}/preload.php");
762

    
763
	if ($g['booting']) {
764
		if ($res == 0)
765
			echo gettext("done.") . "\n";
766
		else
767
			echo gettext("failed!") . "\n";
768
	}
769

    
770
	return $res;
771
}
772

    
773
function system_generate_lighty_config($filename,
774
	$cert,
775
	$key,
776
	$ca,
777
	$pid_file,
778
	$port = 80,
779
	$document_root = "/usr/local/www/",
780
	$cert_location = "cert.pem",
781
	$ca_location = "ca.pem",
782
	$max_procs = 1,
783
	$max_requests = "2",
784
	$fast_cgi_enable = true,
785
	$captive_portal = false) {
786

    
787
	global $config, $g;
788

    
789
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
790
		mkdir("{$g['tmp_path']}/lighttpdcompress");
791

    
792
	if(isset($config['system']['developerspew'])) {
793
		$mt = microtime();
794
		echo "system_generate_lighty_config() being called $mt\n";
795
	}
796

    
797
	if($captive_portal != false)  {
798
		$captiveportal = ",\"mod_rewrite\"";
799
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?zone={$captive_portal}&redirurl=$1\" )\n";
800
		$captive_portal_module = "";
801
		$maxprocperip = $config['captiveportal']['maxprocperip'];
802
		if($maxprocperip and $maxprocperip > 0)
803
			$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
804
		else
805
			$captive_portal_mod_evasive = "";
806
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
807
		exec("mkdir -p {$g['tmp_path']}/captiveportal");
808
		exec("chmod a-w {$g['tmp_path']}/captiveportal");
809
		$server_max_request_size = "server.max-request-size    = 384";
810
	} else {
811
		$captiveportal = "";
812
		$captive_portal_rewrite = "";
813
		$captive_portal_module = "";
814
		$captive_portal_mod_evasive = "";
815
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
816
		$server_max_request_size = "server.max-request-size    = 2097152";
817
	}
818
	
819
	if($port <> "")
820
		$lighty_port = $port;
821
	else
822
		$lighty_port = "80";
823

    
824
	$memory = get_memory();
825
	$avail = $memory[0];
826

    
827
	if($avail > 0 and $avail < 65) {
828
		$fast_cgi_enable = false;
829
	}
830

    
831
	// Ramp up captive portal max procs
832
	//  Work relative to the default of 2, for values that would be >2.
833
	if($captive_portal == true)  {
834
		if($avail > 65 and $avail < 98) {
835
			$max_procs = 1;
836
		}
837
		if($avail > 97 and $avail < 128) {
838
			$max_procs = 2;
839
		}
840
		if($avail > 127 and $avail < 256) {
841
			$max_procs += 1;
842
		}
843
		if($avail > 255 and $avail < 384) {
844
			$max_procs += 2;
845
		}
846
		if($avail > 383) {
847
			$max_procs += 3;
848
		}
849
	}
850

    
851
	if($captive_portal == true)  {	
852
		$bin_environment =  <<<EOC
853
			"bin-environment" => (
854
				"PHP_FCGI_CHILDREN" => "$max_procs",
855
				"PHP_FCGI_MAX_REQUESTS" => "500"
856
			),
857
EOC;
858

    
859
	} else if ($avail > 0 and $avail < 128) {
860
		$bin_environment = <<<EOC
861
			"bin-environment" => (
862
				"PHP_FCGI_CHILDREN" => "$max_procs",
863
				"PHP_FCGI_MAX_REQUESTS" => "2",
864
			),
865

    
866
EOC;
867
	} else
868
		$bin_environment =  <<<EOC
869
			"bin-environment" => (
870
				"PHP_FCGI_CHILDREN" => "$max_procs",
871
				"PHP_FCGI_MAX_REQUESTS" => "500"
872
			),
873
EOC;
874

    
875
	if($fast_cgi_enable == true) {
876
		$module = "\"mod_fastcgi\", \"mod_cgi\"";
877
		if ($captive_portal != false)
878
			$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi-{$captive_portal}.socket";
879
		else
880
			$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi.socket";
881
		$cgi_config = "";
882
		$fastcgi_config = <<<EOD
883
#### fastcgi module
884
## read fastcgi.txt for more info
885
fastcgi.server = ( ".php" =>
886
	( "localhost" =>
887
		(
888
			"socket" => "{$fast_cgi_path}",
889
			"min-procs" => 0,
890
			"max-procs" => {$max_procs},
891
{$bin_environment}
892
			"bin-path" => "/usr/local/bin/php"
893
		)
894
	)
895
)
896

    
897
#### CGI module
898
cgi.assign                 = ( ".cgi" => "" )
899

    
900
EOD;
901
	} else {
902
		$fastcgi_config = "";
903
		$module = "\"mod_cgi\"";
904
		$cgi_config = <<<EOD
905
#### CGI module
906
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
907
                               ".cgi" => "" )
908

    
909
EOD;
910
	}
911

    
912
	$lighty_config = "";
913
	$lighty_config .= <<<EOD
914
#
915
# lighttpd configuration file
916
#
917
# use a it as base for lighttpd 1.0.0 and above
918
#
919
############ Options you really have to take care of ####################
920

    
921
## FreeBSD!
922
server.event-handler	= "freebsd-kqueue"
923
server.network-backend 	= "writev"
924
#server.use-ipv6 = "enable"
925

    
926
## modules to load
927
server.modules              =   (
928
	{$captive_portal_module}
929
	"mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect",
930
	{$module}{$captiveportal}
931
)
932

    
933
## Unused modules
934
#                               "mod_setenv",
935
#                               "mod_rewrite",
936
#                               "mod_ssi",
937
#                               "mod_usertrack",
938
#                               "mod_expire",
939
#                               "mod_secdownload",
940
#                               "mod_rrdtool",
941
#                               "mod_auth",
942
#                               "mod_status",
943
#                               "mod_alias",
944
#                               "mod_proxy",
945
#                               "mod_simple_vhost",
946
#                               "mod_evhost",
947
#                               "mod_userdir",
948
#                               "mod_cgi",
949

    
950
server.max-keep-alive-requests = 15
951
server.max-keep-alive-idle = 30
952

    
953
## a static document-root, for virtual-hosting take look at the
954
## server.virtual-* options
955
server.document-root        = "{$document_root}"
956
{$captive_portal_rewrite}
957

    
958
# Maximum idle time with nothing being written (php downloading)
959
server.max-write-idle = 999
960

    
961
## where to send error-messages to
962
server.errorlog             = "/var/log/lighttpd.error.log"
963

    
964
# files to check for if .../ is requested
965
server.indexfiles           = ( "index.php", "index.html",
966
                                "index.htm", "default.htm" )
967

    
968
# mimetype mapping
969
mimetype.assign             = (
970
  ".pdf"          =>      "application/pdf",
971
  ".sig"          =>      "application/pgp-signature",
972
  ".spl"          =>      "application/futuresplash",
973
  ".class"        =>      "application/octet-stream",
974
  ".ps"           =>      "application/postscript",
975
  ".torrent"      =>      "application/x-bittorrent",
976
  ".dvi"          =>      "application/x-dvi",
977
  ".gz"           =>      "application/x-gzip",
978
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
979
  ".swf"          =>      "application/x-shockwave-flash",
980
  ".tar.gz"       =>      "application/x-tgz",
981
  ".tgz"          =>      "application/x-tgz",
982
  ".tar"          =>      "application/x-tar",
983
  ".zip"          =>      "application/zip",
984
  ".mp3"          =>      "audio/mpeg",
985
  ".m3u"          =>      "audio/x-mpegurl",
986
  ".wma"          =>      "audio/x-ms-wma",
987
  ".wax"          =>      "audio/x-ms-wax",
988
  ".ogg"          =>      "audio/x-wav",
989
  ".wav"          =>      "audio/x-wav",
990
  ".gif"          =>      "image/gif",
991
  ".jpg"          =>      "image/jpeg",
992
  ".jpeg"         =>      "image/jpeg",
993
  ".png"          =>      "image/png",
994
  ".xbm"          =>      "image/x-xbitmap",
995
  ".xpm"          =>      "image/x-xpixmap",
996
  ".xwd"          =>      "image/x-xwindowdump",
997
  ".css"          =>      "text/css",
998
  ".html"         =>      "text/html",
999
  ".htm"          =>      "text/html",
1000
  ".js"           =>      "text/javascript",
1001
  ".asc"          =>      "text/plain",
1002
  ".c"            =>      "text/plain",
1003
  ".conf"         =>      "text/plain",
1004
  ".text"         =>      "text/plain",
1005
  ".txt"          =>      "text/plain",
1006
  ".dtd"          =>      "text/xml",
1007
  ".xml"          =>      "text/xml",
1008
  ".mpeg"         =>      "video/mpeg",
1009
  ".mpg"          =>      "video/mpeg",
1010
  ".mov"          =>      "video/quicktime",
1011
  ".qt"           =>      "video/quicktime",
1012
  ".avi"          =>      "video/x-msvideo",
1013
  ".asf"          =>      "video/x-ms-asf",
1014
  ".asx"          =>      "video/x-ms-asf",
1015
  ".wmv"          =>      "video/x-ms-wmv",
1016
  ".bz2"          =>      "application/x-bzip",
1017
  ".tbz"          =>      "application/x-bzip-compressed-tar",
1018
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
1019
 )
1020

    
1021
# Use the "Content-Type" extended attribute to obtain mime type if possible
1022
#mimetypes.use-xattr        = "enable"
1023

    
1024
#### accesslog module
1025
#accesslog.filename          = "/dev/null"
1026

    
1027
## deny access the file-extensions
1028
#
1029
# ~    is for backupfiles from vi, emacs, joe, ...
1030
# .inc is often used for code includes which should in general not be part
1031
#      of the document-root
1032
url.access-deny             = ( "~", ".inc" )
1033

    
1034

    
1035
######### Options that are good to be but not neccesary to be changed #######
1036

    
1037
## bind to port (default: 80)
1038

    
1039
EOD;
1040

    
1041
	if($captive_portal == true) {
1042
		$lighty_config .= "server.bind	= \"127.0.0.1\"\n";
1043
		$lighty_config .= "server.port  = {$lighty_port}\n";
1044
		$lighty_config .= "\$SERVER[\"socket\"]  == \"127.0.0.1:{$lighty_port}\" { }\n";
1045
		$lighty_config .= "\$SERVER[\"socket\"]  == \"[::1]:{$lighty_port}\" { \n";
1046
		if($cert <> "" and $key <> "") {
1047
			$lighty_config .= "\n";
1048
			$lighty_config .= "## ssl configuration\n";
1049
			$lighty_config .= "ssl.engine = \"enable\"\n";
1050
			$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1051
			if($ca <> "")
1052
				$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1053
		}
1054
		$lighty_config .= " }\n";
1055
	} else {
1056
		$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1057
		$lighty_config .= "server.port  = {$lighty_port}\n";
1058
		$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1059
		$lighty_config .= "\$SERVER[\"socket\"]  == \"[::]:{$lighty_port}\" { \n";
1060
		if($cert <> "" and $key <> "") {
1061
			$lighty_config .= "\n";
1062
			$lighty_config .= "## ssl configuration\n";
1063
			$lighty_config .= "ssl.engine = \"enable\"\n";
1064
			$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1065
			if($ca <> "")
1066
				$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1067
		}
1068
		$lighty_config .= " }\n";
1069
	}
1070

    
1071

    
1072
	$lighty_config .= <<<EOD
1073

    
1074
## error-handler for status 404
1075
#server.error-handler-404   = "/error-handler.html"
1076
#server.error-handler-404   = "/error-handler.php"
1077

    
1078
## to help the rc.scripts
1079
server.pid-file            = "/var/run/{$pid_file}"
1080

    
1081
## virtual directory listings
1082
server.dir-listing         = "disable"
1083

    
1084
## enable debugging
1085
debug.log-request-header   = "disable"
1086
debug.log-response-header  = "disable"
1087
debug.log-request-handling = "disable"
1088
debug.log-file-not-found   = "disable"
1089

    
1090
# gzip compression
1091
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1092
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1093

    
1094
{$server_upload_dirs}
1095

    
1096
{$server_max_request_size}
1097

    
1098
{$fastcgi_config}
1099

    
1100
{$cgi_config}
1101

    
1102
{$captive_portal_mod_evasive}
1103

    
1104
expire.url = (
1105
				"" => "access 50 hours",	
1106
        )
1107

    
1108
EOD;
1109

    
1110
	$cert = str_replace("\r", "", $cert);
1111
	$key = str_replace("\r", "", $key);
1112
	$ca = str_replace("\r", "", $ca);
1113

    
1114
	$cert = str_replace("\n\n", "\n", $cert);
1115
	$key = str_replace("\n\n", "\n", $key);
1116
	$ca = str_replace("\n\n", "\n", $ca);
1117

    
1118
	if($cert <> "" and $key <> "") {
1119
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1120
		if (!$fd) {
1121
			printf(gettext("Error: cannot open cert.pem in system_webgui_start().%s"), "\n");
1122
			return 1;
1123
		}
1124
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1125
		fwrite($fd, $cert);
1126
		fwrite($fd, "\n");
1127
		fwrite($fd, $key);
1128
		fclose($fd);
1129
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
1130
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1131
			if (!$fd) {
1132
				printf(gettext("Error: cannot open ca.pem in system_webgui_start().%s"), "\n");
1133
				return 1;
1134
			}
1135
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1136
			fwrite($fd, $ca);
1137
			fclose($fd);
1138
		}
1139
		$lighty_config .= "\n";
1140
		$lighty_config .= "## " . gettext("ssl configuration") . "\n";
1141
		$lighty_config .= "ssl.engine = \"enable\"\n";
1142
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1143

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

    
1148
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1149
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1150
	}
1151

    
1152
	// Add HTTP to HTTPS redirect	
1153
	if ($captive_portal == false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1154
		if($lighty_port != "443") 
1155
			$redirectport = ":{$lighty_port}";
1156
		$lighty_config .= <<<EOD
1157
\$SERVER["socket"] == ":80" {
1158
	\$HTTP["host"] =~ "(.*)" {
1159
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1160
	}
1161
}
1162
EOD;
1163
	}
1164

    
1165
	$fd = fopen("{$filename}", "w");
1166
	if (!$fd) {
1167
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1168
		return 1;
1169
	}
1170
	fwrite($fd, $lighty_config);
1171
	fclose($fd);
1172

    
1173
	return 0;
1174

    
1175
}
1176

    
1177
function system_timezone_configure() {
1178
	global $config, $g;
1179
	if(isset($config['system']['developerspew'])) {
1180
		$mt = microtime();
1181
		echo "system_timezone_configure() being called $mt\n";
1182
	}
1183

    
1184
	$syscfg = $config['system'];
1185

    
1186
	if ($g['booting'])
1187
		echo gettext("Setting timezone...");
1188

    
1189
	/* extract appropriate timezone file */
1190
	$timezone = $syscfg['timezone'];
1191
	if (!$timezone)
1192
		$timezone = "Etc/UTC";
1193

    
1194
	conf_mount_rw();
1195

    
1196
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1197
		escapeshellarg($timezone) . " > /etc/localtime");
1198

    
1199
	mwexec("sync");
1200
	conf_mount_ro();
1201

    
1202
	if ($g['booting'])
1203
		echo gettext("done.") . "\n";
1204
}
1205

    
1206
function system_ntp_configure() {
1207
	global $config, $g;
1208

    
1209
	if ($g['platform'] == 'jail')
1210
		return;
1211

    
1212
	$ntpcfg = "# \n";
1213
	$ntpcfg .= "# pfSense OpenNTPD configuration file \n";
1214
	$ntpcfg .= "# \n\n";
1215

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

    
1220
	/* Setup listener(s) if the user has configured one */
1221
        if ($config['installedpackages']['openntpd']) {
1222
    		/* server config is in coregui1 */
1223
		$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
1224
		if ($xmlsettings['enable'] == 'on') {
1225
			$ifaces = explode(',', $xmlsettings['interface']);
1226
			$ips = array();
1227
			foreach ($ifaces as $if) {
1228
				if (is_ipaddr($if)) {
1229
					$ips[] = $if;
1230
				} else {
1231
					$if = get_real_interface($if);
1232
					if (does_interface_exist($if))
1233
						$ips[] = find_interface_ip($if);
1234
				}
1235
			}
1236
			foreach ($ips as $ip) {
1237
				if (is_ipaddr($ip))
1238
					$ntpcfg .= "listen on $ip\n";
1239
			}
1240
		}
1241
	}
1242
	$ntpcfg .= "\n";
1243

    
1244
	/* open configuration for wrting or bail */
1245
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1246
	if(!$fd) {
1247
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1248
		return;
1249
	}
1250
	fwrite($fd, $ntpcfg);
1251

    
1252
	/* slurp! */
1253
	fclose($fd);
1254

    
1255
	/* if openntpd is running, kill it */
1256
	while(is_process_running("ntpd")) {
1257
		killbyname("ntpd");
1258
	}
1259

    
1260
	/* if /var/empty does not exist, create it */
1261
	if(!is_dir("/var/empty"))
1262
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1263

    
1264
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1265
	exec("/usr/local/sbin/ntpd -s -f {$g['varetc_path']}/ntpd.conf");
1266
	
1267
	// Note that we are starting up
1268
	log_error("OpenNTPD is starting up.");
1269

    
1270
}
1271

    
1272
function sync_system_time() {
1273
	global $config, $g;
1274

    
1275
	if ($g['booting'])
1276
		echo gettext("Syncing system time before startup...");
1277

    
1278
	/* foreach through servers and write out to ntpd.conf */
1279
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1280
		mwexec("/usr/sbin/ntpdate -s $ts");
1281
	}
1282
	
1283
	if ($g['booting'])
1284
		echo gettext("done.") . "\n";
1285
	
1286
}
1287

    
1288
function system_halt() {
1289
	global $g;
1290

    
1291
	system_reboot_cleanup();
1292

    
1293
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1294
}
1295

    
1296
function system_reboot() {
1297
	global $g;
1298

    
1299
	system_reboot_cleanup();
1300

    
1301
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1302
}
1303

    
1304
function system_reboot_sync() {
1305
	global $g;
1306

    
1307
	system_reboot_cleanup();
1308

    
1309
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1310
}
1311

    
1312
function system_reboot_cleanup() {
1313
	mwexec("/usr/local/bin/beep.sh stop");
1314
	require_once("captiveportal.inc");
1315
	captiveportal_radius_stop_all();
1316
	require_once("voucher.inc");
1317
	voucher_save_db_to_config();
1318
	mwexec("/etc/rc.stop_packages");
1319
}
1320

    
1321
function system_do_shell_commands($early = 0) {
1322
	global $config, $g;
1323
	if(isset($config['system']['developerspew'])) {
1324
		$mt = microtime();
1325
		echo "system_do_shell_commands() being called $mt\n";
1326
	}
1327

    
1328
	if ($early)
1329
		$cmdn = "earlyshellcmd";
1330
	else
1331
		$cmdn = "shellcmd";
1332

    
1333
	if (is_array($config['system'][$cmdn])) {
1334

    
1335
		/* *cmd is an array, loop through */
1336
		foreach ($config['system'][$cmdn] as $cmd) {
1337
			exec($cmd);
1338
		}
1339

    
1340
	} elseif($config['system'][$cmdn] <> "") {
1341

    
1342
		/* execute single item */
1343
		exec($config['system'][$cmdn]);
1344

    
1345
	}
1346
}
1347

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

    
1355
	if (isset($config['system']['disableconsolemenu'])) {
1356
		touch("{$g['varetc_path']}/disableconsole");
1357
	} else {
1358
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1359
	}
1360
}
1361

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

    
1369
	$dmesg = "";
1370
	exec("/sbin/dmesg", $dmesg);
1371

    
1372
	/* find last copyright line (output from previous boots may be present) */
1373
	$lastcpline = 0;
1374

    
1375
	for ($i = 0; $i < count($dmesg); $i++) {
1376
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1377
			$lastcpline = $i;
1378
	}
1379

    
1380
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1381
	if (!$fd) {
1382
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1383
		return 1;
1384
	}
1385

    
1386
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1387
		fwrite($fd, $dmesg[$i] . "\n");
1388

    
1389
	fclose($fd);
1390

    
1391
	return 0;
1392
}
1393

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

    
1401
	if (isset($config['system']['harddiskstandby'])) {
1402
		if ($g['booting']) {
1403
			echo gettext('Setting hard disk standby... ');
1404
		}
1405

    
1406
		$standby = $config['system']['harddiskstandby'];
1407
		// Check for a numeric value
1408
		if (is_numeric($standby)) {
1409
			// Sync the disk(s)
1410
			pfSense_sync();
1411
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1412
				// Reinitialize ATA-drives
1413
				mwexec('/usr/local/sbin/atareinit');
1414
				if ($g['booting']) {
1415
					echo gettext("done.") . "\n";
1416
				}
1417
			} else if ($g['booting']) {
1418
				echo gettext("failed!") . "\n";
1419
			}
1420
		} else if ($g['booting']) {
1421
			echo gettext("failed!") . "\n";
1422
		}
1423
	}
1424
}
1425

    
1426
function system_setup_sysctl() {
1427
	global $config;
1428
	if(isset($config['system']['developerspew'])) {
1429
		$mt = microtime();
1430
		echo "system_setup_sysctl() being called $mt\n";
1431
	}
1432

    
1433
	activate_sysctls();	
1434

    
1435
	if (isset($config['system']['sharednet'])) {
1436
		system_disable_arp_wrong_if();
1437
	}
1438
}
1439

    
1440
function system_disable_arp_wrong_if() {
1441
	global $config;
1442
	if(isset($config['system']['developerspew'])) {
1443
		$mt = microtime();
1444
		echo "system_disable_arp_wrong_if() being called $mt\n";
1445
	}
1446
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1447
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1448
}
1449

    
1450
function system_enable_arp_wrong_if() {
1451
	global $config;
1452
	if(isset($config['system']['developerspew'])) {
1453
		$mt = microtime();
1454
		echo "system_enable_arp_wrong_if() being called $mt\n";
1455
	}
1456
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1457
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1458
}
1459

    
1460
function enable_watchdog() {
1461
	global $config;
1462
	return;
1463
	$install_watchdog = false;
1464
	$supported_watchdogs = array("Geode");
1465
	$file = file_get_contents("/var/log/dmesg.boot");
1466
	foreach($supported_watchdogs as $sd) {
1467
		if(stristr($file, "Geode")) {
1468
			$install_watchdog = true;
1469
		}
1470
	}
1471
	if($install_watchdog == true) {
1472
		if(is_process_running("watchdogd"))
1473
			mwexec("/usr/bin/killall watchdogd", true);
1474
		exec("/usr/sbin/watchdogd");
1475
	}
1476
}
1477

    
1478
function system_check_reset_button() {
1479
	global $g;
1480
	if($g['platform'] != "nanobsd")
1481
		return 0;
1482

    
1483
	$specplatform = system_identify_specific_platform();
1484

    
1485
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1486
		return 0;
1487

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

    
1490
	if ($retval == 99) {
1491
		/* user has pressed reset button for 2 seconds - 
1492
		   reset to factory defaults */
1493
		echo <<<EOD
1494

    
1495
***********************************************************************
1496
* Reset button pressed - resetting configuration to factory defaults. *
1497
* The system will reboot after this completes.                        *
1498
***********************************************************************
1499

    
1500

    
1501
EOD;
1502
		
1503
		reset_factory_defaults();
1504
		system_reboot_sync();
1505
		exit(0);
1506
	}
1507

    
1508
	return 0;
1509
}
1510

    
1511
/* attempt to identify the specific platform (for embedded systems)
1512
   Returns an array with two elements:
1513
	name => platform string (e.g. 'wrap', 'alix' etc.)
1514
	descr => human-readable description (e.g. "PC Engines WRAP")
1515
*/
1516
function system_identify_specific_platform() {
1517
	global $g;
1518
	
1519
	if ($g['platform'] == 'generic-pc')
1520
		return array('name' => 'generic-pc', 'descr' => gettext("Generic PC"));
1521
	
1522
	if ($g['platform'] == 'generic-pc-cdrom')
1523
		return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)"));
1524
	
1525
	/* the rest of the code only deals with 'embedded' platforms */
1526
	if ($g['platform'] != 'nanobsd')
1527
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1528
	
1529
	$dmesg = system_get_dmesg_boot();
1530
	
1531
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1532
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
1533
	
1534
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1535
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
1536

    
1537
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1538
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1539
	
1540
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1541
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1542
		
1543
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1544
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1545
	
1546
	/* unknown embedded platform */
1547
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
1548
}
1549

    
1550
function system_get_dmesg_boot() {
1551
	global $g;
1552
		
1553
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1554
}
1555

    
1556
function get_possible_listen_ips() {
1557
	$interfaces = get_configured_interface_with_descr();
1558
	$carplist = get_configured_carp_interface_list();
1559
	$listenips = array();
1560
	foreach ($carplist as $cif => $carpip)
1561
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1562
	$aliaslist = get_configured_ip_aliases_list();
1563
	foreach ($aliaslist as $aliasip => $aliasif)
1564
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1565
	foreach ($interfaces as $iface => $ifacename) {
1566
		$tmp["name"]  = $ifacename;
1567
		$tmp["value"] = $iface;
1568
		$listenips[] = $tmp;
1569
	}
1570
	$tmp["name"]  = "Localhost";
1571
	$tmp["value"] = "lo0";
1572
	$listenips[] = $tmp;
1573
	return $listenips;
1574
}
1575

    
1576
?>
(49-49/64)