Project

General

Profile

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

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

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

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

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

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

    
32
/*
33
	pfSense_BUILDER_BINARIES:	/usr/sbin/powerd	/usr/bin/killall	/sbin/sysctl	/sbin/route
34
	pfSense_BUILDER_BINARIES:	/bin/hostname	/bin/ls	/usr/sbin/syslogd	
35
	pfSense_BUILDER_BINARIES:	/usr/sbin/pccardd	/usr/local/sbin/lighttpd	/bin/chmod 	/bin/mkdir
36
	pfSense_BUILDER_BINARIES:	/usr/bin/tar		/usr/local/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 -s -c -c -l /var/dhcpd/var/run/log -f {$g['varetc_path']}/syslog.conf");
590
		else {
591
			$retval = mwexec_bg("/usr/sbin/syslogd -s -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
		$cgi_config = "";
745
	} else {
746
		$captiveportal = ",\"mod_cgi\"";
747
		$captive_portal_rewrite = "";
748
		$captive_portal_mod_evasive = "";
749
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
750
		$server_max_request_size = "server.max-request-size    = 2097152";
751
		$cgi_config = "cgi.assign                 = ( \".cgi\" => \"\" )";
752
	}
753
	
754
	if($port <> "")
755
		$lighty_port = $port;
756
	else
757
		$lighty_port = "80";
758

    
759
	$memory = get_memory();
760
	$avail = $memory[0];
761

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

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

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

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

    
799
	if ($captive_portal !== false)
800
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi-CP.socket";
801
	else
802
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi.socket";
803

    
804
	$fastcgi_config = <<<EOD
805
#### fastcgi module
806
## read fastcgi.txt for more info
807
fastcgi.server = ( ".php" =>
808
	( "localhost" =>
809
		(
810
			"socket" => "{$fast_cgi_path}",
811
			"max-procs" => {$max_procs},
812
{$bin_environment}
813
			"bin-path" => "/usr/local/bin/php"
814
		)
815
	)
816
)
817

    
818
EOD;
819

    
820
	$lighty_config = "";
821
	$lighty_config .= <<<EOD
822
#
823
# lighttpd configuration file
824
#
825
# use a it as base for lighttpd 1.0.0 and above
826
#
827
############ Options you really have to take care of ####################
828

    
829
## FreeBSD!
830
server.event-handler	= "freebsd-kqueue"
831
server.network-backend 	= "writev"
832

    
833
## modules to load
834
server.modules              =   ( "mod_access", "mod_accesslog", "mod_expire", "mod_compress", "mod_redirect"
835
			{$captiveportal},"mod_fastcgi"
836
		)
837

    
838
server.max-keep-alive-requests = 15
839
server.max-keep-alive-idle = 30
840

    
841
## a static document-root, for virtual-hosting take look at the
842
## server.virtual-* options
843
server.document-root        = "{$document_root}"
844
{$captive_portal_rewrite}
845

    
846
# Maximum idle time with nothing being written (php downloading)
847
server.max-write-idle = 999
848

    
849
## where to send error-messages to
850
server.errorlog-use-syslog="enable"
851

    
852
# files to check for if .../ is requested
853
server.indexfiles           = ( "index.php", "index.html",
854
                                "index.htm", "default.htm" )
855

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

    
909
# Use the "Content-Type" extended attribute to obtain mime type if possible
910
#mimetypes.use-xattr        = "enable"
911

    
912
## deny access the file-extensions
913
#
914
# ~    is for backupfiles from vi, emacs, joe, ...
915
# .inc is often used for code includes which should in general not be part
916
#      of the document-root
917
url.access-deny             = ( "~", ".inc" )
918

    
919
######### Options that are good to be but not neccesary to be changed #######
920

    
921
## bind to port (default: 80)
922
server.port                = {$lighty_port}
923

    
924
## error-handler for status 404
925
#server.error-handler-404   = "/error-handler.html"
926
#server.error-handler-404   = "/error-handler.php"
927

    
928
## to help the rc.scripts
929
server.pid-file            = "/var/run/{$pid_file}"
930

    
931
## virtual directory listings
932
server.dir-listing         = "disable"
933

    
934
## enable debugging
935
debug.log-request-header   = "disable"
936
debug.log-response-header  = "disable"
937
debug.log-request-handling = "disable"
938
debug.log-file-not-found   = "disable"
939

    
940
# gzip compression
941
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
942
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
943

    
944
{$server_upload_dirs}
945

    
946
{$server_max_request_size}
947

    
948
{$fastcgi_config}
949

    
950
{$cgi_config}
951

    
952
{$captive_portal_mod_evasive}
953

    
954
expire.url = (
955
				"" => "access 50 hours",	
956
        )
957

    
958
EOD;
959

    
960
	$cert = str_replace("\r", "", $cert);
961
	$key = str_replace("\r", "", $key);
962
	$ca = str_replace("\r", "", $ca);
963

    
964
	$cert = str_replace("\n\n", "\n", $cert);
965
	$key = str_replace("\n\n", "\n", $key);
966
	$ca = str_replace("\n\n", "\n", $ca);
967

    
968
	if($cert <> "" and $key <> "") {
969
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
970
		if (!$fd) {
971
			printf("Error: cannot open cert.pem in system_webgui_start().\n");
972
			return 1;
973
		}
974
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
975
		fwrite($fd, $cert);
976
		fwrite($fd, "\n");
977
		fwrite($fd, $key);
978
		fclose($fd);
979
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
980
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
981
			if (!$fd) {
982
				printf("Error: cannot open ca.pem in system_webgui_start().\n");
983
				return 1;
984
			}
985
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
986
			fwrite($fd, $ca);
987
			fclose($fd);
988
		}
989
		$lighty_config .= "\n";
990
		$lighty_config .= "## ssl configuration\n";
991
		$lighty_config .= "ssl.engine = \"enable\"\n";
992
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
993

    
994
		// Harden SSL a bit for PCI conformance testing
995
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
996
		$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";
997

    
998
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
999
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1000
	}
1001

    
1002
	// Add HTTP to HTTPS redirect	
1003
	if ($captive_portal == false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1004
		if($lighty_port != "443") 
1005
			$redirectport = ":{$lighty_port}";
1006
		$lighty_config .= <<<EOD
1007
\$SERVER["socket"] == ":80" {
1008
	\$HTTP["host"] =~ "(.*)" {
1009
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1010
	}
1011
}
1012
EOD;
1013
	}
1014

    
1015
	$fd = fopen("{$filename}", "w");
1016
	if (!$fd) {
1017
		printf("Error: cannot open {$filename} in system_generate_lighty_config().\n");
1018
		return 1;
1019
	}
1020
	fwrite($fd, $lighty_config);
1021
	fclose($fd);
1022

    
1023
	return 0;
1024

    
1025
}
1026

    
1027
function system_timezone_configure() {
1028
	global $config, $g;
1029
	if(isset($config['system']['developerspew'])) {
1030
		$mt = microtime();
1031
		echo "system_timezone_configure() being called $mt\n";
1032
	}
1033

    
1034
	$syscfg = $config['system'];
1035

    
1036
	if ($g['booting'])
1037
		echo "Setting timezone...";
1038

    
1039
	/* extract appropriate timezone file */
