Project

General

Profile

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

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

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

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

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

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

    
32
/*
33
	pfSense_BUILDER_BINARIES:	/usr/sbin/powerd	/usr/bin/killall	/sbin/sysctl	/sbin/route
34
	pfSense_BUILDER_BINARIES:	/bin/hostname	/bin/ls	/usr/bin/netstat	/usr/sbin/syslogd	
35
	pfSense_BUILDER_BINARIES:	/usr/sbin/pccardd	/usr/local/sbin/lighttpd	/bin/chmod 	/bin/mkdir
36
	pfSense_BUILDER_BINARIES:	/usr/bin/tar	/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
	$routev6_arr = array();
401
	foreach($routev6_str as $routeline) {
402
		$items = preg_split("/[ ]+/i", $routeline);
403
		$routev6_arr[$items[0]] = array($items[0], $items[1], $items[5]);
404
	}
405

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

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

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

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

    
452
	return 0;
453
}
454

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

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

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

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

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

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

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

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

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

    
621
EOD;
622

    
623
}
624

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

    
634
EOD;
635

    
636
}
637

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

    
647
EOD;
648

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

    
655
EOD;
656

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

    
661
EOD;
662

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

    
667
EOD;
668

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

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

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

    
685
	return $retval;
686
}
687

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

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

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

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

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

    
711
	return $res;
712
}
713

    
714

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

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

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

    
724
	sleep(1);
725

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

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

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

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

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

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

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

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

    
794
	return $res;
795
}
796

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

    
811
	global $config, $g;
812

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

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

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

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

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

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

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

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

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

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

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

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

    
928
EOD;
929
	}
930

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

    
940
## FreeBSD!
941
server.event-handler	= "freebsd-kqueue"
942
server.network-backend 	= "writev"
943
#server.use-ipv6 = "enable"
944

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

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

    
969
server.max-keep-alive-requests = 15
970
server.max-keep-alive-idle = 30
971

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

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

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

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

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

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

    
1043
#### accesslog module
1044
#accesslog.filename          = "/dev/null"
1045

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

    
1053

    
1054
######### Options that are good to be but not neccesary to be changed #######
1055

    
1056
## bind to port (default: 80)
1057

    
1058
EOD;
1059

    
1060
	if($captive_portal == true) {
1061
		$lighty_config .= "server.bind	= \"127.0.0.1\"\n";
1062
		$lighty_config .= "server.port  = {$lighty_port}\n";
1063
		$lighty_config .= "\$SERVER[\"socket\"]  == \"127.0.0.1:443\" { }\n";
1064
		$lighty_config .= "\$SERVER[\"socket\"]  == \"[::1]:443\" { \n";
1065
		$lighty_config .= "\$SERVER[\"socket\"]  == \"[::1]:443\" { \n";
1066
		if($cert <> "" and $key <> "") {
1067
			$lighty_config .= "\n";
1068
			$lighty_config .= "## ssl configuration\n";
1069
			$lighty_config .= "ssl.engine = \"enable\"\n";
1070
			$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1071
			if($ca <> "")
1072
				$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1073
		}
1074
		$lighty_config .= " }\n";
1075
	} else {
1076
		$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1077
		$lighty_config .= "server.port  = {$lighty_port}\n";
1078
		$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:443\" { }\n";
1079
		$lighty_config .= "\$SERVER[\"socket\"]  == \"[::]:443\" { \n";
1080
		if($cert <> "" and $key <> "") {
1081
			$lighty_config .= "\n";
1082
			$lighty_config .= "## ssl configuration\n";
1083
			$lighty_config .= "ssl.engine = \"enable\"\n";
1084
			$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1085
			if($ca <> "")
1086
				$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1087
		}
1088
		$lighty_config .= " }\n";
1089
	}
1090

    
1091

    
1092
	$lighty_config .= <<<EOD
1093

    
1094

    
1095
## error-handler for status 404
1096
#server.error-handler-404   = "/error-handler.html"
1097
#server.error-handler-404   = "/error-handler.php"
1098

    
1099
## to help the rc.scripts
1100
server.pid-file            = "/var/run/{$pid_file}"
1101

    
1102
## virtual directory listings
1103
server.dir-listing         = "disable"
1104

    
1105
## enable debugging
1106
debug.log-request-header   = "disable"
1107
debug.log-response-header  = "disable"
1108
debug.log-request-handling = "disable"
1109
debug.log-file-not-found   = "disable"
1110

    
1111
# gzip compression
1112
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1113
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1114

    
1115
{$server_upload_dirs}
1116

    
1117
{$server_max_request_size}
1118

    
1119
{$fastcgi_config}
1120

    
1121
{$cgi_config}
1122

    
1123
{$captive_portal_mod_evasive}
1124

    
1125
expire.url = (
1126
				"" => "access 50 hours",	
1127
        )
1128

    
1129
EOD;
1130

    
1131
	$cert = str_replace("\r", "", $cert);
1132
	$key = str_replace("\r", "", $key);
1133
	$ca = str_replace("\r", "", $ca);
1134

    
1135
	$cert = str_replace("\n\n", "\n", $cert);
1136
	$key = str_replace("\n\n", "\n", $key);
1137
	$ca = str_replace("\n\n", "\n", $ca);
1138

    
1139
	if($cert <> "" and $key <> "") {
1140
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1141
		if (!$fd) {
1142
			printf("Error: cannot open cert.pem in system_webgui_start().\n");
1143
			return 1;
1144
		}
1145
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1146
		fwrite($fd, $cert);
1147
		fwrite($fd, "\n");
1148
		fwrite($fd, $key);
1149
		fclose($fd);
1150
		if($ca <> "") {
1151
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1152
			if (!$fd) {
1153
				printf("Error: cannot open ca.pem in system_webgui_start().\n");
1154
				return 1;
1155
			}
1156
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1157
			fwrite($fd, $ca);
1158
			fclose($fd);
1159
		}
1160
		$lighty_config .= "\n";
1161
		$lighty_config .= "## ssl configuration\n";
1162
		$lighty_config .= "ssl.engine = \"enable\"\n";
1163
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1164
		if($ca <> "")
1165
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1166
	}
1167

    
1168
	// Add HTTP to HTTPS redirect	
1169
	if ($captive_portal == false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1170
		if($lighty_port != "443") 
1171
			$redirectport = ":{$lighty_port}";
1172
		$lighty_config .= <<<EOD
1173
\$SERVER["socket"] == ":80" {
1174
	\$HTTP["host"] =~ "(.*)" {
1175
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1176
	}
1177
}
1178
EOD;
1179
	}
1180

    
1181
	$fd = fopen("{$filename}", "w");
1182
	if (!$fd) {
1183
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
1184
		return 1;
1185
	}
1186
	fwrite($fd, $lighty_config);
1187
	fclose($fd);
1188

    
1189
	return 0;
1190

    
1191
}
1192

    
1193
function system_timezone_configure() {
1194
	global $config, $g;
1195
	if(isset($config['system']['developerspew'])) {
1196
		$mt = microtime();
1197
		echo "system_timezone_configure() being called $mt\n";
1198
	}
1199

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

    
1202
	if ($g['booting'])
1203
		echo "Setting timezone...";
1204

    
1205
	/* extract appropriate timezone file */
