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/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
	if (isset($config['dnsmasq']['enable']) && !isset($config['system']['dnslocalhost']))
94
		$resolvconf .= "nameserver 127.0.0.1\n";
95

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

    
116
	$dnslock = lock('resolvconf', LOCK_EX);
117

    
118
	$fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
119
	if (!$fd) {
120
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
121
		unlock($dnslock);
122
		return 1;
123
	}
124

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

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

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

    
151
	unlock($dnslock);
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 = glob("/var/etc/searchdomain_*");
163
	if (is_array($search_lists)) {
164
		foreach($search_lists as $fdns) {
165
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
166
			if (!is_array($contents))
167
				continue;
168
			foreach ($contents as $dns) {
169
				if(is_hostname($dns)) 
170
					$master_list[] = $dns;
171
			}
172
		}
173
	}
174

    
175
	return $master_list;
176
}
177

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

    
196
	// Read in any extra nameservers
197
	if(file_exists("/var/etc/nameservers.conf")) {
198
		$dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
199
		if(is_array($dns_s)) {
200
			foreach($dns_s as $dns)
201
				if (is_ipaddr($dns))
202
					$master_list[] = $dns;
203
		}
204
	}
205

    
206
	return $master_list;
207
}
208

    
209
function system_hosts_generate() {
210
	global $config, $g;
211
	if(isset($config['system']['developerspew'])) {
212
		$mt = microtime();
213
		echo "system_hosts_generate() being called $mt\n";
214
	}
215

    
216
	$syscfg = $config['system'];
217
	$dnsmasqcfg = $config['dnsmasq'];
218

    
219
	if (!is_array($dnsmasqcfg['hosts'])) {
220
		$dnsmasqcfg['hosts'] = array();
221
	}
222
	$hostscfg = $dnsmasqcfg['hosts'];
223

    
224
	$hosts = "127.0.0.1	localhost localhost.{$syscfg['domain']}\n";
225
	$lhosts = "";
226
	$dhosts = "";
227

    
228
	if ($config['interfaces']['lan']) {
229
		$cfgip = get_interface_ip("lan");
230
		if (is_ipaddr($cfgip))
231
			$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
232
	} else {
233
		$sysiflist = get_configured_interface_list();
234
		foreach ($sysiflist as $sysif) {
235
			if (!interface_has_gateway($sysif)) {
236
				$cfgip = get_interface_ip($sysif);
237
				if (is_ipaddr($cfgip)) {
238
					$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
239
					break;
240
				}
241
			}
242
		}
243
	}
244

    
245
	foreach ($hostscfg as $host) {
246
		if ($host['host'])
247
			$lhosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
248
		else
249
			$lhosts .= "{$host['ip']}	{$host['domain']}\n";
250
	}
251
	if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpd'])) {
252
		foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf)
253
			if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
254
					foreach ($dhcpifconf['staticmap'] as $host)
255
						if ($host['ipaddr'] && $host['hostname'])
256
							$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
257
	}
258

    
259
	if (isset($dnsmasqcfg['dhcpfirst']))
260
		$hosts .= $dhosts . $lhosts;
261
	else
262
		$hosts .= $lhosts . $dhosts;
263

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

    
280
	system_dhcpleases_configure();
281

    
282
	return 0;
283
}
284

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

    
302
function system_hostname_configure() {
303
	global $config, $g;
304
	if(isset($config['system']['developerspew'])) {
305
		$mt = microtime();
306
		echo "system_hostname_configure() being called $mt\n";
307
	}
308

    
309
	$syscfg = $config['system'];
310

    
311
	/* set hostname */
312
	$status = mwexec("/bin/hostname " .
313
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
314

    
315
    /* Setup host GUID ID.  This is used by ZFS. */
316
	mwexec("/etc/rc.d/hostid start");
317

    
318
	return $status;
319
}
320

    
321
function system_routing_configure($interface = "") {
322
	global $config, $g;
323
	if(isset($config['system']['developerspew'])) {
324
		$mt = microtime();
325
		echo "system_routing_configure() being called $mt\n";
326
	}
327

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

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

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

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

    
394
			if (is_ipaddr($gatewayip)) {
395
				mwexec("/sbin/route change -inet " . escapeshellarg($rtent['network']) .
396
					" " . escapeshellarg($gatewayip));
397
			} else if (!empty($interfacegw)) {
398
				mwexec("/sbin/route change -inet " . escapeshellarg($rtent['network']) .
399
					" -iface " . escapeshellarg($interfacegw));
400
			}
401
		}
402
	}
403

    
404
	return 0;
405
}
406

    
407
function system_routing_enable() {
408
	global $config, $g;
409
	if(isset($config['system']['developerspew'])) {
410
		$mt = microtime();
411
		echo "system_routing_enable() being called $mt\n";
412
	}
413

    
414
	return mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
415
}
416

    
417
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
418
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
419
	$facility .= " ".
420
	$remote_servers = "";
421
	$pad_to  = 56;
422
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
423
	if($syslogcfg['remoteserver'])
