Project

General

Profile

Download (62.3 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/local/sbin/ntpdate
37
	pfSense_BUILDER_BINARIES:	/usr/bin/nohup	/sbin/dmesg	/usr/local/sbin/atareinit	/sbin/kldload
38
	pfSense_BUILDER_BINARIES:	/usr/local/sbin/filterdns
39
	pfSense_MODULE:	utils
40
*/
41

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

    
52
		$ac_mode = "hadp";
53
		if (!empty($config['system']['powerd_ac_mode']))
54
			$ac_mode = $config['system']['powerd_ac_mode'];
55

    
56
		$battery_mode = "hadp";
57
		if (!empty($config['system']['powerd_battery_mode']))
58
			$battery_mode = $config['system']['powerd_battery_mode'];
59

    
60
		mwexec("/usr/sbin/powerd -b $battery_mode -a $ac_mode");
61
	}
62
}
63

    
64
function get_default_sysctl_value($id) {
65
	global $sysctls;
66

    
67
	if (isset($sysctls[$id]))
68
		return $sysctls[$id];
69
}
70

    
71
function activate_sysctls() {
72
	global $config, $g;
73
	if ($g['platform'] == 'jail')
74
		return;
75
	exec("/sbin/sysctl net.enc.out.ipsec_bpf_mask=0x0001");
76
	exec("/sbin/sysctl net.enc.out.ipsec_filter_mask=0x0001");
77
	exec("/sbin/sysctl net.enc.in.ipsec_bpf_mask=0x0002");
78
	exec("/sbin/sysctl net.enc.in.ipsec_filter_mask=0x0002");
79

    
80
	if(is_array($config['sysctl'])) {
81
		foreach($config['sysctl']['item'] as $tunable) {
82
			if($tunable['value'] == "default") {
83
				$value = get_default_sysctl_value($tunable['tunable']);
84
				mwexec("/sbin/sysctl " . $tunable['tunable'] . "=\"" . $value .  "\"", true);
85
			} else { 
86
				mwexec("/sbin/sysctl " . $tunable['tunable'] . "=\"" . $tunable['value'] .  "\"", true);
87
			}
88
		}
89
	}
90
}
91

    
92
function system_resolvconf_generate($dynupdate = false) {
93
	global $config, $g;
94

    
95
	if(isset($config['system']['developerspew'])) {
96
		$mt = microtime();
97
		echo "system_resolvconf_generate() being called $mt\n";
98
	}
99

    
100
	$syscfg = $config['system'];
101

    
102
	// Do not create blank domain lines, it breaks tools like dig.
103
	if($syscfg['domain'])
104
		$resolvconf = "domain {$syscfg['domain']}\n";
105

    
106
	if ((isset($config['dnsmasq']['enable']) || isset($config['unbound']['enable'])) && !isset($config['system']['dnslocalhost']))
107
		$resolvconf .= "nameserver 127.0.0.1\n";
108

    
109
	if (isset($syscfg['dnsallowoverride'])) {
110
		/* get dynamically assigned DNS servers (if any) */
111
		$ns = array_unique(get_searchdomains());
112
		foreach($ns as $searchserver) {
113
			if($searchserver)
114
				$resolvconf .= "search {$searchserver}\n";
115
		}
116
		$ns = array_unique(get_nameservers());
117
		foreach($ns as $nameserver) {
118
			if($nameserver)
119
				$resolvconf .= "nameserver $nameserver\n";
120
		}
121
	}
122
	if (is_array($syscfg['dnsserver'])) {
123
		foreach ($syscfg['dnsserver'] as $ns) {
124
			if ($ns)
125
				$resolvconf .= "nameserver $ns\n";
126
		}
127
	}
128

    
129
	// Add EDNS support
130
	if (isset($config['unbound']['enable']) && isset($config['unbound']['edns']))
131
		$resolvconf .= "options edns0\n";
132

    
133
	$dnslock = lock('resolvconf', LOCK_EX);
134

    
135
	$fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
136
	if (!$fd) {
137
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
138
		unlock($dnslock);
139
		return 1;
140
	}
141

    
142
	fwrite($fd, $resolvconf);
143
	fclose($fd);
144

    
145
	if (!$g['booting']) {
146
		/* restart dhcpd (nameservers may have changed) */
147
		if (!$dynupdate)
148
			services_dhcpd_configure();
149
	}
150

    
151
	/* setup static routes for DNS servers. */
152
	for ($dnscounter=1; $dnscounter<5; $dnscounter++) {
153
		/* setup static routes for dns servers */
154
		$dnsgw = "dns{$dnscounter}gw";
155
		if (isset($config['system'][$dnsgw])) {
156
			$gwname = $config['system'][$dnsgw];
157
			if (($gwname <> "") && ($gwname <> "none")) {
158
				$gatewayip = lookup_gateway_ip_by_name($gwname);
159
				if (is_ipaddrv4($gatewayip)) {
160
					/* dns server array starts at 0 */
161
					$dnscountermo = $dnscounter - 1;
162
					mwexec("/sbin/route change -host " . $syscfg['dnsserver'][$dnscountermo] . " {$gatewayip}");
163
				}
164
				if (is_ipaddrv6($gatewayip)) {
165
					/* dns server array starts at 0 */
166
					$dnscountermo = $dnscounter - 1;
167
					mwexec("/sbin/route change -host -inet6 " . $syscfg['dnsserver'][$dnscountermo] . " {$gatewayip}");
168
				}
169
			}
170
		}
171
	}
172

    
173
	unlock($dnslock);
174

    
175
	return 0;
176
}
177

    
178
function get_searchdomains() {
179
	global $config, $g;
180

    
181
	$master_list = array();
182
	
183
	// Read in dhclient nameservers
184
	$search_list = glob("/var/etc/searchdomain_*");
185
	if (is_array($search_list)) {
186
		foreach($search_list as $fdns) {
187
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
188
			if (!is_array($contents))
189
				continue;
190
			foreach ($contents as $dns) {
191
				if(is_hostname($dns)) 
192
					$master_list[] = $dns;
193
			}
194
		}
195
	}
196

    
197
	return $master_list;
198
}
199

    
200
function get_nameservers() {
201
	global $config, $g;
202
	$master_list = array();
203
	
204
	// Read in dhclient nameservers
205
	$dns_lists = glob("/var/etc/nameserver_*");
206
	if (is_array($dns_lists)) {
207
		foreach($dns_lists as $fdns) {
208
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
209
			if (!is_array($contents))
210
				continue;
211
			foreach ($contents as $dns) {
212
				if(is_ipaddr($dns)) 
213
					$master_list[] = $dns;
214
			}
215
		}
216
	}
217

    
218
	// Read in any extra nameservers
219
	if(file_exists("/var/etc/nameservers.conf")) {
220
		$dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
221
		if(is_array($dns_s)) {
222
			foreach($dns_s as $dns)
223
				if (is_ipaddr($dns))
224
					$master_list[] = $dns;
225
		}
226
	}
227

    
228
	return $master_list;
229
}
230

    
231
function system_hosts_generate() {
232
	global $config, $g;
233
	if(isset($config['system']['developerspew'])) {
234
		$mt = microtime();
235
		echo "system_hosts_generate() being called $mt\n";
236
	}
237

    
238
	$syscfg = $config['system'];
239
	$dnsmasqcfg = $config['dnsmasq'];
240

    
241
	$hosts = "127.0.0.1	localhost localhost.{$syscfg['domain']}\n";
242
	$lhosts = "";
243
	$dhosts = "";
244

    
245
	if ($config['interfaces']['lan']) {
246
		$cfgip = get_interface_ip("lan");
247
		if (is_ipaddr($cfgip))
248
			$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
249
	} else {
250
		$sysiflist = get_configured_interface_list();
251
		foreach ($sysiflist as $sysif) {
252
			if (!interface_has_gateway($sysif)) {
253
				$cfgip = get_interface_ip($sysif);
254
				if (is_ipaddr($cfgip)) {
255
					$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
256
					break;
257
				}
258
			}
259
		}
260
	}
261

    
262
	if (isset($dnsmasqcfg['enable'])) {
263
		if (!is_array($dnsmasqcfg['hosts']))
264
			$dnsmasqcfg['hosts'] = array();
265

    
266
		foreach ($dnsmasqcfg['hosts'] as $host) {
267
			if ($host['host'])
268
				$lhosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
269
			else
270
				$lhosts .= "{$host['ip']}	{$host['domain']}\n";
271
			if (!is_array($host['aliases']) || !is_array($host['aliases']['item']))
272
				continue;
273
			foreach ($host['aliases']['item'] as $alias) {
274
				if ($alias['host'])
275
					$lhosts .= "{$host['ip']}	{$alias['host']}.{$alias['domain']} {$alias['host']}\n";
276
				else
277
					$lhosts .= "{$host['ip']}	{$alias['domain']}\n";
278
			}
279
		}
280
		if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpd'])) {
281
			foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf)
282
				if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
283
						foreach ($dhcpifconf['staticmap'] as $host)
284
							if ($host['ipaddr'] && $host['hostname'] && $host['domain'])
285
								$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$host['domain']} {$host['hostname']}\n";
