Project

General

Profile

Download (43.5 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
	$resolvconf = "domain {$syscfg['domain']}\n";
90

    
91
	$havedns = false;
92

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

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

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

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

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

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

    
155
	unlock($dnslock);
156

    
157
	return 0;
158
}
159

    
160
function get_searchdomains() {
161
	global $config, $g;
162

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

    
179
	return $master_list;
180
}
181

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

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

    
210
	return $master_list;
211
}
212

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

    
220
	$syscfg = $config['system'];
221
	$dnsmasqcfg = $config['dnsmasq'];
222

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

    
228
	$hosts = "127.0.0.1	localhost localhost.{$syscfg['domain']}\n";
229

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

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

    
261
	/*
262
	 * Do not remove this because dhcpleases monitors with kqueue it needs to be 
263
	 * killed before writing to hosts files.
264
	 */
265
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
266
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
267
                @unlink("{$g['varrun_path']}/dhcpleases.pid");
268
	}
269
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
270
	if (!$fd) {
271
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
272
		return 1;
273
	}
274
	fwrite($fd, $hosts);
275
	fclose($fd);
276

    
277
	system_dhcpleases_configure();
278

    
279
	return 0;
280
}
281

    
282
function system_dhcpleases_configure() {
283
	global $config, $g;
284
	
285
	/* Start the monitoring process for dynamic dhcpclients. */
286
	if (isset($config['dnsmasq']['regdhcp'])) {
287
		/* Make sure we do not error out */
288
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
289
		if (file_exists("{$g['varrun_path']}/dhcpleases.pid"))
290
				sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "HUP");
291
		else
292
			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");
293
	} else {
294
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
295
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
296
	}
297
}
298

    
299
function system_hostname_configure() {
300
	global $config, $g;
301
	if(isset($config['system']['developerspew'])) {
302
		$mt = microtime();
303
		echo "system_hostname_configure() being called $mt\n";
304
	}
305

    
306
	$syscfg = $config['system'];
307

    
308
	/* set hostname */
309
	$status = mwexec("/bin/hostname " .
310
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
311

    
312
    /* Setup host GUID ID.  This is used by ZFS. */
313
	mwexec("/etc/rc.d/hostid start");
314

    
315
	return $status;
316
}
317

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

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

    
377
	if ($dont_add_route == false ) {
378
		if (!empty($interface) && $interface != $interfacegw)
379
			;
380
		else if (($interfacegw <> "bgpd") && (is_ipaddr($gatewayip))) {
381
			$action = "add";
382
			if(isset($route_arr['default'])) {
383
				$action = "change";
384
			}
385
			log_error("ROUTING: $action default route to $gatewayip");
386
			mwexec("/sbin/route {$action} -inet default " . escapeshellarg($gatewayip));
387
		}
388
	}
389

    
390
	if (is_array($config['staticroutes']['route'])) {
391
		$gateways_arr = return_gateways_array();
392

    
393
		foreach ($config['staticroutes']['route'] as $rtent) {
394
			$gatewayip = "";
395
			if (empty($gateways_arr[$rtent['gateway']])) {
396
				log_error("Static Routes: Gateway IP could not be found for {$rtent['network']}");
397
				continue;
398
			}
399
			$gateway = $gateways_arr[$rtent['gateway']];
400
			if (!empty($interface) && $interface != $gateway['friendlyiface'])
401
				continue;
402
			$gatewayip = $gateway['gateway'];
403
			$interfacegw = $gateway['interface'];
404
			$action = "add";
405
			if (isset($route_arr[$rtent['network']]))
406
				$action = "change";
407

    
408
			if (is_ipaddr($gatewayip)) {
409
				mwexec("/sbin/route {$action} -inet " . escapeshellarg($rtent['network']) .
410
					" " . escapeshellarg($gatewayip));
411
			} else if (!empty($interfacegw)) {
412
				mwexec("/sbin/route {$action} -inet " . escapeshellarg($rtent['network']) .
413
					" -iface " . escapeshellarg($interfacegw));
414
			}
415
		}
416
	}
417

    
418
	return 0;
419
}
420

    
421
function system_routing_enable() {
422
	global $config, $g;
423
	if(isset($config['system']['developerspew'])) {
424
		$mt = microtime();
425
		echo "system_routing_enable() being called $mt\n";
426
	}
427

    
428
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
429
}
430

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

    
438
	$syslogcfg = $config['syslog'];
