Project

General

Profile

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

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

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

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

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

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

    
32
/*
33
	pfSense_BUILDER_BINARIES:	/usr/sbin/powerd	/usr/bin/killall	/sbin/sysctl	/sbin/route
34
	pfSense_BUILDER_BINARIES:	/bin/hostname	/bin/ls	/usr/bin/netstat	/usr/sbin/syslogd	
35
	pfSense_BUILDER_BINARIES:	/usr/sbin/pccardd	/usr/local/sbin/lighttpd	/bin/chmod 	/bin/mkdir
36
	pfSense_BUILDER_BINARIES:	/usr/bin/tar		/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

    
56
	if (isset($sysctls[$id]))
57
		return $sysctls[$id];
58
}
59

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

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

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

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

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

    
89
	$resolvconf = "domain {$syscfg['domain']}\n";
90

    
91
	$havedns = false;
92

    
93
	if (isset($syscfg['dnsallowoverride'])) {
94
		/* get dynamically assigned DNS servers (if any) */
95
		$ns = array_unique(get_searchdomains());
96
		foreach($ns as $searchserver) {
97
			if($searchserver) {
98
				$resolvconf .= "search {$searchserver}\n";
99
				$havedns = true;
100
			}
101
		}
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
	$fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
120
	if (!$fd) {
121
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
122
		return 1;
123
	}
124

    
125
	fwrite($fd, $resolvconf);
126
	fclose($fd);
127

    
128
	if (!$g['booting']) {
129
		/* restart dhcpd (nameservers may have changed) */
130
		if (!$dynupdate)
131
			services_dhcpd_configure();
132
	}
133

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

    
155
function get_searchdomains() {
156
	global $config, $g;
157

    
158
	$master_list = array();
159
	
160
	// Read in dhclient nameservers
161
	$search_list = glob("/var/etc/searchdomain_*");
162
	if (is_array($search_lists)) {
163
		foreach($search_lists as $fdns) {
164
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
165
			if (!is_array($contents))
166
				continue;
167
			foreach ($contents as $dns) {
168
				if(is_hostname($dns)) 
169
					$master_list[] = $dns;
170
			}
171
		}
172
	}
173

    
174
	return $master_list;
175
}
176

    
177
function get_nameservers() {
178
	global $config, $g;
179
	$master_list = array();
180
	
181
	// Read in dhclient nameservers
182
	$dns_lists = glob("/var/etc/nameserver_*");
183
	if (is_array($dns_lists)) {
184
		foreach($dns_lists as $fdns) {
185
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
186
			if (!is_array($contents))
187
				continue;
188
			foreach ($contents as $dns) {
189
				if(is_ipaddr($dns)) 
190
					$master_list[] = $dns;
191
			}
192
		}
193
	}
194

    
195
	// Read in any extra nameservers
196
	if(file_exists("/var/etc/nameservers.conf")) {
197
		$dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
198
		if(is_array($dns_s)) {
199
			foreach($dns_s as $dns)
200
				if (is_ipaddr($dns))
201
					$master_list[] = $dns;
202
		}
203
	}
204

    
205
	return $master_list;
206
}
207

    
208
function system_hosts_generate() {
209
	global $config, $g;
210
	if(isset($config['system']['developerspew'])) {
211
		$mt = microtime();
212
		echo "system_hosts_generate() being called $mt\n";
213
	}
214

    
215
	$syscfg = $config['system'];
216
	$dnsmasqcfg = $config['dnsmasq'];
217

    
218
	if (!is_array($dnsmasqcfg['hosts'])) {
219
		$dnsmasqcfg['hosts'] = array();
220
	}
221
	$hostscfg = $dnsmasqcfg['hosts'];
222

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

    
225
	if ($config['interfaces']['lan']) {
226
		$cfgip = get_interface_ip("lan");
227
		if (is_ipaddr($cfgip))
228
			$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
229
	} else {
230
		$sysiflist = get_configured_interface_list();
231
		foreach ($sysiflist as $sysif) {
232
			if (!interface_has_gateway($sysif)) {
233
				$cfgip = get_interface_ip($sysif);
234
				if (is_ipaddr($cfgip)) {
235
					$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
236
					break;
237
				}
238
			}
239
		}
240
	}
241

    
242
	foreach ($hostscfg as $host) {
243
		if ($host['host'])
244
			$hosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
245
		else
246
			$hosts .= "{$host['ip']}	{$host['domain']}\n";
247
	}
248
	if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpd'])) {
249
		foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf)
250
			if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
251
					foreach ($dhcpifconf['staticmap'] as $host)
252
						if ($host['ipaddr'] && $host['hostname'])
253
							$hosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
254
	}
255

    
256
	/*
257
	 * Do not remove this because dhcpleases monitors with kqueue it needs to be 
258
	 * killed before writing to hosts files.
259
	 */
260
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
261
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
262
                @unlink("{$g['varrun_path']}/dhcpleases.pid");
263
	}
264
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
265
	if (!$fd) {
266
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
267
		return 1;
268
	}
269
	fwrite($fd, $hosts);
270
	fclose($fd);
271

    
272
	system_dhcpleases_configure();
273

    
274
	return 0;
275
}
276

    
277
function system_dhcpleases_configure() {
278
	global $config, $g;
279
	
280
	/* Start the monitoring process for dynamic dhcpclients. */
281
	if (isset($config['dnsmasq']['regdhcp'])) {
282
		/* Make sure we do not error out */
283
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
284
		if (file_exists("{$g['varrun_path']}/dhcpleases.pid"))
285
				sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "HUP");
286
		else
287
			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");
288
	} else {
289
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
290
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
291
	}
