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	/bin/sync	/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
	foreach($sysctls as $sysctl => $value) {
56
		if($sysctl == $id)
57
			return $value;
58
	}
59
}
60

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

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

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

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

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

    
90
	$fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
91
	if (!$fd) {
92
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
93
		return 1;
94
	}
95

    
96
	$resolvconf = "domain {$syscfg['domain']}\n";
97

    
98
	$havedns = false;
99

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

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

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

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

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

    
159
	$master_list = array();
160
	
161
	// Read in dhclient nameservers
162
	$search_list = split("\n", `/bin/cat /var/etc/searchdomain_* 2>/dev/null`);
163
	if (is_array($search_lists)) {
164
		foreach($search_lists as $dns) {
165
			if(is_hostname($dns)) 
166
				$master_list[] = $dns;
167
		}
168
	}
169

    
170
	return $master_list;
171
}
172

    
173
function get_nameservers() {
174
	global $config, $g;
175
	$master_list = array();
176
	
177
	// Read in dhclient nameservers
178
	$dns_lists = split("\n", `/bin/cat /var/etc/nameserver_* 2>/dev/null`);
179
	if (is_array($dns_lists)) {
180
		foreach($dns_lists as $dns) {
181
			if(is_ipaddr($dns)) 
182
				$master_list[] = $dns;
183
		}
184
	}
185

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

    
195
	return $master_list;
196
}
197

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

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

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

    
213
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
214
	if (!$fd) {
215
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
216
		return 1;
217
	}
218

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

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

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

    
254
	system_dhcpleases_configure();
255

    
256
	return 0;
257
}
258

    
259
function system_dhcpleases_configure() {
260
	global $config, $g;
261
	
262
	/* Start the monitoring process for dynamic dhcpclients. */
263
	if (isset($config['dnsmasq']['regdhcp'])) {
264
		/* Make sure we do not error out */
265
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
266
		if (file_exists("{$g['varrun_path']}/dhcpleases.pid"))
267
				sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "HUP");
268
		else
269
			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");
270
	} else {
271
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
272
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
273
	}
