Project

General

Profile

Download (39.4 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]}", true);
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
					/* This handles the case where a dynamic gateway is choosen as default. */
318
					if (!is_ipaddr($gatewayip))
319
						$gatewayip = get_interface_gateway($interfacegw);
320
					break;
321
				}
322
			}
323
			if(($interfacegw <> "bgpd") && (is_ipaddr($gatewayip))) {
324
				preg_match("/default[ ]+([0-9].*?)[ ]+/i", $route_str, $elements);
325
				if(trim($elements[1]) != "$gatewayip") {
326
					mwexec("/sbin/route delete default " . escapeshellarg($gatewayip), false);
327
				}
328
				mwexec("/sbin/route add default " . escapeshellarg($gatewayip), true);
329
			}
330
		} else {
331
			log_error("SYSTEM: We do not have a gateways array in our XML. Is this configuration damaged?");
332
			/* adding gateway for 1.2-style configs without the new
333
			  gateway setup configured.
334
			  Force WAN to be default gateway because that is the
335
			  1.2 behavior.
336
			*/
337
			if (is_ipaddr($config['interfaces']['wan']['gateway'])) {
338
				$gatewayip = $config['interfaces']['wan']['gateway'];
339
				mwexec("/sbin/route add default " . escapeshellarg($gatewayip), true);
340
			}
341
		}
342
	}
343

    
344
	if (is_array($config['staticroutes']['route'])) {
345

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

    
352
		foreach ($config['staticroutes']['route'] as $rtent) {
353
			unset($gatewayip);
354
			unset($interfacegw);
355
			if(is_array($config['gateways']['gateway_item'])) {
356
				foreach($config['gateways']['gateway_item'] as $gateway) {
357
					if($rtent['gateway'] == $gateway['name']) {
358
						$gatewayip = $gateway['gateway'];
359
						$interfacegw = $gateway['interface'];
360
						/* This handles the case where a dynamic gateway is choosen. */
361
                                        	if (!is_ipaddr($gatewayip))
362
                                                	$gatewayip = get_interface_gateway($interfacegw);
363
						break;
364
					}
365
				}
366
			}
367
			if((is_ipaddr($rtent['gateway'])) && empty($gatewayip))  {
368
				$gatewayip = $rtent['gateway'];
369
				$interfacegw = $rtent['interface'];
370
			}
371
			if((isset($rtent['interfacegateway'])) && (! is_ipaddr($gatewayip))) {
372
				mwexec("/sbin/route add " . escapeshellarg($rtent['network']) .
373
					" -iface " . escapeshellarg(convert_friendly_interface_to_real_interface_name($interfacegw)));
374
			} else {
375
				mwexec("/sbin/route add " . escapeshellarg($rtent['network']) .
376
					" " . escapeshellarg($gatewayip));
377
			}
378
			/* record route so it can be easily removed later (if necessary) */
379
			fwrite($fd, $rtent['network'] . "\n");
380
		}
381
		fclose($fd);
382
	}
383

    
384
	return 0;
385
}
386

    
387

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

    
395
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
396
}
397

    
398
function system_syslogd_start() {
399
	global $config, $g;
400
	if(isset($config['system']['developerspew'])) {
401
		$mt = microtime();
402
		echo "system_syslogd_start() being called $mt\n";
403
	}
404

    
405
	$syslogcfg = $config['syslog'];
406

    
407
	if ($g['booting'])
408
		echo "Starting syslog...";
409
	else
410
		killbypid("{$g['varrun_path']}/syslog.pid");
411

    
412
	if(is_process_running("syslogd"))
413
		mwexec("/usr/bin/killall -9 syslogd");
414
	if(is_process_running("fifolog_writer"))
415
		mwexec("/usr/bin/killall -9 fifolog_writer");
416
	
417
	// Define carious commands for logging
418
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
419
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
420
	$clog_create = "/usr/sbin/clog -i -s ";
421
	$clog_log = "%";
422

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

    
499
EOD;
500
		if (isset($syslogcfg['filter'])) {
501
			if($syslogcfg['remoteserver'])
502
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver']}\n";
503
			if($syslogcfg['remoteserver2'])
504
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver2']}\n";
505
			if($syslogcfg['remoteserver3'])
506
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver3']}\n";
507

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

    
542
EOD;
543

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

    
553
EOD;
554

    
555
		if (isset($syslogcfg['system'])) {
556
			if($syslogcfg['remoteserver3'])
557
				$syslogconf .= <<<EOD
558
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver3']}
559
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver3']}
560
security.*										 @{$syslogcfg['remoteserver3']}
561
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver3']}
562
*.emerg											 @{$syslogcfg['remoteserver3']}
563

    
564
EOD;
565

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

    
572
EOD;
573

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

    
579
EOD;
580

    
581
}
582
			if($syslogcfg['remoteserver3'])
583
				$syslogconf .= <<<EOD
584
*.*								@{$syslogcfg['remoteserver3']}
585

    
586
EOD;
587

    
588
}
589
		fwrite($fd, $syslogconf);
590
		fclose($fd);
591
		// Are we logging to a least one remote server ?
592
		if(strpos($syslogconf, "@") != false)
593
			$retval = system("/usr/sbin/syslogd -c -f {$g['varetc_path']}/syslog.conf");
594
		else
595
			$retval = system("/usr/sbin/syslogd -c -f {$g['varetc_path']}/syslog.conf");
596

    
597
	} else {
598
		$retval = mwexec("/usr/sbin/syslogd -c");
599
	}