424
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@{$syslogcfg['remoteserver']}\n";
425
	if($syslogcfg['remoteserver2'])
426
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@{$syslogcfg['remoteserver2']}\n";
427
	if($syslogcfg['remoteserver3'])
428
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@{$syslogcfg['remoteserver3']}\n";
429
	return $remote_servers;
430
}
431

    
432
function system_syslogd_start() {
433
	global $config, $g;
434
	if(isset($config['system']['developerspew'])) {
435
		$mt = microtime();
436
		echo "system_syslogd_start() being called $mt\n";
437
	}
438

    
439
	mwexec("/etc/rc.d/hostid start");
440

    
441
	$syslogcfg = $config['syslog'];
442

    
443
	if ($g['booting'])
444
		echo "Starting syslog...";
445
	else
446
		killbypid("{$g['varrun_path']}/syslog.pid");
447

    
448
	if(is_process_running("syslogd"))
449
		mwexec('/bin/pkill syslogd');
450
	if(is_process_running("fifolog_writer"))
451
		mwexec('/bin/pkill fifolog_writer');
452
	
453
	// Define carious commands for logging
454
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
455
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
456
	$clog_create = "/usr/sbin/clog -i -s ";
457
	$clog_log = "%";
458

    
459
	// Which logging type are we using this week??
460
	if(isset($config['system']['usefifolog'])) {
461
		$log_directive = $fifolog_log;
462
		$log_create_directive = $fifolog_create;
463
	} else { // Defaults to CLOG
464
		$log_directive = $clog_log;
465
		$log_create_directive = $clog_create;
466
	}
467
	
468
	if (isset($syslogcfg)) {
469
		$separatelogfacilities = array('ntpd','racoon','openvpn','pptps','poes','l2tps','relayd','hostapd');
470
		if($config['installedpackages']['package']) {
471
			foreach($config['installedpackages']['package'] as $package) {
472
				if($package['logging']) {
473
					array_push($separatelogfacilities, $package['logging']['facilityname']);
474
					mwexec("{$log_create_directive} 10240 {$g['varlog_path']}/{$package['logging']['logfilename']}");
475
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
476
				}
477
			}
478
		}
479
		$facilitylist = implode(',', array_unique($separatelogfacilities));
480
		/* write syslog.conf */		
481
		$fd = fopen("{$g['varetc_path']}/syslog.conf", "w");
482
		if (!$fd) {
483
			printf("Error: cannot open syslog.conf in system_syslogd_start().\n");
484
			return 1;
485
		}
486
		$syslogconf .= "!ntpdate,ntpd\n";
487
		if (!isset($syslogcfg['disablelocallogging'])) 
488
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
489

    
490
		$syslogconf .= "!ppp\n";
491
		if (!isset($syslogcfg['disablelocallogging'])) 
492
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
493

    
494
		$syslogconf .= "!pptps\n";
495
		if (!isset($syslogcfg['disablelocallogging'])) 
496
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/pptps.log\n";
497

    
498
		$syslogconf .= "!poes\n";
499
		if (!isset($syslogcfg['disablelocallogging'])) 
500
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
501

    
502
		$syslogconf .= "!l2tps\n";
503
		if (!isset($syslogcfg['disablelocallogging'])) 
504
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/l2tps.log\n";
505

    
506
		$syslogconf .= "!racoon\n";
507
		if (!isset($syslogcfg['disablelocallogging'])) 
508
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ipsec.log\n";
509
		if (isset($syslogcfg['vpn']))
510
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
511

    
512
		$syslogconf .= "!openvpn\n";
513
		if (!isset($syslogcfg['disablelocallogging'])) 
514
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/openvpn.log\n";
515
		if (isset($syslogcfg['vpn']))
516
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
517

    
518
		$syslogconf .= "!apinger\n";
519
		if (!isset($syslogcfg['disablelocallogging']))
520
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/apinger.log\n";
521
		if (isset($syslogcfg['apinger']))
522
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
523

    
524
		$syslogconf .= "!relayd\n";
525
		if (!isset($syslogcfg['disablelocallogging']))
526
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/relayd.log\n";
527
		if (isset($syslogcfg['relayd']))
528
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
529

    
530
		$syslogconf .= "!hostapd\n";
531
		if (!isset($syslogcfg['disablelocallogging']))
532
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
533
		if (isset($syslogcfg['hostapd']))
534
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
535

    
536
		$syslogconf .= "!-{$facilitylist}\n";
537
		if (!isset($syslogcfg['disablelocallogging'])) 
538
			$syslogconf .= <<<EOD
539
local0.*							{$log_directive}{$g['varlog_path']}/filter.log
540
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
541
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
542
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
543
*.notice;kern.debug;lpr.info;mail.crit;				{$log_directive}{$g['varlog_path']}/system.log
544
news.err;local0.none;local3.none;local4.none;			{$log_directive}{$g['varlog_path']}/system.log
545
local7.none							{$log_directive}{$g['varlog_path']}/system.log
546
security.*							{$log_directive}{$g['varlog_path']}/system.log
547
auth.info;authpriv.info;daemon.info				{$log_directive}{$g['varlog_path']}/system.log
548
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
549
*.emerg								*
550

    
551
EOD;
552
		if (isset($syslogcfg['filter']))
553
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local0.*");
554
		if (isset($syslogcfg['vpn']))
555
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
556
		if (isset($syslogcfg['portalauth']))
557
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
558
		if (isset($syslogcfg['dhcp']))
559
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
560
		if (isset($syslogcfg['system'])) {
561
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.notice;kern.debug;lpr.info;mail.crit;");
562
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "news.err;local0.none;local3.none;local7.none");
563
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "security.*");
564
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "auth.info;authpriv.info;daemon.info");
565
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.emerg");
566
		}
