Project

General

Profile

Download (44.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/sbin/syslogd	
35
	pfSense_BUILDER_BINARIES:	/usr/sbin/pccardd	/usr/local/sbin/lighttpd	/bin/chmod 	/bin/mkdir
36
	pfSense_BUILDER_BINARIES:	/usr/bin/tar		/usr/local/sbin/ntpd	/usr/sbin/ntpdate
37
	pfSense_BUILDER_BINARIES:	/usr/bin/nohup	/sbin/dmesg	/usr/local/sbin/atareinit	/sbin/kldload
38
	pfSense_MODULE:	utils
39
*/
40

    
41
function activate_powerd() {
42
	global $config, $g;
43
	if(isset($config['system']['powerd_enable'])) {
44
		if ($g["platform"] == "nanobsd")
45
			exec("/sbin/kldload cpufreq");
46
		exec("/usr/sbin/powerd -b adp -a adp");
47
	} else {
48
		if(is_process_running("powerd"))
49
			exec("/usr/bin/killall powerd");
50
	}
51
}
52

    
53
function get_default_sysctl_value($id) {
54
	global $sysctls;
55

    
56
	if (isset($sysctls[$id]))
57
		return $sysctls[$id];
58
}
59

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

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

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

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

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

    
89
	// Do not create blank domain lines, it breaks tools like dig.
90
	if($syscfg['domain'])
91
		$resolvconf = "domain {$syscfg['domain']}\n";
92

    
93
	$havedns = false;
94

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

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

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

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

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

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

    
157
	unlock($dnslock);
158

    
159
	return 0;
160
}
161

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

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

    
181
	return $master_list;
182
}
183

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

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

    
212
	return $master_list;
213
}
214

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

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

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

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

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

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

    
265
	if (isset($dnsmasqcfg['dhcpfirst']))
266
		$hosts .= $dhosts . $lhosts;
267
	else
268
		$hosts .= $lhosts . $dhosts;
269

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

    
286
	system_dhcpleases_configure();
287

    
288
	return 0;
289
}
290

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

    
308
function system_hostname_configure() {
309
	global $config, $g;
310
	if(isset($config['system']['developerspew'])) {
311
		$mt = microtime();
312
		echo "system_hostname_configure() being called $mt\n";
313
	}
314

    
315
	$syscfg = $config['system'];
316

    
317
	/* set hostname */
318
	$status = mwexec("/bin/hostname " .
319
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
320

    
321
    /* Setup host GUID ID.  This is used by ZFS. */
322
	mwexec("/etc/rc.d/hostid start");
323

    
324
	return $status;
325
}
326

    
327
function system_routing_configure($interface = "") {
328
	global $config, $g;
329
	if(isset($config['system']['developerspew'])) {
330
		$mt = microtime();
331
		echo "system_routing_configure() being called $mt\n";
332
	}
333

    
334
	$gatewayip = "";
335
	$interfacegw = "";
336
	$foundgw = false;
337
	/* tack on all the hard defined gateways as well */
338
	if (is_array($config['gateways']['gateway_item'])) {
339
		mwexec("/bin/rm {$g['tmp_path']}/*_defaultgw", true);
340
		foreach	($config['gateways']['gateway_item'] as $gateway) {
341
			if (isset($gateway['defaultgw'])) {
342
				if(strstr($gateway['gateway'], ":"))
343
					break;
344
				if ($gateway['gateway'] == "dynamic")
345
					$gateway['gateway'] = get_interface_gateway($gateway['interface']);
346
				$gatewayip = $gateway['gateway'];
347
				$interfacegw = $gateway['interface'];
348
				if (!empty($interfacegw)) {
349
					$defaultif = get_real_interface($gateway['interface']);
350
					if ($defaultif)
351
						@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gatewayip);
352
				}
353
				$foundgw = true;
354
				break;
355
			}
356
		}
357
	}
358
	if ($foundgw == false) {
359
		$defaultif = get_real_interface("wan");
360
		$interfacegw = "wan";
361
		$gatewayip = get_interface_gateway("wan");
362
		@touch("{$g['tmp_path']}/{$defaultif}_defaultgw");
363
	}	
364
	$dont_add_route = false;
365
	/* if OLSRD is enabled, allow WAN to house DHCP. */
366
	if($config['installedpackages']['olsrd']) {
367
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
368
			if($olsrd['enabledyngw'] == "on") {
369
				$dont_add_route = true;
370
				break;
371
			}
372
		}
373
	}