439

    
440
	if ($g['booting'])
441
		echo "Starting syslog...";
442
	else
443
		killbypid("{$g['varrun_path']}/syslog.pid");
444

    
445
	if(is_process_running("syslogd"))
446
		mwexec("/usr/bin/killall -9 syslogd");
447
	if(is_process_running("fifolog_writer"))
448
		mwexec("/usr/bin/killall -9 fifolog_writer");
449
	
450
	// Define carious commands for logging
451
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
452
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
453
	$clog_create = "/usr/sbin/clog -i -s ";
454
	$clog_log = "%";
455

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

    
540
EOD;
541
		if (isset($syslogcfg['filter'])) {
542
			if($syslogcfg['remoteserver'])
543
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver']}\n";
544
			if($syslogcfg['remoteserver2'])
545
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver2']}\n";
546
			if($syslogcfg['remoteserver3'])
547
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver3']}\n";
548

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

    
583
EOD;
584

    
585
}
586

    
587
		if (isset($syslogcfg['system'])) {
588
			if($syslogcfg['remoteserver2'])
589
				$syslogconf .= <<<EOD
590
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver2']}
591
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver2']}
592
security.*										 @{$syslogcfg['remoteserver2']}
593
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver2']}
594
*.emerg											 @{$syslogcfg['remoteserver2']}
595

    
596
EOD;
597

    
598
}
599

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

    
609
EOD;
610

    
611
}
612
		if (isset($syslogcfg['logall'])) {
613
			if($syslogcfg['remoteserver'])
614
				$syslogconf .= <<<EOD
615
*.*								@{$syslogcfg['remoteserver']}
616

    
617
EOD;
618

    
619
			if($syslogcfg['remoteserver2'])
620
				$syslogconf .= <<<EOD
621
*.*								@{$syslogcfg['remoteserver2']}
622

    
623
EOD;
624

    
625
			if($syslogcfg['remoteserver3'])
626
				$syslogconf .= <<<EOD
627
*.*								@{$syslogcfg['remoteserver3']}
628

    
629
EOD;
630

    
631
}
632
		fwrite($fd, $syslogconf);
633
		fclose($fd);
634

    
635
		// Ensure that the log directory exists
636
		if(!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
637
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
638

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

    
645
	} else {
646
		$retval = mwexec("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log");
647
	}
648

    
649
	if ($g['booting'])
650
		echo "done.\n";
651

    
652
	return $retval;
