Project

General

Profile

Download (42.7 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	/sbin/kldload
38
	pfSense_MODULE:	utils
39
*/
40

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

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

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

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

    
80
function system_resolvconf_generate($dynupdate = false) {
81
	global $config, $g;
82

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

    
88
	$syscfg = $config['system'];
89

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

    
96
	$resolvconf = "domain {$syscfg['domain']}\n";
97

    
98
	$havedns = false;
99

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

    
119
	fwrite($fd, $resolvconf);
120
	fclose($fd);
121

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

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

    
149
function get_nameservers() {
150
	global $config, $g;
151
	$master_list = array();
152
	
153
	// Read in dhclient nameservers
154
	$dns_lists = split("\n", `/bin/cat /var/etc/nameserver_* 2>/dev/null`);
155
	if (is_array($dns_lists)) {
156
		foreach($dns_lists as $dns) {
157
			if(is_ipaddr($dns)) 
158
				$master_list[] = $dns;
159
		}
160
	}
161

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

    
171
	return $master_list;
172
}
173

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

    
181
	$syscfg = $config['system'];
182
	$dnsmasqcfg = $config['dnsmasq'];
183

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

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

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

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

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

    
230
	system_dhcpleases_configure();
231

    
232
	return 0;
233
}
234

    
235
function system_dhcpleases_configure() {
236
	global $config, $g;
237
	
238
	/* Start the monitoring process for dynamic dhcpclients. */
239
	if (isset($config['dnsmasq']['regdhcp'])) {
240
		/* Make sure we do not error out */
241
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
242
		if (file_exists("{$g['varrun_path']}/dhcpleases.pid"))
243
				sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "HUP");
244
		else
245
			mwexec("/usr/local/sbin/dhcpleases -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases -d {$config['system']['domain']} -p {$g['varrun_path']}/dnsmasq.pid -h {$g['varetc_path']}/hosts");
246
	} else {
247
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
248
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
249
	}
250
}
251

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

    
259
	$syscfg = $config['system'];
260

    
261
	/* set hostname */
262
	$status = mwexec("/bin/hostname " .
263
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
264

    
265
    /* Setup host GUID ID.  This is used by ZFS. */
266
	mwexec("/etc/rc.d/hostid start");
267

    
268
	return $status;
269
}
270

    
271
function system_routing_configure($interface = "") {
272
	global $config, $g;
273
	if(isset($config['system']['developerspew'])) {
274
		$mt = microtime();
275
		echo "system_routing_configure() being called $mt\n";
276
	}
277

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

    
283
	$gatewayip = "";
284
	$interfacegw = "";
285
	$foundgw = false;
286
	/* tack on all the hard defined gateways as well */
287
	if (is_array($config['gateways']['gateway_item'])) {
288
		mwexec("/bin/rm {$g['tmp_path']}/*_defaultgw", true);
289
		foreach	($config['gateways']['gateway_item'] as $gateway) {
290
			if (isset($gateway['defaultgw'])) {
291
				if ($gateway['gateway'] == "dynamic")
292
					$gateway['gateway'] = get_interface_gateway($gateway['interface']);
293
				$gatewayip = $gateway['gateway'];
294
				$interfacegw = $gateway['interface'];
295
				if (!empty($interfacegw)) {
296
					$defaultif = get_real_interface($gateway['interface']);
297
					if ($defaultif)
298
						@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gatewayip);
299
				}
300
				$foundgw = true;
301
				break;
302
			}
303
		}
304
	}
305
	if ($foundgw == false) {
306
		$defaultif = get_real_interface("wan");
307
		$interfacegw = "wan";
308
		$gatewayip = get_interface_gateway("wan");
309
		@touch("{$g['tmp_path']}/{$defaultif}_defaultgw");
310
	}	
311
	$dont_add_route = false;
312
	/* if OLSRD is enabled, allow WAN to house DHCP. */