374

    
375
	if ($dont_add_route == false ) {
376
		if (!empty($interface) && $interface != $interfacegw)
377
			;
378
		else if (($interfacegw <> "bgpd") && (is_ipaddr($gatewayip))) {
379
			log_error("ROUTING: setting default route to $gatewayip");
380
			mwexec("/sbin/route change -inet default " . escapeshellarg($gatewayip));
381
		}
382
	}
383

    
384
	if (is_array($config['staticroutes']['route'])) {
385
		$gateways_arr = return_gateways_array();
386

    
387
		foreach ($config['staticroutes']['route'] as $rtent) {
388
			$gatewayip = "";
389
			if (empty($gateways_arr[$rtent['gateway']])) {
390
				log_error("Static Routes: Gateway IP could not be found for {$rtent['network']}");
391
				continue;
392
			}
393
			$gateway = $gateways_arr[$rtent['gateway']];
394
			if (!empty($interface) && $interface != $gateway['friendlyiface'])
395
				continue;
396
			$gatewayip = $gateway['gateway'];
397
			$interfacegw = $gateway['interface'];
398

    
399
			if (is_ipaddr($gatewayip)) {
400
				mwexec("/sbin/route change -inet " . escapeshellarg($rtent['network']) .
401
					" " . escapeshellarg($gatewayip));
402
			} else if (!empty($interfacegw)) {
403
				mwexec("/sbin/route change -inet " . 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','pptps','poes','l2tps');
458
		if($config['installedpackages']['package']) {
459
			foreach($config['installedpackages']['package'] as $package) {
460
				if($package['logging']) {
461
					array_push($separatelogfacilities, $package['logging']['facilityname']);
462
					mwexec("{$log_create_directive} 10240 {$g['varlog_path']}/{$package['logging']['logfilename']}");
463
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
464
				}
465
			}
466
		}
467
		$facilitylist = implode(',', array_unique($separatelogfacilities));
468
		/* write syslog.conf */		
469
		$fd = fopen("{$g['varetc_path']}/syslog.conf", "w");
470
		if (!$fd) {
471
			printf("Error: cannot open syslog.conf in system_syslogd_start().\n");
472
			return 1;
473
		}
474
		$syslogconf .= "!ntpdate,!ntpd\n";
475
		if (!isset($syslogcfg['disablelocallogging'])) 
476
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/ntpd.log\n";
477
		$syslogconf .= "!ppp\n";
478
		if (!isset($syslogcfg['disablelocallogging'])) 
479
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/ppp.log\n";
480
		$syslogconf .= "!pptps\n";
481
		if (!isset($syslogcfg['disablelocallogging'])) 
482
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/pptps.log\n";
483
		$syslogconf .= "!poes\n";
484
		if (!isset($syslogcfg['disablelocallogging'])) 
485
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/poes.log\n";
486
		$syslogconf .= "!l2tps\n";
487
		if (!isset($syslogcfg['disablelocallogging'])) 
488
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/l2tps.log\n";
489
		$syslogconf .= "!racoon\n";
490
		if (!isset($syslogcfg['disablelocallogging'])) 
491
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/ipsec.log\n";
492
		if (isset($syslogcfg['vpn'])) {
493
			if($syslogcfg['remoteserver'])
494
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver']}\n";
495
			if($syslogcfg['remoteserver2'])
496
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver2']}\n";
497
			if($syslogcfg['remoteserver3'])
498
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver3']}\n";
499
		}
500
		$syslogconf .= "!openvpn\n";
501
		if (!isset($syslogcfg['disablelocallogging'])) 
502
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/openvpn.log\n";
503
		if (isset($syslogcfg['vpn'])) {
504
			if($syslogcfg['remoteserver'])
505
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver']}\n";
506
			if($syslogcfg['remoteserver2'])
507
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver3']}\n";
508
			if($syslogcfg['remoteserver3'])
509
				$syslogconf .= "*.*					 @{$syslogcfg['remoteserver3']}\n";
510
		}
511
		$syslogconf .= "!apinger\n";
512
		if (!isset($syslogcfg['disablelocallogging']))
513
			$syslogconf .= "*.*					 {$log_directive}{$g['varlog_path']}/apinger.log\n";
514
		$syslogconf .= "!relayd\n";
515
		$syslogconf .= "*.* 						{$log_directive}{$g['varlog_path']}/relayd.log\n";
516
		$syslogconf .= "!-{$facilitylist}\n";
517
		if (!isset($syslogcfg['disablelocallogging'])) 
518
			$syslogconf .= <<<EOD
519
local0.*										 {$log_directive}{$g['varlog_path']}/filter.log
520
local3.*										 {$log_directive}{$g['varlog_path']}/vpn.log
521
local4.*										 {$log_directive}{$g['varlog_path']}/portalauth.log
522
local7.*										 {$log_directive}{$g['varlog_path']}/dhcpd.log
523
*.notice;kern.debug;lpr.info;mail.crit; 		 {$log_directive}{$g['varlog_path']}/system.log
524
news.err;local0.none;local3.none;local4.none; 	 {$log_directive}{$g['varlog_path']}/system.log
525
local7.none										 {$log_directive}{$g['varlog_path']}/system.log
526
security.*										 {$log_directive}{$g['varlog_path']}/system.log
527
auth.info;authpriv.info;daemon.info				 {$log_directive}{$g['varlog_path']}/system.log
528
auth.info;authpriv.info 						 |exec /usr/local/sbin/sshlockout_pf 15
529
*.emerg											 *
530

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

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

    
574
EOD;
575

    
576
}
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
}
590

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

    
600
EOD;
601

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

    
608
EOD;
609

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

    
614
EOD;
615

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

    
620
EOD;
621

    
622
}
623
		if (isset($syslogcfg['zmqserver'])) {
624
				$syslogconf .= <<<EOD
625
*.*								^{$syslogcfg['zmqserver']}
626

    
627
EOD;
628
		}
629
		fwrite($fd, $syslogconf);
630
		fclose($fd);
631

    
632
		// Ensure that the log directory exists
633
		if(!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
634
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
635

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

    
642
	} else {
643
		$retval = mwexec("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log");
644
	}
645

    
646
	if ($g['booting'])
647
		echo "done.\n";
648

    
649
	return $retval;
650
}
651

    
652
function system_pccard_start() {
653
	global $config, $g;
654
	if(isset($config['system']['developerspew'])) {
655
		$mt = microtime();
656
		echo "system_pccard_start() being called $mt\n";
657
	}
658

    
659
	if ($g['booting'])
660
		echo "Initializing PCMCIA...";
661

    
662
	/* kill any running pccardd */
663
	killbypid("{$g['varrun_path']}/pccardd.pid");
664

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

    
668
	if ($g['booting']) {
669
		if ($res == 0)
670
			echo "done.\n";
671
		else
672
			echo "failed!\n";
673
	}
674

    
675
	return $res;
676
}
677

    
678

    
679
function system_webgui_start() {
680
	global $config, $g;
681

    
682
	if ($g['booting'])
683
		echo "Starting webConfigurator...";
684

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

    
688
	sleep(1);
689

    
690
	chdir($g['www_path']);
691

    
692
	/* defaults */
693
	$portarg = "80";
694
	$crt = "";
695
	$key = "";
696
	$ca = "";
697

    
698
	/* non-standard port? */
699
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
700
		$portarg = "{$config['system']['webgui']['port']}";
701

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

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

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

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

    
753
	if ($g['booting']) {
754
		if ($res == 0)
755
			echo "done.\n";
756
		else
757
			echo "failed!\n";
758
	}
759

    
760
	return $res;
761
}
762

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

    
777
	global $config, $g;