286
							else if ($host['ipaddr'] && $host['hostname'] && $dhcpifconf['domain'])
287
								$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$dhcpifconf['domain']} {$host['hostname']}\n";
288
							else if ($host['ipaddr'] && $host['hostname'])
289
								$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
290
		}
291
		if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpdv6'])) {
292
			foreach ($config['dhcpdv6'] as $dhcpif => $dhcpifconf)
293
				if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
294
						foreach ($dhcpifconf['staticmap'] as $host)
295
							if ($host['ipaddrv6'] && $host['hostname'] && $host['domain'])
296
								$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$host['domain']} {$host['hostname']}\n";
297
							else if ($host['ipaddrv6'] && $host['hostname'] && $dhcpifconf['domain'])
298
								$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$dhcpifconf['domain']} {$host['hostname']}\n";
299
							else if ($host['ipaddrv6'] && $host['hostname'])
300
								$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
301
		}
302

    
303
		if (isset($dnsmasqcfg['dhcpfirst']))
304
			$hosts .= $dhosts . $lhosts;
305
		else
306
			$hosts .= $lhosts . $dhosts;
307
	}
308

    
309
	/*
310
	 * Do not remove this because dhcpleases monitors with kqueue it needs to be 
311
	 * killed before writing to hosts files.
312
	 */
313
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
314
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
315
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
316
	}
317
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
318
	if (!$fd) {
319
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
320
		return 1;
321
	}
322
	fwrite($fd, $hosts);
323
	fclose($fd);
324

    
325
	system_dhcpleases_configure();
326

    
327
	return 0;
328
}
329

    
330
function system_dhcpleases_configure() {
331
	global $config, $g;
332
	
333
	if ($g['platform'] == 'jail')
334
		return;
335
	/* Start the monitoring process for dynamic dhcpclients. */
336
	if (isset($config['dnsmasq']['enable']) && isset($config['dnsmasq']['regdhcp'])) {
337
		/* Make sure we do not error out */
338
		mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db");
339
		if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases"))
340
			@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
341
		if (isvalidpid("{$g['varrun_path']}/dhcpleases.pid"))
342
			sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "HUP");
343
		else
344
			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");
345
	} else {
346
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
347
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
348
	}
349
}
350

    
351
function system_hostname_configure() {
352
	global $config, $g;
353
	if(isset($config['system']['developerspew'])) {
354
		$mt = microtime();
355
		echo "system_hostname_configure() being called $mt\n";
356
	}
357

    
358
	$syscfg = $config['system'];
359

    
360
	/* set hostname */
361
	$status = mwexec("/bin/hostname " .
362
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
363

    
364
    /* Setup host GUID ID.  This is used by ZFS. */
365
	mwexec("/etc/rc.d/hostid start");
366

    
367
	return $status;
368
}
369

    
370
function system_routing_configure($interface = "") {
371
	global $config, $g;
372
	if ($g['platform'] == 'jail')
373
		return;
374
	if(isset($config['system']['developerspew'])) {
375
		$mt = microtime();
376
		echo "system_routing_configure() being called $mt\n";
377
	}
378

    
379
	$gatewayip = "";
380
	$interfacegw = "";
381
	$foundgw = false;
382
	$gatewayipv6 = "";
383
	$interfacegwv6 = "";
384
	$foundgwv6 = false;
385
	/* tack on all the hard defined gateways as well */
386
	if (is_array($config['gateways']['gateway_item'])) {
387
		array_map('unlink', glob("{$g['tmp_path']}/*_defaultgw{,v6}", GLOB_BRACE));
388
		foreach	($config['gateways']['gateway_item'] as $gateway) {
389
			if (isset($gateway['defaultgw'])) {
390
				if ($gateway['ipprotocol'] != "inet6" && (is_ipaddrv4($gateway['gateway']) || $gateway['gateway'] == "dynamic")) {
391
					if(strstr($gateway['gateway'], ":"))
392
						continue;
393
					if ($gateway['gateway'] == "dynamic")
394
						$gateway['gateway'] = get_interface_gateway($gateway['interface']);
395
					$gatewayip = $gateway['gateway'];
396
					$interfacegw = $gateway['interface'];
397
					if (!empty($gateway['interface'])) {
398
						$defaultif = get_real_interface($gateway['interface']);
399
						if ($defaultif)
400
							@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gateway['gateway']);
401
					}
402
					$foundgw = true;
403
				} else if ($gateway['ipprotocol'] == "inet6" && (is_ipaddrv6($gateway['gateway']) || $gateway['gateway'] == "dynamic6")) {
404
					if ($gateway['gateway'] == "dynamic6")
405
						$gateway['gateway'] = get_interface_gateway_v6($gateway['interface']);
406
					$gatewayipv6 = $gateway['gateway'];
407
					$interfacegwv6 = $gateway['interface'];
408
					if (!empty($gateway['interface'])) {
409
						$defaultifv6 = get_real_interface($gateway['interface']);
410
						if ($defaultifv6)
411
							@file_put_contents("{$g['tmp_path']}/{$defaultifv6}_defaultgwv6", $gateway['gateway']);
412
					}
413
					$foundgwv6 = true;
414
				}
415
			}
416
			if ($foundgw === true && $foundgwv6 === true)
417
				break;
418
		}
419
	}
420
	if ($foundgw == false) {
421
		$defaultif = get_real_interface("wan");
422
		$interfacegw = "wan";
423
		$gatewayip = get_interface_gateway("wan");
424
		@touch("{$g['tmp_path']}/{$defaultif}_defaultgw");
425
	}	
426
	if ($foundgwv6 == false) {
427
		$defaultifv6 = get_real_interface("wan");
428
		$interfacegwv6 = "wan";
429
		$gatewayipv6 = get_interface_gateway_v6("wan");
430
		@touch("{$g['tmp_path']}/{$defaultif}_defaultgwv6");
431
	}
432
	$dont_add_route = false;
433
	/* if OLSRD is enabled, allow WAN to house DHCP. */
434
	if (is_array($config['installedpackages']['olsrd'])) {
435
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
436
			if(($olsrd['enabledyngw'] == "on") && ($olsrd['enable'] == "on")) {
437
				$dont_add_route = true;
438
				log_error(sprintf(gettext("Not adding default route because OLSR dynamic gateway is enabled.")));
439
				break;
440
			}
441
		}
442
	}
443

    
444
	if ($dont_add_route == false ) {
445
		if (!empty($interface) && $interface != $interfacegw)
446
			;
447
		else if (($interfacegw <> "bgpd") && (is_ipaddrv4($gatewayip))) {
448
			log_error("ROUTING: setting default route to $gatewayip");
449
			mwexec("/sbin/route change -inet default " . escapeshellarg($gatewayip));
450
		}
451

    
452
		if (!empty($interface) && $interface != $interfacegwv6)
453
			;
454
		else if (($interfacegwv6 <> "bgpd") && (is_ipaddrv6($gatewayipv6))) {
455
			$ifscope = "";
456
			if (is_linklocal($gatewayipv6))
457
				$ifscope = "%{$defaultifv6}";
458
			log_error("ROUTING: setting IPv6 default route to {$gatewayipv6}{$ifscope}");
459
			mwexec("/sbin/route change -inet6 default " . escapeshellarg($gatewayipv6) ."{$ifscope}");
460
		}
461
	}
462

    
463
	system_staticroutes_configure($interface, false);
464

    
465
	return 0;
466
}
467

    
468
function system_staticroutes_configure($interface = "", $update_dns = false) {
469
	global $config, $g, $aliastable;
470

    
471
	$filterdns_list = array();
472

    
473
	$static_routes = get_staticroutes(false, true);
474
	if (count($static_routes)) {
475
		$gateways_arr = return_gateways_array(false, true);
476

    
477
		foreach ($static_routes as $rtent) {
478
			if (empty($gateways_arr[$rtent['gateway']])) {
479
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
480
				continue;
481
			}
482
			$gateway = $gateways_arr[$rtent['gateway']];
483
			if (!empty($interface) && $interface != $gateway['friendlyiface'])
484
				continue;
485

    
486
			$gatewayip = $gateway['gateway'];
487
			$interfacegw = $gateway['interface'];
488

    
489
			$blackhole = "";
490
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 3)))
491
				$blackhole = "-blackhole";
492

    
493
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network']))
494
				continue;
495

    
496
			$dnscache = array();
497
			if ($update_dns === true) {
498
				if (is_subnet($rtent['network']))
499
					continue;
500
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
501
				if (empty($dnscache))
502
					continue;
503
			}
504

    
505
			if (is_subnet($rtent['network']))
506
				$ips = array($rtent['network']);
