Project

General

Profile

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

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

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

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

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

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

    
32
/*
33
	pfSense_BUILDER_BINARIES:	/usr/sbin/powerd	/usr/bin/killall	/sbin/sysctl	/sbin/route
34
	pfSense_BUILDER_BINARIES:	/bin/hostname	/bin/ls	/usr/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
	$fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
120
	if (!$fd) {
121
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
122
		return 1;
123
	}
124

    
125
	fwrite($fd, $resolvconf);
126
	fclose($fd);
127

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

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

    
155
function get_searchdomains() {
156
	global $config, $g;
157

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

    
174
	return $master_list;
175
}
176

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

    
195
	// Read in any extra nameservers
196
	if(file_exists("/var/etc/nameservers.conf")) {
197
		$dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
198
		if(is_array($dns_s)) {
199
			foreach($dns_s as $dns)
200
				if (is_ipaddr($dns))
201
					$master_list[] = $dns;
202
		}
203
	}
204

    
205
	return $master_list;
206
}
207

    
208
function system_hosts_generate() {
209
	global $config, $g;
210
	if(isset($config['system']['developerspew'])) {
211
		$mt = microtime();
212
		echo "system_hosts_generate() being called $mt\n";
213
	}
214

    
215
	$syscfg = $config['system'];
216
	$dnsmasqcfg = $config['dnsmasq'];
217

    
218
	if (!is_array($dnsmasqcfg['hosts'])) {
219
		$dnsmasqcfg['hosts'] = array();
220
	}
221
	$hostscfg = $dnsmasqcfg['hosts'];
222

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

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

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

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

    
272
	system_dhcpleases_configure();
273

    
274
	return 0;
275
}
276

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

    
294
function system_hostname_configure() {
295
	global $config, $g;
296
	if(isset($config['system']['developerspew'])) {
297
		$mt = microtime();
298
		echo "system_hostname_configure() being called $mt\n";
299
	}
300

    
301
	$syscfg = $config['system'];
302

    
303
	/* set hostname */
304
	$status = mwexec("/bin/hostname " .
305
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
306

    
307
    /* Setup host GUID ID.  This is used by ZFS. */
308
	mwexec("/etc/rc.d/hostid start");
309

    
310
	return $status;
311
}
312

    
313
function system_routing_configure($interface = "") {
314
	global $config, $g;
315
	if(isset($config['system']['developerspew'])) {
316
		$mt = microtime();
317
		echo "system_routing_configure() being called $mt\n";
318
	}
319

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

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

    
385
	if (is_array($config['staticroutes']['route'])) {
386
		$gateways_arr = return_gateways_array();
387

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

    
403
			if (is_ipaddr($gatewayip)) {
404
				mwexec("/sbin/route {$action} -inet " . escapeshellarg($rtent['network']) .
405
					" " . escapeshellarg($gatewayip));
406
			} else if (!empty($interfacegw)) {
407
				mwexec("/sbin/route {$action} -inet " . escapeshellarg($rtent['network']) .
408
					" -iface " . escapeshellarg($interfacegw));
409
			}
410
		}
411
	}
412

    
413
	return 0;
