Project

General

Profile

Download (41.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
	$route_arr = array();
293
	foreach($route_str as $routeline) {
294
		$items = preg_split("/[ ]+/i", $routeline);
295
		$route_arr[$item[0]] = array($items[0], $items[1], $items[5]);
296
	}
297

    
298
	if ($dont_add_route == false) {
299
		if (($interfacegw <> "bgpd") && (is_ipaddr($gatewayip))) {
300
			$action = "add";
301
			if(isset($route_arr['default'])) {
302
				$action = "change";
303
			}
304
			log_error("ROUTING: $action default route to $gatewayip");
305
			mwexec("/sbin/route {$action} default " . escapeshellarg($gatewayip));
306
		} else if (is_ipaddr($config['interfaces']['wan']['gateway'])) {
307
			/* Adding gateway for 1.2-style configs without the new
308
		  	 * gateway setup configured.
309
		  	 * Force WAN to be default gateway because that is the 1.2 behavior.
310
			 */
311
			log_error("WARNING: There is no default gateway in the configuration.");
312
			$gatewayip = $config['interfaces']['wan']['gateway'];
313
			mwexec("/sbin/route add default " . escapeshellarg($gatewayip), true);
314
		}
315
	}
316

    
317
	if (is_array($config['staticroutes']['route'])) {
318
		$gateways_arr = return_gateways_array();
319

    
320
		foreach ($config['staticroutes']['route'] as $rtent) {
321
			$gatewayip = "";
322
			if (isset($gateways_arr[$rtent['gateway']])) {
323
				$gatewayip = $gateways_arr[$rtent['gateway']]['gateway'];
324
				$interfacegw = get_real_interface($rtent['interface']);
325
			} else if (is_ipaddr($rtent['gateway'])) {
326
				$gatewayip = $rtent['gateway'];
327
			} else {
328
				log_error("Static Routes: Gateway IP could not be found for {$rtent['network']}");
329
				continue;
330
			}
331

    
332
			$action = "add";
333
			if (isset($route_arr[$rtent['network']]))
334
				$action = "change";
335

    
336
			if (is_ipaddr($gatewayip)) {
337
				mwexec("/sbin/route {$action} " . escapeshellarg($rtent['network']) .
338
					" " . escapeshellarg($gatewayip));
339
			} else if (!empty($interfacegw)) {
340
				mwexec("/sbin/route {$action} " . escapeshellarg($rtent['network']) .
341
					" -iface " . escapeshellarg($interfacegw));
342
			}
343
		}
344
	}
345

    
346
	return 0;
347
}
348

    
349
function system_routing_enable() {
350
	global $config, $g;
351
	if(isset($config['system']['developerspew'])) {
352
		$mt = microtime();
353
		echo "system_routing_enable() being called $mt\n";
354
	}
355

    
356
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
357
}
358

    
359
function system_syslogd_start() {
360
	global $config, $g;
361
	if(isset($config['system']['developerspew'])) {
362
		$mt = microtime();
363
		echo "system_syslogd_start() being called $mt\n";
364
	}
365

    
366
	$syslogcfg = $config['syslog'];
367

    
368
	if ($g['booting'])
369
		echo "Starting syslog...";
370
	else
371
		killbypid("{$g['varrun_path']}/syslog.pid");
372

    
373
	if(is_process_running("syslogd"))
374
		mwexec("/usr/bin/killall -9 syslogd");
375
	if(is_process_running("fifolog_writer"))
376
		mwexec("/usr/bin/killall -9 fifolog_writer");
377
	
378
	// Define carious commands for logging
379
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
380
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
381
	$clog_create = "/usr/sbin/clog -i -s ";
382
	$clog_log = "%";
383

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

    
469
EOD;
470
		if (isset($syslogcfg['filter'])) {
471
			if($syslogcfg['remoteserver'])
472
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver']}\n";
473
			if($syslogcfg['remoteserver2'])
474
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver2']}\n";
475
			if($syslogcfg['remoteserver3'])
476
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver3']}\n";
477

    
478
		}
479
		if (isset($syslogcfg['vpn'])) {
480
			if($syslogcfg['remoteserver'])
481
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver']}\n";
482
			if($syslogcfg['remoteserver2'])
483
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver2']}\n";
484
			if($syslogcfg['remoteserver3'])
485
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver3']}\n";
486
		}
487
		if (isset($syslogcfg['portalauth'])) {
488
			if($syslogcfg['remoteserver'])
489
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver']}\n";
490
			if($syslogcfg['remoteserver2'])
491
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver2']}\n";
492
			if($syslogcfg['remoteserver3'])
493
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver3']}\n";
494
		}
495
		if (isset($syslogcfg['dhcp'])) {
496
			if($syslogcfg['remoteserver'])
497
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver']}\n";
498
			if($syslogcfg['remoteserver2'])
499
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver2']}\n";
500
			if($syslogcfg['remoteserver3'])
501
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver3']}\n";
502
		}
503
		if (isset($syslogcfg['system'])) {
504
			if($syslogcfg['remoteserver'])
505
				$syslogconf .= <<<EOD
506
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver']}
507
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver']}
508
security.*										 @{$syslogcfg['remoteserver']}
509
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver']}
510
*.emerg											 @{$syslogcfg['remoteserver']}
511

    
512
EOD;
513

    
514
		if (isset($syslogcfg['system'])) {
515
			if($syslogcfg['remoteserver2'])
516
				$syslogconf .= <<<EOD
517
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver2']}
518
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver2']}
519
security.*										 @{$syslogcfg['remoteserver2']}
520
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver2']}
521
*.emerg											 @{$syslogcfg['remoteserver2']}
522

    
523
EOD;
524

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

    
534
EOD;
535

    
536
}
537
		if (isset($syslogcfg['logall'])) {
538
			if($syslogcfg['remoteserver'])
539
				$syslogconf .= <<<EOD
540
*.*								@{$syslogcfg['remoteserver']}
541

    
542
EOD;
543

    
544
}
545
			if($syslogcfg['remoteserver2'])
546
				$syslogconf .= <<<EOD
547
*.*								@{$syslogcfg['remoteserver2']}
548

    
549
EOD;
550

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

    
556
EOD;
557

    
558
}
559
		fwrite($fd, $syslogconf);
560
		fclose($fd);
561
		// Are we logging to a least one remote server ?
562
		if(strpos($syslogconf, "@") != false)
563
			$retval = system("/usr/sbin/syslogd -c -f {$g['varetc_path']}/syslog.conf");
564
		else
565
			$retval = system("/usr/sbin/syslogd -c -f {$g['varetc_path']}/syslog.conf");
566

    
567
	} else {
568
		$retval = mwexec("/usr/sbin/syslogd -c");
569
	}
