Project

General

Profile

Download (42.8 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/* $Id$ */
3
/*
4
	system.inc
5
	part of m0n0wall (http://m0n0.ch/wall)
6

    
7
	Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
8
	All rights reserved.
9

    
10
	Redistribution and use in source and binary forms, with or without
11
	modification, are permitted provided that the following conditions are met:
12

    
13
	1. Redistributions of source code must retain the above copyright notice,
14
	   this list of conditions and the following disclaimer.
15

    
16
	2. Redistributions in binary form must reproduce the above copyright
17
	   notice, this list of conditions and the following disclaimer in the
18
	   documentation and/or other materials provided with the distribution.
19

    
20
	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
21
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
22
	AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
23
	AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
24
	OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29
	POSSIBILITY OF SUCH DAMAGE.
30
*/
31

    
32
/*
33
	pfSense_BUILDER_BINARIES:	/usr/sbin/powerd	/usr/bin/killall	/sbin/sysctl	/sbin/route
34
	pfSense_BUILDER_BINARIES:	/bin/hostname	/bin/ls	/usr/bin/netstat	/usr/sbin/syslogd	
35
	pfSense_BUILDER_BINARIES:	/usr/sbin/pccardd	/usr/local/sbin/lighttpd	/bin/chmod 	/bin/mkdir
36
	pfSense_BUILDER_BINARIES:	/usr/bin/tar	/bin/sync	/usr/local/sbin/ntpd	/usr/sbin/ntpdate
37
	pfSense_BUILDER_BINARIES:	/usr/bin/nohup	/sbin/dmesg	/usr/local/sbin/atareinit	/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
	/* Start the monitoring process for dynamic dhcpclients. */
231
	if (isset($config['dnsmasq']['regdhcp'])) {
232
		/* Make sure we do not error out */
233
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
234
                if (file_exists("{$g['varrun_path']}/dhcpleases.pid"))
235
                        sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "HUP");
236
                else
237
                        mwexec("/usr/local/sbin/dhcpleases -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases -d {$syscfg['domain']} -p {$g['varrun_path']}/dnsmasq.pid -h {$g['varetc_path']}/hosts");
238
        } else {
239
                sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
240
                @unlink("{$g['varrun_path']}/dhcpleases.pid");
241
        }
242

    
243
	return 0;
244
}
245

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

    
253
	$syscfg = $config['system'];
254

    
255
	/* set hostname */
256
	$status = mwexec("/bin/hostname " .
257
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
258

    
259
    /* Setup host GUID ID.  This is used by ZFS. */
260
	mwexec("/etc/rc.d/hostid start");
261

    
262
	return $status;
263
}
264

    
265
function system_routing_configure($interface = "") {
266
	global $config, $g;
267
	if(isset($config['system']['developerspew'])) {
268
		$mt = microtime();
269
		echo "system_routing_configure() being called $mt\n";
270
	}
271

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

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

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

    
348
	if (is_array($config['staticroutes']['route'])) {
349
		$gateways_arr = return_gateways_array();
350

    
351
		foreach ($config['staticroutes']['route'] as $rtent) {
352
			if (!empty($interface) && $interface != $rtent['interface'])
353
				continue;
354
			$gatewayip = "";
355
			if (isset($gateways_arr[$rtent['gateway']])) {
356
				$gatewayip = $gateways_arr[$rtent['gateway']]['gateway'];
357
				$interfacegw = get_real_interface($rtent['interface']);
358
			} else if (is_ipaddr($rtent['gateway'])) {
359
				$gatewayip = $rtent['gateway'];
360
			} else {
361
				log_error("Static Routes: Gateway IP could not be found for {$rtent['network']}");
362
				continue;
363
			}
364

    
365
			$action = "add";
366
			if (isset($route_arr[$rtent['network']]))
367
				$action = "change";
368

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

    
379
	return 0;
380
}
381

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

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

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

    
399
	$syslogcfg = $config['syslog'];
400

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

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

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

    
503
EOD;
504
		if (isset($syslogcfg['filter'])) {
505
			if($syslogcfg['remoteserver'])
506
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver']}\n";
507
			if($syslogcfg['remoteserver2'])
508
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver2']}\n";
509
			if($syslogcfg['remoteserver3'])
510
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver3']}\n";
511

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

    
546
EOD;
547

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

    
557
EOD;
558

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

    
568
EOD;
569

    
570
}
571
		if (isset($syslogcfg['logall'])) {
572
			if($syslogcfg['remoteserver'])
573
				$syslogconf .= <<<EOD
574
*.*								@{$syslogcfg['remoteserver']}
575

    
576
EOD;
577

    
578
}
579
			if($syslogcfg['remoteserver2'])
580
				$syslogconf .= <<<EOD
581
*.*								@{$syslogcfg['remoteserver2']}
582

    
583
EOD;
584

    
585
}
586
			if($syslogcfg['remoteserver3'])
587
				$syslogconf .= <<<EOD
588
*.*								@{$syslogcfg['remoteserver3']}
589

    
590
EOD;
591

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

    
601
	} else {
602
		$retval = mwexec("/usr/sbin/syslogd -c");
603
	}