567
		if (isset($syslogcfg['logall'])) {
568
			// Make everything mean everything, including facilities excluded above.
569
			$syslogconf .= "!*\n";
570
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
571
		}
572

    
573
		if (isset($syslogcfg['zmqserver'])) {
574
				$syslogconf .= <<<EOD
575
*.*								^{$syslogcfg['zmqserver']}
576

    
577
EOD;
578
		}
579
		fwrite($fd, $syslogconf);
580
		fclose($fd);
581

    
582
		// Ensure that the log directory exists
583
		if(!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
584
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
585

    
586
		// Are we logging to a least one remote server ?
587
		if(strpos($syslogconf, "@") != false)
588
			$retval = mwexec_bg("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log -f {$g['varetc_path']}/syslog.conf");
589
		else {
590
			$retval = mwexec_bg("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log -f {$g['varetc_path']}/syslog.conf");
591
		}
592

    
593
	} else {
594
		$retval = mwexec_bg("/usr/sbin/syslogd -c -c -l /var/dhcpd/var/run/log");
595
	}
596

    
597
	if ($g['booting'])
598
		echo "done.\n";
599

    
600
	return $retval;
601
}
602

    
603
function system_pccard_start() {
604
	global $config, $g;
605
	if(isset($config['system']['developerspew'])) {
606
		$mt = microtime();
607
		echo "system_pccard_start() being called $mt\n";
608
	}
609

    
610
	if ($g['booting'])
611
		echo "Initializing PCMCIA...";
612

    
613
	/* kill any running pccardd */
614
	killbypid("{$g['varrun_path']}/pccardd.pid");
615

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

    
619
	if ($g['booting']) {
620
		if ($res == 0)
621
			echo "done.\n";
622
		else
623
			echo "failed!\n";
624
	}
625

    
626
	return $res;
627
}
628

    
629

    
630
function system_webgui_start() {
631
	global $config, $g;
632

    
633
	if ($g['booting'])
634
		echo "Starting webConfigurator...";
635

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

    
639
	sleep(1);
640

    
641
	chdir($g['www_path']);
642

    
643
	/* defaults */
644
	$portarg = "80";
645
	$crt = "";
646
	$key = "";
647
	$ca = "";
648

    
649
	/* non-standard port? */
650
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
651
		$portarg = "{$config['system']['webgui']['port']}";
652

    
653
	if ($config['system']['webgui']['protocol'] == "https") {
654
		// Ensure that we have a webConfigurator CERT
655
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
656
		if(!is_array($cert) && !$cert['crt'] && !$cert['prv']) {
657
			if (!is_array($config['ca']))
658
				$config['ca'] = array();
659
			$a_ca =& $config['ca'];
660
			if (!is_array($config['cert']))
661
				$config['cert'] = array();
662
			$a_cert =& $config['cert'];
663
			log_error("Creating SSL Certificate for this host");
664
			$cert = array();
665
			$cert['refid'] = uniqid();
666
			$cert['descr'] = "webConfigurator default";
667
			mwexec("/usr/bin/openssl genrsa 1024 > {$g['tmp_path']}/ssl.key");
668
			mwexec("/usr/bin/openssl req -new -x509 -nodes -sha1 -days 2000 -key {$g['tmp_path']}/ssl.key > {$g['tmp_path']}/ssl.crt");
669
			$crt = file_get_contents("{$g['tmp_path']}/ssl.crt");
670
			$key = file_get_contents("{$g['tmp_path']}/ssl.key");
671
			unlink("{$g['tmp_path']}/ssl.key");
672
			unlink("{$g['tmp_path']}/ssl.crt");
673
			cert_import($cert, $crt, $key);
674
			$a_cert[] = $cert;
675
			$config['system']['webgui']['ssl-certref'] = $cert['refid'];
676
			write_config("Importing HTTPS certificate");
677
			if(!$config['system']['webgui']['port'])
678
				$portarg = "443";
679
			$ca = ca_chain($cert);
680
		} else {
681
			$crt = base64_decode($cert['crt']);
682
			$key = base64_decode($cert['prv']);
683
			if(!$config['system']['webgui']['port'])
684
				$portarg = "443";
685
			$ca = ca_chain($cert);
686
		}
687
	}
688

    
689
	/* generate lighttpd configuration */
690
	$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
691
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
692
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
693
		"cert.pem", "ca.pem", $max_procs);