1206
	$timezone = $syscfg['timezone'];
1207
	if (!$timezone)
1208
		$timezone = "Etc/UTC";
1209

    
1210
	conf_mount_rw();
1211

    
1212
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1213
		escapeshellarg($timezone) . " > /etc/localtime");
1214

    
1215
	mwexec("sync");
1216
	conf_mount_ro();
1217

    
1218
	if ($g['booting'])
1219
		echo "done.\n";
1220
}
1221

    
1222
function system_ntp_configure() {
1223
	global $config, $g;
1224

    
1225
	$syscfg =& $config['system'];
1226

    
1227
	/* open configuration for wrting or bail */
1228
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1229
	if(!$fd) {
1230
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1231
		return;
1232
	}
1233

    
1234
	fwrite($fd, "# \n");
1235
	fwrite($fd, "# pfSense OpenNTPD configuration file \n");
1236
	fwrite($fd, "# \n\n");
1237

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

    
1242
	/* Setup listener(s) if the user has configured one */
1243
        if ($config['installedpackages']['openntpd']) {
1244
    		/* server config is in coregui1 */
1245
		$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
1246
		if ($xmlsettings['enable'] == 'on') {
1247
			$ifaces = explode(',', $xmlsettings['interface']);
1248
			$ifaces = array_map('get_real_interface', $ifaces);
1249
			$ifaces = array_filter($ifaces, 'does_interface_exist');
1250
			$ips = array_map('find_interface_ip', $ifaces);
1251
			foreach ($ips as $ip) {
1252
				if (is_ipaddr($ip))
1253
					fwrite($fd, "listen on $ip\n");
1254
			}
1255
		}
1256
	}
1257

    
1258
	fwrite($fd, "\n");
1259

    
1260
	/* slurp! */
1261
	fclose($fd);
1262

    
1263
	/* if openntpd is running, kill it */
1264
	while(is_process_running("ntpd")) {
1265
		killbyname("ntpd");
1266
	}
1267

    
1268
	/* if /var/empty does not exist, create it */
1269
	if(!is_dir("/var/empty"))
1270
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1271

    
1272
	if ($g['booting'])
1273
		return;
1274

    
1275
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1276
	exec("/usr/local/sbin/ntpd -s -f {$g['varetc_path']}/ntpd.conf");
1277
	
1278
	// Note that we are starting up
1279
	exec("echo 'OpenNTPD is starting up' >> {$g['varlog_path']}/ntpd.log");
1280

    
1281
}
1282

    
1283
function sync_system_time() {
1284
	global $config, $g;
1285

    
1286
	$syscfg = $config['system'];
1287

    
1288
	if ($g['booting'])
1289
		echo "Syncing system time before startup...";
1290

    
1291
	/* foreach through servers and write out to ntpd.conf */
1292
	foreach (explode(' ', $syscfg['timeservers']) as $ts) {
1293
		mwexec("/usr/sbin/ntpdate -s $ts");
1294
	}
1295
	
1296
	if ($g['booting'])
1297
		echo "done.\n";
1298
	
1299
}
1300

    
1301
function system_halt() {
1302
	global $g;
1303

    
1304
	system_reboot_cleanup();
1305

    
1306
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1307
}
1308

    
1309
function system_reboot() {
1310
	global $g;
1311

    
1312
	system_reboot_cleanup();
1313

    
1314
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1315
}
1316

    
1317
function system_reboot_sync() {
1318
	global $g;
1319

    
1320
	system_reboot_cleanup();
1321

    
1322
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1323
}
1324

    
1325
function system_reboot_cleanup() {
1326
	mwexec("/usr/local/bin/beep.sh stop");
1327
	require_once("captiveportal.inc");
1328
	captiveportal_radius_stop_all();
1329
	require_once("voucher.inc");
1330
	voucher_save_db_to_config();
1331
}
1332

    
1333
function system_do_shell_commands($early = 0) {
1334
	global $config, $g;
1335
	if(isset($config['system']['developerspew'])) {
1336
		$mt = microtime();
1337
		echo "system_do_shell_commands() being called $mt\n";
1338
	}
1339

    
1340
	if ($early)
1341
		$cmdn = "earlyshellcmd";
1342
	else
1343
		$cmdn = "shellcmd";
1344

    
1345
	if (is_array($config['system'][$cmdn])) {
1346

    
1347
		/* *cmd is an array, loop through */
1348
		foreach ($config['system'][$cmdn] as $cmd) {
1349
			exec($cmd);
1350
		}
1351

    
1352
	} elseif($config['system'][$cmdn] <> "") {
1353

    
1354
		/* execute single item */
1355
		exec($config['system'][$cmdn]);
1356

    
1357
	}
1358
}
1359

    
1360
function system_console_configure() {
1361
	global $config, $g;
1362
	if(isset($config['system']['developerspew'])) {
1363
		$mt = microtime();
1364
		echo "system_console_configure() being called $mt\n";
1365
	}
1366

    
1367
	if (isset($config['system']['disableconsolemenu'])) {
1368
		touch("{$g['varetc_path']}/disableconsole");
1369
	} else {
1370
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1371
	}
1372
}
1373

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

    
1381
	$dmesg = "";
