Project

General

Profile

Download (62.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/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
			/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
345
			if (is_process_running("dhcpleases"))
346
				mwexec('/bin/pkill dhcpleases');
347
			@unlink("{$g['varrun_path']}/dhcpleases.pid");
348
			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");
349
		}
350
	} else {
351
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
352
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
353
	}
354
}
355

    
356
function system_hostname_configure() {
357
	global $config, $g;
358
	if(isset($config['system']['developerspew'])) {
359
		$mt = microtime();
360
		echo "system_hostname_configure() being called $mt\n";
361
	}
362

    
363
	$syscfg = $config['system'];
364

    
365
	/* set hostname */
366
	$status = mwexec("/bin/hostname " .
367
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
368

    
369
    /* Setup host GUID ID.  This is used by ZFS. */
370
	mwexec("/etc/rc.d/hostid start");
371

    
372
	return $status;
373
}
374

    
375
function system_routing_configure($interface = "") {
376
	global $config, $g;
377
	if ($g['platform'] == 'jail')
378
		return;
379
	if(isset($config['system']['developerspew'])) {
380
		$mt = microtime();
381
		echo "system_routing_configure() being called $mt\n";
382
	}
383

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

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

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

    
468
	system_staticroutes_configure($interface, false);
469

    
470
	return 0;
471
}
472

    
473
function system_staticroutes_configure($interface = "", $update_dns = false) {
474
	global $config, $g, $aliastable;
475

    
476
	$filterdns_list = array();
477

    
478
	$static_routes = get_staticroutes(false, true);
479
	if (count($static_routes)) {
480
		$gateways_arr = return_gateways_array(false, true);
481

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

    
491
			$gatewayip = $gateway['gateway'];
492
			$interfacegw = $gateway['interface'];
493

    
494
			$blackhole = "";
495
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 3)))
496
				$blackhole = "-blackhole";
497

    
498
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network']))
499
				continue;
500

    
501
			$dnscache = array();
502
			if ($update_dns === true) {
503
				if (is_subnet($rtent['network']))
504
					continue;
505
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
506
				if (empty($dnscache))
507
					continue;
508
			}
509

    
510
			if (is_subnet($rtent['network']))
511
				$ips = array($rtent['network']);
512
			else {
513
				if (!isset($rtent['disabled']))
514
					$filterdns_list[] = $rtent['network'];
515
				$ips = add_hostname_to_watch($rtent['network']);
516
			}
517

    
518
			foreach ($dnscache as $ip) {
519
				if (in_array($ip, $ips))
520
					continue;
521
				mwexec("/sbin/route delete " . escapeshellarg($ip), true);
522
			}
523

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

    
531
			foreach ($ips as $ip) {
532
				if (is_ipaddrv4($ip))
533
					$ip .= "/32";
534
				else if (is_ipaddrv6($ip))
535
					$ip .= "/128";
536

    
537
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
538

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

    
541
				if (is_subnet($ip))
542
					if (is_ipaddr($gatewayip))
543
						mwexec($cmd . escapeshellarg($gatewayip));
544
					else if (!empty($interfacegw))
545
						mwexec($cmd . "-iface " . escapeshellarg($interfacegw));
546
			}
547
		}
548
		unset($gateways_arr);
549
	}
550
	unset($static_routes);
551

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

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

    
573
	return 0;