274
}
275

    
276
function system_hostname_configure() {
277
	global $config, $g;
278
	if(isset($config['system']['developerspew'])) {
279
		$mt = microtime();
280
		echo "system_hostname_configure() being called $mt\n";
281
	}
282

    
283
	$syscfg = $config['system'];
284

    
285
	/* set hostname */
286
	$status = mwexec("/bin/hostname " .
287
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
288

    
289
    /* Setup host GUID ID.  This is used by ZFS. */
290
	mwexec("/etc/rc.d/hostid start");
291

    
292
	return $status;
293
}
294

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

    
302
	/* Enable fast routing, if enabled */
303
	/* XXX: More checks need to be done for subsystems that are not compatibel with fast routing. */
304
	if(isset($config['staticroutes']['enablefastrouting']) && !isset($config['ipsec']['enable']))
305
		mwexec("/sbin/sysctl net.inet.ip.fastforwarding=1");
306

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

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

    
394
	/* Create a array from the existing inet6 route table */
395
	exec("/usr/bin/netstat -rnf inet6", $routev6_str);
396
	array_shift($routev6_str);
397
	array_shift($routev6_str);
398
	array_shift($routev6_str);
399
	array_shift($routev6_str);
400
	array_shift($routev6_str);
401
	$routev6_arr = array();
402
	foreach($routev6_str as $routeline) {
403
		$items = preg_split("/[ ]+/i", $routeline);
404
		$route_arr[$items[0]] = array($items[0], $items[1], $items[5]);
405
	}
406

    
407
	if ($dont_add_route == false ) {
408
		if (!empty($interface) && $interface != $interfacegw)
409
			;
410
		else if (($interfacegwv6 <> "bgpd") && (is_ipaddrv6($gatewayipv6))) {
411
			$action = "add";
412
			if(isset($routev6_arr['default'])) {
413
				$action = "change";
414
			}
415
			log_error("ROUTING: $action IPv6 default route to $gatewayipv6");
416
			mwexec("/sbin/route {$action} -inet6 default " . escapeshellarg($gatewayipv6));
417
		}
418
	}
419

    
420
	if (is_array($config['staticroutes']['route'])) {
421
		$gateways_arr = return_gateways_array();
422

    
423
		foreach ($config['staticroutes']['route'] as $rtent) {
424
			$gatewayip = "";
425
			if (empty($gateways_arr[$rtent['gateway']])) {
426
				log_error("Static Routes: Gateway IP could not be found for {$rtent['network']}");
427
				continue;
428
			}
429
			$gateway = $gateways_arr[$rtent['gateway']];
430
			if ($interface == $gateway['friendlyiface'])
431
				continue;
432
			$gatewayip = $gateway['gateway'];
433
			$interfacegw = $gateway['interface'];
434
			$action = "add";
435
			if (isset($route_arr[$rtent['network']]))
436
				$action = "change";
437

    
438
			if(is_ipaddrv6($gatewayip)) {
439
				$inet6 = "-inet6";
440
			} else {
441
				$inet6 = "";
442
			}
443
			if (is_ipaddr($gatewayip)) {
444
				mwexec("/sbin/route {$action} {$inet6} " . escapeshellarg($rtent['network']) .
445
					" " . escapeshellarg($gatewayip));
446
			} else if (!empty($interfacegw)) {
447
				mwexec("/sbin/route {$action} {$inet6} " . escapeshellarg($rtent['network']) .
448
					" -iface " . escapeshellarg($interfacegw));
449
			}
450
		}
451
	}
452

    
453
	return 0;
454
}
455

    
456
function system_routing_enable() {
457
	global $config, $g;
458
	if(isset($config['system']['developerspew'])) {
459
		$mt = microtime();
460
		echo "system_routing_enable() being called $mt\n";
461
	}
462

    
463
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
464
}
465

    
466
function system_syslogd_start() {
467
	global $config, $g;
468
	if(isset($config['system']['developerspew'])) {
469
		$mt = microtime();
470
		echo "system_syslogd_start() being called $mt\n";
471
	}
472

    
473
	$syslogcfg = $config['syslog'];
474

    
475
	if ($g['booting'])
476
		echo "Starting syslog...";
477
	else
478
		killbypid("{$g['varrun_path']}/syslog.pid");
479

    
480
	if(is_process_running("syslogd"))
481
		mwexec("/usr/bin/killall -9 syslogd");
482
	if(is_process_running("fifolog_writer"))
483
		mwexec("/usr/bin/killall -9 fifolog_writer");
484
	
485
	// Define carious commands for logging
486
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
487
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
488
	$clog_create = "/usr/sbin/clog -i -s ";
489
	$clog_log = "%";
490

    
491
	// Which logging type are we using this week??
492
	if(isset($config['system']['usefifolog'])) {
493
		$log_directive = $fifolog_log;
494
		$log_create_directive = $fifolog_create;		
495
	} else { // Defaults to CLOG
496
		$log_directive = $clog_log;
497
		$log_create_directive = $clog_create;
498
	}
499
	
500
	if (isset($syslogcfg)) {
501
		$separatelogfacilities = array('ntpd','racoon','openvpn');
502
		if($config['installedpackages']['package']) {
503
			foreach($config['installedpackages']['package'] as $package) {
504
				if($package['logging']) {
505
					$pkgfacilities[] = $package['logging']['facilityname'];
506
					$separatelogfacilities = $separatelogfacilities + $pkgfacilities;
507
					$facilitylist = implode(',', $pkgfacilities);
508
					mwexec("{$log_create_directive} 10240 {$g['varlog_path']}/{$package['logging']['logfilename']}");
509
					$syslogconf .= "!{$facilitylist}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
510
				}
511
			}
512
		}
513
		$facilitylist = implode(',', array_unique($separatelogfacilities));
514
		/* write syslog.conf */		
515
		$fd = fopen("{$g['varetc_path']}/syslog.conf", "w");
516
		if (!$fd) {
517
			printf("Error: cannot open syslog.conf in system_syslogd_start().\n");
518
			return 1;
519
		}
520
		$syslogconf .= "!ntpdate,!ntpd\n";
521
		if (!isset($syslogcfg['disablelocallogging'])) 
522
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/ntpd.log\n";
523
		$syslogconf .= "!ppp\n";
524
		if (!isset($syslogcfg['disablelocallogging'])) 
525
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/ppp.log\n";
526
		$syslogconf .= "!pptp\n";
527
		if (!isset($syslogcfg['disablelocallogging'])) 
528
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/pptp.log\n";
529
		$syslogconf .= "!pppoe\n";
530
		if (!isset($syslogcfg['disablelocallogging'])) 
531
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/pppoe.log\n";
532
		$syslogconf .= "!l2tp\n";
533
		if (!isset($syslogcfg['disablelocallogging'])) 
534
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/l2tp.log\n";
535
		$syslogconf .= "!racoon\n";
536
		if (!isset($syslogcfg['disablelocallogging'])) 
537
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/ipsec.log\n";
538
		if (isset($syslogcfg['vpn'])) {
539
			if($syslogcfg['remoteserver'])
540
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver']}\n";
541
			if($syslogcfg['remoteserver2'])
542
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver2']}\n";
543
			if($syslogcfg['remoteserver3'])
544
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver3']}\n";
545
		}
546
		$syslogconf .= "!openvpn\n";
547
		if (!isset($syslogcfg['disablelocallogging'])) 
548
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/openvpn.log\n";
549
		if (isset($syslogcfg['vpn'])) {
550
			if($syslogcfg['remoteserver'])
551
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver']}\n";
552
			if($syslogcfg['remoteserver2'])
553
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver3']}\n";
554
			if($syslogcfg['remoteserver3'])
555
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver3']}\n";
556
		}
557
		$syslogconf .= "!apinger\n";
558
		if (!isset($syslogcfg['disablelocallogging']))
559
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/apinger.log\n";
560
		$syslogconf .= "!relayd\n";
561
		$syslogconf .= "*.* 						{$log_directive}{$g['varlog_path']}/relayd.log\n";
562
		$syslogconf .= "!-{$facilitylist}\n";
563
		if (!isset($syslogcfg['disablelocallogging'])) 
564
			$syslogconf .= <<<EOD
565
local0.*										 {$log_directive}{$g['varlog_path']}/filter.log
566
local3.*										 {$log_directive}{$g['varlog_path']}/vpn.log
567
local4.*										 {$log_directive}{$g['varlog_path']}/portalauth.log
568
local7.*										 {$log_directive}{$g['varlog_path']}/dhcpd.log
569
*.notice;kern.debug;lpr.info;mail.crit; 		 {$log_directive}{$g['varlog_path']}/system.log
570
news.err;local0.none;local3.none;local4.none; 	 {$log_directive}{$g['varlog_path']}/system.log
571
local7.none										 {$log_directive}{$g['varlog_path']}/system.log
572
security.*										 {$log_directive}{$g['varlog_path']}/system.log
573
auth.info;authpriv.info;daemon.info				 {$log_directive}{$g['varlog_path']}/system.log
574
auth.info;authpriv.info 						 |exec /usr/local/sbin/sshlockout_pf
575
*.emerg											 *
576

    
577
EOD;
578
		if (isset($syslogcfg['filter'])) {
579
			if($syslogcfg['remoteserver'])
580
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver']}\n";
581
			if($syslogcfg['remoteserver2'])
582
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver2']}\n";
583
			if($syslogcfg['remoteserver3'])
584
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver3']}\n";
585

    
586
		}
587
		if (isset($syslogcfg['vpn'])) {
588
			if($syslogcfg['remoteserver'])
589
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver']}\n";
590
			if($syslogcfg['remoteserver2'])
591
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver2']}\n";
592
			if($syslogcfg['remoteserver3'])
593
				$syslogconf .= "local3.*			 @{$syslogcfg['remoteserver3']}\n";
594
		}
595
		if (isset($syslogcfg['portalauth'])) {
596
			if($syslogcfg['remoteserver'])
597
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver']}\n";
598
			if($syslogcfg['remoteserver2'])
599
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver2']}\n";
600
			if($syslogcfg['remoteserver3'])
601
				$syslogconf .= "local4.*			 @{$syslogcfg['remoteserver3']}\n";
602
		}
603
		if (isset($syslogcfg['dhcp'])) {
604
			if($syslogcfg['remoteserver'])
605
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver']}\n";
606
			if($syslogcfg['remoteserver2'])
607
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver2']}\n";
608
			if($syslogcfg['remoteserver3'])
609
				$syslogconf .= "local7.*			 @{$syslogcfg['remoteserver3']}\n";
610
		}
611
		if (isset($syslogcfg['system'])) {
612
			if($syslogcfg['remoteserver'])
613
				$syslogconf .= <<<EOD
614
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver']}
615
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver']}
616
security.*										 @{$syslogcfg['remoteserver']}
617
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver']}
618
*.emerg											 @{$syslogcfg['remoteserver']}
619

    
620
EOD;
621

    
622
}
623

    
624
		if (isset($syslogcfg['system'])) {
625
			if($syslogcfg['remoteserver2'])
626
				$syslogconf .= <<<EOD
627
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver2']}
628
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver2']}
629
security.*										 @{$syslogcfg['remoteserver2']}
630
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver2']}
631
*.emerg											 @{$syslogcfg['remoteserver2']}
632

    
633
EOD;
634

    
635
}
636

    
637
		if (isset($syslogcfg['system'])) {
638
			if($syslogcfg['remoteserver3'])
639
				$syslogconf .= <<<EOD
640
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver3']}
641
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver3']}
642
security.*										 @{$syslogcfg['remoteserver3']}
643
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver3']}
644
*.emerg											 @{$syslogcfg['remoteserver3']}
645

    
646
EOD;
647

    
648
}
649
		if (isset($syslogcfg['logall'])) {
650
			if($syslogcfg['remoteserver'])
651
				$syslogconf .= <<<EOD
652
*.*								@{$syslogcfg['remoteserver']}
653

    
654
EOD;
655

    
656
			if($syslogcfg['remoteserver2'])
657
				$syslogconf .= <<<EOD
658
*.*								@{$syslogcfg['remoteserver2']}
659

    
660
EOD;
661

    
662
			if($syslogcfg['remoteserver3'])
663
				$syslogconf .= <<<EOD
664
*.*								@{$syslogcfg['remoteserver3']}
665

    
666
EOD;
667

    
668
}
669
		fwrite($fd, $syslogconf);
670
		fclose($fd);
671
		// Are we logging to a least one remote server ?
672
		if(strpos($syslogconf, "@") != false)
673
			$retval = system("/usr/sbin/syslogd -c -f {$g['varetc_path']}/syslog.conf");
674
		else
675
			$retval = system("/usr/sbin/syslogd -c -f {$g['varetc_path']}/syslog.conf");
676

    
677
	} else {
678
		$retval = mwexec("/usr/sbin/syslogd -c");
679
	}
680

    
681
	if ($g['booting'])
682
		echo "done.\n";
683

    
684
	return $retval;
685
}
686

    
687
function system_pccard_start() {
688
	global $config, $g;
689
	if(isset($config['system']['developerspew'])) {
690
		$mt = microtime();
691
		echo "system_pccard_start() being called $mt\n";
692
	}
693

    
694
	if ($g['booting'])
695
		echo "Initializing PCMCIA...";
696

    
697
	/* kill any running pccardd */
698
	killbypid("{$g['varrun_path']}/pccardd.pid");
699

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

    
703
	if ($g['booting']) {
704
		if ($res == 0)
705
			echo "done.\n";
706
		else
707
			echo "failed!\n";
708
	}
709

    
710
	return $res;
711
}
712

    
713

    
714
function system_webgui_start() {
715
	global $config, $g;
716

    
717
	if ($g['booting'])
718
		echo "Starting webConfigurator...";
719

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

    
723
	sleep(1);
724

    
725
	chdir($g['www_path']);
726

    
727
	/* defaults */
728
	$portarg = "80";
729
	$crt = "";
730
	$key = "";
731
	$ca = "";
732

    
733
	/* non-standard port? */
734
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
735
		$portarg = "{$config['system']['webgui']['port']}";
736

    
737
	if ($config['system']['webgui']['protocol'] == "https") {
738
		// Ensure that we have a webConfigurator CERT
739
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
740
		if(!is_array($cert) && !$cert['crt'] && !$cert['prv']) {
741
			if (!is_array($config['ca']))
742
				$config['ca'] = array();
743
			$a_ca =& $config['ca'];
744
			if (!is_array($config['cert']))
745
				$config['cert'] = array();
746
			$a_cert =& $config['cert'];
747
			echo "Creating SSL Certificate... ";
748
			$cert = array();
749
			$cert['refid'] = uniqid();
750
			$cert['descr'] = "webConfigurator default";
751
			mwexec("/usr/bin/openssl genrsa 1024 > {$g['tmp_path']}/ssl.key");
752
			mwexec("/usr/bin/openssl req -new -x509 -nodes -sha1 -days 2000 -key {$g['tmp_path']}/ssl.key > {$g['tmp_path']}/ssl.crt");
753
			$crt = file_get_contents("{$g['tmp_path']}/ssl.crt");
754
			$key = file_get_contents("{$g['tmp_path']}/ssl.key");
755
			unlink("{$g['tmp_path']}/ssl.key");
756
			unlink("{$g['tmp_path']}/ssl.crt");
757
			cert_import($cert, $crt, $key);
758
			$a_cert[] = $cert;
759
			$config['system']['webgui']['ssl-certref'] = $cert['refid'];
760
			write_config("Importing HTTPS certificate");
761
			if(!$config['system']['webgui']['port'])
762
				$portarg = "443";
763
			$ca = ca_chain($cert);
764
		} else {
765
			$crt = base64_decode($cert['crt']);
766
			$key = base64_decode($cert['prv']);
767
			if(!$config['system']['webgui']['port'])
768
				$portarg = "443";
769
			$ca = ca_chain($cert);
770
		}
771
	}
772

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

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

    
780
	/* fetch page to preload apc cache */
781
	$proto = "http";
782
	if ($config['system']['webgui']['protocol'])
783
		$proto = $config['system']['webgui']['protocol'];
784
	mwexec_bg("/usr/bin/fetch -o /dev/null -q {$proto}://localhost:{$portarg}/preload.php");
785

    
786
	if ($g['booting']) {
787
		if ($res == 0)
788
			echo "done.\n";
789
		else
790
			echo "failed!\n";
791
	}
792

    
793
	return $res;
794
}
795

    
796
function system_generate_lighty_config($filename,
797
	$cert,
798
	$key,
799
	$ca,
800
	$pid_file,
801
	$port = 80,
802
	$document_root = "/usr/local/www/",
803
	$cert_location = "cert.pem",
804
	$ca_location = "ca.pem",
805
	$max_procs = 2,
806
	$max_requests = "2",
807
	$fast_cgi_enable = true,
808
	$captive_portal = false) {
809

    
810
	global $config, $g;
811

    
812
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
813
		mkdir("{$g['tmp_path']}/lighttpdcompress");
814

    
815
	if(isset($config['system']['developerspew'])) {
816
		$mt = microtime();
817
		echo "system_generate_lighty_config() being called $mt\n";
818
	}
819

    
820
	if($captive_portal == true)  {
821
		$captiveportal = ",\"mod_rewrite\"";
822
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?redirurl=$1\" )\n";
823
		$captive_portal_module = "\"mod_accesslog\", ";
824
		$maxprocperip = $config['captiveportal']['maxprocperip'];
825
		if(!$maxprocperip and $maxprocperip > 0)
826
			$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
827
		else
828
			$captive_portal_mod_evasive = "";
829
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
830
		exec("mkdir -p {$g['tmp_path']}/captiveportal");
831
		exec("chmod a-w {$g['tmp_path']}/captiveportal");
832
		$server_max_request_size = "server.max-request-size    = 384";
833
	} else {
834
		$captiveportal = "";
835
		$captive_portal_rewrite = "";
836
		$captive_portal_module = "";
837
		$captive_portal_mod_evasive = "";
838
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
839
		$server_max_request_size = "server.max-request-size    = 2097152";
840
	}
841
	
842
	if($port <> "")
843
		$lighty_port = $port;
844
	else
845
		$lighty_port = "80";
846

    
847
	$memory = get_memory();
848
	$avail = $memory[0];
849

    
850
	if($avail > 0 and $avail < 65) {
851
		$fast_cgi_enable = false;
852
	}
853

    
854
	// Ramp up captive portal max procs
855
	if($captive_portal == true)  {
856
		if($avail > 65 and $avail < 98) {
857
			$max_procs = 1;
858
		}
859
		if($avail > 97 and $avail < 128) {
860
			$max_procs = 2;
861
		}
862
		if($avail > 127 and $avail < 256) {
863
			$max_procs = 3;
864
		}
865
		if($avail > 255 and $avail < 384) {
866
			$max_procs = 4;
867
		}
868
		if($avail > 383) {
869
			$max_procs = 5;
870
		}
871
	}
872

    
873
	if($captive_portal == true)  {	
874
		$bin_environment =  <<<EOC
875
        "bin-environment" => (
876
           "PHP_FCGI_CHILDREN" => "$max_procs",
877
           "PHP_FCGI_MAX_REQUESTS" => "500"
878
        ), 
879
EOC;
880

    
881
	} else if ($avail > 0 and $avail < 128) {
882
		$bin_environment = <<<EOC
883
		"bin-environment" => (
884
			"PHP_FCGI_CHILDREN" => "$max_procs",
885
			"PHP_FCGI_MAX_REQUESTS" => "2",
886
	),
887

    
888
EOC;
889
	} else
890
		$bin_environment =  <<<EOC
891
        "bin-environment" => (
892
           "PHP_FCGI_CHILDREN" => "$max_procs",
893
           "PHP_FCGI_MAX_REQUESTS" => "500"
894
        ), 
895
EOC;
896

    
897
	if($fast_cgi_enable == true) {
898
		$module = "\"mod_fastcgi\", \"mod_cgi\"";
899
		$cgi_config = "";
900
		$fastcgi_config = <<<EOD
901
#### fastcgi module
902
## read fastcgi.txt for more info
903
fastcgi.server = ( ".php" =>
904
	( "localhost" =>
905
		(
906
			"socket" => "{$g['tmp_path']}/php-fastcgi.socket",
907
			"min-procs" => 0,
908
			"max-procs" => {$max_procs},
909
			{$bin_environment}			
910
			"bin-path" => "/usr/local/bin/php"
911
		)
912
	)
913
)
914

    
915
#### CGI module
916
cgi.assign                 = ( ".cgi" => "" )
917

    
918
EOD;
919
	} else {
920
		$fastcgi_config = "";
921
		$module = "\"mod_cgi\"";
922
		$cgi_config = <<<EOD
923
#### CGI module
924
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
925
                               ".cgi" => "" )
926

    
927
EOD;
928
	}
