Project

General

Profile

Download (42.9 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 $dns) {
164
			if(is_hostname($dns)) 
165
				$master_list[] = $dns;
166
		}
167
	}
168

    
169
	return $master_list;
170
}
171

    
172
function get_nameservers() {
173
	global $config, $g;
174
	$master_list = array();
175
	
176
	// Read in dhclient nameservers
177
	$dns_lists = glob("/var/etc/nameserver_*");
178
	if (is_array($dns_lists)) {
179
		foreach($dns_lists as $dns) {
180
			if(is_ipaddr($dns)) 
181
				$master_list[] = $dns;
182
		}
183
	}
184

    
185
	// Read in any extra nameservers
186
	if(file_exists("/var/etc/nameservers.conf")) {
187
		$dns_lists = split("\n", `/bin/cat /var/etc/nameservers.conf`);
188
		$dns_lists = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
189
		if(is_array($dns_s)) {
190
			foreach($dns_s as $dns)
191
				if (is_ipaddr($dns))
192
					$master_list[] = $dns;
193
		}
194
	}
195

    
196
	return $master_list;
197
}
198

    
199
function system_hosts_generate() {
200
	global $config, $g;
201
	if(isset($config['system']['developerspew'])) {
202
		$mt = microtime();
203
		echo "system_hosts_generate() being called $mt\n";
204
	}
205

    
206
	$syscfg = $config['system'];
207
	$dnsmasqcfg = $config['dnsmasq'];
208

    
209
	if (!is_array($dnsmasqcfg['hosts'])) {
210
		$dnsmasqcfg['hosts'] = array();
211
	}
212
	$hostscfg = $dnsmasqcfg['hosts'];
213

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

    
216
	if ($config['interfaces']['lan']) {
217
		$cfgip = get_interface_ip("lan");
218
		if (is_ipaddr($cfgip))
219
			$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
220
	} else {
221
		$sysiflist = get_configured_interface_list();
222
		foreach ($sysiflist as $sysif) {
223
			if (!interface_has_gateway($sysif)) {
224
				$cfgip = get_interface_ip($sysif);
225
				if (is_ipaddr($cfgip)) {
226
					$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
227
					break;
228
				}
229
			}
230
		}
231
	}
232

    
233
	foreach ($hostscfg as $host) {
234
		if ($host['host'])
235
			$hosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
236
		else
237
			$hosts .= "{$host['ip']}	{$host['domain']}\n";
238
	}
239
	if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpd'])) {
240
		foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf)
241
			if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
242
					foreach ($dhcpifconf['staticmap'] as $host)
243
						if ($host['ipaddr'] && $host['hostname'])
244
							$hosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
245
	}
246

    
247
	/*
248
	 * Do not remove this because dhcpleases monitors with kqueue it needs to be 
249
	 * killed before writing to hosts files.
250
	 */
251
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
252
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
253
                @unlink("{$g['varrun_path']}/dhcpleases.pid");
254
	}
255
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
256
	if (!$fd) {
257
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
258
		return 1;
259
	}
260
	fwrite($fd, $hosts);
261
	fclose($fd);
262

    
263
	system_dhcpleases_configure();
264

    
265
	return 0;
266
}
267

    
268
function system_dhcpleases_configure() {
269
	global $config, $g;
270
	
271
	/* Start the monitoring process for dynamic dhcpclients. */
272
	if (isset($config['dnsmasq']['regdhcp'])) {
273
		/* Make sure we do not error out */
274
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
275
		if (file_exists("{$g['varrun_path']}/dhcpleases.pid"))
276
				sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "HUP");
277
		else
278
			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");
279
	} else {
280
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
281
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
282
	}
