Project

General

Profile

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
93
	$havedns = false;
94

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

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

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

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

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

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

    
157
	unlock($dnslock);
158

    
159
	return 0;
160
}
161

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

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

    
181
	return $master_list;
182
}
183

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

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

    
212
	return $master_list;
213
}
214

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

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

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

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

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

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

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

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

    
286
	system_dhcpleases_configure();
287

    
288
	return 0;
289
}
290

    
291
function system_dhcpleases_configure() {
292
	global $config, $g;
293
	
294
	/* Start the monitoring process for dynamic dhcpclients. */
295
	if (isset($config['dnsmasq']['regdhcp'])) {
296
		/* Make sure we do not error out */
297
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
298
		if (file_exists("{$g['varrun_path']}/dhcpleases.pid"))
299
				sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "HUP");
300
		else
301
			mwexec("/usr/local/sbin/dhcpleases -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases -d {$config['system']['domain']} -p {$g['varrun_path']}/dnsmasq.pid -h {$g['varetc_path']}/hosts");
302
	} else {
303
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
304
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
305
	}
306
}
307

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

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

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

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

    
324
	return $status;
325
}
326

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

    
334
	$gatewayip = "";
335
	$interfacegw = "";
336
	$foundgw = false;
337
	/* tack on all the hard defined gateways as well */
338
	if (is_array($config['gateways']['gateway_item'])) {
339
		mwexec("/bin/rm {$g['tmp_path']}/*_defaultgw", true);
340
		foreach	($config['gateways']['gateway_item'] as $gateway) {
341
			if (isset($gateway['defaultgw'])) {
342
				if(strstr($gateway['gateway'], ":"))
343
					break;
344
				if ($gateway['gateway'] == "dynamic")
345
					$gateway['gateway'] = get_interface_gateway($gateway['interface']);
346
				$gatewayip = $gateway['gateway'];
347
				$interfacegw = $gateway['interface'];
348
				if (!empty($interfacegw)) {
349
					$defaultif = get_real_interface($gateway['interface']);
350
					if ($defaultif)
351
						@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gatewayip);
352
				}
353
				$foundgw = true;
354
				break;
355
			}
356
		}
357
	}
358
	if ($foundgw == false) {
359
		$defaultif = get_real_interface("wan");
360
		$interfacegw = "wan";
361
		$gatewayip = get_interface_gateway("wan");
362
		@touch("{$g['tmp_path']}/{$defaultif}_defaultgw");
363
	}	
364
	$dont_add_route = false;
365
	/* if OLSRD is enabled, allow WAN to house DHCP. */
366
	if($config['installedpackages']['olsrd']) {
367
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
368
			if($olsrd['enabledyngw'] == "on") {
369
				$dont_add_route = true;
370
				break;
371
			}
372
		}
373
	}
374
	/* Create a array from the existing route table */
375
	exec("/usr/bin/netstat -rnf inet", $route_str);
376
	array_shift($route_str);
377
	array_shift($route_str);
378
	array_shift($route_str);
379
	array_shift($route_str);
380
	$route_arr = array();
381
	foreach($route_str as $routeline) {
382
		$items = preg_split("/[ ]+/i", $routeline);
383
		$route_arr[$items[0]] = array($items[0], $items[1], $items[5]);
384
	}
385

    
386
	if ($dont_add_route == false ) {
387
		if (!empty($interface) && $interface != $interfacegw)
388
			;
389
		else if (($interfacegw <> "bgpd") && (is_ipaddr($gatewayip))) {
390
			$action = "add";
391
			if(isset($route_arr['default'])) {
392
				$action = "change";
393
			}
394
			log_error("ROUTING: $action default route to $gatewayip");
395
			mwexec("/sbin/route {$action} -inet default " . escapeshellarg($gatewayip));
396
		}
397
	}
