Project

General

Profile

Download (38.8 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	/bin/sync	/usr/local/sbin/ntpd	/usr/sbin/ntpdate
37
	pfSense_BUILDER_BINARIES:	/usr/bin/nohup	/sbin/dmesg	/usr/local/sbin/atareinit
38
	pfSense_MODULE:	utils
39
*/
40

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

    
51
function get_default_sysctl_value($id) {
52
	global $sysctls;
53
	foreach($sysctls as $sysctl => $value) {
54
		if($sysctl == $id)
55
			return $value;
56
	}
57
}
58

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

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

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

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

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

    
88
	$fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
89
	if (!$fd) {
90
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
91
		return 1;
92
	}
93

    
94
	$resolvconf = "domain {$syscfg['domain']}\n";
95

    
96
	$havedns = false;
97

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

    
117
	fwrite($fd, $resolvconf);
118
	fclose($fd);
119

    
120
	if (!$g['booting']) {
121
		/* restart dhcpd (nameservers may have changed) */
122
		if (!$dynupdate)
123
			services_dhcpd_configure();
124
	}
125

    
126
	/* setup static routes for DNS servers. */
127
	for ($dnscounter=1; $dnscounter<5; $dnscounter++) {
128
		/* setup static routes for dns servers */
129
		$dnsgw = "dns{$dnscounter}gwint";
130
		if (isset($config['system'][$dnsgw])) {
131
			$interface = $config['system'][$dnsgw];
132
			if (($interface <> "") && ($interface <> "none")) {
133
				$gatewayip = get_interface_gateway($interface);
134
				if(is_ipaddr($gatewayip)) {
135
					/* dns server array starts at 0 */
136
					$dnscountermo = $dnscounter - 1;
137
					mwexec("route delete -host {$syscfg['dnsserver'][$dnscountermo]}");
138
					mwexec("route add -host {$syscfg['dnsserver'][$dnscountermo]} {$gatewayip}");
139
				}
140
			}
141
		}
142
	}
143
	
144
	return 0;
145
}
146

    
147
function get_nameservers() {
148
	global $config, $g;
149
	$master_list = array();
150
	
151
	// Read in dhclient nameservers
152
	$dns_lists = split("\n", `ls /var/etc/nameserver_* 2>/dev/null`);
153
	if(is_array($dns_lists)) {
154
		foreach($dns_lists as $dns) {
155
			if(!$dns) 
156
				continue;
157
			$items = split("\n", file_get_contents($dns));
158
			foreach($items as $item)
159
				if($item <> "")
160
					$master_list[] = $item;
161
		}
162
	}
163

    
164
	// Read in any extra nameservers
165
	if(file_exists("/var/etc/nameservers.conf")) {
166
		$dns = `cat /var/etc/nameservers.conf`;
167
		$dns_s = split("\n", $dns);
168
		if(is_array($dns_s))
169
			foreach($dns_s as $dns)
170
				$master_list[] = $dns;
171
	}
172

    
173
	return $master_list;
174
}
175

    
176
function system_hosts_generate() {
177
	global $config, $g;
178
	if(isset($config['system']['developerspew'])) {
179
		$mt = microtime();
180
		echo "system_hosts_generate() being called $mt\n";
181
	}
182

    
183
	$syscfg = $config['system'];
184
	$lancfg = $config['interfaces']['lan'];
185
	$lancfgip = get_interface_ip("lan");
186
	$dnsmasqcfg = $config['dnsmasq'];
187

    
188
	if (!is_array($dnsmasqcfg['hosts'])) {
189
		$dnsmasqcfg['hosts'] = array();
190
	}
191
	$hostscfg = $dnsmasqcfg['hosts'];
192

    
193
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
194
	if (!$fd) {
195
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
196
		return 1;
197
	}
198

    
199
	$hosts = <<<EOD
200
127.0.0.1	localhost localhost.{$syscfg['domain']}
201

    
202
EOD;
203
	if (is_ipaddr($lancfgip))
204
		$hosts .= <<<EOD
205
{$lancfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}
206

    
207
EOD;
208

    
209
	foreach ($hostscfg as $host) {
210
		if ($host['host'])
211
			$hosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
212
		else
213
			$hosts .= "{$host['ip']}	{$host['domain']}\n";
214
	}
215
	if (isset($dnsmasqcfg['regdhcpstatic'])) {
216
		foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf)
217
			if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
218
					foreach ($dhcpifconf['staticmap'] as $host)
219
						if ($host['ipaddr'] && $host['hostname'])
220
							$hosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
221
	}
222
	fwrite($fd, $hosts);
223
	fclose($fd);
224

    
225
	return 0;