507
			else {
508
				if (!isset($rtent['disabled']))
509
					$filterdns_list[] = $rtent['network'];
510
				$ips = add_hostname_to_watch($rtent['network']);
511
			}
512

    
513
			foreach ($dnscache as $ip) {
514
				if (in_array($ip, $ips))
515
					continue;
516
				mwexec("/sbin/route delete " . escapeshellarg($ip), true);
517
			}
518

    
519
			if (isset($rtent['disabled'])) {
520
				/* XXX: This is a bit dangerous in case of routing daemons!? */
521
				foreach ($ips as $ip)
522
					mwexec("/sbin/route delete " . escapeshellarg($ip), true);
523
				continue;
524
			}
525

    
526
			foreach ($ips as $ip) {
527
				if (is_ipaddrv4($ip))
528
					$ip .= "/32";
529
				else if (is_ipaddrv6($ip))
530
					$ip .= "/128";
531

    
532
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
533

    
534
				$cmd = "/sbin/route change {$inet} {$blackhole} " . escapeshellarg($ip) . " ";
535

    
536
				if (is_subnet($ip))
537
					if (is_ipaddr($gatewayip))
538
						mwexec($cmd . escapeshellarg($gatewayip));
539
					else if (!empty($interfacegw))
540
						mwexec($cmd . "-iface " . escapeshellarg($interfacegw));
541
			}
542
		}
543
		unset($gateways_arr);
544
	}
545
	unset($static_routes);
546

    
547
	if ($update_dns === false) {
548
		if (count($filterdns_list)) {
549
			$interval = 60;
550
			$hostnames = "";
551
			array_unique($filterdns_list);
552
			foreach ($filterdns_list as $hostname)
553
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
554
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
555
			unset($hostnames);
556

    
557
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid"))
558
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
559
			else
560
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
561
		} else {
562
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
563
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
564
		}
565
	}
566
	unset($filterdns_list);
567

    
568
	return 0;
569
}
570

    
571
function system_routing_enable() {
572
	global $config, $g;
573
	if(isset($config['system']['developerspew'])) {
574
		$mt = microtime();
575
		echo "system_routing_enable() being called $mt\n";
576
	}
577

    
578
	mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
579
	mwexec("/sbin/sysctl net.inet6.ip6.forwarding=1");
580
	return;
581
}
582

    
583
function system_syslogd_fixup_server($server) {
584
	/* If it's an IPv6 IP alone, encase it in brackets */
585
	if (is_ipaddrv6($server))
586
		return "[$server]";
587
	else
588
		return $server;
589
}
590

    
591
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
592
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
593
	$facility .= " ".
594
	$remote_servers = "";
595
	$pad_to  = 56;
596
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
597
	if($syslogcfg['remoteserver'])
598
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
599
	if($syslogcfg['remoteserver2'])
600
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
601
	if($syslogcfg['remoteserver3'])
602
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
603
	return $remote_servers;
604
}
605

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

    
613
	mwexec("/etc/rc.d/hostid start");
614

    
615
	$syslogcfg = $config['syslog'];
616

    
617
	if ($g['booting'])
618
		echo gettext("Starting syslog...");
619
	else
620
		killbypid("{$g['varrun_path']}/syslog.pid");
621

    
622
	if (is_process_running("syslogd"))
623
		mwexec('/bin/pkill syslogd');
624
	if (is_process_running("fifolog_writer"))
625
		mwexec('/bin/pkill fifolog_writer');
626

    
627
	// Which logging type are we using this week??
628
	if (isset($config['system']['disablesyslogclog'])) {
629
		$log_directive = "";
630
		$log_create_directive = "/usr/bin/touch ";
631
		$log_size = "";
632
	} else if (isset($config['system']['usefifolog'])) {
633
		$log_directive = "|/usr/sbin/fifolog_writer ";
634
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
635
		$log_create_directive = "/usr/sbin/fifolog_create -s ";
636
	} else { // Defaults to CLOG
637
		$log_directive = "%";
638
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
639
		$log_create_directive = "/usr/sbin/clog -i -s ";
640
	}
641
	
642
	if (isset($syslogcfg)) {
643
		$separatelogfacilities = array('ntp','ntpd','ntpdate','racoon','openvpn','pptps','poes','l2tps','relayd','hostapd','dnsmasq','filterdns','unbound','dhcpd','dhcrelay','dhclient','apinger','radvd','routed','olsrd','zebra','ospfd','bgpd','miniupnpd');
644
		$syslogconf = "";
645
		if($config['installedpackages']['package']) {
646
			foreach($config['installedpackages']['package'] as $package) {
647
				if($package['logging']) {
648
					array_push($separatelogfacilities, $package['logging']['facilityname']);
649
					mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
650
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
651
				}
652
			}
653
		}
654
		$facilitylist = implode(',', array_unique($separatelogfacilities));
655
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd,miniupnpd\n";
656
		if (!isset($syslogcfg['disablelocallogging']))
657
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
658

    
659
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
660
		if (!isset($syslogcfg['disablelocallogging'])) 
661
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
662

    
663
		$syslogconf .= "!ppp\n";
664
		if (!isset($syslogcfg['disablelocallogging'])) 
665
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
666

    
667
		$syslogconf .= "!pptps\n";
668
		if (!isset($syslogcfg['disablelocallogging'])) 
669
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/pptps.log\n";
670

    
671
		$syslogconf .= "!poes\n";
672
		if (!isset($syslogcfg['disablelocallogging'])) 
673
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
674

    
675
		$syslogconf .= "!l2tps\n";
676
		if (!isset($syslogcfg['disablelocallogging'])) 
677
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/l2tps.log\n";
678

    
679
		$syslogconf .= "!racoon\n";
680
		if (!isset($syslogcfg['disablelocallogging'])) 
681
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ipsec.log\n";
682
		if (isset($syslogcfg['vpn']))
683
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
684

    
685
		$syslogconf .= "!openvpn\n";
686
		if (!isset($syslogcfg['disablelocallogging'])) 
687
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/openvpn.log\n";
688
		if (isset($syslogcfg['vpn']))
689
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
690

    
691
		$syslogconf .= "!apinger\n";
692
		if (!isset($syslogcfg['disablelocallogging']))
693
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/gateways.log\n";
694
		if (isset($syslogcfg['apinger']))
695
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
696

    
697
		$syslogconf .= "!dnsmasq,filterdns,unbound\n";
698
		if (!isset($syslogcfg['disablelocallogging']))
699
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
700
		if (isset($syslogcfg['apinger']))
701
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
702

    
703
		$syslogconf .= "!dhcpd,dhcrelay,dhclient\n";
704
		if (!isset($syslogcfg['disablelocallogging']))
705
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/dhcpd.log\n";
706
		if (isset($syslogcfg['apinger']))
707
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
708

    
709
		$syslogconf .= "!relayd\n";
710
		if (!isset($syslogcfg['disablelocallogging']))
711
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/relayd.log\n";
712
		if (isset($syslogcfg['relayd']))
713
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
714

    
715
		$syslogconf .= "!hostapd\n";
716
		if (!isset($syslogcfg['disablelocallogging']))
717
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
718
		if (isset($syslogcfg['hostapd']))
719
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
720

    
721
		$syslogconf .= "!-{$facilitylist}\n";
722
		if (!isset($syslogcfg['disablelocallogging'])) 
723
			$syslogconf .= <<<EOD
724
local0.*							{$log_directive}{$g['varlog_path']}/filter.log
725
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
726
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
727
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
728
*.notice;kern.debug;lpr.info;mail.crit;daemon.none;		{$log_directive}{$g['varlog_path']}/system.log
729
news.err;local0.none;local3.none;local4.none;			{$log_directive}{$g['varlog_path']}/system.log
730
local7.none							{$log_directive}{$g['varlog_path']}/system.log
731
security.*							{$log_directive}{$g['varlog_path']}/system.log
732
auth.info;authpriv.info;daemon.info				{$log_directive}{$g['varlog_path']}/system.log
733
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
734
*.emerg								*
735

    
736
EOD;
737
		if (isset($syslogcfg['filter']))
738
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local0.*");
739
		if (isset($syslogcfg['vpn']))
740
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
741
		if (isset($syslogcfg['portalauth']))
742
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
743
		if (isset($syslogcfg['dhcp']))
744
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
745
		if (isset($syslogcfg['system'])) {
746
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.notice;kern.debug;lpr.info;mail.crit;");
747
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "news.err;local0.none;local3.none;local7.none");
748
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "security.*");
749
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "auth.info;authpriv.info;daemon.info");
750
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.emerg");
751
		}
752
		if (isset($syslogcfg['logall'])) {
753
			// Make everything mean everything, including facilities excluded above.
754
			$syslogconf .= "!*\n";
755
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
756
		}
757

    
758
		if (isset($syslogcfg['zmqserver'])) {
759
				$syslogconf .= <<<EOD
760
*.*								^{$syslogcfg['zmqserver']}
761

    
762
EOD;
763
		}
764
		/* write syslog.conf */		