398

    
399
	if (is_array($config['staticroutes']['route'])) {
400
		$gateways_arr = return_gateways_array();
401

    
402
		foreach ($config['staticroutes']['route'] as $rtent) {
403
			$gatewayip = "";
404
			if (empty($gateways_arr[$rtent['gateway']])) {
405
				log_error("Static Routes: Gateway IP could not be found for {$rtent['network']}");
406
				continue;
407
			}
408
			$gateway = $gateways_arr[$rtent['gateway']];
409
			if (!empty($interface) && $interface != $gateway['friendlyiface'])
410
				continue;
411
			$gatewayip = $gateway['gateway'];
412
			$interfacegw = $gateway['interface'];
413
			$action = "add";
414
			if (isset($route_arr[$rtent['network']]))
415
				$action = "change";
416

    
417
			if (is_ipaddr($gatewayip)) {
418
				mwexec("/sbin/route {$action} -inet " . escapeshellarg($rtent['network']) .
419
					" " . escapeshellarg($gatewayip));
420
			} else if (!empty($interfacegw)) {
421
				mwexec("/sbin/route {$action} -inet " . escapeshellarg($rtent['network']) .
422
					" -iface " . escapeshellarg($interfacegw));
423
			}
424
		}
425
	}
426

    
427
	return 0;
