Project

General

Profile

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

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

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

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

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

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

    
32
/*
33
	pfSense_BUILDER_BINARIES:	/usr/sbin/powerd	/usr/bin/killall	/sbin/sysctl	/sbin/route
34
	pfSense_BUILDER_BINARIES:	/bin/hostname	/bin/ls	/usr/bin/netstat	/usr/sbin/syslogd	
35
	pfSense_BUILDER_BINARIES:	/usr/sbin/pccardd	/usr/local/sbin/lighttpd	/bin/chmod 	/bin/mkdir
36
	pfSense_BUILDER_BINARIES:	/usr/bin/tar	/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) && $inteface != $interafegw)
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
		} else if (is_ipaddr($config['interfaces']['wan']['gateway'])) {
368
			/* Adding gateway for 1.2-style configs without the new
369
		  	 * gateway setup configured.
370
		  	 * Force WAN to be default gateway because that is the 1.2 behavior.
371
			 */
372
			log_error("WARNING: There is no default gateway in the configuration.");
373
			$gatewayip = $config['interfaces']['wan']['gateway'];
374
			mwexec("/sbin/route add default " . escapeshellarg($gatewayip), true);
375
		}
376
	}
377

    
378
	if (is_array($config['staticroutes']['route'])) {
379
		$gateways_arr = return_gateways_array();
380

    
381
		foreach ($config['staticroutes']['route'] as $rtent) {
382
			$gatewayip = "";
383
			if (isset($gateways_arr[$rtent['gateway']])) {
384
				$gatewayip = $gateways_arr[$rtent['gateway']]['gateway'];
385
				$interfacegw = $gateways_arr[$rtent['gateway']]['interface'];
386
				if ($interface == $gateways_arr[$rtent['gateway']]['friendlyiface'])
387
					continue;
388
			} else if (is_ipaddr($rtent['gateway'])) {
389
				$gatewayip = $rtent['gateway'];
390
			} else {
391
				log_error("Static Routes: Gateway IP could not be found for {$rtent['network']}");
392
				continue;
393
			}
394

    
395
			$action = "add";
396
			if (isset($route_arr[$rtent['network']]))
397
				$action = "change";
398

    
399
			if (is_ipaddr($gatewayip)) {
400
				mwexec("/sbin/route {$action} " . escapeshellarg($rtent['network']) .
401
					" " . escapeshellarg($gatewayip));
402
			} else if (!empty($interfacegw)) {
403
				mwexec("/sbin/route {$action} " . escapeshellarg($rtent['network']) .
404
					" -iface " . escapeshellarg($interfacegw));
405
			}
406
		}
407
	}
408

    
409
	return 0;
410
}
411

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

    
419
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
420
}
421

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

    
429
	$syslogcfg = $config['syslog'];
430

    
431
	if ($g['booting'])
432
		echo "Starting syslog...";
433
	else
434
		killbypid("{$g['varrun_path']}/syslog.pid");
435

    
436
	if(is_process_running("syslogd"))
437
		mwexec("/usr/bin/killall -9 syslogd");
438
	if(is_process_running("fifolog_writer"))
439
		mwexec("/usr/bin/killall -9 fifolog_writer");
440
	
441
	// Define carious commands for logging
442
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
443
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
444
	$clog_create = "/usr/sbin/clog -i -s ";
445
	$clog_log = "%";
446

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

    
533
EOD;
534
		if (isset($syslogcfg['filter'])) {
535
			if($syslogcfg['remoteserver'])
536
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver']}\n";
537
			if($syslogcfg['remoteserver2'])
538
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver2']}\n";
539
			if($syslogcfg['remoteserver3'])
540
				$syslogconf .= "local0.*			 @{$syslogcfg['remoteserver3']}\n";
541

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

    
576
EOD;
577

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

    
587
EOD;
588

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

    
598
EOD;
599

    
600
}
601
		if (isset($syslogcfg['logall'])) {
602
			if($syslogcfg['remoteserver'])
603
				$syslogconf .= <<<EOD
604
*.*								@{$syslogcfg['remoteserver']}
605

    
606
EOD;
607

    
608
}
609
			if($syslogcfg['remoteserver2'])
610
				$syslogconf .= <<<EOD