313
	if($config['installedpackages']['olsrd']) {
314
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
315
			if($olsrd['enabledyngw'] == "on") {
316
				$dont_add_route = true;
317
				break;
318
			}
319
		}
320
	}
321
	/* Create a array from the existing route table */
322
	exec("/usr/bin/netstat -rnf inet", $route_str);
323
	array_shift($route_str);
324
	array_shift($route_str);
325
	array_shift($route_str);
326
	array_shift($route_str);
327
	$route_arr = array();
328
	foreach($route_str as $routeline) {
329
		$items = preg_split("/[ ]+/i", $routeline);
330
		$route_arr[$items[0]] = array($items[0], $items[1], $items[5]);
331
	}
332

    
333
	if ($dont_add_route == false ) {
334
		if (!empty($interface) && $inteface != $interafegw)
335
			;
336
		else if (($interfacegw <> "bgpd") && (is_ipaddr($gatewayip))) {
337
			$action = "add";
338
			if(isset($route_arr['default'])) {
339
				$action = "change";
340
			}
341
			log_error("ROUTING: $action default route to $gatewayip");
342
			mwexec("/sbin/route {$action} default " . escapeshellarg($gatewayip));
343
		} else if (is_ipaddr($config['interfaces']['wan']['gateway'])) {
344
			/* Adding gateway for 1.2-style configs without the new
345
		  	 * gateway setup configured.
346
		  	 * Force WAN to be default gateway because that is the 1.2 behavior.
347
			 */
348
			log_error("WARNING: There is no default gateway in the configuration.");
349
			$gatewayip = $config['interfaces']['wan']['gateway'];
350
			mwexec("/sbin/route add default " . escapeshellarg($gatewayip), true);
351
		}
352
	}
353

    
354
	if (is_array($config['staticroutes']['route'])) {
355
		$gateways_arr = return_gateways_array();
356

    
357
		foreach ($config['staticroutes']['route'] as $rtent) {
358
			$gatewayip = "";
359
			if (isset($gateways_arr[$rtent['gateway']])) {
360
				$gatewayip = $gateways_arr[$rtent['gateway']]['gateway'];
361
				$interfacegw = $gateways_arr[$rtent['gateway']]['interface'];
362
			} else if (is_ipaddr($rtent['gateway'])) {
363
				$gatewayip = $rtent['gateway'];
364
			} else {
365
				log_error("Static Routes: Gateway IP could not be found for {$rtent['network']}");
366
				continue;
367
			}
368

    
369
			$action = "add";
370
			if (isset($route_arr[$rtent['network']]))
371
				$action = "change";
372

    
373
			if (is_ipaddr($gatewayip)) {
374
				mwexec("/sbin/route {$action} " . escapeshellarg($rtent['network']) .
375
					" " . escapeshellarg($gatewayip));
376
			} else if (!empty($interfacegw)) {
377
				mwexec("/sbin/route {$action} " . escapeshellarg($rtent['network']) .
378
					" -iface " . escapeshellarg($interfacegw));
379
			}
380
		}
381
	}
382

    
383
	return 0;
384
}
385

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

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

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

    
403
	$syslogcfg = $config['syslog'];
404

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

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

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

    
507
EOD;
508
		if (isset($syslogcfg['filter'])) {
509
			if($syslogcfg['remoteserver'])
510
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver']}\n";
511
			if($syslogcfg['remoteserver2'])
512
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver2']}\n";
513
			if($syslogcfg['remoteserver3'])
514
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver3']}\n";
515

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

    
550
EOD;
551

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

    
561
EOD;
562

    
563
		if (isset($syslogcfg['system'])) {
564
			if($syslogcfg['remoteserver3'])
565
				$syslogconf .= <<<EOD
566
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver3']}
567
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver3']}
568
security.*										 @{$syslogcfg['remoteserver3']}
569
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver3']}
570
*.emerg											 @{$syslogcfg['remoteserver3']}
571

    
572
EOD;
573

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

    
580
EOD;
581

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

    
587
EOD;
588

    
589
}
590
			if($syslogcfg['remoteserver3'])
591
				$syslogconf .= <<<EOD
592
*.*								@{$syslogcfg['remoteserver3']}
593

    
594
EOD;
595

    
596
}
597
		fwrite($fd, $syslogconf);
