Project

General

Profile

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

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

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

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

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

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

    
32
/*
33
	pfSense_BUILDER_BINARIES:	/usr/sbin/powerd	/usr/bin/killall	/sbin/sysctl	/sbin/route
34
	pfSense_BUILDER_BINARIES:	/bin/hostname	/bin/ls	/usr/bin/netstat	/usr/sbin/syslogd	
35
	pfSense_BUILDER_BINARIES:	/usr/sbin/pccardd	/usr/local/sbin/lighttpd	/bin/chmod 	/bin/mkdir
36
	pfSense_BUILDER_BINARIES:	/usr/bin/tar		/usr/local/sbin/ntpd	/usr/sbin/ntpdate
37
	pfSense_BUILDER_BINARIES:	/usr/bin/nohup	/sbin/dmesg	/usr/local/sbin/atareinit	/sbin/kldload
38
	pfSense_MODULE:	utils
39
*/
40

    
41
function activate_powerd() {
42
	global $config, $g;
43
	if(isset($config['system']['powerd_enable'])) {
44
		if ($g["platform"] == "nanobsd")
45
			exec("/sbin/kldload cpufreq");
46
		exec("/usr/sbin/powerd -b adp -a adp");
47
	} else {
48
		if(is_process_running("powerd"))
49
			exec("/usr/bin/killall powerd");
50
	}
51
}
52

    
53
function get_default_sysctl_value($id) {
54
	global $sysctls;
55

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

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

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

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

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

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

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

    
91
	$havedns = false;
92

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

    
119
	$dnslock = lock('resolvconf', LOCK_EX);
120

    
121
	$fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
122
	if (!$fd) {
123
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
124
		unlock($dnslock);
125
		return 1;
126
	}
127

    
128
	fwrite($fd, $resolvconf);
129
	fclose($fd);
130

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

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

    
155
	unlock($dnslock);
156

    
157
	return 0;
158
}
159

    
160
function get_searchdomains() {
161
	global $config, $g;
162

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

    
179
	return $master_list;
180
}
181

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

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

    
210
	return $master_list;
211
}
212

    
213
function system_hosts_generate() {
214
	global $config, $g;
215
	if(isset($config['system']['developerspew'])) {
216
		$mt = microtime();
217
		echo "system_hosts_generate() being called $mt\n";
218
	}
219

    
220
	$syscfg = $config['system'];
221
	$dnsmasqcfg = $config['dnsmasq'];
222

    
223
	if (!is_array($dnsmasqcfg['hosts'])) {
224
		$dnsmasqcfg['hosts'] = array();
225
	}
226
	$hostscfg = $dnsmasqcfg['hosts'];
227

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

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

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

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

    
277
	system_dhcpleases_configure();
278

    
279
	return 0;
280
}
281

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

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

    
306
	$syscfg = $config['system'];
307

    
308
	/* set hostname */
309
	$status = mwexec("/bin/hostname " .
310
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
311

    
312
    /* Setup host GUID ID.  This is used by ZFS. */
313
	mwexec("/etc/rc.d/hostid start");
314

    
315
	return $status;
316
}
317

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

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

    
377
	if ($dont_add_route == false ) {
378
		if (!empty($interface) && $interface != $interfacegw)
379
			;
380
		else if (($interfacegw <> "bgpd") && (is_ipaddr($gatewayip))) {
381
			$action = "add";
382
			if(isset($route_arr['default'])) {
383
				$action = "change";
384
			}
385
			log_error("ROUTING: $action default route to $gatewayip");
386
			mwexec("/sbin/route {$action} -inet default " . escapeshellarg($gatewayip));
387
		}
388
	}