653
}
654

    
655
function system_pccard_start() {
656
	global $config, $g;
657
	if(isset($config['system']['developerspew'])) {
658
		$mt = microtime();
659
		echo "system_pccard_start() being called $mt\n";
660
	}
661

    
662
	if ($g['booting'])
663
		echo "Initializing PCMCIA...";
664

    
665
	/* kill any running pccardd */
666
	killbypid("{$g['varrun_path']}/pccardd.pid");
667

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

    
671
	if ($g['booting']) {
672
		if ($res == 0)
673
			echo "done.\n";
674
		else
675
			echo "failed!\n";
676
	}
677

    
678
	return $res;
679
}
680

    
681

    
682
function system_webgui_start() {
683
	global $config, $g;
684

    
685
	if ($g['booting'])
686
		echo "Starting webConfigurator...";
687

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

    
691
	sleep(1);
692

    
693
	chdir($g['www_path']);
694

    
695
	/* defaults */
696
	$portarg = "80";
697
	$crt = "";
698
	$key = "";
699
	$ca = "";
700

    
701
	/* non-standard port? */
702
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
703
		$portarg = "{$config['system']['webgui']['port']}";
704

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

    
741
	/* generate lighttpd configuration */
742
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
743
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/");
744

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

    
748
	/* fetch page to preload apc cache */
749
	$proto = "http";
750
	if ($config['system']['webgui']['protocol'])
751
		$proto = $config['system']['webgui']['protocol'];
752
	mwexec_bg("/usr/bin/fetch -o /dev/null -q {$proto}://localhost:{$portarg}/preload.php");
753

    
754
	if ($g['booting']) {
755
		if ($res == 0)
756
			echo "done.\n";
757
		else
758
			echo "failed!\n";
759
	}
760

    
761
	return $res;
762
}
763

    
764
function system_generate_lighty_config($filename,
765
	$cert,
766
	$key,
767
	$ca,
768
	$pid_file,
769
	$port = 80,
770
	$document_root = "/usr/local/www/",
771
	$cert_location = "cert.pem",
772
	$ca_location = "ca.pem",
773
	$max_procs = 2,
774
	$max_requests = "2",
775
	$fast_cgi_enable = true,
776
	$captive_portal = false) {
777

    
778
	global $config, $g;
779

    
780
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
781
		mkdir("{$g['tmp_path']}/lighttpdcompress");
782

    
783
	if(isset($config['system']['developerspew'])) {
784
		$mt = microtime();
785
		echo "system_generate_lighty_config() being called $mt\n";
786
	}
787

    
788
	if($captive_portal == true)  {
789
		$captiveportal = ",\"mod_rewrite\"";
790
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?redirurl=$1\" )\n";
791
		$captive_portal_module = "";
792
		$maxprocperip = $config['captiveportal']['maxprocperip'];
793
		if(!$maxprocperip and $maxprocperip > 0)
794
			$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
795
		else
796
			$captive_portal_mod_evasive = "";
797
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
798
		exec("mkdir -p {$g['tmp_path']}/captiveportal");
799
		exec("chmod a-w {$g['tmp_path']}/captiveportal");
800
		$server_max_request_size = "server.max-request-size    = 384";
801
	} else {
802
		$captiveportal = "";
803
		$captive_portal_rewrite = "";
804
		$captive_portal_module = "";
805
		$captive_portal_mod_evasive = "";
806
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
807
		$server_max_request_size = "server.max-request-size    = 2097152";
808
	}
809
	
810
	if($port <> "")
811
		$lighty_port = $port;
812
	else
813
		$lighty_port = "80";
814

    
815
	$memory = get_memory();
816
	$avail = $memory[0];
817

    
818
	if($avail > 0 and $avail < 65) {
819
		$fast_cgi_enable = false;
820
	}
821

    
822
	// Ramp up captive portal max procs
823
	if($captive_portal == true)  {
824
		if($avail > 65 and $avail < 98) {
825
			$max_procs = 1;
826
		}
827
		if($avail > 97 and $avail < 128) {
828
			$max_procs = 2;
829
		}
830
		if($avail > 127 and $avail < 256) {
831
			$max_procs = 3;
832
		}
833
		if($avail > 255 and $avail < 384) {
834
			$max_procs = 4;
835
		}
836
		if($avail > 383) {
837
			$max_procs = 5;
838
		}
839
	}
840

    
841
	if($captive_portal == true)  {	
842
		$bin_environment =  <<<EOC
843
        "bin-environment" => (
844
           "PHP_FCGI_CHILDREN" => "$max_procs",
845
           "PHP_FCGI_MAX_REQUESTS" => "500"
846
        ), 
847
EOC;
848

    
849
	} else if ($avail > 0 and $avail < 128) {
850
		$bin_environment = <<<EOC
851
		"bin-environment" => (
852
			"PHP_FCGI_CHILDREN" => "$max_procs",
853
			"PHP_FCGI_MAX_REQUESTS" => "2",
854
	),
855

    
856
EOC;
857
	} else
858
		$bin_environment =  <<<EOC
859
        "bin-environment" => (
860
           "PHP_FCGI_CHILDREN" => "$max_procs",
861
           "PHP_FCGI_MAX_REQUESTS" => "500"
862
        ), 
863
EOC;
864

    
865
	if($fast_cgi_enable == true) {
866
		$module = "\"mod_fastcgi\", \"mod_cgi\"";
867
		$cgi_config = "";
868
		$fastcgi_config = <<<EOD
869
#### fastcgi module
870
## read fastcgi.txt for more info
871
fastcgi.server = ( ".php" =>
872
	( "localhost" =>
873
		(
874
			"socket" => "{$g['tmp_path']}/php-fastcgi.socket",
875
			"min-procs" => 0,
876
			"max-procs" => {$max_procs},
877
			{$bin_environment}			
878
			"bin-path" => "/usr/local/bin/php"
879
		)
880
	)
881
)
882

    
883
#### CGI module
884
cgi.assign                 = ( ".cgi" => "" )
885

    
886
EOD;
887
	} else {
888
		$fastcgi_config = "";
889
		$module = "\"mod_cgi\"";
890
		$cgi_config = <<<EOD
891
#### CGI module
892
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
893
                               ".cgi" => "" )
894

    
895
EOD;
896
	}