414
}
415

    
416
function system_routing_enable() {
417
	global $config, $g;
418
	if(isset($config['system']['developerspew'])) {
419
		$mt = microtime();
420
		echo "system_routing_enable() being called $mt\n";
421
	}
422

    
423
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
424
}
425

    
426
function system_syslogd_start() {
427
	global $config, $g;
428
	if(isset($config['system']['developerspew'])) {
429
		$mt = microtime();
430
		echo "system_syslogd_start() being called $mt\n";
431
	}
432

    
433
	$syslogcfg = $config['syslog'];
434

    
435
	if ($g['booting'])
436
		echo "Starting syslog...";
437
	else
438
		killbypid("{$g['varrun_path']}/syslog.pid");
439

    
440
	if(is_process_running("syslogd"))
441
		mwexec("/usr/bin/killall -9 syslogd");
442
	if(is_process_running("fifolog_writer"))
443
		mwexec("/usr/bin/killall -9 fifolog_writer");
444
	
445
	// Define carious commands for logging
446
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
447
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
448
	$clog_create = "/usr/sbin/clog -i -s ";
449
	$clog_log = "%";
450

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

    
535
EOD;
536
		if (isset($syslogcfg['filter'])) {
537
			if($syslogcfg['remoteserver'])
538
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver']}\n";
539
			if($syslogcfg['remoteserver2'])
540
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver2']}\n";
541
			if($syslogcfg['remoteserver3'])
542
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver3']}\n";
543

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

    
578
EOD;
579

    
580
}
581

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

    
591
EOD;
592

    
593
}
594

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

    
604
EOD;
605

    
606
}
607
		if (isset($syslogcfg['logall'])) {
608
			if($syslogcfg['remoteserver'])
609
				$syslogconf .= <<<EOD
610
*.*								@{$syslogcfg['remoteserver']}
611

    
612
EOD;
613

    
614
			if($syslogcfg['remoteserver2'])
615
				$syslogconf .= <<<EOD
616
*.*								@{$syslogcfg['remoteserver2']}
617

    
618
EOD;
619

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

    
624
EOD;
625

    
626
}
627
		fwrite($fd, $syslogconf);
628
		fclose($fd);
629

    
630
		// Ensure that the log directory exists
631
		if(!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
632
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
633

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

    
640
	} else {
641
		$retval = mwexec("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log");
642
	}
643

    
644
	if ($g['booting'])
645
		echo "done.\n";
646

    
647
	return $retval;
648
}
649

    
650
function system_pccard_start() {
651
	global $config, $g;
652
	if(isset($config['system']['developerspew'])) {
653
		$mt = microtime();
654
		echo "system_pccard_start() being called $mt\n";
655
	}
656

    
657
	if ($g['booting'])
658
		echo "Initializing PCMCIA...";
659

    
660
	/* kill any running pccardd */
661
	killbypid("{$g['varrun_path']}/pccardd.pid");
662

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

    
666
	if ($g['booting']) {
667
		if ($res == 0)
668
			echo "done.\n";
669
		else
670
			echo "failed!\n";
671
	}
672

    
673
	return $res;
674
}
675

    
676

    
677
function system_webgui_start() {
678
	global $config, $g;
679

    
680
	if ($g['booting'])
681
		echo "Starting webConfigurator...";
682

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

    
686
	sleep(1);
687

    
688
	chdir($g['www_path']);
689

    
690
	/* defaults */
691
	$portarg = "80";
692
	$crt = "";
693
	$key = "";
694
	$ca = "";
695

    
696
	/* non-standard port? */
697
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
698
		$portarg = "{$config['system']['webgui']['port']}";
699

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

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

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

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

    
749
	if ($g['booting']) {
750
		if ($res == 0)
751
			echo "done.\n";
752
		else
753
			echo "failed!\n";
754
	}
755

    
756
	return $res;
757
}
758

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

    
773
	global $config, $g;
774

    
775
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
776
		mkdir("{$g['tmp_path']}/lighttpdcompress");
777

    
778
	if(isset($config['system']['developerspew'])) {
779
		$mt = microtime();
780
		echo "system_generate_lighty_config() being called $mt\n";
781
	}
782

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

    
810
	$memory = get_memory();
811
	$avail = $memory[0];
812

    
813
	if($avail > 0 and $avail < 65) {
814
		$fast_cgi_enable = false;
815
	}