570

    
571
	if ($g['booting'])
572
		echo "done.\n";
573

    
574
	return $retval;
575
}
576

    
577
function system_pccard_start() {
578
	global $config, $g;
579
	if(isset($config['system']['developerspew'])) {
580
		$mt = microtime();
581
		echo "system_pccard_start() being called $mt\n";
582
	}
583

    
584
	if ($g['booting'])
585
		echo "Initializing PCMCIA...";
586

    
587
	/* kill any running pccardd */
588
	killbypid("{$g['varrun_path']}/pccardd.pid");
589

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

    
593
	if ($g['booting']) {
594
		if ($res == 0)
595
			echo "done.\n";
596
		else
597
			echo "failed!\n";
598
	}
599

    
600
	return $res;
601
}
602

    
603

    
604
function system_webgui_start() {
605
	global $config, $g;
606

    
607
	if ($g['booting'])
608
		echo "Starting webConfigurator...";
609

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

    
613
	sleep(1);
614

    
615
	chdir($g['www_path']);
616

    
617
	/* defaults */
618
	$portarg = "80";
619
	$crt = "";
620
	$key = "";
621
	$ca = "";
622

    
623
	/* non-standard port? */
624
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
625
		$portarg = "{$config['system']['webgui']['port']}";
626

    
627
	if ($config['system']['webgui']['protocol'] == "https") {
628
		// Ensure that we have a webConfigurator CERT
629
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
630
		if(!is_array($cert) && !$cert['crt'] && !$cert['prv']) {
631
			if (!is_array($config['system']['ca']))
632
				$config['system']['ca'] = array();
633
			$a_ca =& $config['system']['ca'];
634
			if (!is_array($config['system']['cert']))
635
				$config['system']['cert'] = array();
636
			$a_cert =& $config['system']['cert'];
637
			echo "Creating SSL Certificate... ";
638
			$cert = array();
639
			$cert['refid'] = uniqid();
640
			$cert['name'] = "webConfigurator default";
641
			mwexec("/usr/bin/openssl genrsa 1024 > {$g['tmp_path']}/ssl.key");
642
			mwexec("/usr/bin/openssl req -new -x509 -nodes -sha1 -days 2000 -key {$g['tmp_path']}/ssl.key > {$g['tmp_path']}/ssl.crt");
643
			$crt = file_get_contents("{$g['tmp_path']}/ssl.crt");
644
			$key = file_get_contents("{$g['tmp_path']}/ssl.key");
645
			unlink("{$g['tmp_path']}/ssl.key");
646
			unlink("{$g['tmp_path']}/ssl.crt");
647
			cert_import($cert, $crt, $key);
648
			$a_cert[] = $cert;
649
			$config['system']['webgui']['ssl-certref'] = $cert['refid'];
650
			write_config("Importing HTTPS certificate");
651
			if(!$config['system']['webgui']['port'])
652
				$portarg = "443";
653
			$ca = ca_chain($cert);
654
		} else {
655
			$crt = base64_decode($cert['crt']);
656
			$key = base64_decode($cert['prv']);
657
			if(!$config['system']['webgui']['port'])
658
				$portarg = "443";
659
			$ca = ca_chain($cert);
660
		}
661
	}
662

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

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

    
670
	/* fetch page to preload apc cache */
671
	$proto = "http";
672
	if ($config['system']['webgui']['protocol'])
673
		$proto = $config['system']['webgui']['protocol'];
674
	mwexec_bg("/usr/bin/fetch -o /dev/null -q {$proto}://localhost:{$portarg}/preload.php");
675

    
676
	if ($g['booting']) {
677
		if ($res == 0)
678
			echo "done.\n";
679
		else
680
			echo "failed!\n";
681
	}
682

    
683
	return $res;
684
}
685

    
686
function system_generate_lighty_config($filename,
687
	$cert,
688
	$key,
689
	$ca,
690
	$pid_file,
691
	$port = 80,
692
	$document_root = "/usr/local/www/",
693
	$cert_location = "cert.pem",
694
	$ca_location = "ca.pem",
695
	$max_procs = 2,
696
	$max_requests = "1",
697
	$fast_cgi_enable = true,
698
	$captive_portal = false) {
699

    
700
	global $config, $g;
701

    
702
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
703
		mkdir("{$g['tmp_path']}/lighttpdcompress");
704

    
705
	if(isset($config['system']['developerspew'])) {
706
		$mt = microtime();
707
		echo "system_generate_lighty_config() being called $mt\n";
708
	}
709

    
710
	if($captive_portal == true)  {
711
		$captiveportal = ",\"mod_rewrite\"";
712
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?redirurl=$1\" )\n";
713
		$captive_portal_module = "\"mod_accesslog\", ";
714
		$maxprocperip = $config['captiveportal']['maxprocperip'];
715
		if(!$maxprocperip and $maxprocperip > 0)
716
			$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
717
		else
718
			$captive_portal_mod_evasive = "";
719
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
720
		exec("mkdir -p {$g['tmp_path']}/captiveportal");
721
		exec("chmod a-w {$g['tmp_path']}/captiveportal");
722
		$server_max_request_size = "server.max-request-size    = 384";
723
	} else {
724
		$captiveportal = "";
725
		$captive_portal_rewrite = "";
726
		$captive_portal_module = "";
727
		$captive_portal_mod_evasive = "";
728
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
729
		$server_max_request_size = "server.max-request-size    = 2097152";
730
	}
731
	
732
	if($port <> "")
733
		$lighty_port = $port;
734
	else
735
		$lighty_port = "80";
736

    
737
	$memory = get_memory();
738
	$avail = $memory[0];
739

    
740
	if($avail > 0 and $avail < 65) {
741
		$fast_cgi_enable = false;
742
	}
743

    
744
	if($avail > 65 and $avail < 98) {
745
		$max_procs = 1;
746
	}
747

    
748
	if($avail > 97 and $avail < 128) {
749
		$max_procs = 2;
750
	}
751

    
752
	if($avail > 127 and $avail < 256) {
753
		$max_procs = 3;
754
	}
755

    
756
	if($avail > 255 and $avail < 384) {
757
		$max_procs = 4;
758
	}
759

    
760
	if($avail > 383) {
761
		$max_procs = 5;
762
	}
763

    
764
	if($captive_portal == true)  {	
765
		$bin_environment =  <<<EOC
766
        "bin-environment" => (
767
           "PHP_FCGI_CHILDREN" => "$max_procs",
768
           "PHP_FCGI_MAX_REQUESTS" => "500"
769
        ), 
770
EOC;
771

    
772
	} else if ($avail > 0 and $avail < 128) {
773
		$bin_environment = <<<EOC
774
		"bin-environment" => (
775
			"PHP_FCGI_CHILDREN" => "$max_procs",
776
			"PHP_FCGI_MAX_REQUESTS" => "2",
777
	),
778

    
779
EOC;
780
	} else
781
		$bin_environment =  <<<EOC
782
        "bin-environment" => (
783
           "PHP_FCGI_CHILDREN" => "$max_procs",
784
           "PHP_FCGI_MAX_REQUESTS" => "500"
785
        ), 
786
EOC;
787

    
788
	if($fast_cgi_enable == true) {
789
		$module = "\"mod_fastcgi\", \"mod_cgi\"";
790
		$cgi_config = "";
791
		$fastcgi_config = <<<EOD
792
#### fastcgi module
793
## read fastcgi.txt for more info
794
fastcgi.server = ( ".php" =>
795
	( "localhost" =>
796
		(
797
			"socket" => "{$g['tmp_path']}/php-fastcgi.socket",
798
			"min-procs" => 0,
799
			"max-procs" => {$max_procs},
800
			{$bin_environment}			
801
			"bin-path" => "/usr/local/bin/php"
802
		)
803
	)
804
)
805

    
806
#### CGI module
807
cgi.assign                 = ( ".cgi" => "" )
808

    
809
EOD;
810
	} else {
811
		$fastcgi_config = "";
812
		$module = "\"mod_cgi\"";
813
		$cgi_config = <<<EOD
814
#### CGI module
815
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
816
                               ".cgi" => "" )
817

    
818
EOD;
819
	}