283
}
284

    
285
function system_hostname_configure() {
286
	global $config, $g;
287
	if(isset($config['system']['developerspew'])) {
288
		$mt = microtime();
289
		echo "system_hostname_configure() being called $mt\n";
290
	}
291

    
292
	$syscfg = $config['system'];
293

    
294
	/* set hostname */
295
	$status = mwexec("/bin/hostname " .
296
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
297

    
298
    /* Setup host GUID ID.  This is used by ZFS. */
299
	mwexec("/etc/rc.d/hostid start");
300

    
301
	return $status;
302
}
303

    
304
function system_routing_configure($interface = "") {
305
	global $config, $g;
306
	if(isset($config['system']['developerspew'])) {
307
		$mt = microtime();
308
		echo "system_routing_configure() being called $mt\n";
309
	}
310

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

    
361
	if ($dont_add_route == false ) {
362
		if (!empty($interface) && $interface != $interfacegw)
363
			;
364
		else if (($interfacegw <> "bgpd") && (is_ipaddr($gatewayip))) {
365
			$action = "add";
366
			if(isset($route_arr['default'])) {
367
				$action = "change";
368
			}
369
			log_error("ROUTING: $action default route to $gatewayip");
370
			mwexec("/sbin/route {$action} default " . escapeshellarg($gatewayip));
371
		}
372
	}
373

    
374
	if (is_array($config['staticroutes']['route'])) {
375
		$gateways_arr = return_gateways_array();
376

    
377
		foreach ($config['staticroutes']['route'] as $rtent) {
378
			$gatewayip = "";
379
			if (empty($gateways_arr[$rtent['gateway']])) {
380
				log_error("Static Routes: Gateway IP could not be found for {$rtent['network']}");
381
				continue;
382
			}
383
			$gateway = $gateways_arr[$rtent['gateway']];
384
			if ($interface == $gateway['friendlyiface'])
385
				continue;
386
			$gatewayip = $gateway['gateway'];
387
			$interfacegw = $gateway['interface'];
388
			$action = "add";
389
			if (isset($route_arr[$rtent['network']]))
390
				$action = "change";
391

    
392
			if (is_ipaddr($gatewayip)) {
393
				mwexec("/sbin/route {$action} " . escapeshellarg($rtent['network']) .
394
					" " . escapeshellarg($gatewayip));
395
			} else if (!empty($interfacegw)) {
396
				mwexec("/sbin/route {$action} " . escapeshellarg($rtent['network']) .
397
					" -iface " . escapeshellarg($interfacegw));
398
			}
399
		}
400
	}
401

    
402
	return 0;
403
}
404

    
405
function system_routing_enable() {
406
	global $config, $g;
407
	if(isset($config['system']['developerspew'])) {
408
		$mt = microtime();
409
		echo "system_routing_enable() being called $mt\n";
410
	}
411

    
412
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
413
}
414

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

    
422
	$syslogcfg = $config['syslog'];
423

    
424
	if ($g['booting'])
425
		echo "Starting syslog...";
426
	else
427
		killbypid("{$g['varrun_path']}/syslog.pid");
428

    
429
	if(is_process_running("syslogd"))
430
		mwexec("/usr/bin/killall -9 syslogd");
431
	if(is_process_running("fifolog_writer"))
432
		mwexec("/usr/bin/killall -9 fifolog_writer");
433
	
434
	// Define carious commands for logging
435
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
436
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
437
	$clog_create = "/usr/sbin/clog -i -s ";
438
	$clog_log = "%";
439

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

    
524
EOD;
525
		if (isset($syslogcfg['filter'])) {
526
			if($syslogcfg['remoteserver'])
527
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver']}\n";
528
			if($syslogcfg['remoteserver2'])
529
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver2']}\n";
530
			if($syslogcfg['remoteserver3'])
531
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver3']}\n";
532

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

    
567
EOD;
568

    
569
}
570

    
571
		if (isset($syslogcfg['system'])) {
572
			if($syslogcfg['remoteserver2'])
573
				$syslogconf .= <<<EOD
574
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver2']}
575
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver2']}
576
security.*										 @{$syslogcfg['remoteserver2']}
577
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver2']}
578
*.emerg											 @{$syslogcfg['remoteserver2']}
579

    
580
EOD;
581

    
582
}
583

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

    
593
EOD;
594

    
595
}
596
		if (isset($syslogcfg['logall'])) {
597
			if($syslogcfg['remoteserver'])
598
				$syslogconf .= <<<EOD
599
*.*								@{$syslogcfg['remoteserver']}
600

    
601
EOD;
602

    
603
			if($syslogcfg['remoteserver2'])
604
				$syslogconf .= <<<EOD
605
*.*								@{$syslogcfg['remoteserver2']}
606

    
607
EOD;
608

    
609
			if($syslogcfg['remoteserver3'])
610
				$syslogconf .= <<<EOD
611
*.*								@{$syslogcfg['remoteserver3']}
612

    
613
EOD;
614

    
615
}
616
		fwrite($fd, $syslogconf);