694

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

    
698
	/* fetch page to preload apc cache */
699
	$proto = "http";
700
	if ($config['system']['webgui']['protocol'])
701
		$proto = $config['system']['webgui']['protocol'];
702
	mwexec_bg("/usr/bin/fetch -o /dev/null -q {$proto}://localhost:{$portarg}/preload.php");
703

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

    
711
	return $res;
712
}
713

    
714
function system_generate_lighty_config($filename,
715
	$cert,
716
	$key,
717
	$ca,
718
	$pid_file,
719
	$port = 80,
720
	$document_root = "/usr/local/www/",
721
	$cert_location = "cert.pem",
722
	$ca_location = "ca.pem",
723
	$max_procs = 1,
724
	$max_requests = "2",
725
	$fast_cgi_enable = true,
726
	$captive_portal = false) {
727

    
728
	global $config, $g;
729

    
730
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
731
		mkdir("{$g['tmp_path']}/lighttpdcompress");
732

    
733
	if(isset($config['system']['developerspew'])) {
734
		$mt = microtime();
735
		echo "system_generate_lighty_config() being called $mt\n";
736
	}
737

    
738
	if($captive_portal == true)  {
739
		$captiveportal = ",\"mod_rewrite\"";
740
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?redirurl=$1\" )\n";
741
		$captive_portal_module = "";
742
		$maxprocperip = $config['captiveportal']['maxprocperip'];
743
		if($maxprocperip and $maxprocperip > 0)
744
			$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
745
		else
746
			$captive_portal_mod_evasive = "";
747
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
748
		exec("mkdir -p {$g['tmp_path']}/captiveportal");
749
		exec("chmod a-w {$g['tmp_path']}/captiveportal");
750
		$server_max_request_size = "server.max-request-size    = 384";
751
	} else {
752
		$captiveportal = "";
753
		$captive_portal_rewrite = "";
754
		$captive_portal_module = "";
755
		$captive_portal_mod_evasive = "";
756
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
757
		$server_max_request_size = "server.max-request-size    = 2097152";
758
	}
759
	
760
	if($port <> "")
761
		$lighty_port = $port;
762
	else
763
		$lighty_port = "80";
764

    
765
	$memory = get_memory();
766
	$avail = $memory[0];
767

    
768
	if($avail > 0 and $avail < 65) {
769
		$fast_cgi_enable = false;
770
	}
771

    
772
	// Ramp up captive portal max procs
773
	//  Work relative to the default of 2, for values that would be >2.
774
	if($captive_portal == true)  {
775
		if($avail > 65 and $avail < 98) {
776
			$max_procs = 1;
777
		}
778
		if($avail > 97 and $avail < 128) {
779
			$max_procs = 2;
780
		}
781
		if($avail > 127 and $avail < 256) {
782
			$max_procs += 1;
783
		}
784
		if($avail > 255 and $avail < 384) {
785
			$max_procs += 2;
786
		}
787
		if($avail > 383) {
788
			$max_procs += 3;
789
		}
790
	}
791

    
792
	if($captive_portal == true)  {	
793
		$bin_environment =  <<<EOC
794
			"bin-environment" => (
795
				"PHP_FCGI_CHILDREN" => "$max_procs",
796
				"PHP_FCGI_MAX_REQUESTS" => "500"
797
			),
798
EOC;
799

    
800
	} else if ($avail > 0 and $avail < 128) {
801
		$bin_environment = <<<EOC
802
			"bin-environment" => (
803
				"PHP_FCGI_CHILDREN" => "$max_procs",
804
				"PHP_FCGI_MAX_REQUESTS" => "2",
805
			),
806

    
807
EOC;
808
	} else
809
		$bin_environment =  <<<EOC
810
			"bin-environment" => (
811
				"PHP_FCGI_CHILDREN" => "$max_procs",
812
				"PHP_FCGI_MAX_REQUESTS" => "500"
813
			),
814
EOC;
815

    
816
	if($fast_cgi_enable == true) {
817
		$module = "\"mod_fastcgi\", \"mod_cgi\"";
818
		$cgi_config = "";
819
		$fastcgi_config = <<<EOD
820
#### fastcgi module
821
## read fastcgi.txt for more info
822
fastcgi.server = ( ".php" =>
823
	( "localhost" =>
824
		(
825
			"socket" => "{$g['tmp_path']}/php-fastcgi.socket",
826
			"min-procs" => 0,
827
			"max-procs" => {$max_procs},
828
{$bin_environment}
829
			"bin-path" => "/usr/local/bin/php"
830
		)
831
	)
832
)
833

    
834
#### CGI module
835
cgi.assign                 = ( ".cgi" => "" )
836

    
837
EOD;
838
	} else {
839
		$fastcgi_config = "";
840
		$module = "\"mod_cgi\"";
841
		$cgi_config = <<<EOD
842
#### CGI module
843
cgi.assign                 = ( ".php"  => "/usr/local/bin/php",
844
                               ".cgi" => "" )
845

    
846
EOD;
847
	}
848

    
849
	$lighty_config = "";
850
	$lighty_config .= <<<EOD
851
#
852
# lighttpd configuration file
853
#
854
# use a it as base for lighttpd 1.0.0 and above
855
#
856
############ Options you really have to take care of ####################
857

    
858
## FreeBSD!
859
server.event-handler	= "freebsd-kqueue"
860
server.network-backend 	= "writev"
861

    
862
## modules to load
863
server.modules              =   (
864
									{$captive_portal_module}
865
									"mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect",
866
									{$module}{$captiveportal}
867
								)
868

    
869
## Unused modules
870
#                               "mod_setenv",
871
#                               "mod_rewrite",
872
#                               "mod_ssi",
873
#                               "mod_usertrack",
874
#                               "mod_expire",
875
#                               "mod_secdownload",
876
#                               "mod_rrdtool",
877
#                               "mod_auth",
878
#                               "mod_status",
879
#                               "mod_alias",
880
#                               "mod_proxy",
881
#                               "mod_simple_vhost",
882
#                               "mod_evhost",
883
#                               "mod_userdir",
884
#                               "mod_cgi",
885

    
886
server.max-keep-alive-requests = 15
887
server.max-keep-alive-idle = 30
888

    
889
## a static document-root, for virtual-hosting take look at the
890
## server.virtual-* options
891
server.document-root        = "{$document_root}"
892
{$captive_portal_rewrite}
893

    
894
# Maximum idle time with nothing being written (php downloading)
895
server.max-write-idle = 999
896

    
897
## where to send error-messages to
898
server.errorlog             = "/var/log/lighttpd.error.log"
899

    
900
# files to check for if .../ is requested
901
server.indexfiles           = ( "index.php", "index.html",
902
                                "index.htm", "default.htm" )
903

    
904
# mimetype mapping
905
mimetype.assign             = (
906
  ".pdf"          =>      "application/pdf",
907
  ".sig"          =>      "application/pgp-signature",
908
  ".spl"          =>      "application/futuresplash",
909
  ".class"        =>      "application/octet-stream",
910
  ".ps"           =>      "application/postscript",
911
  ".torrent"      =>      "application/x-bittorrent",
912
  ".dvi"          =>      "application/x-dvi",
913
  ".gz"           =>      "application/x-gzip",
914
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
915
  ".swf"          =>      "application/x-shockwave-flash",
916
  ".tar.gz"       =>      "application/x-tgz",
917
  ".tgz"          =>      "application/x-tgz",
918
  ".tar"          =>      "application/x-tar",
919
  ".zip"          =>      "application/zip",
920
  ".mp3"          =>      "audio/mpeg",
921
  ".m3u"          =>      "audio/x-mpegurl",
922
  ".wma"          =>      "audio/x-ms-wma",
923
  ".wax"          =>      "audio/x-ms-wax",
924
  ".ogg"          =>      "audio/x-wav",
925
  ".wav"          =>      "audio/x-wav",
926
  ".gif"          =>      "image/gif",
927
  ".jpg"          =>      "image/jpeg",
928
  ".jpeg"         =>      "image/jpeg",
929
  ".png"          =>      "image/png",
930
  ".xbm"          =>      "image/x-xbitmap",
931
  ".xpm"          =>      "image/x-xpixmap",
932
  ".xwd"          =>      "image/x-xwindowdump",
933
  ".css"          =>      "text/css",
934
  ".html"         =>      "text/html",
935
  ".htm"          =>      "text/html",
936
  ".js"           =>      "text/javascript",
937
  ".asc"          =>      "text/plain",
938
  ".c"            =>      "text/plain",
939
  ".conf"         =>      "text/plain",
940
  ".text"         =>      "text/plain",
941
  ".txt"          =>      "text/plain",
942
  ".dtd"          =>      "text/xml",
943
  ".xml"          =>      "text/xml",
944
  ".mpeg"         =>      "video/mpeg",
945
  ".mpg"          =>      "video/mpeg",
946
  ".mov"          =>      "video/quicktime",
947
  ".qt"           =>      "video/quicktime",
948
  ".avi"          =>      "video/x-msvideo",
949
  ".asf"          =>      "video/x-ms-asf",
950
  ".asx"          =>      "video/x-ms-asf",
951
  ".wmv"          =>      "video/x-ms-wmv",
952
  ".bz2"          =>      "application/x-bzip",
953
  ".tbz"          =>      "application/x-bzip-compressed-tar",
954
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
955
 )
956

    
957
# Use the "Content-Type" extended attribute to obtain mime type if possible
958
#mimetypes.use-xattr        = "enable"
959

    
960
#### accesslog module
961
#accesslog.filename          = "/dev/null"
962

    
963
## deny access the file-extensions
964
#
965
# ~    is for backupfiles from vi, emacs, joe, ...
966
# .inc is often used for code includes which should in general not be part
967
#      of the document-root
968
url.access-deny             = ( "~", ".inc" )
969

    
970

    
971
######### Options that are good to be but not neccesary to be changed #######
972

    
973
## bind to port (default: 80)
974
server.port                = {$lighty_port}
975

    
976
## error-handler for status 404
977
#server.error-handler-404   = "/error-handler.html"
978
#server.error-handler-404   = "/error-handler.php"
979

    
980
## to help the rc.scripts
981
server.pid-file            = "/var/run/{$pid_file}"
982

    
983
## virtual directory listings
984
server.dir-listing         = "disable"
985

    
986
## enable debugging
987
debug.log-request-header   = "disable"
988
debug.log-response-header  = "disable"
989
debug.log-request-handling = "disable"
990
debug.log-file-not-found   = "disable"
991

    
992
# gzip compression
993
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
994
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
995

    
996
{$server_upload_dirs}
997

    
998
{$server_max_request_size}
999

    
1000
{$fastcgi_config}
1001

    
1002
{$cgi_config}
1003

    
1004
{$captive_portal_mod_evasive}
1005

    
1006
expire.url = (
1007
				"" => "access 50 hours",	
1008
        )
1009

    
1010
EOD;
1011

    
1012
	$cert = str_replace("\r", "", $cert);
1013
	$key = str_replace("\r", "", $key);
1014
	$ca = str_replace("\r", "", $ca);
1015

    
1016
	$cert = str_replace("\n\n", "\n", $cert);
1017
	$key = str_replace("\n\n", "\n", $key);
1018
	$ca = str_replace("\n\n", "\n", $ca);
1019

    
1020
	if($cert <> "" and $key <> "") {
1021
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1022
		if (!$fd) {
1023
			printf("Error: cannot open cert.pem in system_webgui_start().\n");
1024
			return 1;
1025
		}
1026
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1027
		fwrite($fd, $cert);
1028
		fwrite($fd, "\n");
1029
		fwrite($fd, $key);
1030
		fclose($fd);
1031
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
1032
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1033
			if (!$fd) {
1034
				printf("Error: cannot open ca.pem in system_webgui_start().\n");
1035
				return 1;
1036
			}
1037
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1038
			fwrite($fd, $ca);
1039
			fclose($fd);
1040
		}
1041
		$lighty_config .= "\n";
1042
		$lighty_config .= "## ssl configuration\n";
1043
		$lighty_config .= "ssl.engine = \"enable\"\n";
1044
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1045

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

    
1050
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1051
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1052
	}
