Project

General

Profile

Download (39.2 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", `/bin/cat /var/etc/nameserver_* 2>/dev/null`);
153
	if (is_array($dns_lists)) {
154
		foreach($dns_lists as $dns) {
155
			if(is_ipaddr($dns)) 
156
				$master_list[] = $dns;
157
		}
158
	}
159

    
160
	// Read in any extra nameservers
161
	if(file_exists("/var/etc/nameservers.conf")) {
162
		$dns_lists = split("\n", `/bin/cat /var/etc/nameservers.conf`);
163
		if(is_array($dns_s))
164
			foreach($dns_s as $dns)
165
				if (is_ipaddr($dns))
166
					$master_list[] = $dns;
167
	}
168

    
169
	return $master_list;
170
}
171

    
172
function system_hosts_generate() {
173
	global $config, $g;
174
	if(isset($config['system']['developerspew'])) {
175
		$mt = microtime();
176
		echo "system_hosts_generate() being called $mt\n";
177
	}
178

    
179
	$syscfg = $config['system'];
180
	$dnsmasqcfg = $config['dnsmasq'];
181

    
182
	if (!is_array($dnsmasqcfg['hosts'])) {
183
		$dnsmasqcfg['hosts'] = array();
184
	}
185
	$hostscfg = $dnsmasqcfg['hosts'];
186

    
187
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
188
	if (!$fd) {
189
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
190
		return 1;
191
	}
192

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

    
195
	if ($config['interfaces']['lan']) {
196
		$cfgip = get_interface_ip("lan");
197
		if (is_ipaddr($cfgip))
198
			$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
199
	} else {
200
		$sysiflist = get_configured_interface_list();
201
		foreach ($sysiflist as $sysif) {
202
			if (!interface_has_gateway($sysif)) {
203
				$cfgip = get_interface_ip($sysif);
204
				if (is_ipaddr($cfgip)) {
205
					$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
206
					break;
207
				}
208
			}
209
		}
210
	}
211

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

    
228
	return 0;
229
}
230

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

    
238
	$syscfg = $config['system'];
239

    
240
	/* set hostname */
241
	$status = mwexec("/bin/hostname " .
242
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
243

    
244
    /* Setup host GUID ID.  This is used by ZFS. */
245
	mwexec("/etc/rc.d/hostid start");
246

    
247
	return $status;
248
}
249

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

    
257
	/* Enable fast routing, if enabled */
258
	/* XXX: More checks need to be done for subsystems that are not compatibel with fast routing. */
259
	if(isset($config['staticroutes']['enablefastrouting']) && !isset($config['ipsec']['enable']))
260
		mwexec("/sbin/sysctl net.inet.ip.fastforwarding=1");
261

    
262
	$gatewayip = "";
263
	$interfacegw = "";
264
	/* tack on all the hard defined gateways as well */
265
	if (is_array($config['gateways']['gateway_item'])) {
266
		foreach	($config['gateways']['gateway_item'] as $gateway) {
267
			if (isset($gateway['defaultgw'])) {
268
				if ($gateway['gateway'] == "dynamic")
269
					$gateway['gateway'] = get_interface_gateway($gateway['interface']);
270
				$gatewayip = $gateway['gateway'];
271
				$interfacegw = $gateway['interface'];
272
				break;
273
			}
274
		}
275
	}
276
	$dont_add_route = false;
277
	/* if OLSRD is enabled, allow WAN to house DHCP. */
278
	if($config['installedpackages']['olsrd']) {
279
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
280
			if($olsrd['enabledyngw'] == "on") {
281
				$dont_add_route = true;
282
				break;
283
			}
284
		}
285
	}
286
	/* Create a array from the existing route table */
287
	exec("/usr/bin/netstat -rnf inet", $route_str);
288
	array_shift($route_str);
289
	array_shift($route_str);
290
	array_shift($route_str);
291
	array_shift($route_str);
292
	$i = 0;
293
	$route_arr = array();
294
	foreach($route_str as $routeline) {
295
		$items = preg_split("/[ ]+/i", $routeline);
296
		$route_arr[$i] = array($items[0], $items[1], $items[5]);
297
		$i++;
298
	}