574
}
575

    
576
function system_routing_enable() {
577
	global $config, $g;
578
	if(isset($config['system']['developerspew'])) {
579
		$mt = microtime();
580
		echo "system_routing_enable() being called $mt\n";
581
	}
582

    
583
	mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
584
	mwexec("/sbin/sysctl net.inet6.ip6.forwarding=1");
585
	return;
586
}
587

    
588
function system_syslogd_fixup_server($server) {
589
	/* If it's an IPv6 IP alone, encase it in brackets */
590
	if (is_ipaddrv6($server))
591
		return "[$server]";
592
	else
593
		return $server;
594
}
595

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

    
611
function system_syslogd_start() {
612
	global $config, $g;
613
	if(isset($config['system']['developerspew'])) {
614
		$mt = microtime();
615
		echo "system_syslogd_start() being called $mt\n";
616
	}
617

    
618
	mwexec("/etc/rc.d/hostid start");
619

    
620
	$syslogcfg = $config['syslog'];
621

    
622
	if ($g['booting'])
623
		echo gettext("Starting syslog...");
624
	else
625
		killbypid("{$g['varrun_path']}/syslog.pid");
626

    
627
	if (is_process_running("syslogd"))
628
		mwexec('/bin/pkill syslogd');
629
	if (is_process_running("fifolog_writer"))
630
		mwexec('/bin/pkill fifolog_writer');
631

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

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

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

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

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

    
680
		$syslogconf .= "!l2tps\n";
681
		if (!isset($syslogcfg['disablelocallogging'])) 
682
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/l2tps.log\n";
683

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

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

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

    
702
		$syslogconf .= "!dnsmasq,filterdns,unbound\n";
703
		if (!isset($syslogcfg['disablelocallogging']))
704
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
705
		if (isset($syslogcfg['apinger']))
706
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
707

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

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

    
720
		$syslogconf .= "!hostapd\n";
721
		if (!isset($syslogcfg['disablelocallogging']))
722
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
723
		if (isset($syslogcfg['hostapd']))
724
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
725

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

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

    
763
		if (isset($syslogcfg['zmqserver'])) {
764
				$syslogconf .= <<<EOD
765
*.*								^{$syslogcfg['zmqserver']}
766

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

    
777
		// Ensure that the log directory exists
778
		if (!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
779
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
780

    
781
		$sourceip = "";
782
		if (!empty($syslogcfg['sourceip'])) {
783
			if ($syslogcfg['ipproto'] == "ipv6") {
784
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
785
				if (!is_ipaddr($ifaddr))
786
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
787
			} else {
788
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
789
				if (!is_ipaddr($ifaddr))
790
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
791
			}
792
			if (is_ipaddr($ifaddr)) {
793
				$sourceip = "-b {$ifaddr}";
794
			}
795
		}
796

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

    
799
	} else {
800
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c -l {$g['dhcpd_chroot_path']}/var/run/log");
801
	}
802

    
803
	if ($g['booting'])
804
		echo gettext("done.") . "\n";
805

    
806
	return $retval;
807
}
808

    
809
function system_webgui_start() {
810
	global $config, $g;
811

    
812
	if ($g['booting'])
813
		echo gettext("Starting webConfigurator...");
814

    
815
	chdir($g['www_path']);
816

    
817
	/* defaults */
818
	$portarg = "80";
819
	$crt = "";
820
	$key = "";
821
	$ca = "";
822

    
823
	/* non-standard port? */
824
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
825
		$portarg = "{$config['system']['webgui']['port']}";
826

    
827
	if ($config['system']['webgui']['protocol'] == "https") {
828
		// Ensure that we have a webConfigurator CERT
829
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
830
		if(!is_array($cert) && !$cert['crt'] && !$cert['prv']) {
831
			if (!is_array($config['ca']))
832
				$config['ca'] = array();
833
			$a_ca =& $config['ca'];
834
			if (!is_array($config['cert']))
835
				$config['cert'] = array();
836
			$a_cert =& $config['cert'];
837
			log_error("Creating SSL Certificate for this host");
838
			$cert = array();
839
			$cert['refid'] = uniqid();
840
			$cert['descr'] = gettext("webConfigurator default");
841
			mwexec("/usr/bin/openssl genrsa 1024 > {$g['tmp_path']}/ssl.key");
842
			mwexec("/usr/bin/openssl req -new -x509 -nodes -sha256 -days 2000 -key {$g['tmp_path']}/ssl.key > {$g['tmp_path']}/ssl.crt");
843
			$crt = file_get_contents("{$g['tmp_path']}/ssl.crt");
844
			$key = file_get_contents("{$g['tmp_path']}/ssl.key");
845
			unlink("{$g['tmp_path']}/ssl.key");
846
			unlink("{$g['tmp_path']}/ssl.crt");
847
			cert_import($cert, $crt, $key);
848
			$a_cert[] = $cert;
849
			$config['system']['webgui']['ssl-certref'] = $cert['refid'];
850
			write_config(gettext("Importing HTTPS certificate"));
851
			if(!$config['system']['webgui']['port'])
852
				$portarg = "443";
853
			$ca = ca_chain($cert);
854
		} else {
855
			$crt = base64_decode($cert['crt']);
856
			$key = base64_decode($cert['prv']);
857
			if(!$config['system']['webgui']['port'])
858
				$portarg = "443";
859
			$ca = ca_chain($cert);
860
		}
861
	}
862

    
863
	/* generate lighttpd configuration */
864
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
865
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
866
		"cert.pem", "ca.pem");
867

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

    
871
	sleep(1);
872

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

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

    
878
	if ($g['booting']) {
879
		if ($res == 0)
880
			echo gettext("done.") . "\n";
881
		else
882
			echo gettext("failed!") . "\n";
883
	}
884

    
885
	return $res;
886
}
887

    
888
function system_generate_lighty_config($filename,
889
	$cert,
890
	$key,
891
	$ca,
892
	$pid_file,
893
	$port = 80,
894
	$document_root = "/usr/local/www/",
895
	$cert_location = "cert.pem",
896
	$ca_location = "ca.pem",
897
	$captive_portal = false) {
898

    
899
	global $config, $g;
900

    
901
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
902
		mkdir("{$g['tmp_path']}/lighttpdcompress");
903

    
904
	if(isset($config['system']['developerspew'])) {
905
		$mt = microtime();
906
		echo "system_generate_lighty_config() being called $mt\n";
907
	}
908

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

    
913
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
914
		if (empty($maxprocperip))
915
			$maxprocperip = 10;
916
		$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
917

    
918
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
919
		if(!is_dir("{$g['tmp_path']}/captiveportal"))
920
			@mkdir("{$g['tmp_path']}/captiveportal", 0555);
921
		$server_max_request_size = "server.max-request-size    = 384";
922
		$cgi_config = "";
923
	} else {
924
		$captiveportal = ",\"mod_cgi\"";
925
		$captive_portal_rewrite = "";
926
		$captive_portal_mod_evasive = "";
927
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
928
		$server_max_request_size = "server.max-request-size    = 2097152";
929
		$cgi_config = "cgi.assign                 = ( \".cgi\" => \"\" )";
930
	}
931
	
932
	if (empty($port))
933
		$lighty_port = "80";
934
	else
935
		$lighty_port = $port;
936

    
937
	$memory = get_memory();
938
	$realmem = $memory[1];
939

    
940
	// Determine web GUI process settings and take into account low memory systems
941
	if ($realmem < 255)
942
		$max_procs = 1;
943
	else
944
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
945

    
946
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM 
947
	if ($captive_portal !== false)  {
948
		if ($realmem > 135 and $realmem < 256) {
949
			$max_procs += 1; // 2 worker processes
950
		} else if ($realmem > 255 and $realmem < 513) {
951
			$max_procs += 2; // 3 worker processes
952
		} else if ($realmem > 512) {
953
			$max_procs += 4; // 6 worker processes
954
		}
955
		if ($max_procs > 1)
956
			$max_php_children = intval($max_procs/2);
957
		else
958
			$max_php_children = 1;
959

    
960
	} else {
961
		if ($realmem < 78)
962
			$max_php_children = 0;
963
		else
964
			$max_php_children = 1;
965
	}
966

    
967
	if(!isset($config['syslog']['nologlighttpd'])) {
968
		$lighty_use_syslog = <<<EOD
969
## where to send error-messages to
970
server.errorlog-use-syslog="enable"
971
EOD;
972
	}