765
		if (!@file_put_contents("{$g['varetc_path']}/syslog.conf", $syslogconf)) {
766
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
767
			unset($syslogconf);
768
			return 1;
769
		}
770
		unset($syslogconf);
771

    
772
		// Ensure that the log directory exists
773
		if (!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
774
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
775

    
776
		$sourceip = "";
777
		if (!empty($syslogcfg['sourceip'])) {
778
			if ($syslogcfg['ipproto'] == "ipv6") {
779
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
780
				if (!is_ipaddr($ifaddr))
781
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
782
			} else {
783
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
784
				if (!is_ipaddr($ifaddr))
785
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
786
			}
787
			if (is_ipaddr($ifaddr)) {
788
				$sourceip = "-b {$ifaddr}";
789
			}
790
		}
791

    
792
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c -l {$g['dhcpd_chroot_path']}/var/run/log -f {$g['varetc_path']}/syslog.conf {$sourceip}");
793

    
794
	} else {
795
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c -l {$g['dhcpd_chroot_path']}/var/run/log");
796
	}
797

    
798
	if ($g['booting'])
799
		echo gettext("done.") . "\n";
800

    
801
	return $retval;
802
}
803

    
804
function system_pccard_start() {
805
	global $config, $g;
806
	if(isset($config['system']['developerspew'])) {
807
		$mt = microtime();
808
		echo "system_pccard_start() being called $mt\n";
809
	}
810

    
811
	if ($g['booting'])
812
		echo gettext("Initializing PCMCIA...");
813

    
814
	/* kill any running pccardd */
815
	killbypid("{$g['varrun_path']}/pccardd.pid");
816

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

    
820
	if ($g['booting']) {
821
		if ($res == 0)
822
			echo gettext("done.") . "\n";
823
		else
824
			echo gettext("failed!") . "\n";
825
	}
826

    
827
	return $res;
828
}
829

    
830

    
831
function system_webgui_start() {
832
	global $config, $g;
833

    
834
	if ($g['booting'])
835
		echo gettext("Starting webConfigurator...");
836

    
837
	chdir($g['www_path']);
838

    
839
	/* defaults */
840
	$portarg = "80";
841
	$crt = "";
842
	$key = "";
843
	$ca = "";
844

    
845
	/* non-standard port? */
846
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
847
		$portarg = "{$config['system']['webgui']['port']}";
848

    
849
	if ($config['system']['webgui']['protocol'] == "https") {
850
		// Ensure that we have a webConfigurator CERT
851
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
852
		if(!is_array($cert) && !$cert['crt'] && !$cert['prv']) {
853
			if (!is_array($config['ca']))
854
				$config['ca'] = array();
855
			$a_ca =& $config['ca'];
856
			if (!is_array($config['cert']))
857
				$config['cert'] = array();
858
			$a_cert =& $config['cert'];
859
			log_error("Creating SSL Certificate for this host");
860
			$cert = array();
861
			$cert['refid'] = uniqid();
862
			$cert['descr'] = gettext("webConfigurator default");
863
			mwexec("/usr/bin/openssl genrsa 1024 > {$g['tmp_path']}/ssl.key");
864
			mwexec("/usr/bin/openssl req -new -x509 -nodes -sha256 -days 2000 -key {$g['tmp_path']}/ssl.key > {$g['tmp_path']}/ssl.crt");
865
			$crt = file_get_contents("{$g['tmp_path']}/ssl.crt");
866
			$key = file_get_contents("{$g['tmp_path']}/ssl.key");
867
			unlink("{$g['tmp_path']}/ssl.key");
868
			unlink("{$g['tmp_path']}/ssl.crt");
869
			cert_import($cert, $crt, $key);
870
			$a_cert[] = $cert;
871
			$config['system']['webgui']['ssl-certref'] = $cert['refid'];
872
			write_config(gettext("Importing HTTPS certificate"));
873
			if(!$config['system']['webgui']['port'])
874
				$portarg = "443";
875
			$ca = ca_chain($cert);
876
		} else {
877
			$crt = base64_decode($cert['crt']);
878
			$key = base64_decode($cert['prv']);
879
			if(!$config['system']['webgui']['port'])
880
				$portarg = "443";
881
			$ca = ca_chain($cert);
882
		}
883
	}
884

    
885
	/* generate lighttpd configuration */
886
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
887
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
888
		"cert.pem", "ca.pem");
889

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

    
893
	sleep(1);
894

    
895
	@unlink("{$g['varrun_path']}/lighty-webConfigurator.pid");
896

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

    
900
	if ($g['booting']) {
901
		if ($res == 0)
902
			echo gettext("done.") . "\n";
903
		else
904
			echo gettext("failed!") . "\n";
905
	}
906

    
907
	return $res;