816

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

    
836
	if($captive_portal == true)  {	
837
		$bin_environment =  <<<EOC
838
        "bin-environment" => (
839
           "PHP_FCGI_CHILDREN" => "$max_procs",
840
           "PHP_FCGI_MAX_REQUESTS" => "500"
841
        ), 
842
EOC;
843

    
844
	} else if ($avail > 0 and $avail < 128) {
845
		$bin_environment = <<<EOC
846
		"bin-environment" => (
847
			"PHP_FCGI_CHILDREN" => "$max_procs",
848
			"PHP_FCGI_MAX_REQUESTS" => "2",
849
	),
850

    
851
EOC;
852
	} else
853
		$bin_environment =  <<<EOC
854
        "bin-environment" => (
855
           "PHP_FCGI_CHILDREN" => "$max_procs",
856
           "PHP_FCGI_MAX_REQUESTS" => "500"
857
        ), 
858
EOC;
859

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

    
878
#### CGI module
879
cgi.assign                 = ( ".cgi" => "" )
880

    
881
EOD;
882
	} else {
883
		$fastcgi_config = "";
884
		$module = "\"mod_cgi\"";
885
		$cgi_config = <<<EOD
886
#### CGI module
887
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
888
                               ".cgi" => "" )
889

    
890
EOD;
891
	}
892

    
893
	$lighty_config = "";
894
	$lighty_config .= <<<EOD
895
#
896
# lighttpd configuration file
897
#
898
# use a it as base for lighttpd 1.0.0 and above
899
#
900
############ Options you really have to take care of ####################
901

    
902
## FreeBSD!
903
server.event-handler	= "freebsd-kqueue"
904
server.network-backend 	= "writev"
905

    
906
## modules to load
907
server.modules              =   (
908
									{$captive_portal_module}
909
									"mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect",
910
									{$module}{$captiveportal}
911
								)
912

    
913
## Unused modules
914
#                               "mod_setenv",
915
#                               "mod_rewrite",
916
#                               "mod_ssi",
917
#                               "mod_usertrack",
918
#                               "mod_expire",
919
#                               "mod_secdownload",
920
#                               "mod_rrdtool",
921
#                               "mod_auth",
922
#                               "mod_status",
923
#                               "mod_alias",
924
#                               "mod_proxy",
925
#                               "mod_simple_vhost",
926
#                               "mod_evhost",
927
#                               "mod_userdir",
928
#                               "mod_cgi",
929

    
930
server.max-keep-alive-requests = 15
931
server.max-keep-alive-idle = 30
932

    
933
## a static document-root, for virtual-hosting take look at the
934
## server.virtual-* options
935
server.document-root        = "{$document_root}"
936
{$captive_portal_rewrite}
937

    
938
# Maximum idle time with nothing being written (php downloading)
939
server.max-write-idle = 999
940

    
941
## where to send error-messages to
942
server.errorlog             = "/var/log/lighttpd.error.log"
943

    
944
# files to check for if .../ is requested
945
server.indexfiles           = ( "index.php", "index.html",
946
                                "index.htm", "default.htm" )
947

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

    
1001
# Use the "Content-Type" extended attribute to obtain mime type if possible
1002
#mimetypes.use-xattr        = "enable"
1003

    
1004
#### accesslog module
1005
#accesslog.filename          = "/dev/null"
1006

    
1007
## deny access the file-extensions
1008
#
1009
# ~    is for backupfiles from vi, emacs, joe, ...
1010
# .inc is often used for code includes which should in general not be part
1011
#      of the document-root
1012
url.access-deny             = ( "~", ".inc" )
1013

    
1014

    
1015
######### Options that are good to be but not neccesary to be changed #######
1016

    
1017
## bind to port (default: 80)
1018
server.port                = {$lighty_port}
1019

    
1020
## error-handler for status 404
1021
#server.error-handler-404   = "/error-handler.html"
1022
#server.error-handler-404   = "/error-handler.php"
1023

    
1024
## to help the rc.scripts
1025
server.pid-file            = "/var/run/{$pid_file}"
1026

    
1027
## virtual directory listings
1028
server.dir-listing         = "disable"
1029

    
1030
## enable debugging
1031
debug.log-request-header   = "disable"
1032
debug.log-response-header  = "disable"
1033
debug.log-request-handling = "disable"
1034
debug.log-file-not-found   = "disable"
1035

    
1036
# gzip compression
1037
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1038
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1039

    
1040
{$server_upload_dirs}
1041

    
1042
{$server_max_request_size}
1043

    
1044
{$fastcgi_config}
1045

    
1046
{$cgi_config}
1047

    
1048
{$captive_portal_mod_evasive}
1049

    
1050
expire.url = (
1051
				"" => "access 50 hours",	
1052
        )
