Project

General

Profile

Download (42 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
	if ($g['booting']) {
700
		if ($res == 0)
701
			echo "done.\n";
702
		else
703
			echo "failed!\n";
704
	}
705

    
706
	return $res;
707
}
708

    
709
function system_generate_lighty_config($filename,
710
	$cert,
711
	$key,
712
	$ca,
713
	$pid_file,
714
	$port = 80,
715
	$document_root = "/usr/local/www/",
716
	$cert_location = "cert.pem",
717
	$ca_location = "ca.pem",
718
	$max_procs = 1,
719
	$captive_portal = false) {
720

    
721
	global $config, $g;
722

    
723
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
724
		mkdir("{$g['tmp_path']}/lighttpdcompress");
725

    
726
	if(isset($config['system']['developerspew'])) {
727
		$mt = microtime();
728
		echo "system_generate_lighty_config() being called $mt\n";
729
	}
730

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

    
757
	$memory = get_memory();
758
	$avail = $memory[0];
759

    
760
	// Ramp up captive portal max procs
761
	//  Work relative to the default of 2, for values that would be >2.
762
	if($captive_portal == true)  {
763
		if ($avail <= 135)
764
			$max_procs = 1;
765
		else if ($avail > 135 and $avail < 256) {
766
			$max_procs += 1;
767
		} else if ($avail > 255 and $avail < 384) {
768
			$max_procs += 2;
769
		} else if ($avail > 383) {
770
			$max_procs += 3;
771
		}
772
	} else if ($avail > 135 && $max_procs < 2)
773
		$max_procs = 2;
774

    
775
	if ($captive_portal == true)  {	
776
		if ($max_procs > 1)
777
			$max_php_children = intval($max_procs/2);
778
		else
779
			$max_php_children = 1;
780

    
781
		$bin_environment =  <<<EOC
782
			"bin-environment" => (
783
				"PHP_FCGI_CHILDREN" => "{$max_php_children}",
784
				"PHP_FCGI_MAX_REQUESTS" => "500"
785
			),
786
EOC;
787

    
788
	} else
789
		$bin_environment =  <<<EOC
790
			"bin-environment" => (
791
				"PHP_FCGI_CHILDREN" => "1",
792
				"PHP_FCGI_MAX_REQUESTS" => "500"
793
			),
794
EOC;
795

    
796
	$fastcgi_config = <<<EOD
797
#### fastcgi module
798
## read fastcgi.txt for more info
799
fastcgi.server = ( ".php" =>
800
	( "localhost" =>
801
		(
802
			"socket" => "{$g['tmp_path']}/php-fastcgi.socket",
803
			"max-procs" => {$max_procs},
804
{$bin_environment}
805
			"bin-path" => "/usr/local/bin/php"
806
		)
807
	)
808
)
809

    
810
EOD;
811

    
812
	$lighty_config = "";
813
	$lighty_config .= <<<EOD
814
#
815
# lighttpd configuration file
816
#
817
# use a it as base for lighttpd 1.0.0 and above
818
#
819
############ Options you really have to take care of ####################
820

    
821
## FreeBSD!
822
server.event-handler	= "freebsd-kqueue"
823
server.network-backend 	= "writev"
824

    
825
## modules to load
826
server.modules              =   ( "mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect"
827
			{$captiveportal},"mod_fastcgi"
828
		)
829

    
830
server.max-keep-alive-requests = 15
831
server.max-keep-alive-idle = 30
832

    
833
## a static document-root, for virtual-hosting take look at the
834
## server.virtual-* options
835
server.document-root        = "{$document_root}"
836
{$captive_portal_rewrite}
837

    
838
# Maximum idle time with nothing being written (php downloading)
839
server.max-write-idle = 999
840

    
841
## where to send error-messages to
842
server.errorlog-use-syslog="enable"
843

    
844
# files to check for if .../ is requested
845
server.indexfiles           = ( "index.php", "index.html",
846
                                "index.htm", "default.htm" )
847

    
848
# mimetype mapping
849
mimetype.assign             = (
850
  ".pdf"          =>      "application/pdf",
851
  ".sig"          =>      "application/pgp-signature",
852
  ".spl"          =>      "application/futuresplash",
853
  ".class"        =>      "application/octet-stream",
854
  ".ps"           =>      "application/postscript",
855
  ".torrent"      =>      "application/x-bittorrent",
856
  ".dvi"          =>      "application/x-dvi",
857
  ".gz"           =>      "application/x-gzip",
858
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
859
  ".swf"          =>      "application/x-shockwave-flash",
860
  ".tar.gz"       =>      "application/x-tgz",
861
  ".tgz"          =>      "application/x-tgz",
862
  ".tar"          =>      "application/x-tar",
863
  ".zip"          =>      "application/zip",
864
  ".mp3"          =>      "audio/mpeg",
865
  ".m3u"          =>      "audio/x-mpegurl",
866
  ".wma"          =>      "audio/x-ms-wma",
867
  ".wax"          =>      "audio/x-ms-wax",
868
  ".ogg"          =>      "audio/x-wav",
869
  ".wav"          =>      "audio/x-wav",
870
  ".gif"          =>      "image/gif",
871
  ".jpg"          =>      "image/jpeg",
872
  ".jpeg"         =>      "image/jpeg",
873
  ".png"          =>      "image/png",
874
  ".xbm"          =>      "image/x-xbitmap",
875
  ".xpm"          =>      "image/x-xpixmap",
876
  ".xwd"          =>      "image/x-xwindowdump",
877
  ".css"          =>      "text/css",
878
  ".html"         =>      "text/html",
879
  ".htm"          =>      "text/html",
880
  ".js"           =>      "text/javascript",
881
  ".asc"          =>      "text/plain",
882
  ".c"            =>      "text/plain",
883
  ".conf"         =>      "text/plain",
884
  ".text"         =>      "text/plain",
885
  ".txt"          =>      "text/plain",
886
  ".dtd"          =>      "text/xml",
887
  ".xml"          =>      "text/xml",
888
  ".mpeg"         =>      "video/mpeg",
889
  ".mpg"          =>      "video/mpeg",
890
  ".mov"          =>      "video/quicktime",
891
  ".qt"           =>      "video/quicktime",
892
  ".avi"          =>      "video/x-msvideo",
893
  ".asf"          =>      "video/x-ms-asf",
894
  ".asx"          =>      "video/x-ms-asf",
895
  ".wmv"          =>      "video/x-ms-wmv",
896
  ".bz2"          =>      "application/x-bzip",
897
  ".tbz"          =>      "application/x-bzip-compressed-tar",
898
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
899
 )
900

    
901
# Use the "Content-Type" extended attribute to obtain mime type if possible
902
#mimetypes.use-xattr        = "enable"
903

    
904
## deny access the file-extensions
905
#
906
# ~    is for backupfiles from vi, emacs, joe, ...
907
# .inc is often used for code includes which should in general not be part
908
#      of the document-root
909
url.access-deny             = ( "~", ".inc" )
910

    
911
######### Options that are good to be but not neccesary to be changed #######
912

    
913
## bind to port (default: 80)
914
server.port                = {$lighty_port}
915

    
916
## error-handler for status 404
917
#server.error-handler-404   = "/error-handler.html"
918
#server.error-handler-404   = "/error-handler.php"
919

    
920
## to help the rc.scripts
921
server.pid-file            = "/var/run/{$pid_file}"
922

    
923
## virtual directory listings
924
server.dir-listing         = "disable"
925

    
926
## enable debugging
927
debug.log-request-header   = "disable"
928
debug.log-response-header  = "disable"
929
debug.log-request-handling = "disable"
930
debug.log-file-not-found   = "disable"
931

    
932
# gzip compression
933
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
934
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
935

    
936
{$server_upload_dirs}
937

    
938
{$server_max_request_size}
939

    
940
{$fastcgi_config}
941

    
942
{$captive_portal_mod_evasive}
943

    
944
expire.url = (
945
				"" => "access 50 hours",	
946
        )
947

    
948
EOD;
949

    
950
	$cert = str_replace("\r", "", $cert);
951
	$key = str_replace("\r", "", $key);
952
	$ca = str_replace("\r", "", $ca);
953

    
954
	$cert = str_replace("\n\n", "\n", $cert);
955
	$key = str_replace("\n\n", "\n", $key);
956
	$ca = str_replace("\n\n", "\n", $ca);
957

    
958
	if($cert <> "" and $key <> "") {
959
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
960
		if (!$fd) {
961
			printf("Error: cannot open cert.pem in system_webgui_start().\n");
962
			return 1;
963
		}
964
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
965
		fwrite($fd, $cert);
966
		fwrite($fd, "\n");
967
		fwrite($fd, $key);
968
		fclose($fd);
969
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
970
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
971
			if (!$fd) {
972
				printf("Error: cannot open ca.pem in system_webgui_start().\n");
973
				return 1;
974
			}
975
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
976
			fwrite($fd, $ca);
977
			fclose($fd);
978
		}
979
		$lighty_config .= "\n";
980
		$lighty_config .= "## ssl configuration\n";
981
		$lighty_config .= "ssl.engine = \"enable\"\n";
982
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
983

    
984
		// Harden SSL a bit for PCI conformance testing
985
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
986
		$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";
987

    
988
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
989
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
990
	}
