Project

General

Profile

Download (44.1 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/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
	// Do not create blank domain lines, it breaks tools like dig.
90
	if($syscfg['domain'])
91
		$resolvconf = "domain {$syscfg['domain']}\n";
92

    
93
	if (isset($config['dnsmasq']['enable']) && !isset($config['system']['dnslocalhost']))
94
		$resolvconf .= "nameserver 127.0.0.1\n";
95

    
96
	if (isset($syscfg['dnsallowoverride'])) {
97
		/* get dynamically assigned DNS servers (if any) */
98
		$ns = array_unique(get_searchdomains());
99
		foreach($ns as $searchserver) {
100
			if($searchserver)
101
				$resolvconf .= "search {$searchserver}\n";
102
		}
103
		$ns = array_unique(get_nameservers());
104
		foreach($ns as $nameserver) {
105
			if($nameserver)
106
				$resolvconf .= "nameserver $nameserver\n";
107
		}
108
	}
109
	if (is_array($syscfg['dnsserver'])) {
110
		foreach ($syscfg['dnsserver'] as $ns) {
111
			if ($ns)
112
				$resolvconf .= "nameserver $ns\n";
113
		}
114
	}
115

    
116
	$dnslock = lock('resolvconf', LOCK_EX);
117

    
118
	$fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
119
	if (!$fd) {
120
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
121
		unlock($dnslock);
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 change -host " . $syscfg['dnsserver'][$dnscountermo] . " {$gatewayip}");
146
				}
147
			}
148
		}
149
	}
150

    
151
	unlock($dnslock);
152

    
153
	return 0;
154
}
155

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

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

    
175
	return $master_list;
176
}
177

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

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

    
206
	return $master_list;
207
}
208

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

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

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

    
224
	$hosts = "127.0.0.1	localhost localhost.{$syscfg['domain']}\n";
225
	$lhosts = "";
226
	$dhosts = "";
227

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

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

    
259
	if (isset($dnsmasqcfg['dhcpfirst']))
260
		$hosts .= $dhosts . $lhosts;
261
	else
262
		$hosts .= $lhosts . $dhosts;
263

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

    
280
	system_dhcpleases_configure();
281

    
282
	return 0;
283
}
284

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

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

    
309
	$syscfg = $config['system'];
310

    
311
	/* set hostname */
312
	$status = mwexec("/bin/hostname " .
313
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
314

    
315
    /* Setup host GUID ID.  This is used by ZFS. */
316
	mwexec("/etc/rc.d/hostid start");
317

    
318
	return $status;
319
}
320

    
321
function system_routing_configure($interface = "") {
322
	global $config, $g;
323
	if(isset($config['system']['developerspew'])) {
324
		$mt = microtime();
325
		echo "system_routing_configure() being called $mt\n";
326
	}
327

    
328
	$gatewayip = "";
329
	$interfacegw = "";
330
	$foundgw = false;
331
	/* tack on all the hard defined gateways as well */
332
	if (is_array($config['gateways']['gateway_item'])) {
333
		mwexec("/bin/rm {$g['tmp_path']}/*_defaultgw", true);
334
		foreach	($config['gateways']['gateway_item'] as $gateway) {
335
			if (isset($gateway['defaultgw'])) {
336
				if(strstr($gateway['gateway'], ":"))
337
					break;
338
				if ($gateway['gateway'] == "dynamic")
339
					$gateway['gateway'] = get_interface_gateway($gateway['interface']);
340
				$gatewayip = $gateway['gateway'];
341
				$interfacegw = $gateway['interface'];
342
				if (!empty($interfacegw)) {
343
					$defaultif = get_real_interface($gateway['interface']);
344
					if ($defaultif)
345
						@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gatewayip);
346
				}
347
				$foundgw = true;
348
				break;
349
			}
350
		}
351
	}
352
	if ($foundgw == false) {
353
		$defaultif = get_real_interface("wan");
354
		$interfacegw = "wan";
355
		$gatewayip = get_interface_gateway("wan");
356
		@touch("{$g['tmp_path']}/{$defaultif}_defaultgw");
357
	}	