1053

    
1054
EOD;
1055

    
1056
	$cert = str_replace("\r", "", $cert);
1057
	$key = str_replace("\r", "", $key);
1058
	$ca = str_replace("\r", "", $ca);
1059

    
1060
	$cert = str_replace("\n\n", "\n", $cert);
1061
	$key = str_replace("\n\n", "\n", $key);
1062
	$ca = str_replace("\n\n", "\n", $ca);
1063

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

    
1093
	// Add HTTP to HTTPS redirect	
1094
	if ($captive_portal == false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1095
		if($lighty_port != "443") 
1096
			$redirectport = ":{$lighty_port}";
1097
		$lighty_config .= <<<EOD
1098
\$SERVER["socket"] == ":80" {
1099
	\$HTTP["host"] =~ "(.*)" {
1100
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1101
	}
1102
}
1103
EOD;
1104
	}
1105

    
1106
	$fd = fopen("{$filename}", "w");
1107
	if (!$fd) {
1108
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
1109
		return 1;
1110
	}
1111
	fwrite($fd, $lighty_config);
1112
	fclose($fd);
1113

    
1114
	return 0;
1115

    
1116
}
1117

    
1118
function system_timezone_configure() {
1119
	global $config, $g;
1120
	if(isset($config['system']['developerspew'])) {
1121
		$mt = microtime();
1122
		echo "system_timezone_configure() being called $mt\n";
1123
	}
1124

    
1125
	$syscfg = $config['system'];
1126

    
1127
	if ($g['booting'])
1128
		echo "Setting timezone...";
1129

    
1130
	/* extract appropriate timezone file */
1131
	$timezone = $syscfg['timezone'];
1132
	if (!$timezone)
1133
		$timezone = "Etc/UTC";
1134

    
1135
	conf_mount_rw();
1136

    
1137
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1138
		escapeshellarg($timezone) . " > /etc/localtime");
1139

    
1140
	mwexec("sync");
1141
	conf_mount_ro();
1142

    
1143
	if ($g['booting'])
1144
		echo "done.\n";
1145
}
1146

    
1147
function system_ntp_configure() {
1148
	global $config, $g;
1149

    
1150
	$ntpcfg = "# \n";
1151
	$ntpcfg .= "# pfSense OpenNTPD configuration file \n";
1152
	$ntpcfg .= "# \n\n";
1153

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

    
1158
	/* Setup listener(s) if the user has configured one */
1159
        if ($config['installedpackages']['openntpd']) {
1160
    		/* server config is in coregui1 */
1161
		$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
1162
		if ($xmlsettings['enable'] == 'on') {
1163
			$ifaces = explode(',', $xmlsettings['interface']);
1164
			$ifaces = array_map('get_real_interface', $ifaces);
1165
			$ifaces = array_filter($ifaces, 'does_interface_exist');
1166
			$ips = array_map('find_interface_ip', $ifaces);
1167
			foreach ($ips as $ip) {
1168
				if (is_ipaddr($ip))
1169
					$ntpdcfg .= "listen on $ip\n";
1170
			}
1171
		}
1172
	}
1173
	$ntpdcfg .= "\n";
1174

    
1175
	/* open configuration for wrting or bail */
1176
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1177
	if(!$fd) {
1178
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1179
		return;
1180
	}
1181
	fwrite($fd, $ntpcfg);
1182

    
1183
	/* slurp! */
1184
	fclose($fd);
1185

    
1186
	/* if openntpd is running, kill it */
1187
	while(is_process_running("ntpd")) {
1188
		killbyname("ntpd");
1189
	}
1190

    
1191
	/* if /var/empty does not exist, create it */
1192
	if(!is_dir("/var/empty"))
1193
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1194

    
1195
	if ($g['booting'])
1196
		return;
1197

    
1198
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1199
	exec("/usr/local/sbin/ntpd -s -f {$g['varetc_path']}/ntpd.conf");
1200
	
1201
	// Note that we are starting up
1202
	exec("echo 'OpenNTPD is starting up' >> {$g['varlog_path']}/ntpd.log");
1203

    
1204
}
1205

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

    
1209
	if ($g['booting'])