600

    
601
	if ($g['booting'])
602
		echo "done.\n";
603

    
604
	return $retval;
605
}
606

    
607
function system_pccard_start() {
608
	global $config, $g;
609
	if(isset($config['system']['developerspew'])) {
610
		$mt = microtime();
611
		echo "system_pccard_start() being called $mt\n";
612
	}
613

    
614
	if ($g['booting'])
615
		echo "Initializing PCMCIA...";
616

    
617
	/* kill any running pccardd */
618
	killbypid("{$g['varrun_path']}/pccardd.pid");
619

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

    
623
	if ($g['booting']) {
624
		if ($res == 0)
625
			echo "done.\n";
626
		else
627
			echo "failed!\n";
628
	}
629

    
630
	return $res;
631
}
632

    
633

    
634
function system_webgui_start() {
635
	global $config, $g;
636

    
637
	if ($g['booting'])
638
		echo "Starting webConfigurator...";
639

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

    
643
	sleep(1);
644

    
645
	chdir($g['www_path']);
646

    
647
	/* defaults */
648
	$portarg = "80";
649
	$crt = "";
650
	$key = "";
651
	$ca = "";
652

    
653
	/* non-standard port? */
654
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
655
		$portarg = "{$config['system']['webgui']['port']}";
656

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

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

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

    
700
	/* fetch page to preload apc cache */
701
	$proto = "http";
702
	if ($config['system']['webgui']['protocol'])
703
		$proto = $config['system']['webgui']['protocol'];
704
	mwexec_bg("/usr/bin/fetch -o /dev/null -q {$proto}://localhost:{$portarg}/preload.php");
705

    
706
	if ($g['booting']) {
707
		if ($res == 0)
708
			echo "done.\n";
709
		else
710
			echo "failed!\n";
711
	}
712

    
713
	return $res;
714
}
715

    
716
function system_generate_lighty_config($filename,
717
	$cert,
718
	$key,
719
	$ca,
720
	$pid_file,
721
	$port = 80,
722
	$document_root = "/usr/local/www/",
723
	$cert_location = "cert.pem",
724
	$ca_location = "ca.pem",
725
	$max_procs = 2,
726
	$max_requests = "1",
727
	$fast_cgi_enable = true,
728
	$captive_portal = false) {
729

    
730
	global $config, $g;
731

    
732
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
733
		mkdir("{$g['tmp_path']}/lighttpdcompress");
734

    
735
	if(isset($config['system']['developerspew'])) {
736
		$mt = microtime();
737
		echo "system_generate_lighty_config() being called $mt\n";
738
	}
739

    
740
	if($captive_portal == true)  {
741
		$captiveportal = ",\"mod_rewrite\"";
742
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?redirurl=$1\" )\n";
743
		$captive_portal_module = "\"mod_accesslog\", ";
744
		$maxprocperip = $config['captiveportal']['maxprocperip'];
745
		if(!$maxprocperip and $maxprocperip > 0)
746
			$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
747
		else
748
			$captive_portal_mod_evasive = "";
749
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
750
		exec("mkdir -p {$g['tmp_path']}/captiveportal");
751
		exec("chmod a-w {$g['tmp_path']}/captiveportal");
752
		$server_max_request_size = "server.max-request-size    = 384";
753
	} else {
754
		$captiveportal = "";
755
		$captive_portal_rewrite = "";
756
		$captive_portal_module = "";
757
		$captive_portal_mod_evasive = "";
758
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
759
		$server_max_request_size = "server.max-request-size    = 2097152";
760
	}
761
	
762
	if($port <> "")
763
		$lighty_port = $port;
764
	else
765
		$lighty_port = "80";
766

    
767
	$memory = get_memory();
768
	$avail = $memory[0];
769

    
770
	if($avail > 0 and $avail < 65) {
771
		$fast_cgi_enable = false;
772
	}
773

    
774
	if($avail > 65 and $avail < 98) {
775
		$max_procs = 1;
776
	}
777

    
778
	if($avail > 97 and $avail < 128) {
779
		$max_procs = 2;
780
	}
781

    
782
	if($avail > 127 and $avail < 256) {
783
		$max_procs = 3;
784
	}
785

    
786
	if($avail > 255 and $avail < 384) {
787
		$max_procs = 4;
788
	}
789

    
790
	if($avail > 383) {
791
		$max_procs = 5;
792
	}
793

    
794
	if($captive_portal == true)  {	
795
		$bin_environment =  <<<EOC
796
        "bin-environment" => (
797
           "PHP_FCGI_CHILDREN" => "$max_procs",
798
           "PHP_FCGI_MAX_REQUESTS" => "500"
799
        ), 
800
EOC;
801

    
802
	} else if ($avail > 0 and $avail < 128) {
803
		$bin_environment = <<<EOC
804
		"bin-environment" => (
805
			"PHP_FCGI_CHILDREN" => "$max_procs",
806
			"PHP_FCGI_MAX_REQUESTS" => "2",
807
	),
808

    
809
EOC;
810
	} else
811
		$bin_environment =  <<<EOC
812
        "bin-environment" => (
813
           "PHP_FCGI_CHILDREN" => "$max_procs",
814
           "PHP_FCGI_MAX_REQUESTS" => "500"
815
        ), 
816
EOC;
817

    
818
	if($fast_cgi_enable == true) {
819
		$module = "\"mod_fastcgi\", \"mod_cgi\"";
820
		$cgi_config = "";
821
		$fastcgi_config = <<<EOD
822
#### fastcgi module
823
## read fastcgi.txt for more info
824
fastcgi.server = ( ".php" =>
825
	( "localhost" =>
826
		(
827
			"socket" => "{$g['tmp_path']}/php-fastcgi.socket",
828
			"min-procs" => 0,
829
			"max-procs" => {$max_procs},
830
			{$bin_environment}			
831
			"bin-path" => "/usr/local/bin/php"
832
		)
833
	)
834
)
835

    
836
#### CGI module
837
cgi.assign                 = ( ".cgi" => "" )
838

    
839
EOD;
840
	} else {
841
		$fastcgi_config = "";
842
		$module = "\"mod_cgi\"";
843
		$cgi_config = <<<EOD
844
#### CGI module
845
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
846
                               ".cgi" => "" )
847

    
848
EOD;
849
	}