389

    
390
	if (is_array($config['staticroutes']['route'])) {
391
		$gateways_arr = return_gateways_array();
392

    
393
		foreach ($config['staticroutes']['route'] as $rtent) {
394
			$gatewayip = "";
395
			if (empty($gateways_arr[$rtent['gateway']])) {
396
				log_error("Static Routes: Gateway IP could not be found for {$rtent['network']}");
397
				continue;
398
			}
399
			$gateway = $gateways_arr[$rtent['gateway']];
400
			if (!empty($interface) && $interface != $gateway['friendlyiface'])
401
				continue;
402
			$gatewayip = $gateway['gateway'];
403
			$interfacegw = $gateway['interface'];
404
			$action = "add";
405
			if (isset($route_arr[$rtent['network']]))
406
				$action = "change";
407

    
408
			if (is_ipaddr($gatewayip)) {
409
				mwexec("/sbin/route {$action} -inet " . escapeshellarg($rtent['network']) .
410
					" " . escapeshellarg($gatewayip));
411
			} else if (!empty($interfacegw)) {
412
				mwexec("/sbin/route {$action} -inet " . escapeshellarg($rtent['network']) .
413
					" -iface " . escapeshellarg($interfacegw));
414
			}
415
		}
416
	}
417

    
418
	return 0;
419
}
420

    
421
function system_routing_enable() {
422
	global $config, $g;
423
	if(isset($config['system']['developerspew'])) {
424
		$mt = microtime();
425
		echo "system_routing_enable() being called $mt\n";
426
	}
427

    
428
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
429
}
430

    
431
function system_syslogd_start() {
432
	global $config, $g;
433
	if(isset($config['system']['developerspew'])) {
434
		$mt = microtime();
435
		echo "system_syslogd_start() being called $mt\n";
436
	}
437

    
438
	$syslogcfg = $config['syslog'];
439

    
440
	if ($g['booting'])
441
		echo "Starting syslog...";
442
	else
443
		killbypid("{$g['varrun_path']}/syslog.pid");
444

    
445
	if(is_process_running("syslogd"))
446
		mwexec("/usr/bin/killall -9 syslogd");
447
	if(is_process_running("fifolog_writer"))
448
		mwexec("/usr/bin/killall -9 fifolog_writer");
449
	
450
	// Define carious commands for logging
451
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
452
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
453
	$clog_create = "/usr/sbin/clog -i -s ";
454
	$clog_log = "%";
455

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

    
540
EOD;
541
		if (isset($syslogcfg['filter'])) {
542
			if($syslogcfg['remoteserver'])
543
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver']}\n";
544
			if($syslogcfg['remoteserver2'])
545
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver2']}\n";
546
			if($syslogcfg['remoteserver3'])
547
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver3']}\n";
548

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

    
583
EOD;
584

    
585
}
586

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

    
596
EOD;
597

    
598
}
599

    
600
		if (isset($syslogcfg['system'])) {
601
			if($syslogcfg['remoteserver3'])
602
				$syslogconf .= <<<EOD
603
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver3']}
604
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver3']}
605
security.*										 @{$syslogcfg['remoteserver3']}
606
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver3']}
607
*.emerg											 @{$syslogcfg['remoteserver3']}
608

    
609
EOD;
610

    
611
}
612
		if (isset($syslogcfg['logall'])) {
613
			if($syslogcfg['remoteserver'])
614
				$syslogconf .= <<<EOD
615
*.*								@{$syslogcfg['remoteserver']}
616

    
617
EOD;
618

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

    
623
EOD;
624

    
625
			if($syslogcfg['remoteserver3'])
626
				$syslogconf .= <<<EOD
627
*.*								@{$syslogcfg['remoteserver3']}
628

    
629
EOD;
630

    
631
}
632
		fwrite($fd, $syslogconf);
633
		fclose($fd);
634

    
635
		// Ensure that the log directory exists
636
		if(!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
637
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
638

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

    
645
	} else {
646
		$retval = mwexec("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log");
647
	}
648

    
649
	if ($g['booting'])
650
		echo "done.\n";
651

    
652
	return $retval;