1210
		echo "Syncing system time before startup...";
1211

    
1212
	/* foreach through servers and write out to ntpd.conf */
1213
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1214
		mwexec("/usr/sbin/ntpdate -s $ts");
1215
	}
1216
	
1217
	if ($g['booting'])
1218
		echo "done.\n";
1219
	
1220
}
1221

    
1222
function system_halt() {
1223
	global $g;
1224

    
1225
	system_reboot_cleanup();
1226

    
1227
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1228
}
1229

    
1230
function system_reboot() {
1231
	global $g;
1232

    
1233
	system_reboot_cleanup();
1234

    
1235
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1236
}
1237

    
1238
function system_reboot_sync() {
1239
	global $g;
1240

    
1241
	system_reboot_cleanup();
1242

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

    
1246
function system_reboot_cleanup() {
1247
	mwexec("/usr/local/bin/beep.sh stop");
1248
	require_once("captiveportal.inc");
1249
	captiveportal_radius_stop_all();
1250
	require_once("voucher.inc");
1251
	voucher_save_db_to_config();
1252
}
1253

    
1254
function system_do_shell_commands($early = 0) {
1255
	global $config, $g;
1256
	if(isset($config['system']['developerspew'])) {
1257
		$mt = microtime();
1258
		echo "system_do_shell_commands() being called $mt\n";
1259
	}
1260

    
1261
	if ($early)
1262
		$cmdn = "earlyshellcmd";
1263
	else
1264
		$cmdn = "shellcmd";
1265

    
1266
	if (is_array($config['system'][$cmdn])) {
1267

    
1268
		/* *cmd is an array, loop through */
1269
		foreach ($config['system'][$cmdn] as $cmd) {
1270
			exec($cmd);
1271
		}
1272

    
1273
	} elseif($config['system'][$cmdn] <> "") {
1274

    
1275
		/* execute single item */
1276
		exec($config['system'][$cmdn]);
1277

    
1278
	}
1279
}
1280

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

    
1288
	if (isset($config['system']['disableconsolemenu'])) {
1289
		touch("{$g['varetc_path']}/disableconsole");
1290
	} else {
1291
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1292
	}
1293
}
1294

    
1295
function system_dmesg_save() {
1296
	global $g;
1297
	if(isset($config['system']['developerspew'])) {
1298
		$mt = microtime();
1299
		echo "system_dmesg_save() being called $mt\n";
1300
	}
1301

    
1302
	$dmesg = "";
1303
	exec("/sbin/dmesg", $dmesg);
1304

    
1305
	/* find last copyright line (output from previous boots may be present) */
1306
	$lastcpline = 0;
1307

    
1308
	for ($i = 0; $i < count($dmesg); $i++) {
1309
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1310
			$lastcpline = $i;
1311
	}
1312

    
1313
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1314
	if (!$fd) {
1315
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1316
		return 1;
1317
	}
1318

    
1319
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1320
		fwrite($fd, $dmesg[$i] . "\n");
1321

    
1322
	fclose($fd);
1323

    
1324
	return 0;
1325
}
1326

    
1327
function system_set_harddisk_standby() {
1328
	global $g, $config;
1329
	if(isset($config['system']['developerspew'])) {
1330
		$mt = microtime();
1331
		echo "system_set_harddisk_standby() being called $mt\n";
1332
	}
1333

    
1334
	if (isset($config['system']['harddiskstandby'])) {
1335
		if ($g['booting']) {
1336
			echo 'Setting hard disk standby... ';
1337
		}
1338

    
1339
		$standby = $config['system']['harddiskstandby'];
1340
		// Check for a numeric value
1341
		if (is_numeric($standby)) {
1342
			// Sync the disk(s)
1343
			pfSense_sync();
1344
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1345
				// Reinitialize ATA-drives
1346
				mwexec('/usr/local/sbin/atareinit');
1347
				if ($g['booting']) {
1348
					echo "done.\n";
1349
				}
1350
			} else if ($g['booting']) {
1351
				echo "failed!\n";
1352
			}
1353
		} else if ($g['booting']) {
1354
			echo "failed!\n";
1355
		}
1356
	}