820

    
821
	$lighty_config = "";
822
	$lighty_config .= <<<EOD
823
#
824
# lighttpd configuration file
825
#
826
# use a it as base for lighttpd 1.0.0 and above
827
#
828
############ Options you really have to take care of ####################
829

    
830
## FreeBSD!
831
server.event-handler	= "freebsd-kqueue"
832
server.network-backend 	= "writev"
833

    
834
## modules to load
835
server.modules              =   (
836
									{$captive_portal_module}
837
									"mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect",
838
									{$module}{$captiveportal}
839
								)
840

    
841
## Unused modules
842
#                               "mod_setenv",
843
#                               "mod_rewrite",
844
#                               "mod_ssi",
845
#                               "mod_usertrack",
846
#                               "mod_expire",
847
#                               "mod_secdownload",
848
#                               "mod_rrdtool",
849
#                               "mod_auth",
850
#                               "mod_status",
851
#                               "mod_alias",
852
#                               "mod_proxy",
853
#                               "mod_simple_vhost",
854
#                               "mod_evhost",
855
#                               "mod_userdir",
856
#                               "mod_cgi",
857

    
858
server.max-keep-alive-requests = 15
859
server.max-keep-alive-idle = 30
860

    
861
## a static document-root, for virtual-hosting take look at the
862
## server.virtual-* options
863
server.document-root        = "{$document_root}"
864
{$captive_portal_rewrite}
865

    
866
# Maximum idle time with nothing being written (php downloading)
867
server.max-write-idle = 999
868

    
869
## where to send error-messages to
870
server.errorlog             = "/var/log/lighttpd.error.log"
871

    
872
# files to check for if .../ is requested
873
server.indexfiles           = ( "index.php", "index.html",
874
                                "index.htm", "default.htm" )