358
	$dont_add_route = false;
359
	/* if OLSRD is enabled, allow WAN to house DHCP. */
360
	if($config['installedpackages']['olsrd']) {
361
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
362
			if($olsrd['enabledyngw'] == "on") {
363
				$dont_add_route = true;
364
				break;
365
			}
366
		}
367
	}
368

    
369
	if ($dont_add_route == false ) {
370
		if (!empty($interface) && $interface != $interfacegw)
371
			;
372
		else if (($interfacegw <> "bgpd") && (is_ipaddr($gatewayip))) {
373
			log_error("ROUTING: setting default route to $gatewayip");
374
			mwexec("/sbin/route change -inet default " . escapeshellarg($gatewayip));
375
		}
376
	}
377

    
378
	if (is_array($config['staticroutes']['route'])) {
379
		$gateways_arr = return_gateways_array();
380

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

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

    
403
	return 0;
404
}
405

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

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

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

    
423
	mwexec("/etc/rc.d/hostid start");
424

    
425
	$syslogcfg = $config['syslog'];
426

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

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

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

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

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

    
570
EOD;
571

    
572
}
573

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

    
583
EOD;
584

    
585
}
586

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

    
596
EOD;
597

    
598
}
599
		if (isset($syslogcfg['logall'])) {
600
			if($syslogcfg['remoteserver'])
601
				$syslogconf .= <<<EOD
602
*.*								@{$syslogcfg['remoteserver']}
603

    
604
EOD;
605

    
606
			if($syslogcfg['remoteserver2'])
607
				$syslogconf .= <<<EOD
608
*.*								@{$syslogcfg['remoteserver2']}
609

    
610
EOD;
611

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

    
616
EOD;
617

    
618
}
619
		if (isset($syslogcfg['zmqserver'])) {
620
				$syslogconf .= <<<EOD
621
*.*								^{$syslogcfg['zmqserver']}
622

    
623
EOD;
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
	$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
736
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
737
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
738
		"cert.pem", "ca.pem", $max_procs);
739

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

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

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

    
756
	return $res;
757
}
758

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

    
773
	global $config, $g;
774

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

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

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

    
810
	$memory = get_memory();
811
	$avail = $memory[0];
812

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

    
817
	// Ramp up captive portal max procs
818
	//  Work relative to the default of 2, for values that would be >2.
819
	if($captive_portal == true)  {
820
		if($avail > 65 and $avail < 98) {
821
			$max_procs = 1;
822
		}
823
		if($avail > 97 and $avail < 128) {
824
			$max_procs = 2;
825
		}
826
		if($avail > 127 and $avail < 256) {
827
			$max_procs += 1;
828
		}
829
		if($avail > 255 and $avail < 384) {
830
			$max_procs += 2;
831
		}
832
		if($avail > 383) {
833
			$max_procs += 3;
834
		}
835
	}
836

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

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

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

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

    
879
#### CGI module
880
cgi.assign                 = ( ".cgi" => "" )
881

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

    
891
EOD;
892
	}
893

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

    
903
## FreeBSD!
904
server.event-handler	= "freebsd-kqueue"
905
server.network-backend 	= "writev"
906

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

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

    
931
server.max-keep-alive-requests = 15
932
server.max-keep-alive-idle = 30
933

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

    
939
# Maximum idle time with nothing being written (php downloading)
940
server.max-write-idle = 999
941

    
942
## where to send error-messages to
943
server.errorlog             = "/var/log/lighttpd.error.log"
944

    
945
# files to check for if .../ is requested
946
server.indexfiles           = ( "index.php", "index.html",
947
                                "index.htm", "default.htm" )