226
}
227

    
228
function system_hostname_configure() {
229
	global $config, $g;
230
	if(isset($config['system']['developerspew'])) {
231
		$mt = microtime();
232
		echo "system_hostname_configure() being called $mt\n";
233
	}
234

    
235
	$syscfg = $config['system'];
236

    
237
	/* set hostname */
238
	$status = mwexec("/bin/hostname " .
239
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
240

    
241
    /* Setup host GUID ID.  This is used by ZFS. */
242
	mwexec("/etc/rc.d/hostid start");
243

    
244
	return $status;
245
}
246

    
247
function system_routing_configure() {
248
	global $config, $g;
249
	if(isset($config['system']['developerspew'])) {
250
		$mt = microtime();
251
		echo "system_routing_configure() being called $mt\n";
252
	}
253

    
254
	/* Enable fast routing, if enabled */
255
	if(isset($config['staticroutes']['enablefastrouting']))
256
		mwexec("/sbin/sysctl net.inet.ip.fastforwarding=1");
257

    
258
	$route_str = exec_command("/usr/bin/netstat -rn");
259

    
260
	/* clear out old routes, if necessary */
261
	if (file_exists("{$g['vardb_path']}/routes.db")) {
262
		$fd = fopen("{$g['vardb_path']}/routes.db", "r");
263
		if (!$fd) {
264
			printf("Error: cannot open routes DB file in system_routing_configure().\n");
265
			return 1;
266
		}
267
		while (!feof($fd)) {
268
			$oldrt = trim(fgets($fd));
269
			if (($oldrt) && (stristr($route_str, $oldrt)))
270
				mwexec("/sbin/route delete " . escapeshellarg($oldrt));
271
		}
272
		fclose($fd);
273
		unlink("{$g['vardb_path']}/routes.db");
274
	}
275

    
276
	if (false) {
277
	/* if list */
278
	$iflist = get_configured_interface_list();
279

    
280
	$dont_remove_route = false;
281
	foreach ($iflist as $ifent => $ifname) {
282
		/* 
283
		 * XXX: The value of this is really when this function can take
284
		 * 	an interface as parameter.
285
		 */
286
		/* do not process interfaces that will end up with gateways */
287
		if (interface_has_gateway($ifent) || 
288
			$config['interfaces'][$ifent]['ipaddr'] == "carpdev-dhcp") {
289
			$dont_remove_route = true;
290
			break;
291
		}
292
	}
293

    
294
	if ($dont_remove_route == false) {
295
		/* remove default route */
296
		mwexec("/sbin/route delete default", true);
297
	}
298
	}
299

    
300
	$dont_add_route = false;
301
	/* if OLSRD is enabled, allow WAN to house DHCP. */
302
	if($config['installedpackages']['olsrd']) {
303
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
304
			if($olsrd['enabledyngw'] == "on") {
305
				$dont_add_route = true;
306
				break;
307
			}
308
		}
309
	}
310

    
311
	if($dont_add_route == false) {
312
		if(is_array($config['gateways']['gateway_item'])) {
313
			foreach($config['gateways']['gateway_item'] as $gateway) {
314
		        	if(isset($gateway['defaultgw'])) {
315
					$gatewayip = $gateway['gateway'];
316
					$interfacegw = $gateway['interface'];
317
				}
318
			}
319
			if(($interfacegw <> "bgpd") && (is_ipaddr($gatewayip))) {
320
				preg_match("/default[ ]+([0-9].*?)[ ]+/i", $route_str, $elements);
321
				if(trim($elements[1]) != "$gatewayip") {
322
					mwexec("/sbin/route delete default " . escapeshellarg($gatewayip), false);
323
				}
324
				mwexec("/sbin/route add default " . escapeshellarg($gatewayip), true);
325
			}
326
		} else {
327
			log_error("SYSTEM: We do not have a gateways array in our XML. Is this configuration damaged?");
328
			/* adding gateway for 1.2-style configs without the new
329
			  gateway setup configured.
330
			  Force WAN to be default gateway because that is the
331
			  1.2 behavior.
332
			*/
333
			if (is_ipaddr($config['interfaces']['wan']['gateway'])) {
334
				$gatewayip = $config['interfaces']['wan']['gateway'];
335
				mwexec("/sbin/route add default " . escapeshellarg($gatewayip), true);
336
			}
337
		}
338
	}
339

    
340
	if (is_array($config['staticroutes']['route'])) {
341

    
342
		$fd = fopen("{$g['vardb_path']}/routes.db", "w");
343
		if (!$fd) {
344
			printf("Error: cannot open routes DB file in system_routing_configure().\n");
345
			return 1;
346
		}
347

    
348
		foreach ($config['staticroutes']['route'] as $rtent) {
349
			unset($gatewayip);
350
			unset($interfacegw);
351
			if(is_array($config['gateways']['gateway_item'])) {
352
				foreach($config['gateways']['gateway_item'] as $gateway) {
353
					if($rtent['gateway'] == $gateway['name']) {
354
						$gatewayip = $gateway['gateway'];
355
						$interfacegw = $gateway['interface'];
356
					}
357
				}
358
			}
359
			if((is_ipaddr($rtent['gateway'])) && ($gatewayip == ""))  {
360
				$gatewayip = $rtent['gateway'];
361
				$interfacegw = $rtent['interface'];
362
			}			
363
			if((isset($rtent['interfacegateway'])) && (! is_ipaddr($gatewayip))) {
364
				mwexec("/sbin/route add " . escapeshellarg($rtent['network']) .
365
					" -iface " . escapeshellarg(convert_friendly_interface_to_real_interface_name($interfacegw)));
366
			} else {
367
				mwexec("/sbin/route add " . escapeshellarg($rtent['network']) .
368
					" " . escapeshellarg($gatewayip));
369
			}
370
			/* record route so it can be easily removed later (if necessary) */
371
			fwrite($fd, $rtent['network'] . "\n");
372
		}
373
		fclose($fd);
374
	}
375

    
376
	return 0;
377
}
378

    
379

    
380
function system_routing_enable() {
381
	global $config, $g;
382
	if(isset($config['system']['developerspew'])) {
383
		$mt = microtime();
384
		echo "system_routing_enable() being called $mt\n";
385
	}
386

    
387
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
388
}
389

    
390
function system_syslogd_start() {
391
	global $config, $g;
392
	if(isset($config['system']['developerspew'])) {
393
		$mt = microtime();
394
		echo "system_syslogd_start() being called $mt\n";
395
	}
396

    
397
	$syslogcfg = $config['syslog'];
398

    
399
	if ($g['booting'])
400
		echo "Starting syslog...";
401
	else
402
		killbypid("{$g['varrun_path']}/syslog.pid");
403

    
404
	if(is_process_running("syslogd"))
405
		mwexec("/usr/bin/killall -9 syslogd");
406
	if(is_process_running("fifolog_writer"))
407
		mwexec("/usr/bin/killall -9 fifolog_writer");
408
	
409
	// Define carious commands for logging
410
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
411
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
412
	$clog_create = "/usr/sbin/clog -i -s ";
413
	$clog_log = "%";
414

    
415
	// Which logging type are we using this week??
416
	if(isset($config['system']['usefifolog'])) {
417
		$log_directive = $fifolog_log;
418
		$log_create_directive = $fifolog_create;		
419
	} else { // Defaults to CLOG
420
		$log_directive = $clog_log;
421
		$log_create_directive = $clog_create;
422
	}
423
	
424
	if (isset($syslogcfg)) {
425
		$separatelogfacilities = array('ntpd','racoon','openvpn');
426
		if($config['installedpackages']['package']) {
427
			foreach($config['installedpackages']['package'] as $package) {
428
				if($package['logging']) {
429
					$pkgfacilities[] = $package['logging']['facilityname'];
430
					$separatelogfacilities = $separatelogfacilities + $pkgfacilities;
431
					$facilitylist = implode(',', $pkgfacilities);
432
					mwexec("{$log_create_directive} 10240 {$g['varlog_path']}/{$package['logging']['logfilename']}");
433
					$syslogconf .= "!{$facilitylist}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
434
				}
435
			}
436
		}
437
		$facilitylist = implode(',', array_unique($separatelogfacilities));
438
		/* write syslog.conf */		
439
		$fd = fopen("{$g['varetc_path']}/syslog.conf", "w");
440
		if (!$fd) {
441
			printf("Error: cannot open syslog.conf in system_syslogd_start().\n");
442
			return 1;
443
		}
444
		$syslogconf .= "!ntpdate,!ntpd\n";
445
		if (!isset($syslogcfg['disablelocallogging'])) 
446
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/ntpd.log\n";
447
		$syslogconf .= "!ppp\n";
448
		if (!isset($syslogcfg['disablelocallogging'])) 
449
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/ppp.log\n";
450
		$syslogconf .= "!racoon\n";
451
		if (!isset($syslogcfg['disablelocallogging'])) 
452
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/ipsec.log\n";
453
		$syslogconf .= "!apinger\n";
454
		if (!isset($syslogcfg['disablelocallogging'])) 
455
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/slbd.log\n";
456
		if (isset($syslogcfg['vpn'])) {
457
			if($syslogcfg['remoteserver'])
458
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver']}\n";
459
			if($syslogcfg['remoteserver2'])
460
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver2']}\n";
461
			if($syslogcfg['remoteserver3'])
462
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver3']}\n";
463
		}
464
		$syslogconf .= "!openvpn\n";
465
		if (!isset($syslogcfg['disablelocallogging'])) 
466
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/openvpn.log\n";
467
		if (isset($syslogcfg['vpn'])) {
468
			if($syslogcfg['remoteserver'])
469
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver']}\n";
470
			if($syslogcfg['remoteserver2'])
471
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver3']}\n";
472
			if($syslogcfg['remoteserver3'])
473
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver3']}\n";
474
		}
475
		$syslogconf .= "!-{$facilitylist}\n";
476
		if (!isset($syslogcfg['disablelocallogging'])) 
477
			$syslogconf .= <<<EOD
478
local0.*										 {$log_directive}{$g['varlog_path']}/filter.log
479
local3.*										 {$log_directive}{$g['varlog_path']}/vpn.log
480
local4.*										 {$log_directive}{$g['varlog_path']}/portalauth.log
481
local7.*										 {$log_directive}{$g['varlog_path']}/dhcpd.log
482
*.notice;kern.debug;lpr.info;mail.crit; 		 {$log_directive}{$g['varlog_path']}/system.log
483
news.err;local0.none;local3.none;local4.none; 	 {$log_directive}{$g['varlog_path']}/system.log
484
local7.none										 {$log_directive}{$g['varlog_path']}/system.log
485
security.*										 {$log_directive}{$g['varlog_path']}/system.log
486
auth.info;authpriv.info;daemon.info				 {$log_directive}{$g['varlog_path']}/system.log
487
local1.*										 {$log_directive}{$g['varlog_path']}/relayd.log
488
auth.info;authpriv.info 						 |exec /usr/local/sbin/sshlockout_pf
489
*.emerg											 *
490

    
491
EOD;
492
		if (isset($syslogcfg['filter'])) {
493
			if($syslogcfg['remoteserver'])
494
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver']}\n";
495
			if($syslogcfg['remoteserver2'])
496
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver2']}\n";
497
			if($syslogcfg['remoteserver3'])
498
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver3']}\n";
499

    
500
		}
501
		if (isset($syslogcfg['vpn'])) {
502
			if($syslogcfg['remoteserver'])
503
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver']}\n";
504
			if($syslogcfg['remoteserver2'])
505
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver2']}\n";
506
			if($syslogcfg['remoteserver3'])
507
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver3']}\n";
508
		}
509
		if (isset($syslogcfg['portalauth'])) {
510
			if($syslogcfg['remoteserver'])
511
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver']}\n";
512
			if($syslogcfg['remoteserver2'])
513
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver2']}\n";
514
			if($syslogcfg['remoteserver3'])
515
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver3']}\n";
516
		}
517
		if (isset($syslogcfg['dhcp'])) {
518
			if($syslogcfg['remoteserver'])
519
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver']}\n";
520
			if($syslogcfg['remoteserver2'])
521
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver2']}\n";
522
			if($syslogcfg['remoteserver3'])
523
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver3']}\n";
524
		}
525
		if (isset($syslogcfg['system'])) {
526
			if($syslogcfg['remoteserver'])
527
				$syslogconf .= <<<EOD
528
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver']}
529
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver']}
530
security.*										 @{$syslogcfg['remoteserver']}
531
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver']}
532
*.emerg											 @{$syslogcfg['remoteserver']}
533

    
534
EOD;
535

    
536
		if (isset($syslogcfg['system'])) {
537
			if($syslogcfg['remoteserver2'])
538
				$syslogconf .= <<<EOD
539
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver2']}
540
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver2']}
541
security.*										 @{$syslogcfg['remoteserver2']}
542
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver2']}
543
*.emerg											 @{$syslogcfg['remoteserver2']}
544

    
545
EOD;
546

    
547
		if (isset($syslogcfg['system'])) {
548
			if($syslogcfg['remoteserver3'])
549
				$syslogconf .= <<<EOD
550
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver3']}
551
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver3']}
552
security.*										 @{$syslogcfg['remoteserver3']}
553
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver3']}
554
*.emerg											 @{$syslogcfg['remoteserver3']}
555

    
556
EOD;
557

    
558
}
559
		if (isset($syslogcfg['logall'])) {
560
			if($syslogcfg['remoteserver'])
561
				$syslogconf .= <<<EOD
562
*.*								@{$syslogcfg['remoteserver']}
563

    
564
EOD;
565

    
566
}
567
			if($syslogcfg['remoteserver2'])
568
				$syslogconf .= <<<EOD
569
*.*								@{$syslogcfg['remoteserver2']}
570

    
571
EOD;
572

    
573
}
574
			if($syslogcfg['remoteserver3'])
575
				$syslogconf .= <<<EOD
576
*.*								@{$syslogcfg['remoteserver3']}
577

    
578
EOD;
579

    
580
}
581
		fwrite($fd, $syslogconf);
582
		fclose($fd);
583
		// Are we logging to a least one remote server ?
584
		if(strpos($syslogconf, "@") != false)
585
			$retval = system("/usr/sbin/syslogd -c -f {$g['varetc_path']}/syslog.conf");
586
		else
587
			$retval = system("/usr/sbin/syslogd -c -f {$g['varetc_path']}/syslog.conf");
588

    
589
	} else {
590
		$retval = mwexec("/usr/sbin/syslogd -c");
591
	}
592

    
593
	if ($g['booting'])
594
		echo "done.\n";
595

    
596
	return $retval;
597
}
598

    
599
function system_pccard_start() {
600
	global $config, $g;
601
	if(isset($config['system']['developerspew'])) {
602
		$mt = microtime();
603
		echo "system_pccard_start() being called $mt\n";
604
	}
605

    
606
	if ($g['booting'])
607
		echo "Initializing PCMCIA...";
608

    
609
	/* kill any running pccardd */
610
	killbypid("{$g['varrun_path']}/pccardd.pid");
611

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

    
615
	if ($g['booting']) {
616
		if ($res == 0)
617
			echo "done.\n";
618
		else
619
			echo "failed!\n";
620
	}
621

    
622
	return $res;
623
}
624

    
625

    
626
function system_webgui_start() {
627
	global $config, $g;
628

    
629
	if ($g['booting'])
630
		echo "Starting webConfigurator...";
631

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

    
635
	sleep(1);
636

    
637
	chdir($g['www_path']);
638

    
639
	/* defaults */
640
	$portarg = "80";
641
	$crt = "";
642
	$key = "";
643
	$ca = "";
644

    
645
	/* non-standard port? */
646
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
647
		$portarg = "{$config['system']['webgui']['port']}";
648

    
649
	if ($config['system']['webgui']['protocol'] == "https") {
650
		// Ensure that we have a webConfigurator CERT
651
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
652
		if(!is_array($cert) && !$cert['crt'] && !$cert['prv']) {
653
			if (!is_array($config['system']['ca']))
654
				$config['system']['ca'] = array();
655
			$a_ca =& $config['system']['ca'];
656
			if (!is_array($config['system']['cert']))
657
				$config['system']['cert'] = array();
658
			$a_cert =& $config['system']['cert'];
659
			echo "Creating SSL Certificate... ";
660
			$cert = array();
661
			$cert['refid'] = uniqid();
662
			$cert['name'] = "webConfigurator default";
663
			mwexec("/usr/bin/openssl genrsa 1024 > {$g['tmp_path']}/ssl.key");
664
			mwexec("/usr/bin/openssl req -new -x509 -nodes -sha1 -days 2000 -key {$g['tmp_path']}/ssl.key > {$g['tmp_path']}/ssl.crt");
665
			$crt = file_get_contents("{$g['tmp_path']}/ssl.crt");
666
			$key = file_get_contents("{$g['tmp_path']}/ssl.key");
667
			unlink("{$g['tmp_path']}/ssl.key");
668
			unlink("{$g['tmp_path']}/ssl.crt");
669
			cert_import($cert, $crt, $key);
670
			$a_cert[] = $cert;
671
			$config['system']['webgui']['ssl-certref'] = $cert['refid'];
672
			write_config("Importing HTTPS certificate");
673
			if(!$config['system']['webgui']['port'])
674
				$portarg = "443";
675
			$ca = ca_chain($cert);
676
		} else {
677
			$crt = base64_decode($cert['crt']);
678
			$key = base64_decode($cert['prv']);
679
			if(!$config['system']['webgui']['port'])
680
				$portarg = "443";
681
			$ca = ca_chain($cert);
682
		}
683
	}
684

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

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

    
692
	/* fetch page to preload apc cache */
693
	mwexec("fetch -o /dev/null -q {$config['system']['webgui']['protocol']}://localhost:{$portarg}/preload.php");
694

    
695
	if ($g['booting']) {
696
		if ($res == 0)
697
			echo "done.\n";
698
		else
699
			echo "failed!\n";
700
	}
701

    
702
	return $res;
703
}
704

    
705
function system_generate_lighty_config($filename,
706
	$cert,
707
	$key,
708
	$ca,
709
	$pid_file,
710
	$port = 80,
711
	$document_root = "/usr/local/www/",
712
	$cert_location = "cert.pem",
713
	$ca_location = "ca.pem",
714
	$max_procs = 2,
715
	$max_requests = "1",
716
	$fast_cgi_enable = true,
717
	$captive_portal = false) {
718

    
719
	global $config, $g;
720

    
721
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
722
		mkdir("{$g['tmp_path']}/lighttpdcompress");
723

    
724
	if(isset($config['system']['developerspew'])) {
725
		$mt = microtime();
726
		echo "system_generate_lighty_config() being called $mt\n";
727
	}
728

    
729
	if($captive_portal == true)  {
730
		$captiveportal = ",\"mod_rewrite\"";
731
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?redirurl=$1\" )\n";
732
		$captive_portal_module = "\"mod_accesslog\", ";
733
		$maxprocperip = $config['captiveportal']['maxprocperip'];
734
		if(!$maxprocperip and $maxprocperip > 0)
735
			$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
736
		else
737
			$captive_portal_mod_evasive = "";
738
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
739
		exec("mkdir -p {$g['tmp_path']}/captiveportal");
740
		exec("chmod a-w {$g['tmp_path']}/captiveportal");
741
		$server_max_request_size = "server.max-request-size    = 384";
742
	} else {
743
		$captive_portal_module = "";
744
		$captive_portal_mod_evasive = "";
745
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
746
		$server_max_request_size = "server.max-request-size    = 2097152";
747
	}
748
	
749
	if($port <> "")
750
		$lighty_port = $port;
751
	else
752
		$lighty_port = "80";
753

    
754
	$memory = get_memory();
755
	$avail = $memory[0];
756

    
757
	if($avail > 0 and $avail < 65) {
758
		$fast_cgi_enable = false;
759
	}
760

    
761
	if($avail > 65 and $avail < 98) {
762
		$max_procs = 1;
763
	}
764

    
765
	if($avail > 97 and $avail < 128) {
766
		$max_procs = 2;
767
	}
768

    
769
	if($avail > 127 and $avail < 256) {
770
		$max_procs = 3;
771
	}
772

    
773
	if($avail > 255 and $avail < 384) {
774
		$max_procs = 4;
775
	}
776

    
777
	if($avail > 383) {
778
		$max_procs = 5;
779
	}
780

    
781
	if($captive_portal == true)  {	
782
		$bin_environment =  <<<EOC
783
        "bin-environment" => (
784
           "PHP_FCGI_CHILDREN" => "$max_procs",
785
           "PHP_FCGI_MAX_REQUESTS" => "500"
786
        ), 
787
EOC;
788

    
789
	} else if ($avail > 0 and $avail < 128) {
790
		$bin_environment = <<<EOC
791
		"bin-environment" => (
792
			"PHP_FCGI_CHILDREN" => "$max_procs",
793
			"PHP_FCGI_MAX_REQUESTS" => "2",
794
	),
795

    
796
EOC;
797
	} else
798
		$bin_environment =  <<<EOC
799
        "bin-environment" => (
800
           "PHP_FCGI_CHILDREN" => "$max_procs",
801
           "PHP_FCGI_MAX_REQUESTS" => "500"
802
        ), 
803
EOC;
804

    
805
	if($fast_cgi_enable == true) {
806
		$module = "\"mod_fastcgi\", \"mod_cgi\"";
807
		$cgi_config = "";
808
		$fastcgi_config = <<<EOD
809
#### fastcgi module
810
## read fastcgi.txt for more info
811
fastcgi.server = ( ".php" =>
812
	( "localhost" =>
813
		(
814
			"socket" => "{$g['tmp_path']}/php-fastcgi.socket",
815
			"min-procs" => 0,
816
			"max-procs" => {$max_procs},
817
			{$bin_environment}			
818
			"bin-path" => "/usr/local/bin/php"
819
		)
820
	)
821
)
822

    
823
#### CGI module
824
cgi.assign                 = ( ".cgi" => "" )
825

    
826
EOD;
827
	} else {
828
		$fastcgi_config = "";
829
		$module = "\"mod_cgi\"";
830
		$cgi_config = <<<EOD
831
#### CGI module
832
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
833
                               ".cgi" => "" )
834

    
835
EOD;
836
	}