991

    
992
	// Add HTTP to HTTPS redirect	
993
	if ($captive_portal == false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
994
		if($lighty_port != "443") 
995
			$redirectport = ":{$lighty_port}";
996
		$lighty_config .= <<<EOD
997
\$SERVER["socket"] == ":80" {
998
	\$HTTP["host"] =~ "(.*)" {
999
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1000
	}
1001
}
1002
EOD;
1003
	}
1004

    
1005
	$fd = fopen("{$filename}", "w");
1006
	if (!$fd) {
1007
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
1008
		return 1;
1009
	}
1010
	fwrite($fd, $lighty_config);
1011
	fclose($fd);
1012

    
1013
	return 0;
1014

    
1015
}
1016

    
1017
function system_timezone_configure() {
1018
	global $config, $g;
1019
	if(isset($config['system']['developerspew'])) {
1020
		$mt = microtime();
1021
		echo "system_timezone_configure() being called $mt\n";
1022
	}
1023

    
1024
	$syscfg = $config['system'];
1025

    
1026
	if ($g['booting'])
1027
		echo "Setting timezone...";
1028

    
1029
	/* extract appropriate timezone file */
1030
	$timezone = $syscfg['timezone'];
1031
	if (!$timezone)
1032
		$timezone = "Etc/UTC";
1033

    
1034
	conf_mount_rw();
1035

    
1036
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1037
		escapeshellarg($timezone) . " > /etc/localtime");
