Project

General

Profile

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

    
93
	$havedns = false;
94

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

    
121
	$dnslock = lock('resolvconf', LOCK_EX);
122

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

    
130
	fwrite($fd, $resolvconf);
131
	fclose($fd);
132

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

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

    
157
	unlock($dnslock);
158

    
159
	return 0;
160
}
161

    
162
function get_searchdomains() {
163
	global $config, $g;
164

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

    
181
	return $master_list;
182
}
183

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

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

    
212
	return $master_list;
213
}
214

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

    
222
	$syscfg = $config['system'];
223
	$dnsmasqcfg = $config['dnsmasq'];
224

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

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

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

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

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

    
279
	system_dhcpleases_configure();
280

    
281
	return 0;
282
}
283

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

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

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

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

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

    
317
	return $status;
318
}
319

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

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

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

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

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

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

    
420
	return 0;
421
}
422

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

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

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

    
440
	$syslogcfg = $config['syslog'];
441

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

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

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

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

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

    
585
EOD;
586

    
587
}
588

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

    
598
EOD;
599

    
600
}
601

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

    
611
EOD;
612

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

    
619
EOD;
620

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

    
625
EOD;
626

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

    
631
EOD;
632

    
633
}
634
		fwrite($fd, $syslogconf);
635
		fclose($fd);
636

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

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

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

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

    
654
	return $retval;
655
}
656

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

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

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

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

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

    
680
	return $res;
681
}
682

    
683

    
684
function system_webgui_start() {
685
	global $config, $g;
686

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

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

    
693
	sleep(1);
694

    
695
	chdir($g['www_path']);
696

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

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

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

    
743
	/* generate lighttpd configuration */
744
	$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
745
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
746
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
747
		"cert.pem", "ca.pem", $max_procs);
748

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

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

    
758
	if ($g['booting']) {
759
		if ($res == 0)
760
			echo "done.\n";
761
		else
762
			echo "failed!\n";
763
	}
764

    
765
	return $res;
766
}
767

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

    
782
	global $config, $g;
783

    
784
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
785
		mkdir("{$g['tmp_path']}/lighttpdcompress");
786

    
787
	if(isset($config['system']['developerspew'])) {
788
		$mt = microtime();
789
		echo "system_generate_lighty_config() being called $mt\n";
790
	}
791

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

    
819
	$memory = get_memory();
820
	$avail = $memory[0];
821

    
822
	if($avail > 0 and $avail < 65) {
823
		$fast_cgi_enable = false;
824
	}
825

    
826
	// Ramp up captive portal max procs
827
	//  Work relative to the default of 2, for values that would be >2.
828
	if($captive_portal == true)  {
829
		if($avail > 65 and $avail < 98) {
830
			$max_procs = 1;
831
		}
832
		if($avail > 97 and $avail < 128) {
833
			$max_procs = 2;
834
		}
835
		if($avail > 127 and $avail < 256) {
836
			$max_procs += 1;
837
		}
838
		if($avail > 255 and $avail < 384) {
839
			$max_procs += 2;
840
		}
841
		if($avail > 383) {
842
			$max_procs += 3;
843
		}
844
	}
845

    
846
	if($captive_portal == true)  {	
847
		$bin_environment =  <<<EOC
848
			"bin-environment" => (
849
				"PHP_FCGI_CHILDREN" => "$max_procs",
850
				"PHP_FCGI_MAX_REQUESTS" => "500"
851
			),
852
EOC;
853

    
854
	} else if ($avail > 0 and $avail < 128) {
855
		$bin_environment = <<<EOC
856
			"bin-environment" => (
857
				"PHP_FCGI_CHILDREN" => "$max_procs",
858
				"PHP_FCGI_MAX_REQUESTS" => "2",
859
			),
860

    
861
EOC;
862
	} else
863
		$bin_environment =  <<<EOC
864
			"bin-environment" => (
865
				"PHP_FCGI_CHILDREN" => "$max_procs",
866
				"PHP_FCGI_MAX_REQUESTS" => "500"
867
			),
868
EOC;
869

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

    
888
#### CGI module
889
cgi.assign                 = ( ".cgi" => "" )
890

    
891
EOD;
892
	} else {
893
		$fastcgi_config = "";
894
		$module = "\"mod_cgi\"";
895
		$cgi_config = <<<EOD
896
#### CGI module
897
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
898
                               ".cgi" => "" )
899

    
900
EOD;
901
	}
902

    
903
	$lighty_config = "";
904
	$lighty_config .= <<<EOD
905
#
906
# lighttpd configuration file
907
#
908
# use a it as base for lighttpd 1.0.0 and above
909
#
910
############ Options you really have to take care of ####################
911

    
912
## FreeBSD!
913
server.event-handler	= "freebsd-kqueue"
914
server.network-backend 	= "writev"
915

    
916
## modules to load
917
server.modules              =   (
918
									{$captive_portal_module}
919
									"mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect",
920
									{$module}{$captiveportal}
921
								)