875

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

    
929
# Use the "Content-Type" extended attribute to obtain mime type if possible
930
#mimetypes.use-xattr        = "enable"
931

    
932
#### accesslog module
933
#accesslog.filename          = "/dev/null"
934

    
935
## deny access the file-extensions
936
#
937
# ~    is for backupfiles from vi, emacs, joe, ...
938
# .inc is often used for code includes which should in general not be part
939
#      of the document-root
940
url.access-deny             = ( "~", ".inc" )
941

    
942

    
943
######### Options that are good to be but not neccesary to be changed #######
944

    
945
## bind to port (default: 80)
946
server.port                = {$lighty_port}
947

    
948
## error-handler for status 404
949
#server.error-handler-404   = "/error-handler.html"
950
#server.error-handler-404   = "/error-handler.php"
951

    
952
## to help the rc.scripts
953
server.pid-file            = "/var/run/{$pid_file}"
954

    
955
## virtual directory listings
956
server.dir-listing         = "disable"
957

    
958
## enable debugging
959
debug.log-request-header   = "disable"
960
debug.log-response-header  = "disable"
961
debug.log-request-handling = "disable"
962
debug.log-file-not-found   = "disable"
963

    
964
# gzip compression
965
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
966
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
967

    
968
{$server_upload_dirs}
969

    
970
{$server_max_request_size}
971

    
972
{$fastcgi_config}
973

    
974
{$cgi_config}
975

    
976
{$captive_portal_mod_evasive}
977

    
978
expire.url = (
979
				"" => "access 50 hours",	
980
        )