973

    
974

    
975
	if ($captive_portal !== false) {
976
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi-{$captive_portal}.socket";
977
		$fastcgi_config = <<<EOD
978
#### fastcgi module
979
## read fastcgi.txt for more info
980
fastcgi.server = ( ".php" =>
981
	( "localhost" =>
982
		(
983
			"socket" => "{$fast_cgi_path}",
984
			"max-procs" => {$max_procs},
985
			"bin-environment" => (
986
				"PHP_FCGI_CHILDREN" => "{$max_php_children}",
987
				"PHP_FCGI_MAX_REQUESTS" => "500"
988
			),
989
			"bin-path" => "/usr/local/bin/php"
990
		)
991
	)
992
)
993

    
994
EOD;
995
	} else {
996
		$fast_cgi_path = "{$g['varrun_path']}/php-fpm.socket";
997
		$fastcgi_config = <<<EOD
998
#### fastcgi module
999
## read fastcgi.txt for more info
1000
fastcgi.server = ( ".php" =>
1001
	( "localhost" =>
1002
		(
1003
			"socket" => "{$fast_cgi_path}",
1004
			"broken-scriptfilename" => "enable"
1005
		)
1006
	)
1007
)
1008

    
1009
EOD;
1010
	}
1011

    
1012

    
1013
	$lighty_config = <<<EOD
1014
#
1015
# lighttpd configuration file
1016
#
1017
# use a it as base for lighttpd 1.0.0 and above
1018
#
1019
############ Options you really have to take care of ####################
1020

    
1021
## FreeBSD!
1022
server.event-handler	= "freebsd-kqueue"
1023
server.network-backend 	= "writev"
1024
#server.use-ipv6 = "enable"
1025

    
1026
## modules to load
1027
server.modules              =   ( "mod_access", "mod_expire", "mod_compress", "mod_redirect",
1028
	{$captiveportal}, "mod_fastcgi"
1029
)
1030

    
1031
server.max-keep-alive-requests = 15
1032
server.max-keep-alive-idle = 30
1033

    
1034
## a static document-root, for virtual-hosting take look at the
1035
## server.virtual-* options
1036
server.document-root        = "{$document_root}"
1037
{$captive_portal_rewrite}
1038

    
1039
# Maximum idle time with nothing being written (php downloading)
1040
server.max-write-idle = 999
1041

    
1042
{$lighty_use_syslog}
1043

    
1044
# files to check for if .../ is requested
1045
server.indexfiles           = ( "index.php", "index.html",
1046
                                "index.htm", "default.htm" )
1047

    
1048
# mimetype mapping
1049
mimetype.assign             = (
1050
  ".pdf"          =>      "application/pdf",
1051
  ".sig"          =>      "application/pgp-signature",
1052
  ".spl"          =>      "application/futuresplash",
1053
  ".class"        =>      "application/octet-stream",
1054
  ".ps"           =>      "application/postscript",
1055
  ".torrent"      =>      "application/x-bittorrent",
1056
  ".dvi"          =>      "application/x-dvi",
1057
  ".gz"           =>      "application/x-gzip",
1058
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
1059
  ".swf"          =>      "application/x-shockwave-flash",
1060
  ".tar.gz"       =>      "application/x-tgz",
1061
  ".tgz"          =>      "application/x-tgz",
1062
  ".tar"          =>      "application/x-tar",
1063
  ".zip"          =>      "application/zip",
1064
  ".mp3"          =>      "audio/mpeg",
1065
  ".m3u"          =>      "audio/x-mpegurl",
1066
  ".wma"          =>      "audio/x-ms-wma",
1067
  ".wax"          =>      "audio/x-ms-wax",
1068
  ".ogg"          =>      "audio/x-wav",
1069
  ".wav"          =>      "audio/x-wav",
1070
  ".gif"          =>      "image/gif",
1071
  ".jpg"          =>      "image/jpeg",
1072
  ".jpeg"         =>      "image/jpeg",
1073
  ".png"          =>      "image/png",
1074
  ".xbm"          =>      "image/x-xbitmap",
1075
  ".xpm"          =>      "image/x-xpixmap",
1076
  ".xwd"          =>      "image/x-xwindowdump",
1077
  ".css"          =>      "text/css",
1078
  ".html"         =>      "text/html",
1079
  ".htm"          =>      "text/html",
1080
  ".js"           =>      "text/javascript",
1081
  ".asc"          =>      "text/plain",
1082
  ".c"            =>      "text/plain",
1083
  ".conf"         =>      "text/plain",
1084
  ".text"         =>      "text/plain",
1085
  ".txt"          =>      "text/plain",
1086
  ".dtd"          =>      "text/xml",
1087
  ".xml"          =>      "text/xml",
1088
  ".mpeg"         =>      "video/mpeg",
1089
  ".mpg"          =>      "video/mpeg",
1090
  ".mov"          =>      "video/quicktime",
1091
  ".qt"           =>      "video/quicktime",
1092
  ".avi"          =>      "video/x-msvideo",
1093
  ".asf"          =>      "video/x-ms-asf",
1094
  ".asx"          =>      "video/x-ms-asf",
1095
  ".wmv"          =>      "video/x-ms-wmv",
1096
  ".bz2"          =>      "application/x-bzip",
1097
  ".tbz"          =>      "application/x-bzip-compressed-tar",
1098
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
1099
 )
1100

    
1101
# Use the "Content-Type" extended attribute to obtain mime type if possible
1102
#mimetypes.use-xattr        = "enable"
1103

    
1104
## deny access the file-extensions
1105
#
1106
# ~    is for backupfiles from vi, emacs, joe, ...
1107
# .inc is often used for code includes which should in general not be part
1108
#      of the document-root
1109
url.access-deny             = ( "~", ".inc" )
1110

    
1111

    
1112
######### Options that are good to be but not neccesary to be changed #######
1113

    
1114
## bind to port (default: 80)
1115

    
1116
EOD;
1117

    
1118
	$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1119
	$lighty_config .= "server.port  = {$lighty_port}\n";
1120
	$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1121
	$lighty_config .= "\$SERVER[\"socket\"]  == \"[::]:{$lighty_port}\" { \n";
1122
	if($cert <> "" and $key <> "") {
1123
		$lighty_config .= "\n";
1124
		$lighty_config .= "## ssl configuration\n";
1125
		$lighty_config .= "ssl.engine = \"enable\"\n";
1126
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1127
		if($ca <> "")
1128
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1129
	}
1130
	$lighty_config .= " }\n";
1131

    
1132

    
1133
	$lighty_config .= <<<EOD
