Project

General

Profile

Download (42.7 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'])) {
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
	/* tack on all the hard defined gateways as well */
311
	if (is_array($config['gateways']['gateway_item'])) {
312
		mwexec("/bin/rm {$g['tmp_path']}/*_defaultgw", true);
313
		foreach	($config['gateways']['gateway_item'] as $gateway) {
314
			if (isset($gateway['defaultgw'])) {
315
				if ($gateway['gateway'] == "dynamic")
316
					$gateway['gateway'] = get_interface_gateway($gateway['interface']);
317
				$gatewayip = $gateway['gateway'];
318
				$interfacegw = $gateway['interface'];
319
				if (!empty($interfacegw)) {
320
					$defaultif = get_real_interface($gateway['interface']);
321
					if ($defaultif)
322
						@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gatewayip);
323
				}
324
				$foundgw = true;
325
				break;
326
			}
327
		}
328
	}
329
	if ($foundgw == false) {
330
		$defaultif = get_real_interface("wan");
331
		$interfacegw = "wan";
332
		$gatewayip = get_interface_gateway("wan");
333
		@touch("{$g['tmp_path']}/{$defaultif}_defaultgw");
334
	}	
335
	$dont_add_route = false;
336
	/* if OLSRD is enabled, allow WAN to house DHCP. */
337
	if($config['installedpackages']['olsrd']) {
338
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
339
			if($olsrd['enabledyngw'] == "on") {
340
				$dont_add_route = true;
341
				break;
342
			}
343
		}
344
	}
345
	/* Create a array from the existing route table */
346
	exec("/usr/bin/netstat -rnf inet", $route_str);
347
	array_shift($route_str);
348
	array_shift($route_str);
349
	array_shift($route_str);
350
	array_shift($route_str);
351
	$route_arr = array();
352
	foreach($route_str as $routeline) {
353
		$items = preg_split("/[ ]+/i", $routeline);
354
		$route_arr[$items[0]] = array($items[0], $items[1], $items[5]);
355
	}
356

    
357
	if ($dont_add_route == false ) {
358
		if (!empty($interface) && $interface != $interfacegw)
359
			;
360
		else if (($interfacegw <> "bgpd") && (is_ipaddr($gatewayip))) {
361
			$action = "add";
362
			if(isset($route_arr['default'])) {
363
				$action = "change";
364
			}
365
			log_error("ROUTING: $action default route to $gatewayip");
366
			mwexec("/sbin/route {$action} default " . escapeshellarg($gatewayip));
367
		}
368
	}
369

    
370
	if (is_array($config['staticroutes']['route'])) {
371
		$gateways_arr = return_gateways_array();
372

    
373
		foreach ($config['staticroutes']['route'] as $rtent) {
374
			$gatewayip = "";
375
			if (isset($gateways_arr[$rtent['gateway']])) {
376
				if ($interface == $gateways_arr[$rtent['gateway']]['friendlyiface'])
377
					continue;
378
				$gatewayip = $gateways_arr[$rtent['gateway']]['gateway'];
379
				$interfacegw = $gateways_arr[$rtent['gateway']]['interface'];
380
			} else {
381
				log_error("Static Routes: Gateway IP could not be found for {$rtent['network']}");
382
				continue;
383
			}
384

    
385
			$action = "add";
386
			if (isset($route_arr[$rtent['network']]))
387
				$action = "change";
388

    
389
			if (is_ipaddr($gatewayip)) {
390
				mwexec("/sbin/route {$action} " . escapeshellarg($rtent['network']) .
391
					" " . escapeshellarg($gatewayip));
392
			} else if (!empty($interfacegw)) {
393
				mwexec("/sbin/route {$action} " . escapeshellarg($rtent['network']) .
394
					" -iface " . escapeshellarg($interfacegw));
395
			}
396
		}
397
	}
398

    
399
	return 0;