428
}
429

    
430
function system_routing_enable() {
431
	global $config, $g;
432
	if(isset($config['system']['developerspew'])) {
433
		$mt = microtime();
434
		echo "system_routing_enable() being called $mt\n";
435
	}
436

    
437
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
438
}
439

    
440
function system_syslogd_start() {
441
	global $config, $g;
442
	if(isset($config['system']['developerspew'])) {
443
		$mt = microtime();
444
		echo "system_syslogd_start() being called $mt\n";
445
	}
446

    
447
	$syslogcfg = $config['syslog'];
448

    
449
	if ($g['booting'])
450
		echo "Starting syslog...";
451
	else
452
		killbypid("{$g['varrun_path']}/syslog.pid");
453

    
454
	if(is_process_running("syslogd"))
455
		mwexec("/usr/bin/killall -9 syslogd");
456
	if(is_process_running("fifolog_writer"))
457
		mwexec("/usr/bin/killall -9 fifolog_writer");
458
	
459
	// Define carious commands for logging
460
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
461
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
462
	$clog_create = "/usr/sbin/clog -i -s ";
463
	$clog_log = "%";
464

    
465
	// Which logging type are we using this week??
466
	if(isset($config['system']['usefifolog'])) {
467
		$log_directive = $fifolog_log;
468
		$log_create_directive = $fifolog_create;		
469
	} else { // Defaults to CLOG
470
		$log_directive = $clog_log;
471
		$log_create_directive = $clog_create;
472
	}
473
	
474
	if (isset($syslogcfg)) {
475
		$separatelogfacilities = array('ntpd','racoon','openvpn','pptps','poes','l2tps');
476
		if($config['installedpackages']['package']) {
477
			foreach($config['installedpackages']['package'] as $package) {
478
				if($package['logging']) {
479
					array_push($separatelogfacilities, $package['logging']['facilityname']);
480
					mwexec("{$log_create_directive} 10240 {$g['varlog_path']}/{$package['logging']['logfilename']}");
481
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
482
				}
483
			}
484
		}
485
		$facilitylist = implode(',', array_unique($separatelogfacilities));
486
		/* write syslog.conf */		
487
		$fd = fopen("{$g['varetc_path']}/syslog.conf", "w");
488
		if (!$fd) {
489
			printf("Error: cannot open syslog.conf in system_syslogd_start().\n");
490
			return 1;
491
		}
492
		$syslogconf .= "!ntpdate,!ntpd\n";
493
		if (!isset($syslogcfg['disablelocallogging'])) 
494
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/ntpd.log\n";
495
		$syslogconf .= "!ppp\n";
496
		if (!isset($syslogcfg['disablelocallogging'])) 
497
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/ppp.log\n";
498
		$syslogconf .= "!pptps\n";
499
		if (!isset($syslogcfg['disablelocallogging'])) 
500
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/pptps.log\n";
501
		$syslogconf .= "!poes\n";
502
		if (!isset($syslogcfg['disablelocallogging'])) 
503
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/poes.log\n";
504
		$syslogconf .= "!l2tps\n";
505
		if (!isset($syslogcfg['disablelocallogging'])) 
506
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/l2tps.log\n";
507
		$syslogconf .= "!racoon\n";
508
		if (!isset($syslogcfg['disablelocallogging'])) 
509
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/ipsec.log\n";
510
		if (isset($syslogcfg['vpn'])) {
511
			if($syslogcfg['remoteserver'])
512
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver']}\n";
513
			if($syslogcfg['remoteserver2'])
514
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver2']}\n";
515
			if($syslogcfg['remoteserver3'])
516
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver3']}\n";
517
		}
518
		$syslogconf .= "!openvpn\n";
519
		if (!isset($syslogcfg['disablelocallogging'])) 
520
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/openvpn.log\n";
521
		if (isset($syslogcfg['vpn'])) {
522
			if($syslogcfg['remoteserver'])
523
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver']}\n";
524
			if($syslogcfg['remoteserver2'])
525
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver3']}\n";
526
			if($syslogcfg['remoteserver3'])
527
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver3']}\n";
528
		}
529
		$syslogconf .= "!apinger\n";
530
		if (!isset($syslogcfg['disablelocallogging']))
531
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/apinger.log\n";
532
		$syslogconf .= "!relayd\n";
533
		$syslogconf .= "*.* 						{$log_directive}{$g['varlog_path']}/relayd.log\n";
534
		$syslogconf .= "!-{$facilitylist}\n";
535
		if (!isset($syslogcfg['disablelocallogging'])) 
536
			$syslogconf .= <<<EOD
537
local0.*										 {$log_directive}{$g['varlog_path']}/filter.log
538
local3.*										 {$log_directive}{$g['varlog_path']}/vpn.log
539
local4.*										 {$log_directive}{$g['varlog_path']}/portalauth.log
540
local7.*										 {$log_directive}{$g['varlog_path']}/dhcpd.log
541
*.notice;kern.debug;lpr.info;mail.crit; 		 {$log_directive}{$g['varlog_path']}/system.log
542
news.err;local0.none;local3.none;local4.none; 	 {$log_directive}{$g['varlog_path']}/system.log
543
local7.none										 {$log_directive}{$g['varlog_path']}/system.log
544
security.*										 {$log_directive}{$g['varlog_path']}/system.log
545
auth.info;authpriv.info;daemon.info				 {$log_directive}{$g['varlog_path']}/system.log
546
auth.info;authpriv.info 						 |exec /usr/local/sbin/sshlockout_pf 15
547
*.emerg											 *
548

    
549
EOD;
550
		if (isset($syslogcfg['filter'])) {
551
			if($syslogcfg['remoteserver'])
552
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver']}\n";
553
			if($syslogcfg['remoteserver2'])
554
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver2']}\n";
555
			if($syslogcfg['remoteserver3'])
556
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver3']}\n";
557

    
558
		}
559
		if (isset($syslogcfg['vpn'])) {
560
			if($syslogcfg['remoteserver'])
561
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver']}\n";
562
			if($syslogcfg['remoteserver2'])
563
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver2']}\n";
564
			if($syslogcfg['remoteserver3'])
565
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver3']}\n";
566
		}
567
		if (isset($syslogcfg['portalauth'])) {
568
			if($syslogcfg['remoteserver'])
569
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver']}\n";
570
			if($syslogcfg['remoteserver2'])
571
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver2']}\n";
572
			if($syslogcfg['remoteserver3'])
573
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver3']}\n";
574
		}
575
		if (isset($syslogcfg['dhcp'])) {
576
			if($syslogcfg['remoteserver'])
577
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver']}\n";
578
			if($syslogcfg['remoteserver2'])
579
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver2']}\n";
580
			if($syslogcfg['remoteserver3'])
581
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver3']}\n";
582
		}
583
		if (isset($syslogcfg['system'])) {
584
			if($syslogcfg['remoteserver'])
585
				$syslogconf .= <<<EOD
586
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver']}
587
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver']}
588
security.*										 @{$syslogcfg['remoteserver']}
589
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver']}
590
*.emerg											 @{$syslogcfg['remoteserver']}
591

    
592
EOD;
593

    
594
}
595

    
596
		if (isset($syslogcfg['system'])) {
597
			if($syslogcfg['remoteserver2'])
598
				$syslogconf .= <<<EOD
599
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver2']}
600
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver2']}
601
security.*										 @{$syslogcfg['remoteserver2']}
602
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver2']}
603
*.emerg											 @{$syslogcfg['remoteserver2']}
604

    
605
EOD;
606

    
607
}
608

    
609
		if (isset($syslogcfg['system'])) {
610
			if($syslogcfg['remoteserver3'])
611
				$syslogconf .= <<<EOD
612
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver3']}
613
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver3']}
614
security.*										 @{$syslogcfg['remoteserver3']}
615
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver3']}
616
*.emerg											 @{$syslogcfg['remoteserver3']}
617

    
618
EOD;
619

    
620
}
621
		if (isset($syslogcfg['logall'])) {
622
			if($syslogcfg['remoteserver'])
623
				$syslogconf .= <<<EOD
624
*.*								@{$syslogcfg['remoteserver']}
625

    
626
EOD;
627

    
628
			if($syslogcfg['remoteserver2'])
629
				$syslogconf .= <<<EOD
630
*.*								@{$syslogcfg['remoteserver2']}
631

    
632
EOD;
633

    
634
			if($syslogcfg['remoteserver3'])
635
				$syslogconf .= <<<EOD
636
*.*								@{$syslogcfg['remoteserver3']}
637

    
638
EOD;
639

    
640
}
641
		fwrite($fd, $syslogconf);
642
		fclose($fd);
643

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

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

    
654
	} else {
655
		$retval = mwexec("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log");
656
	}
657

    
658
	if ($g['booting'])
659
		echo "done.\n";
660

    
661
	return $retval;
662
}
663

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

    
671
	if ($g['booting'])