929

    
930
	$lighty_config = "";
931
	$lighty_config .= <<<EOD
932
#
933
# lighttpd configuration file
934
#
935
# use a it as base for lighttpd 1.0.0 and above
936
#
937
############ Options you really have to take care of ####################
938

    
939
## FreeBSD!
940
server.event-handler	= "freebsd-kqueue"
941
server.network-backend 	= "writev"
942

    
943
## modules to load
944
server.modules              =   (
945
									{$captive_portal_module}
946
									"mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect",
947
									{$module}{$captiveportal}
948
								)
949

    
950
## Unused modules
951
#                               "mod_setenv",
952
#                               "mod_rewrite",
953
#                               "mod_ssi",
954
#                               "mod_usertrack",
955
#                               "mod_expire",
956
#                               "mod_secdownload",
957
#                               "mod_rrdtool",
958
#                               "mod_auth",
959
#                               "mod_status",
960
#                               "mod_alias",
961
#                               "mod_proxy",
962
#                               "mod_simple_vhost",
963
#                               "mod_evhost",
964
#                               "mod_userdir",
965
#                               "mod_cgi",
966

    
967
server.max-keep-alive-requests = 15
968
server.max-keep-alive-idle = 30
969

    
970
## a static document-root, for virtual-hosting take look at the
971
## server.virtual-* options
972
server.document-root        = "{$document_root}"
973
{$captive_portal_rewrite}
974

    
975
# Maximum idle time with nothing being written (php downloading)
976
server.max-write-idle = 999
977

    
978
## where to send error-messages to
979
server.errorlog             = "/var/log/lighttpd.error.log"
980

    
981
# files to check for if .../ is requested
982
server.indexfiles           = ( "index.php", "index.html",
983
                                "index.htm", "default.htm" )