400
}
401

    
402
function system_routing_enable() {
403
	global $config, $g;
404
	if(isset($config['system']['developerspew'])) {
405
		$mt = microtime();
406
		echo "system_routing_enable() being called $mt\n";
407
	}
408

    
409
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
410
}
411

    
412
function system_syslogd_start() {
413
	global $config, $g;
414
	if(isset($config['system']['developerspew'])) {
415
		$mt = microtime();
416
		echo "system_syslogd_start() being called $mt\n";
417
	}
418

    
419
	$syslogcfg = $config['syslog'];
420

    
421
	if ($g['booting'])
422
		echo "Starting syslog...";
423
	else
424
		killbypid("{$g['varrun_path']}/syslog.pid");
425

    
426
	if(is_process_running("syslogd"))
427
		mwexec("/usr/bin/killall -9 syslogd");
428
	if(is_process_running("fifolog_writer"))
429
		mwexec("/usr/bin/killall -9 fifolog_writer");
430
	
431
	// Define carious commands for logging
432
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
433
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
434
	$clog_create = "/usr/sbin/clog -i -s ";
435
	$clog_log = "%";
436

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

    
523
EOD;
524
		if (isset($syslogcfg['filter'])) {
525
			if($syslogcfg['remoteserver'])
526
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver']}\n";
527
			if($syslogcfg['remoteserver2'])
528
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver2']}\n";
529
			if($syslogcfg['remoteserver3'])
530
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver3']}\n";
531

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

    
566
EOD;
567

    
568
		if (isset($syslogcfg['system'])) {
569
			if($syslogcfg['remoteserver2'])
570
				$syslogconf .= <<<EOD
571
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver2']}
572
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver2']}
573
security.*										 @{$syslogcfg['remoteserver2']}
574
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver2']}
575
*.emerg											 @{$syslogcfg['remoteserver2']}
576

    
577
EOD;
578

    
579
		if (isset($syslogcfg['system'])) {
580
			if($syslogcfg['remoteserver3'])
581
				$syslogconf .= <<<EOD
582
*.notice;kern.debug;lpr.info;mail.crit;			 @{$syslogcfg['remoteserver3']}
583
news.err;local0.none;local3.none;local7.none	 @{$syslogcfg['remoteserver3']}
584
security.*										 @{$syslogcfg['remoteserver3']}
585
auth.info;authpriv.info;daemon.info				 @{$syslogcfg['remoteserver3']}
586
*.emerg											 @{$syslogcfg['remoteserver3']}
587

    
588
EOD;
589

    
590
}
591
		if (isset($syslogcfg['logall'])) {
592
			if($syslogcfg['remoteserver'])
593
				$syslogconf .= <<<EOD
594
*.*								@{$syslogcfg['remoteserver']}
595

    
596
EOD;
597

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

    
603
EOD;
604

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

    
610
EOD;
611

    
612
}
613
		fwrite($fd, $syslogconf);
614
		fclose($fd);
615
		// Are we logging to a least one remote server ?
616
		if(strpos($syslogconf, "@") != false)
617
			$retval = system("/usr/sbin/syslogd -c -f {$g['varetc_path']}/syslog.conf");
618
		else
619
			$retval = system("/usr/sbin/syslogd -c -f {$g['varetc_path']}/syslog.conf");
620

    
621
	} else {
622
		$retval = mwexec("/usr/sbin/syslogd -c");
623
	}
624

    
625
	if ($g['booting'])
626
		echo "done.\n";
627

    
628
	return $retval;
629
}
630

    
631
function system_pccard_start() {
632
	global $config, $g;
633
	if(isset($config['system']['developerspew'])) {
634
		$mt = microtime();
635
		echo "system_pccard_start() being called $mt\n";
636
	}
637

    
638
	if ($g['booting'])
639
		echo "Initializing PCMCIA...";
640

    
641
	/* kill any running pccardd */
642
	killbypid("{$g['varrun_path']}/pccardd.pid");
643

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

    
647
	if ($g['booting']) {
648
		if ($res == 0)
649
			echo "done.\n";
650
		else
651
			echo "failed!\n";
652
	}
653

    
654
	return $res;
655
}
656

    
657

    
658
function system_webgui_start() {
659
	global $config, $g;
660

    
661
	if ($g['booting'])
662
		echo "Starting webConfigurator...";
663

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

    
667
	sleep(1);
668

    
669
	chdir($g['www_path']);
670

    
671
	/* defaults */
672
	$portarg = "80";
673
	$crt = "";
674
	$key = "";
675
	$ca = "";
676

    
677
	/* non-standard port? */
678
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
679
		$portarg = "{$config['system']['webgui']['port']}";
680

    
681
	if ($config['system']['webgui']['protocol'] == "https") {
682
		// Ensure that we have a webConfigurator CERT
683
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
684
		if(!is_array($cert) && !$cert['crt'] && !$cert['prv']) {
685
			if (!is_array($config['ca']))
686
				$config['ca'] = array();
687
			$a_ca =& $config['ca'];
688
			if (!is_array($config['cert']))
689
				$config['cert'] = array();
690
			$a_cert =& $config['cert'];
691
			echo "Creating SSL Certificate... ";
692
			$cert = array();
693
			$cert['refid'] = uniqid();
694
			$cert['name'] = "webConfigurator default";
695
			mwexec("/usr/bin/openssl genrsa 1024 > {$g['tmp_path']}/ssl.key");
696
			mwexec("/usr/bin/openssl req -new -x509 -nodes -sha1 -days 2000 -key {$g['tmp_path']}/ssl.key > {$g['tmp_path']}/ssl.crt");
697
			$crt = file_get_contents("{$g['tmp_path']}/ssl.crt");
698
			$key = file_get_contents("{$g['tmp_path']}/ssl.key");
699
			unlink("{$g['tmp_path']}/ssl.key");
700
			unlink("{$g['tmp_path']}/ssl.crt");
701
			cert_import($cert, $crt, $key);
702
			$a_cert[] = $cert;
703
			$config['system']['webgui']['ssl-certref'] = $cert['refid'];
704
			write_config("Importing HTTPS certificate");
705
			if(!$config['system']['webgui']['port'])
706
				$portarg = "443";
707
			$ca = ca_chain($cert);
708
		} else {
709
			$crt = base64_decode($cert['crt']);
710
			$key = base64_decode($cert['prv']);
711
			if(!$config['system']['webgui']['port'])
712
				$portarg = "443";
713
			$ca = ca_chain($cert);
714
		}
715
	}
716

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

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

    
724
	/* fetch page to preload apc cache */
725
	$proto = "http";
726
	if ($config['system']['webgui']['protocol'])
727
		$proto = $config['system']['webgui']['protocol'];
728
	mwexec_bg("/usr/bin/fetch -o /dev/null -q {$proto}://localhost:{$portarg}/preload.php");
729

    
730
	if ($g['booting']) {
731
		if ($res == 0)
732
			echo "done.\n";
733
		else
734
			echo "failed!\n";
735
	}
736

    
737
	return $res;
738
}
739

    
740
function system_generate_lighty_config($filename,
741
	$cert,
742
	$key,
743
	$ca,
744
	$pid_file,
745
	$port = 80,
746
	$document_root = "/usr/local/www/",
747
	$cert_location = "cert.pem",
748
	$ca_location = "ca.pem",
749
	$max_procs = 2,
750
	$max_requests = "2",
751
	$fast_cgi_enable = true,
752
	$captive_portal = false) {
753

    
754
	global $config, $g;
755

    
756
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
757
		mkdir("{$g['tmp_path']}/lighttpdcompress");
758

    
759
	if(isset($config['system']['developerspew'])) {
760
		$mt = microtime();
761
		echo "system_generate_lighty_config() being called $mt\n";
762
	}
763

    
764
	if($captive_portal == true)  {
765
		$captiveportal = ",\"mod_rewrite\"";
766
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?redirurl=$1\" )\n";
767
		$captive_portal_module = "\"mod_accesslog\", ";
768
		$maxprocperip = $config['captiveportal']['maxprocperip'];
769
		if(!$maxprocperip and $maxprocperip > 0)
770
			$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
771
		else
772
			$captive_portal_mod_evasive = "";
773
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
774
		exec("mkdir -p {$g['tmp_path']}/captiveportal");
775
		exec("chmod a-w {$g['tmp_path']}/captiveportal");
776
		$server_max_request_size = "server.max-request-size    = 384";
777
	} else {
778
		$captiveportal = "";
779
		$captive_portal_rewrite = "";
780
		$captive_portal_module = "";
781
		$captive_portal_mod_evasive = "";
782
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
783
		$server_max_request_size = "server.max-request-size    = 2097152";
784
	}
785
	
786
	if($port <> "")
787
		$lighty_port = $port;
788
	else
789
		$lighty_port = "80";
790

    
791
	$memory = get_memory();
792
	$avail = $memory[0];
793

    
794
	if($avail > 0 and $avail < 65) {
795
		$fast_cgi_enable = false;
796
	}
797

    
798
	// Ramp up captive portal max procs
799
	if($captive_portal == true)  {
800
		if($avail > 65 and $avail < 98) {
801
			$max_procs = 1;
802
		}
803
		if($avail > 97 and $avail < 128) {
804
			$max_procs = 2;
805
		}
806
		if($avail > 127 and $avail < 256) {
807
			$max_procs = 3;
808
		}
809
		if($avail > 255 and $avail < 384) {
810
			$max_procs = 4;
811
		}
812
		if($avail > 383) {
813
			$max_procs = 5;
814
		}
815
	}
816

    
817
	if($captive_portal == true)  {	
818
		$bin_environment =  <<<EOC
819
        "bin-environment" => (
820
           "PHP_FCGI_CHILDREN" => "$max_procs",
821
           "PHP_FCGI_MAX_REQUESTS" => "500"
822
        ), 
823
EOC;
824

    
825
	} else if ($avail > 0 and $avail < 128) {
826
		$bin_environment = <<<EOC
827
		"bin-environment" => (
828
			"PHP_FCGI_CHILDREN" => "$max_procs",
829
			"PHP_FCGI_MAX_REQUESTS" => "2",
830
	),
831

    
832
EOC;
833
	} else
834
		$bin_environment =  <<<EOC
835
        "bin-environment" => (
836
           "PHP_FCGI_CHILDREN" => "$max_procs",
837
           "PHP_FCGI_MAX_REQUESTS" => "500"
838
        ), 
839
EOC;
840

    
841
	if($fast_cgi_enable == true) {
842
		$module = "\"mod_fastcgi\", \"mod_cgi\"";
843
		$cgi_config = "";
844
		$fastcgi_config = <<<EOD
845
#### fastcgi module
846
## read fastcgi.txt for more info
847
fastcgi.server = ( ".php" =>
848
	( "localhost" =>
849
		(
850
			"socket" => "{$g['tmp_path']}/php-fastcgi.socket",
851
			"min-procs" => 0,
852
			"max-procs" => {$max_procs},
853
			{$bin_environment}			
854
			"bin-path" => "/usr/local/bin/php"
855
		)
856
	)
857
)
858

    
859
#### CGI module
860
cgi.assign                 = ( ".cgi" => "" )
861

    
862
EOD;
863
	} else {
864
		$fastcgi_config = "";
865
		$module = "\"mod_cgi\"";
866
		$cgi_config = <<<EOD
867
#### CGI module
868
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
869
                               ".cgi" => "" )
870

    
871
EOD;
872
	}
873

    
874
	$lighty_config = "";
875
	$lighty_config .= <<<EOD
876
#
877
# lighttpd configuration file
878
#
879
# use a it as base for lighttpd 1.0.0 and above
880
#
881
############ Options you really have to take care of ####################
882

    
883
## FreeBSD!
884
server.event-handler	= "freebsd-kqueue"
885
server.network-backend 	= "writev"
886

    
887
## modules to load
888
server.modules              =   (
889
									{$captive_portal_module}
890
									"mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect",
891
									{$module}{$captiveportal}
892
								)
893

    
894
## Unused modules
895
#                               "mod_setenv",
896
#                               "mod_rewrite",
897
#                               "mod_ssi",
898
#                               "mod_usertrack",
899
#                               "mod_expire",
900
#                               "mod_secdownload",
901
#                               "mod_rrdtool",
902
#                               "mod_auth",
903
#                               "mod_status",
904
#                               "mod_alias",
905
#                               "mod_proxy",
906
#                               "mod_simple_vhost",
907
#                               "mod_evhost",
908
#                               "mod_userdir",
909
#                               "mod_cgi",
910

    
911
server.max-keep-alive-requests = 15
912
server.max-keep-alive-idle = 30
913

    
914
## a static document-root, for virtual-hosting take look at the
915
## server.virtual-* options
916
server.document-root        = "{$document_root}"
917
{$captive_portal_rewrite}
918

    
919
# Maximum idle time with nothing being written (php downloading)
920
server.max-write-idle = 999
921

    
922
## where to send error-messages to
923
server.errorlog             = "/var/log/lighttpd.error.log"
924

    
925
# files to check for if .../ is requested
926
server.indexfiles           = ( "index.php", "index.html",
927
                                "index.htm", "default.htm" )
928

    
929
# mimetype mapping
930
mimetype.assign             = (
931
  ".pdf"          =>      "application/pdf",
932
  ".sig"          =>      "application/pgp-signature",
933
  ".spl"          =>      "application/futuresplash",
934
  ".class"        =>      "application/octet-stream",
935
  ".ps"           =>      "application/postscript",
936
  ".torrent"      =>      "application/x-bittorrent",
937
  ".dvi"          =>      "application/x-dvi",
938
  ".gz"           =>      "application/x-gzip",
939
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
940
  ".swf"          =>      "application/x-shockwave-flash",
941
  ".tar.gz"       =>      "application/x-tgz",
942
  ".tgz"          =>      "application/x-tgz",
943
  ".tar"          =>      "application/x-tar",
944
  ".zip"          =>      "application/zip",
945
  ".mp3"          =>      "audio/mpeg",
946
  ".m3u"          =>      "audio/x-mpegurl",
947
  ".wma"          =>      "audio/x-ms-wma",
948
  ".wax"          =>      "audio/x-ms-wax",
949
  ".ogg"          =>      "audio/x-wav",
950
  ".wav"          =>      "audio/x-wav",
951
  ".gif"          =>      "image/gif",
952
  ".jpg"          =>      "image/jpeg",
953
  ".jpeg"         =>      "image/jpeg",
954
  ".png"          =>      "image/png",
955
  ".xbm"          =>      "image/x-xbitmap",
956
  ".xpm"          =>      "image/x-xpixmap",
957
  ".xwd"          =>      "image/x-xwindowdump",
958
  ".css"          =>      "text/css",
959
  ".html"         =>      "text/html",
960
  ".htm"          =>      "text/html",
961
  ".js"           =>      "text/javascript",
962
  ".asc"          =>      "text/plain",
963
  ".c"            =>      "text/plain",
964
  ".conf"         =>      "text/plain",
965
  ".text"         =>      "text/plain",
966
  ".txt"          =>      "text/plain",
967
  ".dtd"          =>      "text/xml",
968
  ".xml"          =>      "text/xml",
969
  ".mpeg"         =>      "video/mpeg",
970
  ".mpg"          =>      "video/mpeg",
971
  ".mov"          =>      "video/quicktime",
972
  ".qt"           =>      "video/quicktime",
973
  ".avi"          =>      "video/x-msvideo",
974
  ".asf"          =>      "video/x-ms-asf",
975
  ".asx"          =>      "video/x-ms-asf",
976
  ".wmv"          =>      "video/x-ms-wmv",
977
  ".bz2"          =>      "application/x-bzip",
978
  ".tbz"          =>      "application/x-bzip-compressed-tar",
979
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
980
 )
981

    
982
# Use the "Content-Type" extended attribute to obtain mime type if possible
983
#mimetypes.use-xattr        = "enable"
984

    
985
#### accesslog module
986
#accesslog.filename          = "/dev/null"
987

    
988
## deny access the file-extensions
989
#
990
# ~    is for backupfiles from vi, emacs, joe, ...
991
# .inc is often used for code includes which should in general not be part
992
#      of the document-root
993
url.access-deny             = ( "~", ".inc" )
994

    
995

    
996
######### Options that are good to be but not neccesary to be changed #######
997

    
998
## bind to port (default: 80)
999
server.port                = {$lighty_port}
1000

    
1001
## error-handler for status 404
1002
#server.error-handler-404   = "/error-handler.html"
1003
#server.error-handler-404   = "/error-handler.php"
1004

    
1005
## to help the rc.scripts
1006
server.pid-file            = "/var/run/{$pid_file}"
1007

    
1008
## virtual directory listings
1009
server.dir-listing         = "disable"
1010

    
1011
## enable debugging
1012
debug.log-request-header   = "disable"
1013
debug.log-response-header  = "disable"
1014
debug.log-request-handling = "disable"
1015
debug.log-file-not-found   = "disable"
1016

    
1017
# gzip compression
1018
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1019
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1020

    
1021
{$server_upload_dirs}
1022

    
1023
{$server_max_request_size}
1024

    
1025
{$fastcgi_config}
1026

    
1027
{$cgi_config}
1028

    
1029
{$captive_portal_mod_evasive}
1030

    
1031
expire.url = (
1032
				"" => "access 50 hours",	
1033
        )
1034

    
1035
EOD;
1036

    
1037
	$cert = str_replace("\r", "", $cert);
1038
	$key = str_replace("\r", "", $key);
1039
	$ca = str_replace("\r", "", $ca);
1040

    
1041
	$cert = str_replace("\n\n", "\n", $cert);
1042
	$key = str_replace("\n\n", "\n", $key);
1043
	$ca = str_replace("\n\n", "\n", $ca);
1044

    
1045
	if($cert <> "" and $key <> "") {
1046
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1047
		if (!$fd) {
1048
			printf("Error: cannot open cert.pem in system_webgui_start().\n");
1049
			return 1;
1050
		}
1051
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1052
		fwrite($fd, $cert);
1053
		fwrite($fd, "\n");
1054
		fwrite($fd, $key);
1055
		fclose($fd);
1056
		if($ca <> "") {
1057
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1058
			if (!$fd) {
1059
				printf("Error: cannot open ca.pem in system_webgui_start().\n");
1060
				return 1;
1061
			}
1062
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1063
			fwrite($fd, $ca);
1064
			fclose($fd);
1065
		}
1066
		$lighty_config .= "\n";
1067
		$lighty_config .= "## ssl configuration\n";
1068
		$lighty_config .= "ssl.engine = \"enable\"\n";
1069
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1070
		if($ca <> "")
1071
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1072
	}
1073

    
1074
	// Add HTTP to HTTPS redirect	
1075
	if ($captive_portal == false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1076
		if($lighty_port != "443") 
1077
			$redirectport = ":{$lighty_port}";
1078
		$lighty_config .= <<<EOD
1079
\$SERVER["socket"] == ":80" {
1080
	\$HTTP["host"] =~ "(.*)" {
1081
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1082
	}
1083
}
1084
EOD;
1085
	}
1086

    
1087
	$fd = fopen("{$filename}", "w");
1088
	if (!$fd) {
1089
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
1090
		return 1;
1091
	}
1092
	fwrite($fd, $lighty_config);
1093
	fclose($fd);
1094

    
1095
	return 0;
1096

    
1097
}
1098

    
1099
function system_timezone_configure() {
1100
	global $config, $g;
1101
	if(isset($config['system']['developerspew'])) {
1102
		$mt = microtime();
1103
		echo "system_timezone_configure() being called $mt\n";
1104
	}
1105

    
1106
	$syscfg = $config['system'];
1107

    
1108
	if ($g['booting'])
1109
		echo "Setting timezone...";
1110

    
1111
	/* extract appropriate timezone file */
1112
	$timezone = $syscfg['timezone'];
1113
	if (!$timezone)
1114
		$timezone = "Etc/UTC";
1115

    
1116
	conf_mount_rw();
1117

    
1118
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1119
		escapeshellarg($timezone) . " > /etc/localtime");