1053

    
1054
	// Add HTTP to HTTPS redirect	
1055
	if ($captive_portal == false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1056
		if($lighty_port != "443") 
1057
			$redirectport = ":{$lighty_port}";
1058
		$lighty_config .= <<<EOD
1059
\$SERVER["socket"] == ":80" {
1060
	\$HTTP["host"] =~ "(.*)" {
1061
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1062
	}
1063
}
1064
EOD;
1065
	}
1066

    
1067
	$fd = fopen("{$filename}", "w");
1068
	if (!$fd) {
1069
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
1070
		return 1;
1071
	}
1072
	fwrite($fd, $lighty_config);
1073
	fclose($fd);
1074

    
1075
	return 0;
1076

    
1077
}
1078

    
1079
function system_timezone_configure() {
1080
	global $config, $g;
1081
	if(isset($config['system']['developerspew'])) {
1082
		$mt = microtime();
1083
		echo "system_timezone_configure() being called $mt\n";
1084
	}
1085

    
1086
	$syscfg = $config['system'];
1087

    
1088
	if ($g['booting'])
1089
		echo "Setting timezone...";
1090

    
1091
	/* extract appropriate timezone file */
1092
	$timezone = $syscfg['timezone'];
1093
	if (!$timezone)
1094
		$timezone = "Etc/UTC";
1095

    
1096
	conf_mount_rw();
1097

    
1098
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1099
		escapeshellarg($timezone) . " > /etc/localtime");