292
}
293

    
294
function system_hostname_configure() {
295
	global $config, $g;
296
	if(isset($config['system']['developerspew'])) {
297
		$mt = microtime();
298
		echo "system_hostname_configure() being called $mt\n";
299
	}
300

    
301
	$syscfg = $config['system'];
302

    
303
	/* set hostname */
304
	$status = mwexec("/bin/hostname " .
305
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
306

    
307
    /* Setup host GUID ID.  This is used by ZFS. */
308
	mwexec("/etc/rc.d/hostid start");
309

    
310
	return $status;
311
}
312

    
313
function system_routing_configure($interface = "") {
314
	global $config, $g;
315
	if(isset($config['system']['developerspew'])) {
316
		$mt = microtime();
317
		echo "system_routing_configure() being called $mt\n";
318
	}
319

    
320
	$gatewayip = "";
321
	$interfacegw = "";
322
	$foundgw = false;
323
	/* tack on all the hard defined gateways as well */
324
	if (is_array($config['gateways']['gateway_item'])) {
325
		mwexec("/bin/rm {$g['tmp_path']}/*_defaultgw", true);
326
		foreach	($config['gateways']['gateway_item'] as $gateway) {
327
			if (isset($gateway['defaultgw'])) {
328
				if ($gateway['gateway'] == "dynamic")
329
					$gateway['gateway'] = get_interface_gateway($gateway['interface']);
330
				$gatewayip = $gateway['gateway'];
331
				$interfacegw = $gateway['interface'];
332
				if (!empty($interfacegw)) {
333
					$defaultif = get_real_interface($gateway['interface']);
334
					if ($defaultif)
335
						@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gatewayip);
336
				}
337
				$foundgw = true;
338
				break;
339
			}
340
		}
341
	}
342
	if ($foundgw == false) {
343
		$defaultif = get_real_interface("wan");
344
		$interfacegw = "wan";
345
		$gatewayip = get_interface_gateway("wan");
346
		@touch("{$g['tmp_path']}/{$defaultif}_defaultgw");
347
	}	
348
	$dont_add_route = false;
349
	/* if OLSRD is enabled, allow WAN to house DHCP. */
350
	if($config['installedpackages']['olsrd']) {
351
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
352
			if($olsrd['enabledyngw'] == "on") {
353
				$dont_add_route = true;
354
				break;
355
			}
356
		}
357
	}
358
	/* Create a array from the existing route table */
359
	exec("/usr/bin/netstat -rnf inet", $route_str);
360
	array_shift($route_str);
361
	array_shift($route_str);
362
	array_shift($route_str);
363
	array_shift($route_str);
364
	$route_arr = array();
365
	foreach($route_str as $routeline) {
366
		$items = preg_split("/[ ]+/i", $routeline);
367
		$route_arr[$items[0]] = array($items[0], $items[1], $items[5]);
368
	}
369

    
370
	if ($dont_add_route == false ) {
371
		if (!empty($interface) && $interface != $interfacegw)
372
			;
373
		else if (($interfacegw <> "bgpd") && (is_ipaddr($gatewayip))) {
374
			$action = "add";
375
			if(isset($route_arr['default'])) {
376
				$action = "change";
377
			}
378
			log_error("ROUTING: $action default route to $gatewayip");
379
			mwexec("/sbin/route {$action} default " . escapeshellarg($gatewayip));
380
		}
381
	}
382

    
383
	if (is_array($config['staticroutes']['route'])) {
384
		$gateways_arr = return_gateways_array();
385

    
386
		foreach ($config['staticroutes']['route'] as $rtent) {
387
			$gatewayip = "";
388
			if (empty($gateways_arr[$rtent['gateway']])) {
389
				log_error("Static Routes: Gateway IP could not be found for {$rtent['network']}");
390
				continue;
391
			}
392
			$gateway = $gateways_arr[$rtent['gateway']];
393
			if ($interface == $gateway['friendlyiface'])
394
				continue;
395
			$gatewayip = $gateway['gateway'];
396
			$interfacegw = $gateway['interface'];
397
			$action = "add";
398
			if (isset($route_arr[$rtent['network']]))
399
				$action = "change";
400

    
401
			if (is_ipaddr($gatewayip)) {
402
				mwexec("/sbin/route {$action} " . escapeshellarg($rtent['network']) .
403
					" " . escapeshellarg($gatewayip));
404
			} else if (!empty($interfacegw)) {
405
				mwexec("/sbin/route {$action} " . escapeshellarg($rtent['network']) .
406
					" -iface " . escapeshellarg($interfacegw));
407
			}
408
		}
409
	}
410

    
411
	return 0;