984

    
985
# mimetype mapping
986
mimetype.assign             = (
987
  ".pdf"          =>      "application/pdf",
988
  ".sig"          =>      "application/pgp-signature",
989
  ".spl"          =>      "application/futuresplash",
990
  ".class"        =>      "application/octet-stream",
991
  ".ps"           =>      "application/postscript",
992
  ".torrent"      =>      "application/x-bittorrent",
993
  ".dvi"          =>      "application/x-dvi",
994
  ".gz"           =>      "application/x-gzip",
995
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
996
  ".swf"          =>      "application/x-shockwave-flash",
997
  ".tar.gz"       =>      "application/x-tgz",
998
  ".tgz"          =>      "application/x-tgz",
999
  ".tar"          =>      "application/x-tar",
1000
  ".zip"          =>      "application/zip",
1001
  ".mp3"          =>      "audio/mpeg",
1002
  ".m3u"          =>      "audio/x-mpegurl",
1003
  ".wma"          =>      "audio/x-ms-wma",
1004
  ".wax"          =>      "audio/x-ms-wax",
1005
  ".ogg"          =>      "audio/x-wav",
1006
  ".wav"          =>      "audio/x-wav",
1007
  ".gif"          =>      "image/gif",
1008
  ".jpg"          =>      "image/jpeg",
1009
  ".jpeg"         =>      "image/jpeg",
1010
  ".png"          =>      "image/png",
1011
  ".xbm"          =>      "image/x-xbitmap",
1012
  ".xpm"          =>      "image/x-xpixmap",
1013
  ".xwd"          =>      "image/x-xwindowdump",
1014
  ".css"          =>      "text/css",
1015
  ".html"         =>      "text/html",
1016
  ".htm"          =>      "text/html",
1017
  ".js"           =>      "text/javascript",
1018
  ".asc"          =>      "text/plain",
1019
  ".c"            =>      "text/plain",
1020
  ".conf"         =>      "text/plain",
1021
  ".text"         =>      "text/plain",
1022
  ".txt"          =>      "text/plain",
1023
  ".dtd"          =>      "text/xml",
1024
  ".xml"          =>      "text/xml",
1025
  ".mpeg"         =>      "video/mpeg",
1026
  ".mpg"          =>      "video/mpeg",
1027
  ".mov"          =>      "video/quicktime",
1028
  ".qt"           =>      "video/quicktime",
1029
  ".avi"          =>      "video/x-msvideo",
1030
  ".asf"          =>      "video/x-ms-asf",
1031
  ".asx"          =>      "video/x-ms-asf",
1032
  ".wmv"          =>      "video/x-ms-wmv",
1033
  ".bz2"          =>      "application/x-bzip",
1034
  ".tbz"          =>      "application/x-bzip-compressed-tar",
1035
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
1036
 )