617
		fclose($fd);
618

    
619
		// Ensure that the log directory exists
620
		if(!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
621
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
622

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

    
629
	} else {
630
		$retval = mwexec("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log");
631
	}
632

    
633
	if ($g['booting'])
634
		echo "done.\n";
635

    
636
	return $retval;
637
}
638

    
639
function system_pccard_start() {
640
	global $config, $g;
641
	if(isset($config['system']['developerspew'])) {
642
		$mt = microtime();
643
		echo "system_pccard_start() being called $mt\n";
644
	}
645

    
646
	if ($g['booting'])
647
		echo "Initializing PCMCIA...";
648

    
649
	/* kill any running pccardd */
650
	killbypid("{$g['varrun_path']}/pccardd.pid");
651

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

    
655
	if ($g['booting']) {
656
		if ($res == 0)
657
			echo "done.\n";
658
		else
659
			echo "failed!\n";
660
	}
661

    
662
	return $res;
663
}
664

    
665

    
666
function system_webgui_start() {
667
	global $config, $g;
668

    
669
	if ($g['booting'])
670
		echo "Starting webConfigurator...";
671

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

    
675
	sleep(1);
676

    
677
	chdir($g['www_path']);
678

    
679
	/* defaults */
680
	$portarg = "80";
681
	$crt = "";
682
	$key = "";
683
	$ca = "";
684

    
685
	/* non-standard port? */
686
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
687
		$portarg = "{$config['system']['webgui']['port']}";
688

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

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

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

    
732
	/* fetch page to preload apc cache */
733
	$proto = "http";
734
	if ($config['system']['webgui']['protocol'])
735
		$proto = $config['system']['webgui']['protocol'];
736
	mwexec_bg("/usr/bin/fetch -o /dev/null -q {$proto}://localhost:{$portarg}/preload.php");
737

    
738
	if ($g['booting']) {
739
		if ($res == 0)
740
			echo "done.\n";
741
		else
742
			echo "failed!\n";
743
	}
744

    
745
	return $res;
746
}
747

    
748
function system_generate_lighty_config($filename,
749
	$cert,
750
	$key,
751
	$ca,
752
	$pid_file,
753
	$port = 80,
754
	$document_root = "/usr/local/www/",
755
	$cert_location = "cert.pem",
756
	$ca_location = "ca.pem",
757
	$max_procs = 2,
758
	$max_requests = "2",
759
	$fast_cgi_enable = true,
760
	$captive_portal = false) {
761

    
762
	global $config, $g;
763

    
764
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
765
		mkdir("{$g['tmp_path']}/lighttpdcompress");
766

    
767
	if(isset($config['system']['developerspew'])) {
768
		$mt = microtime();
769
		echo "system_generate_lighty_config() being called $mt\n";
770
	}
771

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

    
799
	$memory = get_memory();
800
	$avail = $memory[0];
801

    
802
	if($avail > 0 and $avail < 65) {
803
		$fast_cgi_enable = false;
804
	}
805

    
806
	// Ramp up captive portal max procs
807
	if($captive_portal == true)  {
808
		if($avail > 65 and $avail < 98) {
809
			$max_procs = 1;
810
		}
811
		if($avail > 97 and $avail < 128) {
812
			$max_procs = 2;
813
		}
814
		if($avail > 127 and $avail < 256) {
815
			$max_procs = 3;
816
		}
817
		if($avail > 255 and $avail < 384) {
818
			$max_procs = 4;
819
		}
820
		if($avail > 383) {
821
			$max_procs = 5;
822
		}
823
	}
824

    
825
	if($captive_portal == true)  {	
826
		$bin_environment =  <<<EOC
827
        "bin-environment" => (
828
           "PHP_FCGI_CHILDREN" => "$max_procs",
829
           "PHP_FCGI_MAX_REQUESTS" => "500"
830
        ), 
831
EOC;
832

    
833
	} else if ($avail > 0 and $avail < 128) {
834
		$bin_environment = <<<EOC
835
		"bin-environment" => (
836
			"PHP_FCGI_CHILDREN" => "$max_procs",
837
			"PHP_FCGI_MAX_REQUESTS" => "2",
838
	),
839

    
840
EOC;
841
	} else
842
		$bin_environment =  <<<EOC
843
        "bin-environment" => (
844
           "PHP_FCGI_CHILDREN" => "$max_procs",
845
           "PHP_FCGI_MAX_REQUESTS" => "500"
846
        ), 
847
EOC;
848

    
849
	if($fast_cgi_enable == true) {
850
		$module = "\"mod_fastcgi\", \"mod_cgi\"";
851
		$cgi_config = "";
852
		$fastcgi_config = <<<EOD
853
#### fastcgi module
854
## read fastcgi.txt for more info
855
fastcgi.server = ( ".php" =>
856
	( "localhost" =>
857
		(
858
			"socket" => "{$g['tmp_path']}/php-fastcgi.socket",
859
			"min-procs" => 0,
860
			"max-procs" => {$max_procs},
861
			{$bin_environment}			
862
			"bin-path" => "/usr/local/bin/php"
863
		)
864
	)
865
)
866

    
867
#### CGI module
868
cgi.assign                 = ( ".cgi" => "" )
869

    
870
EOD;
871
	} else {
872
		$fastcgi_config = "";
873
		$module = "\"mod_cgi\"";
874
		$cgi_config = <<<EOD
875
#### CGI module
876
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
877
                               ".cgi" => "" )
878

    
879
EOD;
880
	}