598
		fclose($fd);
599
		// Are we logging to a least one remote server ?
600
		if(strpos($syslogconf, "@") != false)
601
			$retval = system("/usr/sbin/syslogd -c -f {$g['varetc_path']}/syslog.conf");
602
		else
603
			$retval = system("/usr/sbin/syslogd -c -f {$g['varetc_path']}/syslog.conf");
604

    
605
	} else {
606
		$retval = mwexec("/usr/sbin/syslogd -c");
607
	}
608

    
609
	if ($g['booting'])
610
		echo "done.\n";
611

    
612
	return $retval;
613
}
614

    
615
function system_pccard_start() {
616
	global $config, $g;
617
	if(isset($config['system']['developerspew'])) {
618
		$mt = microtime();
619
		echo "system_pccard_start() being called $mt\n";
620
	}
621

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

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

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

    
631
	if ($g['booting']) {
632
		if ($res == 0)
633
			echo "done.\n";
634
		else
635
			echo "failed!\n";
636
	}
637

    
638
	return $res;
639
}
640

    
641

    
642
function system_webgui_start() {
643
	global $config, $g;
644

    
645
	if ($g['booting'])
646
		echo "Starting webConfigurator...";
647

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

    
651
	sleep(1);
652

    
653
	chdir($g['www_path']);
654

    
655
	/* defaults */
656
	$portarg = "80";
657
	$crt = "";
658
	$key = "";
659
	$ca = "";
660

    
661
	/* non-standard port? */
662
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
663
		$portarg = "{$config['system']['webgui']['port']}";
664

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

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

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

    
708
	/* fetch page to preload apc cache */
709
	$proto = "http";
710
	if ($config['system']['webgui']['protocol'])
711
		$proto = $config['system']['webgui']['protocol'];
712
	mwexec_bg("/usr/bin/fetch -o /dev/null -q {$proto}://localhost:{$portarg}/preload.php");
713

    
714
	if ($g['booting']) {
715
		if ($res == 0)
716
			echo "done.\n";
717
		else
718
			echo "failed!\n";
719
	}
720

    
721
	return $res;
722
}
723

    
724
function system_generate_lighty_config($filename,
725
	$cert,
726
	$key,
727
	$ca,
728
	$pid_file,
729
	$port = 80,
730
	$document_root = "/usr/local/www/",
731
	$cert_location = "cert.pem",
732
	$ca_location = "ca.pem",
733
	$max_procs = 2,
734
	$max_requests = "2",
735
	$fast_cgi_enable = true,
736
	$captive_portal = false) {
737

    
738
	global $config, $g;
739

    
740
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
741
		mkdir("{$g['tmp_path']}/lighttpdcompress");
742

    
743
	if(isset($config['system']['developerspew'])) {
744
		$mt = microtime();
745
		echo "system_generate_lighty_config() being called $mt\n";
746
	}
747

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

    
775
	$memory = get_memory();
776
	$avail = $memory[0];
777

    
778
	if($avail > 0 and $avail < 65) {
779
		$fast_cgi_enable = false;
780
	}
781

    
782
	// Ramp up captive portal max procs
783
	if($captive_portal == true)  {
784
		if($avail > 65 and $avail < 98) {
785
			$max_procs = 1;
786
		}
787
		if($avail > 97 and $avail < 128) {
788
			$max_procs = 2;
789
		}
790
		if($avail > 127 and $avail < 256) {
791
			$max_procs = 3;
792
		}
793
		if($avail > 255 and $avail < 384) {
794
			$max_procs = 4;
795
		}
796
		if($avail > 383) {
797
			$max_procs = 5;
798
		}
799
	}
800

    
801
	if($captive_portal == true)  {	
802
		$bin_environment =  <<<EOC
803
        "bin-environment" => (
804
           "PHP_FCGI_CHILDREN" => "$max_procs",
805
           "PHP_FCGI_MAX_REQUESTS" => "500"
806
        ), 
807
EOC;
808

    
809
	} else if ($avail > 0 and $avail < 128) {
810
		$bin_environment = <<<EOC
811
		"bin-environment" => (
812
			"PHP_FCGI_CHILDREN" => "$max_procs",
813
			"PHP_FCGI_MAX_REQUESTS" => "2",
814
	),
815

    
816
EOC;
817
	} else
818
		$bin_environment =  <<<EOC
819
        "bin-environment" => (
820
           "PHP_FCGI_CHILDREN" => "$max_procs",
821
           "PHP_FCGI_MAX_REQUESTS" => "500"
822
        ), 
823
EOC;
824

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

    
843
#### CGI module
844
cgi.assign                 = ( ".cgi" => "" )
845

    
846
EOD;
847
	} else {
848
		$fastcgi_config = "";
849
		$module = "\"mod_cgi\"";
850
		$cgi_config = <<<EOD
851
#### CGI module
852
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
853
                               ".cgi" => "" )