778

    
779
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
780
		mkdir("{$g['tmp_path']}/lighttpdcompress");
781

    
782
	if(isset($config['system']['developerspew'])) {
783
		$mt = microtime();
784
		echo "system_generate_lighty_config() being called $mt\n";
785
	}
786

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

    
814
	$memory = get_memory();
815
	$avail = $memory[0];
816

    
817
	if($avail > 0 and $avail < 65) {
818
		$fast_cgi_enable = false;
819
	}
820

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

    
841
	if($captive_portal == true)  {	
842
		$bin_environment =  <<<EOC
843
			"bin-environment" => (
844
				"PHP_FCGI_CHILDREN" => "$max_procs",
845
				"PHP_FCGI_MAX_REQUESTS" => "500"
846
			),
847
EOC;
848

    
849
	} else if ($avail > 0 and $avail < 128) {
850
		$bin_environment = <<<EOC
851
			"bin-environment" => (
852
				"PHP_FCGI_CHILDREN" => "$max_procs",
853
				"PHP_FCGI_MAX_REQUESTS" => "2",
854
			),
855

    
856
EOC;
857
	} else
858
		$bin_environment =  <<<EOC
859
			"bin-environment" => (
860
				"PHP_FCGI_CHILDREN" => "$max_procs",
861
				"PHP_FCGI_MAX_REQUESTS" => "500"
862
			),