881

    
882
	$lighty_config = "";
883
	$lighty_config .= <<<EOD
884
#
885
# lighttpd configuration file
886
#
887
# use a it as base for lighttpd 1.0.0 and above
888
#
889
############ Options you really have to take care of ####################
890

    
891
## FreeBSD!
892
server.event-handler	= "freebsd-kqueue"
893
server.network-backend 	= "writev"
894

    
895
## modules to load
896
server.modules              =   (
897
									{$captive_portal_module}
898
									"mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect",
899
									{$module}{$captiveportal}
900
								)
901

    
902
## Unused modules
903
#                               "mod_setenv",
904
#                               "mod_rewrite",
905
#                               "mod_ssi",
906
#                               "mod_usertrack",
907
#                               "mod_expire",
908
#                               "mod_secdownload",
909
#                               "mod_rrdtool",
910
#                               "mod_auth",
911
#                               "mod_status",
912
#                               "mod_alias",
913
#                               "mod_proxy",
914
#                               "mod_simple_vhost",
915
#                               "mod_evhost",
916
#                               "mod_userdir",
917
#                               "mod_cgi",
918

    
919
server.max-keep-alive-requests = 15
920
server.max-keep-alive-idle = 30
921

    
922
## a static document-root, for virtual-hosting take look at the
923
## server.virtual-* options
924
server.document-root        = "{$document_root}"
925
{$captive_portal_rewrite}
926

    
927
# Maximum idle time with nothing being written (php downloading)
928
server.max-write-idle = 999
929

    
930
## where to send error-messages to
931
server.errorlog             = "/var/log/lighttpd.error.log"
932

    
933
# files to check for if .../ is requested
934
server.indexfiles           = ( "index.php", "index.html",
935
                                "index.htm", "default.htm" )