299

    
300
	if($dont_add_route == false) {
301
		if (($interfacegw <> "bgpd") && (is_ipaddr($gatewayip))) {
302
			$route_count = 0;
303
			foreach($route_arr as $route_item) {
304
				if($route_item[0] == "default") {
305
					$route_count = 1;
306
					continue;
307
				}
308
			}
309
			if($route_count == 0) {
310
				$action = "add";
311
			} else {
312
				$action = "change";
313
			}
314
			log_error("$action default route to $gatewayip");
315
			mwexec("/sbin/route {$action} default " . escapeshellarg($gatewayip));
316
		} else {
317
			/* Adding gateway for 1.2-style configs without the new
318
		  	 * gateway setup configured.
319
		  	 * Force WAN to be default gateway because that is the 1.2 behavior.
320
			 */
321
			log_error("WARNING: There is no default gateway in the configuration.");
322
			if (is_ipaddr($config['interfaces']['wan']['gateway'])) {
323
				$gatewayip = $config['interfaces']['wan']['gateway'];
324
				mwexec("/sbin/route add default " . escapeshellarg($gatewayip), true);
325
			}
326
		}
327
	}
328

    
329
	if (is_array($config['staticroutes']['route'])) {
330
		$route_str = array();
331
		exec("/usr/bin/netstat -rnf inet | /usr/bin/cut -d \" \" -f 1", $route_str);
332
		$route_str = array_flip($route_str);
333
		$gateways_arr = return_gateways_array();
334

    
335
		foreach ($config['staticroutes']['route'] as $rtent) {
336
			$gatewayip = "";
337
			if (isset($gateways_arr[$rtent['gateway']])) {
338
				$gatewayip = $gateways_arr[$rtent['gateway']]['gateway'];
339
				$interfacegw = get_real_interface($rtent['interface']);
340
			} else if (is_ipaddr($rtent['gateway'])) {
341
				$gatewayip = $rtent['gateway'];
342
			} else {
343
				log_error("Static Routes: Gateway IP could not be found for {$rtent['network']}");
344
				continue;
345
			}
346

    
347
			$action = "add";
348
			if (isset($route_str[$rtent['network']]))
349
				$action = "change";
350

    
351
			if (is_ipaddr($gatewayip)) {
352
				mwexec("/sbin/route {$action} " . escapeshellarg($rtent['network']) .
353
					" " . escapeshellarg($gatewayip));
354
			} else if (!empty($interfacegw)) {
355
				mwexec("/sbin/route {$action} " . escapeshellarg($rtent['network']) .
356
					" -iface " . escapeshellarg($interfacegw));
357
			}
358
		}
359
	}
360

    
361
	return 0;