672
		echo "Initializing PCMCIA...";
673

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

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

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

    
687
	return $res;
688
}
689

    
690

    
691
function system_webgui_start() {
692
	global $config, $g;
693

    
694
	if ($g['booting'])
695
		echo "Starting webConfigurator...";
696

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

    
700
	sleep(1);
701

    
702
	chdir($g['www_path']);
703

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

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

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

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

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

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

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

    
772
	return $res;
773
}
774

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

    
789
	global $config, $g;
790

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

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

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

    
826
	$memory = get_memory();
827
	$avail = $memory[0];
828

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

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

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

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

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

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

    
895
#### CGI module
896
cgi.assign                 = ( ".cgi" => "" )
897

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

    
907
EOD;
908
	}
909

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

    
919
## FreeBSD!
920
server.event-handler	= "freebsd-kqueue"
921
server.network-backend 	= "writev"
922

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

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

    
947
server.max-keep-alive-requests = 15
948
server.max-keep-alive-idle = 30
949

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

    
955
# Maximum idle time with nothing being written (php downloading)
956
server.max-write-idle = 999
957

    
958
## where to send error-messages to
959
server.errorlog             = "/var/log/lighttpd.error.log"
960

    
961
# files to check for if .../ is requested
962
server.indexfiles           = ( "index.php", "index.html",
963
                                "index.htm", "default.htm" )
964

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

    
1018
# Use the "Content-Type" extended attribute to obtain mime type if possible
1019
#mimetypes.use-xattr        = "enable"
1020

    
1021
#### accesslog module
1022
#accesslog.filename          = "/dev/null"
1023

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

    
1031

    
1032
######### Options that are good to be but not neccesary to be changed #######
1033

    
1034
## bind to port (default: 80)
1035
server.port                = {$lighty_port}
1036

    
1037
## error-handler for status 404
1038
#server.error-handler-404   = "/error-handler.html"
1039
#server.error-handler-404   = "/error-handler.php"
1040

    
1041
## to help the rc.scripts
1042
server.pid-file            = "/var/run/{$pid_file}"
1043

    
1044
## virtual directory listings
1045
server.dir-listing         = "disable"
1046

    
1047
## enable debugging
1048
debug.log-request-header   = "disable"
1049
debug.log-response-header  = "disable"
1050
debug.log-request-handling = "disable"
1051
debug.log-file-not-found   = "disable"
1052

    
1053
# gzip compression
1054
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1055
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1056

    
1057
{$server_upload_dirs}
1058

    
1059
{$server_max_request_size}
1060

    
1061
{$fastcgi_config}
1062

    
1063
{$cgi_config}
1064

    
1065
{$captive_portal_mod_evasive}
1066

    
1067
expire.url = (
1068
				"" => "access 50 hours",	
1069
        )
1070

    
1071
EOD;
1072

    
1073
	$cert = str_replace("\r", "", $cert);
1074
	$key = str_replace("\r", "", $key);
1075
	$ca = str_replace("\r", "", $ca);
1076

    
1077
	$cert = str_replace("\n\n", "\n", $cert);
1078
	$key = str_replace("\n\n", "\n", $key);
1079
	$ca = str_replace("\n\n", "\n", $ca);