412
}
413

    
414
function system_routing_enable() {
415
	global $config, $g;
416
	if(isset($config['system']['developerspew'])) {
417
		$mt = microtime();
418
		echo "system_routing_enable() being called $mt\n";
419
	}
420

    
421
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
422
}
423

    
424
function system_syslogd_start() {
425
	global $config, $g;
426
	if(isset($config['system']['developerspew'])) {
427
		$mt = microtime();
428
		echo "system_syslogd_start() being called $mt\n";
429
	}
430

    
431
	$syslogcfg = $config['syslog'];
432

    
433
	if ($g['booting'])
434
		echo "Starting syslog...";
435
	else
436
		killbypid("{$g['varrun_path']}/syslog.pid");
437

    
438
	if(is_process_running("syslogd"))
439
		mwexec("/usr/bin/killall -9 syslogd");
440
	if(is_process_running("fifolog_writer"))
441
		mwexec("/usr/bin/killall -9 fifolog_writer");
442
	
443
	// Define carious commands for logging
444
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
445
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
446
	$clog_create = "/usr/sbin/clog -i -s ";
447
	$clog_log = "%";
448

    
449
	// Which logging type are we using this week??
450
	if(isset($config['system']['usefifolog'])) {
451
		$log_directive = $fifolog_log;
452
		$log_create_directive = $fifolog_create;		
453
	} else { // Defaults to CLOG
454
		$log_directive = $clog_log;
455
		$log_create_directive = $clog_create;
456
	}
457
	
458
	if (isset($syslogcfg)) {
459
		$separatelogfacilities = array('ntpd','racoon','openvpn','pptps','poes','l2tps');
460
		if($config['installedpackages']['package']) {
461
			foreach($config['installedpackages']['package'] as $package) {
462
				if($package['logging']) {
463
					array_push($separatelogfacilities, $package['logging']['facilityname']);
464
					mwexec("{$log_create_directive} 10240 {$g['varlog_path']}/{$package['logging']['logfilename']}");
465
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
466
				}
467
			}
468
		}
469
		$facilitylist = implode(',', array_unique($separatelogfacilities));
470
		/* write syslog.conf */		
471
		$fd = fopen("{$g['varetc_path']}/syslog.conf", "w");
472
		if (!$fd) {
473
			printf("Error: cannot open syslog.conf in system_syslogd_start().\n");
474
			return 1;
475
		}
476
		$syslogconf .= "!ntpdate,!ntpd\n";
477
		if (!isset($syslogcfg['disablelocallogging'])) 
478
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/ntpd.log\n";
479
		$syslogconf .= "!ppp\n";
480
		if (!isset($syslogcfg['disablelocallogging'])) 
481
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/ppp.log\n";
482
		$syslogconf .= "!pptps\n";
483
		if (!isset($syslogcfg['disablelocallogging'])) 
484
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/pptps.log\n";
485
		$syslogconf .= "!poes\n";
486
		if (!isset($syslogcfg['disablelocallogging'])) 
487
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/poes.log\n";
488
		$syslogconf .= "!l2tps\n";
489
		if (!isset($syslogcfg['disablelocallogging'])) 
490
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/l2tps.log\n";
491
		$syslogconf .= "!racoon\n";
492
		if (!isset($syslogcfg['disablelocallogging'])) 
493
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/ipsec.log\n";
494
		if (isset($syslogcfg['vpn'])) {
495
			if($syslogcfg['remoteserver'])
496
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver']}\n";
497
			if($syslogcfg['remoteserver2'])
498
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver2']}\n";
499
			if($syslogcfg['remoteserver3'])
500
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver3']}\n";
501
		}
502
		$syslogconf .= "!openvpn\n";
503
		if (!isset($syslogcfg['disablelocallogging'])) 
504
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/openvpn.log\n";
505
		if (isset($syslogcfg['vpn'])) {
506
			if($syslogcfg['remoteserver'])
507
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver']}\n";
508
			if($syslogcfg['remoteserver2'])
509
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver3']}\n";
510
			if($syslogcfg['remoteserver3'])
511
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver3']}\n";
512
		}
513
		$syslogconf .= "!apinger\n";
514
		if (!isset($syslogcfg['disablelocallogging']))
515
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/apinger.log\n";
516
		$syslogconf .= "!relayd\n";
517
		$syslogconf .= "*.* 						{$log_directive}{$g['varlog_path']}/relayd.log\n";
518
		$syslogconf .= "!-{$facilitylist}\n";
519
		if (!isset($syslogcfg['disablelocallogging'])) 
520
			$syslogconf .= <<<EOD
521
local0.*										 {$log_directive}{$g['varlog_path']}/filter.log
522
local3.*										 {$log_directive}{$g['varlog_path']}/vpn.log
523
local4.*										 {$log_directive}{$g['varlog_path']}/portalauth.log
524
local7.*										 {$log_directive}{$g['varlog_path']}/dhcpd.log
525
*.notice;kern.debug;lpr.info;mail.crit; 		 {$log_directive}{$g['varlog_path']}/system.log
526
news.err;local0.none;local3.none;local4.none; 	 {$log_directive}{$g['varlog_path']}/system.log
527
local7.none										 {$log_directive}{$g['varlog_path']}/system.log
528
security.*										 {$log_directive}{$g['varlog_path']}/system.log
529
auth.info;authpriv.info;daemon.info				 {$log_directive}{$g['varlog_path']}/system.log
530
auth.info;authpriv.info 						 |exec /usr/local/sbin/sshlockout_pf 15
531
*.emerg											 *
532

    
533
EOD;
534
		if (isset($syslogcfg['filter'])) {
535
			if($syslogcfg['remoteserver'])
536
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver']}\n";
537
			if($syslogcfg['remoteserver2'])
538
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver2']}\n";
539
			if($syslogcfg['remoteserver3'])
540
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver3']}\n";
541

    
542
		}
543
		if (isset($syslogcfg['vpn'])) {
544
			if($syslogcfg['remoteserver'])
545
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver']}\n";
546
			if($syslogcfg['remoteserver2'])
547
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver2']}\n";
548
			if($syslogcfg['remoteserver3'])
549
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver3']}\n";
550
		}
551
		if (isset($syslogcfg['portalauth'])) {
552
			if($syslogcfg['remoteserver'])
553
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver']}\n";
554
			if($syslogcfg['remoteserver2'])
555
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver2']}\n";
556
			if($syslogcfg['remoteserver3'])
557
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver3']}\n";
558
		}
559
		if (isset($syslogcfg['dhcp'])) {
560
			if($syslogcfg['remoteserver'])
561
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver']}\n";
562
			if($syslogcfg['remoteserver2'])
563
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver2']}\n";
564
			if($syslogcfg['remoteserver3'])
565
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver3']}\n";
566
		}
567
		if (isset($syslogcfg['system'])) {
568
			if($syslogcfg['remoteserver'])
569
				$syslogconf .= <<<EOD
570
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver']}
571
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver']}
572
security.*										 @{$syslogcfg['remoteserver']}
573
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver']}
574
*.emerg											 @{$syslogcfg['remoteserver']}
575

    
576
EOD;
577

    
578
}
579

    
580
		if (isset($syslogcfg['system'])) {
581
			if($syslogcfg['remoteserver2'])
582
				$syslogconf .= <<<EOD
583
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver2']}
584
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver2']}
585
security.*										 @{$syslogcfg['remoteserver2']}
586
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver2']}
587
*.emerg											 @{$syslogcfg['remoteserver2']}
588

    
589
EOD;
590

    
591
}
592

    
593
		if (isset($syslogcfg['system'])) {
594
			if($syslogcfg['remoteserver3'])
595
				$syslogconf .= <<<EOD
596
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver3']}
597
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver3']}
598
security.*										 @{$syslogcfg['remoteserver3']}
599
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver3']}
600
*.emerg											 @{$syslogcfg['remoteserver3']}
601

    
602
EOD;
603

    
604
}
605
		if (isset($syslogcfg['logall'])) {
606
			if($syslogcfg['remoteserver'])
607
				$syslogconf .= <<<EOD
608
*.*								@{$syslogcfg['remoteserver']}
609

    
610
EOD;
611

    
612
			if($syslogcfg['remoteserver2'])
613
				$syslogconf .= <<<EOD
614
*.*								@{$syslogcfg['remoteserver2']}
615

    
616
EOD;
617

    
618
			if($syslogcfg['remoteserver3'])
619
				$syslogconf .= <<<EOD
620
*.*								@{$syslogcfg['remoteserver3']}
621

    
622
EOD;
623

    
624
}
625
		fwrite($fd, $syslogconf);
626
		fclose($fd);
627

    
628
		// Ensure that the log directory exists
629
		if(!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
630
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
631

    
632
		// Are we logging to a least one remote server ?
633
		if(strpos($syslogconf, "@") != false)
634
			$retval = system("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log -f {$g['varetc_path']}/syslog.conf");
635
		else
636
			$retval = system("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log -f {$g['varetc_path']}/syslog.conf");
637

    
638
	} else {
639
		$retval = mwexec("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log");
640
	}
641

    
642
	if ($g['booting'])
643
		echo "done.\n";
644

    
645
	return $retval;
646
}
647

    
648
function system_pccard_start() {
649
	global $config, $g;
650
	if(isset($config['system']['developerspew'])) {
651
		$mt = microtime();
652
		echo "system_pccard_start() being called $mt\n";
653
	}
654

    
655
	if ($g['booting'])
656
		echo "Initializing PCMCIA...";
657

    
658
	/* kill any running pccardd */
659
	killbypid("{$g['varrun_path']}/pccardd.pid");
660

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

    
664
	if ($g['booting']) {
665
		if ($res == 0)
666
			echo "done.\n";
667
		else
668
			echo "failed!\n";
669
	}
670

    
671
	return $res;
672
}
673

    
674

    
675
function system_webgui_start() {
676
	global $config, $g;
677

    
678
	if ($g['booting'])
679
		echo "Starting webConfigurator...";
680

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

    
684
	sleep(1);
685

    
686
	chdir($g['www_path']);
687

    
688
	/* defaults */
689
	$portarg = "80";
690
	$crt = "";
691
	$key = "";
692
	$ca = "";
693

    
694
	/* non-standard port? */
695
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
696
		$portarg = "{$config['system']['webgui']['port']}";
697

    
698
	if ($config['system']['webgui']['protocol'] == "https") {
699
		// Ensure that we have a webConfigurator CERT
700
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
701
		if(!is_array($cert) && !$cert['crt'] && !$cert['prv']) {
702
			if (!is_array($config['ca']))
703
				$config['ca'] = array();
704
			$a_ca =& $config['ca'];
705
			if (!is_array($config['cert']))
706
				$config['cert'] = array();
707
			$a_cert =& $config['cert'];
708
			log_error("Creating SSL Certificate for this host");
709
			$cert = array();
710
			$cert['refid'] = uniqid();
711
			$cert['descr'] = "webConfigurator default";
712
			mwexec("/usr/bin/openssl genrsa 1024 > {$g['tmp_path']}/ssl.key");
713
			mwexec("/usr/bin/openssl req -new -x509 -nodes -sha1 -days 2000 -key {$g['tmp_path']}/ssl.key > {$g['tmp_path']}/ssl.crt");
714
			$crt = file_get_contents("{$g['tmp_path']}/ssl.crt");
715
			$key = file_get_contents("{$g['tmp_path']}/ssl.key");
716
			unlink("{$g['tmp_path']}/ssl.key");
717
			unlink("{$g['tmp_path']}/ssl.crt");
718
			cert_import($cert, $crt, $key);
719
			$a_cert[] = $cert;
720
			$config['system']['webgui']['ssl-certref'] = $cert['refid'];
721
			write_config("Importing HTTPS certificate");
722
			if(!$config['system']['webgui']['port'])
723
				$portarg = "443";
724
			$ca = ca_chain($cert);
725
		} else {
726
			$crt = base64_decode($cert['crt']);
727
			$key = base64_decode($cert['prv']);
728
			if(!$config['system']['webgui']['port'])
729
				$portarg = "443";
730
			$ca = ca_chain($cert);
731
		}
732
	}
733

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

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

    
741
	/* fetch page to preload apc cache */
742
	$proto = "http";
743
	if ($config['system']['webgui']['protocol'])
744
		$proto = $config['system']['webgui']['protocol'];
745
	mwexec_bg("/usr/bin/fetch -o /dev/null -q {$proto}://localhost:{$portarg}/preload.php");
746

    
747
	if ($g['booting']) {
748
		if ($res == 0)
749
			echo "done.\n";
750
		else
751
			echo "failed!\n";
752
	}
753

    
754
	return $res;
755
}
756

    
757
function system_generate_lighty_config($filename,
758
	$cert,
759
	$key,
760
	$ca,
761
	$pid_file,
762
	$port = 80,
763
	$document_root = "/usr/local/www/",
764
	$cert_location = "cert.pem",
765
	$ca_location = "ca.pem",
766
	$max_procs = 2,
767
	$max_requests = "2",
768
	$fast_cgi_enable = true,
769
	$captive_portal = false) {
770

    
771
	global $config, $g;
772

    
773
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
774
		mkdir("{$g['tmp_path']}/lighttpdcompress");
775

    
776
	if(isset($config['system']['developerspew'])) {
777
		$mt = microtime();
778
		echo "system_generate_lighty_config() being called $mt\n";
779
	}
780

    
781
	if($captive_portal == true)  {
782
		$captiveportal = ",\"mod_rewrite\"";
783
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?redirurl=$1\" )\n";
784
		$captive_portal_module = "\"mod_accesslog\", ";
785
		$maxprocperip = $config['captiveportal']['maxprocperip'];
786
		if(!$maxprocperip and $maxprocperip > 0)
787
			$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
788
		else
789
			$captive_portal_mod_evasive = "";
790
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
791
		exec("mkdir -p {$g['tmp_path']}/captiveportal");
792
		exec("chmod a-w {$g['tmp_path']}/captiveportal");
793
		$server_max_request_size = "server.max-request-size    = 384";
794
	} else {
795
		$captiveportal = "";
796
		$captive_portal_rewrite = "";
797
		$captive_portal_module = "";
798
		$captive_portal_mod_evasive = "";
799
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
800
		$server_max_request_size = "server.max-request-size    = 2097152";
801
	}
802
	
803
	if($port <> "")
804
		$lighty_port = $port;
805
	else
806
		$lighty_port = "80";
807

    
808
	$memory = get_memory();
809
	$avail = $memory[0];
810

    
811
	if($avail > 0 and $avail < 65) {
812
		$fast_cgi_enable = false;
813
	}
814

    
815
	// Ramp up captive portal max procs
816
	if($captive_portal == true)  {
817
		if($avail > 65 and $avail < 98) {
818
			$max_procs = 1;
819
		}
820
		if($avail > 97 and $avail < 128) {
821
			$max_procs = 2;
822
		}
823
		if($avail > 127 and $avail < 256) {
824
			$max_procs = 3;
825
		}
826
		if($avail > 255 and $avail < 384) {
827
			$max_procs = 4;
828
		}
829
		if($avail > 383) {
830
			$max_procs = 5;
831
		}
832
	}
833

    
834
	if($captive_portal == true)  {	
835
		$bin_environment =  <<<EOC
836
        "bin-environment" => (
837
           "PHP_FCGI_CHILDREN" => "$max_procs",
838
           "PHP_FCGI_MAX_REQUESTS" => "500"
839
        ), 
840
EOC;
841

    
842
	} else if ($avail > 0 and $avail < 128) {
843
		$bin_environment = <<<EOC
844
		"bin-environment" => (
845
			"PHP_FCGI_CHILDREN" => "$max_procs",
846
			"PHP_FCGI_MAX_REQUESTS" => "2",
847
	),
848

    
849
EOC;
850
	} else
851
		$bin_environment =  <<<EOC
852
        "bin-environment" => (
853
           "PHP_FCGI_CHILDREN" => "$max_procs",
854
           "PHP_FCGI_MAX_REQUESTS" => "500"
855
        ), 
856
EOC;
857

    
858
	if($fast_cgi_enable == true) {
859
		$module = "\"mod_fastcgi\", \"mod_cgi\"";
860
		$cgi_config = "";
861
		$fastcgi_config = <<<EOD
862
#### fastcgi module
863
## read fastcgi.txt for more info
864
fastcgi.server = ( ".php" =>
865
	( "localhost" =>
866
		(
867
			"socket" => "{$g['tmp_path']}/php-fastcgi.socket",
868
			"min-procs" => 0,
869
			"max-procs" => {$max_procs},
870
			{$bin_environment}			
871
			"bin-path" => "/usr/local/bin/php"
872
		)
873
	)
874
)
875

    
876
#### CGI module
877
cgi.assign                 = ( ".cgi" => "" )
878

    
879
EOD;
880
	} else {
881
		$fastcgi_config = "";
882
		$module = "\"mod_cgi\"";
883
		$cgi_config = <<<EOD
884
#### CGI module
885
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
886
                               ".cgi" => "" )
887

    
888
EOD;
889
	}
890

    
891
	$lighty_config = "";
892
	$lighty_config .= <<<EOD
893
#
894
# lighttpd configuration file
895
#
896
# use a it as base for lighttpd 1.0.0 and above
897
#
898
############ Options you really have to take care of ####################
899

    
900
## FreeBSD!
901
server.event-handler	= "freebsd-kqueue"
902
server.network-backend 	= "writev"
903

    
904
## modules to load
905
server.modules              =   (
906
									{$captive_portal_module}
907
									"mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect",
908
									{$module}{$captiveportal}
909
								)
910

    
911
## Unused modules
912
#                               "mod_setenv",
913
#                               "mod_rewrite",
914
#                               "mod_ssi",
915
#                               "mod_usertrack",
916
#                               "mod_expire",
917
#                               "mod_secdownload",
918
#                               "mod_rrdtool",
919
#                               "mod_auth",
920
#                               "mod_status",
921
#                               "mod_alias",
922
#                               "mod_proxy",
923
#                               "mod_simple_vhost",
924
#                               "mod_evhost",
925
#                               "mod_userdir",
926
#                               "mod_cgi",
927

    
928
server.max-keep-alive-requests = 15
929
server.max-keep-alive-idle = 30
930

    
931
## a static document-root, for virtual-hosting take look at the
932
## server.virtual-* options
933
server.document-root        = "{$document_root}"
934
{$captive_portal_rewrite}
935

    
936
# Maximum idle time with nothing being written (php downloading)
937
server.max-write-idle = 999
938

    
939
## where to send error-messages to
940
server.errorlog             = "/var/log/lighttpd.error.log"
941

    
942
# files to check for if .../ is requested
943
server.indexfiles           = ( "index.php", "index.html",
944
                                "index.htm", "default.htm" )
945

    
946
# mimetype mapping
947
mimetype.assign             = (
948
  ".pdf"          =>      "application/pdf",
949
  ".sig"          =>      "application/pgp-signature",
950
  ".spl"          =>      "application/futuresplash",
951
  ".class"        =>      "application/octet-stream",
952
  ".ps"           =>      "application/postscript",
953
  ".torrent"      =>      "application/x-bittorrent",
954
  ".dvi"          =>      "application/x-dvi",
955
  ".gz"           =>      "application/x-gzip",
956
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
957
  ".swf"          =>      "application/x-shockwave-flash",
958
  ".tar.gz"       =>      "application/x-tgz",
959
  ".tgz"          =>      "application/x-tgz",
960
  ".tar"          =>      "application/x-tar",
961
  ".zip"          =>      "application/zip",
962
  ".mp3"          =>      "audio/mpeg",
963
  ".m3u"          =>      "audio/x-mpegurl",
964
  ".wma"          =>      "audio/x-ms-wma",
965
  ".wax"          =>      "audio/x-ms-wax",
966
  ".ogg"          =>      "audio/x-wav",
967
  ".wav"          =>      "audio/x-wav",
968
  ".gif"          =>      "image/gif",
969
  ".jpg"          =>      "image/jpeg",
970
  ".jpeg"         =>      "image/jpeg",
971
  ".png"          =>      "image/png",
972
  ".xbm"          =>      "image/x-xbitmap",
973
  ".xpm"          =>      "image/x-xpixmap",
974
  ".xwd"          =>      "image/x-xwindowdump",
975
  ".css"          =>      "text/css",
976
  ".html"         =>      "text/html",
977
  ".htm"          =>      "text/html",
978
  ".js"           =>      "text/javascript",
979
  ".asc"          =>      "text/plain",
980
  ".c"            =>      "text/plain",
981
  ".conf"         =>      "text/plain",
982
  ".text"         =>      "text/plain",
983
  ".txt"          =>      "text/plain",
984
  ".dtd"          =>      "text/xml",
985
  ".xml"          =>      "text/xml",
986
  ".mpeg"         =>      "video/mpeg",
987
  ".mpg"          =>      "video/mpeg",
988
  ".mov"          =>      "video/quicktime",
989
  ".qt"           =>      "video/quicktime",
990
  ".avi"          =>      "video/x-msvideo",
991
  ".asf"          =>      "video/x-ms-asf",
992
  ".asx"          =>      "video/x-ms-asf",
993
  ".wmv"          =>      "video/x-ms-wmv",
994
  ".bz2"          =>      "application/x-bzip",
995
  ".tbz"          =>      "application/x-bzip-compressed-tar",
996
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
997
 )
998

    
999
# Use the "Content-Type" extended attribute to obtain mime type if possible
1000
#mimetypes.use-xattr        = "enable"
1001

    
1002
#### accesslog module
1003
#accesslog.filename          = "/dev/null"
1004

    
1005
## deny access the file-extensions
1006
#
1007
# ~    is for backupfiles from vi, emacs, joe, ...
1008
# .inc is often used for code includes which should in general not be part
1009
#      of the document-root
1010
url.access-deny             = ( "~", ".inc" )
1011

    
1012

    
1013
######### Options that are good to be but not neccesary to be changed #######
1014

    
1015
## bind to port (default: 80)
1016
server.port                = {$lighty_port}
1017

    
1018
## error-handler for status 404
1019
#server.error-handler-404   = "/error-handler.html"
1020
#server.error-handler-404   = "/error-handler.php"
1021

    
1022
## to help the rc.scripts
1023
server.pid-file            = "/var/run/{$pid_file}"
1024

    
1025
## virtual directory listings
1026
server.dir-listing         = "disable"
1027

    
1028
## enable debugging
1029
debug.log-request-header   = "disable"
1030
debug.log-response-header  = "disable"
1031
debug.log-request-handling = "disable"
1032
debug.log-file-not-found   = "disable"
1033

    
1034
# gzip compression
1035
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1036
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1037

    
1038
{$server_upload_dirs}
1039

    
1040
{$server_max_request_size}
1041

    
1042
{$fastcgi_config}
1043

    
1044
{$cgi_config}
1045

    
1046
{$captive_portal_mod_evasive}
1047

    
1048
expire.url = (
1049
				"" => "access 50 hours",	
1050
        )
1051

    
1052
EOD;
1053

    
1054
	$cert = str_replace("\r", "", $cert);
1055
	$key = str_replace("\r", "", $key);
1056
	$ca = str_replace("\r", "", $ca);
1057

    
1058
	$cert = str_replace("\n\n", "\n", $cert);
1059
	$key = str_replace("\n\n", "\n", $key);
1060
	$ca = str_replace("\n\n", "\n", $ca);
1061

    
1062
	if($cert <> "" and $key <> "") {
1063
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1064
		if (!$fd) {
1065
			printf("Error: cannot open cert.pem in system_webgui_start().\n");
1066
			return 1;
1067
		}
1068
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1069
		fwrite($fd, $cert);
1070
		fwrite($fd, "\n");
1071
		fwrite($fd, $key);
1072
		fclose($fd);
1073
		if($ca <> "") {
1074
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1075
			if (!$fd) {
1076
				printf("Error: cannot open ca.pem in system_webgui_start().\n");
1077
				return 1;
1078
			}
1079
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1080
			fwrite($fd, $ca);
1081
			fclose($fd);
1082
		}
1083
		$lighty_config .= "\n";
1084
		$lighty_config .= "## ssl configuration\n";
1085
		$lighty_config .= "ssl.engine = \"enable\"\n";
1086
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1087
		if($ca <> "")
1088
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1089
	}
1090

    
1091
	// Add HTTP to HTTPS redirect	
1092
	if ($captive_portal == false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1093
		if($lighty_port != "443") 
1094
			$redirectport = ":{$lighty_port}";
1095
		$lighty_config .= <<<EOD
1096
\$SERVER["socket"] == ":80" {
1097
	\$HTTP["host"] =~ "(.*)" {
1098
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1099
	}
1100
}
1101
EOD;
1102
	}
1103

    
1104
	$fd = fopen("{$filename}", "w");
1105
	if (!$fd) {
1106
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
1107
		return 1;
1108
	}
1109
	fwrite($fd, $lighty_config);
1110
	fclose($fd);
1111

    
1112
	return 0;
1113

    
1114
}
1115

    
1116
function system_timezone_configure() {
1117
	global $config, $g;
1118
	if(isset($config['system']['developerspew'])) {
1119
		$mt = microtime();
1120
		echo "system_timezone_configure() being called $mt\n";
1121
	}
1122

    
1123
	$syscfg = $config['system'];
1124

    
1125
	if ($g['booting'])
1126
		echo "Setting timezone...";
1127

    
1128
	/* extract appropriate timezone file */
1129
	$timezone = $syscfg['timezone'];
1130
	if (!$timezone)
1131
		$timezone = "Etc/UTC";
1132

    
1133
	conf_mount_rw();
1134

    
1135
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1136
		escapeshellarg($timezone) . " > /etc/localtime");