837

    
838
	$lighty_config .= <<<EOD
839
#
840
# lighttpd configuration file
841
#
842
# use a it as base for lighttpd 1.0.0 and above
843
#
844
############ Options you really have to take care of ####################
845

    
846
## FreeBSD!
847
server.event-handler	= "freebsd-kqueue"
848
server.network-backend 	= "writev"
849

    
850
## modules to load
851
server.modules              =   (
852
									{$captive_portal_module}
853
									"mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect",
854
									{$module}{$captiveportal}
855
								)
856

    
857
## Unused modules
858
#                               "mod_setenv",
859
#                               "mod_rewrite",
860
#                               "mod_ssi",
861
#                               "mod_usertrack",
862
#                               "mod_expire",
863
#                               "mod_secdownload",
864
#                               "mod_rrdtool",
865
#                               "mod_auth",
866
#                               "mod_status",
867
#                               "mod_alias",
868
#                               "mod_proxy",
869
#                               "mod_simple_vhost",
870
#                               "mod_evhost",
871
#                               "mod_userdir",
872
#                               "mod_cgi",
873

    
874
server.max-keep-alive-requests = 15
875
server.max-keep-alive-idle = 30
876

    
877
## a static document-root, for virtual-hosting take look at the
878
## server.virtual-* options
879
server.document-root        = "{$document_root}"
880
{$captive_portal_rewrite}
881

    
882
# Maximum idle time with nothing being written (php downloading)
883
server.max-write-idle = 999
884

    
885
## where to send error-messages to
886
server.errorlog             = "/var/log/lighttpd.error.log"
887

    
888
# files to check for if .../ is requested
889
server.indexfiles           = ( "index.php", "index.html",
890
                                "index.htm", "default.htm" )