611
*.*								@{$syslogcfg['remoteserver2']}
612

    
613
EOD;
614

    
615
}
616
			if($syslogcfg['remoteserver3'])
617
				$syslogconf .= <<<EOD
618
*.*								@{$syslogcfg['remoteserver3']}
619

    
620
EOD;
621

    
622
}
623
		fwrite($fd, $syslogconf);
624
		fclose($fd);
625
		// Are we logging to a least one remote server ?
626
		if(strpos($syslogconf, "@") != false)
627
			$retval = system("/usr/sbin/syslogd -c -f {$g['varetc_path']}/syslog.conf");
628
		else
629
			$retval = system("/usr/sbin/syslogd -c -f {$g['varetc_path']}/syslog.conf");
630

    
631
	} else {
632
		$retval = mwexec("/usr/sbin/syslogd -c");
633
	}
634

    
635
	if ($g['booting'])
636
		echo "done.\n";
637

    
638
	return $retval;
639
}
640

    
641
function system_pccard_start() {
642
	global $config, $g;
643
	if(isset($config['system']['developerspew'])) {
644
		$mt = microtime();
645
		echo "system_pccard_start() being called $mt\n";
646
	}
647

    
648
	if ($g['booting'])
649
		echo "Initializing PCMCIA...";
650

    
651
	/* kill any running pccardd */
652
	killbypid("{$g['varrun_path']}/pccardd.pid");
653

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

    
657
	if ($g['booting']) {
658
		if ($res == 0)
659
			echo "done.\n";
660
		else
661
			echo "failed!\n";
662
	}
663

    
664
	return $res;
665
}
666

    
667

    
668
function system_webgui_start() {
669
	global $config, $g;
670

    
671
	if ($g['booting'])
672
		echo "Starting webConfigurator...";
673

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

    
677
	sleep(1);
678

    
679
	chdir($g['www_path']);
680

    
681
	/* defaults */
682
	$portarg = "80";
683
	$crt = "";
684
	$key = "";
685
	$ca = "";
686

    
687
	/* non-standard port? */
688
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
689
		$portarg = "{$config['system']['webgui']['port']}";
690

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

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

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

    
734
	/* fetch page to preload apc cache */
735
	$proto = "http";
736
	if ($config['system']['webgui']['protocol'])
737
		$proto = $config['system']['webgui']['protocol'];
738
	mwexec_bg("/usr/bin/fetch -o /dev/null -q {$proto}://localhost:{$portarg}/preload.php");
739

    
740
	if ($g['booting']) {
741
		if ($res == 0)
742
			echo "done.\n";
743
		else
744
			echo "failed!\n";
745
	}
746

    
747
	return $res;
748
}
749

    
750
function system_generate_lighty_config($filename,
751
	$cert,
752
	$key,
753
	$ca,
754
	$pid_file,
755
	$port = 80,
756
	$document_root = "/usr/local/www/",
757
	$cert_location = "cert.pem",
758
	$ca_location = "ca.pem",
759
	$max_procs = 2,
760
	$max_requests = "2",
761
	$fast_cgi_enable = true,
762
	$captive_portal = false) {
763

    
764
	global $config, $g;
765

    
766
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
767
		mkdir("{$g['tmp_path']}/lighttpdcompress");
768

    
769
	if(isset($config['system']['developerspew'])) {
770
		$mt = microtime();
771
		echo "system_generate_lighty_config() being called $mt\n";
772
	}
773

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

    
801
	$memory = get_memory();
802
	$avail = $memory[0];
803

    
804
	if($avail > 0 and $avail < 65) {
805
		$fast_cgi_enable = false;
806
	}
807

    
808
	// Ramp up captive portal max procs
809
	if($captive_portal == true)  {
810
		if($avail > 65 and $avail < 98) {
811
			$max_procs = 1;
812
		}
813
		if($avail > 97 and $avail < 128) {
814
			$max_procs = 2;
815
		}
816
		if($avail > 127 and $avail < 256) {
817
			$max_procs = 3;
818
		}
819
		if($avail > 255 and $avail < 384) {
820
			$max_procs = 4;
821
		}
822
		if($avail > 383) {
823
			$max_procs = 5;
824
		}
825
	}
826

    
827
	if($captive_portal == true)  {	
828
		$bin_environment =  <<<EOC
829
        "bin-environment" => (
830
           "PHP_FCGI_CHILDREN" => "$max_procs",
831
           "PHP_FCGI_MAX_REQUESTS" => "500"
832
        ), 
833
EOC;
834

    
835
	} else if ($avail > 0 and $avail < 128) {
836
		$bin_environment = <<<EOC
837
		"bin-environment" => (
838
			"PHP_FCGI_CHILDREN" => "$max_procs",
839
			"PHP_FCGI_MAX_REQUESTS" => "2",
840
	),
841

    
842
EOC;
843
	} else
844
		$bin_environment =  <<<EOC
845
        "bin-environment" => (
846
           "PHP_FCGI_CHILDREN" => "$max_procs",
847
           "PHP_FCGI_MAX_REQUESTS" => "500"
848
        ), 
849
EOC;
850

    
851
	if($fast_cgi_enable == true) {
852
		$module = "\"mod_fastcgi\", \"mod_cgi\"";
853
		$cgi_config = "";
854
		$fastcgi_config = <<<EOD
855
#### fastcgi module
856
## read fastcgi.txt for more info
857
fastcgi.server = ( ".php" =>
858
	( "localhost" =>
859
		(
860
			"socket" => "{$g['tmp_path']}/php-fastcgi.socket",
861
			"min-procs" => 0,
862
			"max-procs" => {$max_procs},
863
			{$bin_environment}			
864
			"bin-path" => "/usr/local/bin/php"
865
		)
866
	)
867
)
868

    
869
#### CGI module
870
cgi.assign                 = ( ".cgi" => "" )
871

    
872
EOD;
873
	} else {
874
		$fastcgi_config = "";
875
		$module = "\"mod_cgi\"";
876
		$cgi_config = <<<EOD
877
#### CGI module
878
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
879
                               ".cgi" => "" )
880

    
881
EOD;
882
	}