854

    
855
EOD;
856
	}
857

    
858
	$lighty_config = "";
859
	$lighty_config .= <<<EOD
860
#
861
# lighttpd configuration file
862
#
863
# use a it as base for lighttpd 1.0.0 and above
864
#
865
############ Options you really have to take care of ####################
866

    
867
## FreeBSD!
868
server.event-handler	= "freebsd-kqueue"
869
server.network-backend 	= "writev"
870

    
871
## modules to load
872
server.modules              =   (
873
									{$captive_portal_module}
874
									"mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect",
875
									{$module}{$captiveportal}
876
								)
877

    
878
## Unused modules
879
#                               "mod_setenv",
880
#                               "mod_rewrite",
881
#                               "mod_ssi",
882
#                               "mod_usertrack",
883
#                               "mod_expire",
884
#                               "mod_secdownload",
885
#                               "mod_rrdtool",
886
#                               "mod_auth",
887
#                               "mod_status",
888
#                               "mod_alias",
889
#                               "mod_proxy",
890
#                               "mod_simple_vhost",
891
#                               "mod_evhost",
892
#                               "mod_userdir",
893
#                               "mod_cgi",
894

    
895
server.max-keep-alive-requests = 15
896
server.max-keep-alive-idle = 30
897

    
898
## a static document-root, for virtual-hosting take look at the
899
## server.virtual-* options
900
server.document-root        = "{$document_root}"
901
{$captive_portal_rewrite}
902

    
903
# Maximum idle time with nothing being written (php downloading)
904
server.max-write-idle = 999
905

    
906
## where to send error-messages to
907
server.errorlog             = "/var/log/lighttpd.error.log"
908

    
909
# files to check for if .../ is requested
910
server.indexfiles           = ( "index.php", "index.html",
911
                                "index.htm", "default.htm" )