1038

    
1039
	mwexec("sync");
1040
	conf_mount_ro();
1041

    
1042
	if ($g['booting'])
1043
		echo "done.\n";
1044
}
1045

    
1046
function system_ntp_configure($start_ntpd=true) {
1047
	global $config, $g;
1048
	$driftfile = "/var/db/ntpd.drift";
1049

    
1050
	$ntpcfg = "# \n";
1051
	$ntpcfg .= "# pfSense ntp configuration file \n";
1052
	$ntpcfg .= "# \n\n";
1053
	$ntpcfg .= "tinker panic 0 \n";
1054

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

    
1059
	$ntpcfg .= "driftfile {$driftfile}\n";
1060

    
1061
	if (empty($config['ntpd']['interface']))
1062
		if (!empty($config['installedpackages']['openntpd']['config'][0]['interface']))
1063
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1064
		else
1065
			$interfaces = array();
1066
	else
1067
		$interfaces = explode(",", $config['ntpd']['interface']);
1068

    
1069
	if (is_array($interfaces) && count($interfaces)) {
1070
		$ntpcfg .= "interface ignore all\n";
1071
		foreach ($interfaces as $interface) {
1072
			if (!is_ipaddr($interface)) {
1073
				$interface = get_real_interface($interface);
1074
			}
1075
			$ntpcfg .= "interface listen {$interface}\n";
1076
		}
1077
	}
1078

    
1079
	/* open configuration for wrting or bail */
1080
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1081
	if(!$fd) {
1082
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1083
		return;
1084
	}
1085
	fwrite($fd, $ntpcfg);
1086

    
1087
	/* slurp! */
1088
	fclose($fd);
1089

    
1090
	/* At bootup we just want to write out the config. */
1091
	if (!$start_ntpd)
1092
		return;
1093

    
1094
	/* if ntpd is running, kill it */
1095
	while(is_process_running("ntpd")) {
1096
		killbyname("ntpd");
1097
	}
1098

    
1099
	/* if /var/empty does not exist, create it */
1100
	if(!is_dir("/var/empty"))
1101
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1102

    
1103
	/* start ntpd, allow a large initial skew, and use /var/etc/ntpd.conf - run through tcsh to work around a PHP shell exec bug. */
1104
	exec("echo /usr/local/bin/ntpd -g -c {$g['varetc_path']}/ntpd.conf | tcsh");
1105
	
1106
	// Note that we are starting up
1107
	log_error("NTPD is starting up.");
1108
	return;
1109
}
1110

    
1111
function sync_system_time() {
1112
	global $config, $g;
1113

    
1114
	if ($g['booting'])
1115
		echo "Syncing system time before startup...";
1116

    
1117
	/* foreach through servers and write out to ntpd.conf */
1118
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1119
		mwexec("/usr/sbin/ntpdate -s $ts");
1120
	}