883

    
884
	$lighty_config = "";
885
	$lighty_config .= <<<EOD
886
#
887
# lighttpd configuration file
888
#
889
# use a it as base for lighttpd 1.0.0 and above
890
#
891
############ Options you really have to take care of ####################
892

    
893
## FreeBSD!
894
server.event-handler	= "freebsd-kqueue"
895
server.network-backend 	= "writev"
896

    
897
## modules to load
898
server.modules              =   (
899
									{$captive_portal_module}
900
									"mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect",
901
									{$module}{$captiveportal}
902
								)
903

    
904
## Unused modules
905
#                               "mod_setenv",
906
#                               "mod_rewrite",
907
#                               "mod_ssi",
908
#                               "mod_usertrack",
909
#                               "mod_expire",
910
#                               "mod_secdownload",
911
#                               "mod_rrdtool",
912
#                               "mod_auth",
913
#                               "mod_status",
914
#                               "mod_alias",
915
#                               "mod_proxy",
916
#                               "mod_simple_vhost",
917
#                               "mod_evhost",
918
#                               "mod_userdir",
919
#                               "mod_cgi",
920

    
921
server.max-keep-alive-requests = 15
922
server.max-keep-alive-idle = 30
923

    
924
## a static document-root, for virtual-hosting take look at the
925
## server.virtual-* options
926
server.document-root        = "{$document_root}"
927
{$captive_portal_rewrite}
928

    
929
# Maximum idle time with nothing being written (php downloading)
930
server.max-write-idle = 999
931

    
932
## where to send error-messages to
933
server.errorlog             = "/var/log/lighttpd.error.log"
934

    
935
# files to check for if .../ is requested
936
server.indexfiles           = ( "index.php", "index.html",
937
                                "index.htm", "default.htm" )