908
}
909

    
910
function system_generate_lighty_config($filename,
911
	$cert,
912
	$key,
913
	$ca,
914
	$pid_file,
915
	$port = 80,
916
	$document_root = "/usr/local/www/",
917
	$cert_location = "cert.pem",
918
	$ca_location = "ca.pem",
919
	$captive_portal = false) {
920

    
921
	global $config, $g;
922

    
923
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
924
		mkdir("{$g['tmp_path']}/lighttpdcompress");
925

    
926
	if(isset($config['system']['developerspew'])) {
927
		$mt = microtime();
928
		echo "system_generate_lighty_config() being called $mt\n";
929
	}
930

    
931
	if ($captive_portal !== false)  {
932
		$captiveportal = ",\"mod_rewrite\",\"mod_evasive\"";
933
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?zone={$captive_portal}&redirurl=$1\" )\n";
934

    
935
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
936
		if (empty($maxprocperip))
937
			$maxprocperip = 10;
938
		$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
939

    
940
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
941
		if(!is_dir("{$g['tmp_path']}/captiveportal"))
942
			@mkdir("{$g['tmp_path']}/captiveportal", 0555);
943
		$server_max_request_size = "server.max-request-size    = 384";
944
		$cgi_config = "";
945
	} else {
946
		$captiveportal = ",\"mod_cgi\"";
947
		$captive_portal_rewrite = "";
948
		$captive_portal_mod_evasive = "";
949
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
950
		$server_max_request_size = "server.max-request-size    = 2097152";
951
		$cgi_config = "cgi.assign                 = ( \".cgi\" => \"\" )";
952
	}
953
	
954
	if (empty($port))
955
		$lighty_port = "80";
956
	else
957
		$lighty_port = $port;
958

    
959
	$memory = get_memory();
960
	$realmem = $memory[1];
961

    
962
	// Determine web GUI process settings and take into account low memory systems
963
	if ($realmem < 255)
964
		$max_procs = 1;
965
	else
966
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
967

    
968
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM 
969
	if ($captive_portal !== false)  {
970
		if ($realmem > 135 and $realmem < 256) {
971
			$max_procs += 1; // 2 worker processes
972
		} else if ($realmem > 255 and $realmem < 513) {
973
			$max_procs += 2; // 3 worker processes
974
		} else if ($realmem > 512) {
975
			$max_procs += 4; // 6 worker processes
976
		}
977
		if ($max_procs > 1)
978
			$max_php_children = intval($max_procs/2);
979
		else
980
			$max_php_children = 1;
981

    
982
	} else {
983
		if ($realmem < 78)
984
			$max_php_children = 0;
985
		else
986
			$max_php_children = 1;
987
	}
988

    
989
	if(!isset($config['syslog']['nologlighttpd'])) {
990
		$lighty_use_syslog = <<<EOD
991
## where to send error-messages to
992
server.errorlog-use-syslog="enable"
993
EOD;
994
	}
995

    
996

    
997
	if ($captive_portal !== false) {
998
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi-{$captive_portal}.socket";
999
		$fastcgi_config = <<<EOD
1000
#### fastcgi module
1001
## read fastcgi.txt for more info
1002
fastcgi.server = ( ".php" =>
1003
	( "localhost" =>
1004
		(
1005
			"socket" => "{$fast_cgi_path}",
1006
			"max-procs" => {$max_procs},
1007
			"bin-environment" => (
1008
				"PHP_FCGI_CHILDREN" => "{$max_php_children}",
1009
				"PHP_FCGI_MAX_REQUESTS" => "500"
1010
			),
1011
			"bin-path" => "/usr/local/bin/php"
1012
		)
1013
	)
1014
)
1015

    
1016
EOD;
1017
	} else {
1018
		$fast_cgi_path = "{$g['varrun_path']}/php-fpm.socket";
1019
		$fastcgi_config = <<<EOD
1020
#### fastcgi module
1021
## read fastcgi.txt for more info
1022
fastcgi.server = ( ".php" =>
1023
	( "localhost" =>
1024
		(
1025
			"socket" => "{$fast_cgi_path}",
1026
			"broken-scriptfilename" => "enable"
1027
		)
1028
	)
1029
)
1030

    
1031
EOD;
1032
	}
1033

    
1034

    
1035
	$lighty_config = <<<EOD
1036
#
1037
# lighttpd configuration file
1038
#
1039
# use a it as base for lighttpd 1.0.0 and above
1040
#
1041
############ Options you really have to take care of ####################
1042

    
1043
## FreeBSD!
1044
server.event-handler	= "freebsd-kqueue"
1045
server.network-backend 	= "writev"
1046
#server.use-ipv6 = "enable"
1047

    
1048
## modules to load
1049
server.modules              =   ( "mod_access", "mod_expire", "mod_compress", "mod_redirect",
1050
	{$captiveportal}, "mod_fastcgi"
1051
)
1052

    
1053
server.max-keep-alive-requests = 15
1054
server.max-keep-alive-idle = 30
1055

    
1056
## a static document-root, for virtual-hosting take look at the
1057
## server.virtual-* options
1058
server.document-root        = "{$document_root}"
1059
{$captive_portal_rewrite}
1060

    
1061
# Maximum idle time with nothing being written (php downloading)
1062
server.max-write-idle = 999
1063

    
1064
{$lighty_use_syslog}
1065

    
1066
# files to check for if .../ is requested
1067
server.indexfiles           = ( "index.php", "index.html",
1068
                                "index.htm", "default.htm" )
1069

    
1070
# mimetype mapping
1071
mimetype.assign             = (
1072
  ".pdf"          =>      "application/pdf",
1073
  ".sig"          =>      "application/pgp-signature",
1074
  ".spl"          =>      "application/futuresplash",
1075
  ".class"        =>      "application/octet-stream",
1076
  ".ps"           =>      "application/postscript",
1077
  ".torrent"      =>      "application/x-bittorrent",
1078
  ".dvi"          =>      "application/x-dvi",
1079
  ".gz"           =>      "application/x-gzip",
1080
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
1081
  ".swf"          =>      "application/x-shockwave-flash",
1082
  ".tar.gz"       =>      "application/x-tgz",
1083
  ".tgz"          =>      "application/x-tgz",
1084
  ".tar"          =>      "application/x-tar",
1085
  ".zip"          =>      "application/zip",
1086
  ".mp3"          =>      "audio/mpeg",
1087
  ".m3u"          =>      "audio/x-mpegurl",
1088
  ".wma"          =>      "audio/x-ms-wma",
1089
  ".wax"          =>      "audio/x-ms-wax",
1090
  ".ogg"          =>      "audio/x-wav",
1091
  ".wav"          =>      "audio/x-wav",
1092
  ".gif"          =>      "image/gif",
1093
  ".jpg"          =>      "image/jpeg",
1094
  ".jpeg"         =>      "image/jpeg",
1095
  ".png"          =>      "image/png",
1096
  ".xbm"          =>      "image/x-xbitmap",
1097
  ".xpm"          =>      "image/x-xpixmap",
1098
  ".xwd"          =>      "image/x-xwindowdump",
1099
  ".css"          =>      "text/css",
1100
  ".html"         =>      "text/html",
1101
  ".htm"          =>      "text/html",
1102
  ".js"           =>      "text/javascript",
1103
  ".asc"          =>      "text/plain",
1104
  ".c"            =>      "text/plain",
1105
  ".conf"         =>      "text/plain",
1106
  ".text"         =>      "text/plain",
1107
  ".txt"          =>      "text/plain",
1108
  ".dtd"          =>      "text/xml",
1109
  ".xml"          =>      "text/xml",
1110
  ".mpeg"         =>      "video/mpeg",
1111
  ".mpg"          =>      "video/mpeg",
1112
  ".mov"          =>      "video/quicktime",
1113
  ".qt"           =>      "video/quicktime",
1114
  ".avi"          =>      "video/x-msvideo",
1115
  ".asf"          =>      "video/x-ms-asf",
1116
  ".asx"          =>      "video/x-ms-asf",
1117
  ".wmv"          =>      "video/x-ms-wmv",
1118
  ".bz2"          =>      "application/x-bzip",
1119
  ".tbz"          =>      "application/x-bzip-compressed-tar",
1120
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
1121
 )
1122

    
1123
# Use the "Content-Type" extended attribute to obtain mime type if possible
1124
#mimetypes.use-xattr        = "enable"
1125

    
1126
## deny access the file-extensions
1127
#
1128
# ~    is for backupfiles from vi, emacs, joe, ...
1129
# .inc is often used for code includes which should in general not be part
1130
#      of the document-root
1131
url.access-deny             = ( "~", ".inc" )
1132

    
1133

    
1134
######### Options that are good to be but not neccesary to be changed #######
1135

    
1136
## bind to port (default: 80)
1137

    
1138
EOD;
1139

    
1140
	$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1141
	$lighty_config .= "server.port  = {$lighty_port}\n";
1142
	$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1143
	$lighty_config .= "\$SERVER[\"socket\"]  == \"[::]:{$lighty_port}\" { \n";
1144
	if($cert <> "" and $key <> "") {
1145
		$lighty_config .= "\n";
1146
		$lighty_config .= "## ssl configuration\n";
1147
		$lighty_config .= "ssl.engine = \"enable\"\n";
1148
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1149
		if($ca <> "")
1150
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1151
	}
1152
	$lighty_config .= " }\n";
1153

    
1154

    
1155
	$lighty_config .= <<<EOD
1156

    
1157
## error-handler for status 404
1158
#server.error-handler-404   = "/error-handler.html"
1159
#server.error-handler-404   = "/error-handler.php"
1160

    
1161
## to help the rc.scripts
1162
server.pid-file            = "{$g['varrun_path']}/{$pid_file}"
1163

    
1164
## virtual directory listings
1165
server.dir-listing         = "disable"
1166

    
1167
## enable debugging
1168
debug.log-request-header   = "disable"
1169
debug.log-response-header  = "disable"
1170
debug.log-request-handling = "disable"
1171
debug.log-file-not-found   = "disable"
1172

    
1173
# gzip compression
1174
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1175
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1176

    
1177
{$server_upload_dirs}
1178

    
1179
{$server_max_request_size}
1180

    
1181
{$fastcgi_config}
1182

    
1183
{$cgi_config}
1184

    
1185
{$captive_portal_mod_evasive}
1186

    
1187
expire.url = (
1188
				"" => "access 50 hours",	
1189
        )
1190

    
1191
EOD;
1192

    
1193
	$cert = str_replace("\r", "", $cert);
1194
	$key = str_replace("\r", "", $key);
1195
	$ca = str_replace("\r", "", $ca);
1196

    
1197
	$cert = str_replace("\n\n", "\n", $cert);
1198
	$key = str_replace("\n\n", "\n", $key);
1199
	$ca = str_replace("\n\n", "\n", $ca);
1200

    
1201
	if($cert <> "" and $key <> "") {
1202
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1203
		if (!$fd) {
1204
			printf(gettext("Error: cannot open cert.pem in system_webgui_start().%s"), "\n");
1205
			return 1;
1206
		}
1207
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1208
		fwrite($fd, $cert);
1209
		fwrite($fd, "\n");
1210
		fwrite($fd, $key);
1211
		fclose($fd);
1212
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
1213
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1214
			if (!$fd) {
1215
				printf(gettext("Error: cannot open ca.pem in system_webgui_start().%s"), "\n");
1216
				return 1;
1217
			}
1218
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1219
			fwrite($fd, $ca);
1220
			fclose($fd);
1221
		}
1222
		$lighty_config .= "\n";
1223
		$lighty_config .= "## " . gettext("ssl configuration") . "\n";
1224
		$lighty_config .= "ssl.engine = \"enable\"\n";
1225
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1226

    
1227
		// Harden SSL a bit for PCI conformance testing
1228
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
1229

    
1230
		/* Hifn accelerators do NOT work with the BEAST mitigation code. Do not allow it to be enabled if a Hifn card has been detected. */
1231
		$fd = @fopen("{$g['varlog_path']}/dmesg.boot", "r");
1232
		if ($fd) {
1233
			while (!feof($fd)) {
1234
				$dmesgl = fgets($fd);
1235
				if (preg_match("/^hifn.: (.*?),/", $dmesgl, $matches) && isset($config['system']['webgui']['beast_protection'])) {
1236
						unset($config['system']['webgui']['beast_protection']);
1237
						log_error("BEAST Protection disabled because a conflicting cryptographic accelerator card has been detected (" . $matches[1] . ")");
1238
					break;
1239
				}
1240
			}
1241
			fclose($fd);
1242
		}
1243

    
1244
		if (isset($config['system']['webgui']['beast_protection'])) {
1245
			$lighty_config .= "ssl.honor-cipher-order = \"enable\"\n";
1246
			$lighty_config .= "ssl.cipher-list = \"ECDHE-RSA-AES256-SHA384:AES256-SHA256:RC4-SHA:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM\"\n";
1247
		} else {
1248
			$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";
1249
		}
1250

    
1251
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1252
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1253
	}
1254

    
1255
	// Add HTTP to HTTPS redirect	