1120

    
1121
	mwexec("sync");
1122
	conf_mount_ro();
1123

    
1124
	if ($g['booting'])
1125
		echo "done.\n";
1126
}
1127

    
1128
function system_ntp_configure() {
1129
	global $config, $g;
1130

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

    
1133
	/* open configuration for wrting or bail */
1134
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1135
	if(!$fd) {
1136
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1137
		return;
1138
	}
1139

    
1140
	fwrite($fd, "# \n");
1141
	fwrite($fd, "# pfSense OpenNTPD configuration file \n");
1142
	fwrite($fd, "# \n\n");
1143

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

    
1148
	/* Setup listener(s) if the user has configured one */
1149
        if ($config['installedpackages']['openntpd']) {
1150
    		/* server config is in coregui1 */
1151
		$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
1152
		if ($xmlsettings['enable'] == 'on') {
1153
			$ifaces = explode(',', $xmlsettings['interface']);
1154
			$ifaces = array_map('get_real_interface', $ifaces);
1155
			$ifaces = array_filter($ifaces, 'does_interface_exist');
1156
			$ips = array_map('find_interface_ip', $ifaces);
1157
			foreach ($ips as $ip) {
1158
				if (is_ipaddr($ip))
1159
					fwrite($fd, "listen on $ip\n");
1160
			}
1161
		}
1162
	}
1163

    
1164
	fwrite($fd, "\n");
1165

    
1166
	/* slurp! */
1167
	fclose($fd);
1168

    
1169
	/* if openntpd is running, kill it */
1170
	while(is_process_running("ntpd")) {
1171
		killbyname("ntpd");
1172
	}
1173

    
1174
	/* if /var/empty does not exist, create it */
1175
	if(!is_dir("/var/empty"))
1176
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1177

    
1178
	if ($g['booting'])
1179
		return;
1180

    
1181
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1182
	exec("/usr/local/sbin/ntpd -s -f {$g['varetc_path']}/ntpd.conf");
1183
	
1184
	// Note that we are starting up
1185
	exec("echo 'OpenNTPD is starting up' >> {$g['varlog_path']}/ntpd.log");
1186

    
1187
}
1188

    
1189
function sync_system_time() {
1190
	global $config, $g;
1191

    
1192
	$syscfg = $config['system'];
1193

    
1194
	if ($g['booting'])
1195
		echo "Syncing system time before startup...";
1196

    
1197
	/* foreach through servers and write out to ntpd.conf */
1198
	foreach (explode(' ', $syscfg['timeservers']) as $ts) {
1199
		mwexec("/usr/sbin/ntpdate -s $ts");
1200
	}
1201
	
1202
	if ($g['booting'])
1203
		echo "done.\n";
1204
	
1205
}
1206

    
1207
function system_halt() {
1208
	global $g;
1209

    
1210
	system_reboot_cleanup();
1211

    
1212
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1213
}
1214

    
1215
function system_reboot() {
1216
	global $g;
1217

    
1218
	system_reboot_cleanup();
1219

    
1220
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1221
}
1222

    
1223
function system_reboot_sync() {
1224
	global $g;
1225

    
1226
	system_reboot_cleanup();
1227

    
1228
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1229
}
1230

    
1231
function system_reboot_cleanup() {
1232
	mwexec("/usr/local/bin/beep.sh stop");
1233
	require_once("captiveportal.inc");
1234
	captiveportal_radius_stop_all();
1235
	require_once("voucher.inc");
1236
	voucher_save_db_to_config();
1237
}
1238

    
1239
function system_do_shell_commands($early = 0) {
1240
	global $config, $g;
1241
	if(isset($config['system']['developerspew'])) {
1242
		$mt = microtime();
1243
		echo "system_do_shell_commands() being called $mt\n";
1244
	}
1245

    
1246
	if ($early)
1247
		$cmdn = "earlyshellcmd";
1248
	else
1249
		$cmdn = "shellcmd";
1250

    
1251
	if (is_array($config['system'][$cmdn])) {
1252

    
1253
		/* *cmd is an array, loop through */
1254
		foreach ($config['system'][$cmdn] as $cmd) {
1255
			exec($cmd);
1256
		}
1257

    
1258
	} elseif($config['system'][$cmdn] <> "") {
1259

    
1260
		/* execute single item */
1261
		exec($config['system'][$cmdn]);
1262

    
1263
	}
1264
}
1265

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

    
1273
	if (isset($config['system']['disableconsolemenu'])) {
1274
		touch("{$g['varetc_path']}/disableconsole");
1275
	} else {
1276
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1277
	}