604

    
605
	if ($g['booting'])
606
		echo "done.\n";
607

    
608
	return $retval;
609
}
610

    
611
function system_pccard_start() {
612
	global $config, $g;
613
	if(isset($config['system']['developerspew'])) {
614
		$mt = microtime();
615
		echo "system_pccard_start() being called $mt\n";
616
	}
617

    
618
	if ($g['booting'])
619
		echo "Initializing PCMCIA...";
620

    
621
	/* kill any running pccardd */
622
	killbypid("{$g['varrun_path']}/pccardd.pid");
623

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

    
627
	if ($g['booting']) {
628
		if ($res == 0)
629
			echo "done.\n";
630
		else
631
			echo "failed!\n";
632
	}
633

    
634
	return $res;
635
}
636

    
637

    
638
function system_webgui_start() {
639
	global $config, $g;
640

    
641
	if ($g['booting'])
642
		echo "Starting webConfigurator...";
643

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

    
647
	sleep(1);
648

    
649
	chdir($g['www_path']);
650

    
651
	/* defaults */
652
	$portarg = "80";
653
	$crt = "";
654
	$key = "";
655
	$ca = "";
656

    
657
	/* non-standard port? */
658
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
659
		$portarg = "{$config['system']['webgui']['port']}";
660

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

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

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

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

    
710
	if ($g['booting']) {
711
		if ($res == 0)
712
			echo "done.\n";
713
		else
714
			echo "failed!\n";
715
	}
716

    
717
	return $res;
718
}
719

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

    
734
	global $config, $g;
735

    
736
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
737
		mkdir("{$g['tmp_path']}/lighttpdcompress");
738

    
739
	if(isset($config['system']['developerspew'])) {
740
		$mt = microtime();
741
		echo "system_generate_lighty_config() being called $mt\n";
742
	}
743

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

    
771
	$memory = get_memory();
772
	$avail = $memory[0];
773

    
774
	if($avail > 0 and $avail < 65) {
775
		$fast_cgi_enable = false;
776
	}
777

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

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

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

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

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

    
839
#### CGI module
840
cgi.assign                 = ( ".cgi" => "" )
841

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

    
851
EOD;
852
	}
853

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

    
863
## FreeBSD!
864
server.event-handler	= "freebsd-kqueue"
865
server.network-backend 	= "writev"
866

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

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

    
891
server.max-keep-alive-requests = 15
892
server.max-keep-alive-idle = 30
893

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

    
899
# Maximum idle time with nothing being written (php downloading)
900
server.max-write-idle = 999
901

    
902
## where to send error-messages to
903
server.errorlog             = "/var/log/lighttpd.error.log"
904

    
905
# files to check for if .../ is requested
906
server.indexfiles           = ( "index.php", "index.html",
907
                                "index.htm", "default.htm" )
908

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

    
962
# Use the "Content-Type" extended attribute to obtain mime type if possible
963
#mimetypes.use-xattr        = "enable"
964

    
965
#### accesslog module
966
#accesslog.filename          = "/dev/null"
967

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

    
975

    
976
######### Options that are good to be but not neccesary to be changed #######
977

    
978
## bind to port (default: 80)
979
server.port                = {$lighty_port}
980

    
981
## error-handler for status 404
982
#server.error-handler-404   = "/error-handler.html"
983
#server.error-handler-404   = "/error-handler.php"
984

    
985
## to help the rc.scripts
986
server.pid-file            = "/var/run/{$pid_file}"
987

    
988
## virtual directory listings
989
server.dir-listing         = "disable"
990

    
991
## enable debugging
992
debug.log-request-header   = "disable"
993
debug.log-response-header  = "disable"
994
debug.log-request-handling = "disable"
995
debug.log-file-not-found   = "disable"
996

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

    
1001
{$server_upload_dirs}
1002

    
1003
{$server_max_request_size}
1004

    
1005
{$fastcgi_config}
1006

    
1007
{$cgi_config}
1008

    
1009
{$captive_portal_mod_evasive}
1010

    
1011
expire.url = (
1012
				"" => "access 50 hours",	
1013
        )