1037

    
1038
# Use the "Content-Type" extended attribute to obtain mime type if possible
1039
#mimetypes.use-xattr        = "enable"
1040

    
1041
#### accesslog module
1042
#accesslog.filename          = "/dev/null"
1043

    
1044
## deny access the file-extensions
1045
#
1046
# ~    is for backupfiles from vi, emacs, joe, ...
1047
# .inc is often used for code includes which should in general not be part
1048
#      of the document-root
1049
url.access-deny             = ( "~", ".inc" )
1050

    
1051

    
1052
######### Options that are good to be but not neccesary to be changed #######
1053

    
1054
## bind to port (default: 80)
1055
server.port                = {$lighty_port}
1056

    
1057
## error-handler for status 404
1058
#server.error-handler-404   = "/error-handler.html"
1059
#server.error-handler-404   = "/error-handler.php"
1060

    
1061
## to help the rc.scripts
1062
server.pid-file            = "/var/run/{$pid_file}"
1063

    
1064
## virtual directory listings
1065
server.dir-listing         = "disable"
1066

    
1067
## enable debugging
1068
debug.log-request-header   = "disable"
1069
debug.log-response-header  = "disable"
1070
debug.log-request-handling = "disable"
1071
debug.log-file-not-found   = "disable"
1072

    
1073
# gzip compression
1074
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1075
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1076

    
1077
{$server_upload_dirs}
1078

    
1079
{$server_max_request_size}
1080

    
1081
{$fastcgi_config}
1082

    
1083
{$cgi_config}
1084

    
1085
{$captive_portal_mod_evasive}
1086

    
1087
expire.url = (
1088
				"" => "access 50 hours",	
1089
        )