1134

    
1135
## error-handler for status 404
1136
#server.error-handler-404   = "/error-handler.html"
1137
#server.error-handler-404   = "/error-handler.php"
1138

    
1139
## to help the rc.scripts
1140
server.pid-file            = "{$g['varrun_path']}/{$pid_file}"
1141

    
1142
## virtual directory listings
1143
server.dir-listing         = "disable"
1144

    
1145
## enable debugging
1146
debug.log-request-header   = "disable"
1147
debug.log-response-header  = "disable"
1148
debug.log-request-handling = "disable"
1149
debug.log-file-not-found   = "disable"
1150

    
1151
# gzip compression
1152
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1153
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1154

    
1155
{$server_upload_dirs}
1156

    
1157
{$server_max_request_size}
1158

    
1159
{$fastcgi_config}
1160

    
1161
{$cgi_config}
1162

    
1163
{$captive_portal_mod_evasive}
1164

    
1165
expire.url = (
1166
				"" => "access 50 hours",	
1167
        )
1168

    
1169
EOD;
1170

    
1171
	$cert = str_replace("\r", "", $cert);
1172
	$key = str_replace("\r", "", $key);
1173
	$ca = str_replace("\r", "", $ca);
1174

    
1175
	$cert = str_replace("\n\n", "\n", $cert);
1176
	$key = str_replace("\n\n", "\n", $key);
1177
	$ca = str_replace("\n\n", "\n", $ca);
1178

    
1179
	if($cert <> "" and $key <> "") {
1180
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1181
		if (!$fd) {
1182
			printf(gettext("Error: cannot open cert.pem in system_webgui_start().%s"), "\n");
1183
			return 1;
1184
		}
1185
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1186
		fwrite($fd, $cert);
1187
		fwrite($fd, "\n");
1188
		fwrite($fd, $key);
1189
		fclose($fd);
1190
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
1191
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1192
			if (!$fd) {
1193
				printf(gettext("Error: cannot open ca.pem in system_webgui_start().%s"), "\n");
1194
				return 1;
1195
			}
1196
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1197
			fwrite($fd, $ca);
1198
			fclose($fd);
1199
		}
1200
		$lighty_config .= "\n";
1201
		$lighty_config .= "## " . gettext("ssl configuration") . "\n";
1202
		$lighty_config .= "ssl.engine = \"enable\"\n";
1203
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1204

    
1205
		// Harden SSL a bit for PCI conformance testing
1206
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
1207

    
1208
		/* Hifn accelerators do NOT work with the BEAST mitigation code. Do not allow it to be enabled if a Hifn card has been detected. */
1209
		$fd = @fopen("{$g['varlog_path']}/dmesg.boot", "r");
1210
		if ($fd) {
1211
			while (!feof($fd)) {
1212
				$dmesgl = fgets($fd);
1213
				if (preg_match("/^hifn.: (.*?),/", $dmesgl, $matches) && isset($config['system']['webgui']['beast_protection'])) {
1214
						unset($config['system']['webgui']['beast_protection']);
1215
						log_error("BEAST Protection disabled because a conflicting cryptographic accelerator card has been detected (" . $matches[1] . ")");
1216
					break;
1217
				}
1218
			}
1219
			fclose($fd);
1220
		}
1221

    
1222
		if (isset($config['system']['webgui']['beast_protection'])) {
1223
			$lighty_config .= "ssl.honor-cipher-order = \"enable\"\n";
1224
			$lighty_config .= "ssl.cipher-list = \"ECDHE-RSA-AES256-SHA384:AES256-SHA256:RC4-SHA:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM\"\n";
1225
		} else {
1226
			$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";
1227
		}
1228

    
1229
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1230
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1231
	}
1232

    
1233
	// Add HTTP to HTTPS redirect	
1234
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1235
		if($lighty_port != "443") 
1236
			$redirectport = ":{$lighty_port}";
1237
		$lighty_config .= <<<EOD
1238
\$SERVER["socket"] == ":80" {
1239
	\$HTTP["host"] =~ "(.*)" {
1240
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1241
	}
1242
}
1243
EOD;
1244
	}
1245

    
1246
	$fd = fopen("{$filename}", "w");
1247
	if (!$fd) {
1248
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1249
		return 1;
1250
	}
1251
	fwrite($fd, $lighty_config);
1252
	fclose($fd);
1253

    
1254
	return 0;
1255

    
1256
}
1257

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

    
1265
	$syscfg = $config['system'];
1266

    
1267
	if ($g['booting'])
1268
		echo gettext("Setting timezone...");
1269

    
1270
	/* extract appropriate timezone file */
1271
	$timezone = $syscfg['timezone'];
1272
	if ($timezone) {
1273
		exec('/usr/bin/tar -tvzf /usr/share/zoneinfo.tgz', $tzs);
1274
		foreach ($tzs as $tz) {
1275
			if (preg_match(",{$timezone}$,", $tz))
1276
				break;
1277
			if (preg_match(",{$timezone} link to *(.*)$,", $tz, $matches)) {
1278
				$timezone = $matches[1];
1279
				break;
1280
			}
1281
		}
1282
	} else
1283
		$timezone = "Etc/UTC";
1284

    
1285
	conf_mount_rw();
1286

    
1287
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1288
		escapeshellarg($timezone) . " > /etc/localtime");
1289

    
1290
	mwexec("sync");
1291
	conf_mount_ro();
1292

    
1293
	if ($g['booting'])
1294
		echo gettext("done.") . "\n";
1295
}
1296

    
1297
function system_ntp_setup_gps($serialport) {
1298
	global $config, $g;
1299
	$gps_device = '/dev/gps0';
1300
	$serialport = '/dev/'.$serialport;
1301

    
1302
	if (!file_exists($serialport))
1303
		return false;
1304

    
1305
	conf_mount_rw();
1306
	// Create symlink that ntpd requires
1307
	unlink_if_exists($gps_device);
1308
	symlink($serialport, $gps_device);
1309

    
1310
	/* Send the following to the GPS port to initialize the GPS */
1311
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
1312
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
1313
	}else{
1314
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1315
	}
1316

    
1317
	/* XXX: Why not file_put_contents to the device */