981

    
982
EOD;
983

    
984
	$cert = str_replace("\r", "", $cert);
985
	$key = str_replace("\r", "", $key);
986
	$ca = str_replace("\r", "", $ca);
987

    
988
	$cert = str_replace("\n\n", "\n", $cert);
989
	$key = str_replace("\n\n", "\n", $key);
990
	$ca = str_replace("\n\n", "\n", $ca);
991

    
992
	if($cert <> "" and $key <> "") {
993
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
994
		if (!$fd) {
995
			printf("Error: cannot open cert.pem in system_webgui_start().\n");
996
			return 1;
997
		}
998
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
999
		fwrite($fd, $cert);
1000
		fwrite($fd, "\n");
1001
		fwrite($fd, $key);
1002
		fclose($fd);
1003
		if($ca <> "") {
1004
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1005
			if (!$fd) {
1006
				printf("Error: cannot open ca.pem in system_webgui_start().\n");
1007
				return 1;
1008
			}
1009
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1010
			fwrite($fd, $ca);
1011
			fclose($fd);
1012
		}
1013
		$lighty_config .= "\n";
1014
		$lighty_config .= "## ssl configuration\n";
1015
		$lighty_config .= "ssl.engine = \"enable\"\n";
1016
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1017
		if($ca <> "")
1018
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1019
	}