897

    
898
	$lighty_config = "";
899
	$lighty_config .= <<<EOD
900
#
901
# lighttpd configuration file
902
#
903
# use a it as base for lighttpd 1.0.0 and above
904
#
905
############ Options you really have to take care of ####################
906

    
907
## FreeBSD!
908
server.event-handler	= "freebsd-kqueue"
909
server.network-backend 	= "writev"
910

    
911
## modules to load
912
server.modules              =   (
913
									{$captive_portal_module}
914
									"mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect",
915
									{$module}{$captiveportal}
916
								)
917

    
918
## Unused modules
919
#                               "mod_setenv",
920
#                               "mod_rewrite",
921
#                               "mod_ssi",
922
#                               "mod_usertrack",
923
#                               "mod_expire",
924
#                               "mod_secdownload",
925
#                               "mod_rrdtool",
926
#                               "mod_auth",
927
#                               "mod_status",
928
#                               "mod_alias",
929
#                               "mod_proxy",
930
#                               "mod_simple_vhost",
931
#                               "mod_evhost",
932
#                               "mod_userdir",
933
#                               "mod_cgi",
934

    
935
server.max-keep-alive-requests = 15
936
server.max-keep-alive-idle = 30
937

    
938
## a static document-root, for virtual-hosting take look at the
939
## server.virtual-* options
940
server.document-root        = "{$document_root}"
941
{$captive_portal_rewrite}
942

    
943
# Maximum idle time with nothing being written (php downloading)
944
server.max-write-idle = 999
945

    
946
## where to send error-messages to
947
server.errorlog             = "/var/log/lighttpd.error.log"
948

    
949
# files to check for if .../ is requested
950
server.indexfiles           = ( "index.php", "index.html",
951
                                "index.htm", "default.htm" )
952

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

    
1006
# Use the "Content-Type" extended attribute to obtain mime type if possible
1007
#mimetypes.use-xattr        = "enable"
1008

    
1009
#### accesslog module
1010
#accesslog.filename          = "/dev/null"
1011

    
1012
## deny access the file-extensions
1013
#
1014
# ~    is for backupfiles from vi, emacs, joe, ...
1015
# .inc is often used for code includes which should in general not be part
1016
#      of the document-root
1017
url.access-deny             = ( "~", ".inc" )
1018

    
1019

    
1020
######### Options that are good to be but not neccesary to be changed #######
1021

    
1022
## bind to port (default: 80)
1023
server.port                = {$lighty_port}
1024

    
1025
## error-handler for status 404
1026
#server.error-handler-404   = "/error-handler.html"
1027
#server.error-handler-404   = "/error-handler.php"
1028

    
1029
## to help the rc.scripts
1030
server.pid-file            = "/var/run/{$pid_file}"
1031

    
1032
## virtual directory listings
1033
server.dir-listing         = "disable"
1034

    
1035
## enable debugging
1036
debug.log-request-header   = "disable"
1037
debug.log-response-header  = "disable"
1038
debug.log-request-handling = "disable"
1039
debug.log-file-not-found   = "disable"
1040

    
1041
# gzip compression
1042
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1043
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1044

    
1045
{$server_upload_dirs}
1046

    
1047
{$server_max_request_size}
1048

    
1049
{$fastcgi_config}
1050

    
1051
{$cgi_config}
1052

    
1053
{$captive_portal_mod_evasive}
1054

    
1055
expire.url = (
1056
				"" => "access 50 hours",	
1057
        )
1058

    
1059
EOD;
1060

    
1061
	$cert = str_replace("\r", "", $cert);
1062
	$key = str_replace("\r", "", $key);
1063
	$ca = str_replace("\r", "", $ca);
1064

    
1065
	$cert = str_replace("\n\n", "\n", $cert);
1066
	$key = str_replace("\n\n", "\n", $key);
1067
	$ca = str_replace("\n\n", "\n", $ca);