850

    
851
	$lighty_config = "";
852
	$lighty_config .= <<<EOD
853
#
854
# lighttpd configuration file
855
#
856
# use a it as base for lighttpd 1.0.0 and above
857
#
858
############ Options you really have to take care of ####################
859

    
860
## FreeBSD!
861
server.event-handler	= "freebsd-kqueue"
862
server.network-backend 	= "writev"
863

    
864
## modules to load
865
server.modules              =   (
866
									{$captive_portal_module}
867
									"mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect",
868
									{$module}{$captiveportal}
869
								)
870

    
871
## Unused modules
872
#                               "mod_setenv",
873
#                               "mod_rewrite",
874
#                               "mod_ssi",
875
#                               "mod_usertrack",
876
#                               "mod_expire",
877
#                               "mod_secdownload",
878
#                               "mod_rrdtool",
879
#                               "mod_auth",
880
#                               "mod_status",
881
#                               "mod_alias",
882
#                               "mod_proxy",
883
#                               "mod_simple_vhost",
884
#                               "mod_evhost",
885
#                               "mod_userdir",
886
#                               "mod_cgi",
887

    
888
server.max-keep-alive-requests = 15
889
server.max-keep-alive-idle = 30
890

    
891
## a static document-root, for virtual-hosting take look at the
892
## server.virtual-* options
893
server.document-root        = "{$document_root}"
894
{$captive_portal_rewrite}
895

    
896
# Maximum idle time with nothing being written (php downloading)
897
server.max-write-idle = 999
898

    
899
## where to send error-messages to
900
server.errorlog             = "/var/log/lighttpd.error.log"
901

    
902
# files to check for if .../ is requested
903
server.indexfiles           = ( "index.php", "index.html",
904
                                "index.htm", "default.htm" )