1080

    
1081
	if($cert <> "" and $key <> "") {
1082
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1083
		if (!$fd) {
1084
			printf("Error: cannot open cert.pem in system_webgui_start().\n");
1085
			return 1;
1086
		}
1087
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1088
		fwrite($fd, $cert);
1089
		fwrite($fd, "\n");
1090
		fwrite($fd, $key);
1091
		fclose($fd);
1092
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
1093
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1094
			if (!$fd) {
1095
				printf("Error: cannot open ca.pem in system_webgui_start().\n");
1096
				return 1;
1097
			}
1098
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1099
			fwrite($fd, $ca);
1100
			fclose($fd);
1101
		}
1102
		$lighty_config .= "\n";
1103
		$lighty_config .= "## ssl configuration\n";
1104
		$lighty_config .= "ssl.engine = \"enable\"\n";
1105
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1106

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

    
1111
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1112
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1113
	}
1114

    
1115
	// Add HTTP to HTTPS redirect	
1116
	if ($captive_portal == false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1117
		if($lighty_port != "443") 
1118
			$redirectport = ":{$lighty_port}";
1119
		$lighty_config .= <<<EOD
1120
\$SERVER["socket"] == ":80" {
1121
	\$HTTP["host"] =~ "(.*)" {
1122
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1123
	}
1124
}
1125
EOD;
1126
	}
1127

    
1128
	$fd = fopen("{$filename}", "w");
1129
	if (!$fd) {
1130
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
1131
		return 1;
1132
	}
1133
	fwrite($fd, $lighty_config);
1134
	fclose($fd);
1135

    
1136
	return 0;
1137

    
1138
}
1139

    
1140
function system_timezone_configure() {
1141
	global $config, $g;
1142
	if(isset($config['system']['developerspew'])) {
1143
		$mt = microtime();
1144
		echo "system_timezone_configure() being called $mt\n";
1145
	}
1146

    
1147
	$syscfg = $config['system'];
1148

    
1149
	if ($g['booting'])
1150
		echo "Setting timezone...";
1151

    
1152
	/* extract appropriate timezone file */
1153
	$timezone = $syscfg['timezone'];
1154
	if (!$timezone)
1155
		$timezone = "Etc/UTC";
1156

    
1157
	conf_mount_rw();
1158

    
1159
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1160
		escapeshellarg($timezone) . " > /etc/localtime");
1161

    
1162
	mwexec("sync");
1163
	conf_mount_ro();
1164

    
1165
	if ($g['booting'])
1166
		echo "done.\n";
1167
}
1168

    
1169
function system_ntp_configure() {
1170
	global $config, $g;
1171

    
1172
	$ntpcfg = "# \n";
1173
	$ntpcfg .= "# pfSense OpenNTPD configuration file \n";
1174
	$ntpcfg .= "# \n\n";
1175

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

    
1180
	/* Setup listener(s) if the user has configured one */
1181
        if ($config['installedpackages']['openntpd']) {
1182
    		/* server config is in coregui1 */
1183
		$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
1184
		if ($xmlsettings['enable'] == 'on') {
1185
			$ifaces = explode(',', $xmlsettings['interface']);
1186
			$ips = array();
1187
			foreach ($ifaces as $if) {
1188
				if (is_ipaddr($if)) {
1189
					$ips[] = $if;
1190
				} else {
1191
					$if = get_real_interface($if);
1192
					if (does_interface_exist($if))
1193
						$ips[] = find_interface_ip($if);
1194
				}
1195
			}
1196
			foreach ($ips as $ip) {
1197
				if (is_ipaddr($ip))
1198
					$ntpcfg .= "listen on $ip\n";
1199
			}
1200
		}
1201
	}
1202
	$ntpcfg .= "\n";
1203

    
1204
	/* open configuration for wrting or bail */
1205
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1206
	if(!$fd) {
1207
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1208
		return;
1209
	}
1210
	fwrite($fd, $ntpcfg);
1211

    
1212
	/* slurp! */
1213
	fclose($fd);
1214

    
1215
	/* if openntpd is running, kill it */
1216
	while(is_process_running("ntpd")) {
1217
		killbyname("ntpd");
1218
	}
1219

    
1220
	/* if /var/empty does not exist, create it */
1221
	if(!is_dir("/var/empty"))
1222
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1223

    
1224
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1225
	exec("/usr/local/sbin/ntpd -s -f {$g['varetc_path']}/ntpd.conf");
1226
	
1227
	// Note that we are starting up
1228
	log_error("OpenNTPD is starting up.");
1229

    
1230
}
1231

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

    
1235
	if ($g['booting'])