1357
}
1358

    
1359
function system_setup_sysctl() {
1360
	global $config;
1361
	if(isset($config['system']['developerspew'])) {
1362
		$mt = microtime();
1363
		echo "system_setup_sysctl() being called $mt\n";
1364
	}
1365

    
1366
	activate_sysctls();	
1367

    
1368
	if (isset($config['system']['sharednet'])) {
1369
		system_disable_arp_wrong_if();
1370
	}
1371
}
1372

    
1373
function system_disable_arp_wrong_if() {
1374
	global $config;
1375
	if(isset($config['system']['developerspew'])) {
1376
		$mt = microtime();
1377
		echo "system_disable_arp_wrong_if() being called $mt\n";
1378
	}
1379
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1380
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1381
}
1382

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

    
1393
function enable_watchdog() {
1394
	global $config;
1395
	return;
1396
	$install_watchdog = false;
1397
	$supported_watchdogs = array("Geode");
1398
	$file = file_get_contents("/var/log/dmesg.boot");
1399
	foreach($supported_watchdogs as $sd) {
1400
		if(stristr($file, "Geode")) {
1401
			$install_watchdog = true;
1402
		}
1403
	}
1404
	if($install_watchdog == true) {
1405
		if(is_process_running("watchdogd"))
1406
			mwexec("/usr/bin/killall watchdogd", true);
1407
		exec("/usr/sbin/watchdogd");
1408
	}
1409
}
1410

    
1411
function system_check_reset_button() {
1412
	global $g;
1413
	if($g['platform'] != "nanobsd")
1414
		return 0;
1415

    
1416
	$specplatform = system_identify_specific_platform();
1417

    
1418
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1419
		return 0;
1420

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

    
1423
	if ($retval == 99) {
1424
		/* user has pressed reset button for 2 seconds - 
1425
		   reset to factory defaults */
1426
		echo <<<EOD
1427

    
1428
***********************************************************************
1429
* Reset button pressed - resetting configuration to factory defaults. *
1430
* The system will reboot after this completes.                        *
1431
***********************************************************************
1432

    
1433

    
1434
EOD;
1435
		
1436
		reset_factory_defaults();
1437
		system_reboot_sync();
1438
		exit(0);
1439
	}
1440

    
1441
	return 0;
1442
}
1443

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

    
1470
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1471
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1472
	
1473
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1474
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1475
		
1476
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1477
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1478
	
1479
	/* unknown embedded platform */
1480
	return array('name' => 'embedded', 'descr' => 'embedded (unknown)');
1481
}
1482

    
1483
function system_get_dmesg_boot() {
1484
	global $g;
1485
		
1486
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1487
}
1488

    
1489
?>
(47-47/61)