1020

    
1021
	// Add HTTP to HTTPS redirect	
1022
	if ($captive_portal == false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1023
		if($lighty_port != "443") 
1024
			$redirectport = ":{$lighty_port}";
1025
		$lighty_config .= <<<EOD
1026
\$SERVER["socket"] == ":80" {
1027
	\$HTTP["host"] =~ "(.*)" {
1028
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1029
	}
1030
}
1031
EOD;
1032
	}
1033

    
1034
	$fd = fopen("{$filename}", "w");
1035
	if (!$fd) {
1036
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
1037
		return 1;
1038
	}
1039
	fwrite($fd, $lighty_config);
1040
	fclose($fd);
1041

    
1042
	return 0;
1043

    
1044
}
1045

    
1046
function system_timezone_configure() {
1047
	global $config, $g;
1048
	if(isset($config['system']['developerspew'])) {
1049
		$mt = microtime();
1050
		echo "system_timezone_configure() being called $mt\n";
1051
	}
1052

    
1053
	$syscfg = $config['system'];
1054

    
1055
	if ($g['booting'])
1056
		echo "Setting timezone...";
1057

    
1058
	/* extract appropriate timezone file */
1059
	$timezone = $syscfg['timezone'];
1060
	if (!$timezone)
1061
		$timezone = "Etc/UTC";
1062

    
1063
	conf_mount_rw();
1064

    
1065
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1066
		escapeshellarg($timezone) . " > /etc/localtime");
1067

    
1068
	mwexec("sync");
1069
	conf_mount_ro();
1070

    
1071
	if ($g['booting'])
1072
		echo "done.\n";
1073
}
1074

    
1075
function system_ntp_configure() {
1076
	global $config, $g;
1077

    
1078
	$syscfg = $config['system'];
1079

    
1080
	/* open configuration for wrting or bail */
1081
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1082
	if(!$fd) {
1083
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1084
		return;
1085
	}
1086

    
1087
	fwrite($fd, "# \n");
1088
	fwrite($fd, "# pfSense OpenNTPD configuration file \n");
1089
	fwrite($fd, "# \n\n");
1090

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

    
1095
	/* Setup listener(s) if the user has configured one */
1096
        if ($config['installedpackages']['openntpd']) {
1097
    		/* server config is in coregui1 */
1098
		$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
1099
		if ($xmlsettings['enable'] == 'on') {
1100
			$ifaces = explode(',', $xmlsettings['interface']);
1101
			$ifaces = array_map('get_real_interface', $ifaces);
1102
			$ifaces = array_filter($ifaces, 'does_interface_exist');
1103
			$ips = array_map('find_interface_ip', $ifaces);
1104
			foreach ($ips as $ip) {
1105
				if (is_ipaddr($ip))
1106
					fwrite($fd, "listen on $ip\n");
1107
			}
1108
		}
1109
	}
1110

    
1111
	fwrite($fd, "\n");
1112

    
1113
	/* slurp! */
1114
	fclose($fd);
1115

    
1116
	/* if openntpd is running, kill it */
1117
	while(is_process_running("ntpd")) {
1118
		mwexec("/usr/bin/killall ntpd", true);
1119
	}
1120

    
1121
	/* if /var/empty does not exist, create it */
1122
	if(!is_dir("/var/empty"))
1123
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1124

    
1125
	if($g['booting'])
1126
		return;
1127
	
1128
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1129
	exec("/usr/local/sbin/ntpd -s -f {$g['varetc_path']}/ntpd.conf");
1130
	
1131
	// Note that we are starting up
1132
	exec("echo 'OpenNTPD is starting up' >> {$g['varlog_path']}/ntpd.log");
1133

    
1134
}
1135

    
1136
function sync_system_time() {
1137
	global $config, $g;
1138

    
1139
	$syscfg = $config['system'];
1140

    
1141
	if ($g['booting'])
1142
		echo "Syncing system time before startup...";
1143

    
1144
	/* foreach through servers and write out to ntpd.conf */
1145
	foreach (explode(' ', $syscfg['timeservers']) as $ts) {
1146
		mwexec("/usr/sbin/ntpdate -s $ts");
1147
	}
1148
	
1149
	if ($g['booting'])
1150
		echo "done.\n";
1151
	
1152
}
1153

    
1154
function system_halt() {
1155
	global $g;
1156

    
1157
	system_reboot_cleanup();
1158

    
1159
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1160
}
1161

    
1162
function system_reboot() {
1163
	global $g;
1164

    
1165
	system_reboot_cleanup();
1166

    
1167
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1168
}
1169

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

    
1173
	system_reboot_cleanup();