936

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

    
990
# Use the "Content-Type" extended attribute to obtain mime type if possible
991
#mimetypes.use-xattr        = "enable"
992

    
993
#### accesslog module
994
#accesslog.filename          = "/dev/null"
995

    
996
## deny access the file-extensions
997
#
998
# ~    is for backupfiles from vi, emacs, joe, ...
999
# .inc is often used for code includes which should in general not be part
1000
#      of the document-root
1001
url.access-deny             = ( "~", ".inc" )
1002

    
1003

    
1004
######### Options that are good to be but not neccesary to be changed #######
1005

    
1006
## bind to port (default: 80)
1007
server.port                = {$lighty_port}
1008

    
1009
## error-handler for status 404
1010
#server.error-handler-404   = "/error-handler.html"
1011
#server.error-handler-404   = "/error-handler.php"
1012

    
1013
## to help the rc.scripts
1014
server.pid-file            = "/var/run/{$pid_file}"
1015

    
1016
## virtual directory listings
1017
server.dir-listing         = "disable"
1018

    
1019
## enable debugging
1020
debug.log-request-header   = "disable"
1021
debug.log-response-header  = "disable"
1022
debug.log-request-handling = "disable"
1023
debug.log-file-not-found   = "disable"
1024

    
1025
# gzip compression
1026
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1027
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1028

    
1029
{$server_upload_dirs}
1030

    
1031
{$server_max_request_size}
1032

    
1033
{$fastcgi_config}
1034

    
1035
{$cgi_config}
1036

    
1037
{$captive_portal_mod_evasive}
1038

    
1039
expire.url = (
1040
				"" => "access 50 hours",	
1041
        )
1042

    
1043
EOD;
1044

    
1045
	$cert = str_replace("\r", "", $cert);
1046
	$key = str_replace("\r", "", $key);
1047
	$ca = str_replace("\r", "", $ca);
1048

    
1049
	$cert = str_replace("\n\n", "\n", $cert);
1050
	$key = str_replace("\n\n", "\n", $key);
1051
	$ca = str_replace("\n\n", "\n", $ca);
1052

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

    
1082
	// Add HTTP to HTTPS redirect	
1083
	if ($captive_portal == false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1084
		if($lighty_port != "443") 
1085
			$redirectport = ":{$lighty_port}";
1086
		$lighty_config .= <<<EOD
1087
\$SERVER["socket"] == ":80" {
1088
	\$HTTP["host"] =~ "(.*)" {
1089
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1090
	}
1091
}
1092
EOD;
1093
	}
1094

    
1095
	$fd = fopen("{$filename}", "w");
1096
	if (!$fd) {
1097
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
1098
		return 1;
1099
	}
1100
	fwrite($fd, $lighty_config);
1101
	fclose($fd);
1102

    
1103
	return 0;
1104

    
1105
}
1106

    
1107
function system_timezone_configure() {
1108
	global $config, $g;
1109
	if(isset($config['system']['developerspew'])) {
1110
		$mt = microtime();
1111
		echo "system_timezone_configure() being called $mt\n";
1112
	}
1113

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

    
1116
	if ($g['booting'])
1117
		echo "Setting timezone...";
1118

    
1119
	/* extract appropriate timezone file */
1120
	$timezone = $syscfg['timezone'];
1121
	if (!$timezone)
1122
		$timezone = "Etc/UTC";
1123

    
1124
	conf_mount_rw();
1125

    
1126
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1127
		escapeshellarg($timezone) . " > /etc/localtime");
1128

    
1129
	mwexec("sync");
1130
	conf_mount_ro();
1131

    
1132
	if ($g['booting'])
1133
		echo "done.\n";
1134
}
1135

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

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

    
1141
	/* open configuration for wrting or bail */
1142
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1143
	if(!$fd) {
1144
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1145
		return;
1146
	}
1147

    
1148
	fwrite($fd, "# \n");
1149
	fwrite($fd, "# pfSense OpenNTPD configuration file \n");
1150
	fwrite($fd, "# \n\n");
1151

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

    
1156
	/* Setup listener(s) if the user has configured one */
1157
        if ($config['installedpackages']['openntpd']) {
1158
    		/* server config is in coregui1 */
1159
		$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
1160
		if ($xmlsettings['enable'] == 'on') {
1161
			$ifaces = explode(',', $xmlsettings['interface']);
1162
			$ifaces = array_map('get_real_interface', $ifaces);
1163
			$ifaces = array_filter($ifaces, 'does_interface_exist');
1164
			$ips = array_map('find_interface_ip', $ifaces);
1165
			foreach ($ips as $ip) {
1166
				if (is_ipaddr($ip))
1167
					fwrite($fd, "listen on $ip\n");
1168
			}
1169
		}
1170
	}