948

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

    
1002
# Use the "Content-Type" extended attribute to obtain mime type if possible
1003
#mimetypes.use-xattr        = "enable"
1004

    
1005
#### accesslog module
1006
#accesslog.filename          = "/dev/null"
1007

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

    
1015

    
1016
######### Options that are good to be but not neccesary to be changed #######
1017

    
1018
## bind to port (default: 80)
1019
server.port                = {$lighty_port}
1020

    
1021
## error-handler for status 404
1022
#server.error-handler-404   = "/error-handler.html"
1023
#server.error-handler-404   = "/error-handler.php"
1024

    
1025
## to help the rc.scripts
1026
server.pid-file            = "/var/run/{$pid_file}"
1027

    
1028
## virtual directory listings
1029
server.dir-listing         = "disable"
1030

    
1031
## enable debugging
1032
debug.log-request-header   = "disable"
1033
debug.log-response-header  = "disable"
1034
debug.log-request-handling = "disable"
1035
debug.log-file-not-found   = "disable"
1036

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

    
1041
{$server_upload_dirs}
1042

    
1043
{$server_max_request_size}
1044

    
1045
{$fastcgi_config}
1046

    
1047
{$cgi_config}
1048

    
1049
{$captive_portal_mod_evasive}
1050

    
1051
expire.url = (
1052
				"" => "access 50 hours",	
1053
        )
1054

    
1055
EOD;
1056

    
1057
	$cert = str_replace("\r", "", $cert);
1058
	$key = str_replace("\r", "", $key);
1059
	$ca = str_replace("\r", "", $ca);
1060

    
1061
	$cert = str_replace("\n\n", "\n", $cert);
1062
	$key = str_replace("\n\n", "\n", $key);
1063
	$ca = str_replace("\n\n", "\n", $ca);
1064

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

    
1091
		// Harden SSL a bit for PCI conformance testing
1092
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
1093
		$lighty_config .= "ssl.cipher-list = \"TLSv1+HIGH !SSLv2 RC4+MEDIUM !aNULL !eNULL !3DES @STRENGTH\"\n";
1094

    
1095
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1096
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1097
	}
1098

    
1099
	// Add HTTP to HTTPS redirect	
1100
	if ($captive_portal == false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1101
		if($lighty_port != "443") 
1102
			$redirectport = ":{$lighty_port}";
1103
		$lighty_config .= <<<EOD
1104
\$SERVER["socket"] == ":80" {
1105
	\$HTTP["host"] =~ "(.*)" {
1106
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1107
	}
1108
}
1109
EOD;
1110
	}
1111

    
1112
	$fd = fopen("{$filename}", "w");
1113
	if (!$fd) {
1114
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
1115
		return 1;
1116
	}
1117
	fwrite($fd, $lighty_config);
1118
	fclose($fd);
1119

    
1120
	return 0;
1121

    
1122
}
1123

    
1124
function system_timezone_configure() {
1125
	global $config, $g;
1126
	if(isset($config['system']['developerspew'])) {
1127
		$mt = microtime();
1128
		echo "system_timezone_configure() being called $mt\n";
1129
	}
1130

    
1131
	$syscfg = $config['system'];
1132

    
1133
	if ($g['booting'])
1134
		echo "Setting timezone...";
1135

    
1136
	/* extract appropriate timezone file */
1137
	$timezone = $syscfg['timezone'];
1138
	if (!$timezone)
1139
		$timezone = "Etc/UTC";
1140

    
1141
	conf_mount_rw();
1142

    
1143
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1144
		escapeshellarg($timezone) . " > /etc/localtime");
1145

    
1146
	mwexec("sync");
1147
	conf_mount_ro();
1148

    
1149
	if ($g['booting'])
1150
		echo "done.\n";
