Project

General

Profile

Download (43.6 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/bin/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
	$static_routes = get_staticroutes();
380
	if (count($static_routes)) {
381
		$gateways_arr = return_gateways_array();
382

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

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

    
405
	return 0;
406
}
407

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
601
	return $retval;
602
}
603

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

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

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

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

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

    
627
	return $res;
628
}
629

    
630

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

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

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

    
640
	sleep(1);
641

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

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

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

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

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

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

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

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

    
712
	return $res;
713
}
714

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

    
729
	global $config, $g;
730

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

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

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

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

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

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

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

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

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

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

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

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

    
847
EOD;
848
	}
849

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

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

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

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

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

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

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

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

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

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

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

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

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

    
971

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

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

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

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

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

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

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

    
997
{$server_upload_dirs}
998

    
999
{$server_max_request_size}
1000

    
1001
{$fastcgi_config}
1002

    
1003
{$cgi_config}
1004

    
1005
{$captive_portal_mod_evasive}
1006

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

    
1011
EOD;
1012

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

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

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

    
1047
		// Harden SSL a bit for PCI conformance testing
1048
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
1049
		$lighty_config .= "ssl.cipher-list = \"DHE-RSA-CAMELLIA256-SHA:DHE-DSS-CAMELLIA256-SHA:CAMELLIA256-SHA:DHE-DSS-AES256-SHA:AES256-SHA:DHE-RSA-CAMELLIA128-SHA:DHE-DSS-CAMELLIA128-SHA:CAMELLIA128-SHA:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA:AES128-SHA:RC4-SHA:RC4-MD5:!aNULL:!eNULL:!3DES:@STRENGTH\"\n";
1050

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

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

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

    
1076
	return 0;
1077

    
1078
}
1079

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

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

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

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

    
1097
	conf_mount_rw();
1098

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

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

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

    
1109
function system_ntp_configure($start_ntpd=true) {
1110
	global $config, $g;
1111
	$driftfile = "/var/db/ntpd.drift";
1112

    
1113
	$ntpcfg = "# \n";
1114
	$ntpcfg .= "# pfSense ntp configuration file \n";
1115
	$ntpcfg .= "# \n\n";
1116
	$ntpcfg .= "tinker panic 0 \n";
1117

    
1118
	/* foreach through servers and write out to ntpd.conf */
1119
	foreach (explode(' ', $config['system']['timeservers']) as $ts)
1120
		$ntpcfg .= "server {$ts} iburst maxpoll 9\n";
1121

    
1122
	$ntpcfg .= "driftfile {$driftfile}\n";
1123

    
1124
	if (empty($config['ntpd']['interface']))
1125
		if (!empty($config['installedpackages']['openntpd']['config'][0]['interface']))
1126
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1127
		else
1128
			$interfaces = array();
1129
	else
1130
		$interfaces = explode(",", $config['ntpd']['interface']);
1131

    
1132
	if (is_array($interfaces) && count($interfaces)) {
1133
		$ntpcfg .= "interface ignore all\n";
1134
		foreach ($interfaces as $interface) {
1135
			if (!is_ipaddr($interface)) {
1136
				$interface = get_real_interface($interface);
1137
			}
1138
			$ntpcfg .= "interface listen {$interface}\n";
1139
		}
1140
	}
1141

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

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

    
1153
	/* At bootup we just want to write out the config. */
1154
	if (!$start_ntpd)
1155
		return;
1156

    
1157
	/* if ntpd is running, kill it */
1158
	while(is_process_running("ntpd")) {
1159
		killbyname("ntpd");
1160
	}
1161

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

    
1166
	/* start ntpd, allow a large initial skew, and use /var/etc/ntpd.conf - run through tcsh to work around a PHP shell exec bug. */
1167
	exec("echo /usr/local/bin/ntpd -g -c {$g['varetc_path']}/ntpd.conf | tcsh");
1168
	
1169
	// Note that we are starting up
1170
	log_error("NTPD is starting up.");
1171
	return;
1172
}
1173

    
1174
function sync_system_time() {
1175
	global $config, $g;
1176

    
1177
	if ($g['booting'])
1178
		echo "Syncing system time before startup...";
1179

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

    
1190
function system_halt() {
1191
	global $g;
1192

    
1193
	system_reboot_cleanup();
1194

    
1195
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1196
}
1197

    
1198
function system_reboot() {
1199
	global $g;
1200

    
1201
	system_reboot_cleanup();
1202

    
1203
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1204
}
1205

    
1206
function system_reboot_sync() {
1207
	global $g;
1208

    
1209
	system_reboot_cleanup();
1210

    
1211
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1212
}
1213

    
1214
function system_reboot_cleanup() {
1215
	mwexec("/usr/local/bin/beep.sh stop");
1216
	require_once("captiveportal.inc");
1217
	captiveportal_radius_stop_all();
1218
	require_once("voucher.inc");
1219
	voucher_save_db_to_config();
1220
	require_once("pkg-utils.inc");
1221
	stop_packages();
1222
}
1223

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

    
1231
	if ($early)
1232
		$cmdn = "earlyshellcmd";
1233
	else
1234
		$cmdn = "shellcmd";
1235

    
1236
	if (is_array($config['system'][$cmdn])) {
1237

    
1238
		/* *cmd is an array, loop through */
1239
		foreach ($config['system'][$cmdn] as $cmd) {
1240
			exec($cmd);
1241
		}
1242

    
1243
	} elseif($config['system'][$cmdn] <> "") {
1244

    
1245
		/* execute single item */
1246
		exec($config['system'][$cmdn]);
1247

    
1248
	}
1249
}
1250

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

    
1258
	if (isset($config['system']['disableconsolemenu'])) {
1259
		touch("{$g['varetc_path']}/disableconsole");
1260
	} else {
1261
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1262
	}