1171

    
1172
	fwrite($fd, "\n");
1173

    
1174
	/* slurp! */
1175
	fclose($fd);
1176

    
1177
	/* if openntpd is running, kill it */
1178
	while(is_process_running("ntpd")) {
1179
		killbyname("ntpd");
1180
	}
1181

    
1182
	/* if /var/empty does not exist, create it */
1183
	if(!is_dir("/var/empty"))
1184
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1185

    
1186
	if ($g['booting'])
1187
		return;
1188

    
1189
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1190
	exec("/usr/local/sbin/ntpd -s -f {$g['varetc_path']}/ntpd.conf");
1191
	
1192
	// Note that we are starting up
1193
	exec("echo 'OpenNTPD is starting up' >> {$g['varlog_path']}/ntpd.log");
1194

    
1195
}
1196

    
1197
function sync_system_time() {
1198
	global $config, $g;
1199

    
1200
	$syscfg = $config['system'];
1201

    
1202
	if ($g['booting'])
1203
		echo "Syncing system time before startup...";
1204

    
1205
	/* foreach through servers and write out to ntpd.conf */
1206
	foreach (explode(' ', $syscfg['timeservers']) as $ts) {
1207
		mwexec("/usr/sbin/ntpdate -s $ts");
1208
	}
1209
	
1210
	if ($g['booting'])
1211
		echo "done.\n";
1212
	
1213
}
1214

    
1215
function system_halt() {
1216
	global $g;
1217

    
1218
	system_reboot_cleanup();
1219

    
1220
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1221
}
1222

    
1223
function system_reboot() {
1224
	global $g;
1225

    
1226
	system_reboot_cleanup();
1227

    
1228
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1229
}
1230

    
1231
function system_reboot_sync() {
1232
	global $g;
1233

    
1234
	system_reboot_cleanup();
1235

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

    
1239
function system_reboot_cleanup() {
1240
	mwexec("/usr/local/bin/beep.sh stop");
1241
	require_once("captiveportal.inc");
1242
	captiveportal_radius_stop_all();
1243
	require_once("voucher.inc");
1244
	voucher_save_db_to_config();
1245
}
1246

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

    
1254
	if ($early)
1255
		$cmdn = "earlyshellcmd";
1256
	else
1257
		$cmdn = "shellcmd";
1258

    
1259
	if (is_array($config['system'][$cmdn])) {
1260

    
1261
		/* *cmd is an array, loop through */
1262
		foreach ($config['system'][$cmdn] as $cmd) {
1263
			exec($cmd);
1264
		}
1265

    
1266
	} elseif($config['system'][$cmdn] <> "") {
1267

    
1268
		/* execute single item */
1269
		exec($config['system'][$cmdn]);
1270

    
1271
	}
1272
}
1273

    
1274
function system_console_configure() {
1275
	global $config, $g;
1276
	if(isset($config['system']['developerspew'])) {
1277
		$mt = microtime();
1278
		echo "system_console_configure() being called $mt\n";
1279
	}
1280

    
1281
	if (isset($config['system']['disableconsolemenu'])) {
1282
		touch("{$g['varetc_path']}/disableconsole");
1283
	} else {
1284
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1285
	}
1286
}
1287

    
1288
function system_dmesg_save() {
1289
	global $g;
1290
	if(isset($config['system']['developerspew'])) {
1291
		$mt = microtime();
1292
		echo "system_dmesg_save() being called $mt\n";
1293
	}
1294

    
1295
	$dmesg = "";
1296
	exec("/sbin/dmesg", $dmesg);
1297

    
1298
	/* find last copyright line (output from previous boots may be present) */
1299
	$lastcpline = 0;
1300

    
1301
	for ($i = 0; $i < count($dmesg); $i++) {
1302
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1303
			$lastcpline = $i;
1304
	}
1305

    
1306
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1307
	if (!$fd) {
1308
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1309
		return 1;
1310
	}
1311

    
1312
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1313
		fwrite($fd, $dmesg[$i] . "\n");
1314

    
1315
	fclose($fd);
1316

    
1317
	return 0;
1318
}
1319

    
1320
function system_set_harddisk_standby() {
1321
	global $g, $config;
1322
	if(isset($config['system']['developerspew'])) {
1323
		$mt = microtime();
1324
		echo "system_set_harddisk_standby() being called $mt\n";
1325
	}
1326

    
1327
	if (isset($config['system']['harddiskstandby'])) {
1328
		if ($g['booting']) {
1329
			echo 'Setting hard disk standby... ';
1330
		}
1331

    
1332
		$standby = $config['system']['harddiskstandby'];
1333
		// Check for a numeric value
1334
		if (is_numeric($standby)) {
1335
			// Sync the disk(s)
1336
			pfSense_sync();
1337
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1338
				// Reinitialize ATA-drives
1339
				mwexec('/usr/local/sbin/atareinit');
1340
				if ($g['booting']) {
1341
					echo "done.\n";
1342
				}
1343
			} else if ($g['booting']) {
1344
				echo "failed!\n";
1345
			}
1346
		} else if ($g['booting']) {
1347
			echo "failed!\n";
1348
		}
1349
	}