938

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

    
992
# Use the "Content-Type" extended attribute to obtain mime type if possible
993
#mimetypes.use-xattr        = "enable"
994

    
995
#### accesslog module
996
#accesslog.filename          = "/dev/null"
997

    
998
## deny access the file-extensions
999
#
1000
# ~    is for backupfiles from vi, emacs, joe, ...
1001
# .inc is often used for code includes which should in general not be part
1002
#      of the document-root
1003
url.access-deny             = ( "~", ".inc" )
1004

    
1005

    
1006
######### Options that are good to be but not neccesary to be changed #######
1007

    
1008
## bind to port (default: 80)
1009
server.port                = {$lighty_port}
1010

    
1011
## error-handler for status 404
1012
#server.error-handler-404   = "/error-handler.html"
1013
#server.error-handler-404   = "/error-handler.php"
1014

    
1015
## to help the rc.scripts
1016
server.pid-file            = "/var/run/{$pid_file}"
1017

    
1018
## virtual directory listings
1019
server.dir-listing         = "disable"
1020

    
1021
## enable debugging
1022
debug.log-request-header   = "disable"
1023
debug.log-response-header  = "disable"
1024
debug.log-request-handling = "disable"
1025
debug.log-file-not-found   = "disable"
1026

    
1027
# gzip compression
1028
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1029
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1030

    
1031
{$server_upload_dirs}
1032

    
1033
{$server_max_request_size}
1034

    
1035
{$fastcgi_config}
1036

    
1037
{$cgi_config}
1038

    
1039
{$captive_portal_mod_evasive}
1040

    
1041
expire.url = (
1042
				"" => "access 50 hours",	
1043
        )
1044

    
1045
EOD;
1046

    
1047
	$cert = str_replace("\r", "", $cert);
1048
	$key = str_replace("\r", "", $key);
1049
	$ca = str_replace("\r", "", $ca);
1050

    
1051
	$cert = str_replace("\n\n", "\n", $cert);
1052
	$key = str_replace("\n\n", "\n", $key);
1053
	$ca = str_replace("\n\n", "\n", $ca);
1054

    
1055
	if($cert <> "" and $key <> "") {
1056
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1057
		if (!$fd) {
1058
			printf("Error: cannot open cert.pem in system_webgui_start().\n");
1059
			return 1;
1060
		}
1061
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1062
		fwrite($fd, $cert);
1063
		fwrite($fd, "\n");
1064
		fwrite($fd, $key);
1065
		fclose($fd);
1066
		if($ca <> "") {
1067
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1068
			if (!$fd) {
1069
				printf("Error: cannot open ca.pem in system_webgui_start().\n");
1070
				return 1;
1071
			}
1072
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1073
			fwrite($fd, $ca);
1074
			fclose($fd);
1075
		}
1076
		$lighty_config .= "\n";
1077
		$lighty_config .= "## ssl configuration\n";
1078
		$lighty_config .= "ssl.engine = \"enable\"\n";
1079
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1080
		if($ca <> "")
1081
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1082
	}
1083

    
1084
	// Add HTTP to HTTPS redirect	
1085
	if ($captive_portal == false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1086
		if($lighty_port != "443") 
1087
			$redirectport = ":{$lighty_port}";
1088
		$lighty_config .= <<<EOD
1089
\$SERVER["socket"] == ":80" {
1090
	\$HTTP["host"] =~ "(.*)" {
1091
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1092
	}
1093
}
1094
EOD;
1095
	}
1096

    
1097
	$fd = fopen("{$filename}", "w");
1098
	if (!$fd) {
1099
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
1100
		return 1;
1101
	}
1102
	fwrite($fd, $lighty_config);
1103
	fclose($fd);
1104

    
1105
	return 0;
1106

    
1107
}
1108

    
1109
function system_timezone_configure() {
1110
	global $config, $g;
1111
	if(isset($config['system']['developerspew'])) {
1112
		$mt = microtime();
1113
		echo "system_timezone_configure() being called $mt\n";
1114
	}
1115

    
1116
	$syscfg = $config['system'];
1117

    
1118
	if ($g['booting'])
1119
		echo "Setting timezone...";
1120

    
1121
	/* extract appropriate timezone file */
1122
	$timezone = $syscfg['timezone'];
1123
	if (!$timezone)
1124
		$timezone = "Etc/UTC";
1125

    
1126
	conf_mount_rw();
1127

    
1128
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1129
		escapeshellarg($timezone) . " > /etc/localtime");
1130

    
1131
	mwexec("sync");
1132
	conf_mount_ro();
1133

    
1134
	if ($g['booting'])
1135
		echo "done.\n";