1174

    
1175
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1176
}
1177

    
1178
function system_reboot_cleanup() {
1179
	mwexec("/usr/local/bin/beep.sh stop");
1180
	require_once("captiveportal.inc");
1181
	captiveportal_radius_stop_all();
1182
	require_once("voucher.inc");
1183
	voucher_save_db_to_config();
1184
}
1185

    
1186
function system_do_shell_commands($early = 0) {
1187
	global $config, $g;
1188
	if(isset($config['system']['developerspew'])) {
1189
		$mt = microtime();
1190
		echo "system_do_shell_commands() being called $mt\n";
1191
	}
1192

    
1193
	if ($early)
1194
		$cmdn = "earlyshellcmd";
1195
	else
1196
		$cmdn = "shellcmd";
1197

    
1198
	if (is_array($config['system'][$cmdn])) {
1199

    
1200
		/* *cmd is an array, loop through */
1201
		foreach ($config['system'][$cmdn] as $cmd) {
1202
			exec($cmd);
1203
		}
1204

    
1205
	} elseif($config['system'][$cmdn] <> "") {
1206

    
1207
		/* execute single item */
1208
		exec($config['system'][$cmdn]);
1209

    
1210
	}
1211
}
1212

    
1213
function system_console_configure() {
1214
	global $config, $g;
1215
	if(isset($config['system']['developerspew'])) {
1216
		$mt = microtime();
1217
		echo "system_console_configure() being called $mt\n";
1218
	}
1219

    
1220
	if (isset($config['system']['disableconsolemenu'])) {
1221
		touch("{$g['varetc_path']}/disableconsole");
1222
	} else {
1223
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1224
	}
1225
}
1226

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

    
1234
	$dmesg = "";
1235
	exec("/sbin/dmesg", $dmesg);
1236

    
1237
	/* find last copyright line (output from previous boots may be present) */
1238
	$lastcpline = 0;
1239

    
1240
	for ($i = 0; $i < count($dmesg); $i++) {
1241
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1242
			$lastcpline = $i;
1243
	}
1244

    
1245
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1246
	if (!$fd) {
1247
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1248
		return 1;
1249
	}
1250

    
1251
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1252
		fwrite($fd, $dmesg[$i] . "\n");
1253

    
1254
	fclose($fd);
1255

    
1256
	return 0;
1257
}
1258

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

    
1266
	if (isset($config['system']['harddiskstandby'])) {
1267
		if ($g['booting']) {
1268
			echo 'Setting hard disk standby... ';
1269
		}
1270

    
1271
		$standby = $config['system']['harddiskstandby'];
1272
		// Check for a numeric value
1273
		if (is_numeric($standby)) {
1274
			// Sync the disk(s)
1275
			mwexec('/bin/sync');
1276
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1277
				// Reinitialize ATA-drives
1278
				mwexec('/usr/local/sbin/atareinit');
1279
				if ($g['booting']) {
1280
					echo "done.\n";
1281
				}
1282
			} else if ($g['booting']) {
1283
				echo "failed!\n";
1284
			}
1285
		} else if ($g['booting']) {
1286
			echo "failed!\n";
1287
		}
1288
	}