905

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

    
959
# Use the "Content-Type" extended attribute to obtain mime type if possible
960
#mimetypes.use-xattr        = "enable"
961

    
962
#### accesslog module
963
#accesslog.filename          = "/dev/null"
964

    
965
## deny access the file-extensions
966
#
967
# ~    is for backupfiles from vi, emacs, joe, ...
968
# .inc is often used for code includes which should in general not be part
969
#      of the document-root
970
url.access-deny             = ( "~", ".inc" )
971

    
972

    
973
######### Options that are good to be but not neccesary to be changed #######
974

    
975
## bind to port (default: 80)
976
server.port                = {$lighty_port}
977

    
978
## error-handler for status 404
979
#server.error-handler-404   = "/error-handler.html"
980
#server.error-handler-404   = "/error-handler.php"
981

    
982
## to help the rc.scripts
983
server.pid-file            = "/var/run/{$pid_file}"
984

    
985
## virtual directory listings
986
server.dir-listing         = "disable"
987

    
988
## enable debugging
989
debug.log-request-header   = "disable"
990
debug.log-response-header  = "disable"
991
debug.log-request-handling = "disable"
992
debug.log-file-not-found   = "disable"
993

    
994
# gzip compression
995
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
996
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
997

    
998
{$server_upload_dirs}
999

    
1000
{$server_max_request_size}
1001

    
1002
{$fastcgi_config}
1003

    
1004
{$cgi_config}
1005

    
1006
{$captive_portal_mod_evasive}
1007

    
1008
expire.url = (
1009
				"" => "access 50 hours",	
1010
        )
1011

    
1012
EOD;
1013

    
1014
	$cert = str_replace("\r", "", $cert);
1015
	$key = str_replace("\r", "", $key);
1016
	$ca = str_replace("\r", "", $ca);
1017

    
1018
	$cert = str_replace("\n\n", "\n", $cert);
1019
	$key = str_replace("\n\n", "\n", $key);
1020
	$ca = str_replace("\n\n", "\n", $ca);
1021

    
1022
	if($cert <> "" and $key <> "") {
1023
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1024
		if (!$fd) {
1025
			printf("Error: cannot open cert.pem in system_webgui_start().\n");
1026
			return 1;
1027
		}
1028
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1029
		fwrite($fd, $cert);
1030
		fwrite($fd, "\n");
1031
		fwrite($fd, $key);
1032
		fclose($fd);
1033
		if($ca <> "") {
1034
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1035
			if (!$fd) {
1036
				printf("Error: cannot open ca.pem in system_webgui_start().\n");
1037
				return 1;
1038
			}
1039
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1040
			fwrite($fd, $ca);
1041
			fclose($fd);
1042
		}
1043
		$lighty_config .= "\n";
1044
		$lighty_config .= "## ssl configuration\n";
1045
		$lighty_config .= "ssl.engine = \"enable\"\n";
1046
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1047
		if($ca <> "")
1048
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1049
	}
1050

    
1051
	// Add HTTP to HTTPS redirect	
1052
	if ($captive_portal == false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1053
		if($lighty_port != "443") 
1054
			$redirectport = ":{$lighty_port}";
1055
		$lighty_config .= <<<EOD
1056
\$SERVER["socket"] == ":80" {
1057
	\$HTTP["host"] =~ "(.*)" {
1058
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1059
	}
1060
}
1061
EOD;
1062
	}
1063

    
1064
	$fd = fopen("{$filename}", "w");
1065
	if (!$fd) {
1066
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
1067
		return 1;
1068
	}
1069
	fwrite($fd, $lighty_config);
1070
	fclose($fd);
1071

    
1072
	return 0;