1068

    
1069
	if($cert <> "" and $key <> "") {
1070
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1071
		if (!$fd) {
1072
			printf("Error: cannot open cert.pem in system_webgui_start().\n");
1073
			return 1;
1074
		}
1075
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1076
		fwrite($fd, $cert);
1077
		fwrite($fd, "\n");
1078
		fwrite($fd, $key);
1079
		fclose($fd);
1080
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
1081
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1082
			if (!$fd) {
1083
				printf("Error: cannot open ca.pem in system_webgui_start().\n");
1084
				return 1;
1085
			}
1086
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1087
			fwrite($fd, $ca);
1088
			fclose($fd);
1089
		}
1090
		$lighty_config .= "\n";
1091
		$lighty_config .= "## ssl configuration\n";
1092
		$lighty_config .= "ssl.engine = \"enable\"\n";
1093
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1094

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

    
1099
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1100
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1101
	}
1102

    
1103
	// Add HTTP to HTTPS redirect	
1104
	if ($captive_portal == false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1105
		if($lighty_port != "443") 
1106
			$redirectport = ":{$lighty_port}";
1107
		$lighty_config .= <<<EOD
1108
\$SERVER["socket"] == ":80" {
1109
	\$HTTP["host"] =~ "(.*)" {
1110
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1111
	}
1112
}
1113
EOD;
1114
	}
1115

    
1116
	$fd = fopen("{$filename}", "w");
1117
	if (!$fd) {
1118
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
1119
		return 1;
1120
	}
1121
	fwrite($fd, $lighty_config);
1122
	fclose($fd);
1123

    
1124
	return 0;
1125

    
1126
}
1127

    
1128
function system_timezone_configure() {
1129
	global $config, $g;
1130
	if(isset($config['system']['developerspew'])) {
1131
		$mt = microtime();
1132
		echo "system_timezone_configure() being called $mt\n";
1133
	}
1134

    
1135
	$syscfg = $config['system'];
1136

    
1137
	if ($g['booting'])
1138
		echo "Setting timezone...";
1139

    
1140
	/* extract appropriate timezone file */
1141
	$timezone = $syscfg['timezone'];
1142
	if (!$timezone)
1143
		$timezone = "Etc/UTC";
1144

    
1145
	conf_mount_rw();
1146

    
1147
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1148
		escapeshellarg($timezone) . " > /etc/localtime");
1149

    
1150
	mwexec("sync");
1151
	conf_mount_ro();
1152

    
1153
	if ($g['booting'])
1154
		echo "done.\n";
1155
}
1156

    
1157
function system_ntp_configure() {
1158
	global $config, $g;
1159

    
1160
	$ntpcfg = "# \n";
1161
	$ntpcfg .= "# pfSense OpenNTPD configuration file \n";
1162
	$ntpcfg .= "# \n\n";
1163

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

    
1168
	/* Setup listener(s) if the user has configured one */
1169
        if ($config['installedpackages']['openntpd']) {
1170
    		/* server config is in coregui1 */
1171
		$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
1172
		if ($xmlsettings['enable'] == 'on') {
1173
			$ifaces = explode(',', $xmlsettings['interface']);
1174
			$ifaces = array_map('get_real_interface', $ifaces);
1175
			$ifaces = array_filter($ifaces, 'does_interface_exist');
1176
			$ips = array_map('find_interface_ip', $ifaces);
1177
			foreach ($ips as $ip) {
1178
				if (is_ipaddr($ip))
1179
					$ntpcfg .= "listen on $ip\n";
1180
			}
1181
		}
1182
	}
1183
	$ntpcfg .= "\n";
1184

    
1185
	/* open configuration for wrting or bail */
1186
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1187
	if(!$fd) {
1188
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1189
		return;
1190
	}
1191
	fwrite($fd, $ntpcfg);
1192

    
1193
	/* slurp! */
1194
	fclose($fd);
1195

    
1196
	/* if openntpd is running, kill it */
1197
	while(is_process_running("ntpd")) {
1198
		killbyname("ntpd");
1199
	}
1200

    
1201
	/* if /var/empty does not exist, create it */
1202
	if(!is_dir("/var/empty"))
1203
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1204

    
1205
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1206
	exec("/usr/local/sbin/ntpd -s -f {$g['varetc_path']}/ntpd.conf");
1207
	
1208
	// Note that we are starting up
1209
	log_error("OpenNTPD is starting up.");
1210

    
1211
}
1212

    
1213
function sync_system_time() {
1214
	global $config, $g;
1215

    
1216
	if ($g['booting'])
1217
		echo "Syncing system time before startup...";
1218

    
1219
	/* foreach through servers and write out to ntpd.conf */
1220
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1221
		mwexec("/usr/sbin/ntpdate -s $ts");
1222
	}