891

    
892
# mimetype mapping
893
mimetype.assign             = (
894
  ".pdf"          =>      "application/pdf",
895
  ".sig"          =>      "application/pgp-signature",
896
  ".spl"          =>      "application/futuresplash",
897
  ".class"        =>      "application/octet-stream",
898
  ".ps"           =>      "application/postscript",
899
  ".torrent"      =>      "application/x-bittorrent",
900
  ".dvi"          =>      "application/x-dvi",
901
  ".gz"           =>      "application/x-gzip",
902
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
903
  ".swf"          =>      "application/x-shockwave-flash",
904
  ".tar.gz"       =>      "application/x-tgz",
905
  ".tgz"          =>      "application/x-tgz",
906
  ".tar"          =>      "application/x-tar",
907
  ".zip"          =>      "application/zip",
908
  ".mp3"          =>      "audio/mpeg",
909
  ".m3u"          =>      "audio/x-mpegurl",
910
  ".wma"          =>      "audio/x-ms-wma",
911
  ".wax"          =>      "audio/x-ms-wax",
912
  ".ogg"          =>      "audio/x-wav",
913
  ".wav"          =>      "audio/x-wav",
914
  ".gif"          =>      "image/gif",
915
  ".jpg"          =>      "image/jpeg",
916
  ".jpeg"         =>      "image/jpeg",
917
  ".png"          =>      "image/png",
918
  ".xbm"          =>      "image/x-xbitmap",
919
  ".xpm"          =>      "image/x-xpixmap",
920
  ".xwd"          =>      "image/x-xwindowdump",
921
  ".css"          =>      "text/css",
922
  ".html"         =>      "text/html",
923
  ".htm"          =>      "text/html",
924
  ".js"           =>      "text/javascript",
925
  ".asc"          =>      "text/plain",
926
  ".c"            =>      "text/plain",
927
  ".conf"         =>      "text/plain",
928
  ".text"         =>      "text/plain",
929
  ".txt"          =>      "text/plain",
930
  ".dtd"          =>      "text/xml",
931
  ".xml"          =>      "text/xml",
932
  ".mpeg"         =>      "video/mpeg",
933
  ".mpg"          =>      "video/mpeg",
934
  ".mov"          =>      "video/quicktime",
935
  ".qt"           =>      "video/quicktime",
936
  ".avi"          =>      "video/x-msvideo",
937
  ".asf"          =>      "video/x-ms-asf",
938
  ".asx"          =>      "video/x-ms-asf",
939
  ".wmv"          =>      "video/x-ms-wmv",
940
  ".bz2"          =>      "application/x-bzip",
941
  ".tbz"          =>      "application/x-bzip-compressed-tar",
942
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
943
 )