1382
	exec("/sbin/dmesg", $dmesg);
1383

    
1384
	/* find last copyright line (output from previous boots may be present) */
1385
	$lastcpline = 0;
1386

    
1387
	for ($i = 0; $i < count($dmesg); $i++) {
1388
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1389
			$lastcpline = $i;
1390
	}
1391

    
1392
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1393
	if (!$fd) {
1394
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1395
		return 1;
1396
	}
1397

    
1398
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1399
		fwrite($fd, $dmesg[$i] . "\n");
1400

    
1401
	fclose($fd);
1402

    
1403
	return 0;
1404
}
1405

    
1406
function system_set_harddisk_standby() {
1407
	global $g, $config;
1408
	if(isset($config['system']['developerspew'])) {
1409
		$mt = microtime();
1410
		echo "system_set_harddisk_standby() being called $mt\n";
1411
	}
1412

    
1413
	if (isset($config['system']['harddiskstandby'])) {
1414
		if ($g['booting']) {
1415
			echo 'Setting hard disk standby... ';
1416
		}
1417

    
1418
		$standby = $config['system']['harddiskstandby'];
1419
		// Check for a numeric value
1420
		if (is_numeric($standby)) {
1421
			// Sync the disk(s)
1422
			mwexec('/bin/sync');
1423
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1424
				// Reinitialize ATA-drives
1425
				mwexec('/usr/local/sbin/atareinit');
1426
				if ($g['booting']) {
1427
					echo "done.\n";
1428
				}
1429
			} else if ($g['booting']) {
1430
				echo "failed!\n";
1431
			}
1432
		} else if ($g['booting']) {
1433
			echo "failed!\n";
1434
		}
1435
	}