1223
	
1224
	if ($g['booting'])
1225
		echo "done.\n";
1226
	
1227
}
1228

    
1229
function system_halt() {
1230
	global $g;
1231

    
1232
	system_reboot_cleanup();
1233

    
1234
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1235
}
1236

    
1237
function system_reboot() {
1238
	global $g;
1239

    
1240
	system_reboot_cleanup();
1241

    
1242
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1243
}
1244

    
1245
function system_reboot_sync() {
1246
	global $g;
1247

    
1248
	system_reboot_cleanup();
1249

    
1250
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1251
}
1252

    
1253
function system_reboot_cleanup() {
1254
	mwexec("/usr/local/bin/beep.sh stop");
1255
	require_once("captiveportal.inc");
1256
	captiveportal_radius_stop_all();
1257
	require_once("voucher.inc");
1258
	voucher_save_db_to_config();
1259
	// mwexec("/etc/rc.stop_packages");
1260
}
1261

    
1262
function system_do_shell_commands($early = 0) {
1263
	global $config, $g;
1264
	if(isset($config['system']['developerspew'])) {
1265
		$mt = microtime();
1266
		echo "system_do_shell_commands() being called $mt\n";
1267
	}
1268

    
1269
	if ($early)
1270
		$cmdn = "earlyshellcmd";
1271
	else
1272
		$cmdn = "shellcmd";
1273

    
1274
	if (is_array($config['system'][$cmdn])) {
1275

    
1276
		/* *cmd is an array, loop through */
1277
		foreach ($config['system'][$cmdn] as $cmd) {
1278
			exec($cmd);
1279
		}
1280

    
1281
	} elseif($config['system'][$cmdn] <> "") {
1282

    
1283
		/* execute single item */
1284
		exec($config['system'][$cmdn]);
1285

    
1286
	}
1287
}
1288

    
1289
function system_console_configure() {
1290
	global $config, $g;
1291
	if(isset($config['system']['developerspew'])) {
1292
		$mt = microtime();
1293
		echo "system_console_configure() being called $mt\n";
1294
	}
1295

    
1296
	if (isset($config['system']['disableconsolemenu'])) {
1297
		touch("{$g['varetc_path']}/disableconsole");
1298
	} else {
1299
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1300
	}
1301
}
1302

    
1303
function system_dmesg_save() {
1304
	global $g;
1305
	if(isset($config['system']['developerspew'])) {
1306
		$mt = microtime();
1307
		echo "system_dmesg_save() being called $mt\n";
1308
	}
1309

    
1310
	$dmesg = "";
1311
	exec("/sbin/dmesg", $dmesg);
1312

    
1313
	/* find last copyright line (output from previous boots may be present) */
1314
	$lastcpline = 0;
1315

    
1316
	for ($i = 0; $i < count($dmesg); $i++) {
1317
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1318
			$lastcpline = $i;
1319
	}
1320

    
1321
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1322
	if (!$fd) {
1323
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1324
		return 1;
1325
	}
1326

    
1327
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1328
		fwrite($fd, $dmesg[$i] . "\n");
1329

    
1330
	fclose($fd);
1331

    
1332
	return 0;
1333
}
1334

    
1335
function system_set_harddisk_standby() {
1336
	global $g, $config;
1337
	if(isset($config['system']['developerspew'])) {
1338
		$mt = microtime();
1339
		echo "system_set_harddisk_standby() being called $mt\n";
1340
	}
1341

    
1342
	if (isset($config['system']['harddiskstandby'])) {
1343
		if ($g['booting']) {
1344
			echo 'Setting hard disk standby... ';
1345
		}
1346

    
1347
		$standby = $config['system']['harddiskstandby'];
1348
		// Check for a numeric value
1349
		if (is_numeric($standby)) {
1350
			// Sync the disk(s)
1351
			pfSense_sync();
1352
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1353
				// Reinitialize ATA-drives
1354
				mwexec('/usr/local/sbin/atareinit');
1355
				if ($g['booting']) {
1356
					echo "done.\n";
1357
				}
1358
			} else if ($g['booting']) {
1359
				echo "failed!\n";
1360
			}
1361
		} else if ($g['booting']) {
1362
			echo "failed!\n";
1363
		}
1364
	}