1090

    
1091
EOD;
1092

    
1093
	$cert = str_replace("\r", "", $cert);
1094
	$key = str_replace("\r", "", $key);
1095
	$ca = str_replace("\r", "", $ca);
1096

    
1097
	$cert = str_replace("\n\n", "\n", $cert);
1098
	$key = str_replace("\n\n", "\n", $key);
1099
	$ca = str_replace("\n\n", "\n", $ca);
1100

    
1101
	if($cert <> "" and $key <> "") {
1102
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1103
		if (!$fd) {
1104
			printf("Error: cannot open cert.pem in system_webgui_start().\n");
1105
			return 1;
1106
		}
1107
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1108
		fwrite($fd, $cert);
1109
		fwrite($fd, "\n");
1110
		fwrite($fd, $key);
1111
		fclose($fd);
1112
		if($ca <> "") {
1113
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1114
			if (!$fd) {
1115
				printf("Error: cannot open ca.pem in system_webgui_start().\n");
1116
				return 1;
1117
			}
1118
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1119
			fwrite($fd, $ca);
1120
			fclose($fd);
1121
		}
1122
		$lighty_config .= "\n";
1123
		$lighty_config .= "## ssl configuration\n";
1124
		$lighty_config .= "ssl.engine = \"enable\"\n";
1125
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1126
		if($ca <> "")
1127
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1128
	}
1129

    
1130
	// Add HTTP to HTTPS redirect	
1131
	if ($captive_portal == false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1132
		if($lighty_port != "443") 
1133
			$redirectport = ":{$lighty_port}";
1134
		$lighty_config .= <<<EOD
1135
\$SERVER["socket"] == ":80" {
1136
	\$HTTP["host"] =~ "(.*)" {
1137
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1138
	}
1139
}
1140
EOD;
1141
	}
1142

    
1143
	$fd = fopen("{$filename}", "w");
1144
	if (!$fd) {
1145
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
1146
		return 1;
1147
	}
1148
	fwrite($fd, $lighty_config);
1149
	fclose($fd);
1150

    
1151
	return 0;