1256
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1257
		if($lighty_port != "443") 
1258
			$redirectport = ":{$lighty_port}";
1259
		$lighty_config .= <<<EOD
1260
\$SERVER["socket"] == ":80" {
1261
	\$HTTP["host"] =~ "(.*)" {
1262
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1263
	}
1264
}
1265
EOD;
1266
	}
1267

    
1268
	$fd = fopen("{$filename}", "w");
1269
	if (!$fd) {
1270
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1271
		return 1;
1272
	}
1273
	fwrite($fd, $lighty_config);
1274
	fclose($fd);
1275

    
1276
	return 0;
1277

    
1278
}
1279

    
1280
function system_timezone_configure() {
1281
	global $config, $g;
1282
	if(isset($config['system']['developerspew'])) {
1283
		$mt = microtime();
1284
		echo "system_timezone_configure() being called $mt\n";
1285
	}
1286

    
1287
	$syscfg = $config['system'];
1288

    
1289
	if ($g['booting'])
1290
		echo gettext("Setting timezone...");
1291

    
1292
	/* extract appropriate timezone file */
1293
	$timezone = $syscfg['timezone'];
1294
	if ($timezone) {
1295
		exec('/usr/bin/tar -tvzf /usr/share/zoneinfo.tgz', $tzs);
1296
		foreach ($tzs as $tz) {
1297
			if (preg_match(",{$timezone}$,", $tz))
1298
				break;
1299
			if (preg_match(",{$timezone} link to *(.*)$,", $tz, $matches)) {
1300
				$timezone = $matches[1];
1301
				break;
1302
			}
1303
		}
1304
	} else
1305
		$timezone = "Etc/UTC";
1306

    
1307
	conf_mount_rw();
1308

    
1309
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1310
		escapeshellarg($timezone) . " > /etc/localtime");
1311

    
1312
	mwexec("sync");
1313
	conf_mount_ro();
1314

    
1315
	if ($g['booting'])
1316
		echo gettext("done.") . "\n";
1317
}
1318

    
1319
function system_ntp_setup_gps($serialport) {
1320
	global $config, $g;
1321
	$gps_device = '/dev/gps0';
1322
	$serialport = '/dev/'.$serialport;
1323

    
1324
	if (!file_exists($serialport))
1325
		return false;
1326

    
1327
	conf_mount_rw();
1328
	// Create symlink that ntpd requires
1329
	unlink_if_exists($gps_device);
1330
	symlink($serialport, $gps_device);
1331

    
1332
	/* Send the following to the GPS port to initialize the GPS */
1333
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
1334
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
1335
	}else{
1336
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1337
	}
1338

    
1339
	/* XXX: Why not file_put_contents to the device */
1340
	@file_put_contents('/tmp/gps.init', $gps_init);
1341
	`cat /tmp/gps.init > $serialport`;
1342

    
1343
	/* Add /etc/remote entry in case we need to read from the GPS with tip */
1344
	if (intval(`grep -c '^gps0' /etc/remote`) == 0) {
1345
		$gpsbaud = '4800';
1346
		if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['speed'])) {
1347
			switch($config['ntpd']['gps']['speed']) {
1348
				case '16':
1349
					$gpsbaud = '9600';
1350
					break;
1351
				case '32':
1352
					$gpsbaud = '19200';
1353
					break;
1354
				case '48':
1355
					$gpsbaud = '38400';
1356
					break;
1357
				case '64':
1358
					$gpsbaud = '57600';
1359
					break;
1360
				case '80':
1361
					$gpsbaud = '115200';
1362
					break;
1363
			}
1364
		}
1365
		@file_put_contents("/etc/remote", "gps0:dv={$serialport}:br#{$gpsbaud}:pa=none:", FILE_APPEND);
1366
	}
1367

    
1368
	conf_mount_ro();
1369

    
1370
	return true;
1371
}
1372

    
1373
function system_ntp_setup_pps($serialport) {
1374
	global $config, $g;
1375

    
1376
	$pps_device = '/dev/pps0';
1377
	$serialport = '/dev/'.$serialport;
1378

    
1379
	if (!file_exists($serialport))
1380
		return false;
1381

    
1382
	conf_mount_rw();
1383
	// Create symlink that ntpd requires
1384
	unlink_if_exists($pps_device);
1385
	@symlink($serialport, $pps_device);
1386

    
1387
	conf_mount_ro();
1388

    
1389
	return true;
1390
}
1391

    
1392

    
1393
function system_ntp_configure($start_ntpd=true) {
1394
	global $config, $g;
1395

    
1396
	$driftfile = "/var/db/ntpd.drift";
1397
	$statsdir = "/var/log/ntp";
1398
	$gps_device = '/dev/gps0';
1399

    
1400
	if ($g['platform'] == 'jail')
1401
		return;
1402

    
1403
	safe_mkdir($statsdir);
1404

    
1405
	if (!is_array($config['ntpd']))
1406
		$config['ntpd'] = array();
1407

    
1408
	$ntpcfg = "# \n";
1409
	$ntpcfg .= "# pfSense ntp configuration file \n";
1410
	$ntpcfg .= "# \n\n";
1411
	$ntpcfg .= "tinker panic 0 \n";
1412

    
1413
	/* Add Orphan mode */
1414
	$ntpcfg .= "# Orphan mode stratum\n";
1415
	$ntpcfg .= 'tos orphan ';
1416
	if (!empty($config['ntpd']['orphan'])) {
1417
		$ntpcfg .= $config['ntpd']['orphan'];
1418
	}else{
1419
		$ntpcfg .= '12';
1420
	}
1421
	$ntpcfg .= "\n";
1422

    
1423
	/* Add PPS configuration */
1424
	if (!empty($config['ntpd']['pps'])
1425
		&& file_exists('/dev/'.$config['ntpd']['pps']['port'])
1426
		&& system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
1427
		$ntpcfg .= "\n";
1428
		$ntpcfg .= "# PPS Setup\n";
1429
		$ntpcfg .= 'server 127.127.22.0';
1430
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1431
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
1432
			$ntpcfg .= ' prefer'; 
1433
		}
1434
		if (!empty($config['ntpd']['pps']['noselect'])) {
1435
			$ntpcfg .= ' noselect ';
1436
		}
1437
		$ntpcfg .= "\n";
1438
		$ntpcfg .= 'fudge 127.127.22.0';
1439
		if (!empty($config['ntpd']['pps']['fudge1'])) {
1440
			$ntpcfg .= ' time1 ';
1441
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
1442
		}
1443
		if (!empty($config['ntpd']['pps']['flag2'])) {
1444
			$ntpcfg .= ' flag2 1';
1445
		}
1446
		if (!empty($config['ntpd']['pps']['flag3'])) {
1447
			$ntpcfg .= ' flag3 1';
1448
		}else{
1449
			$ntpcfg .= ' flag3 0';
1450
		}
1451
		if (!empty($config['ntpd']['pps']['flag4'])) {
1452
			$ntpcfg .= ' flag4 1';
1453
		}
1454
		if (!empty($config['ntpd']['pps']['refid'])) {
1455
			$ntpcfg .= ' refid ';
1456
			$ntpcfg .= $config['ntpd']['pps']['refid'];
1457
		}
1458
		$ntpcfg .= "\n";
1459
	}
1460
	/* End PPS configuration */
1461

    
1462
	/* Add GPS configuration */