1365
}
1366

    
1367
function system_setup_sysctl() {
1368
	global $config;
1369
	if(isset($config['system']['developerspew'])) {
1370
		$mt = microtime();
1371
		echo "system_setup_sysctl() being called $mt\n";
1372
	}
1373

    
1374
	activate_sysctls();	
1375

    
1376
	if (isset($config['system']['sharednet'])) {
1377
		system_disable_arp_wrong_if();
1378
	}
1379
}
1380

    
1381
function system_disable_arp_wrong_if() {
1382
	global $config;
1383
	if(isset($config['system']['developerspew'])) {
1384
		$mt = microtime();
1385
		echo "system_disable_arp_wrong_if() being called $mt\n";
1386
	}
1387
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1388
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1389
}
1390

    
1391
function system_enable_arp_wrong_if() {
1392
	global $config;
1393
	if(isset($config['system']['developerspew'])) {
1394
		$mt = microtime();
1395
		echo "system_enable_arp_wrong_if() being called $mt\n";
1396
	}
1397
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1398
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1399
}
1400

    
1401
function enable_watchdog() {
1402
	global $config;
1403
	return;
1404
	$install_watchdog = false;
1405
	$supported_watchdogs = array("Geode");
1406
	$file = file_get_contents("/var/log/dmesg.boot");
1407
	foreach($supported_watchdogs as $sd) {
1408
		if(stristr($file, "Geode")) {
1409
			$install_watchdog = true;
1410
		}
1411
	}
1412
	if($install_watchdog == true) {
1413
		if(is_process_running("watchdogd"))
1414
			mwexec("/usr/bin/killall watchdogd", true);
1415
		exec("/usr/sbin/watchdogd");
1416
	}
1417
}
1418

    
1419
function system_check_reset_button() {
1420
	global $g;
1421
	if($g['platform'] != "nanobsd")
1422
		return 0;
1423

    
1424
	$specplatform = system_identify_specific_platform();
1425

    
1426
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1427
		return 0;
1428

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

    
1431
	if ($retval == 99) {
1432
		/* user has pressed reset button for 2 seconds - 
1433
		   reset to factory defaults */
1434
		echo <<<EOD
1435

    
1436
***********************************************************************
1437
* Reset button pressed - resetting configuration to factory defaults. *
1438
* The system will reboot after this completes.                        *
1439
***********************************************************************
1440

    
1441

    
1442
EOD;
1443
		
1444
		reset_factory_defaults();
1445
		system_reboot_sync();
1446
		exit(0);
1447
	}
1448

    
1449
	return 0;
1450
}
1451

    
1452
/* attempt to identify the specific platform (for embedded systems)
1453
   Returns an array with two elements:
1454
	name => platform string (e.g. 'wrap', 'alix' etc.)
1455
	descr => human-readable description (e.g. "PC Engines WRAP")
1456
*/
1457
function system_identify_specific_platform() {
1458
	global $g;
1459
	
1460
	if ($g['platform'] == 'generic-pc')
1461
		return array('name' => 'generic-pc', 'descr' => "Generic PC");
1462
	
1463
	if ($g['platform'] == 'generic-pc-cdrom')
1464
		return array('name' => 'generic-pc-cdrom', 'descr' => "Generic PC (CD-ROM)");
1465
	
1466
	/* the rest of the code only deals with 'embedded' platforms */
1467
	if ($g['platform'] != 'nanobsd')
1468
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1469
	
1470
	$dmesg = system_get_dmesg_boot();
1471
	
1472
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1473
		return array('name' => 'wrap', 'descr' => 'PC Engines WRAP');
1474
	
1475
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1476
		return array('name' => 'alix', 'descr' => 'PC Engines ALIX');
1477

    
1478
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1479
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1480
	
1481
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1482
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1483
		
1484
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1485
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1486
	
1487
	/* unknown embedded platform */
1488
	return array('name' => 'embedded', 'descr' => 'embedded (unknown)');
1489
}
1490

    
1491
function system_get_dmesg_boot() {
1492
	global $g;
1493
		
1494
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1495
}
1496

    
1497
?>
(47-47/61)