1318
	@file_put_contents('/tmp/gps.init', $gps_init);
1319
	`cat /tmp/gps.init > $serialport`;
1320

    
1321
	/* Add /etc/remote entry in case we need to read from the GPS with tip */
1322
	if (intval(`grep -c '^gps0' /etc/remote`) == 0) {
1323
		$gpsbaud = '4800';
1324
		if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['speed'])) {
1325
			switch($config['ntpd']['gps']['speed']) {
1326
				case '16':
1327
					$gpsbaud = '9600';
1328
					break;
1329
				case '32':
1330
					$gpsbaud = '19200';
1331
					break;
1332
				case '48':
1333
					$gpsbaud = '38400';
1334
					break;
1335
				case '64':
1336
					$gpsbaud = '57600';
1337
					break;
1338
				case '80':
1339
					$gpsbaud = '115200';
1340
					break;
1341
			}
1342
		}
1343
		@file_put_contents("/etc/remote", "gps0:dv={$serialport}:br#{$gpsbaud}:pa=none:", FILE_APPEND);
1344
	}
1345

    
1346
	conf_mount_ro();
1347

    
1348
	return true;
1349
}
1350

    
1351
function system_ntp_setup_pps($serialport) {
1352
	global $config, $g;
1353

    
1354
	$pps_device = '/dev/pps0';
1355
	$serialport = '/dev/'.$serialport;
1356

    
1357
	if (!file_exists($serialport))
1358
		return false;
1359

    
1360
	conf_mount_rw();
1361
	// Create symlink that ntpd requires
1362
	unlink_if_exists($pps_device);
1363
	@symlink($serialport, $pps_device);
1364

    
1365
	conf_mount_ro();
1366

    
1367
	return true;
1368
}
1369

    
1370

    
1371
function system_ntp_configure($start_ntpd=true) {
1372
	global $config, $g;
1373

    
1374
	$driftfile = "/var/db/ntpd.drift";
1375
	$statsdir = "/var/log/ntp";
1376
	$gps_device = '/dev/gps0';
1377

    
1378
	if ($g['platform'] == 'jail')
1379
		return;
1380

    
1381
	safe_mkdir($statsdir);
1382

    
1383
	if (!is_array($config['ntpd']))
1384
		$config['ntpd'] = array();
1385

    
1386
	$ntpcfg = "# \n";
1387
	$ntpcfg .= "# pfSense ntp configuration file \n";
1388
	$ntpcfg .= "# \n\n";
1389
	$ntpcfg .= "tinker panic 0 \n";
1390

    
1391
	/* Add Orphan mode */
1392
	$ntpcfg .= "# Orphan mode stratum\n";
1393
	$ntpcfg .= 'tos orphan ';
1394
	if (!empty($config['ntpd']['orphan'])) {
1395
		$ntpcfg .= $config['ntpd']['orphan'];
1396
	}else{
1397
		$ntpcfg .= '12';
1398
	}
1399
	$ntpcfg .= "\n";
1400

    
1401
	/* Add PPS configuration */
1402
	if (!empty($config['ntpd']['pps'])
1403
		&& file_exists('/dev/'.$config['ntpd']['pps']['port'])
1404
		&& system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
1405
		$ntpcfg .= "\n";
1406
		$ntpcfg .= "# PPS Setup\n";
1407
		$ntpcfg .= 'server 127.127.22.0';
1408
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1409
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
1410
			$ntpcfg .= ' prefer'; 
1411
		}
1412
		if (!empty($config['ntpd']['pps']['noselect'])) {
1413
			$ntpcfg .= ' noselect ';
1414
		}
1415
		$ntpcfg .= "\n";
1416
		$ntpcfg .= 'fudge 127.127.22.0';
1417
		if (!empty($config['ntpd']['pps']['fudge1'])) {
1418
			$ntpcfg .= ' time1 ';
1419
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
1420
		}
1421
		if (!empty($config['ntpd']['pps']['flag2'])) {
1422
			$ntpcfg .= ' flag2 1';
1423
		}
1424
		if (!empty($config['ntpd']['pps']['flag3'])) {
1425
			$ntpcfg .= ' flag3 1';
1426
		}else{
1427
			$ntpcfg .= ' flag3 0';
1428
		}
1429
		if (!empty($config['ntpd']['pps']['flag4'])) {
1430
			$ntpcfg .= ' flag4 1';
1431
		}
1432
		if (!empty($config['ntpd']['pps']['refid'])) {
1433
			$ntpcfg .= ' refid ';
1434
			$ntpcfg .= $config['ntpd']['pps']['refid'];
1435
		}
1436
		$ntpcfg .= "\n";
1437
	}
1438
	/* End PPS configuration */
1439

    
1440
	/* Add GPS configuration */
