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
	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
			if (!empty($interface) && $interface != $rtent['interface'])
359
				continue;
360
			$gatewayip = "";
361
			if (isset($gateways_arr[$rtent['gateway']])) {
362
				$gatewayip = $gateways_arr[$rtent['gateway']]['gateway'];
363
				$interfacegw = get_real_interface($rtent['interface']);
364
			} else if (is_ipaddr($rtent['gateway'])) {
365
				$gatewayip = $rtent['gateway'];
366
			} else {
367
				log_error("Static Routes: Gateway IP could not be found for {$rtent['network']}");
368
				continue;
369
			}
370

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

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

    
385
	return 0;
386
}
387

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

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

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

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

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

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

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

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

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

    
552
EOD;
553

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

    
563
EOD;
564

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

    
574
EOD;
575

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

    
582
EOD;
583

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

    
589
EOD;
590

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

    
596
EOD;
597

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

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

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

    
614
	return $retval;
615
}
616

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

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

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

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

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

    
640
	return $res;
641
}
642

    
643

    
644
function system_webgui_start() {
645
	global $config, $g;
646

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

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

    
653
	sleep(1);
654

    
655
	chdir($g['www_path']);
656

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

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

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

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

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

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

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

    
723
	return $res;
724
}
725

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

    
740
	global $config, $g;
741

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

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

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

    
777
	$memory = get_memory();
778
	$avail = $memory[0];
779

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

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

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

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

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

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

    
845
#### CGI module
846
cgi.assign                 = ( ".cgi" => "" )
847

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

    
857
EOD;
858
	}
859

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

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

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

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

    
897
server.max-keep-alive-requests = 15
898
server.max-keep-alive-idle = 30
899

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

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

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

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

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

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

    
971
#### accesslog module
972
#accesslog.filename          = "/dev/null"
973

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

    
981

    
982
######### Options that are good to be but not neccesary to be changed #######
983

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

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

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

    
994
## virtual directory listings
995
server.dir-listing         = "disable"
996

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

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

    
1007
{$server_upload_dirs}
1008

    
1009
{$server_max_request_size}
1010

    
1011
{$fastcgi_config}
1012

    
1013
{$cgi_config}
1014

    
1015
{$captive_portal_mod_evasive}
1016

    
1017
expire.url = (
1018
				"" => "access 50 hours",	
1019
        )
1020

    
1021
EOD;
1022

    
1023
	$cert = str_replace("\r", "", $cert);
1024
	$key = str_replace("\r", "", $key);
1025
	$ca = str_replace("\r", "", $ca);
1026

    
1027
	$cert = str_replace("\n\n", "\n", $cert);
1028
	$key = str_replace("\n\n", "\n", $key);
1029
	$ca = str_replace("\n\n", "\n", $ca);
1030

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

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

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

    
1081
	return 0;
1082

    
1083
}
1084

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

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

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

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

    
1102
	conf_mount_rw();
1103

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

    
1107
	mwexec("sync");
1108
	conf_mount_ro();
1109

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

    
1114
function system_ntp_configure() {
1115
	global $config, $g;
1116

    
1117
	$syscfg = $config['system'];
1118

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

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

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

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

    
1150
	fwrite($fd, "\n");
1151

    
1152
	/* slurp! */
1153
	fclose($fd);
1154

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

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

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

    
1173
}
1174

    
1175
function sync_system_time() {
1176
	global $config, $g;
1177

    
1178
	$syscfg = $config['system'];
1179

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

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

    
1193
function system_halt() {
1194
	global $g;
1195

    
1196
	system_reboot_cleanup();
1197

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

    
1201
function system_reboot() {
1202
	global $g;
1203

    
1204
	system_reboot_cleanup();
1205

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

    
1209
function system_reboot_sync() {
1210
	global $g;
1211

    
1212
	system_reboot_cleanup();
1213

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

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

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

    
1232
	if ($early)
1233
		$cmdn = "earlyshellcmd";
1234
	else
1235
		$cmdn = "shellcmd";
1236

    
1237
	if (is_array($config['system'][$cmdn])) {
1238

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

    
1244
	} elseif($config['system'][$cmdn] <> "") {
1245

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

    
1249
	}
1250
}
1251

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

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

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

    
1273
	$dmesg = "";
1274
	exec("/sbin/dmesg", $dmesg);
1275

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

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

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

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

    
1293
	fclose($fd);
1294

    
1295
	return 0;
1296
}
1297

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

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

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

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

    
1337
	activate_sysctls();	
1338

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

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

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

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

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

    
1387
	$specplatform = system_identify_specific_platform();
1388

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

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

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

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

    
1404

    
1405
EOD;
1406
		
1407
		reset_factory_defaults();
1408
		system_reboot_sync();
1409
		exit(0);
1410
	}
1411

    
1412
	return 0;
1413
}
1414

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

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

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

    
1460
?>
(40-40/54)