1236
		echo "Syncing system time before startup...";
1237

    
1238
	/* foreach through servers and write out to ntpd.conf */
1239
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1240
		mwexec("/usr/sbin/ntpdate -s $ts");
1241
	}
1242
	
1243
	if ($g['booting'])
1244
		echo "done.\n";
1245
	
1246
}
1247

    
1248
function system_halt() {
1249
	global $g;
1250

    
1251
	system_reboot_cleanup();
1252

    
1253
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1254
}
1255

    
1256
function system_reboot() {
1257
	global $g;
1258

    
1259
	system_reboot_cleanup();
1260

    
1261
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1262
}
1263

    
1264
function system_reboot_sync() {
1265
	global $g;
1266

    
1267
	system_reboot_cleanup();
1268

    
1269
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1270
}
1271

    
1272
function system_reboot_cleanup() {
1273
	mwexec("/usr/local/bin/beep.sh stop");
1274
	require_once("captiveportal.inc");
1275
	captiveportal_radius_stop_all();
1276
	require_once("voucher.inc");
1277
	voucher_save_db_to_config();
1278
	// mwexec("/etc/rc.stop_packages");
1279
}
1280

    
1281
function system_do_shell_commands($early = 0) {
1282
	global $config, $g;
1283
	if(isset($config['system']['developerspew'])) {
1284
		$mt = microtime();
1285
		echo "system_do_shell_commands() being called $mt\n";
1286
	}
1287

    
1288
	if ($early)
1289
		$cmdn = "earlyshellcmd";
1290
	else
1291
		$cmdn = "shellcmd";
1292

    
1293
	if (is_array($config['system'][$cmdn])) {
1294

    
1295
		/* *cmd is an array, loop through */
1296
		foreach ($config['system'][$cmdn] as $cmd) {
1297
			exec($cmd);
1298
		}
1299

    
1300
	} elseif($config['system'][$cmdn] <> "") {
1301

    
1302
		/* execute single item */
1303
		exec($config['system'][$cmdn]);
1304

    
1305
	}
1306
}
1307

    
1308
function system_console_configure() {
1309
	global $config, $g;
1310
	if(isset($config['system']['developerspew'])) {
1311
		$mt = microtime();
1312
		echo "system_console_configure() being called $mt\n";
1313
	}
1314

    
1315
	if (isset($config['system']['disableconsolemenu'])) {
1316
		touch("{$g['varetc_path']}/disableconsole");
1317
	} else {
1318
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1319
	}
1320
}
1321

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

    
1329
	$dmesg = "";
1330
	exec("/sbin/dmesg", $dmesg);
1331

    
1332
	/* find last copyright line (output from previous boots may be present) */
1333
	$lastcpline = 0;
1334

    
1335
	for ($i = 0; $i < count($dmesg); $i++) {
1336
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1337
			$lastcpline = $i;
1338
	}
1339

    
1340
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1341
	if (!$fd) {
1342
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1343
		return 1;
1344
	}
1345

    
1346
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1347
		fwrite($fd, $dmesg[$i] . "\n");
1348

    
1349
	fclose($fd);
1350

    
1351
	return 0;
1352
}
1353

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

    
1361
	if (isset($config['system']['harddiskstandby'])) {
1362
		if ($g['booting']) {
1363
			echo 'Setting hard disk standby... ';
1364
		}
1365

    
1366
		$standby = $config['system']['harddiskstandby'];
1367
		// Check for a numeric value
1368
		if (is_numeric($standby)) {
1369
			// Sync the disk(s)
1370
			pfSense_sync();
1371
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1372
				// Reinitialize ATA-drives
1373
				mwexec('/usr/local/sbin/atareinit');
1374
				if ($g['booting']) {
1375
					echo "done.\n";
1376
				}
1377
			} else if ($g['booting']) {
1378
				echo "failed!\n";
1379
			}
1380
		} else if ($g['booting']) {
1381
			echo "failed!\n";
1382
		}
1383
	}
1384
}
1385

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

    
1393
	activate_sysctls();	
1394

    
1395
	if (isset($config['system']['sharednet'])) {
1396
		system_disable_arp_wrong_if();
1397
	}