653
}
654

    
655
function system_pccard_start() {
656
	global $config, $g;
657
	if(isset($config['system']['developerspew'])) {
658
		$mt = microtime();
659
		echo "system_pccard_start() being called $mt\n";
660
	}
661

    
662
	if ($g['booting'])
663
		echo "Initializing PCMCIA...";
664

    
665
	/* kill any running pccardd */
666
	killbypid("{$g['varrun_path']}/pccardd.pid");
667

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

    
671
	if ($g['booting']) {
672
		if ($res == 0)
673
			echo "done.\n";
674
		else
675
			echo "failed!\n";
676
	}
677

    
678
	return $res;
679
}
680

    
681

    
682
function system_webgui_start() {
683
	global $config, $g;
684

    
685
	if ($g['booting'])
686
		echo "Starting webConfigurator...";
687

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

    
691
	sleep(1);
692

    
693
	chdir($g['www_path']);
694

    
695
	/* defaults */
696
	$portarg = "80";
697
	$crt = "";
698
	$key = "";
699
	$ca = "";
700

    
701
	/* non-standard port? */
702
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
703
		$portarg = "{$config['system']['webgui']['port']}";
704

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

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

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

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

    
754
	if ($g['booting']) {
755
		if ($res == 0)
756
			echo "done.\n";
757
		else
758
			echo "failed!\n";
759
	}
760

    
761
	return $res;
762
}
763

    
764
function system_generate_lighty_config($filename,
765
	$cert,
766
	$key,
767
	$ca,
768
	$pid_file,
769
	$port = 80,
770
	$document_root = "/usr/local/www/",
771
	$cert_location = "cert.pem",
772
	$ca_location = "ca.pem",
773
	$max_procs = 2,
774
	$max_requests = "2",
775
	$fast_cgi_enable = true,
776
	$captive_portal = false) {
777

    
778
	global $config, $g;
779

    
780
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
781
		mkdir("{$g['tmp_path']}/lighttpdcompress");
782

    
783
	if(isset($config['system']['developerspew'])) {
784
		$mt = microtime();
785
		echo "system_generate_lighty_config() being called $mt\n";
786
	}
787

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

    
815
	$memory = get_memory();
816
	$avail = $memory[0];
817

    
818
	if($avail > 0 and $avail < 65) {
819
		$fast_cgi_enable = false;
820
	}
821

    
822
	// Ramp up captive portal max procs
823
	if($captive_portal == true)  {
824
		if($avail > 65 and $avail < 98) {
825
			$max_procs = 1;
826
		}
827
		if($avail > 97 and $avail < 128) {
828
			$max_procs = 2;
829
		}
830
		if($avail > 127 and $avail < 256) {
831
			$max_procs = 3;
832
		}
833
		if($avail > 255 and $avail < 384) {
834
			$max_procs = 4;
835
		}
836
		if($avail > 383) {
837
			$max_procs = 5;
838
		}
839
	}
840

    
841
	if($captive_portal == true)  {	
842
		$bin_environment =  <<<EOC
843
        "bin-environment" => (
844
           "PHP_FCGI_CHILDREN" => "$max_procs",
845
           "PHP_FCGI_MAX_REQUESTS" => "500"
846
        ), 
847
EOC;
848

    
849
	} else if ($avail > 0 and $avail < 128) {
850
		$bin_environment = <<<EOC
851
		"bin-environment" => (
852
			"PHP_FCGI_CHILDREN" => "$max_procs",
853
			"PHP_FCGI_MAX_REQUESTS" => "2",
854
	),
855

    
856
EOC;
857
	} else
858
		$bin_environment =  <<<EOC
859
        "bin-environment" => (
860
           "PHP_FCGI_CHILDREN" => "$max_procs",
861
           "PHP_FCGI_MAX_REQUESTS" => "500"
862
        ), 
863
EOC;
864

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

    
883
#### CGI module
884
cgi.assign                 = ( ".cgi" => "" )
885

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

    
895
EOD;
896
	}
897

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

    
907
## FreeBSD!
908
server.event-handler	= "freebsd-kqueue"
909
server.network-backend 	= "writev"
910

    
911
## modules to load
912
server.modules              =   (
913
									{$captive_portal_module}
914
									"mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect",
915
									{$module}{$captiveportal}
916
								)