1436
}
1437

    
1438
function system_setup_sysctl() {
1439
	global $config;
1440
	if(isset($config['system']['developerspew'])) {
1441
		$mt = microtime();
1442
		echo "system_setup_sysctl() being called $mt\n";
1443
	}
1444

    
1445
	activate_sysctls();	
1446

    
1447
	if (isset($config['system']['sharednet'])) {
1448
		system_disable_arp_wrong_if();
1449
	}
1450
}
1451

    
1452
function system_disable_arp_wrong_if() {
1453
	global $config;
1454
	if(isset($config['system']['developerspew'])) {
1455
		$mt = microtime();
1456
		echo "system_disable_arp_wrong_if() being called $mt\n";
1457
	}
1458
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1459
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1460
}
1461

    
1462
function system_enable_arp_wrong_if() {
1463
	global $config;
1464
	if(isset($config['system']['developerspew'])) {
1465
		$mt = microtime();
1466
		echo "system_enable_arp_wrong_if() being called $mt\n";
1467
	}
1468
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1469
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1470
}
1471

    
1472
function enable_watchdog() {
1473
	global $config;
1474
	return;
1475
	$install_watchdog = false;
1476
	$supported_watchdogs = array("Geode");
1477
	$file = file_get_contents("/var/log/dmesg.boot");
1478
	foreach($supported_watchdogs as $sd) {
1479
		if(stristr($file, "Geode")) {
1480
			$install_watchdog = true;
1481
		}
1482
	}
1483
	if($install_watchdog == true) {
1484
		if(is_process_running("watchdogd"))
1485
			mwexec("/usr/bin/killall watchdogd", true);
1486
		exec("/usr/sbin/watchdogd");
1487
	}
1488
}
1489

    
1490
function system_check_reset_button() {
1491
	global $g;
1492
	if($g['platform'] != "nanobsd")
1493
		return 0;
1494

    
1495
	$specplatform = system_identify_specific_platform();
1496

    
1497
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1498
		return 0;
1499

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

    
1502
	if ($retval == 99) {
1503
		/* user has pressed reset button for 2 seconds - 
1504
		   reset to factory defaults */
1505
		echo <<<EOD
1506

    
1507
***********************************************************************
1508
* Reset button pressed - resetting configuration to factory defaults. *
1509
* The system will reboot after this completes.                        *
1510
***********************************************************************
1511

    
1512

    
1513
EOD;
1514
		
1515
		reset_factory_defaults();
1516
		system_reboot_sync();
1517
		exit(0);
1518
	}
1519

    
1520
	return 0;
1521
}
1522

    
1523
/* attempt to identify the specific platform (for embedded systems)
1524
   Returns an array with two elements:
1525
	name => platform string (e.g. 'wrap', 'alix' etc.)
1526
	descr => human-readable description (e.g. "PC Engines WRAP")
1527
*/
1528
function system_identify_specific_platform() {
1529
	global $g;
1530
	
1531
	if ($g['platform'] == 'generic-pc')
1532
		return array('name' => 'generic-pc', 'descr' => "Generic PC");
1533
	
1534
	if ($g['platform'] == 'generic-pc-cdrom')
1535
		return array('name' => 'generic-pc-cdrom', 'descr' => "Generic PC (CD-ROM)");
1536
	
1537
	/* the rest of the code only deals with 'embedded' platforms */
1538
	if ($g['platform'] != 'nanobsd')
1539
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1540
	
1541
	$dmesg = system_get_dmesg_boot();
1542
	
1543
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1544
		return array('name' => 'wrap', 'descr' => 'PC Engines WRAP');
1545
	
1546
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1547
		return array('name' => 'alix', 'descr' => 'PC Engines ALIX');
1548

    
1549
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1550
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1551
	
1552
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1553
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1554
		
1555
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1556
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1557
	
1558
	/* unknown embedded platform */
1559
	return array('name' => 'embedded', 'descr' => 'embedded (unknown)');
1560
}
1561

    
1562
function system_get_dmesg_boot() {
1563
	global $g;
1564
		
1565
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1566
}
1567

    
1568
?>
(40-40/54)