1137

    
1138
	mwexec("sync");
1139
	conf_mount_ro();
1140

    
1141
	if ($g['booting'])
1142
		echo "done.\n";
1143
}
1144

    
1145
function system_ntp_configure() {
1146
	global $config, $g;
1147

    
1148
	$syscfg =& $config['system'];
1149

    
1150
	/* open configuration for wrting or bail */
1151
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1152
	if(!$fd) {
1153
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1154
		return;
1155
	}
1156

    
1157
	fwrite($fd, "# \n");
1158
	fwrite($fd, "# pfSense OpenNTPD configuration file \n");
1159
	fwrite($fd, "# \n\n");
1160

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

    
1165
	/* Setup listener(s) if the user has configured one */
1166
        if ($config['installedpackages']['openntpd']) {
1167
    		/* server config is in coregui1 */
1168
		$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
1169
		if ($xmlsettings['enable'] == 'on') {
1170
			$ifaces = explode(',', $xmlsettings['interface']);
1171
			$ifaces = array_map('get_real_interface', $ifaces);
1172
			$ifaces = array_filter($ifaces, 'does_interface_exist');
1173
			$ips = array_map('find_interface_ip', $ifaces);
1174
			foreach ($ips as $ip) {
1175
				if (is_ipaddr($ip))
1176
					fwrite($fd, "listen on $ip\n");
1177
			}
1178
		}
1179
	}
1180

    
1181
	fwrite($fd, "\n");
1182

    
1183
	/* slurp! */
1184
	fclose($fd);
1185

    
1186
	/* if openntpd is running, kill it */
1187
	while(is_process_running("ntpd")) {
1188
		killbyname("ntpd");
1189
	}
1190

    
1191
	/* if /var/empty does not exist, create it */
1192
	if(!is_dir("/var/empty"))
1193
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1194

    
1195
	if ($g['booting'])
1196
		return;
1197

    
1198
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1199
	exec("/usr/local/sbin/ntpd -s -f {$g['varetc_path']}/ntpd.conf");
1200
	
1201
	// Note that we are starting up
1202
	exec("echo 'OpenNTPD is starting up' >> {$g['varlog_path']}/ntpd.log");
1203

    
1204
}
1205

    
1206
function sync_system_time() {
1207
	global $config, $g;
1208

    
1209
	$syscfg = $config['system'];
1210

    
1211
	if ($g['booting'])
1212
		echo "Syncing system time before startup...";
1213

    
1214
	/* foreach through servers and write out to ntpd.conf */
1215
	foreach (explode(' ', $syscfg['timeservers']) as $ts) {
1216
		mwexec("/usr/sbin/ntpdate -s $ts");
1217
	}
1218
	
1219
	if ($g['booting'])
1220
		echo "done.\n";
1221
	
1222
}
1223

    
1224
function system_halt() {
1225
	global $g;
1226

    
1227
	system_reboot_cleanup();
1228

    
1229
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1230
}
1231

    
1232
function system_reboot() {
1233
	global $g;
1234

    
1235
	system_reboot_cleanup();
1236

    
1237
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1238
}
1239

    
1240
function system_reboot_sync() {
1241
	global $g;
1242

    
1243
	system_reboot_cleanup();
1244

    
1245
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1246
}
1247

    
1248
function system_reboot_cleanup() {
1249
	mwexec("/usr/local/bin/beep.sh stop");
1250
	require_once("captiveportal.inc");
1251
	captiveportal_radius_stop_all();
1252
	require_once("voucher.inc");
1253
	voucher_save_db_to_config();
1254
}
1255

    
1256
function system_do_shell_commands($early = 0) {
1257
	global $config, $g;
1258
	if(isset($config['system']['developerspew'])) {
1259
		$mt = microtime();
1260
		echo "system_do_shell_commands() being called $mt\n";
1261
	}
1262

    
1263
	if ($early)
1264
		$cmdn = "earlyshellcmd";
1265
	else
1266
		$cmdn = "shellcmd";
1267

    
1268
	if (is_array($config['system'][$cmdn])) {
1269

    
1270
		/* *cmd is an array, loop through */
1271
		foreach ($config['system'][$cmdn] as $cmd) {
1272
			exec($cmd);
1273
		}
1274

    
1275
	} elseif($config['system'][$cmdn] <> "") {
1276

    
1277
		/* execute single item */
1278
		exec($config['system'][$cmdn]);
1279

    
1280
	}
1281
}
1282

    
1283
function system_console_configure() {
1284
	global $config, $g;
1285
	if(isset($config['system']['developerspew'])) {
1286
		$mt = microtime();
1287
		echo "system_console_configure() being called $mt\n";
1288
	}
1289

    
1290
	if (isset($config['system']['disableconsolemenu'])) {
1291
		touch("{$g['varetc_path']}/disableconsole");
1292
	} else {
1293
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1294
	}
1295
}
1296

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

    
1304
	$dmesg = "";
