Project

General

Profile

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

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

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

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

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

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

    
32
/*
33
	pfSense_BUILDER_BINARIES:	/usr/sbin/powerd	/usr/bin/killall	/sbin/sysctl	/sbin/route
34
	pfSense_BUILDER_BINARIES:	/bin/hostname	/bin/ls	/usr/sbin/syslogd	
35
	pfSense_BUILDER_BINARIES:	/usr/sbin/pccardd	/usr/local/sbin/lighttpd	/bin/chmod 	/bin/mkdir
36
	pfSense_BUILDER_BINARIES:	/usr/bin/tar		/usr/local/sbin/ntpd	/usr/sbin/ntpdate
37
	pfSense_BUILDER_BINARIES:	/usr/bin/nohup	/sbin/dmesg	/usr/local/sbin/atareinit	/sbin/kldload
38
	pfSense_MODULE:	utils
39
*/
40

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

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

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

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

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

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

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

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

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

    
93
	if (isset($config['dnsmasq']['enable']) && !isset($config['system']['dnslocalhost']))
94
		$resolvconf .= "nameserver 127.0.0.1\n";
95

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

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

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

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

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

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

    
151
	unlock($dnslock);
152

    
153
	return 0;
154
}
155

    
156
function get_searchdomains() {
157
	global $config, $g;
158

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

    
175
	return $master_list;
176
}
177

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

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

    
206
	return $master_list;
207
}
208

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

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

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

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

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

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

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

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

    
280
	system_dhcpleases_configure();
281

    
282
	return 0;
283
}
284

    
285
function system_dhcpleases_configure() {
286
	global $config, $g;
287
	
288
	/* Start the monitoring process for dynamic dhcpclients. */
289
	if (isset($config['dnsmasq']['regdhcp'])) {
290
		/* Make sure we do not error out */
291
		@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
292
		if (file_exists("{$g['varrun_path']}/dhcpleases.pid"))
293
				sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "HUP");
294
		else
295
			mwexec("/usr/local/sbin/dhcpleases -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases -d {$config['system']['domain']} -p {$g['varrun_path']}/dnsmasq.pid -h {$g['varetc_path']}/hosts");
296
	} else {
297
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
298
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
299
	}
300
}
301

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

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

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

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

    
318
	return $status;
319
}
320

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

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

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

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

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

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

    
403
	return 0;
404
}
405

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
599
	return $retval;
600
}
601

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

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

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

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

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

    
625
	return $res;
626
}
627

    
628

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

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

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

    
638
	sleep(1);
639

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

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

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

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

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

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

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

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

    
710
	return $res;
711
}
712

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

    
727
	global $config, $g;
728

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

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

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

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

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

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

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

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

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

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

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

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

    
845
EOD;
846
	}
847

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

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

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

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

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

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

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

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

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

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

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

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

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

    
969

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

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

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

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

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

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

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

    
995
{$server_upload_dirs}
996

    
997
{$server_max_request_size}
998

    
999
{$fastcgi_config}
1000

    
1001
{$cgi_config}
1002

    
1003
{$captive_portal_mod_evasive}
1004

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

    
1009
EOD;
1010

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

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

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

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

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

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

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

    
1074
	return 0;
1075

    
1076
}
1077

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

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

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

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

    
1095
	conf_mount_rw();
1096

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

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

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

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

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

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

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

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

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

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

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

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

    
1168
}
1169

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

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

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

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

    
1189
	system_reboot_cleanup();
1190

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

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

    
1197
	system_reboot_cleanup();
1198

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

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

    
1205
	system_reboot_cleanup();
1206

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

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

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

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

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

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

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

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

    
1243
	}
1244
}
1245

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

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

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

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

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

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

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

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

    
1287
	fclose($fd);
1288

    
1289
	return 0;
1290
}
1291

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

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

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

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

    
1331
	activate_sysctls();	
1332

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

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

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

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

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

    
1381
	$specplatform = system_identify_specific_platform();
1382

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

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

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

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

    
1398

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

    
1406
	return 0;
1407
}
1408

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

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

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

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