944

    
945
# Use the "Content-Type" extended attribute to obtain mime type if possible
946
#mimetypes.use-xattr        = "enable"
947

    
948
#### accesslog module
949
#accesslog.filename          = "/dev/null"
950

    
951
## deny access the file-extensions
952
#
953
# ~    is for backupfiles from vi, emacs, joe, ...
954
# .inc is often used for code includes which should in general not be part
955
#      of the document-root
956
url.access-deny             = ( "~", ".inc" )
957

    
958

    
959
######### Options that are good to be but not neccesary to be changed #######
960

    
961
## bind to port (default: 80)
962
server.port                = {$lighty_port}
963

    
964
## error-handler for status 404
965
#server.error-handler-404   = "/error-handler.html"
966
#server.error-handler-404   = "/error-handler.php"
967

    
968
## to help the rc.scripts
969
server.pid-file            = "/var/run/{$pid_file}"
970

    
971
## virtual directory listings
972
server.dir-listing         = "disable"
973

    
974
## enable debugging
975
debug.log-request-header   = "disable"
976
debug.log-response-header  = "disable"
977
debug.log-request-handling = "disable"
978
debug.log-file-not-found   = "disable"
979

    
980
# gzip compression
981
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
982
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
983

    
984
{$server_upload_dirs}
985

    
986
{$server_max_request_size}
987

    
988
{$fastcgi_config}
989

    
990
{$cgi_config}
991

    
992
{$captive_portal_mod_evasive}
993

    
994
expire.url = (
995
				"" => "access 50 hours",	
996
        )