1278
}
1279

    
1280
function system_dmesg_save() {
1281
	global $g;
1282
	if(isset($config['system']['developerspew'])) {
1283
		$mt = microtime();
1284
		echo "system_dmesg_save() being called $mt\n";
1285
	}
1286

    
1287
	$dmesg = "";
1288
	exec("/sbin/dmesg", $dmesg);
1289

    
1290
	/* find last copyright line (output from previous boots may be present) */
1291
	$lastcpline = 0;
1292

    
1293
	for ($i = 0; $i < count($dmesg); $i++) {
1294
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1295
			$lastcpline = $i;
1296
	}
1297

    
1298
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1299
	if (!$fd) {
1300
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1301
		return 1;
1302
	}
1303

    
1304
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1305
		fwrite($fd, $dmesg[$i] . "\n");
1306

    
1307
	fclose($fd);
1308

    
1309
	return 0;
1310
}
1311

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

    
1319
	if (isset($config['system']['harddiskstandby'])) {
1320
		if ($g['booting']) {
1321
			echo 'Setting hard disk standby... ';
1322
		}
1323

    
1324
		$standby = $config['system']['harddiskstandby'];
1325
		// Check for a numeric value
1326
		if (is_numeric($standby)) {
1327
			// Sync the disk(s)
1328
			mwexec('/bin/sync');
1329
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1330
				// Reinitialize ATA-drives
1331
				mwexec('/usr/local/sbin/atareinit');
1332
				if ($g['booting']) {
1333
					echo "done.\n";
1334
				}
1335
			} else if ($g['booting']) {
1336
				echo "failed!\n";
1337
			}
1338
		} else if ($g['booting']) {
1339
			echo "failed!\n";
1340
		}