1350
}
1351

    
1352
function system_setup_sysctl() {
1353
	global $config;
1354
	if(isset($config['system']['developerspew'])) {
1355
		$mt = microtime();
1356
		echo "system_setup_sysctl() being called $mt\n";
1357
	}
1358

    
1359
	activate_sysctls();	
1360

    
1361
	if (isset($config['system']['sharednet'])) {
1362
		system_disable_arp_wrong_if();
1363
	}
1364
}
1365

    
1366
function system_disable_arp_wrong_if() {
1367
	global $config;
1368
	if(isset($config['system']['developerspew'])) {
1369
		$mt = microtime();
1370
		echo "system_disable_arp_wrong_if() being called $mt\n";
1371
	}
1372
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1373
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1374
}
1375

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

    
1386
function enable_watchdog() {
1387
	global $config;
1388
	return;
1389
	$install_watchdog = false;
1390
	$supported_watchdogs = array("Geode");
1391
	$file = file_get_contents("/var/log/dmesg.boot");
1392
	foreach($supported_watchdogs as $sd) {
1393
		if(stristr($file, "Geode")) {
1394
			$install_watchdog = true;
1395
		}
1396
	}
1397
	if($install_watchdog == true) {
1398
		if(is_process_running("watchdogd"))
1399
			mwexec("/usr/bin/killall watchdogd", true);
1400
		exec("/usr/sbin/watchdogd");
1401
	}
1402
}
1403

    
1404
function system_check_reset_button() {
1405
	global $g;
1406
	if($g['platform'] != "nanobsd")
1407
		return 0;
1408

    
1409
	$specplatform = system_identify_specific_platform();
1410

    
1411
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1412
		return 0;
1413

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

    
1416
	if ($retval == 99) {
1417
		/* user has pressed reset button for 2 seconds - 
1418
		   reset to factory defaults */
1419
		echo <<<EOD
1420

    
1421
***********************************************************************
1422
* Reset button pressed - resetting configuration to factory defaults. *
1423
* The system will reboot after this completes.                        *
1424
***********************************************************************
1425

    
1426

    
1427
EOD;
1428
		
1429
		reset_factory_defaults();
1430
		system_reboot_sync();
1431
		exit(0);
1432
	}
1433

    
1434
	return 0;
1435
}
1436

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

    
1463
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1464
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1465
	
1466
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1467
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1468
		
1469
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1470
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1471
	
1472
	/* unknown embedded platform */
1473
	return array('name' => 'embedded', 'descr' => 'embedded (unknown)');
1474
}
1475

    
1476
function system_get_dmesg_boot() {
1477
	global $g;
1478
		
1479
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1480
}
1481

    
1482
?>
(46-46/60)