1073

    
1074
}
1075

    
1076
function system_timezone_configure() {
1077
	global $config, $g;
1078
	if(isset($config['system']['developerspew'])) {
1079
		$mt = microtime();
1080
		echo "system_timezone_configure() being called $mt\n";
1081
	}
1082

    
1083
	$syscfg = $config['system'];
1084

    
1085
	if ($g['booting'])
1086
		echo "Setting timezone...";
1087

    
1088
	/* extract appropriate timezone file */
1089
	$timezone = $syscfg['timezone'];
1090
	if (!$timezone)
1091
		$timezone = "Etc/UTC";
1092

    
1093
	conf_mount_rw();
1094

    
1095
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1096
		escapeshellarg($timezone) . " > /etc/localtime");
1097

    
1098
	mwexec("sync");
1099
	conf_mount_ro();
1100

    
1101
	if ($g['booting'])
1102
		echo "done.\n";
1103
}
1104

    
1105
function system_ntp_configure() {
1106
	global $config, $g;
1107

    
1108
	$syscfg = $config['system'];
1109

    
1110
	/* open configuration for wrting or bail */
1111
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1112
	if(!$fd) {
1113
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1114
		return;
1115
	}
1116

    
1117
	fwrite($fd, "# \n");
1118
	fwrite($fd, "# pfSense OpenNTPD configuration file \n");
1119
	fwrite($fd, "# \n\n");
1120

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

    
1125
	/* Setup listener(s) if the user has configured one */
1126
        if ($config['installedpackages']['openntpd']) {
1127
    		/* server config is in coregui1 */
1128
		$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
1129
		if ($xmlsettings['enable'] == 'on') {
1130
			$ifaces = explode(',', $xmlsettings['interface']);
1131
			$ifaces = array_map('get_real_interface', $ifaces);
1132
			$ifaces = array_filter($ifaces, 'does_interface_exist');
1133
			$ips = array_map('find_interface_ip', $ifaces);
1134
			foreach ($ips as $ip) {
1135
				if (is_ipaddr($ip))
1136
					fwrite($fd, "listen on $ip\n");
1137
			}
1138
		}
1139
	}
1140

    
1141
	fwrite($fd, "\n");
1142

    
1143
	/* slurp! */
1144
	fclose($fd);
1145

    
1146
	/* if openntpd is running, kill it */
1147
	while(is_process_running("ntpd")) {
1148
		mwexec("/usr/bin/killall ntpd", true);
1149
	}
1150

    
1151
	/* if /var/empty does not exist, create it */
1152
	if(!is_dir("/var/empty"))
1153
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1154

    
1155
	if($g['booting'])
1156
		return;
1157
	
1158
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1159
	exec("/usr/local/sbin/ntpd -s -f {$g['varetc_path']}/ntpd.conf");
1160
	
1161
	// Note that we are starting up
1162
	exec("echo 'OpenNTPD is starting up' >> {$g['varlog_path']}/ntpd.log");
1163

    
1164
}
1165

    
1166
function sync_system_time() {
1167
	global $config, $g;
1168

    
1169
	$syscfg = $config['system'];
1170

    
1171
	if ($g['booting'])
1172
		echo "Syncing system time before startup...";
1173

    
1174
	/* foreach through servers and write out to ntpd.conf */
1175
	foreach (explode(' ', $syscfg['timeservers']) as $ts) {
1176
		mwexec("/usr/sbin/ntpdate -s $ts");
1177
	}
1178
	
1179
	if ($g['booting'])
1180
		echo "done.\n";
1181
	
1182
}
1183

    
1184
function system_halt() {
1185
	global $g;
1186

    
1187
	system_reboot_cleanup();
1188

    
1189
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1190
}
1191

    
1192
function system_reboot() {
1193
	global $g;
1194

    
1195
	system_reboot_cleanup();
1196

    
1197
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1198
}
1199

    
1200
function system_reboot_sync() {
1201
	global $g;
1202

    
1203
	system_reboot_cleanup();
1204

    
1205
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1206
}
1207

    
1208
function system_reboot_cleanup() {
1209
	mwexec("/usr/local/bin/beep.sh stop");
1210
	require_once("captiveportal.inc");
1211
	captiveportal_radius_stop_all();
1212
	require_once("voucher.inc");
1213
	voucher_save_db_to_config();
1214
}
1215

    
1216
function system_do_shell_commands($early = 0) {
1217
	global $config, $g;
1218
	if(isset($config['system']['developerspew'])) {
1219
		$mt = microtime();
1220
		echo "system_do_shell_commands() being called $mt\n";
1221
	}
1222

    
1223
	if ($early)
1224
		$cmdn = "earlyshellcmd";
1225
	else
1226
		$cmdn = "shellcmd";
1227

    
1228
	if (is_array($config['system'][$cmdn])) {
1229

    
1230
		/* *cmd is an array, loop through */
1231
		foreach ($config['system'][$cmdn] as $cmd) {
1232
			exec($cmd);
1233
		}
1234

    
1235
	} elseif($config['system'][$cmdn] <> "") {
1236

    
1237
		/* execute single item */
1238
		exec($config['system'][$cmdn]);
1239

    
1240
	}
1241
}
1242

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

    
1250
	if (isset($config['system']['disableconsolemenu'])) {
1251
		touch("{$g['varetc_path']}/disableconsole");
1252
	} else {
1253
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1254
	}