917

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

    
935
server.max-keep-alive-requests = 15
936
server.max-keep-alive-idle = 30
937

    
938
## a static document-root, for virtual-hosting take look at the
939
## server.virtual-* options
940
server.document-root        = "{$document_root}"
941
{$captive_portal_rewrite}
942

    
943
# Maximum idle time with nothing being written (php downloading)
944
server.max-write-idle = 999
945

    
946
## where to send error-messages to
947
server.errorlog             = "/var/log/lighttpd.error.log"
948

    
949
# files to check for if .../ is requested
950
server.indexfiles           = ( "index.php", "index.html",
951
                                "index.htm", "default.htm" )
952

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

    
1006
# Use the "Content-Type" extended attribute to obtain mime type if possible
1007
#mimetypes.use-xattr        = "enable"
1008

    
1009
#### accesslog module
1010
#accesslog.filename          = "/dev/null"
1011

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

    
1019

    
1020
######### Options that are good to be but not neccesary to be changed #######
1021

    
1022
## bind to port (default: 80)
1023
server.port                = {$lighty_port}
1024

    
1025
## error-handler for status 404
1026
#server.error-handler-404   = "/error-handler.html"
1027
#server.error-handler-404   = "/error-handler.php"
1028

    
1029
## to help the rc.scripts
1030
server.pid-file            = "/var/run/{$pid_file}"
1031

    
1032
## virtual directory listings
1033
server.dir-listing         = "disable"
1034

    
1035
## enable debugging
1036
debug.log-request-header   = "disable"
1037
debug.log-response-header  = "disable"
1038
debug.log-request-handling = "disable"
1039
debug.log-file-not-found   = "disable"
1040

    
1041
# gzip compression
1042
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1043
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1044

    
1045
{$server_upload_dirs}
1046

    
1047
{$server_max_request_size}
1048

    
1049
{$fastcgi_config}
1050

    
1051
{$cgi_config}
1052

    
1053
{$captive_portal_mod_evasive}
1054

    
1055
expire.url = (
1056
				"" => "access 50 hours",	
1057
        )
1058

    
1059
EOD;
1060

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

    
1065
	$cert = str_replace("\n\n", "\n", $cert);
1066
	$key = str_replace("\n\n", "\n", $key);
1067
	$ca = str_replace("\n\n", "\n", $ca);
1068

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

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

    
1099
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1100
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1101
	}
1102

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

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

    
1124
	return 0;
1125

    
1126
}
1127

    
1128
function system_timezone_configure() {
1129
	global $config, $g;
1130
	if(isset($config['system']['developerspew'])) {
1131
		$mt = microtime();
1132
		echo "system_timezone_configure() being called $mt\n";
1133
	}
1134

    
1135
	$syscfg = $config['system'];
1136

    
1137
	if ($g['booting'])
1138
		echo "Setting timezone...";
1139

    
1140
	/* extract appropriate timezone file */
1141
	$timezone = $syscfg['timezone'];
1142
	if (!$timezone)
1143
		$timezone = "Etc/UTC";
1144

    
1145
	conf_mount_rw();
1146

    
1147
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1148
		escapeshellarg($timezone) . " > /etc/localtime");
1149

    
1150
	mwexec("sync");
1151
	conf_mount_ro();
1152

    
1153
	if ($g['booting'])
1154
		echo "done.\n";