1152

    
1153
}
1154

    
1155
function system_timezone_configure() {
1156
	global $config, $g;
1157
	if(isset($config['system']['developerspew'])) {
1158
		$mt = microtime();
1159
		echo "system_timezone_configure() being called $mt\n";
1160
	}
1161

    
1162
	$syscfg = $config['system'];
1163

    
1164
	if ($g['booting'])
1165
		echo "Setting timezone...";
1166

    
1167
	/* extract appropriate timezone file */
1168
	$timezone = $syscfg['timezone'];
1169
	if (!$timezone)
1170
		$timezone = "Etc/UTC";
1171

    
1172
	conf_mount_rw();
1173

    
1174
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1175
		escapeshellarg($timezone) . " > /etc/localtime");
1176

    
1177
	mwexec("sync");
1178
	conf_mount_ro();
1179

    
1180
	if ($g['booting'])
1181
		echo "done.\n";
1182
}
1183

    
1184
function system_ntp_configure() {
1185
	global $config, $g;
1186

    
1187
	$syscfg =& $config['system'];
1188

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

    
1196
	fwrite($fd, "# \n");
1197
	fwrite($fd, "# pfSense OpenNTPD configuration file \n");
1198
	fwrite($fd, "# \n\n");
1199

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

    
1204
	/* Setup listener(s) if the user has configured one */
1205
        if ($config['installedpackages']['openntpd']) {
1206
    		/* server config is in coregui1 */
1207
		$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
1208
		if ($xmlsettings['enable'] == 'on') {
1209
			$ifaces = explode(',', $xmlsettings['interface']);
1210
			$ifaces = array_map('get_real_interface', $ifaces);
1211
			$ifaces = array_filter($ifaces, 'does_interface_exist');
1212
			$ips = array_map('find_interface_ip', $ifaces);
1213
			foreach ($ips as $ip) {
1214
				if (is_ipaddr($ip))
1215
					fwrite($fd, "listen on $ip\n");
1216
			}
1217
		}
1218
	}
1219

    
1220
	fwrite($fd, "\n");
1221

    
1222
	/* slurp! */
1223
	fclose($fd);
1224

    
1225
	/* if openntpd is running, kill it */
1226
	while(is_process_running("ntpd")) {
1227
		killbyname("ntpd");
1228
	}
1229

    
1230
	/* if /var/empty does not exist, create it */
1231
	if(!is_dir("/var/empty"))
1232
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1233

    
1234
	if ($g['booting'])
1235
		return;
1236

    
1237
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1238
	exec("/usr/local/sbin/ntpd -s -f {$g['varetc_path']}/ntpd.conf");
1239
	
1240
	// Note that we are starting up
1241
	exec("echo 'OpenNTPD is starting up' >> {$g['varlog_path']}/ntpd.log");
1242

    
1243
}
1244

    
1245
function sync_system_time() {
1246
	global $config, $g;
1247

    
1248
	$syscfg = $config['system'];
1249

    
1250
	if ($g['booting'])
1251
		echo "Syncing system time before startup...";
1252

    
1253
	/* foreach through servers and write out to ntpd.conf */
1254
	foreach (explode(' ', $syscfg['timeservers']) as $ts) {
1255
		mwexec("/usr/sbin/ntpdate -s $ts");
1256
	}
1257
	
1258
	if ($g['booting'])
1259
		echo "done.\n";
1260
	
1261
}
1262

    
1263
function system_halt() {
1264
	global $g;
1265

    
1266
	system_reboot_cleanup();
1267

    
1268
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1269
}
1270

    
1271
function system_reboot() {
1272
	global $g;
1273

    
1274
	system_reboot_cleanup();
1275

    
1276
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1277
}
1278

    
1279
function system_reboot_sync() {
1280
	global $g;
1281

    
1282
	system_reboot_cleanup();
1283

    
1284
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1285
}
1286

    
1287
function system_reboot_cleanup() {
1288
	mwexec("/usr/local/bin/beep.sh stop");
1289
	require_once("captiveportal.inc");
1290
	captiveportal_radius_stop_all();
1291
	require_once("voucher.inc");
1292
	voucher_save_db_to_config();
1293
}
1294

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

    
1302
	if ($early)
1303
		$cmdn = "earlyshellcmd";
1304
	else
1305
		$cmdn = "shellcmd";
1306

    
1307
	if (is_array($config['system'][$cmdn])) {
1308

    
1309
		/* *cmd is an array, loop through */
1310
		foreach ($config['system'][$cmdn] as $cmd) {
1311
			exec($cmd);
1312
		}
1313

    
1314
	} elseif($config['system'][$cmdn] <> "") {
1315

    
1316
		/* execute single item */
1317
		exec($config['system'][$cmdn]);
1318

    
1319
	}
1320
}
1321

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

    
1329
	if (isset($config['system']['disableconsolemenu'])) {
1330
		touch("{$g['varetc_path']}/disableconsole");
1331
	} else {
1332
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1333
	}
1334
}
1335

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

    
1343
	$dmesg = "";
1344
	exec("/sbin/dmesg", $dmesg);
1345

    
1346
	/* find last copyright line (output from previous boots may be present) */
1347
	$lastcpline = 0;
1348

    
1349
	for ($i = 0; $i < count($dmesg); $i++) {
1350
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1351
			$lastcpline = $i;
1352
	}
1353

    
1354
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1355
	if (!$fd) {
1356
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1357
		return 1;
1358
	}