1151
}
1152

    
1153
function system_ntp_configure() {
1154
	global $config, $g;
1155

    
1156
	$ntpcfg = "# \n";
1157
	$ntpcfg .= "# pfSense OpenNTPD configuration file \n";
1158
	$ntpcfg .= "# \n\n";
1159

    
1160
	/* foreach through servers and write out to ntpd.conf */
1161
	foreach (explode(' ', $config['system']['timeservers']) as $ts)
1162
		$ntpcfg .= "servers {$ts}\n";
1163

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

    
1188
	/* open configuration for wrting or bail */
1189
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1190
	if(!$fd) {
1191
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1192
		return;
1193
	}
1194
	fwrite($fd, $ntpcfg);
1195

    
1196
	/* slurp! */
1197
	fclose($fd);
1198

    
1199
	/* if openntpd is running, kill it */
1200
	while(is_process_running("ntpd")) {
1201
		killbyname("ntpd");
1202
	}
1203

    
1204
	/* if /var/empty does not exist, create it */
1205
	if(!is_dir("/var/empty"))
1206
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1207

    
1208
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1209
	exec("/usr/local/sbin/ntpd -s -f {$g['varetc_path']}/ntpd.conf");
1210
	
1211
	// Note that we are starting up
1212
	log_error("OpenNTPD is starting up.");
1213

    
1214
}
1215

    
1216
function sync_system_time() {
1217
	global $config, $g;
1218

    
1219
	if ($g['booting'])
1220
		echo "Syncing system time before startup...";
1221

    
1222
	/* foreach through servers and write out to ntpd.conf */
1223
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1224
		mwexec("/usr/sbin/ntpdate -s $ts");
1225
	}
1226
	
1227
	if ($g['booting'])
1228
		echo "done.\n";
1229
	
1230
}
1231

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

    
1235
	system_reboot_cleanup();
1236

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

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

    
1243
	system_reboot_cleanup();
1244

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

    
1248
function system_reboot_sync() {
1249
	global $g;
1250

    
1251
	system_reboot_cleanup();
1252

    
1253
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1254
}
1255

    
1256
function system_reboot_cleanup() {
1257
	mwexec("/usr/local/bin/beep.sh stop");
1258
	require_once("captiveportal.inc");
1259
	captiveportal_radius_stop_all();
1260
	require_once("voucher.inc");
1261
	voucher_save_db_to_config();
1262
	mwexec("/etc/rc.stop_packages");
1263
}
1264

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

    
1272
	if ($early)
1273
		$cmdn = "earlyshellcmd";
1274
	else
1275
		$cmdn = "shellcmd";
1276

    
1277
	if (is_array($config['system'][$cmdn])) {
1278

    
1279
		/* *cmd is an array, loop through */
1280
		foreach ($config['system'][$cmdn] as $cmd) {
1281
			exec($cmd);
1282
		}
1283

    
1284
	} elseif($config['system'][$cmdn] <> "") {
1285

    
1286
		/* execute single item */
1287
		exec($config['system'][$cmdn]);
1288

    
1289
	}
1290
}
1291

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

    
1299
	if (isset($config['system']['disableconsolemenu'])) {
1300
		touch("{$g['varetc_path']}/disableconsole");
1301
	} else {
1302
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1303
	}
1304
}
1305

    
1306
function system_dmesg_save() {
1307
	global $g;
1308
	if(isset($config['system']['developerspew'])) {
1309
		$mt = microtime();
1310
		echo "system_dmesg_save() being called $mt\n";
1311
	}
1312

    
1313
	$dmesg = "";
1314
	exec("/sbin/dmesg", $dmesg);
1315

    
1316
	/* find last copyright line (output from previous boots may be present) */
1317
	$lastcpline = 0;
1318

    
1319
	for ($i = 0; $i < count($dmesg); $i++) {
1320
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1321
			$lastcpline = $i;
1322
	}
1323

    
1324
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1325
	if (!$fd) {
1326
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1327
		return 1;
1328
	}
1329

    
1330
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1331
		fwrite($fd, $dmesg[$i] . "\n");
1332

    
1333
	fclose($fd);
1334

    
1335
	return 0;
1336
}
1337

    
1338
function system_set_harddisk_standby() {
1339
	global $g, $config;
1340
	if(isset($config['system']['developerspew'])) {
1341
		$mt = microtime();
1342
		echo "system_set_harddisk_standby() being called $mt\n";
1343
	}
1344

    
1345
	if (isset($config['system']['harddiskstandby'])) {
1346
		if ($g['booting']) {
1347
			echo 'Setting hard disk standby... ';
1348
		}
1349

    
1350
		$standby = $config['system']['harddiskstandby'];
1351
		// Check for a numeric value
1352
		if (is_numeric($standby)) {
1353
			// Sync the disk(s)
1354
			pfSense_sync();
1355
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1356
				// Reinitialize ATA-drives
1357
				mwexec('/usr/local/sbin/atareinit');
1358
				if ($g['booting']) {
1359
					echo "done.\n";
1360
				}
1361
			} else if ($g['booting']) {
1362
				echo "failed!\n";
1363
			}
1364
		} else if ($g['booting']) {
1365
			echo "failed!\n";
1366
		}
1367
	}