1463
	if (!empty($config['ntpd']['gps'])
1464
		&& file_exists('/dev/'.$config['ntpd']['gps']['port'])
1465
		&& system_ntp_setup_gps($config['ntpd']['gps']['port'])) {
1466
		$ntpcfg .= "\n";
1467
		$ntpcfg .= "# GPS Setup\n";
1468
		$ntpcfg .= 'server 127.127.20.0 mode ';
1469
		if (!empty($config['ntpd']['gps']['nmea']) || !empty($config['ntpd']['gps']['speed']) || !empty($config['ntpd']['gps']['subsec'])) {
1470
			if (!empty($config['ntpd']['gps']['nmea'])) {
1471
				$ntpmode = (int) $config['ntpd']['gps']['nmea'];
1472
			}
1473
			if (!empty($config['ntpd']['gps']['speed'])) {
1474
				$ntpmode += (int) $config['ntpd']['gps']['speed'];
1475
			}
1476
			if (!empty($config['ntpd']['gps']['subsec'])) {
1477
				$ntpmode += 128;
1478
			}
1479
			$ntpcfg .= (string) $ntpmode;
1480
		}else{
1481
			$ntpcfg .= '0';
1482
		}
1483
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1484
		if (empty($config['ntpd']['gps']['prefer'])) { /*note: this one works backwards */
1485
			$ntpcfg .= ' prefer'; 
1486
		}
1487
		if (!empty($config['ntpd']['gps']['noselect'])) {
1488
			$ntpcfg .= ' noselect ';
1489
		}
1490
		$ntpcfg .= "\n";
1491
		$ntpcfg .= 'fudge 127.127.20.0';
1492
		if (!empty($config['ntpd']['gps']['fudge1'])) {
1493
			$ntpcfg .= ' time1 ';
1494
			$ntpcfg .= $config['ntpd']['gps']['fudge1'];
1495
		}
1496
		if (!empty($config['ntpd']['gps']['fudge2'])) {
1497
			$ntpcfg .= ' time2 ';
1498
			$ntpcfg .= $config['ntpd']['gps']['fudge2'];
1499
		}
1500
		if (!empty($config['ntpd']['gps']['flag1'])) {
1501
			$ntpcfg .= ' flag1 1';
1502
		}else{
1503
			$ntpcfg .= ' flag1 0';
1504
		}
1505
		if (!empty($config['ntpd']['gps']['flag2'])) {
1506
			$ntpcfg .= ' flag2 1';
1507
		}
1508
		if (!empty($config['ntpd']['gps']['flag3'])) {
1509
			$ntpcfg .= ' flag3 1';
1510
		}else{
1511
			$ntpcfg .= ' flag3 0';
1512
		}
1513
		if (!empty($config['ntpd']['gps']['flag4'])) {
1514
			$ntpcfg .= ' flag4 1';
1515
		}
1516
		if (!empty($config['ntpd']['gps']['refid'])) {
1517
			$ntpcfg .= ' refid ';
1518
			$ntpcfg .= $config['ntpd']['gps']['refid'];
1519
		}
1520
		$ntpcfg .= "\n";
1521
	}elseif (!empty($config['ntpd']['gpsport'])
1522
		&& file_exists('/dev/'.$config['ntpd']['gpsport'])
1523
		&& system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1524
		/* This handles a 2.1 and earlier config */
1525
		$ntpcfg .= "# GPS Setup\n";
1526
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1527
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1528
		// Fall back to local clock if GPS is out of sync?
1529
		$ntpcfg .= "server 127.127.1.0\n";
1530
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1531
	}
1532
	/* End GPS configuration */
1533
	
1534
	$ntpcfg .= "\n\n# Upstream Servers\n";
1535
	/* foreach through ntp servers and write out to ntpd.conf */
1536
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1537
		$ntpcfg .= "server {$ts} iburst maxpoll 9";
1538
		if (substr_count($config['ntpd']['prefer'], $ts)) $ntpcfg .= ' prefer';
1539
		if (substr_count($config['ntpd']['noselect'], $ts)) $ntpcfg .= ' noselect';
1540
		$ntpcfg .= "\n";
1541
	}
1542
	unset($ts);
1543

    
1544
	$ntpcfg .= "\n\n";
1545
	$ntpcfg .= "disable monitor\n"; //prevent NTP reflection attack, see http://forum.pfsense.org/index.php/topic,67189.msg389132.html#msg389132
1546
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
1547
		$ntpcfg .= "enable stats\n";
1548
		$ntpcfg .= 'statistics';
1549
		if (!empty($config['ntpd']['clockstats'])) {
1550
			$ntpcfg .= ' clockstats';
1551
		}
1552
		if (!empty($config['ntpd']['loopstats'])) {
1553
			$ntpcfg .= ' loopstats';
1554
		}
1555
		if (!empty($config['ntpd']['peerstats'])) {
1556
			$ntpcfg .= ' peerstats';
1557
		}
1558
		$ntpcfg .= "\n";
1559
	}
1560
	$ntpcfg .= "statsdir {$statsdir}\n";
1561
	$ntpcfg .= 'logconfig =syncall +clockall';
1562
	if (!empty($config['ntpd']['logpeer'])) {
1563
		$ntpcfg .= ' +peerall';
1564
	}
1565
	if (!empty($config['ntpd']['logsys'])) {
1566
		$ntpcfg .= ' +sysall';
1567
	}
1568
	$ntpcfg .= "\n";
1569
	$ntpcfg .= "driftfile {$driftfile}\n";
1570
	/* Access restrictions */
1571
	$ntpcfg .= 'restrict default';
1572
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1573
		$ntpcfg .= ' kod limited'; 
1574
	}
1575
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1576
		$ntpcfg .= ' nomodify'; 
1577
	}
1578
	if (!empty($config['ntpd']['noquery'])) {
1579
		$ntpcfg .= ' noquery';
1580
	}
1581
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1582
		$ntpcfg .= ' nopeer'; 
1583
	}
1584
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1585
		$ntpcfg .= ' notrap'; 
1586
	}
1587
	if (!empty($config['ntpd']['noserve'])) {
1588
		$ntpcfg .= ' noserve';
1589
	}
1590
	$ntpcfg .= "\nrestrict -6 default";
1591
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1592
		$ntpcfg .= ' kod limited'; 
1593
	}
1594
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1595
		$ntpcfg .= ' nomodify'; 
1596
	}
1597
	if (!empty($config['ntpd']['noquery'])) {
1598
		$ntpcfg .= ' noquery';
1599
	}
1600
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1601
		$ntpcfg .= ' nopeer'; 
1602
	}
1603
	if (!empty($config['ntpd']['noserve'])) {
1604
		$ntpcfg .= ' noserve';
1605
	}
1606
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1607
		$ntpcfg .= ' notrap'; 
1608
	}
1609
	$ntpcfg .= "\n";
1610

    
1611
	/* A leapseconds file is really only useful if this clock is stratum 1 */
1612
	$ntpcfg .= "\n";
1613
	if (!empty($config['ntpd']['leapsec'])) {
1614
		$leapsec .= base64_decode($config['ntpd']['leapsec']);
1615
		file_put_contents('/var/db/leap-seconds', $leapsec);
1616
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
1617
	}
1618
	
1619

    
1620
	if (empty($config['ntpd']['interface']))
1621
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface']))
1622
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1623
		else
1624
			$interfaces = array();
1625
	else
1626
		$interfaces = explode(",", $config['ntpd']['interface']);
1627

    
1628
	if (is_array($interfaces) && count($interfaces)) {
1629
		$ntpcfg .= "interface ignore all\n";
1630
		foreach ($interfaces as $interface) {
1631
			if (!is_ipaddr($interface)) {
1632
				$interface = get_real_interface($interface);
1633
			}
1634
			$ntpcfg .= "interface listen {$interface}\n";
1635
		}
1636
	}
1637

    
1638
	/* open configuration for wrting or bail */
1639
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
1640
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1641
		return;
1642
	}
1643

    
1644
	/* At bootup we just want to write out the config. */
1645
	if (!$start_ntpd)
1646
		return;
1647

    
1648
	/* if ntpd is running, kill it */
1649
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1650
		killbypid("{$g['varrun_path']}/ntpd.pid");
1651
	}
1652
	@unlink("{$g['varrun_path']}/ntpd.pid");
1653

    
1654
	/* if /var/empty does not exist, create it */
1655
	if(!is_dir("/var/empty"))
1656
		mkdir("/var/empty", 0775, true);
1657

    
1658
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1659
	mwexec("/usr/local/sbin/ntpd -g -c {$g['varetc_path']}/ntpd.conf -p {$g['varrun_path']}/ntpd.pid", false, true);
1660
	
1661
	// Note that we are starting up
1662
	log_error("NTPD is starting up.");
1663
	return;
1664
}
1665

    
1666
function sync_system_time() {
1667
	global $config, $g;
1668

    
1669
	if ($g['booting'])
1670
		echo gettext("Syncing system time before startup...");
1671

    
1672
	/* foreach through servers and write out to ntpd.conf */
1673
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1674
		mwexec("/usr/local/sbin/ntpdate -s $ts");
1675
	}
1676
	
1677
	if ($g['booting'])
1678
		echo gettext("done.") . "\n";
1679
	
1680
}
1681

    
1682
function system_halt() {
1683
	global $g;
1684

    
1685
	system_reboot_cleanup();
1686

    
1687
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1688
}
1689

    
1690
function system_reboot() {
1691
	global $g;
1692

    
1693
	system_reboot_cleanup();
1694

    
1695
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1696
}
1697

    
1698
function system_reboot_sync() {
1699
	global $g;
1700

    
1701
	system_reboot_cleanup();
1702

    
1703
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1704
}
1705

    
1706
function system_reboot_cleanup() {
1707
	global $config, $cpzone;
1708

    
1709
	mwexec("/usr/local/bin/beep.sh stop");
1710
	require_once("captiveportal.inc");
1711
	if (is_array($config['captiveportal'])) {
1712
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
1713
			captiveportal_radius_stop_all();
1714
			captiveportal_send_server_accounting(true);
1715
		}
1716
	}
1717
	require_once("voucher.inc");
1718
	voucher_save_db_to_config();
1719
	require_once("pkg-utils.inc");
1720
	stop_packages();