997

    
998
EOD;
999

    
1000
	$cert = str_replace("\r", "", $cert);
1001
	$key = str_replace("\r", "", $key);
1002
	$ca = str_replace("\r", "", $ca);
1003

    
1004
	$cert = str_replace("\n\n", "\n", $cert);
1005
	$key = str_replace("\n\n", "\n", $key);
1006
	$ca = str_replace("\n\n", "\n", $ca);
1007

    
1008
	if($cert <> "" and $key <> "") {
1009
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1010
		if (!$fd) {
1011
			printf("Error: cannot open cert.pem in system_webgui_start().\n");
1012
			return 1;
1013
		}
1014
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1015
		fwrite($fd, $cert);
1016
		fwrite($fd, "\n");
1017
		fwrite($fd, $key);
1018
		fclose($fd);
1019
		if($ca <> "") {
1020
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1021
			if (!$fd) {
1022
				printf("Error: cannot open ca.pem in system_webgui_start().\n");
1023
				return 1;
1024
			}
1025
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1026
			fwrite($fd, $ca);
1027
			fclose($fd);
1028
		}
1029
		$lighty_config .= "\n";
1030
		$lighty_config .= "## ssl configuration\n";
1031
		$lighty_config .= "ssl.engine = \"enable\"\n";
1032
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1033
		if($ca <> "")
1034
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1035
	}