863
EOC;
864

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

    
883
#### CGI module
884
cgi.assign                 = ( ".cgi" => "" )
885

    
886
EOD;
887
	} else {
888
		$fastcgi_config = "";
889
		$module = "\"mod_cgi\"";
890
		$cgi_config = <<<EOD
891
#### CGI module
892
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
893
                               ".cgi" => "" )
894

    
895
EOD;
896
	}
897

    
898
	$lighty_config = "";
899
	$lighty_config .= <<<EOD
900
#
901
# lighttpd configuration file
902
#
903
# use a it as base for lighttpd 1.0.0 and above
904
#
905
############ Options you really have to take care of ####################
906

    
907
## FreeBSD!
908
server.event-handler	= "freebsd-kqueue"
909
server.network-backend 	= "writev"
910

    
911
## modules to load
912
server.modules              =   (
913
									{$captive_portal_module}
914
									"mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect",
915
									{$module}{$captiveportal}
916
								)
917

    
918
## Unused modules
919
#                               "mod_setenv",
920
#                               "mod_rewrite",
921
#                               "mod_ssi",
922
#                               "mod_usertrack",
923
#                               "mod_expire",
924
#                               "mod_secdownload",
925
#                               "mod_rrdtool",
926
#                               "mod_auth",
927
#                               "mod_status",
928
#                               "mod_alias",
929
#                               "mod_proxy",
930
#                               "mod_simple_vhost",
931
#                               "mod_evhost",
932
#                               "mod_userdir",
933
#                               "mod_cgi",
934

    
935
server.max-keep-alive-requests = 15
936
server.max-keep-alive-idle = 30
937

    
938
## a static document-root, for virtual-hosting take look at the
939
## server.virtual-* options
940
server.document-root        = "{$document_root}"
941
{$captive_portal_rewrite}
942

    
943
# Maximum idle time with nothing being written (php downloading)
944
server.max-write-idle = 999
945

    
946
## where to send error-messages to
947
server.errorlog             = "/var/log/lighttpd.error.log"
948

    
949
# files to check for if .../ is requested
950
server.indexfiles           = ( "index.php", "index.html",
951
                                "index.htm", "default.htm" )