912

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

    
966
# Use the "Content-Type" extended attribute to obtain mime type if possible
967
#mimetypes.use-xattr        = "enable"
968

    
969
#### accesslog module
970
#accesslog.filename          = "/dev/null"
971

    
972
## deny access the file-extensions
973
#
974
# ~    is for backupfiles from vi, emacs, joe, ...
975
# .inc is often used for code includes which should in general not be part
976
#      of the document-root
977
url.access-deny             = ( "~", ".inc" )
978

    
979

    
980
######### Options that are good to be but not neccesary to be changed #######
981

    
982
## bind to port (default: 80)
983
server.port                = {$lighty_port}
984

    
985
## error-handler for status 404
986
#server.error-handler-404   = "/error-handler.html"
987
#server.error-handler-404   = "/error-handler.php"
988

    
989
## to help the rc.scripts
990
server.pid-file            = "/var/run/{$pid_file}"
991

    
992
## virtual directory listings
993
server.dir-listing         = "disable"
994

    
995
## enable debugging
996
debug.log-request-header   = "disable"
997
debug.log-response-header  = "disable"
998
debug.log-request-handling = "disable"
999
debug.log-file-not-found   = "disable"
1000

    
1001
# gzip compression
1002
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1003
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1004

    
1005
{$server_upload_dirs}
1006

    
1007
{$server_max_request_size}
1008

    
1009
{$fastcgi_config}
1010

    
1011
{$cgi_config}
1012

    
1013
{$captive_portal_mod_evasive}
1014

    
1015
expire.url = (
1016
				"" => "access 50 hours",	
1017
        )
1018

    
1019
EOD;
1020

    
1021
	$cert = str_replace("\r", "", $cert);
1022
	$key = str_replace("\r", "", $key);
1023
	$ca = str_replace("\r", "", $ca);
1024

    
1025
	$cert = str_replace("\n\n", "\n", $cert);
1026
	$key = str_replace("\n\n", "\n", $key);
1027
	$ca = str_replace("\n\n", "\n", $ca);
1028

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

    
1058
	// Add HTTP to HTTPS redirect	
1059
	if ($captive_portal == false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1060
		if($lighty_port != "443") 
1061
			$redirectport = ":{$lighty_port}";
1062
		$lighty_config .= <<<EOD
1063
\$SERVER["socket"] == ":80" {
1064
	\$HTTP["host"] =~ "(.*)" {
1065
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1066
	}
1067
}
1068
EOD;
1069
	}
1070

    
1071
	$fd = fopen("{$filename}", "w");
1072
	if (!$fd) {
1073
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
1074
		return 1;
1075
	}
1076
	fwrite($fd, $lighty_config);
1077
	fclose($fd);
1078

    
1079
	return 0;
1080

    
1081
}
1082

    
1083
function system_timezone_configure() {
1084
	global $config, $g;
1085
	if(isset($config['system']['developerspew'])) {
1086
		$mt = microtime();
1087
		echo "system_timezone_configure() being called $mt\n";
1088
	}
1089

    
1090
	$syscfg = $config['system'];
1091

    
1092
	if ($g['booting'])
1093
		echo "Setting timezone...";
1094

    
1095
	/* extract appropriate timezone file */
1096
	$timezone = $syscfg['timezone'];
1097
	if (!$timezone)
1098
		$timezone = "Etc/UTC";
1099

    
1100
	conf_mount_rw();
1101

    
1102
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1103
		escapeshellarg($timezone) . " > /etc/localtime");
1104

    
1105
	mwexec("sync");
1106
	conf_mount_ro();
1107

    
1108
	if ($g['booting'])
1109
		echo "done.\n";