1040
	$timezone = $syscfg['timezone'];
1041
	if (!$timezone)
1042
		$timezone = "Etc/UTC";
1043

    
1044
	conf_mount_rw();
1045

    
1046
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1047
		escapeshellarg($timezone) . " > /etc/localtime");
1048

    
1049
	mwexec("sync");
1050
	conf_mount_ro();
1051

    
1052
	if ($g['booting'])
1053
		echo "done.\n";
1054
}
1055

    
1056
function system_ntp_configure($start_ntpd=true) {
1057
	global $config, $g;
1058
	$driftfile = "/var/db/ntpd.drift";
1059

    
1060
	$ntpcfg = "# \n";
1061
	$ntpcfg .= "# pfSense ntp configuration file \n";
1062
	$ntpcfg .= "# \n\n";
1063
	$ntpcfg .= "tinker panic 0 \n";
1064

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

    
1069
	$ntpcfg .= "driftfile {$driftfile}\n";
1070

    
1071
	if (empty($config['ntpd']['interface']))
1072
		if (!empty($config['installedpackages']['openntpd']['config'][0]['interface']))
1073
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1074
		else
1075
			$interfaces = array();
1076
	else
1077
		$interfaces = explode(",", $config['ntpd']['interface']);
1078

    
1079
	if (is_array($interfaces) && count($interfaces)) {
1080
		$ntpcfg .= "interface ignore all\n";
1081
		foreach ($interfaces as $interface) {
1082
			if (!is_ipaddr($interface)) {
1083
				$interface = get_real_interface($interface);
1084
			}
1085
			$ntpcfg .= "interface listen {$interface}\n";
1086
		}
1087
	}
1088

    
1089
	/* open configuration for wrting or bail */
1090
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1091
	if(!$fd) {
1092
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1093
		return;
1094
	}
1095
	fwrite($fd, $ntpcfg);
1096

    
1097
	/* slurp! */
1098
	fclose($fd);
1099

    
1100
	/* At bootup we just want to write out the config. */
1101
	if (!$start_ntpd)
1102
		return;
1103

    
1104
	/* if ntpd is running, kill it */
1105
	while(is_process_running("ntpd")) {
1106
		killbyname("ntpd");
1107
	}
1108

    
1109
	/* if /var/empty does not exist, create it */
1110
	if(!is_dir("/var/empty"))
1111
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1112

    
1113
	/* start ntpd, allow a large initial skew, and use /var/etc/ntpd.conf - run through tcsh to work around a PHP shell exec bug. */
1114
	exec("echo /usr/local/bin/ntpd -g -c {$g['varetc_path']}/ntpd.conf | tcsh");
1115
	
1116
	// Note that we are starting up
1117
	log_error("NTPD is starting up.");
1118
	return;
1119
}
1120

    
1121
function sync_system_time() {
1122
	global $config, $g;
1123

    
1124
	if ($g['booting'])
1125
		echo "Syncing system time before startup...";
1126

    
1127
	/* foreach through servers and write out to ntpd.conf */
1128
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1129
		mwexec("/usr/sbin/ntpdate -s $ts");
1130
	}