1036

    
1037
	// Add HTTP to HTTPS redirect	
1038
	if ($captive_portal == false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1039
		if($lighty_port != "443") 
1040
			$redirectport = ":{$lighty_port}";
1041
		$lighty_config .= <<<EOD
1042
\$SERVER["socket"] == ":80" {
1043
	\$HTTP["host"] =~ "(.*)" {
1044
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1045
	}
1046
}
1047
EOD;
1048
	}
1049

    
1050
	$fd = fopen("{$filename}", "w");
1051
	if (!$fd) {
1052
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
1053
		return 1;
1054
	}
1055
	fwrite($fd, $lighty_config);
1056
	fclose($fd);
1057

    
1058
	return 0;
1059

    
1060
}
1061

    
1062
function system_timezone_configure() {
1063
	global $config, $g;
1064
	if(isset($config['system']['developerspew'])) {
1065
		$mt = microtime();
1066
		echo "system_timezone_configure() being called $mt\n";
1067
	}
1068

    
1069
	$syscfg = $config['system'];
1070

    
1071
	if ($g['booting'])
1072
		echo "Setting timezone...";
1073

    
1074
	/* extract appropriate timezone file */
1075
	$timezone = $syscfg['timezone'];
1076
	if (!$timezone)
1077
		$timezone = "Etc/UTC";
1078

    
1079
	conf_mount_rw();
1080

    
1081
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1082
		escapeshellarg($timezone) . " > /etc/localtime");
1083

    
1084
	mwexec("sync");
1085
	conf_mount_ro();
1086

    
1087
	if ($g['booting'])
1088
		echo "done.\n";