922

    
923
## Unused modules
924
#                               "mod_setenv",
925
#                               "mod_rewrite",
926
#                               "mod_ssi",
927
#                               "mod_usertrack",
928
#                               "mod_expire",
929
#                               "mod_secdownload",
930
#                               "mod_rrdtool",
931
#                               "mod_auth",
932
#                               "mod_status",
933
#                               "mod_alias",
934
#                               "mod_proxy",
935
#                               "mod_simple_vhost",
936
#                               "mod_evhost",
937
#                               "mod_userdir",
938
#                               "mod_cgi",
939

    
940
server.max-keep-alive-requests = 15
941
server.max-keep-alive-idle = 30
942

    
943
## a static document-root, for virtual-hosting take look at the
944
## server.virtual-* options
945
server.document-root        = "{$document_root}"
946
{$captive_portal_rewrite}
947

    
948
# Maximum idle time with nothing being written (php downloading)
949
server.max-write-idle = 999
950

    
951
## where to send error-messages to
952
server.errorlog             = "/var/log/lighttpd.error.log"
953

    
954
# files to check for if .../ is requested
955
server.indexfiles           = ( "index.php", "index.html",
956
                                "index.htm", "default.htm" )
957

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

    
1011
# Use the "Content-Type" extended attribute to obtain mime type if possible
1012
#mimetypes.use-xattr        = "enable"
1013

    
1014
#### accesslog module
1015
#accesslog.filename          = "/dev/null"
1016

    
1017
## deny access the file-extensions
1018
#
1019
# ~    is for backupfiles from vi, emacs, joe, ...
1020
# .inc is often used for code includes which should in general not be part
1021
#      of the document-root
1022
url.access-deny             = ( "~", ".inc" )
1023

    
1024

    
1025
######### Options that are good to be but not neccesary to be changed #######
1026

    
1027
## bind to port (default: 80)
1028
server.port                = {$lighty_port}
1029

    
1030
## error-handler for status 404
1031
#server.error-handler-404   = "/error-handler.html"
1032
#server.error-handler-404   = "/error-handler.php"
1033

    
1034
## to help the rc.scripts
1035
server.pid-file            = "/var/run/{$pid_file}"
1036

    
1037
## virtual directory listings
1038
server.dir-listing         = "disable"
1039

    
1040
## enable debugging
1041
debug.log-request-header   = "disable"
1042
debug.log-response-header  = "disable"
1043
debug.log-request-handling = "disable"
1044
debug.log-file-not-found   = "disable"
1045

    
1046
# gzip compression
1047
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1048
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1049

    
1050
{$server_upload_dirs}
1051

    
1052
{$server_max_request_size}
1053

    
1054
{$fastcgi_config}
1055

    
1056
{$cgi_config}
1057

    
1058
{$captive_portal_mod_evasive}
1059

    
1060
expire.url = (
1061
				"" => "access 50 hours",	
1062
        )
1063

    
1064
EOD;
1065

    
1066
	$cert = str_replace("\r", "", $cert);
1067
	$key = str_replace("\r", "", $key);
1068
	$ca = str_replace("\r", "", $ca);
1069

    
1070
	$cert = str_replace("\n\n", "\n", $cert);
1071
	$key = str_replace("\n\n", "\n", $key);
1072
	$ca = str_replace("\n\n", "\n", $ca);
1073

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

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

    
1104
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1105
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1106
	}
1107

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

    
1121
	$fd = fopen("{$filename}", "w");
1122
	if (!$fd) {
1123
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
1124
		return 1;
1125
	}
1126
	fwrite($fd, $lighty_config);
1127
	fclose($fd);
1128

    
1129
	return 0;
1130

    
1131
}
1132

    
1133
function system_timezone_configure() {
1134
	global $config, $g;
1135
	if(isset($config['system']['developerspew'])) {
1136
		$mt = microtime();
1137
		echo "system_timezone_configure() being called $mt\n";
1138
	}
1139

    
1140
	$syscfg = $config['system'];
1141

    
1142
	if ($g['booting'])
1143
		echo "Setting timezone...";
1144

    
1145
	/* extract appropriate timezone file */
1146
	$timezone = $syscfg['timezone'];
1147
	if (!$timezone)
1148
		$timezone = "Etc/UTC";
1149

    
1150
	conf_mount_rw();
1151

    
1152
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1153
		escapeshellarg($timezone) . " > /etc/localtime");
1154

    
1155
	mwexec("sync");
1156
	conf_mount_ro();
1157

    
1158
	if ($g['booting'])
1159
		echo "done.\n";