1131
	
1132
	if ($g['booting'])
1133
		echo "done.\n";
1134
	
1135
}
1136

    
1137
function system_halt() {
1138
	global $g;
1139

    
1140
	system_reboot_cleanup();
1141

    
1142
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1143
}
1144

    
1145
function system_reboot() {
1146
	global $g;
1147

    
1148
	system_reboot_cleanup();
1149

    
1150
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1151
}
1152

    
1153
function system_reboot_sync() {
1154
	global $g;
1155

    
1156
	system_reboot_cleanup();
1157

    
1158
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1159
}
1160

    
1161
function system_reboot_cleanup() {
1162
	mwexec("/usr/local/bin/beep.sh stop");
1163
	require_once("captiveportal.inc");
1164
	captiveportal_radius_stop_all();
1165
	require_once("voucher.inc");
1166
	voucher_save_db_to_config();
1167
	require_once("pkg-utils.inc");
1168
	stop_packages();
1169
}
1170

    
1171
function system_do_shell_commands($early = 0) {
1172
	global $config, $g;
1173
	if(isset($config['system']['developerspew'])) {
1174
		$mt = microtime();
1175
		echo "system_do_shell_commands() being called $mt\n";
1176
	}
1177

    
1178
	if ($early)
1179
		$cmdn = "earlyshellcmd";
1180
	else
1181
		$cmdn = "shellcmd";
1182

    
1183
	if (is_array($config['system'][$cmdn])) {
1184

    
1185
		/* *cmd is an array, loop through */
1186
		foreach ($config['system'][$cmdn] as $cmd) {
1187
			exec($cmd);
1188
		}
1189

    
1190
	} elseif($config['system'][$cmdn] <> "") {
1191

    
1192
		/* execute single item */
1193
		exec($config['system'][$cmdn]);
1194

    
1195
	}
1196
}
1197

    
1198
function system_console_configure() {
1199
	global $config, $g;
1200
	if(isset($config['system']['developerspew'])) {
1201
		$mt = microtime();
1202
		echo "system_console_configure() being called $mt\n";
1203
	}
1204

    
1205
	if (isset($config['system']['disableconsolemenu'])) {
1206
		touch("{$g['varetc_path']}/disableconsole");
1207
	} else {
1208
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1209
	}
1210
}
1211

    
1212
function system_dmesg_save() {
1213
	global $g;
1214
	if(isset($config['system']['developerspew'])) {
1215
		$mt = microtime();
1216
		echo "system_dmesg_save() being called $mt\n";
1217
	}
1218

    
1219
	$dmesg = "";
1220
	exec("/sbin/dmesg", $dmesg);
1221

    
1222
	/* find last copyright line (output from previous boots may be present) */
1223
	$lastcpline = 0;
1224

    
1225
	for ($i = 0; $i < count($dmesg); $i++) {
1226
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1227
			$lastcpline = $i;
1228
	}
1229

    
1230
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1231
	if (!$fd) {
1232
		printf("Error: cannot open dmesg.boot in system_dmesg_save().\n");
1233
		return 1;
1234
	}
1235

    
1236
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1237
		fwrite($fd, $dmesg[$i] . "\n");
1238

    
1239
	fclose($fd);
1240

    
1241
	return 0;
1242
}
1243

    
1244
function system_set_harddisk_standby() {
1245
	global $g, $config;
1246
	if(isset($config['system']['developerspew'])) {
1247
		$mt = microtime();
1248
		echo "system_set_harddisk_standby() being called $mt\n";
1249
	}
1250

    
1251
	if (isset($config['system']['harddiskstandby'])) {
1252
		if ($g['booting']) {
1253
			echo 'Setting hard disk standby... ';
1254
		}
1255

    
1256
		$standby = $config['system']['harddiskstandby'];
1257
		// Check for a numeric value
1258
		if (is_numeric($standby)) {
1259
			// Sync the disk(s)
1260
			pfSense_sync();
1261
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1262
				// Reinitialize ATA-drives
1263
				mwexec('/usr/local/sbin/atareinit');
1264
				if ($g['booting']) {
1265
					echo "done.\n";
1266
				}
1267
			} else if ($g['booting']) {
1268
				echo "failed!\n";
1269
			}
1270
		} else if ($g['booting']) {
1271
			echo "failed!\n";
1272
		}
1273
	}