1110
}
1111

    
1112
function system_ntp_configure() {
1113
	global $config, $g;
1114

    
1115
	$syscfg = $config['system'];
1116

    
1117
	/* open configuration for wrting or bail */
1118
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1119
	if(!$fd) {
1120
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1121
		return;
1122
	}
1123

    
1124
	fwrite($fd, "# \n");
1125
	fwrite($fd, "# pfSense OpenNTPD configuration file \n");
1126
	fwrite($fd, "# \n\n");
1127

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

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

    
1148
	fwrite($fd, "\n");
1149

    
1150
	/* slurp! */
1151
	fclose($fd);
1152

    
1153
	/* if openntpd is running, kill it */
1154
	while(is_process_running("ntpd")) {
1155
		mwexec("/usr/bin/killall ntpd", true);
1156
	}
1157

    
1158
	/* if /var/empty does not exist, create it */
1159
	if(!is_dir("/var/empty"))
1160
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1161

    
1162
	if($g['booting'])
1163
		return;
1164
	
1165
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1166
	exec("/usr/local/sbin/ntpd -s -f {$g['varetc_path']}/ntpd.conf");
1167
	
1168
	// Note that we are starting up
1169
	exec("echo 'OpenNTPD is starting up' >> {$g['varlog_path']}/ntpd.log");
1170

    
1171
}
1172

    
1173
function sync_system_time() {
1174
	global $config, $g;
1175

    
1176
	$syscfg = $config['system'];
1177

    
1178
	if ($g['booting'])
1179
		echo "Syncing system time before startup...";
1180

    
1181
	/* foreach through servers and write out to ntpd.conf */
1182
	foreach (explode(' ', $syscfg['timeservers']) as $ts) {
1183
		mwexec("/usr/sbin/ntpdate -s $ts");
1184
	}
1185
	
1186
	if ($g['booting'])
1187
		echo "done.\n";
1188
	
1189
}
1190

    
1191
function system_halt() {
1192
	global $g;
1193

    
1194
	system_reboot_cleanup();
1195

    
1196
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1197
}
1198

    
1199
function system_reboot() {
1200
	global $g;
1201

    
1202
	system_reboot_cleanup();
1203

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

    
1207
function system_reboot_sync() {
1208
	global $g;
1209

    
1210
	system_reboot_cleanup();
1211

    
1212
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1213
}
1214

    
1215
function system_reboot_cleanup() {
1216
	mwexec("/usr/local/bin/beep.sh stop");
1217
	require_once("captiveportal.inc");
1218
	captiveportal_radius_stop_all();
1219
	require_once("voucher.inc");
1220
	voucher_save_db_to_config();
1221
}
1222

    
1223
function system_do_shell_commands($early = 0) {
1224
	global $config, $g;
1225
	if(isset($config['system']['developerspew'])) {
1226
		$mt = microtime();
1227
		echo "system_do_shell_commands() being called $mt\n";
1228
	}
1229

    
1230
	if ($early)
1231
		$cmdn = "earlyshellcmd";
1232
	else
1233
		$cmdn = "shellcmd";
1234

    
1235
	if (is_array($config['system'][$cmdn])) {
1236

    
1237
		/* *cmd is an array, loop through */
1238
		foreach ($config['system'][$cmdn] as $cmd) {
1239
			exec($cmd);
1240
		}
1241

    
1242
	} elseif($config['system'][$cmdn] <> "") {
1243

    
1244
		/* execute single item */
1245
		exec($config['system'][$cmdn]);
1246

    
1247
	}
1248
}
1249

    
1250
function system_console_configure() {
1251
	global $config, $g;
1252
	if(isset($config['system']['developerspew'])) {
1253
		$mt = microtime();
1254
		echo "system_console_configure() being called $mt\n";
1255
	}
1256

    
1257
	if (isset($config['system']['disableconsolemenu'])) {
1258
		touch("{$g['varetc_path']}/disableconsole");
1259
	} else {
1260
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1261
	}
1262
}
1263

    
1264
function system_dmesg_save() {
1265
	global $g;
1266
	if(isset($config['system']['developerspew'])) {
1267
		$mt = microtime();
1268
		echo "system_dmesg_save() being called $mt\n";
1269
	}
1270

    
1271
	$dmesg = "";
1272
	exec("/sbin/dmesg", $dmesg);
1273

    
1274
	/* find last copyright line (output from previous boots may be present) */
1275
	$lastcpline = 0;
1276

    
1277
	for ($i = 0; $i < count($dmesg); $i++) {
1278
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1279
			$lastcpline = $i;
1280
	}
1281

    
1282
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1283
	if (!$fd) {
1284
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1285
		return 1;
1286
	}
1287

    
1288
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1289
		fwrite($fd, $dmesg[$i] . "\n");
1290

    
1291
	fclose($fd);
1292

    
1293
	return 0;
1294
}
1295

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

    
1303
	if (isset($config['system']['harddiskstandby'])) {
1304
		if ($g['booting']) {
1305
			echo 'Setting hard disk standby... ';
1306
		}
1307

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

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

    
1335
	activate_sysctls();	
1336

    
1337
	if (isset($config['system']['sharednet'])) {
1338
		system_disable_arp_wrong_if();
1339
	}
1340
}
1341

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

    
1352
function system_enable_arp_wrong_if() {
1353
	global $config;
1354
	if(isset($config['system']['developerspew'])) {
1355
		$mt = microtime();
1356
		echo "system_enable_arp_wrong_if() being called $mt\n";
1357
	}
1358
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1359
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1360
}
1361

    
1362
function enable_watchdog() {
1363
	global $config;
1364
	return;
1365
	$install_watchdog = false;
1366
	$supported_watchdogs = array("Geode");
1367
	$file = file_get_contents("/var/log/dmesg.boot");
1368
	foreach($supported_watchdogs as $sd) {
1369
		if(stristr($file, "Geode")) {
1370
			$install_watchdog = true;
1371
		}
1372
	}
1373
	if($install_watchdog == true) {
1374
		if(is_process_running("watchdogd"))
1375
			mwexec("/usr/bin/killall watchdogd", true);
1376
		exec("/usr/sbin/watchdogd");
1377
	}
1378
}
1379

    
1380
function system_check_reset_button() {
1381
	global $g;
1382
	if($g['platform'] != "nanobsd")
1383
		return 0;
1384

    
1385
	$specplatform = system_identify_specific_platform();
1386

    
1387
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1388
		return 0;
1389

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

    
1392
	if ($retval == 99) {
1393
		/* user has pressed reset button for 2 seconds - 
1394
		   reset to factory defaults */
1395
		echo <<<EOD
1396

    
1397
***********************************************************************
1398
* Reset button pressed - resetting configuration to factory defaults. *
1399
* The system will reboot after this completes.                        *
1400
***********************************************************************
1401

    
1402

    
1403
EOD;
1404
		
1405
		reset_factory_defaults();
1406
		system_reboot_sync();
1407
		exit(0);
1408
	}
1409

    
1410
	return 0;
1411
}
1412

    
1413
/* attempt to identify the specific platform (for embedded systems)
1414
   Returns an array with two elements:
1415
	name => platform string (e.g. 'wrap', 'alix' etc.)
1416
	descr => human-readable description (e.g. "PC Engines WRAP")
1417
*/
1418
function system_identify_specific_platform() {
1419
	global $g;
1420
	
1421
	if ($g['platform'] == 'generic-pc')
1422
		return array('name' => 'generic-pc', 'descr' => "Generic PC");
1423
	
1424
	if ($g['platform'] == 'generic-pc-cdrom')
1425
		return array('name' => 'generic-pc-cdrom', 'descr' => "Generic PC (CD-ROM)");
1426
	
1427
	/* the rest of the code only deals with 'embedded' platforms */
1428
	if ($g['platform'] != 'nanobsd')
1429
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1430
	
1431
	$dmesg = system_get_dmesg_boot();
1432
	
1433
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1434
		return array('name' => 'wrap', 'descr' => 'PC Engines WRAP');
1435
	
1436
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1437
		return array('name' => 'alix', 'descr' => 'PC Engines ALIX');
1438

    
1439
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1440
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1441
	
1442
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1443
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1444
		
1445
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1446
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1447
	
1448
	/* unknown embedded platform */
1449
	return array('name' => 'embedded', 'descr' => 'embedded (unknown)');
1450
}
1451

    
1452
function system_get_dmesg_boot() {
1453
	global $g;
1454
		
1455
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1456
}
1457

    
1458
?>
(40-40/54)