1089
}
1090

    
1091
function system_ntp_configure() {
1092
	global $config, $g;
1093

    
1094
	$syscfg = $config['system'];
1095

    
1096
	/* open configuration for wrting or bail */
1097
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1098
	if(!$fd) {
1099
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1100
		return;
1101
	}
1102

    
1103
	fwrite($fd, "# \n");
1104
	fwrite($fd, "# pfSense OpenNTPD configuration file \n");
1105
	fwrite($fd, "# \n\n");
1106

    
1107
	/* foreach through servers and write out to ntpd.conf */
1108
	foreach (explode(' ', $syscfg['timeservers']) as $ts)
1109
		fwrite($fd, "servers {$ts}\n");
1110

    
1111
	/* Setup listener(s) if the user has configured one */
1112
        if ($config['installedpackages']['openntpd']) {
1113
    		/* server config is in coregui1 */
1114
		$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
1115
		if ($xmlsettings['enable'] == 'on') {
1116
			$ifaces = explode(',', $xmlsettings['interface']);
1117
			$ifaces = array_map('get_real_interface', $ifaces);
1118
			$ifaces = array_filter($ifaces, 'does_interface_exist');
1119
			$ips = array_map('find_interface_ip', $ifaces);
1120
			foreach ($ips as $ip) {
1121
				if (is_ipaddr($ip))
1122
					fwrite($fd, "listen on $ip\n");
1123
			}
1124
		}
1125
	}
1126

    
1127
	fwrite($fd, "\n");
1128

    
1129
	/* slurp! */
1130
	fclose($fd);
1131

    
1132
	/* if openntpd is running, kill it */
1133
	while(is_process_running("ntpd")) {
1134
		mwexec("/usr/bin/killall ntpd", true);
1135
	}
1136

    
1137
	/* if /var/empty does not exist, create it */
1138
	if(!is_dir("/var/empty"))
1139
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1140

    
1141
	if($g['booting'])
1142
		return;
1143
	
1144
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1145
	exec("/usr/local/sbin/ntpd -s -f {$g['varetc_path']}/ntpd.conf");
1146
	
1147
	// Note that we are starting up
1148
	exec("echo 'OpenNTPD is starting up' >> {$g['varlog_path']}/ntpd.log");
1149

    
1150
}
1151

    
1152
function sync_system_time() {
1153
	global $config, $g;
1154

    
1155
	$syscfg = $config['system'];
1156

    
1157
	if ($g['booting'])
1158
		echo "Syncing system time before startup...";
1159

    
1160
	/* foreach through servers and write out to ntpd.conf */
1161
	foreach (explode(' ', $syscfg['timeservers']) as $ts) {
1162
		mwexec("/usr/sbin/ntpdate -s $ts");
1163
	}
1164
	
1165
	if ($g['booting'])
1166
		echo "done.\n";
1167
	
1168
}
1169

    
1170
function system_halt() {
1171
	global $g;
1172

    
1173
	system_reboot_cleanup();
1174

    
1175
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1176
}
1177

    
1178
function system_reboot() {
1179
	global $g;
1180

    
1181
	system_reboot_cleanup();
1182

    
1183
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1184
}
1185

    
1186
function system_reboot_sync() {
1187
	global $g;
1188

    
1189
	system_reboot_cleanup();
1190

    
1191
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1192
}
1193

    
1194
function system_reboot_cleanup() {
1195
	mwexec("/usr/local/bin/beep.sh stop");
1196
	require_once("captiveportal.inc");
1197
	captiveportal_radius_stop_all();
1198
	require_once("voucher.inc");
1199
	voucher_save_db_to_config();
1200
}
1201

    
1202
function system_do_shell_commands($early = 0) {
1203
	global $config, $g;
1204
	if(isset($config['system']['developerspew'])) {
1205
		$mt = microtime();
1206
		echo "system_do_shell_commands() being called $mt\n";
1207
	}
1208

    
1209
	if ($early)
1210
		$cmdn = "earlyshellcmd";
1211
	else
1212
		$cmdn = "shellcmd";
1213

    
1214
	if (is_array($config['system'][$cmdn])) {
1215

    
1216
		/* *cmd is an array, loop through */
1217
		foreach ($config['system'][$cmdn] as $cmd) {
1218
			exec($cmd);
1219
		}
1220

    
1221
	} elseif($config['system'][$cmdn] <> "") {
1222

    
1223
		/* execute single item */
1224
		exec($config['system'][$cmdn]);
1225

    
1226
	}
1227
}
1228

    
1229
function system_console_configure() {
1230
	global $config, $g;
1231
	if(isset($config['system']['developerspew'])) {
1232
		$mt = microtime();
1233
		echo "system_console_configure() being called $mt\n";
1234
	}
1235

    
1236
	if (isset($config['system']['disableconsolemenu'])) {
1237
		touch("{$g['varetc_path']}/disableconsole");
1238
	} else {
1239
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1240
	}
1241
}
1242

    
1243
function system_dmesg_save() {
1244
	global $g;
1245
	if(isset($config['system']['developerspew'])) {
1246
		$mt = microtime();
1247
		echo "system_dmesg_save() being called $mt\n";
1248
	}
1249

    
1250
	$dmesg = "";
1251
	exec("/sbin/dmesg", $dmesg);
1252

    
1253
	/* find last copyright line (output from previous boots may be present) */
1254
	$lastcpline = 0;
1255

    
1256
	for ($i = 0; $i < count($dmesg); $i++) {
1257
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1258
			$lastcpline = $i;
1259
	}
1260

    
1261
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1262
	if (!$fd) {
1263
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1264
		return 1;
1265
	}
1266

    
1267
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1268
		fwrite($fd, $dmesg[$i] . "\n");
1269

    
1270
	fclose($fd);
1271

    
1272
	return 0;
1273
}
1274

    
1275
function system_set_harddisk_standby() {
1276
	global $g, $config;
1277
	if(isset($config['system']['developerspew'])) {
1278
		$mt = microtime();
1279
		echo "system_set_harddisk_standby() being called $mt\n";
1280
	}
1281

    
1282
	if (isset($config['system']['harddiskstandby'])) {
1283
		if ($g['booting']) {
1284
			echo 'Setting hard disk standby... ';
1285
		}
1286

    
1287
		$standby = $config['system']['harddiskstandby'];
1288
		// Check for a numeric value
1289
		if (is_numeric($standby)) {
1290
			// Sync the disk(s)
1291
			mwexec('/bin/sync');
1292
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1293
				// Reinitialize ATA-drives
1294
				mwexec('/usr/local/sbin/atareinit');
1295
				if ($g['booting']) {
1296
					echo "done.\n";
1297
				}
1298
			} else if ($g['booting']) {
1299
				echo "failed!\n";
1300
			}
1301
		} else if ($g['booting']) {
1302
			echo "failed!\n";
1303
		}
1304
	}
1305
}
1306

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

    
1314
	activate_sysctls();	
1315

    
1316
	if (isset($config['system']['sharednet'])) {
1317
		system_disable_arp_wrong_if();
1318
	}
1319
}
1320

    
1321
function system_disable_arp_wrong_if() {
1322
	global $config;
1323
	if(isset($config['system']['developerspew'])) {
1324
		$mt = microtime();
1325
		echo "system_disable_arp_wrong_if() being called $mt\n";
1326
	}
1327
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1328
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1329
}
1330

    
1331
function system_enable_arp_wrong_if() {
1332
	global $config;
1333
	if(isset($config['system']['developerspew'])) {
1334
		$mt = microtime();
1335
		echo "system_enable_arp_wrong_if() being called $mt\n";
1336
	}
1337
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1338
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1339
}
1340

    
1341
function enable_watchdog() {
1342
	global $config;
1343
	return;
1344
	$install_watchdog = false;
1345
	$supported_watchdogs = array("Geode");
1346
	$file = file_get_contents("/var/log/dmesg.boot");
1347
	foreach($supported_watchdogs as $sd) {
1348
		if(stristr($file, "Geode")) {
1349
			$install_watchdog = true;
1350
		}
1351
	}
1352
	if($install_watchdog == true) {
1353
		if(is_process_running("watchdogd"))
1354
			mwexec("/usr/bin/killall watchdogd", true);
1355
		exec("/usr/sbin/watchdogd");
1356
	}
1357
}
1358

    
1359
?>
(39-39/50)