1100

    
1101
	mwexec("sync");
1102
	conf_mount_ro();
1103

    
1104
	if ($g['booting'])
1105
		echo "done.\n";
1106
}
1107

    
1108
function system_ntp_configure() {
1109
	global $config, $g;
1110

    
1111
	$ntpcfg = "# \n";
1112
	$ntpcfg .= "# pfSense OpenNTPD configuration file \n";
1113
	$ntpcfg .= "# \n\n";
1114

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

    
1119
	/* Setup listener(s) if the user has configured one */
1120
        if ($config['installedpackages']['openntpd']) {
1121
    		/* server config is in coregui1 */
1122
		$xmlsettings = $config['installedpackages']['openntpd']['config'][0];
1123
		if ($xmlsettings['enable'] == 'on') {
1124
			$ifaces = explode(',', $xmlsettings['interface']);
1125
			$ips = array();
1126
			foreach ($ifaces as $if) {
1127
				if (is_ipaddr($if)) {
1128
					$ips[] = $if;
1129
				} else {
1130
					$if = get_real_interface($if);
1131
					if (does_interface_exist($if))
1132
						$ips[] = find_interface_ip($if);
1133
				}
1134
			}
1135
			foreach ($ips as $ip) {
1136
				if (is_ipaddr($ip))
1137
					$ntpcfg .= "listen on $ip\n";
1138
			}
1139
		}
1140
	}
1141
	$ntpcfg .= "\n";
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
	fwrite($fd, $ntpcfg);
1150

    
1151
	/* slurp! */
1152
	fclose($fd);
1153

    
1154
	/* if openntpd is running, kill it */
1155
	while(is_process_running("ntpd")) {
1156
		killbyname("ntpd");
1157
	}
1158

    
1159
	/* if /var/empty does not exist, create it */
1160
	if(!is_dir("/var/empty"))
1161
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1162

    
1163
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1164
	exec("/usr/local/sbin/ntpd -s -f {$g['varetc_path']}/ntpd.conf");
1165
	
1166
	// Note that we are starting up
1167
	log_error("OpenNTPD is starting up.");
1168

    
1169
}
1170

    
1171
function sync_system_time() {
1172
	global $config, $g;
1173

    
1174
	if ($g['booting'])
1175
		echo "Syncing system time before startup...";
1176

    
1177
	/* foreach through servers and write out to ntpd.conf */
1178
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1179
		mwexec("/usr/sbin/ntpdate -s $ts");
1180
	}