1263
}
1264

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

    
1272
	$dmesg = "";
1273
	exec("/sbin/dmesg", $dmesg);
1274

    
1275
	/* find last copyright line (output from previous boots may be present) */
1276
	$lastcpline = 0;
1277

    
1278
	for ($i = 0; $i < count($dmesg); $i++) {
1279
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1280
			$lastcpline = $i;
1281
	}
1282

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

    
1289
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1290
		fwrite($fd, $dmesg[$i] . "\n");
1291

    
1292
	fclose($fd);
1293

    
1294
	return 0;
1295
}
1296

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

    
1304
	if (isset($config['system']['harddiskstandby'])) {
1305
		if ($g['booting']) {
1306
			echo 'Setting hard disk standby... ';
1307
		}
1308

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

    
1329
function system_setup_sysctl() {
1330
	global $config;
1331
	if(isset($config['system']['developerspew'])) {
1332
		$mt = microtime();
1333
		echo "system_setup_sysctl() being called $mt\n";
1334
	}
1335

    
1336
	activate_sysctls();	
1337

    
1338
	if (isset($config['system']['sharednet'])) {
1339
		system_disable_arp_wrong_if();
1340
	}
1341
}
1342

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

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

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

    
1381
function system_check_reset_button() {
1382
	global $g;
1383
	if($g['platform'] != "nanobsd")
1384
		return 0;
1385

    
1386
	$specplatform = system_identify_specific_platform();
1387

    
1388
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1389
		return 0;
1390

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

    
1393
	if ($retval == 99) {
1394
		/* user has pressed reset button for 2 seconds - 
1395
		   reset to factory defaults */
1396
		echo <<<EOD
1397

    
1398
***********************************************************************
1399
* Reset button pressed - resetting configuration to factory defaults. *
1400
* The system will reboot after this completes.                        *
1401
***********************************************************************
1402

    
1403

    
1404
EOD;
1405
		
1406
		reset_factory_defaults();
1407
		system_reboot_sync();
1408
		exit(0);
1409
	}
1410

    
1411
	return 0;
1412
}
1413

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

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

    
1453
function system_get_dmesg_boot() {
1454
	global $g;
1455
		
1456
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1457
}
1458

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