1721
}
1722

    
1723
function system_do_shell_commands($early = 0) {
1724
	global $config, $g;
1725
	if(isset($config['system']['developerspew'])) {
1726
		$mt = microtime();
1727
		echo "system_do_shell_commands() being called $mt\n";
1728
	}
1729

    
1730
	if ($early)
1731
		$cmdn = "earlyshellcmd";
1732
	else
1733
		$cmdn = "shellcmd";
1734

    
1735
	if (is_array($config['system'][$cmdn])) {
1736

    
1737
		/* *cmd is an array, loop through */
1738
		foreach ($config['system'][$cmdn] as $cmd) {
1739
			exec($cmd);
1740
		}
1741

    
1742
	} elseif($config['system'][$cmdn] <> "") {
1743

    
1744
		/* execute single item */
1745
		exec($config['system'][$cmdn]);
1746

    
1747
	}
1748
}
1749

    
1750
function system_console_configure() {
1751
	global $config, $g;
1752
	if(isset($config['system']['developerspew'])) {
1753
		$mt = microtime();
1754
		echo "system_console_configure() being called $mt\n";
1755
	}
1756

    
1757
	if (isset($config['system']['disableconsolemenu'])) {
1758
		touch("{$g['varetc_path']}/disableconsole");
1759
	} else {
1760
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1761
	}
1762
}
1763

    
1764
function system_dmesg_save() {
1765
	global $g;
1766
	if(isset($config['system']['developerspew'])) {
1767
		$mt = microtime();
1768
		echo "system_dmesg_save() being called $mt\n";
1769
	}
1770

    
1771
	$dmesg = "";
1772
	exec("/sbin/dmesg", $dmesg);
1773

    
1774
	/* find last copyright line (output from previous boots may be present) */
1775
	$lastcpline = 0;
1776

    
1777
	for ($i = 0; $i < count($dmesg); $i++) {
1778
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1779
			$lastcpline = $i;
1780
	}
1781

    
1782
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1783
	if (!$fd) {
1784
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1785
		return 1;
1786
	}
1787

    
1788
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1789
		fwrite($fd, $dmesg[$i] . "\n");
1790

    
1791
	fclose($fd);
1792

    
1793
	return 0;
1794
}
1795

    
1796
function system_set_harddisk_standby() {
1797
	global $g, $config;
1798
	if(isset($config['system']['developerspew'])) {
1799
		$mt = microtime();
1800
		echo "system_set_harddisk_standby() being called $mt\n";
1801
	}
1802

    
1803
	if (isset($config['system']['harddiskstandby'])) {
1804
		if ($g['booting']) {
1805
			echo gettext('Setting hard disk standby... ');
1806
		}
1807

    
1808
		$standby = $config['system']['harddiskstandby'];
1809
		// Check for a numeric value
1810
		if (is_numeric($standby)) {
1811
			// Sync the disk(s)
1812
			pfSense_sync();
1813
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1814
				// Reinitialize ATA-drives
1815
				mwexec('/usr/local/sbin/atareinit');
1816
				if ($g['booting']) {
1817
					echo gettext("done.") . "\n";
1818
				}
1819
			} else if ($g['booting']) {
1820
				echo gettext("failed!") . "\n";
1821
			}
1822
		} else if ($g['booting']) {
1823
			echo gettext("failed!") . "\n";
1824
		}
1825
	}
1826
}
1827

    
1828
function system_setup_sysctl() {
1829
	global $config;
1830
	if(isset($config['system']['developerspew'])) {
1831
		$mt = microtime();
1832
		echo "system_setup_sysctl() being called $mt\n";
1833
	}
1834

    
1835
	activate_sysctls();	
1836

    
1837
	if (isset($config['system']['sharednet'])) {
1838
		system_disable_arp_wrong_if();
1839
	}
1840
}
1841

    
1842
function system_disable_arp_wrong_if() {
1843
	global $config;
1844
	if(isset($config['system']['developerspew'])) {
1845
		$mt = microtime();
1846
		echo "system_disable_arp_wrong_if() being called $mt\n";
1847
	}
1848
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1849
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1850
}
1851

    
1852
function system_enable_arp_wrong_if() {
1853
	global $config;
1854
	if(isset($config['system']['developerspew'])) {
1855
		$mt = microtime();
1856
		echo "system_enable_arp_wrong_if() being called $mt\n";
1857
	}
1858
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1859
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1860
}
1861

    
1862
function enable_watchdog() {
1863
	global $config;
1864
	return;
1865
	$install_watchdog = false;
1866
	$supported_watchdogs = array("Geode");
1867
	$file = file_get_contents("/var/log/dmesg.boot");
1868
	foreach($supported_watchdogs as $sd) {
1869
		if(stristr($file, "Geode")) {
1870
			$install_watchdog = true;
1871
		}
1872
	}
1873
	if($install_watchdog == true) {
1874
		if(is_process_running("watchdogd"))
1875
			mwexec("/usr/bin/killall watchdogd", true);
1876
		exec("/usr/sbin/watchdogd");
1877
	}
1878
}
1879

    
1880
function system_check_reset_button() {
1881
	global $g;
1882
	if($g['platform'] != "nanobsd")
1883
		return 0;
1884

    
1885
	$specplatform = system_identify_specific_platform();
1886

    
1887
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1888
		return 0;
1889

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

    
1892
	if ($retval == 99) {
1893
		/* user has pressed reset button for 2 seconds - 
1894
		   reset to factory defaults */
1895
		echo <<<EOD
1896

    
1897
***********************************************************************
1898
* Reset button pressed - resetting configuration to factory defaults. *
1899
* The system will reboot after this completes.                        *
1900
***********************************************************************
1901

    
1902

    
1903
EOD;
1904
		
1905
		reset_factory_defaults();
1906
		system_reboot_sync();
1907
		exit(0);
1908
	}
1909

    
1910
	return 0;
1911
}
1912

    
1913
/* attempt to identify the specific platform (for embedded systems)
1914
   Returns an array with two elements:
1915
	name => platform string (e.g. 'wrap', 'alix' etc.)
1916
	descr => human-readable description (e.g. "PC Engines WRAP")
1917
*/
1918
function system_identify_specific_platform() {
1919
	global $g;
1920
	
1921
	if ($g['platform'] == 'generic-pc')
1922
		return array('name' => 'generic-pc', 'descr' => gettext("Generic PC"));
1923
	
1924
	if ($g['platform'] == 'generic-pc-cdrom')
1925
		return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)"));
1926
	
1927
	/* the rest of the code only deals with 'embedded' platforms */
1928
	if ($g['platform'] != 'nanobsd')
1929
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1930
	
1931
	$dmesg = system_get_dmesg_boot();
1932
	
1933
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1934
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
1935
	
1936
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1937
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
1938

    
1939
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1940
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1941
	
1942
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1943
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1944
		
1945
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1946
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1947
	
1948
	/* unknown embedded platform */
1949
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
1950
}
1951

    
1952
function system_get_dmesg_boot() {
1953
	global $g;
1954
		
1955
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1956
}
1957

    
1958
function get_possible_listen_ips($include_ipv6_link_local=false) {
1959
	$interfaces = get_configured_interface_with_descr();
1960
	$carplist = get_configured_carp_interface_list();
1961
	$listenips = array();
1962
	foreach ($carplist as $cif => $carpip)
1963
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1964
	$aliaslist = get_configured_ip_aliases_list();
1965
	foreach ($aliaslist as $aliasip => $aliasif)
1966
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1967
	foreach ($interfaces as $iface => $ifacename) {
1968
		$tmp["name"]  = $ifacename;
1969
		$tmp["value"] = $iface;
1970
		$listenips[] = $tmp;
1971
		if ($include_ipv6_link_local) {
1972
			$llip = find_interface_ipv6_ll(get_real_interface($iface));
1973
			if (!empty($llip)) {
1974
				$tmp["name"]  = "{$ifacename} IPv6 Link-Local";
1975
				$tmp["value"] = $llip;
1976
				$listenips[] = $tmp;
1977
			}
1978
		}
1979
	}
1980
	$tmp["name"]  = "Localhost";
1981
	$tmp["value"] = "lo0";
1982
	$listenips[] = $tmp;
1983
	return $listenips;
1984
}
1985

    
1986
function get_possible_traffic_source_addresses($include_ipv6_link_local=false) {
1987
	global $config;
1988
	$sourceips = get_possible_listen_ips($include_ipv6_link_local);
1989
	foreach (array('server', 'client') as $mode) {
1990
		if (is_array($config['openvpn']["openvpn-{$mode}"])) {
1991
			foreach ($config['openvpn']["openvpn-{$mode}"] as $id => $setting) {
1992
				if (!isset($setting['disable'])) {
1993
					$vpn = array();
1994
					$vpn['value'] = 'ovpn' . substr($mode, 0, 1) . $setting['vpnid'];
1995
					$vpn['name'] = gettext("OpenVPN") . " ".$mode.": ".htmlspecialchars($setting['description']);
1996
					$sourceips[] = $vpn;
1997
				}
1998
			}
1999
		}
2000
	}
2001
	return $sourceips;
2002
}
2003
?>
(52-52/67)