1121
	
1122
	if ($g['booting'])
1123
		echo "done.\n";
1124
	
1125
}
1126

    
1127
function system_halt() {
1128
	global $g;
1129

    
1130
	system_reboot_cleanup();
1131

    
1132
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1133
}
1134

    
1135
function system_reboot() {
1136
	global $g;
1137

    
1138
	system_reboot_cleanup();
1139

    
1140
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1141
}
1142

    
1143
function system_reboot_sync() {
1144
	global $g;
1145

    
1146
	system_reboot_cleanup();
1147

    
1148
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1149
}
1150

    
1151
function system_reboot_cleanup() {
1152
	mwexec("/usr/local/bin/beep.sh stop");
1153
	require_once("captiveportal.inc");
1154
	captiveportal_radius_stop_all();
1155
	require_once("voucher.inc");
1156
	voucher_save_db_to_config();
1157
	require_once("pkg-utils.inc");
1158
	stop_packages();
1159
}
1160

    
1161
function system_do_shell_commands($early = 0) {
1162
	global $config, $g;
1163
	if(isset($config['system']['developerspew'])) {
1164
		$mt = microtime();
1165
		echo "system_do_shell_commands() being called $mt\n";
1166
	}
1167

    
1168
	if ($early)
1169
		$cmdn = "earlyshellcmd";
1170
	else
1171
		$cmdn = "shellcmd";
1172

    
1173
	if (is_array($config['system'][$cmdn])) {
1174

    
1175
		/* *cmd is an array, loop through */
1176
		foreach ($config['system'][$cmdn] as $cmd) {
1177
			exec($cmd);
1178
		}
1179

    
1180
	} elseif($config['system'][$cmdn] <> "") {
1181

    
1182
		/* execute single item */
1183
		exec($config['system'][$cmdn]);
1184

    
1185
	}
1186
}
1187

    
1188
function system_console_configure() {
1189
	global $config, $g;
1190
	if(isset($config['system']['developerspew'])) {
1191
		$mt = microtime();
1192
		echo "system_console_configure() being called $mt\n";
1193
	}
1194

    
1195
	if (isset($config['system']['disableconsolemenu'])) {
1196
		touch("{$g['varetc_path']}/disableconsole");
1197
	} else {
1198
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1199
	}
1200
}
1201

    
1202
function system_dmesg_save() {
1203
	global $g;
1204
	if(isset($config['system']['developerspew'])) {
1205
		$mt = microtime();
1206
		echo "system_dmesg_save() being called $mt\n";
1207
	}
1208

    
1209
	$dmesg = "";
1210
	exec("/sbin/dmesg", $dmesg);
1211

    
1212
	/* find last copyright line (output from previous boots may be present) */
1213
	$lastcpline = 0;
1214

    
1215
	for ($i = 0; $i < count($dmesg); $i++) {
1216
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1217
			$lastcpline = $i;
1218
	}
1219

    
1220
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1221
	if (!$fd) {
1222
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1223
		return 1;
1224
	}
1225

    
1226
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1227
		fwrite($fd, $dmesg[$i] . "\n");
1228

    
1229
	fclose($fd);
1230

    
1231
	return 0;
1232
}
1233

    
1234
function system_set_harddisk_standby() {
1235
	global $g, $config;
1236
	if(isset($config['system']['developerspew'])) {
1237
		$mt = microtime();
1238
		echo "system_set_harddisk_standby() being called $mt\n";
1239
	}
1240

    
1241
	if (isset($config['system']['harddiskstandby'])) {
1242
		if ($g['booting']) {
1243
			echo 'Setting hard disk standby... ';
1244
		}
1245

    
1246
		$standby = $config['system']['harddiskstandby'];
1247
		// Check for a numeric value
1248
		if (is_numeric($standby)) {
1249
			// Sync the disk(s)
1250
			pfSense_sync();
1251
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1252
				// Reinitialize ATA-drives
1253
				mwexec('/usr/local/sbin/atareinit');
1254
				if ($g['booting']) {
1255
					echo "done.\n";
1256
				}
1257
			} else if ($g['booting']) {
1258
				echo "failed!\n";
1259
			}
1260
		} else if ($g['booting']) {
1261
			echo "failed!\n";
1262
		}
1263
	}
1264
}
1265

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

    
1273
	activate_sysctls();	
1274

    
1275
	if (isset($config['system']['sharednet'])) {
1276
		system_disable_arp_wrong_if();
1277
	}