1014

    
1015
EOD;
1016

    
1017
	$cert = str_replace("\r", "", $cert);
1018
	$key = str_replace("\r", "", $key);
1019
	$ca = str_replace("\r", "", $ca);
1020

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

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

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

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

    
1075
	return 0;
1076

    
1077
}
1078

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

    
1086
	$syscfg = $config['system'];
1087

    
1088
	if ($g['booting'])
1089
		echo "Setting timezone...";
1090

    
1091
	/* extract appropriate timezone file */
1092
	$timezone = $syscfg['timezone'];
1093
	if (!$timezone)
1094
		$timezone = "Etc/UTC";
1095

    
1096
	conf_mount_rw();
1097

    
1098
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1099
		escapeshellarg($timezone) . " > /etc/localtime");
1100

    
1101
	mwexec("sync");
1102
	conf_mount_ro();
1103

    
1104
	if ($g['booting'])
1105
		echo "done.\n";
1106
}
1107

    
1108
function system_ntp_configure() {
1109
	global $config, $g;
1110

    
1111
	$syscfg = $config['system'];
1112

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

    
1120
	fwrite($fd, "# \n");
1121
	fwrite($fd, "# pfSense OpenNTPD configuration file \n");
1122
	fwrite($fd, "# \n\n");
1123

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

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

    
1144
	fwrite($fd, "\n");
1145

    
1146
	/* slurp! */
1147
	fclose($fd);
1148

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

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

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

    
1167
}
1168

    
1169
function sync_system_time() {
1170
	global $config, $g;
1171

    
1172
	$syscfg = $config['system'];
1173

    
1174
	if ($g['booting'])
1175
		echo "Syncing system time before startup...";
1176

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

    
1187
function system_halt() {
1188
	global $g;
1189

    
1190
	system_reboot_cleanup();
1191

    
1192
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1193
}
1194

    
1195
function system_reboot() {
1196
	global $g;
1197

    
1198
	system_reboot_cleanup();
1199

    
1200
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1201
}
1202

    
1203
function system_reboot_sync() {
1204
	global $g;
1205

    
1206
	system_reboot_cleanup();
1207

    
1208
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1209
}
1210

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

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

    
1226
	if ($early)
1227
		$cmdn = "earlyshellcmd";
1228
	else
1229
		$cmdn = "shellcmd";
1230

    
1231
	if (is_array($config['system'][$cmdn])) {
1232

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

    
1238
	} elseif($config['system'][$cmdn] <> "") {
1239

    
1240
		/* execute single item */
1241
		exec($config['system'][$cmdn]);
1242

    
1243
	}
1244
}
1245

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

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

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

    
1267
	$dmesg = "";
1268
	exec("/sbin/dmesg", $dmesg);
1269

    
1270
	/* find last copyright line (output from previous boots may be present) */
1271
	$lastcpline = 0;
1272

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

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

    
1284
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1285
		fwrite($fd, $dmesg[$i] . "\n");
1286

    
1287
	fclose($fd);
1288

    
1289
	return 0;
1290
}
1291

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

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

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

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

    
1331
	activate_sysctls();	
1332

    
1333
	if (isset($config['system']['sharednet'])) {
1334
		system_disable_arp_wrong_if();
1335
	}
1336
}
1337

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

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

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

    
1376
function system_check_reset_button() {
1377
	global $g;
1378
	if($g['platform'] != "nanobsd")
1379
		return 0;
1380

    
1381
	$specplatform = system_identify_specific_platform();
1382

    
1383
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1384
		return 0;
1385

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

    
1388
	if ($retval == 99) {
1389
		/* user has pressed reset button for 2 seconds - 
1390
		   reset to factory defaults */
1391
		echo <<<EOD
1392

    
1393
***********************************************************************
1394
* Reset button pressed - resetting configuration to factory defaults. *
1395
* The system will reboot after this completes.                        *
1396
***********************************************************************
1397

    
1398

    
1399
EOD;
1400
		
1401
		reset_factory_defaults();
1402
		system_reboot_sync();
1403
		exit(0);
1404
	}
1405

    
1406
	return 0;
1407
}
1408

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

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

    
1448
function system_get_dmesg_boot() {
1449
	global $g;
1450
		
1451
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1452
}
1453

    
1454
?>
(40-40/53)