1398
}
1399

    
1400
function system_disable_arp_wrong_if() {
1401
	global $config;
1402
	if(isset($config['system']['developerspew'])) {
1403
		$mt = microtime();
1404
		echo "system_disable_arp_wrong_if() being called $mt\n";
1405
	}
1406
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1407
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1408
}
1409

    
1410
function system_enable_arp_wrong_if() {
1411
	global $config;
1412
	if(isset($config['system']['developerspew'])) {
1413
		$mt = microtime();
1414
		echo "system_enable_arp_wrong_if() being called $mt\n";
1415
	}
1416
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1417
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1418
}
1419

    
1420
function enable_watchdog() {
1421
	global $config;
1422
	return;
1423
	$install_watchdog = false;
1424
	$supported_watchdogs = array("Geode");
1425
	$file = file_get_contents("/var/log/dmesg.boot");
1426
	foreach($supported_watchdogs as $sd) {
1427
		if(stristr($file, "Geode")) {
1428
			$install_watchdog = true;
1429
		}
1430
	}
1431
	if($install_watchdog == true) {
1432
		if(is_process_running("watchdogd"))
1433
			mwexec("/usr/bin/killall watchdogd", true);
1434
		exec("/usr/sbin/watchdogd");
1435
	}
1436
}
1437

    
1438
function system_check_reset_button() {
1439
	global $g;
1440
	if($g['platform'] != "nanobsd")
1441
		return 0;
1442

    
1443
	$specplatform = system_identify_specific_platform();
1444

    
1445
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1446
		return 0;
1447

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

    
1450
	if ($retval == 99) {
1451
		/* user has pressed reset button for 2 seconds - 
1452
		   reset to factory defaults */
1453
		echo <<<EOD
1454

    
1455
***********************************************************************
1456
* Reset button pressed - resetting configuration to factory defaults. *
1457
* The system will reboot after this completes.                        *
1458
***********************************************************************
1459

    
1460

    
1461
EOD;
1462
		
1463
		reset_factory_defaults();
1464
		system_reboot_sync();
1465
		exit(0);
1466
	}
1467

    
1468
	return 0;
1469
}
1470

    
1471
/* attempt to identify the specific platform (for embedded systems)
1472
   Returns an array with two elements:
1473
	name => platform string (e.g. 'wrap', 'alix' etc.)
1474
	descr => human-readable description (e.g. "PC Engines WRAP")
1475
*/
1476
function system_identify_specific_platform() {
1477
	global $g;
1478
	
1479
	if ($g['platform'] == 'generic-pc')
1480
		return array('name' => 'generic-pc', 'descr' => "Generic PC");
1481
	
1482
	if ($g['platform'] == 'generic-pc-cdrom')
1483
		return array('name' => 'generic-pc-cdrom', 'descr' => "Generic PC (CD-ROM)");
1484
	
1485
	/* the rest of the code only deals with 'embedded' platforms */
1486
	if ($g['platform'] != 'nanobsd')
1487
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1488
	
1489
	$dmesg = system_get_dmesg_boot();
1490
	
1491
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1492
		return array('name' => 'wrap', 'descr' => 'PC Engines WRAP');
1493
	
1494
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1495
		return array('name' => 'alix', 'descr' => 'PC Engines ALIX');
1496

    
1497
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1498
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1499
	
1500
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1501
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1502
		
1503
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1504
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1505
	
1506
	/* unknown embedded platform */
1507
	return array('name' => 'embedded', 'descr' => 'embedded (unknown)');
1508
}
1509

    
1510
function system_get_dmesg_boot() {
1511
	global $g;
1512
		
1513
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1514
}
1515

    
1516
function openntpd_get_listen_ips() {
1517
	$interfaces = get_configured_interface_with_descr();
1518
	$carplist = get_configured_carp_interface_list();
1519
	$listenips = array();
1520
	foreach ($carplist as $cif => $carpip)
1521
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1522
	$aliaslist = get_configured_ip_aliases_list();
1523
	foreach ($aliaslist as $aliasip => $aliasif)
1524
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1525
	foreach ($interfaces as $iface => $ifacename) {
1526
		$tmp["name"]  = $ifacename;
1527
		$tmp["value"] = $iface;
1528
		$listenips[] = $tmp;
1529
	}
1530
	$tmp["name"]  = "Localhost";
1531
	$tmp["value"] = "lo0";
1532
	$listenips[] = $tmp;
1533
	return $listenips;
1534
}
1535
?>
(47-47/61)