1160
}
1161

    
1162
function system_ntp_configure() {
1163
	global $config, $g;
1164

    
1165
	$ntpcfg = "# \n";
1166
	$ntpcfg .= "# pfSense OpenNTPD configuration file \n";
1167
	$ntpcfg .= "# \n\n";
1168

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

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

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

    
1205
	/* slurp! */
1206
	fclose($fd);
1207

    
1208
	/* if openntpd is running, kill it */
1209
	while(is_process_running("ntpd")) {
1210
		killbyname("ntpd");
1211
	}
1212

    
1213
	/* if /var/empty does not exist, create it */
1214
	if(!is_dir("/var/empty"))
1215
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1216

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

    
1223
}
1224

    
1225
function sync_system_time() {
1226
	global $config, $g;
1227

    
1228
	if ($g['booting'])
1229
		echo "Syncing system time before startup...";
1230

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

    
1241
function system_halt() {
1242
	global $g;
1243

    
1244
	system_reboot_cleanup();
1245

    
1246
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1247
}
1248

    
1249
function system_reboot() {
1250
	global $g;
1251

    
1252
	system_reboot_cleanup();
1253

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

    
1257
function system_reboot_sync() {
1258
	global $g;
1259

    
1260
	system_reboot_cleanup();
1261

    
1262
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1263
}
1264

    
1265
function system_reboot_cleanup() {
1266
	mwexec("/usr/local/bin/beep.sh stop");
1267
	require_once("captiveportal.inc");
1268
	captiveportal_radius_stop_all();
1269
	require_once("voucher.inc");
1270
	voucher_save_db_to_config();
1271
	// mwexec("/etc/rc.stop_packages");
1272
}
1273

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

    
1281
	if ($early)
1282
		$cmdn = "earlyshellcmd";
1283
	else
1284
		$cmdn = "shellcmd";
1285

    
1286
	if (is_array($config['system'][$cmdn])) {
1287

    
1288
		/* *cmd is an array, loop through */
1289
		foreach ($config['system'][$cmdn] as $cmd) {
1290
			exec($cmd);
1291
		}
1292

    
1293
	} elseif($config['system'][$cmdn] <> "") {
1294

    
1295
		/* execute single item */
1296
		exec($config['system'][$cmdn]);
1297

    
1298
	}
1299
}
1300

    
1301
function system_console_configure() {
1302
	global $config, $g;
1303
	if(isset($config['system']['developerspew'])) {
1304
		$mt = microtime();
1305
		echo "system_console_configure() being called $mt\n";
1306
	}
1307

    
1308
	if (isset($config['system']['disableconsolemenu'])) {
1309
		touch("{$g['varetc_path']}/disableconsole");
1310
	} else {
1311
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1312
	}
1313
}
1314

    
1315
function system_dmesg_save() {
1316
	global $g;
1317
	if(isset($config['system']['developerspew'])) {
1318
		$mt = microtime();
1319
		echo "system_dmesg_save() being called $mt\n";
1320
	}
1321

    
1322
	$dmesg = "";
1323
	exec("/sbin/dmesg", $dmesg);
1324

    
1325
	/* find last copyright line (output from previous boots may be present) */
1326
	$lastcpline = 0;
1327

    
1328
	for ($i = 0; $i < count($dmesg); $i++) {
1329
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1330
			$lastcpline = $i;
1331
	}
1332

    
1333
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1334
	if (!$fd) {
1335
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1336
		return 1;
1337
	}
1338

    
1339
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1340
		fwrite($fd, $dmesg[$i] . "\n");
1341

    
1342
	fclose($fd);
1343

    
1344
	return 0;
1345
}
1346

    
1347
function system_set_harddisk_standby() {
1348
	global $g, $config;
1349
	if(isset($config['system']['developerspew'])) {
1350
		$mt = microtime();
1351
		echo "system_set_harddisk_standby() being called $mt\n";
1352
	}
1353

    
1354
	if (isset($config['system']['harddiskstandby'])) {
1355
		if ($g['booting']) {
1356
			echo 'Setting hard disk standby... ';
1357
		}
1358

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

    
1379
function system_setup_sysctl() {
1380
	global $config;
1381
	if(isset($config['system']['developerspew'])) {
1382
		$mt = microtime();
1383
		echo "system_setup_sysctl() being called $mt\n";
1384
	}
1385

    
1386
	activate_sysctls();	
1387

    
1388
	if (isset($config['system']['sharednet'])) {
1389
		system_disable_arp_wrong_if();
1390
	}
1391
}
1392

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

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

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

    
1431
function system_check_reset_button() {
1432
	global $g;
1433
	if($g['platform'] != "nanobsd")
1434
		return 0;
1435

    
1436
	$specplatform = system_identify_specific_platform();
1437

    
1438
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1439
		return 0;
1440

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

    
1443
	if ($retval == 99) {
1444
		/* user has pressed reset button for 2 seconds - 
1445
		   reset to factory defaults */
1446
		echo <<<EOD
1447

    
1448
***********************************************************************
1449
* Reset button pressed - resetting configuration to factory defaults. *
1450
* The system will reboot after this completes.                        *
1451
***********************************************************************
1452

    
1453

    
1454
EOD;
1455
		
1456
		reset_factory_defaults();
1457
		system_reboot_sync();
1458
		exit(0);
1459
	}
1460

    
1461
	return 0;
1462
}
1463

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

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

    
1503
function system_get_dmesg_boot() {
1504
	global $g;
1505
		
1506
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1507
}
1508

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