1305
	exec("/sbin/dmesg", $dmesg);
1306

    
1307
	/* find last copyright line (output from previous boots may be present) */
1308
	$lastcpline = 0;
1309

    
1310
	for ($i = 0; $i < count($dmesg); $i++) {
1311
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1312
			$lastcpline = $i;
1313
	}
1314

    
1315
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1316
	if (!$fd) {
1317
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1318
		return 1;
1319
	}
1320

    
1321
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1322
		fwrite($fd, $dmesg[$i] . "\n");
1323

    
1324
	fclose($fd);
1325

    
1326
	return 0;
1327
}
1328

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

    
1336
	if (isset($config['system']['harddiskstandby'])) {
1337
		if ($g['booting']) {
1338
			echo 'Setting hard disk standby... ';
1339
		}
1340

    
1341
		$standby = $config['system']['harddiskstandby'];
1342
		// Check for a numeric value
1343
		if (is_numeric($standby)) {
1344
			// Sync the disk(s)
1345
			pfSense_sync();
1346
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1347
				// Reinitialize ATA-drives
1348
				mwexec('/usr/local/sbin/atareinit');
1349
				if ($g['booting']) {
1350
					echo "done.\n";
1351
				}
1352
			} else if ($g['booting']) {
1353
				echo "failed!\n";
1354
			}
1355
		} else if ($g['booting']) {
1356
			echo "failed!\n";
1357
		}