1181
	
1182
	if ($g['booting'])
1183
		echo "done.\n";
1184
	
1185
}
1186

    
1187
function system_halt() {
1188
	global $g;
1189

    
1190
	system_reboot_cleanup();
1191

    
1192
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1193
}
1194

    
1195
function system_reboot() {
1196
	global $g;
1197

    
1198
	system_reboot_cleanup();
1199

    
1200
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1201
}
1202

    
1203
function system_reboot_sync() {
1204
	global $g;
1205

    
1206
	system_reboot_cleanup();
1207

    
1208
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1209
}
1210

    
1211
function system_reboot_cleanup() {
1212
	mwexec("/usr/local/bin/beep.sh stop");
1213
	require_once("captiveportal.inc");
1214
	captiveportal_radius_stop_all();
1215
	require_once("voucher.inc");
1216
	voucher_save_db_to_config();
1217
	mwexec("/etc/rc.stop_packages");
1218
}
1219

    
1220
function system_do_shell_commands($early = 0) {
1221
	global $config, $g;
1222
	if(isset($config['system']['developerspew'])) {
1223
		$mt = microtime();
1224
		echo "system_do_shell_commands() being called $mt\n";
1225
	}
1226

    
1227
	if ($early)
1228
		$cmdn = "earlyshellcmd";
1229
	else
1230
		$cmdn = "shellcmd";
1231

    
1232
	if (is_array($config['system'][$cmdn])) {
1233

    
1234
		/* *cmd is an array, loop through */
1235
		foreach ($config['system'][$cmdn] as $cmd) {
1236
			exec($cmd);
1237
		}
1238

    
1239
	} elseif($config['system'][$cmdn] <> "") {
1240

    
1241
		/* execute single item */
1242
		exec($config['system'][$cmdn]);
1243

    
1244
	}
1245
}
1246

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

    
1254
	if (isset($config['system']['disableconsolemenu'])) {
1255
		touch("{$g['varetc_path']}/disableconsole");
1256
	} else {
1257
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1258
	}
1259
}
1260

    
1261
function system_dmesg_save() {
1262
	global $g;
1263
	if(isset($config['system']['developerspew'])) {
1264
		$mt = microtime();
1265
		echo "system_dmesg_save() being called $mt\n";
1266
	}
1267

    
1268
	$dmesg = "";
1269
	exec("/sbin/dmesg", $dmesg);
1270

    
1271
	/* find last copyright line (output from previous boots may be present) */
1272
	$lastcpline = 0;
1273

    
1274
	for ($i = 0; $i < count($dmesg); $i++) {
1275
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1276
			$lastcpline = $i;
1277
	}
1278

    
1279
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1280
	if (!$fd) {
1281
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1282
		return 1;
1283
	}
1284

    
1285
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1286
		fwrite($fd, $dmesg[$i] . "\n");
1287

    
1288
	fclose($fd);
1289

    
1290
	return 0;
1291
}
1292

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

    
1300
	if (isset($config['system']['harddiskstandby'])) {
1301
		if ($g['booting']) {
1302
			echo 'Setting hard disk standby... ';
1303
		}
1304

    
1305
		$standby = $config['system']['harddiskstandby'];
1306
		// Check for a numeric value
1307
		if (is_numeric($standby)) {
1308
			// Sync the disk(s)
1309
			pfSense_sync();
1310
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1311
				// Reinitialize ATA-drives
1312
				mwexec('/usr/local/sbin/atareinit');
1313
				if ($g['booting']) {
1314
					echo "done.\n";
1315
				}
1316
			} else if ($g['booting']) {
1317
				echo "failed!\n";
1318
			}
1319
		} else if ($g['booting']) {
1320
			echo "failed!\n";
1321
		}