1289
}
1290

    
1291
function system_setup_sysctl() {
1292
	global $config;
1293
	if(isset($config['system']['developerspew'])) {
1294
		$mt = microtime();
1295
		echo "system_setup_sysctl() being called $mt\n";
1296
	}
1297

    
1298
	activate_sysctls();	
1299

    
1300
	if (isset($config['system']['sharednet'])) {
1301
		system_disable_arp_wrong_if();
1302
	}
1303
}
1304

    
1305
function system_disable_arp_wrong_if() {
1306
	global $config;
1307
	if(isset($config['system']['developerspew'])) {
1308
		$mt = microtime();
1309
		echo "system_disable_arp_wrong_if() being called $mt\n";
1310
	}
1311
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1312
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1313
}
1314

    
1315
function system_enable_arp_wrong_if() {
1316
	global $config;
1317
	if(isset($config['system']['developerspew'])) {
1318
		$mt = microtime();
1319
		echo "system_enable_arp_wrong_if() being called $mt\n";
1320
	}
1321
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1322
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1323
}
1324

    
1325
function enable_watchdog() {
1326
	global $config;
1327
	return;
1328
	$install_watchdog = false;
1329
	$supported_watchdogs = array("Geode");
1330
	$file = file_get_contents("/var/log/dmesg.boot");
1331
	foreach($supported_watchdogs as $sd) {
1332
		if(stristr($file, "Geode")) {
1333
			$install_watchdog = true;
1334
		}
1335
	}
1336
	if($install_watchdog == true) {
1337
		if(is_process_running("watchdogd"))
1338
			mwexec("/usr/bin/killall watchdogd", true);
1339
		exec("/usr/sbin/watchdogd");
1340
	}
1341
}
1342

    
1343
function system_check_reset_button() {
1344
	global $g;
1345
	if($g['platform'] != "nanobsd")
1346
		return 0;
1347

    
1348
	$specplatform = system_identify_specific_platform();
1349

    
1350
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1351
		return 0;
1352

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

    
1355
	if ($retval == 99) {
1356
		/* user has pressed reset button for 2 seconds - 
1357
		   reset to factory defaults */
1358
		echo <<<EOD
1359

    
1360
***********************************************************************
1361
* Reset button pressed - resetting configuration to factory defaults. *
1362
* The system will reboot after this completes.                        *
1363
***********************************************************************
1364

    
1365

    
1366
EOD;
1367
		
1368
		reset_factory_defaults();
1369
		system_reboot_sync();
1370
		exit(0);
1371
	}
1372

    
1373
	return 0;
1374
}
1375

    
1376
/* attempt to identify the specific platform (for embedded systems)
1377
   Returns an array with two elements:
1378
	name => platform string (e.g. 'wrap', 'alix' etc.)
1379
	descr => human-readable description (e.g. "PC Engines WRAP")
1380
*/
1381
function system_identify_specific_platform() {
1382
	global $g;
1383
	
1384
	if ($g['platform'] == 'generic-pc')
1385
		return array('name' => 'generic-pc', 'descr' => "Generic PC");
1386
	
1387
	if ($g['platform'] == 'generic-pc-cdrom')
1388
		return array('name' => 'generic-pc-cdrom', 'descr' => "Generic PC (CD-ROM)");
1389
	
1390
	/* the rest of the code only deals with 'embedded' platforms */
1391
	if ($g['platform'] != 'nanobsd')
1392
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1393
	
1394
	$dmesg = system_get_dmesg_boot();
1395
	
1396
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1397
		return array('name' => 'wrap', 'descr' => 'PC Engines WRAP');
1398
	
1399
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1400
		return array('name' => 'alix', 'descr' => 'PC Engines ALIX');
1401

    
1402
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1403
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1404
	
1405
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1406
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1407
		
1408
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1409
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1410
	
1411
	/* unknown embedded platform */
1412
	return array('name' => 'embedded', 'descr' => 'embedded (unknown)');
1413
}
1414

    
1415
function system_get_dmesg_boot() {
1416
	global $g;
1417
		
1418
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1419
}
1420

    
1421
?>
(39-39/50)