1358
	}
1359
}
1360

    
1361
function system_setup_sysctl() {
1362
	global $config;
1363
	if(isset($config['system']['developerspew'])) {
1364
		$mt = microtime();
1365
		echo "system_setup_sysctl() being called $mt\n";
1366
	}
1367

    
1368
	activate_sysctls();	
1369

    
1370
	if (isset($config['system']['sharednet'])) {
1371
		system_disable_arp_wrong_if();
1372
	}
1373
}
1374

    
1375
function system_disable_arp_wrong_if() {
1376
	global $config;
1377
	if(isset($config['system']['developerspew'])) {
1378
		$mt = microtime();
1379
		echo "system_disable_arp_wrong_if() being called $mt\n";
1380
	}
1381
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1382
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1383
}
1384

    
1385
function system_enable_arp_wrong_if() {
1386
	global $config;
1387
	if(isset($config['system']['developerspew'])) {
1388
		$mt = microtime();
1389
		echo "system_enable_arp_wrong_if() being called $mt\n";
1390
	}
1391
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1392
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1393
}
1394

    
1395
function enable_watchdog() {
1396
	global $config;
1397
	return;
1398
	$install_watchdog = false;
1399
	$supported_watchdogs = array("Geode");
1400
	$file = file_get_contents("/var/log/dmesg.boot");
1401
	foreach($supported_watchdogs as $sd) {
1402
		if(stristr($file, "Geode")) {
1403
			$install_watchdog = true;
1404
		}
1405
	}
1406
	if($install_watchdog == true) {
1407
		if(is_process_running("watchdogd"))
1408
			mwexec("/usr/bin/killall watchdogd", true);
1409
		exec("/usr/sbin/watchdogd");
1410
	}
1411
}
1412

    
1413
function system_check_reset_button() {
1414
	global $g;
1415
	if($g['platform'] != "nanobsd")
1416
		return 0;
1417

    
1418
	$specplatform = system_identify_specific_platform();
1419

    
1420
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1421
		return 0;
1422

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

    
1425
	if ($retval == 99) {
1426
		/* user has pressed reset button for 2 seconds - 
1427
		   reset to factory defaults */
1428
		echo <<<EOD
1429

    
1430
***********************************************************************
1431
* Reset button pressed - resetting configuration to factory defaults. *
1432
* The system will reboot after this completes.                        *
1433
***********************************************************************
1434

    
1435

    
1436
EOD;
1437
		
1438
		reset_factory_defaults();
1439
		system_reboot_sync();
1440
		exit(0);
1441
	}
1442

    
1443
	return 0;
1444
}
1445

    
1446
/* attempt to identify the specific platform (for embedded systems)
1447
   Returns an array with two elements:
1448
	name => platform string (e.g. 'wrap', 'alix' etc.)
1449
	descr => human-readable description (e.g. "PC Engines WRAP")
1450
*/
1451
function system_identify_specific_platform() {
1452
	global $g;
1453
	
1454
	if ($g['platform'] == 'generic-pc')
1455
		return array('name' => 'generic-pc', 'descr' => "Generic PC");
1456
	
1457
	if ($g['platform'] == 'generic-pc-cdrom')
1458
		return array('name' => 'generic-pc-cdrom', 'descr' => "Generic PC (CD-ROM)");
1459
	
1460
	/* the rest of the code only deals with 'embedded' platforms */
1461
	if ($g['platform'] != 'nanobsd')
1462
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1463
	
1464
	$dmesg = system_get_dmesg_boot();
1465
	
1466
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1467
		return array('name' => 'wrap', 'descr' => 'PC Engines WRAP');
1468
	
1469
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1470
		return array('name' => 'alix', 'descr' => 'PC Engines ALIX');
1471

    
1472
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1473
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1474
	
1475
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1476
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1477
		
1478
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1479
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1480
	
1481
	/* unknown embedded platform */
1482
	return array('name' => 'embedded', 'descr' => 'embedded (unknown)');
1483
}
1484

    
1485
function system_get_dmesg_boot() {
1486
	global $g;
1487
		
1488
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1489
}
1490

    
1491
?>
(47-47/61)