952

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

    
1006
# Use the "Content-Type" extended attribute to obtain mime type if possible
1007
#mimetypes.use-xattr        = "enable"
1008

    
1009
#### accesslog module
1010
#accesslog.filename          = "/dev/null"
1011

    
1012
## deny access the file-extensions
1013
#
1014
# ~    is for backupfiles from vi, emacs, joe, ...
1015
# .inc is often used for code includes which should in general not be part
1016
#      of the document-root
1017
url.access-deny             = ( "~", ".inc" )
1018

    
1019

    
1020
######### Options that are good to be but not neccesary to be changed #######
1021

    
1022
## bind to port (default: 80)
1023
server.port                = {$lighty_port}
1024

    
1025
## error-handler for status 404
1026
#server.error-handler-404   = "/error-handler.html"
1027
#server.error-handler-404   = "/error-handler.php"
1028

    
1029
## to help the rc.scripts
1030
server.pid-file            = "/var/run/{$pid_file}"
1031

    
1032
## virtual directory listings
1033
server.dir-listing         = "disable"
1034

    
1035
## enable debugging
1036
debug.log-request-header   = "disable"
1037
debug.log-response-header  = "disable"
1038
debug.log-request-handling = "disable"
1039
debug.log-file-not-found   = "disable"
1040

    
1041
# gzip compression
1042
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1043
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1044

    
1045
{$server_upload_dirs}
1046

    
1047
{$server_max_request_size}
1048

    
1049
{$fastcgi_config}
1050

    
1051
{$cgi_config}
1052

    
1053
{$captive_portal_mod_evasive}
1054

    
1055
expire.url = (
1056
				"" => "access 50 hours",	
1057
        )
1058

    
1059
EOD;
1060

    
1061
	$cert = str_replace("\r", "", $cert);
1062
	$key = str_replace("\r", "", $key);
1063
	$ca = str_replace("\r", "", $ca);
1064

    
1065
	$cert = str_replace("\n\n", "\n", $cert);
1066
	$key = str_replace("\n\n", "\n", $key);
1067
	$ca = str_replace("\n\n", "\n", $ca);
1068

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

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

    
1099
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1100
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1101
	}
1102

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

    
1116
	$fd = fopen("{$filename}", "w");
1117
	if (!$fd) {
1118
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
1119
		return 1;
1120
	}
1121
	fwrite($fd, $lighty_config);
1122
	fclose($fd);
1123

    
1124
	return 0;
1125

    
1126
}
1127

    
1128
function system_timezone_configure() {
1129
	global $config, $g;
1130
	if(isset($config['system']['developerspew'])) {
1131
		$mt = microtime();
1132
		echo "system_timezone_configure() being called $mt\n";
1133
	}
1134

    
1135
	$syscfg = $config['system'];
1136

    
1137
	if ($g['booting'])
1138
		echo "Setting timezone...";
1139

    
1140
	/* extract appropriate timezone file */
1141
	$timezone = $syscfg['timezone'];
1142
	if (!$timezone)
1143
		$timezone = "Etc/UTC";
1144

    
1145
	conf_mount_rw();
1146

    
1147
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1148
		escapeshellarg($timezone) . " > /etc/localtime");
1149

    
1150
	mwexec("sync");
1151
	conf_mount_ro();
1152

    
1153
	if ($g['booting'])
1154
		echo "done.\n";