1278
}
1279

    
1280
function system_disable_arp_wrong_if() {
1281
	global $config;
1282
	if(isset($config['system']['developerspew'])) {
1283
		$mt = microtime();
1284
		echo "system_disable_arp_wrong_if() being called $mt\n";
1285
	}
1286
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1287
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1288
}
1289

    
1290
function system_enable_arp_wrong_if() {
1291
	global $config;
1292
	if(isset($config['system']['developerspew'])) {
1293
		$mt = microtime();
1294
		echo "system_enable_arp_wrong_if() being called $mt\n";
1295
	}
1296
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1297
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1298
}
1299

    
1300
function enable_watchdog() {
1301
	global $config;
1302
	return;
1303
	$install_watchdog = false;
1304
	$supported_watchdogs = array("Geode");
1305
	$file = file_get_contents("/var/log/dmesg.boot");
1306
	foreach($supported_watchdogs as $sd) {
1307
		if(stristr($file, "Geode")) {
1308
			$install_watchdog = true;
1309
		}
1310
	}
1311
	if($install_watchdog == true) {
1312
		if(is_process_running("watchdogd"))
1313
			mwexec("/usr/bin/killall watchdogd", true);
1314
		exec("/usr/sbin/watchdogd");
1315
	}
1316
}
1317

    
1318
function system_check_reset_button() {
1319
	global $g;
1320
	if($g['platform'] != "nanobsd")
1321
		return 0;
1322

    
1323
	$specplatform = system_identify_specific_platform();
1324

    
1325
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1326
		return 0;
1327

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

    
1330
	if ($retval == 99) {
1331
		/* user has pressed reset button for 2 seconds - 
1332
		   reset to factory defaults */
1333
		echo <<<EOD
1334

    
1335
***********************************************************************
1336
* Reset button pressed - resetting configuration to factory defaults. *
1337
* The system will reboot after this completes.                        *
1338
***********************************************************************
1339

    
1340

    
1341
EOD;
1342
		
1343
		reset_factory_defaults();
1344
		system_reboot_sync();
1345
		exit(0);
1346
	}
1347

    
1348
	return 0;
1349
}
1350

    
1351
/* attempt to identify the specific platform (for embedded systems)
1352
   Returns an array with two elements:
1353
	name => platform string (e.g. 'wrap', 'alix' etc.)
1354
	descr => human-readable description (e.g. "PC Engines WRAP")
1355
*/
1356
function system_identify_specific_platform() {
1357
	global $g;
1358
	
1359
	if ($g['platform'] == 'generic-pc')
1360
		return array('name' => 'generic-pc', 'descr' => "Generic PC");
1361
	
1362
	if ($g['platform'] == 'generic-pc-cdrom')
1363
		return array('name' => 'generic-pc-cdrom', 'descr' => "Generic PC (CD-ROM)");
1364
	
1365
	/* the rest of the code only deals with 'embedded' platforms */
1366
	if ($g['platform'] != 'nanobsd')
1367
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1368
	
1369
	$dmesg = system_get_dmesg_boot();
1370
	
1371
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1372
		return array('name' => 'wrap', 'descr' => 'PC Engines WRAP');
1373
	
1374
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1375
		return array('name' => 'alix', 'descr' => 'PC Engines ALIX');
1376

    
1377
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1378
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1379
	
1380
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1381
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1382
		
1383
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1384
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1385
	
1386
	/* unknown embedded platform */
1387
	return array('name' => 'embedded', 'descr' => 'embedded (unknown)');
1388
}
1389

    
1390
function system_get_dmesg_boot() {
1391
	global $g;
1392
		
1393
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1394
}
1395

    
1396
function get_possible_listen_ips() {
1397
	$interfaces = get_configured_interface_with_descr();
1398
	$carplist = get_configured_carp_interface_list();
1399
	$listenips = array();
1400
	foreach ($carplist as $cif => $carpip)
1401
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1402
	$aliaslist = get_configured_ip_aliases_list();
1403
	foreach ($aliaslist as $aliasip => $aliasif)
1404
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1405
	foreach ($interfaces as $iface => $ifacename) {
1406
		$tmp["name"]  = $ifacename;
1407
		$tmp["value"] = $iface;
1408
		$listenips[] = $tmp;
1409
	}
1410
	$tmp["name"]  = "Localhost";
1411
	$tmp["value"] = "lo0";
1412
	$listenips[] = $tmp;
1413
	return $listenips;
1414
}
1415
?>
(47-47/61)