1441
	if (!empty($config['ntpd']['gps'])
1442
		&& file_exists('/dev/'.$config['ntpd']['gps']['port'])
1443
		&& system_ntp_setup_gps($config['ntpd']['gps']['port'])) {
1444
		$ntpcfg .= "\n";
1445
		$ntpcfg .= "# GPS Setup\n";
1446
		$ntpcfg .= 'server 127.127.20.0 mode ';
1447
		if (!empty($config['ntpd']['gps']['nmea']) || !empty($config['ntpd']['gps']['speed']) || !empty($config['ntpd']['gps']['subsec'])) {
1448
			if (!empty($config['ntpd']['gps']['nmea'])) {
1449
				$ntpmode = (int) $config['ntpd']['gps']['nmea'];
1450
			}
1451
			if (!empty($config['ntpd']['gps']['speed'])) {
1452
				$ntpmode += (int) $config['ntpd']['gps']['speed'];
1453
			}
1454
			if (!empty($config['ntpd']['gps']['subsec'])) {
1455
				$ntpmode += 128;
1456
			}
1457
			$ntpcfg .= (string) $ntpmode;
1458
		}else{
1459
			$ntpcfg .= '0';
1460
		}
1461
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1462
		if (empty($config['ntpd']['gps']['prefer'])) { /*note: this one works backwards */
1463
			$ntpcfg .= ' prefer'; 
1464
		}
1465
		if (!empty($config['ntpd']['gps']['noselect'])) {
1466
			$ntpcfg .= ' noselect ';
1467
		}
1468
		$ntpcfg .= "\n";
1469
		$ntpcfg .= 'fudge 127.127.20.0';
1470
		if (!empty($config['ntpd']['gps']['fudge1'])) {
1471
			$ntpcfg .= ' time1 ';
1472
			$ntpcfg .= $config['ntpd']['gps']['fudge1'];
1473
		}
1474
		if (!empty($config['ntpd']['gps']['fudge2'])) {
1475
			$ntpcfg .= ' time2 ';
1476
			$ntpcfg .= $config['ntpd']['gps']['fudge2'];
1477
		}
1478
		if (!empty($config['ntpd']['gps']['flag1'])) {
1479
			$ntpcfg .= ' flag1 1';
1480
		}else{
1481
			$ntpcfg .= ' flag1 0';
1482
		}
1483
		if (!empty($config['ntpd']['gps']['flag2'])) {
1484
			$ntpcfg .= ' flag2 1';
1485
		}
1486
		if (!empty($config['ntpd']['gps']['flag3'])) {
1487
			$ntpcfg .= ' flag3 1';
1488
		}else{
1489
			$ntpcfg .= ' flag3 0';
1490
		}
1491
		if (!empty($config['ntpd']['gps']['flag4'])) {
1492
			$ntpcfg .= ' flag4 1';
1493
		}
1494
		if (!empty($config['ntpd']['gps']['refid'])) {
1495
			$ntpcfg .= ' refid ';
1496
			$ntpcfg .= $config['ntpd']['gps']['refid'];
1497
		}
1498
		$ntpcfg .= "\n";
1499
	}elseif (!empty($config['ntpd']['gpsport'])
1500
		&& file_exists('/dev/'.$config['ntpd']['gpsport'])
1501
		&& system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1502
		/* This handles a 2.1 and earlier config */
1503
		$ntpcfg .= "# GPS Setup\n";
1504
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1505
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1506
		// Fall back to local clock if GPS is out of sync?
1507
		$ntpcfg .= "server 127.127.1.0\n";
1508
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1509
	}
1510
	/* End GPS configuration */
1511
	
1512
	$ntpcfg .= "\n\n# Upstream Servers\n";
1513
	/* foreach through ntp servers and write out to ntpd.conf */
1514
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1515
		$ntpcfg .= "server {$ts} iburst maxpoll 9";
1516
		if (substr_count($config['ntpd']['prefer'], $ts)) $ntpcfg .= ' prefer';
1517
		if (substr_count($config['ntpd']['noselect'], $ts)) $ntpcfg .= ' noselect';
1518
		$ntpcfg .= "\n";
1519
	}
1520
	unset($ts);
1521

    
1522
	$ntpcfg .= "\n\n";
1523
	$ntpcfg .= "disable monitor\n"; //prevent NTP reflection attack, see https://forum.pfsense.org/index.php/topic,67189.msg389132.html#msg389132
1524
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
1525
		$ntpcfg .= "enable stats\n";
1526
		$ntpcfg .= 'statistics';
1527
		if (!empty($config['ntpd']['clockstats'])) {
1528
			$ntpcfg .= ' clockstats';
1529
		}
1530
		if (!empty($config['ntpd']['loopstats'])) {
1531
			$ntpcfg .= ' loopstats';
1532
		}
1533
		if (!empty($config['ntpd']['peerstats'])) {
1534
			$ntpcfg .= ' peerstats';
1535
		}
1536
		$ntpcfg .= "\n";
1537
	}
1538
	$ntpcfg .= "statsdir {$statsdir}\n";
1539
	$ntpcfg .= 'logconfig =syncall +clockall';
1540
	if (!empty($config['ntpd']['logpeer'])) {
1541
		$ntpcfg .= ' +peerall';
1542
	}
1543
	if (!empty($config['ntpd']['logsys'])) {
1544
		$ntpcfg .= ' +sysall';
1545
	}
1546
	$ntpcfg .= "\n";
1547
	$ntpcfg .= "driftfile {$driftfile}\n";
1548
	/* Access restrictions */
1549
	$ntpcfg .= 'restrict default';
1550
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1551
		$ntpcfg .= ' kod limited'; 
1552
	}
1553
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1554
		$ntpcfg .= ' nomodify'; 
1555
	}
1556
	if (!empty($config['ntpd']['noquery'])) {
1557
		$ntpcfg .= ' noquery';
1558
	}
1559
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1560
		$ntpcfg .= ' nopeer'; 
1561
	}
1562
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1563
		$ntpcfg .= ' notrap'; 
1564
	}
1565
	if (!empty($config['ntpd']['noserve'])) {
1566
		$ntpcfg .= ' noserve';
1567
	}
1568
	$ntpcfg .= "\nrestrict -6 default";
1569
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1570
		$ntpcfg .= ' kod limited'; 
1571
	}
1572
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1573
		$ntpcfg .= ' nomodify'; 
1574
	}
1575
	if (!empty($config['ntpd']['noquery'])) {
1576
		$ntpcfg .= ' noquery';
1577
	}
1578
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1579
		$ntpcfg .= ' nopeer'; 
1580
	}
1581
	if (!empty($config['ntpd']['noserve'])) {
1582
		$ntpcfg .= ' noserve';
1583
	}
1584
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1585
		$ntpcfg .= ' notrap'; 
1586
	}
1587
	$ntpcfg .= "\n";
1588

    
1589
	/* A leapseconds file is really only useful if this clock is stratum 1 */
1590
	$ntpcfg .= "\n";
1591
	if (!empty($config['ntpd']['leapsec'])) {
1592
		$leapsec .= base64_decode($config['ntpd']['leapsec']);
1593
		file_put_contents('/var/db/leap-seconds', $leapsec);
1594
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
1595
	}
1596
	
1597

    
1598
	if (empty($config['ntpd']['interface']))
1599
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface']))
1600
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1601
		else
1602
			$interfaces = array();
1603
	else
1604
		$interfaces = explode(",", $config['ntpd']['interface']);