1341
	}
1342
}
1343

    
1344
function system_setup_sysctl() {
1345
	global $config;
1346
	if(isset($config['system']['developerspew'])) {
1347
		$mt = microtime();
1348
		echo "system_setup_sysctl() being called $mt\n";
1349
	}
1350

    
1351
	activate_sysctls();	
1352

    
1353
	if (isset($config['system']['sharednet'])) {
1354
		system_disable_arp_wrong_if();
1355
	}
1356
}
1357

    
1358
function system_disable_arp_wrong_if() {
1359
	global $config;
1360
	if(isset($config['system']['developerspew'])) {
1361
		$mt = microtime();
1362
		echo "system_disable_arp_wrong_if() being called $mt\n";
1363
	}
1364
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1365
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1366
}
1367

    
1368
function system_enable_arp_wrong_if() {
1369
	global $config;
1370
	if(isset($config['system']['developerspew'])) {
1371
		$mt = microtime();
1372
		echo "system_enable_arp_wrong_if() being called $mt\n";
1373
	}
1374
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1375
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1376
}
1377

    
1378
function enable_watchdog() {
1379
	global $config;
1380
	return;
1381
	$install_watchdog = false;
1382
	$supported_watchdogs = array("Geode");
1383
	$file = file_get_contents("/var/log/dmesg.boot");
1384
	foreach($supported_watchdogs as $sd) {
1385
		if(stristr($file, "Geode")) {
1386
			$install_watchdog = true;
1387
		}
1388
	}
1389
	if($install_watchdog == true) {
1390
		if(is_process_running("watchdogd"))
1391
			mwexec("/usr/bin/killall watchdogd", true);
1392
		exec("/usr/sbin/watchdogd");
1393
	}
1394
}
1395

    
1396
function system_check_reset_button() {
1397
	global $g;
1398
	if($g['platform'] != "nanobsd")
1399
		return 0;
1400

    
1401
	$specplatform = system_identify_specific_platform();
1402

    
1403
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1404
		return 0;
1405

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

    
1408
	if ($retval == 99) {
1409
		/* user has pressed reset button for 2 seconds - 
1410
		   reset to factory defaults */
1411
		echo <<<EOD
1412

    
1413
***********************************************************************
1414
* Reset button pressed - resetting configuration to factory defaults. *
1415
* The system will reboot after this completes.                        *
1416
***********************************************************************
1417

    
1418

    
1419
EOD;
1420
		
1421
		reset_factory_defaults();
1422
		system_reboot_sync();
1423
		exit(0);
1424
	}
1425

    
1426
	return 0;
1427
}
1428

    
1429
/* attempt to identify the specific platform (for embedded systems)
1430
   Returns an array with two elements:
1431
	name => platform string (e.g. 'wrap', 'alix' etc.)
1432
	descr => human-readable description (e.g. "PC Engines WRAP")
1433
*/
1434
function system_identify_specific_platform() {
1435
	global $g;
1436
	
1437
	if ($g['platform'] == 'generic-pc')
1438
		return array('name' => 'generic-pc', 'descr' => "Generic PC");
1439
	
1440
	if ($g['platform'] == 'generic-pc-cdrom')
1441
		return array('name' => 'generic-pc-cdrom', 'descr' => "Generic PC (CD-ROM)");
1442
	
1443
	/* the rest of the code only deals with 'embedded' platforms */
1444
	if ($g['platform'] != 'nanobsd')
1445
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1446
	
1447
	$dmesg = system_get_dmesg_boot();
1448
	
1449
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1450
		return array('name' => 'wrap', 'descr' => 'PC Engines WRAP');
1451
	
1452
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1453
		return array('name' => 'alix', 'descr' => 'PC Engines ALIX');
1454

    
1455
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1456
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1457
	
1458
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1459
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1460
		
1461
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1462
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1463
	
1464
	/* unknown embedded platform */
1465
	return array('name' => 'embedded', 'descr' => 'embedded (unknown)');
1466
}
1467

    
1468
function system_get_dmesg_boot() {
1469
	global $g;
1470
		
1471
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1472
}
1473

    
1474
?>
(40-40/54)