1368
}
1369

    
1370
function system_setup_sysctl() {
1371
	global $config;
1372
	if(isset($config['system']['developerspew'])) {
1373
		$mt = microtime();
1374
		echo "system_setup_sysctl() being called $mt\n";
1375
	}
1376

    
1377
	activate_sysctls();	
1378

    
1379
	if (isset($config['system']['sharednet'])) {
1380
		system_disable_arp_wrong_if();
1381
	}
1382
}
1383

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

    
1394
function system_enable_arp_wrong_if() {
1395
	global $config;
1396
	if(isset($config['system']['developerspew'])) {
1397
		$mt = microtime();
1398
		echo "system_enable_arp_wrong_if() being called $mt\n";
1399
	}
1400
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1401
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1402
}
1403

    
1404
function enable_watchdog() {
1405
	global $config;
1406
	return;
1407
	$install_watchdog = false;
1408
	$supported_watchdogs = array("Geode");
1409
	$file = file_get_contents("/var/log/dmesg.boot");
1410
	foreach($supported_watchdogs as $sd) {
1411
		if(stristr($file, "Geode")) {
1412
			$install_watchdog = true;
1413
		}
1414
	}
1415
	if($install_watchdog == true) {
1416
		if(is_process_running("watchdogd"))
1417
			mwexec("/usr/bin/killall watchdogd", true);
1418
		exec("/usr/sbin/watchdogd");
1419
	}
1420
}
1421

    
1422
function system_check_reset_button() {
1423
	global $g;
1424
	if($g['platform'] != "nanobsd")
1425
		return 0;
1426

    
1427
	$specplatform = system_identify_specific_platform();
1428

    
1429
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1430
		return 0;
1431

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

    
1434
	if ($retval == 99) {
1435
		/* user has pressed reset button for 2 seconds - 
1436
		   reset to factory defaults */
1437
		echo <<<EOD
1438

    
1439
***********************************************************************
1440
* Reset button pressed - resetting configuration to factory defaults. *
1441
* The system will reboot after this completes.                        *
1442
***********************************************************************
1443

    
1444

    
1445
EOD;
1446
		
1447
		reset_factory_defaults();
1448
		system_reboot_sync();
1449
		exit(0);
1450
	}
1451

    
1452
	return 0;
1453
}
1454

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

    
1481
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1482
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1483
	
1484
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1485
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1486
		
1487
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1488
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1489
	
1490
	/* unknown embedded platform */
1491
	return array('name' => 'embedded', 'descr' => 'embedded (unknown)');
1492
}
1493

    
1494
function system_get_dmesg_boot() {
1495
	global $g;
1496
		
1497
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1498
}
1499

    
1500
function openntpd_get_listen_ips() {
1501
	$interfaces = get_configured_interface_with_descr();
1502
	$carplist = get_configured_carp_interface_list();
1503
	$listenips = array();
1504
	foreach ($carplist as $cif => $carpip)
1505
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1506
	$aliaslist = get_configured_ip_aliases_list();
1507
	foreach ($aliaslist as $aliasip => $aliasif)
1508
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1509
	foreach ($interfaces as $iface => $ifacename) {
1510
		$tmp["name"]  = $ifacename;
1511
		$tmp["value"] = $iface;
1512
		$listenips[] = $tmp;
1513
	}
1514
	$tmp["name"]  = "Localhost";
1515
	$tmp["value"] = "lo0";
1516
	$listenips[] = $tmp;
1517
	return $listenips;
1518
}
1519
?>
(47-47/61)