1605

    
1606
	if (is_array($interfaces) && count($interfaces)) {
1607
		$ntpcfg .= "interface ignore all\n";
1608
		foreach ($interfaces as $interface) {
1609
			if (!is_ipaddr($interface)) {
1610
				$interface = get_real_interface($interface);
1611
			}
1612
			if (!empty($interface))
1613
				$ntpcfg .= "interface listen {$interface}\n";
1614
		}
1615
	}
1616

    
1617
	/* open configuration for wrting or bail */
1618
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
1619
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1620
		return;
1621
	}
1622

    
1623
	/* At bootup we just want to write out the config. */
1624
	if (!$start_ntpd)
1625
		return;
1626

    
1627
	/* if ntpd is running, kill it */
1628
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1629
		killbypid("{$g['varrun_path']}/ntpd.pid");
1630
	}
1631
	@unlink("{$g['varrun_path']}/ntpd.pid");
1632

    
1633
	/* if /var/empty does not exist, create it */
1634
	if(!is_dir("/var/empty"))
1635
		mkdir("/var/empty", 0775, true);
1636

    
1637
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1638
	mwexec("/usr/local/sbin/ntpd -g -c {$g['varetc_path']}/ntpd.conf -p {$g['varrun_path']}/ntpd.pid", false, true);
1639
	
1640
	// Note that we are starting up
1641
	log_error("NTPD is starting up.");
1642
	return;
1643
}
1644

    
1645
function sync_system_time() {
1646
	global $config, $g;
1647

    
1648
	if ($g['booting'])
1649
		echo gettext("Syncing system time before startup...");
1650

    
1651
	/* foreach through servers and write out to ntpd.conf */
1652
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1653
		mwexec("/usr/local/sbin/ntpdate -s $ts");
1654
	}
1655
	
1656
	if ($g['booting'])
1657
		echo gettext("done.") . "\n";
1658
	
1659
}
1660

    
1661
function system_halt() {
1662
	global $g;
1663

    
1664
	system_reboot_cleanup();
1665

    
1666
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1667
}
1668

    
1669
function system_reboot() {
1670
	global $g;
1671

    
1672
	system_reboot_cleanup();
1673

    
1674
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1675
}
1676

    
1677
function system_reboot_sync() {
1678
	global $g;
1679

    
1680
	system_reboot_cleanup();
1681

    
1682
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1683
}
1684

    
1685
function system_reboot_cleanup() {
1686
	global $config, $cpzone;
1687

    
1688
	mwexec("/usr/local/bin/beep.sh stop");
1689
	require_once("captiveportal.inc");
1690
	if (is_array($config['captiveportal'])) {
1691
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
1692
			captiveportal_radius_stop_all();
1693
			captiveportal_send_server_accounting(true);
1694
		}
1695
	}
1696
	require_once("voucher.inc");
1697
	voucher_save_db_to_config();
1698
	require_once("pkg-utils.inc");
1699
	stop_packages();
1700
}
1701

    
1702
function system_do_shell_commands($early = 0) {
1703
	global $config, $g;
1704
	if(isset($config['system']['developerspew'])) {
1705
		$mt = microtime();
1706
		echo "system_do_shell_commands() being called $mt\n";
1707
	}
1708

    
1709
	if ($early)
1710
		$cmdn = "earlyshellcmd";
1711
	else
1712
		$cmdn = "shellcmd";
1713

    
1714
	if (is_array($config['system'][$cmdn])) {
1715

    
1716
		/* *cmd is an array, loop through */
1717
		foreach ($config['system'][$cmdn] as $cmd) {
1718
			exec($cmd);
1719
		}
1720

    
1721
	} elseif($config['system'][$cmdn] <> "") {
1722

    
1723
		/* execute single item */
1724
		exec($config['system'][$cmdn]);
1725

    
1726
	}
1727
}
1728

    
1729
function system_console_configure() {
1730
	global $config, $g;
1731
	if(isset($config['system']['developerspew'])) {
1732
		$mt = microtime();
1733
		echo "system_console_configure() being called $mt\n";
1734
	}
1735

    
1736
	if (isset($config['system']['disableconsolemenu'])) {
1737
		touch("{$g['varetc_path']}/disableconsole");
1738
	} else {
1739
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1740
	}
1741
}
1742

    
1743
function system_dmesg_save() {
1744
	global $g;
1745
	if(isset($config['system']['developerspew'])) {
1746
		$mt = microtime();
1747
		echo "system_dmesg_save() being called $mt\n";
1748
	}
1749

    
1750
	$dmesg = "";
1751
	$_gb = exec("/sbin/dmesg", $dmesg);
1752

    
1753
	/* find last copyright line (output from previous boots may be present) */
1754
	$lastcpline = 0;
1755

    
1756
	for ($i = 0; $i < count($dmesg); $i++) {
1757
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1758
			$lastcpline = $i;
1759
	}
1760

    
1761
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1762
	if (!$fd) {
1763
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1764
		return 1;
1765
	}
1766

    
1767
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1768
		fwrite($fd, $dmesg[$i] . "\n");
1769

    
1770
	fclose($fd);
1771
	unset($dmesg);
1772

    
1773
	return 0;
1774
}
1775

    
1776
function system_set_harddisk_standby() {
1777
	global $g, $config;
1778
	if(isset($config['system']['developerspew'])) {
1779
		$mt = microtime();
1780
		echo "system_set_harddisk_standby() being called $mt\n";
1781
	}
1782

    
1783
	if (isset($config['system']['harddiskstandby'])) {
1784
		if ($g['booting']) {
1785
			echo gettext('Setting hard disk standby... ');
1786
		}
1787

    
1788
		$standby = $config['system']['harddiskstandby'];
1789
		// Check for a numeric value
1790
		if (is_numeric($standby)) {
1791
			// Sync the disk(s)
1792
			pfSense_sync();
1793
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1794
				// Reinitialize ATA-drives
1795
				mwexec('/usr/local/sbin/atareinit');
1796
				if ($g['booting']) {
1797
					echo gettext("done.") . "\n";
1798
				}
1799
			} else if ($g['booting']) {
1800
				echo gettext("failed!") . "\n";
1801
			}
1802
		} else if ($g['booting']) {
1803
			echo gettext("failed!") . "\n";
1804
		}
1805
	}