1136
}
1137

    
1138
function system_ntp_configure() {
1139
	global $config, $g;
1140

    
1141
	$syscfg =& $config['system'];
1142

    
1143
	/* open configuration for wrting or bail */
1144
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1145
	if(!$fd) {
1146
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1147
		return;
1148
	}
1149

    
1150
	fwrite($fd, "# \n");
1151
	fwrite($fd, "# pfSense OpenNTPD configuration file \n");
1152
	fwrite($fd, "# \n\n");
1153

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

    
1158
	/* Setup listener(s) if the user has configured one */
1159
        if ($config['installedpackages']['openntpd']) {
1160
    		/* server config is in coregui1 */
1161
		$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
1162
		if ($xmlsettings['enable'] == 'on') {
1163
			$ifaces = explode(',', $xmlsettings['interface']);
1164
			$ifaces = array_map('get_real_interface', $ifaces);
1165
			$ifaces = array_filter($ifaces, 'does_interface_exist');
1166
			$ips = array_map('find_interface_ip', $ifaces);
1167
			foreach ($ips as $ip) {
1168
				if (is_ipaddr($ip))
1169
					fwrite($fd, "listen on $ip\n");
1170
			}
1171
		}
1172
	}
1173

    
1174
	fwrite($fd, "\n");
1175

    
1176
	/* slurp! */
1177
	fclose($fd);
1178

    
1179
	/* if openntpd is running, kill it */
1180
	while(is_process_running("ntpd")) {
1181
		killbyname("ntpd");
1182
	}
1183

    
1184
	/* if /var/empty does not exist, create it */
1185
	if(!is_dir("/var/empty"))
1186
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1187

    
1188
	if ($g['booting'])
1189
		return;
1190

    
1191
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1192
	exec("/usr/local/sbin/ntpd -s -f {$g['varetc_path']}/ntpd.conf");
1193
	
1194
	// Note that we are starting up
1195
	exec("echo 'OpenNTPD is starting up' >> {$g['varlog_path']}/ntpd.log");
1196

    
1197
}
1198

    
1199
function sync_system_time() {
1200
	global $config, $g;
1201

    
1202
	$syscfg = $config['system'];
1203

    
1204
	if ($g['booting'])
1205
		echo "Syncing system time before startup...";
1206

    
1207
	/* foreach through servers and write out to ntpd.conf */
1208
	foreach (explode(' ', $syscfg['timeservers']) as $ts) {
1209
		mwexec("/usr/sbin/ntpdate -s $ts");
1210
	}
1211
	
1212
	if ($g['booting'])
1213
		echo "done.\n";
1214
	
1215
}
1216

    
1217
function system_halt() {
1218
	global $g;
1219

    
1220
	system_reboot_cleanup();
1221

    
1222
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1223
}
1224

    
1225
function system_reboot() {
1226
	global $g;
1227

    
1228
	system_reboot_cleanup();
1229

    
1230
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1231
}
1232

    
1233
function system_reboot_sync() {
1234
	global $g;
1235

    
1236
	system_reboot_cleanup();
1237

    
1238
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1239
}
1240

    
1241
function system_reboot_cleanup() {
1242
	mwexec("/usr/local/bin/beep.sh stop");
1243
	require_once("captiveportal.inc");
1244
	captiveportal_radius_stop_all();
1245
	require_once("voucher.inc");
1246
	voucher_save_db_to_config();
1247
}
1248

    
1249
function system_do_shell_commands($early = 0) {
1250
	global $config, $g;
1251
	if(isset($config['system']['developerspew'])) {
1252
		$mt = microtime();
1253
		echo "system_do_shell_commands() being called $mt\n";
1254
	}
1255

    
1256
	if ($early)
1257
		$cmdn = "earlyshellcmd";
1258
	else
1259
		$cmdn = "shellcmd";
1260

    
1261
	if (is_array($config['system'][$cmdn])) {
1262

    
1263
		/* *cmd is an array, loop through */
1264
		foreach ($config['system'][$cmdn] as $cmd) {
1265
			exec($cmd);
1266
		}
1267

    
1268
	} elseif($config['system'][$cmdn] <> "") {
1269

    
1270
		/* execute single item */
1271
		exec($config['system'][$cmdn]);
1272

    
1273
	}
1274
}
1275

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

    
1283
	if (isset($config['system']['disableconsolemenu'])) {
1284
		touch("{$g['varetc_path']}/disableconsole");
1285
	} else {
1286
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1287
	}