1155
}
1156

    
1157
function system_ntp_configure() {
1158
	global $config, $g;
1159

    
1160
	$ntpcfg = "# \n";
1161
	$ntpcfg .= "# pfSense OpenNTPD configuration file \n";
1162
	$ntpcfg .= "# \n\n";
1163

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

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

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

    
1200
	/* slurp! */
1201
	fclose($fd);
1202

    
1203
	/* if openntpd is running, kill it */
1204
	while(is_process_running("ntpd")) {
1205
		killbyname("ntpd");
1206
	}
1207

    
1208
	/* if /var/empty does not exist, create it */
1209
	if(!is_dir("/var/empty"))
1210
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1211

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

    
1218
}
1219

    
1220
function sync_system_time() {
1221
	global $config, $g;
1222

    
1223
	if ($g['booting'])
1224
		echo "Syncing system time before startup...";
1225

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

    
1236
function system_halt() {
1237
	global $g;
1238

    
1239
	system_reboot_cleanup();
1240

    
1241
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1242
}
1243

    
1244
function system_reboot() {
1245
	global $g;
1246

    
1247
	system_reboot_cleanup();
1248

    
1249
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1250
}
1251

    
1252
function system_reboot_sync() {
1253
	global $g;
1254

    
1255
	system_reboot_cleanup();
1256

    
1257
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1258
}
1259

    
1260
function system_reboot_cleanup() {
1261
	mwexec("/usr/local/bin/beep.sh stop");
1262
	require_once("captiveportal.inc");
1263
	captiveportal_radius_stop_all();
1264
	require_once("voucher.inc");
1265
	voucher_save_db_to_config();
1266
	// mwexec("/etc/rc.stop_packages");
1267
}
1268

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

    
1276
	if ($early)
1277
		$cmdn = "earlyshellcmd";
1278
	else
1279
		$cmdn = "shellcmd";
1280

    
1281
	if (is_array($config['system'][$cmdn])) {
1282

    
1283
		/* *cmd is an array, loop through */
1284
		foreach ($config['system'][$cmdn] as $cmd) {
1285
			exec($cmd);
1286
		}
1287

    
1288
	} elseif($config['system'][$cmdn] <> "") {
1289

    
1290
		/* execute single item */
1291
		exec($config['system'][$cmdn]);
1292

    
1293
	}
1294
}
1295

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

    
1303
	if (isset($config['system']['disableconsolemenu'])) {
1304
		touch("{$g['varetc_path']}/disableconsole");
1305
	} else {
1306
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1307
	}
1308
}
1309

    
1310
function system_dmesg_save() {
1311
	global $g;
1312
	if(isset($config['system']['developerspew'])) {
1313
		$mt = microtime();
1314
		echo "system_dmesg_save() being called $mt\n";
1315
	}
1316

    
1317
	$dmesg = "";
1318
	exec("/sbin/dmesg", $dmesg);
1319

    
1320
	/* find last copyright line (output from previous boots may be present) */
1321
	$lastcpline = 0;
1322

    
1323
	for ($i = 0; $i < count($dmesg); $i++) {
1324
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1325
			$lastcpline = $i;
1326
	}
1327

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

    
1334
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1335
		fwrite($fd, $dmesg[$i] . "\n");
1336

    
1337
	fclose($fd);
1338

    
1339
	return 0;
1340
}
1341

    
1342
function system_set_harddisk_standby() {
1343
	global $g, $config;
1344
	if(isset($config['system']['developerspew'])) {
1345
		$mt = microtime();
1346
		echo "system_set_harddisk_standby() being called $mt\n";
1347
	}
1348

    
1349
	if (isset($config['system']['harddiskstandby'])) {
1350
		if ($g['booting']) {
1351
			echo 'Setting hard disk standby... ';
1352
		}
1353

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

    
1374
function system_setup_sysctl() {
1375
	global $config;
1376
	if(isset($config['system']['developerspew'])) {
1377
		$mt = microtime();
1378
		echo "system_setup_sysctl() being called $mt\n";
1379
	}
1380

    
1381
	activate_sysctls();	
1382

    
1383
	if (isset($config['system']['sharednet'])) {
1384
		system_disable_arp_wrong_if();
1385
	}
1386
}
1387

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

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

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

    
1426
function system_check_reset_button() {
1427
	global $g;
1428
	if($g['platform'] != "nanobsd")
1429
		return 0;
1430

    
1431
	$specplatform = system_identify_specific_platform();
1432

    
1433
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1434
		return 0;
1435

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

    
1438
	if ($retval == 99) {
1439
		/* user has pressed reset button for 2 seconds - 
1440
		   reset to factory defaults */
1441
		echo <<<EOD
1442

    
1443
***********************************************************************
1444
* Reset button pressed - resetting configuration to factory defaults. *
1445
* The system will reboot after this completes.                        *
1446
***********************************************************************
1447

    
1448

    
1449
EOD;
1450
		
1451
		reset_factory_defaults();
1452
		system_reboot_sync();
1453
		exit(0);
1454
	}
1455

    
1456
	return 0;
1457
}
1458

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

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

    
1498
function system_get_dmesg_boot() {
1499
	global $g;
1500
		
1501
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1502
}
1503

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