1255
}
1256

    
1257
function system_dmesg_save() {
1258
	global $g;
1259
	if(isset($config['system']['developerspew'])) {
1260
		$mt = microtime();
1261
		echo "system_dmesg_save() being called $mt\n";
1262
	}
1263

    
1264
	$dmesg = "";
1265
	exec("/sbin/dmesg", $dmesg);
1266

    
1267
	/* find last copyright line (output from previous boots may be present) */
1268
	$lastcpline = 0;
1269

    
1270
	for ($i = 0; $i < count($dmesg); $i++) {
1271
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1272
			$lastcpline = $i;
1273
	}
1274

    
1275
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1276
	if (!$fd) {
1277
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1278
		return 1;
1279
	}
1280

    
1281
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1282
		fwrite($fd, $dmesg[$i] . "\n");
1283

    
1284
	fclose($fd);
1285

    
1286
	return 0;
1287
}
1288

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

    
1296
	if (isset($config['system']['harddiskstandby'])) {
1297
		if ($g['booting']) {
1298
			echo 'Setting hard disk standby... ';
1299
		}
1300

    
1301
		$standby = $config['system']['harddiskstandby'];
1302
		// Check for a numeric value
1303
		if (is_numeric($standby)) {
1304
			// Sync the disk(s)
1305
			mwexec('/bin/sync');
1306
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1307
				// Reinitialize ATA-drives
1308
				mwexec('/usr/local/sbin/atareinit');
1309
				if ($g['booting']) {
1310
					echo "done.\n";
1311
				}
1312
			} else if ($g['booting']) {
1313
				echo "failed!\n";
1314
			}
1315
		} else if ($g['booting']) {
1316
			echo "failed!\n";
1317
		}
1318
	}
1319
}
1320

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

    
1328
	activate_sysctls();	
1329

    
1330
	if (isset($config['system']['sharednet'])) {
1331
		system_disable_arp_wrong_if();
1332
	}
1333
}
1334

    
1335
function system_disable_arp_wrong_if() {
1336
	global $config;
1337
	if(isset($config['system']['developerspew'])) {
1338
		$mt = microtime();
1339
		echo "system_disable_arp_wrong_if() being called $mt\n";
1340
	}
1341
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1342
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1343
}
1344

    
1345
function system_enable_arp_wrong_if() {
1346
	global $config;
1347
	if(isset($config['system']['developerspew'])) {
1348
		$mt = microtime();
1349
		echo "system_enable_arp_wrong_if() being called $mt\n";
1350
	}
1351
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1352
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1353
}
1354

    
1355
function enable_watchdog() {
1356
	global $config;
1357
	return;
1358
	$install_watchdog = false;
1359
	$supported_watchdogs = array("Geode");
1360
	$file = file_get_contents("/var/log/dmesg.boot");
1361
	foreach($supported_watchdogs as $sd) {
1362
		if(stristr($file, "Geode")) {
1363
			$install_watchdog = true;
1364
		}
1365
	}
1366
	if($install_watchdog == true) {
1367
		if(is_process_running("watchdogd"))
1368
			mwexec("/usr/bin/killall watchdogd", true);
1369
		exec("/usr/sbin/watchdogd");
1370
	}
1371
}
1372
?>
(39-39/50)