1155
}
1156

    
1157
function system_ntp_configure() {
1158
	global $config, $g;
1159

    
1160
	$ntpcfg = "# \n";
1161
	$ntpcfg .= "# pfSense OpenNTPD configuration file \n";
1162
	$ntpcfg .= "# \n\n";
1163

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

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

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

    
1200
	/* slurp! */
1201
	fclose($fd);
1202

    
1203
	/* if openntpd is running, kill it */
1204
	while(is_process_running("ntpd")) {
1205
		killbyname("ntpd");
1206
	}
1207

    
1208
	/* if /var/empty does not exist, create it */
1209
	if(!is_dir("/var/empty"))
1210
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1211

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

    
1218
}
1219

    
1220
function sync_system_time() {
1221
	global $config, $g;
1222

    
1223
	if ($g['booting'])
1224
		echo "Syncing system time before startup...";
1225

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

    
1236
function system_halt() {
1237
	global $g;
1238

    
1239
	system_reboot_cleanup();
1240

    
1241
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1242
}
1243

    
1244
function system_reboot() {
1245
	global $g;
1246

    
1247
	system_reboot_cleanup();
1248

    
1249
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1250
}
1251

    
1252
function system_reboot_sync() {
1253
	global $g;
1254

    
1255
	system_reboot_cleanup();
1256

    
1257
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1258
}
1259

    
1260
function system_reboot_cleanup() {
1261
	mwexec("/usr/local/bin/beep.sh stop");
1262
	require_once("captiveportal.inc");
1263
	captiveportal_radius_stop_all();
1264
	require_once("voucher.inc");
1265
	voucher_save_db_to_config();
1266
	// mwexec("/etc/rc.stop_packages");
1267
}
1268

    
1269
function system_do_shell_commands($early = 0) {
1270
	global $config, $g;
1271
	if(isset($config['system']['developerspew'])) {
1272
		$mt = microtime();
1273
		echo "system_do_shell_commands() being called $mt\n";
1274
	}
1275

    
1276
	if ($early)
1277
		$cmdn = "earlyshellcmd";
1278
	else
1279
		$cmdn = "shellcmd";
1280

    
1281
	if (is_array($config['system'][$cmdn])) {
1282

    
1283
		/* *cmd is an array, loop through */
1284
		foreach ($config['system'][$cmdn] as $cmd) {
1285
			exec($cmd);
1286
		}
1287

    
1288
	} elseif($config['system'][$cmdn] <> "") {
1289

    
1290
		/* execute single item */
1291
		exec($config['system'][$cmdn]);
1292

    
1293
	}
1294
}
1295

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

    
1303
	if (isset($config['system']['disableconsolemenu'])) {
1304
		touch("{$g['varetc_path']}/disableconsole");
1305
	} else {
1306
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1307
	}
1308
}
1309

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

    
1317
	$dmesg = "";
1318
	exec("/sbin/dmesg", $dmesg);
1319

    
1320
	/* find last copyright line (output from previous boots may be present) */
1321
	$lastcpline = 0;
1322

    
1323
	for ($i = 0; $i < count($dmesg); $i++) {
1324
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1325
			$lastcpline = $i;
1326
	}
1327

    
1328
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1329
	if (!$fd) {
1330
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1331
		return 1;
1332
	}
1333

    
1334
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1335
		fwrite($fd, $dmesg[$i] . "\n");
1336

    
1337
	fclose($fd);
1338

    
1339
	return 0;
1340
}
1341

    
1342
function system_set_harddisk_standby() {
1343
	global $g, $config;
1344
	if(isset($config['system']['developerspew'])) {
1345
		$mt = microtime();
1346
		echo "system_set_harddisk_standby() being called $mt\n";
1347
	}
1348

    
1349
	if (isset($config['system']['harddiskstandby'])) {
1350
		if ($g['booting']) {
1351
			echo 'Setting hard disk standby... ';
1352
		}
1353

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

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

    
1381
	activate_sysctls();	
1382

    
1383
	if (isset($config['system']['sharednet'])) {
1384
		system_disable_arp_wrong_if();
1385
	}
1386
}
1387

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

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

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

    
1426
function system_check_reset_button() {
1427
	global $g;
1428
	if($g['platform'] != "nanobsd")
1429
		return 0;
1430

    
1431
	$specplatform = system_identify_specific_platform();
1432

    
1433
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1434
		return 0;
1435

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

    
1438
	if ($retval == 99) {
1439
		/* user has pressed reset button for 2 seconds - 
1440
		   reset to factory defaults */
1441
		echo <<<EOD
1442

    
1443
***********************************************************************
1444
* Reset button pressed - resetting configuration to factory defaults. *
1445
* The system will reboot after this completes.                        *
1446
***********************************************************************
1447

    
1448

    
1449
EOD;
1450
		
1451
		reset_factory_defaults();
1452
		system_reboot_sync();
1453
		exit(0);
1454
	}
1455

    
1456
	return 0;
1457
}
1458

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

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

    
1498
function system_get_dmesg_boot() {
1499
	global $g;
1500
		
1501
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1502
}
1503

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