1806
}
1807

    
1808
function system_setup_sysctl() {
1809
	global $config;
1810
	if(isset($config['system']['developerspew'])) {
1811
		$mt = microtime();
1812
		echo "system_setup_sysctl() being called $mt\n";
1813
	}
1814

    
1815
	activate_sysctls();	
1816

    
1817
	if (isset($config['system']['sharednet'])) {
1818
		system_disable_arp_wrong_if();
1819
	}
1820
}
1821

    
1822
function system_disable_arp_wrong_if() {
1823
	global $config;
1824
	if(isset($config['system']['developerspew'])) {
1825
		$mt = microtime();
1826
		echo "system_disable_arp_wrong_if() being called $mt\n";
1827
	}
1828
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1829
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1830
}
1831

    
1832
function system_enable_arp_wrong_if() {
1833
	global $config;
1834
	if(isset($config['system']['developerspew'])) {
1835
		$mt = microtime();
1836
		echo "system_enable_arp_wrong_if() being called $mt\n";
1837
	}
1838
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1839
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1840
}
1841

    
1842
function enable_watchdog() {
1843
	global $config;
1844
	return;
1845
	$install_watchdog = false;
1846
	$supported_watchdogs = array("Geode");
1847
	$file = file_get_contents("/var/log/dmesg.boot");
1848
	foreach($supported_watchdogs as $sd) {
1849
		if(stristr($file, "Geode")) {
1850
			$install_watchdog = true;
1851
		}
1852
	}
1853
	if($install_watchdog == true) {
1854
		if(is_process_running("watchdogd"))
1855
			mwexec("/usr/bin/killall watchdogd", true);
1856
		exec("/usr/sbin/watchdogd");
1857
	}
1858
}
1859

    
1860
function system_check_reset_button() {
1861
	global $g;
1862
	if($g['platform'] != "nanobsd")
1863
		return 0;
1864

    
1865
	$specplatform = system_identify_specific_platform();
1866

    
1867
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1868
		return 0;
1869

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

    
1872
	if ($retval == 99) {
1873
		/* user has pressed reset button for 2 seconds - 
1874
		   reset to factory defaults */
1875
		echo <<<EOD
1876

    
1877
***********************************************************************
1878
* Reset button pressed - resetting configuration to factory defaults. *
1879
* The system will reboot after this completes.                        *
1880
***********************************************************************
1881

    
1882

    
1883
EOD;
1884
		
1885
		reset_factory_defaults();
1886
		system_reboot_sync();
1887
		exit(0);
1888
	}
1889

    
1890
	return 0;
1891
}
1892

    
1893
/* attempt to identify the specific platform (for embedded systems)
1894
   Returns an array with two elements:
1895
	name => platform string (e.g. 'wrap', 'alix' etc.)
1896
	descr => human-readable description (e.g. "PC Engines WRAP")
1897
*/
1898
function system_identify_specific_platform() {
1899
	global $g;
1900
	
1901
	if ($g['platform'] == 'generic-pc')
1902
		return array('name' => 'generic-pc', 'descr' => gettext("Generic PC"));
1903
	
1904
	if ($g['platform'] == 'generic-pc-cdrom')
1905
		return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)"));
1906
	
1907
	/* the rest of the code only deals with 'embedded' platforms */
1908
	if ($g['platform'] != 'nanobsd')
1909
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1910

    
1911
	unset($output);
1912
	$_gb = exec('/sbin/sysctl -n hw.model', $output);
1913
	$dmesg = $output[0];
1914

    
1915
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1916
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
1917
	
1918
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1919
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
1920

    
1921
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1922
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1923
	
1924
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1925
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1926
		
1927
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1928
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1929
	
1930
	/* unknown embedded platform */
1931
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
1932
}
1933

    
1934
function system_get_dmesg_boot() {
1935
	global $g;
1936
		
1937
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1938
}
1939

    
1940
function get_possible_listen_ips($include_ipv6_link_local=false) {
1941
	$interfaces = get_configured_interface_with_descr();
1942
	$carplist = get_configured_carp_interface_list();
1943
	$listenips = array();
1944
	foreach ($carplist as $cif => $carpip)
1945
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1946
	$aliaslist = get_configured_ip_aliases_list();
1947
	foreach ($aliaslist as $aliasip => $aliasif)
1948
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1949
	foreach ($interfaces as $iface => $ifacename) {
1950
		$tmp["name"]  = $ifacename;
1951
		$tmp["value"] = $iface;
1952
		$listenips[] = $tmp;
1953
		if ($include_ipv6_link_local) {
1954
			$llip = find_interface_ipv6_ll(get_real_interface($iface));
1955
			if (!empty($llip)) {
1956
				$tmp["name"]  = "{$ifacename} IPv6 Link-Local";
1957
				$tmp["value"] = $llip;
1958
				$listenips[] = $tmp;
1959
			}
1960
		}
1961
	}
1962
	$tmp["name"]  = "Localhost";
1963
	$tmp["value"] = "lo0";
1964
	$listenips[] = $tmp;
1965
	return $listenips;
1966
}
1967

    
1968
function get_possible_traffic_source_addresses($include_ipv6_link_local=false) {
1969
	global $config;
1970
	$sourceips = get_possible_listen_ips($include_ipv6_link_local);
1971
	foreach (array('server', 'client') as $mode) {
1972
		if (is_array($config['openvpn']["openvpn-{$mode}"])) {
1973
			foreach ($config['openvpn']["openvpn-{$mode}"] as $id => $setting) {
1974
				if (!isset($setting['disable'])) {
1975
					$vpn = array();
1976
					$vpn['value'] = 'ovpn' . substr($mode, 0, 1) . $setting['vpnid'];
1977
					$vpn['name'] = gettext("OpenVPN") . " ".$mode.": ".htmlspecialchars($setting['description']);
1978
					$sourceips[] = $vpn;
1979
				}
1980
			}
1981
		}
1982
	}
1983
	return $sourceips;
1984
}
1985
?>
(52-52/67)