1274
}
1275

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

    
1283
	activate_sysctls();	
1284

    
1285
	if (isset($config['system']['sharednet'])) {
1286
		system_disable_arp_wrong_if();
1287
	}
1288
}
1289

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

    
1300
function system_enable_arp_wrong_if() {
1301
	global $config;
1302
	if(isset($config['system']['developerspew'])) {
1303
		$mt = microtime();
1304
		echo "system_enable_arp_wrong_if() being called $mt\n";
1305
	}
1306
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1307
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1308
}
1309

    
1310
function enable_watchdog() {
1311
	global $config;
1312
	return;
1313
	$install_watchdog = false;
1314
	$supported_watchdogs = array("Geode");
1315
	$file = file_get_contents("/var/log/dmesg.boot");
1316
	foreach($supported_watchdogs as $sd) {
1317
		if(stristr($file, "Geode")) {
1318
			$install_watchdog = true;
1319
		}
1320
	}
1321
	if($install_watchdog == true) {
1322
		if(is_process_running("watchdogd"))
1323
			mwexec("/usr/bin/killall watchdogd", true);
1324
		exec("/usr/sbin/watchdogd");
1325
	}
1326
}
1327

    
1328
function system_check_reset_button() {
1329
	global $g;
1330
	if($g['platform'] != "nanobsd")
1331
		return 0;
1332

    
1333
	$specplatform = system_identify_specific_platform();
1334

    
1335
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1336
		return 0;
1337

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

    
1340
	if ($retval == 99) {
1341
		/* user has pressed reset button for 2 seconds - 
1342
		   reset to factory defaults */
1343
		echo <<<EOD
1344

    
1345
***********************************************************************
1346
* Reset button pressed - resetting configuration to factory defaults. *
1347
* The system will reboot after this completes.                        *
1348
***********************************************************************
1349

    
1350

    
1351
EOD;
1352
		
1353
		reset_factory_defaults();
1354
		system_reboot_sync();
1355
		exit(0);
1356
	}
1357

    
1358
	return 0;
1359
}
1360

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

    
1387
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1388
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1389
	
1390
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1391
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1392
		
1393
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1394
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1395
	
1396
	/* unknown embedded platform */
1397
	return array('name' => 'embedded', 'descr' => 'embedded (unknown)');
1398
}
1399

    
1400
function system_get_dmesg_boot() {
1401
	global $g;
1402
		
1403
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1404
}
1405

    
1406
function get_possible_listen_ips() {
1407
	$interfaces = get_configured_interface_with_descr();
1408
	$carplist = get_configured_carp_interface_list();
1409
	$listenips = array();
1410
	foreach ($carplist as $cif => $carpip)
1411
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1412
	$aliaslist = get_configured_ip_aliases_list();
1413
	foreach ($aliaslist as $aliasip => $aliasif)
1414
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1415
	foreach ($interfaces as $iface => $ifacename) {
1416
		$tmp["name"]  = $ifacename;
1417
		$tmp["value"] = $iface;
1418
		$listenips[] = $tmp;
1419
	}
1420
	$tmp["name"]  = "Localhost";
1421
	$tmp["value"] = "lo0";
1422
	$listenips[] = $tmp;
1423
	return $listenips;
1424
}
1425
?>
(47-47/61)