1288
}
1289

    
1290
function system_dmesg_save() {
1291
	global $g;
1292
	if(isset($config['system']['developerspew'])) {
1293
		$mt = microtime();
1294
		echo "system_dmesg_save() being called $mt\n";
1295
	}
1296

    
1297
	$dmesg = "";
1298
	exec("/sbin/dmesg", $dmesg);
1299

    
1300
	/* find last copyright line (output from previous boots may be present) */
1301
	$lastcpline = 0;
1302

    
1303
	for ($i = 0; $i < count($dmesg); $i++) {
1304
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1305
			$lastcpline = $i;
1306
	}
1307

    
1308
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1309
	if (!$fd) {
1310
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1311
		return 1;
1312
	}
1313

    
1314
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1315
		fwrite($fd, $dmesg[$i] . "\n");
1316

    
1317
	fclose($fd);
1318

    
1319
	return 0;
1320
}
1321

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

    
1329
	if (isset($config['system']['harddiskstandby'])) {
1330
		if ($g['booting']) {
1331
			echo 'Setting hard disk standby... ';
1332
		}
1333

    
1334
		$standby = $config['system']['harddiskstandby'];
1335
		// Check for a numeric value
1336
		if (is_numeric($standby)) {
1337
			// Sync the disk(s)
1338
			mwexec('/bin/sync');
1339
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1340
				// Reinitialize ATA-drives
1341
				mwexec('/usr/local/sbin/atareinit');
1342
				if ($g['booting']) {
1343
					echo "done.\n";
1344
				}
1345
			} else if ($g['booting']) {
1346
				echo "failed!\n";
1347
			}
1348
		} else if ($g['booting']) {
1349
			echo "failed!\n";
1350
		}
1351
	}
1352
}
1353

    
1354
function system_setup_sysctl() {
1355
	global $config;
1356
	if(isset($config['system']['developerspew'])) {
1357
		$mt = microtime();
1358
		echo "system_setup_sysctl() being called $mt\n";
1359
	}
1360

    
1361
	activate_sysctls();	
1362

    
1363
	if (isset($config['system']['sharednet'])) {
1364
		system_disable_arp_wrong_if();
1365
	}
1366
}
1367

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

    
1378
function system_enable_arp_wrong_if() {
1379
	global $config;
1380
	if(isset($config['system']['developerspew'])) {
1381
		$mt = microtime();
1382
		echo "system_enable_arp_wrong_if() being called $mt\n";
1383
	}
1384
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1385
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1386
}
1387

    
1388
function enable_watchdog() {
1389
	global $config;
1390
	return;
1391
	$install_watchdog = false;
1392
	$supported_watchdogs = array("Geode");
1393
	$file = file_get_contents("/var/log/dmesg.boot");
1394
	foreach($supported_watchdogs as $sd) {
1395
		if(stristr($file, "Geode")) {
1396
			$install_watchdog = true;
1397
		}
1398
	}
1399
	if($install_watchdog == true) {
1400
		if(is_process_running("watchdogd"))
1401
			mwexec("/usr/bin/killall watchdogd", true);
1402
		exec("/usr/sbin/watchdogd");
1403
	}
1404
}
1405

    
1406
function system_check_reset_button() {
1407
	global $g;
1408
	if($g['platform'] != "nanobsd")
1409
		return 0;
1410

    
1411
	$specplatform = system_identify_specific_platform();
1412

    
1413
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1414
		return 0;
1415

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

    
1418
	if ($retval == 99) {
1419
		/* user has pressed reset button for 2 seconds - 
1420
		   reset to factory defaults */
1421
		echo <<<EOD
1422

    
1423
***********************************************************************
1424
* Reset button pressed - resetting configuration to factory defaults. *
1425
* The system will reboot after this completes.                        *
1426
***********************************************************************
1427

    
1428

    
1429
EOD;
1430
		
1431
		reset_factory_defaults();
1432
		system_reboot_sync();
1433
		exit(0);
1434
	}
1435

    
1436
	return 0;
1437
}
1438

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

    
1465
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1466
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1467
	
1468
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1469
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1470
		
1471
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1472
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1473
	
1474
	/* unknown embedded platform */
1475
	return array('name' => 'embedded', 'descr' => 'embedded (unknown)');
1476
}
1477

    
1478
function system_get_dmesg_boot() {
1479
	global $g;
1480
		
1481
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1482
}
1483

    
1484
?>
(40-40/54)