1322
	}
1323
}
1324

    
1325
function system_setup_sysctl() {
1326
	global $config;
1327
	if(isset($config['system']['developerspew'])) {
1328
		$mt = microtime();
1329
		echo "system_setup_sysctl() being called $mt\n";
1330
	}
1331

    
1332
	activate_sysctls();	
1333

    
1334
	if (isset($config['system']['sharednet'])) {
1335
		system_disable_arp_wrong_if();
1336
	}
1337
}
1338

    
1339
function system_disable_arp_wrong_if() {
1340
	global $config;
1341
	if(isset($config['system']['developerspew'])) {
1342
		$mt = microtime();
1343
		echo "system_disable_arp_wrong_if() being called $mt\n";
1344
	}
1345
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1346
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1347
}
1348

    
1349
function system_enable_arp_wrong_if() {
1350
	global $config;
1351
	if(isset($config['system']['developerspew'])) {
1352
		$mt = microtime();
1353
		echo "system_enable_arp_wrong_if() being called $mt\n";
1354
	}
1355
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1356
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1357
}
1358

    
1359
function enable_watchdog() {
1360
	global $config;
1361
	return;
1362
	$install_watchdog = false;
1363
	$supported_watchdogs = array("Geode");
1364
	$file = file_get_contents("/var/log/dmesg.boot");
1365
	foreach($supported_watchdogs as $sd) {
1366
		if(stristr($file, "Geode")) {
1367
			$install_watchdog = true;
1368
		}
1369
	}
1370
	if($install_watchdog == true) {
1371
		if(is_process_running("watchdogd"))
1372
			mwexec("/usr/bin/killall watchdogd", true);
1373
		exec("/usr/sbin/watchdogd");
1374
	}
1375
}
1376

    
1377
function system_check_reset_button() {
1378
	global $g;
1379
	if($g['platform'] != "nanobsd")
1380
		return 0;
1381

    
1382
	$specplatform = system_identify_specific_platform();
1383

    
1384
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1385
		return 0;
1386

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

    
1389
	if ($retval == 99) {
1390
		/* user has pressed reset button for 2 seconds - 
1391
		   reset to factory defaults */
1392
		echo <<<EOD
1393

    
1394
***********************************************************************
1395
* Reset button pressed - resetting configuration to factory defaults. *
1396
* The system will reboot after this completes.                        *
1397
***********************************************************************
1398

    
1399

    
1400
EOD;
1401
		
1402
		reset_factory_defaults();
1403
		system_reboot_sync();
1404
		exit(0);
1405
	}
1406

    
1407
	return 0;
1408
}
1409

    
1410
/* attempt to identify the specific platform (for embedded systems)
1411
   Returns an array with two elements:
1412
	name => platform string (e.g. 'wrap', 'alix' etc.)
1413
	descr => human-readable description (e.g. "PC Engines WRAP")
1414
*/
1415
function system_identify_specific_platform() {
1416
	global $g;
1417
	
1418
	if ($g['platform'] == 'generic-pc')
1419
		return array('name' => 'generic-pc', 'descr' => "Generic PC");
1420
	
1421
	if ($g['platform'] == 'generic-pc-cdrom')
1422
		return array('name' => 'generic-pc-cdrom', 'descr' => "Generic PC (CD-ROM)");
1423
	
1424
	/* the rest of the code only deals with 'embedded' platforms */
1425
	if ($g['platform'] != 'nanobsd')
1426
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1427
	
1428
	$dmesg = system_get_dmesg_boot();
1429
	
1430
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1431
		return array('name' => 'wrap', 'descr' => 'PC Engines WRAP');
1432
	
1433
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1434
		return array('name' => 'alix', 'descr' => 'PC Engines ALIX');
1435

    
1436
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1437
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1438
	
1439
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1440
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1441
		
1442
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1443
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1444
	
1445
	/* unknown embedded platform */
1446
	return array('name' => 'embedded', 'descr' => 'embedded (unknown)');
1447
}
1448

    
1449
function system_get_dmesg_boot() {
1450
	global $g;
1451
		
1452
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1453
}
1454

    
1455
function get_possible_listen_ips() {
1456
	$interfaces = get_configured_interface_with_descr();
1457
	$carplist = get_configured_carp_interface_list();
1458
	$listenips = array();
1459
	foreach ($carplist as $cif => $carpip)
1460
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1461
	$aliaslist = get_configured_ip_aliases_list();
1462
	foreach ($aliaslist as $aliasip => $aliasif)
1463
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1464
	foreach ($interfaces as $iface => $ifacename) {
1465
		$tmp["name"]  = $ifacename;
1466
		$tmp["value"] = $iface;
1467
		$listenips[] = $tmp;
1468
	}
1469
	$tmp["name"]  = "Localhost";
1470
	$tmp["value"] = "lo0";
1471
	$listenips[] = $tmp;
1472
	return $listenips;
1473
}
1474
?>
(48-48/62)