1359

    
1360
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1361
		fwrite($fd, $dmesg[$i] . "\n");
1362

    
1363
	fclose($fd);
1364

    
1365
	return 0;
1366
}
1367

    
1368
function system_set_harddisk_standby() {
1369
	global $g, $config;
1370
	if(isset($config['system']['developerspew'])) {
1371
		$mt = microtime();
1372
		echo "system_set_harddisk_standby() being called $mt\n";
1373
	}
1374

    
1375
	if (isset($config['system']['harddiskstandby'])) {
1376
		if ($g['booting']) {
1377
			echo 'Setting hard disk standby... ';
1378
		}
1379

    
1380
		$standby = $config['system']['harddiskstandby'];
1381
		// Check for a numeric value
1382
		if (is_numeric($standby)) {
1383
			// Sync the disk(s)
1384
			mwexec('/bin/sync');
1385
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1386
				// Reinitialize ATA-drives
1387
				mwexec('/usr/local/sbin/atareinit');
1388
				if ($g['booting']) {
1389
					echo "done.\n";
1390
				}
1391
			} else if ($g['booting']) {
1392
				echo "failed!\n";
1393
			}
1394
		} else if ($g['booting']) {
1395
			echo "failed!\n";
1396
		}
1397
	}
1398
}
1399

    
1400
function system_setup_sysctl() {
1401
	global $config;
1402
	if(isset($config['system']['developerspew'])) {
1403
		$mt = microtime();
1404
		echo "system_setup_sysctl() being called $mt\n";
1405
	}
1406

    
1407
	activate_sysctls();	
1408

    
1409
	if (isset($config['system']['sharednet'])) {
1410
		system_disable_arp_wrong_if();
1411
	}
1412
}
1413

    
1414
function system_disable_arp_wrong_if() {
1415
	global $config;
1416
	if(isset($config['system']['developerspew'])) {
1417
		$mt = microtime();
1418
		echo "system_disable_arp_wrong_if() being called $mt\n";
1419
	}
1420
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1421
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1422
}
1423

    
1424
function system_enable_arp_wrong_if() {
1425
	global $config;
1426
	if(isset($config['system']['developerspew'])) {
1427
		$mt = microtime();
1428
		echo "system_enable_arp_wrong_if() being called $mt\n";
1429
	}
1430
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1431
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1432
}
1433

    
1434
function enable_watchdog() {
1435
	global $config;
1436
	return;
1437
	$install_watchdog = false;
1438
	$supported_watchdogs = array("Geode");
1439
	$file = file_get_contents("/var/log/dmesg.boot");
1440
	foreach($supported_watchdogs as $sd) {
1441
		if(stristr($file, "Geode")) {
1442
			$install_watchdog = true;
1443
		}
1444
	}
1445
	if($install_watchdog == true) {
1446
		if(is_process_running("watchdogd"))
1447
			mwexec("/usr/bin/killall watchdogd", true);
1448
		exec("/usr/sbin/watchdogd");
1449
	}
1450
}
1451

    
1452
function system_check_reset_button() {
1453
	global $g;
1454
	if($g['platform'] != "nanobsd")
1455
		return 0;
1456

    
1457
	$specplatform = system_identify_specific_platform();
1458

    
1459
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1460
		return 0;
1461

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

    
1464
	if ($retval == 99) {
1465
		/* user has pressed reset button for 2 seconds - 
1466
		   reset to factory defaults */
1467
		echo <<<EOD
1468

    
1469
***********************************************************************
1470
* Reset button pressed - resetting configuration to factory defaults. *
1471
* The system will reboot after this completes.                        *
1472
***********************************************************************
1473

    
1474

    
1475
EOD;
1476
		
1477
		reset_factory_defaults();
1478
		system_reboot_sync();
1479
		exit(0);
1480
	}
1481

    
1482
	return 0;
1483
}
1484

    
1485
/* attempt to identify the specific platform (for embedded systems)
1486
   Returns an array with two elements:
1487
	name => platform string (e.g. 'wrap', 'alix' etc.)
1488
	descr => human-readable description (e.g. "PC Engines WRAP")
1489
*/
1490
function system_identify_specific_platform() {
1491
	global $g;
1492
	
1493
	if ($g['platform'] == 'generic-pc')
1494
		return array('name' => 'generic-pc', 'descr' => "Generic PC");
1495
	
1496
	if ($g['platform'] == 'generic-pc-cdrom')
1497
		return array('name' => 'generic-pc-cdrom', 'descr' => "Generic PC (CD-ROM)");
1498
	
1499
	/* the rest of the code only deals with 'embedded' platforms */
1500
	if ($g['platform'] != 'nanobsd')
1501
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1502
	
1503
	$dmesg = system_get_dmesg_boot();
1504
	
1505
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1506
		return array('name' => 'wrap', 'descr' => 'PC Engines WRAP');
1507
	
1508
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1509
		return array('name' => 'alix', 'descr' => 'PC Engines ALIX');
1510

    
1511
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1512
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1513
	
1514
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1515
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1516
		
1517
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1518
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1519
	
1520
	/* unknown embedded platform */
1521
	return array('name' => 'embedded', 'descr' => 'embedded (unknown)');
1522
}
1523

    
1524
function system_get_dmesg_boot() {
1525
	global $g;
1526
		
1527
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1528
}
1529

    
1530
?>
(40-40/54)