362
}
363

    
364
function system_routing_enable() {
365
	global $config, $g;
366
	if(isset($config['system']['developerspew'])) {
367
		$mt = microtime();
368
		echo "system_routing_enable() being called $mt\n";
369
	}
370

    
371
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
372
}
373

    
374
function system_syslogd_start() {
375
	global $config, $g;
376
	if(isset($config['system']['developerspew'])) {
377
		$mt = microtime();
378
		echo "system_syslogd_start() being called $mt\n";
379
	}
380

    
381
	$syslogcfg = $config['syslog'];
382

    
383
	if ($g['booting'])
384
		echo "Starting syslog...";
385
	else
386
		killbypid("{$g['varrun_path']}/syslog.pid");
387

    
388
	if(is_process_running("syslogd"))
389
		mwexec("/usr/bin/killall -9 syslogd");
390
	if(is_process_running("fifolog_writer"))
391
		mwexec("/usr/bin/killall -9 fifolog_writer");
392
	
393
	// Define carious commands for logging
394
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
395
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
396
	$clog_create = "/usr/sbin/clog -i -s ";
397
	$clog_log = "%";
398

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

    
484
EOD;
485
		if (isset($syslogcfg['filter'])) {
486
			if($syslogcfg['remoteserver'])
487
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver']}\n";
488
			if($syslogcfg['remoteserver2'])
489
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver2']}\n";
490
			if($syslogcfg['remoteserver3'])
491
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver3']}\n";
492

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

    
527
EOD;
528

    
529
		if (isset($syslogcfg['system'])) {
530
			if($syslogcfg['remoteserver2'])
531
				$syslogconf .= <<<EOD
532
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver2']}
533
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver2']}
534
security.*										 @{$syslogcfg['remoteserver2']}
535
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver2']}
536
*.emerg											 @{$syslogcfg['remoteserver2']}
537

    
538
EOD;
539

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

    
549
EOD;
550

    
551
}
552
		if (isset($syslogcfg['logall'])) {
553
			if($syslogcfg['remoteserver'])
554
				$syslogconf .= <<<EOD
555
*.*								@{$syslogcfg['remoteserver']}
556

    
557
EOD;
558

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

    
564
EOD;
565

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

    
571
EOD;
572

    
573
}
574
		fwrite($fd, $syslogconf);
575
		fclose($fd);
576
		// Are we logging to a least one remote server ?
577
		if(strpos($syslogconf, "@") != false)
578
			$retval = system("/usr/sbin/syslogd -c -f {$g['varetc_path']}/syslog.conf");
579
		else
580
			$retval = system("/usr/sbin/syslogd -c -f {$g['varetc_path']}/syslog.conf");
581

    
582
	} else {
583
		$retval = mwexec("/usr/sbin/syslogd -c");
584
	}
585

    
586
	if ($g['booting'])
587
		echo "done.\n";
588

    
589
	return $retval;
590
}
591

    
592
function system_pccard_start() {
593
	global $config, $g;
594
	if(isset($config['system']['developerspew'])) {
595
		$mt = microtime();
596
		echo "system_pccard_start() being called $mt\n";
597
	}
598

    
599
	if ($g['booting'])
600
		echo "Initializing PCMCIA...";
601

    
602
	/* kill any running pccardd */
603
	killbypid("{$g['varrun_path']}/pccardd.pid");
604

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

    
608
	if ($g['booting']) {
609
		if ($res == 0)
610
			echo "done.\n";
611
		else
612
			echo "failed!\n";
613
	}
614

    
615
	return $res;
616
}
617

    
618

    
619
function system_webgui_start() {
620
	global $config, $g;
621

    
622
	if ($g['booting'])
623
		echo "Starting webConfigurator...";
624

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

    
628
	sleep(1);
629

    
630
	chdir($g['www_path']);
631

    
632
	/* defaults */
633
	$portarg = "80";
634
	$crt = "";
635
	$key = "";
636
	$ca = "";
637

    
638
	/* non-standard port? */
639
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
640
		$portarg = "{$config['system']['webgui']['port']}";
641

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

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

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

    
685
	/* fetch page to preload apc cache */
686
	$proto = "http";
687
	if ($config['system']['webgui']['protocol'])
688
		$proto = $config['system']['webgui']['protocol'];
689
	mwexec_bg("/usr/bin/fetch -o /dev/null -q {$proto}://localhost:{$portarg}/preload.php");
690

    
691
	if ($g['booting']) {
692
		if ($res == 0)
693
			echo "done.\n";
694
		else
695
			echo "failed!\n";
696
	}
697

    
698
	return $res;
699
}
700

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

    
715
	global $config, $g;
716

    
717
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
718
		mkdir("{$g['tmp_path']}/lighttpdcompress");
719

    
720
	if(isset($config['system']['developerspew'])) {
721
		$mt = microtime();
722
		echo "system_generate_lighty_config() being called $mt\n";
723
	}
724

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

    
752
	$memory = get_memory();
753
	$avail = $memory[0];
754

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

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

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

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

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

    
775
	if($avail > 383) {
776
		$max_procs = 5;
777
	}
778

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

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

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

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

    
821
#### CGI module
822
cgi.assign                 = ( ".cgi" => "" )
823

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

    
833
EOD;
834
	}
835

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

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

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

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

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

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

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

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

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

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

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

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

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

    
957

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

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

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

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

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

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

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

    
983
{$server_upload_dirs}
984

    
985
{$server_max_request_size}
986

    
987
{$fastcgi_config}
988

    
989
{$cgi_config}
990

    
991
{$captive_portal_mod_evasive}
992

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

    
997
EOD;
998

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

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

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

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

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

    
1057
	return 0;
1058

    
1059
}
1060

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

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

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

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

    
1078
	conf_mount_rw();
1079

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1149
}
1150

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

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

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

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

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

    
1172
	system_reboot_cleanup();
1173

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

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

    
1180
	system_reboot_cleanup();
1181

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

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

    
1188
	system_reboot_cleanup();
1189

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

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

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

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

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

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

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

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

    
1225
	}
1226
}
1227

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

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

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

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

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

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

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

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

    
1269
	fclose($fd);
1270

    
1271
	return 0;
1272
}
1273

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

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

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

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

    
1313
	activate_sysctls();	
1314

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

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

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

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