Projet

Général

Profil

Télécharger (63,1 ko) Statistiques
| Branche: | Tag: | Révision:

univnautes / etc / inc / system.inc @ 2cf2c62b

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/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
		$normal_mode = "hadp";
61
		if (!empty($config['system']['powerd_normal_mode']))
62
			$normal_mode = $config['system']['powerd_normal_mode'];
63

    
64
		mwexec("/usr/sbin/powerd -b $battery_mode -a $ac_mode -n $normal_mode");
65
	}
66
}
67

    
68
function get_default_sysctl_value($id) {
69
	global $sysctls;
70

    
71
	if (isset($sysctls[$id]))
72
		return $sysctls[$id];
73
}
74

    
75
function activate_sysctls() {
76
	global $config, $g;
77

    
78
	if ($g['platform'] == 'jail')
79
		return;
80

    
81
	$sysctls = array(
82
		"net.enc.out.ipsec_bpf_mask" => "0x0001",
83
		"net.enc.out.ipsec_filter_mask" => "0x0001",
84
		"net.enc.in.ipsec_bpf_mask" => "0x0002",
85
		"net.enc.in.ipsec_filter_mask" => "0x0002"
86
	);
87

    
88
	if(is_array($config['sysctl'])) {
89
		foreach($config['sysctl']['item'] as $tunable) {
90
			if($tunable['value'] == "default")
91
				$value = get_default_sysctl_value($tunable['tunable']);
92
			else
93
				$value = $tunable['value'];
94

    
95
			$sysctls[$tunable['tunable']] = $value;
96
		}
97
	}
98

    
99
	set_sysctl($sysctls);
100
}
101

    
102
function system_resolvconf_generate($dynupdate = false) {
103
	global $config, $g;
104

    
105
	if(isset($config['system']['developerspew'])) {
106
		$mt = microtime();
107
		echo "system_resolvconf_generate() being called $mt\n";
108
	}
109

    
110
	$syscfg = $config['system'];
111

    
112
	// Do not create blank domain lines, it breaks tools like dig.
113
	if($syscfg['domain'])
114
		$resolvconf = "domain {$syscfg['domain']}\n";
115

    
116
	if (((isset($config['dnsmasq']['enable']) && (empty($config['dnsmasq']['interface']) || in_array("lo0", explode(",", $config['dnsmasq']['interface']))))
117
		|| (isset($config['unbound']['enable'])) && (empty($config['unbound']['active_interface']) || in_array("lo0", explode(",", $config['unbound']['active_interface']))))
118
		&& !isset($config['system']['dnslocalhost']))
119
		$resolvconf .= "nameserver 127.0.0.1\n";
120

    
121
	if (isset($syscfg['dnsallowoverride'])) {
122
		/* get dynamically assigned DNS servers (if any) */
123
		$ns = array_unique(get_searchdomains());
124
		foreach($ns as $searchserver) {
125
			if($searchserver)
126
				$resolvconf .= "search {$searchserver}\n";
127
		}
128
		$ns = array_unique(get_nameservers());
129
		foreach($ns as $nameserver) {
130
			if($nameserver)
131
				$resolvconf .= "nameserver $nameserver\n";
132
		}
133
	}
134
	if (is_array($syscfg['dnsserver'])) {
135
		foreach ($syscfg['dnsserver'] as $ns) {
136
			if ($ns)
137
				$resolvconf .= "nameserver $ns\n";
138
		}
139
	}
140

    
141
	// Add EDNS support
142
	if (isset($config['unbound']['enable']) && isset($config['unbound']['edns']))
143
		$resolvconf .= "options edns0\n";
144

    
145
	$dnslock = lock('resolvconf', LOCK_EX);
146

    
147
	$fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
148
	if (!$fd) {
149
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
150
		unlock($dnslock);
151
		return 1;
152
	}
153

    
154
	fwrite($fd, $resolvconf);
155
	fclose($fd);
156

    
157
	if (!$g['booting']) {
158
		/* restart dhcpd (nameservers may have changed) */
159
		if (!$dynupdate)
160
			services_dhcpd_configure();
161
	}
162

    
163
	/* setup static routes for DNS servers. */
164
	for ($dnscounter=1; $dnscounter<5; $dnscounter++) {
165
		/* setup static routes for dns servers */
166
		$dnsgw = "dns{$dnscounter}gw";
167
		if (isset($config['system'][$dnsgw])) {
168
			$gwname = $config['system'][$dnsgw];
169
			if (($gwname <> "") && ($gwname <> "none")) {
170
				$gatewayip = lookup_gateway_ip_by_name($gwname);
171
				if (is_ipaddrv4($gatewayip)) {
172
					/* dns server array starts at 0 */
173
					$dnscountermo = $dnscounter - 1;
174
					mwexec("/sbin/route change -host " . $syscfg['dnsserver'][$dnscountermo] . " {$gatewayip}");
175
				}
176
				if (is_ipaddrv6($gatewayip)) {
177
					/* dns server array starts at 0 */
178
					$dnscountermo = $dnscounter - 1;
179
					mwexec("/sbin/route change -host -inet6 " . $syscfg['dnsserver'][$dnscountermo] . " {$gatewayip}");
180
				}
181
			}
182
		}
183
	}
184

    
185
	unlock($dnslock);
186

    
187
	return 0;
188
}
189

    
190
function get_searchdomains() {
191
	global $config, $g;
192

    
193
	$master_list = array();
194
	
195
	// Read in dhclient nameservers
196
	$search_list = glob("/var/etc/searchdomain_*");
197
	if (is_array($search_list)) {
198
		foreach($search_list as $fdns) {
199
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
200
			if (!is_array($contents))
201
				continue;
202
			foreach ($contents as $dns) {
203
				if(is_hostname($dns)) 
204
					$master_list[] = $dns;
205
			}
206
		}
207
	}
208

    
209
	return $master_list;
210
}
211

    
212
function get_nameservers() {
213
	global $config, $g;
214
	$master_list = array();
215
	
216
	// Read in dhclient nameservers
217
	$dns_lists = glob("/var/etc/nameserver_*");
218
	if (is_array($dns_lists)) {
219
		foreach($dns_lists as $fdns) {
220
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
221
			if (!is_array($contents))
222
				continue;
223
			foreach ($contents as $dns) {
224
				if(is_ipaddr($dns)) 
225
					$master_list[] = $dns;
226
			}
227
		}
228
	}
229

    
230
	// Read in any extra nameservers
231
	if(file_exists("/var/etc/nameservers.conf")) {
232
		$dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
233
		if(is_array($dns_s)) {
234
			foreach($dns_s as $dns)
235
				if (is_ipaddr($dns))
236
					$master_list[] = $dns;
237
		}
238
	}
239

    
240
	return $master_list;
241
}
242

    
243
function system_hosts_generate() {
244
	global $config, $g;
245
	if (isset($config['system']['developerspew'])) {
246
		$mt = microtime();
247
		echo "system_hosts_generate() being called $mt\n";
248
	}
249

    
250
	$syscfg = $config['system'];
251
	$dnsmasqcfg = $config['dnsmasq'];
252

    
253
	$hosts = "127.0.0.1	localhost localhost.{$syscfg['domain']}\n";
254
	$lhosts = "";
255
	$dhosts = "";
256

    
257
	if ($config['interfaces']['lan']) {
258
		$cfgip = get_interface_ip("lan");
259
		if (is_ipaddr($cfgip))
260
			$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
261
	} else {
262
		$sysiflist = get_configured_interface_list();
263
		foreach ($sysiflist as $sysif) {
264
			if (!interface_has_gateway($sysif)) {
265
				$cfgip = get_interface_ip($sysif);
266
				if (is_ipaddr($cfgip)) {
267
					$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
268
					break;
269
				}
270
			}
271
		}
272
	}
273

    
274
	if (isset($dnsmasqcfg['enable'])) {
275
		if (!is_array($dnsmasqcfg['hosts']))
276
			$dnsmasqcfg['hosts'] = array();
277

    
278
		foreach ($dnsmasqcfg['hosts'] as $host) {
279
			if ($host['host'])
280
				$lhosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
281
			else
282
				$lhosts .= "{$host['ip']}	{$host['domain']}\n";
283
			if (!is_array($host['aliases']) || !is_array($host['aliases']['item']))
284
				continue;
285
			foreach ($host['aliases']['item'] as $alias) {
286
				if ($alias['host'])
287
					$lhosts .= "{$host['ip']}	{$alias['host']}.{$alias['domain']} {$alias['host']}\n";
288
				else
289
					$lhosts .= "{$host['ip']}	{$alias['domain']}\n";
290
			}
291
		}
292
		if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpd'])) {
293
			foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf)
294
				if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
295
						foreach ($dhcpifconf['staticmap'] as $host)
296
							if ($host['ipaddr'] && $host['hostname'] && $host['domain'])
297
								$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$host['domain']} {$host['hostname']}\n";
298
							else if ($host['ipaddr'] && $host['hostname'] && $dhcpifconf['domain'])
299
								$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$dhcpifconf['domain']} {$host['hostname']}\n";
300
							else if ($host['ipaddr'] && $host['hostname'])
301
								$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
302
		}
303
		if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpdv6'])) {
304
			foreach ($config['dhcpdv6'] as $dhcpif => $dhcpifconf)
305
				if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
306
						foreach ($dhcpifconf['staticmap'] as $host)
307
							if ($host['ipaddrv6'] && $host['hostname'] && $host['domain'])
308
								$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$host['domain']} {$host['hostname']}\n";
309
							else if ($host['ipaddrv6'] && $host['hostname'] && $dhcpifconf['domain'])
310
								$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$dhcpifconf['domain']} {$host['hostname']}\n";
311
							else if ($host['ipaddrv6'] && $host['hostname'])
312
								$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
313
		}
314

    
315
		if (isset($dnsmasqcfg['dhcpfirst']))
316
			$hosts .= $dhosts . $lhosts;
317
		else
318
			$hosts .= $lhosts . $dhosts;
319
	}
320

    
321
	/*
322
	 * Do not remove this because dhcpleases monitors with kqueue it needs to be 
323
	 * killed before writing to hosts files.
324
	 */
325
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
326
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
327
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
328
	}
329
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
330
	if (!$fd) {
331
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
332
		return 1;
333
	}
334
	fwrite($fd, $hosts);
335
	fclose($fd);
336

    
337
	if (isset($config['unbound']['enable'])) {
338
		require_once("unbound.inc");
339
		unbound_hosts_generate();
340
	}
341

    
342
	system_dhcpleases_configure();
343

    
344
	return 0;
345
}
346

    
347
function system_dhcpleases_configure() {
348
	global $config, $g;
349
	
350
	if ($g['platform'] == 'jail')
351
		return;
352
	/* Start the monitoring process for dynamic dhcpclients. */
353
	if ((isset($config['dnsmasq']['enable']) && isset($config['dnsmasq']['regdhcp'])) 
354
		|| (isset($config['unbound']['enable']) && isset($config['unbound']['regdhcp']))) {
355
		/* Make sure we do not error out */
356
		mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db");
357
		if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases"))
358
			@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
359
		if (isvalidpid("{$g['varrun_path']}/dhcpleases.pid"))
360
			sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "HUP");
361
		else {
362
			/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
363
			if (is_process_running("dhcpleases"))
364
				mwexec('/bin/pkill dhcpleases');
365
			@unlink("{$g['varrun_path']}/dhcpleases.pid");
366
			if (isset($config['unbound']['enable']))
367
				$dns_pid = "unbound.pid";
368
			else
369
				$dns_pid = "dnsmasq.pid";
370
			mwexec("/usr/local/sbin/dhcpleases -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases -d {$config['system']['domain']} -p {$g['varrun_path']}/{$dns_pid} -h {$g['varetc_path']}/hosts");
371
		}
372
	} else {
373
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
374
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
375
	}
376
}
377

    
378
function system_hostname_configure() {
379
	global $config, $g;
380
	if(isset($config['system']['developerspew'])) {
381
		$mt = microtime();
382
		echo "system_hostname_configure() being called $mt\n";
383
	}
384

    
385
	$syscfg = $config['system'];
386

    
387
	/* set hostname */
388
	$status = mwexec("/bin/hostname " .
389
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
390

    
391
    /* Setup host GUID ID.  This is used by ZFS. */
392
	mwexec("/etc/rc.d/hostid start");
393

    
394
	return $status;
395
}
396

    
397
function system_routing_configure($interface = "") {
398
	global $config, $g;
399
	if ($g['platform'] == 'jail')
400
		return;
401
	if(isset($config['system']['developerspew'])) {
402
		$mt = microtime();
403
		echo "system_routing_configure() being called $mt\n";
404
	}
405

    
406
	$gatewayip = "";
407
	$interfacegw = "";
408
	$foundgw = false;
409
	$gatewayipv6 = "";
410
	$interfacegwv6 = "";
411
	$foundgwv6 = false;
412
	/* tack on all the hard defined gateways as well */
413
	if (is_array($config['gateways']['gateway_item'])) {
414
		array_map('unlink', glob("{$g['tmp_path']}/*_defaultgw{,v6}", GLOB_BRACE));
415
		foreach	($config['gateways']['gateway_item'] as $gateway) {
416
			if (isset($gateway['defaultgw'])) {
417
				if ($gateway['ipprotocol'] != "inet6" && (is_ipaddrv4($gateway['gateway']) || $gateway['gateway'] == "dynamic")) {
418
					if(strstr($gateway['gateway'], ":"))
419
						continue;
420
					if ($gateway['gateway'] == "dynamic")
421
						$gateway['gateway'] = get_interface_gateway($gateway['interface']);
422
					$gatewayip = $gateway['gateway'];
423
					$interfacegw = $gateway['interface'];
424
					if (!empty($gateway['interface'])) {
425
						$defaultif = get_real_interface($gateway['interface']);
426
						if ($defaultif)
427
							@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gateway['gateway']);
428
					}
429
					$foundgw = true;
430
				} else if ($gateway['ipprotocol'] == "inet6" && (is_ipaddrv6($gateway['gateway']) || $gateway['gateway'] == "dynamic")) {
431
					if ($gateway['gateway'] == "dynamic")
432
						$gateway['gateway'] = get_interface_gateway_v6($gateway['interface']);
433
					$gatewayipv6 = $gateway['gateway'];
434
					$interfacegwv6 = $gateway['interface'];
435
					if (!empty($gateway['interface'])) {
436
						$defaultifv6 = get_real_interface($gateway['interface']);
437
						if ($defaultifv6)
438
							@file_put_contents("{$g['tmp_path']}/{$defaultifv6}_defaultgwv6", $gateway['gateway']);
439
					}
440
					$foundgwv6 = true;
441
				}
442
			}
443
			if ($foundgw === true && $foundgwv6 === true)
444
				break;
445
		}
446
	}
447
	if ($foundgw == false) {
448
		$defaultif = get_real_interface("wan");
449
		$interfacegw = "wan";
450
		$gatewayip = get_interface_gateway("wan");
451
		@touch("{$g['tmp_path']}/{$defaultif}_defaultgw");
452
	}	
453
	if ($foundgwv6 == false) {
454
		$defaultifv6 = get_real_interface("wan");
455
		$interfacegwv6 = "wan";
456
		$gatewayipv6 = get_interface_gateway_v6("wan");
457
		@touch("{$g['tmp_path']}/{$defaultif}_defaultgwv6");
458
	}
459
	$dont_add_route = false;
460
	/* if OLSRD is enabled, allow WAN to house DHCP. */
461
	if (is_array($config['installedpackages']['olsrd'])) {
462
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
463
			if(($olsrd['enabledyngw'] == "on") && ($olsrd['enable'] == "on")) {
464
				$dont_add_route = true;
465
				log_error(sprintf(gettext("Not adding default route because OLSR dynamic gateway is enabled.")));
466
				break;
467
			}
468
		}
469
	}
470

    
471
	if ($dont_add_route == false ) {
472
		if (!empty($interface) && $interface != $interfacegw)
473
			;
474
		else if (is_ipaddrv4($gatewayip)) {
475
			log_error("ROUTING: setting default route to $gatewayip");
476
			mwexec("/sbin/route change -inet default " . escapeshellarg($gatewayip));
477
		}
478

    
479
		if (!empty($interface) && $interface != $interfacegwv6)
480
			;
481
		else if (is_ipaddrv6($gatewayipv6)) {
482
			$ifscope = "";
483
			if (is_linklocal($gatewayipv6))
484
				$ifscope = "%{$defaultifv6}";
485
			log_error("ROUTING: setting IPv6 default route to {$gatewayipv6}{$ifscope}");
486
			mwexec("/sbin/route change -inet6 default " . escapeshellarg("{$gatewayipv6}{$ifscope}"));
487
		}
488
	}
489

    
490
	system_staticroutes_configure($interface, false);
491

    
492
	return 0;
493
}
494

    
495
function system_staticroutes_configure($interface = "", $update_dns = false) {
496
	global $config, $g, $aliastable;
497

    
498
	$filterdns_list = array();
499

    
500
	$static_routes = get_staticroutes(false, true);
501
	if (count($static_routes)) {
502
		$gateways_arr = return_gateways_array(false, true);
503

    
504
		foreach ($static_routes as $rtent) {
505
			if (empty($gateways_arr[$rtent['gateway']])) {
506
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
507
				continue;
508
			}
509
			$gateway = $gateways_arr[$rtent['gateway']];
510
			if (!empty($interface) && $interface != $gateway['friendlyiface'])
511
				continue;
512

    
513
			$gatewayip = $gateway['gateway'];
514
			$interfacegw = $gateway['interface'];
515

    
516
			$blackhole = "";
517
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 3)))
518
				$blackhole = "-blackhole";
519

    
520
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network']))
521
				continue;
522

    
523
			$dnscache = array();
524
			if ($update_dns === true) {
525
				if (is_subnet($rtent['network']))
526
					continue;
527
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
528
				if (empty($dnscache))
529
					continue;
530
			}
531

    
532
			if (is_subnet($rtent['network']))
533
				$ips = array($rtent['network']);
534
			else {
535
				if (!isset($rtent['disabled']))
536
					$filterdns_list[] = $rtent['network'];
537
				$ips = add_hostname_to_watch($rtent['network']);
538
			}
539

    
540
			foreach ($dnscache as $ip) {
541
				if (in_array($ip, $ips))
542
					continue;
543
				mwexec("/sbin/route delete " . escapeshellarg($ip), true);
544
			}
545

    
546
			if (isset($rtent['disabled'])) {
547
				/* XXX: This can break things by deleting routes that shouldn't be deleted - OpenVPN, dynamic routing scenarios, etc. redmine #3709 */
548
				foreach ($ips as $ip)
549
					mwexec("/sbin/route delete " . escapeshellarg($ip), true);
550
				continue;
551
			}
552

    
553
			foreach ($ips as $ip) {
554
				if (is_ipaddrv4($ip))
555
					$ip .= "/32";
556
				else if (is_ipaddrv6($ip))
557
					$ip .= "/128";
558

    
559
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
560

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

    
563
				if (is_subnet($ip))
564
					if (is_ipaddr($gatewayip))
565
						mwexec($cmd . escapeshellarg($gatewayip));
566
					else if (!empty($interfacegw))
567
						mwexec($cmd . "-iface " . escapeshellarg($interfacegw));
568
			}
569
		}
570
		unset($gateways_arr);
571
	}
572
	unset($static_routes);
573

    
574
	if ($update_dns === false) {
575
		if (count($filterdns_list)) {
576
			$interval = 60;
577
			$hostnames = "";
578
			array_unique($filterdns_list);
579
			foreach ($filterdns_list as $hostname)
580
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
581
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
582
			unset($hostnames);
583

    
584
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid"))
585
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
586
			else
587
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
588
		} else {
589
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
590
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
591
		}
592
	}
593
	unset($filterdns_list);
594

    
595
	return 0;
596
}
597

    
598
function system_routing_enable() {
599
	global $config, $g;
600
	if(isset($config['system']['developerspew'])) {
601
		$mt = microtime();
602
		echo "system_routing_enable() being called $mt\n";
603
	}
604

    
605
	set_sysctl(array(
606
		"net.inet.ip.forwarding" => "1",
607
		"net.inet6.ip6.forwarding" => "1"
608
	));
609

    
610
	return;
611
}
612

    
613
function system_syslogd_fixup_server($server) {
614
	/* If it's an IPv6 IP alone, encase it in brackets */
615
	if (is_ipaddrv6($server))
616
		return "[$server]";
617
	else
618
		return $server;
619
}
620

    
621
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
622
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
623
	$facility .= " ".
624
	$remote_servers = "";
625
	$pad_to  = 56;
626
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
627
	if($syslogcfg['remoteserver'])
628
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
629
	if($syslogcfg['remoteserver2'])
630
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
631
	if($syslogcfg['remoteserver3'])
632
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
633
	return $remote_servers;
634
}
635

    
636
function system_syslogd_start() {
637
	global $config, $g;
638
	if(isset($config['system']['developerspew'])) {
639
		$mt = microtime();
640
		echo "system_syslogd_start() being called $mt\n";
641
	}
642

    
643
	mwexec("/etc/rc.d/hostid start");
644

    
645
	$syslogcfg = $config['syslog'];
646

    
647
	if ($g['booting'])
648
		echo gettext("Starting syslog...");
649

    
650
	if (is_process_running("fifolog_writer"))
651
		mwexec('/bin/pkill fifolog_writer');
652

    
653
	// Which logging type are we using this week??
654
	if (isset($config['system']['disablesyslogclog'])) {
655
		$log_directive = "";
656
		$log_create_directive = "/usr/bin/touch ";
657
		$log_size = "";
658
	} else if (isset($config['system']['usefifolog'])) {
659
		$log_directive = "|/usr/sbin/fifolog_writer ";
660
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
661
		$log_create_directive = "/usr/sbin/fifolog_create -s ";
662
	} else { // Defaults to CLOG
663
		$log_directive = "%";
664
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
665
		$log_create_directive = "/usr/local/sbin/clog -i -s ";
666
	}
667

    
668
	$syslogd_extra = "";
669
	if (isset($syslogcfg)) {
670
		$separatelogfacilities = array('ntp','ntpd','ntpdate','charon','openvpn','pptps','poes','l2tps','relayd','hostapd','dnsmasq','filterdns','unbound','dhcpd','dhcrelay','dhclient','dhcp6c','apinger','radvd','routed','olsrd','zebra','ospfd','bgpd','miniupnpd','filterlog');
671
		$syslogconf = "";
672
		if($config['installedpackages']['package']) {
673
			foreach($config['installedpackages']['package'] as $package) {
674
				if($package['logging']) {
675
					array_push($separatelogfacilities, $package['logging']['facilityname']);
676
					mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
677
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
678
				}
679
			}
680
		}
681
		$facilitylist = implode(',', array_unique($separatelogfacilities));
682
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd,miniupnpd\n";
683
		if (!isset($syslogcfg['disablelocallogging']))
684
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
685

    
686
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
687
		if (!isset($syslogcfg['disablelocallogging'])) 
688
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
689

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

    
694
		$syslogconf .= "!pptps\n";
695
		if (!isset($syslogcfg['disablelocallogging'])) 
696
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/pptps.log\n";
697

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

    
702
		$syslogconf .= "!l2tps\n";
703
		if (!isset($syslogcfg['disablelocallogging'])) 
704
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/l2tps.log\n";
705

    
706
		$syslogconf .= "!charon\n";
707
		if (!isset($syslogcfg['disablelocallogging'])) 
708
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ipsec.log\n";
709
		if (isset($syslogcfg['vpn']))
710
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
711

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

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

    
724
		$syslogconf .= "!dnsmasq,filterdns,unbound\n";
725
		if (!isset($syslogcfg['disablelocallogging']))
726
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
727

    
728
		$syslogconf .= "!dhcpd,dhcrelay,dhclient,dhcp6c\n";
729
		if (!isset($syslogcfg['disablelocallogging']))
730
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/dhcpd.log\n";
731
		if (isset($syslogcfg['dhcp']))
732
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
733

    
734
		$syslogconf .= "!relayd\n";
735
		if (!isset($syslogcfg['disablelocallogging']))
736
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/relayd.log\n";
737
		if (isset($syslogcfg['relayd']))
738
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
739

    
740
		$syslogconf .= "!hostapd\n";
741
		if (!isset($syslogcfg['disablelocallogging']))
742
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
743
		if (isset($syslogcfg['hostapd']))
744
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
745

    
746
		$syslogconf .= "!filterlog\n";
747
		$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/filter.log\n";
748
		if (isset($syslogcfg['filter']))
749
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
750

    
751
		$syslogconf .= "!-{$facilitylist}\n";
752
		if (!isset($syslogcfg['disablelocallogging'])) 
753
			$syslogconf .= <<<EOD
754
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
755
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
756
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
757
*.notice;kern.debug;lpr.info;mail.crit;daemon.none;		{$log_directive}{$g['varlog_path']}/system.log
758
news.err;local0.none;local3.none;local4.none;			{$log_directive}{$g['varlog_path']}/system.log
759
local7.none							{$log_directive}{$g['varlog_path']}/system.log
760
security.*							{$log_directive}{$g['varlog_path']}/system.log
761
auth.info;authpriv.info;daemon.info				{$log_directive}{$g['varlog_path']}/system.log
762
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
763
*.emerg								*
764

    
765
EOD;
766
		if (isset($syslogcfg['vpn']))
767
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
768
		if (isset($syslogcfg['portalauth']))
769
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
770
		if (isset($syslogcfg['dhcp']))
771
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
772
		if (isset($syslogcfg['system'])) {
773
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.notice;kern.debug;lpr.info;mail.crit;");
774
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "news.err;local0.none;local3.none;local7.none");
775
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "security.*");
776
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "auth.info;authpriv.info;daemon.info");
777
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.emerg");
778
		}
779
		if (isset($syslogcfg['logall'])) {
780
			// Make everything mean everything, including facilities excluded above.
781
			$syslogconf .= "!*\n";
782
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
783
		}
784

    
785
		if (isset($syslogcfg['zmqserver'])) {
786
				$syslogconf .= <<<EOD
787
*.*								^{$syslogcfg['zmqserver']}
788

    
789
EOD;
790
		}
791
		/* write syslog.conf */		
792
		if (!@file_put_contents("{$g['varetc_path']}/syslog.conf", $syslogconf)) {
793
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
794
			unset($syslogconf);
795
			return 1;
796
		}
797
		unset($syslogconf);
798

    
799
		// Ensure that the log directory exists
800
		if (!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
801
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
802

    
803
		$sourceip = "";
804
		if (!empty($syslogcfg['sourceip'])) {
805
			if ($syslogcfg['ipproto'] == "ipv6") {
806
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
807
				if (!is_ipaddr($ifaddr))
808
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
809
			} else {
810
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
811
				if (!is_ipaddr($ifaddr))
812
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
813
			}
814
			if (is_ipaddr($ifaddr)) {
815
				$sourceip = "-b {$ifaddr}";
816
			}
817
		}
818

    
819
		$syslogd_extra = "-f {$g['varetc_path']}/syslog.conf {$sourceip}";
820
	}
821

    
822
	if (isvalidpid("{$g['varrun_path']}/syslog.pid"))
823
		sigkillbypid("{$g['varrun_path']}/syslog.pid", "HUP");
824
	else
825
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c -l {$g['dhcpd_chroot_path']}/var/run/log -P {$g['varrun_path']}/syslog.pid {$syslogd_extra}");
826

    
827
	if ($g['booting'])
828
		echo gettext("done.") . "\n";
829

    
830
	return $retval;
831
}
832

    
833
function system_webgui_create_certificate() {
834
	global $config, $g;
835

    
836
	if (!is_array($config['ca']))
837
		$config['ca'] = array();
838
	$a_ca =& $config['ca'];
839
	if (!is_array($config['cert']))
840
		$config['cert'] = array();
841
	$a_cert =& $config['cert'];
842
	log_error("Creating SSL Certificate for this host");
843

    
844
	$cert = array();
845
	$cert['refid'] = uniqid();
846
	$cert['descr'] = gettext("webConfigurator default ({$cert['refid']})");
847

    
848
	$dn = array(
849
		'countryName' => "US",
850
		'stateOrProvinceName' => "State",
851
		'localityName' => "Locality",
852
		'organizationName' => "{$g['product_name']} webConfigurator Self-Signed Certificate",
853
		'emailAddress' => "admin@{$config['system']['hostname']}.{$config['system']['domain']}",
854
		'commonName' => "{$config['system']['hostname']}-{$cert['refid']}");
855
	$old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warings directly to a page screwing menu tab */
856
	if (!cert_create($cert, null, 2048, 2000, $dn, "self-signed", "sha256")){
857
		while($ssl_err = openssl_error_string()){
858
			log_error("Error creating WebGUI Certificate: openssl library returns: " . $ssl_err);
859
		}
860
		error_reporting($old_err_level);
861
		return null;
862
	}
863
	error_reporting($old_err_level);
864

    
865
	$a_cert[] = $cert;
866
	$config['system']['webgui']['ssl-certref'] = $cert['refid'];
867
	write_config(gettext("Generated new self-signed HTTPS certificate ({$cert['refid']})"));
868
	return $cert;
869
}
870

    
871
function system_webgui_start() {
872
	global $config, $g;
873

    
874
	if ($g['booting'])
875
		echo gettext("Starting webConfigurator...");
876

    
877
	chdir($g['www_path']);
878

    
879
	/* defaults */
880
	$portarg = "80";
881
	$crt = "";
882
	$key = "";
883
	$ca = "";
884

    
885
	/* non-standard port? */
886
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
887
		$portarg = "{$config['system']['webgui']['port']}";
888

    
889
	if ($config['system']['webgui']['protocol'] == "https") {
890
		// Ensure that we have a webConfigurator CERT
891
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
892
		if(!is_array($cert) && !$cert['crt'] && !$cert['prv']) {
893
			$cert = system_webgui_create_certificate();
894
			$crt = $cert['crt'];
895
			$key = $cert['prv'];
896
		} else {
897
			$crt = base64_decode($cert['crt']);
898
			$key = base64_decode($cert['prv']);
899
		}
900

    
901
		if(!$config['system']['webgui']['port'])
902
			$portarg = "443";
903
		$ca  = ca_chain($cert);
904
	}
905

    
906
	/* generate lighttpd configuration */
907
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
908
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
909
		"cert.pem", "ca.pem");
910

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

    
914
	sleep(1);
915

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

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

    
921
	if ($g['booting']) {
922
		if ($res == 0)
923
			echo gettext("done.") . "\n";
924
		else
925
			echo gettext("failed!") . "\n";
926
	}
927

    
928
	return $res;
929
}
930

    
931
function system_generate_lighty_config($filename,
932
	$cert,
933
	$key,
934
	$ca,
935
	$pid_file,
936
	$port = 80,
937
	$document_root = "/usr/local/www/",
938
	$cert_location = "cert.pem",
939
	$ca_location = "ca.pem",
940
	$captive_portal = false) {
941

    
942
	global $config, $g;
943

    
944
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
945
		mkdir("{$g['tmp_path']}/lighttpdcompress");
946

    
947
	if(isset($config['system']['developerspew'])) {
948
		$mt = microtime();
949
		echo "system_generate_lighty_config() being called $mt\n";
950
	}
951

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

    
956
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
957
		if (empty($maxprocperip))
958
			$maxprocperip = 10;
959
		$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
960

    
961
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
962
		if(!is_dir("{$g['tmp_path']}/captiveportal"))
963
			@mkdir("{$g['tmp_path']}/captiveportal", 0555);
964
		$server_max_request_size = "server.max-request-size    = 384";
965
		$cgi_config = "";
966
	} else {
967
		$captiveportal = ",\"mod_cgi\"";
968
		$captive_portal_rewrite = "";
969
		$captive_portal_mod_evasive = "";
970
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
971
		$server_max_request_size = "server.max-request-size    = 2097152";
972
		$cgi_config = "cgi.assign                 = ( \".cgi\" => \"\" )";
973
	}
974
	
975
	if (empty($port))
976
		$lighty_port = "80";
977
	else
978
		$lighty_port = $port;
979

    
980
	$memory = get_memory();
981
	$realmem = $memory[1];
982

    
983
	// Determine web GUI process settings and take into account low memory systems
984
	if ($realmem < 255)
985
		$max_procs = 1;
986
	else
987
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
988

    
989
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM 
990
	if ($captive_portal !== false)  {
991
		if ($realmem > 135 and $realmem < 256) {
992
			$max_procs += 1; // 2 worker processes
993
		} else if ($realmem > 255 and $realmem < 513) {
994
			$max_procs += 2; // 3 worker processes
995
		} else if ($realmem > 512) {
996
			$max_procs += 4; // 6 worker processes
997
		}
998
		if ($max_procs > 1)
999
			$max_php_children = intval($max_procs/2);
1000
		else
1001
			$max_php_children = 1;
1002

    
1003
	} else {
1004
		if ($realmem < 78)
1005
			$max_php_children = 0;
1006
		else
1007
			$max_php_children = 1;
1008
	}
1009

    
1010
	if(!isset($config['syslog']['nologlighttpd'])) {
1011
		$lighty_use_syslog = <<<EOD
1012
## where to send error-messages to
1013
server.errorlog-use-syslog="enable"
1014
EOD;
1015
	}
1016

    
1017

    
1018
	if ($captive_portal !== false) {
1019
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi-{$captive_portal}.socket";
1020
		$fastcgi_config = <<<EOD
1021
#### fastcgi module
1022
## read fastcgi.txt for more info
1023
fastcgi.server = ( ".php" =>
1024
	( "localhost" =>
1025
		(
1026
			"socket" => "{$fast_cgi_path}",
1027
			"max-procs" => {$max_procs},
1028
			"bin-environment" => (
1029
				"PHP_FCGI_CHILDREN" => "{$max_php_children}",
1030
				"PHP_FCGI_MAX_REQUESTS" => "500"
1031
			),
1032
			"bin-path" => "/usr/local/bin/php"
1033
		)
1034
	)
1035
)
1036

    
1037
EOD;
1038
	} else {
1039
		$fast_cgi_path = "{$g['varrun_path']}/php-fpm.socket";
1040
		$fastcgi_config = <<<EOD
1041
#### fastcgi module
1042
## read fastcgi.txt for more info
1043
fastcgi.server = ( ".php" =>
1044
	( "localhost" =>
1045
		(
1046
			"socket" => "{$fast_cgi_path}",
1047
			"broken-scriptfilename" => "enable"
1048
		)
1049
	)
1050
)
1051

    
1052
EOD;
1053
	}
1054

    
1055

    
1056
	$lighty_config = <<<EOD
1057
#
1058
# lighttpd configuration file
1059
#
1060
# use a it as base for lighttpd 1.0.0 and above
1061
#
1062
############ Options you really have to take care of ####################
1063

    
1064
## FreeBSD!
1065
server.event-handler	= "freebsd-kqueue"
1066
server.network-backend 	= "writev"
1067
#server.use-ipv6 = "enable"
1068

    
1069
## modules to load
1070
server.modules              =   ( "mod_access", "mod_expire", "mod_compress", "mod_redirect",
1071
	{$captiveportal}, "mod_fastcgi"
1072
)
1073

    
1074
server.max-keep-alive-requests = 15
1075
server.max-keep-alive-idle = 30
1076

    
1077
## a static document-root, for virtual-hosting take look at the
1078
## server.virtual-* options
1079
server.document-root        = "{$document_root}"
1080
{$captive_portal_rewrite}
1081

    
1082
# Maximum idle time with nothing being written (php downloading)
1083
server.max-write-idle = 999
1084

    
1085
{$lighty_use_syslog}
1086

    
1087
# files to check for if .../ is requested
1088
server.indexfiles           = ( "index.php", "index.html",
1089
                                "index.htm", "default.htm" )
1090

    
1091
# mimetype mapping
1092
mimetype.assign             = (
1093
  ".pdf"          =>      "application/pdf",
1094
  ".sig"          =>      "application/pgp-signature",
1095
  ".spl"          =>      "application/futuresplash",
1096
  ".class"        =>      "application/octet-stream",
1097
  ".ps"           =>      "application/postscript",
1098
  ".torrent"      =>      "application/x-bittorrent",
1099
  ".dvi"          =>      "application/x-dvi",
1100
  ".gz"           =>      "application/x-gzip",
1101
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
1102
  ".swf"          =>      "application/x-shockwave-flash",
1103
  ".tar.gz"       =>      "application/x-tgz",
1104
  ".tgz"          =>      "application/x-tgz",
1105
  ".tar"          =>      "application/x-tar",
1106
  ".zip"          =>      "application/zip",
1107
  ".mp3"          =>      "audio/mpeg",
1108
  ".m3u"          =>      "audio/x-mpegurl",
1109
  ".wma"          =>      "audio/x-ms-wma",
1110
  ".wax"          =>      "audio/x-ms-wax",
1111
  ".ogg"          =>      "audio/x-wav",
1112
  ".wav"          =>      "audio/x-wav",
1113
  ".gif"          =>      "image/gif",
1114
  ".jpg"          =>      "image/jpeg",
1115
  ".jpeg"         =>      "image/jpeg",
1116
  ".png"          =>      "image/png",
1117
  ".xbm"          =>      "image/x-xbitmap",
1118
  ".xpm"          =>      "image/x-xpixmap",
1119
  ".xwd"          =>      "image/x-xwindowdump",
1120
  ".css"          =>      "text/css",
1121
  ".html"         =>      "text/html",
1122
  ".htm"          =>      "text/html",
1123
  ".js"           =>      "text/javascript",
1124
  ".asc"          =>      "text/plain",
1125
  ".c"            =>      "text/plain",
1126
  ".conf"         =>      "text/plain",
1127
  ".text"         =>      "text/plain",
1128
  ".txt"          =>      "text/plain",
1129
  ".dtd"          =>      "text/xml",
1130
  ".xml"          =>      "text/xml",
1131
  ".mpeg"         =>      "video/mpeg",
1132
  ".mpg"          =>      "video/mpeg",
1133
  ".mov"          =>      "video/quicktime",
1134
  ".qt"           =>      "video/quicktime",
1135
  ".avi"          =>      "video/x-msvideo",
1136
  ".asf"          =>      "video/x-ms-asf",
1137
  ".asx"          =>      "video/x-ms-asf",
1138
  ".wmv"          =>      "video/x-ms-wmv",
1139
  ".bz2"          =>      "application/x-bzip",
1140
  ".tbz"          =>      "application/x-bzip-compressed-tar",
1141
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
1142
 )
1143

    
1144
# Use the "Content-Type" extended attribute to obtain mime type if possible
1145
#mimetypes.use-xattr        = "enable"
1146

    
1147
## deny access the file-extensions
1148
#
1149
# ~    is for backupfiles from vi, emacs, joe, ...
1150
# .inc is often used for code includes which should in general not be part
1151
#      of the document-root
1152
url.access-deny             = ( "~", ".inc" )
1153

    
1154

    
1155
######### Options that are good to be but not neccesary to be changed #######
1156

    
1157
## bind to port (default: 80)
1158

    
1159
EOD;
1160

    
1161
	$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1162
	$lighty_config .= "server.port  = {$lighty_port}\n";
1163
	$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1164
	$lighty_config .= "\$SERVER[\"socket\"]  == \"[::]:{$lighty_port}\" { \n";
1165
	if($cert <> "" and $key <> "") {
1166
		$lighty_config .= "\n";
1167
		$lighty_config .= "## ssl configuration\n";
1168
		$lighty_config .= "ssl.engine = \"enable\"\n";
1169
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1170
		if($ca <> "")
1171
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1172
	}
1173
	$lighty_config .= " }\n";
1174

    
1175

    
1176
	$lighty_config .= <<<EOD
1177

    
1178
## error-handler for status 404
1179
#server.error-handler-404   = "/error-handler.html"
1180
#server.error-handler-404   = "/error-handler.php"
1181

    
1182
## to help the rc.scripts
1183
server.pid-file            = "{$g['varrun_path']}/{$pid_file}"
1184

    
1185
## virtual directory listings
1186
server.dir-listing         = "disable"
1187

    
1188
## enable debugging
1189
debug.log-request-header   = "disable"
1190
debug.log-response-header  = "disable"
1191
debug.log-request-handling = "disable"
1192
debug.log-file-not-found   = "disable"
1193

    
1194
# gzip compression
1195
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1196
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1197

    
1198
{$server_upload_dirs}
1199

    
1200
{$server_max_request_size}
1201

    
1202
{$fastcgi_config}
1203

    
1204
{$cgi_config}
1205

    
1206
{$captive_portal_mod_evasive}
1207

    
1208
expire.url = (
1209
				"" => "access 50 hours",	
1210
        )
1211

    
1212
EOD;
1213

    
1214
	$cert = str_replace("\r", "", $cert);
1215
	$key = str_replace("\r", "", $key);
1216
	$ca = str_replace("\r", "", $ca);
1217

    
1218
	$cert = str_replace("\n\n", "\n", $cert);
1219
	$key = str_replace("\n\n", "\n", $key);
1220
	$ca = str_replace("\n\n", "\n", $ca);
1221

    
1222
	if($cert <> "" and $key <> "") {
1223
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1224
		if (!$fd) {
1225
			printf(gettext("Error: cannot open cert.pem in system_webgui_start().%s"), "\n");
1226
			return 1;
1227
		}
1228
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1229
		fwrite($fd, $cert);
1230
		fwrite($fd, "\n");
1231
		fwrite($fd, $key);
1232
		fclose($fd);
1233
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
1234
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1235
			if (!$fd) {
1236
				printf(gettext("Error: cannot open ca.pem in system_webgui_start().%s"), "\n");
1237
				return 1;
1238
			}
1239
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1240
			fwrite($fd, $ca);
1241
			fclose($fd);
1242
		}
1243
		$lighty_config .= "\n";
1244
		$lighty_config .= "## " . gettext("ssl configuration") . "\n";
1245
		$lighty_config .= "ssl.engine = \"enable\"\n";
1246
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1247

    
1248
		// Harden SSL a bit for PCI conformance testing
1249
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
1250
		$lighty_config .= "ssl.use-sslv3 = \"disable\"\n";
1251

    
1252
		/* Hifn accelerators do NOT work with the BEAST mitigation code. Do not allow it to be enabled if a Hifn card has been detected. */
1253
		$fd = @fopen("{$g['varlog_path']}/dmesg.boot", "r");
1254
		if ($fd) {
1255
			while (!feof($fd)) {
1256
				$dmesgl = fgets($fd);
1257
				if (preg_match("/^hifn.: (.*?),/", $dmesgl, $matches) && isset($config['system']['webgui']['beast_protection'])) {
1258
						unset($config['system']['webgui']['beast_protection']);
1259
						log_error("BEAST Protection disabled because a conflicting cryptographic accelerator card has been detected (" . $matches[1] . ")");
1260
					break;
1261
				}
1262
			}
1263
			fclose($fd);
1264
		}
1265

    
1266
		if (isset($config['system']['webgui']['beast_protection'])) {
1267
			$lighty_config .= "ssl.honor-cipher-order = \"enable\"\n";
1268
			$lighty_config .= "ssl.cipher-list = \"ECDHE-RSA-AES256-SHA384:AES256-SHA256:RC4-SHA:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM\"\n";
1269
		} else {
1270
			$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";
1271
		}
1272

    
1273
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1274
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1275
	}
1276

    
1277
	// Add HTTP to HTTPS redirect	
1278
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1279
		if($lighty_port != "443") 
1280
			$redirectport = ":{$lighty_port}";
1281
		$lighty_config .= <<<EOD
1282
\$SERVER["socket"] == ":80" {
1283
	\$HTTP["host"] =~ "(.*)" {
1284
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1285
	}
1286
}
1287
\$SERVER["socket"] == "[::]:80" {
1288
	\$HTTP["host"] =~ "(.*)" {
1289
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1290
	}
1291
}
1292
EOD;
1293
	}
1294

    
1295
	$fd = fopen("{$filename}", "w");
1296
	if (!$fd) {
1297
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1298
		return 1;
1299
	}
1300
	fwrite($fd, $lighty_config);
1301
	fclose($fd);
1302

    
1303
	return 0;
1304

    
1305
}
1306

    
1307
function system_timezone_configure() {
1308
	global $config, $g;
1309
	if(isset($config['system']['developerspew'])) {
1310
		$mt = microtime();
1311
		echo "system_timezone_configure() being called $mt\n";
1312
	}
1313

    
1314
	$syscfg = $config['system'];
1315

    
1316
	if ($g['booting'])
1317
		echo gettext("Setting timezone...");
1318

    
1319
	/* extract appropriate timezone file */
1320
	$timezone = $syscfg['timezone'];
1321
	if ($timezone) {
1322
		exec('/usr/bin/tar -tvzf /usr/share/zoneinfo.tgz', $tzs);
1323
		foreach ($tzs as $tz) {
1324
			if (preg_match(",{$timezone}$,", $tz))
1325
				break;
1326
			if (preg_match(",{$timezone} link to *(.*)$,", $tz, $matches)) {
1327
				$timezone = $matches[1];
1328
				break;
1329
			}
1330
		}
1331
	} else
1332
		$timezone = "Etc/UTC";
1333

    
1334
	conf_mount_rw();
1335

    
1336
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1337
		escapeshellarg($timezone) . " > /etc/localtime");
1338

    
1339
	mwexec("sync");
1340
	conf_mount_ro();
1341

    
1342
	if ($g['booting'])
1343
		echo gettext("done.") . "\n";
1344
}
1345

    
1346
function system_ntp_setup_gps($serialport) {
1347
	global $config, $g;
1348
	$gps_device = '/dev/gps0';
1349
	$serialport = '/dev/'.$serialport;
1350

    
1351
	if (!file_exists($serialport))
1352
		return false;
1353

    
1354
	conf_mount_rw();
1355
	// Create symlink that ntpd requires
1356
	unlink_if_exists($gps_device);
1357
	symlink($serialport, $gps_device);
1358

    
1359
	/* Send the following to the GPS port to initialize the GPS */
1360
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
1361
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
1362
	}else{
1363
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1364
	}
1365

    
1366
	/* XXX: Why not file_put_contents to the device */
1367
	@file_put_contents('/tmp/gps.init', $gps_init);
1368
	`cat /tmp/gps.init > $serialport`;
1369

    
1370
	/* Add /etc/remote entry in case we need to read from the GPS with tip */
1371
	if (intval(`grep -c '^gps0' /etc/remote`) == 0) {
1372
		$gpsbaud = '4800';
1373
		if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['speed'])) {
1374
			switch($config['ntpd']['gps']['speed']) {
1375
				case '16':
1376
					$gpsbaud = '9600';
1377
					break;
1378
				case '32':
1379
					$gpsbaud = '19200';
1380
					break;
1381
				case '48':
1382
					$gpsbaud = '38400';
1383
					break;
1384
				case '64':
1385
					$gpsbaud = '57600';
1386
					break;
1387
				case '80':
1388
					$gpsbaud = '115200';
1389
					break;
1390
			}
1391
		}
1392
		@file_put_contents("/etc/remote", "gps0:dv={$serialport}:br#{$gpsbaud}:pa=none:", FILE_APPEND);
1393
	}
1394

    
1395
	conf_mount_ro();
1396

    
1397
	return true;
1398
}
1399

    
1400
function system_ntp_setup_pps($serialport) {
1401
	global $config, $g;
1402

    
1403
	$pps_device = '/dev/pps0';
1404
	$serialport = '/dev/'.$serialport;
1405

    
1406
	if (!file_exists($serialport))
1407
		return false;
1408

    
1409
	conf_mount_rw();
1410
	// Create symlink that ntpd requires
1411
	unlink_if_exists($pps_device);
1412
	@symlink($serialport, $pps_device);
1413

    
1414
	conf_mount_ro();
1415

    
1416
	return true;
1417
}
1418

    
1419

    
1420
function system_ntp_configure($start_ntpd=true) {
1421
	global $config, $g;
1422

    
1423
	$driftfile = "/var/db/ntpd.drift";
1424
	$statsdir = "/var/log/ntp";
1425
	$gps_device = '/dev/gps0';
1426

    
1427
	if ($g['platform'] == 'jail')
1428
		return;
1429

    
1430
	safe_mkdir($statsdir);
1431

    
1432
	if (!is_array($config['ntpd']))
1433
		$config['ntpd'] = array();
1434

    
1435
	$ntpcfg = "# \n";
1436
	$ntpcfg .= "# pfSense ntp configuration file \n";
1437
	$ntpcfg .= "# \n\n";
1438
	$ntpcfg .= "tinker panic 0 \n";
1439

    
1440
	/* Add Orphan mode */
1441
	$ntpcfg .= "# Orphan mode stratum\n";
1442
	$ntpcfg .= 'tos orphan ';
1443
	if (!empty($config['ntpd']['orphan'])) {
1444
		$ntpcfg .= $config['ntpd']['orphan'];
1445
	}else{
1446
		$ntpcfg .= '12';
1447
	}
1448
	$ntpcfg .= "\n";
1449

    
1450
	/* Add PPS configuration */
1451
	if (!empty($config['ntpd']['pps'])
1452
		&& file_exists('/dev/'.$config['ntpd']['pps']['port'])
1453
		&& system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
1454
		$ntpcfg .= "\n";
1455
		$ntpcfg .= "# PPS Setup\n";
1456
		$ntpcfg .= 'server 127.127.22.0';
1457
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1458
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
1459
			$ntpcfg .= ' prefer'; 
1460
		}
1461
		if (!empty($config['ntpd']['pps']['noselect'])) {
1462
			$ntpcfg .= ' noselect ';
1463
		}
1464
		$ntpcfg .= "\n";
1465
		$ntpcfg .= 'fudge 127.127.22.0';
1466
		if (!empty($config['ntpd']['pps']['fudge1'])) {
1467
			$ntpcfg .= ' time1 ';
1468
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
1469
		}
1470
		if (!empty($config['ntpd']['pps']['flag2'])) {
1471
			$ntpcfg .= ' flag2 1';
1472
		}
1473
		if (!empty($config['ntpd']['pps']['flag3'])) {
1474
			$ntpcfg .= ' flag3 1';
1475
		}else{
1476
			$ntpcfg .= ' flag3 0';
1477
		}
1478
		if (!empty($config['ntpd']['pps']['flag4'])) {
1479
			$ntpcfg .= ' flag4 1';
1480
		}
1481
		if (!empty($config['ntpd']['pps']['refid'])) {
1482
			$ntpcfg .= ' refid ';
1483
			$ntpcfg .= $config['ntpd']['pps']['refid'];
1484
		}
1485
		$ntpcfg .= "\n";
1486
	}
1487
	/* End PPS configuration */
1488

    
1489
	/* Add GPS configuration */
1490
	if (!empty($config['ntpd']['gps'])
1491
		&& file_exists('/dev/'.$config['ntpd']['gps']['port'])
1492
		&& system_ntp_setup_gps($config['ntpd']['gps']['port'])) {
1493
		$ntpcfg .= "\n";
1494
		$ntpcfg .= "# GPS Setup\n";
1495
		$ntpcfg .= 'server 127.127.20.0 mode ';
1496
		if (!empty($config['ntpd']['gps']['nmea']) || !empty($config['ntpd']['gps']['speed']) || !empty($config['ntpd']['gps']['subsec'])) {
1497
			if (!empty($config['ntpd']['gps']['nmea'])) {
1498
				$ntpmode = (int) $config['ntpd']['gps']['nmea'];
1499
			}
1500
			if (!empty($config['ntpd']['gps']['speed'])) {
1501
				$ntpmode += (int) $config['ntpd']['gps']['speed'];
1502
			}
1503
			if (!empty($config['ntpd']['gps']['subsec'])) {
1504
				$ntpmode += 128;
1505
			}
1506
			$ntpcfg .= (string) $ntpmode;
1507
		}else{
1508
			$ntpcfg .= '0';
1509
		}
1510
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1511
		if (empty($config['ntpd']['gps']['prefer'])) { /*note: this one works backwards */
1512
			$ntpcfg .= ' prefer'; 
1513
		}
1514
		if (!empty($config['ntpd']['gps']['noselect'])) {
1515
			$ntpcfg .= ' noselect ';
1516
		}
1517
		$ntpcfg .= "\n";
1518
		$ntpcfg .= 'fudge 127.127.20.0';
1519
		if (!empty($config['ntpd']['gps']['fudge1'])) {
1520
			$ntpcfg .= ' time1 ';
1521
			$ntpcfg .= $config['ntpd']['gps']['fudge1'];
1522
		}
1523
		if (!empty($config['ntpd']['gps']['fudge2'])) {
1524
			$ntpcfg .= ' time2 ';
1525
			$ntpcfg .= $config['ntpd']['gps']['fudge2'];
1526
		}
1527
		if (!empty($config['ntpd']['gps']['flag1'])) {
1528
			$ntpcfg .= ' flag1 1';
1529
		}else{
1530
			$ntpcfg .= ' flag1 0';
1531
		}
1532
		if (!empty($config['ntpd']['gps']['flag2'])) {
1533
			$ntpcfg .= ' flag2 1';
1534
		}
1535
		if (!empty($config['ntpd']['gps']['flag3'])) {
1536
			$ntpcfg .= ' flag3 1';
1537
		}else{
1538
			$ntpcfg .= ' flag3 0';
1539
		}
1540
		if (!empty($config['ntpd']['gps']['flag4'])) {
1541
			$ntpcfg .= ' flag4 1';
1542
		}
1543
		if (!empty($config['ntpd']['gps']['refid'])) {
1544
			$ntpcfg .= ' refid ';
1545
			$ntpcfg .= $config['ntpd']['gps']['refid'];
1546
		}
1547
		$ntpcfg .= "\n";
1548
	}elseif (!empty($config['ntpd']['gpsport'])
1549
		&& file_exists('/dev/'.$config['ntpd']['gpsport'])
1550
		&& system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1551
		/* This handles a 2.1 and earlier config */
1552
		$ntpcfg .= "# GPS Setup\n";
1553
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1554
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1555
		// Fall back to local clock if GPS is out of sync?
1556
		$ntpcfg .= "server 127.127.1.0\n";
1557
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1558
	}
1559
	/* End GPS configuration */
1560
	
1561
	$ntpcfg .= "\n\n# Upstream Servers\n";
1562
	/* foreach through ntp servers and write out to ntpd.conf */
1563
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1564
		$ntpcfg .= "server {$ts} iburst maxpoll 9";
1565
		if (substr_count($config['ntpd']['prefer'], $ts)) $ntpcfg .= ' prefer';
1566
		if (substr_count($config['ntpd']['noselect'], $ts)) $ntpcfg .= ' noselect';
1567
		$ntpcfg .= "\n";
1568
	}
1569
	unset($ts);
1570

    
1571
	$ntpcfg .= "\n\n";
1572
	$ntpcfg .= "disable monitor\n"; //prevent NTP reflection attack, see https://forum.pfsense.org/index.php/topic,67189.msg389132.html#msg389132
1573
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
1574
		$ntpcfg .= "enable stats\n";
1575
		$ntpcfg .= 'statistics';
1576
		if (!empty($config['ntpd']['clockstats'])) {
1577
			$ntpcfg .= ' clockstats';
1578
		}
1579
		if (!empty($config['ntpd']['loopstats'])) {
1580
			$ntpcfg .= ' loopstats';
1581
		}
1582
		if (!empty($config['ntpd']['peerstats'])) {
1583
			$ntpcfg .= ' peerstats';
1584
		}
1585
		$ntpcfg .= "\n";
1586
	}
1587
	$ntpcfg .= "statsdir {$statsdir}\n";
1588
	$ntpcfg .= 'logconfig =syncall +clockall';
1589
	if (!empty($config['ntpd']['logpeer'])) {
1590
		$ntpcfg .= ' +peerall';
1591
	}
1592
	if (!empty($config['ntpd']['logsys'])) {
1593
		$ntpcfg .= ' +sysall';
1594
	}
1595
	$ntpcfg .= "\n";
1596
	$ntpcfg .= "driftfile {$driftfile}\n";
1597
	/* Access restrictions */
1598
	$ntpcfg .= 'restrict default';
1599
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1600
		$ntpcfg .= ' kod limited'; 
1601
	}
1602
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1603
		$ntpcfg .= ' nomodify'; 
1604
	}
1605
	if (!empty($config['ntpd']['noquery'])) {
1606
		$ntpcfg .= ' noquery';
1607
	}
1608
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1609
		$ntpcfg .= ' nopeer'; 
1610
	}
1611
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1612
		$ntpcfg .= ' notrap'; 
1613
	}
1614
	if (!empty($config['ntpd']['noserve'])) {
1615
		$ntpcfg .= ' noserve';
1616
	}
1617
	$ntpcfg .= "\nrestrict -6 default";
1618
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1619
		$ntpcfg .= ' kod limited'; 
1620
	}
1621
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1622
		$ntpcfg .= ' nomodify'; 
1623
	}
1624
	if (!empty($config['ntpd']['noquery'])) {
1625
		$ntpcfg .= ' noquery';
1626
	}
1627
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1628
		$ntpcfg .= ' nopeer'; 
1629
	}
1630
	if (!empty($config['ntpd']['noserve'])) {
1631
		$ntpcfg .= ' noserve';
1632
	}
1633
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1634
		$ntpcfg .= ' notrap'; 
1635
	}
1636
	$ntpcfg .= "\n";
1637

    
1638
	/* A leapseconds file is really only useful if this clock is stratum 1 */
1639
	$ntpcfg .= "\n";
1640
	if (!empty($config['ntpd']['leapsec'])) {
1641
		$leapsec .= base64_decode($config['ntpd']['leapsec']);
1642
		file_put_contents('/var/db/leap-seconds', $leapsec);
1643
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
1644
	}
1645
	
1646

    
1647
	if (empty($config['ntpd']['interface']))
1648
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface']))
1649
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1650
		else
1651
			$interfaces = array();
1652
	else
1653
		$interfaces = explode(",", $config['ntpd']['interface']);
1654

    
1655
	if (is_array($interfaces) && count($interfaces)) {
1656
		$ntpcfg .= "interface ignore all\n";
1657
		foreach ($interfaces as $interface) {
1658
			if (!is_ipaddr($interface)) {
1659
				$interface = get_real_interface($interface);
1660
			}
1661
			if (!empty($interface))
1662
				$ntpcfg .= "interface listen {$interface}\n";
1663
		}
1664
	}
1665

    
1666
	/* open configuration for wrting or bail */
1667
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
1668
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1669
		return;
1670
	}
1671

    
1672
	/* At bootup we just want to write out the config. */
1673
	if (!$start_ntpd)
1674
		return;
1675

    
1676
	/* if ntpd is running, kill it */
1677
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1678
		killbypid("{$g['varrun_path']}/ntpd.pid");
1679
	}
1680
	@unlink("{$g['varrun_path']}/ntpd.pid");
1681

    
1682
	/* if /var/empty does not exist, create it */
1683
	if(!is_dir("/var/empty"))
1684
		mkdir("/var/empty", 0775, true);
1685

    
1686
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1687
	mwexec("/usr/local/sbin/ntpd -g -c {$g['varetc_path']}/ntpd.conf -p {$g['varrun_path']}/ntpd.pid", false, true);
1688
	
1689
	// Note that we are starting up
1690
	log_error("NTPD is starting up.");
1691
	return;
1692
}
1693

    
1694
function sync_system_time() {
1695
	global $config, $g;
1696

    
1697
	if ($g['booting'])
1698
		echo gettext("Syncing system time before startup...");
1699

    
1700
	/* foreach through servers and write out to ntpd.conf */
1701
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1702
		mwexec("/usr/local/sbin/ntpdate -s $ts");
1703
	}
1704
	
1705
	if ($g['booting'])
1706
		echo gettext("done.") . "\n";
1707
	
1708
}
1709

    
1710
function system_halt() {
1711
	global $g;
1712

    
1713
	system_reboot_cleanup();
1714

    
1715
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1716
}
1717

    
1718
function system_reboot() {
1719
	global $g;
1720

    
1721
	system_reboot_cleanup();
1722

    
1723
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1724
}
1725

    
1726
function system_reboot_sync() {
1727
	global $g;
1728

    
1729
	system_reboot_cleanup();
1730

    
1731
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1732
}
1733

    
1734
function system_reboot_cleanup() {
1735
	global $config, $cpzone;
1736

    
1737
	mwexec("/usr/local/bin/beep.sh stop");
1738
	require_once("captiveportal.inc");
1739
	if (is_array($config['captiveportal'])) {
1740
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
1741
			captiveportal_radius_stop_all();
1742
			captiveportal_send_server_accounting(true);
1743
		}
1744
	}
1745
	require_once("voucher.inc");
1746
	voucher_save_db_to_config();
1747
	require_once("pkg-utils.inc");
1748
	stop_packages();
1749
}
1750

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

    
1758
	if ($early)
1759
		$cmdn = "earlyshellcmd";
1760
	else
1761
		$cmdn = "shellcmd";
1762

    
1763
	if (is_array($config['system'][$cmdn])) {
1764

    
1765
		/* *cmd is an array, loop through */
1766
		foreach ($config['system'][$cmdn] as $cmd) {
1767
			exec($cmd);
1768
		}
1769

    
1770
	} elseif($config['system'][$cmdn] <> "") {
1771

    
1772
		/* execute single item */
1773
		exec($config['system'][$cmdn]);
1774

    
1775
	}
1776
}
1777

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

    
1785
	if (isset($config['system']['disableconsolemenu'])) {
1786
		touch("{$g['varetc_path']}/disableconsole");
1787
	} else {
1788
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1789
	}
1790
}
1791

    
1792
function system_dmesg_save() {
1793
	global $g;
1794
	if(isset($config['system']['developerspew'])) {
1795
		$mt = microtime();
1796
		echo "system_dmesg_save() being called $mt\n";
1797
	}
1798

    
1799
	$dmesg = "";
1800
	$_gb = exec("/sbin/dmesg", $dmesg);
1801

    
1802
	/* find last copyright line (output from previous boots may be present) */
1803
	$lastcpline = 0;
1804

    
1805
	for ($i = 0; $i < count($dmesg); $i++) {
1806
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1807
			$lastcpline = $i;
1808
	}
1809

    
1810
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1811
	if (!$fd) {
1812
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1813
		return 1;
1814
	}
1815

    
1816
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1817
		fwrite($fd, $dmesg[$i] . "\n");
1818

    
1819
	fclose($fd);
1820
	unset($dmesg);
1821

    
1822
	return 0;
1823
}
1824

    
1825
function system_set_harddisk_standby() {
1826
	global $g, $config;
1827
	if(isset($config['system']['developerspew'])) {
1828
		$mt = microtime();
1829
		echo "system_set_harddisk_standby() being called $mt\n";
1830
	}
1831

    
1832
	if (isset($config['system']['harddiskstandby'])) {
1833
		if ($g['booting']) {
1834
			echo gettext('Setting hard disk standby... ');
1835
		}
1836

    
1837
		$standby = $config['system']['harddiskstandby'];
1838
		// Check for a numeric value
1839
		if (is_numeric($standby)) {
1840
			// Sync the disk(s)
1841
			pfSense_sync();
1842
			if (set_single_sysctl('hw.ata.standby', (int)$standby)) {
1843
				// Reinitialize ATA-drives
1844
				mwexec('/usr/local/sbin/atareinit');
1845
				if ($g['booting']) {
1846
					echo gettext("done.") . "\n";
1847
				}
1848
			} else if ($g['booting']) {
1849
				echo gettext("failed!") . "\n";
1850
			}
1851
		} else if ($g['booting']) {
1852
			echo gettext("failed!") . "\n";
1853
		}
1854
	}
1855
}
1856

    
1857
function system_setup_sysctl() {
1858
	global $config;
1859
	if(isset($config['system']['developerspew'])) {
1860
		$mt = microtime();
1861
		echo "system_setup_sysctl() being called $mt\n";
1862
	}
1863

    
1864
	activate_sysctls();	
1865

    
1866
	if (isset($config['system']['sharednet'])) {
1867
		system_disable_arp_wrong_if();
1868
	}
1869
}
1870

    
1871
function system_disable_arp_wrong_if() {
1872
	global $config;
1873
	if(isset($config['system']['developerspew'])) {
1874
		$mt = microtime();
1875
		echo "system_disable_arp_wrong_if() being called $mt\n";
1876
	}
1877
	set_sysctl(array(
1878
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
1879
		"net.link.ether.inet.log_arp_movements" => "0"
1880
	));
1881
}
1882

    
1883
function system_enable_arp_wrong_if() {
1884
	global $config;
1885
	if(isset($config['system']['developerspew'])) {
1886
		$mt = microtime();
1887
		echo "system_enable_arp_wrong_if() being called $mt\n";
1888
	}
1889
	set_sysctl(array(
1890
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
1891
		"net.link.ether.inet.log_arp_movements" => "1"
1892
	));
1893
}
1894

    
1895
function enable_watchdog() {
1896
	global $config;
1897
	return;
1898
	$install_watchdog = false;
1899
	$supported_watchdogs = array("Geode");
1900
	$file = file_get_contents("/var/log/dmesg.boot");
1901
	foreach($supported_watchdogs as $sd) {
1902
		if(stristr($file, "Geode")) {
1903
			$install_watchdog = true;
1904
		}
1905
	}
1906
	if($install_watchdog == true) {
1907
		if(is_process_running("watchdogd"))
1908
			mwexec("/usr/bin/killall watchdogd", true);
1909
		exec("/usr/sbin/watchdogd");
1910
	}
1911
}
1912

    
1913
function system_check_reset_button() {
1914
	global $g;
1915
	if($g['platform'] != "nanobsd")
1916
		return 0;
1917

    
1918
	$specplatform = system_identify_specific_platform();
1919

    
1920
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1921
		return 0;
1922

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

    
1925
	if ($retval == 99) {
1926
		/* user has pressed reset button for 2 seconds - 
1927
		   reset to factory defaults */
1928
		echo <<<EOD
1929

    
1930
***********************************************************************
1931
* Reset button pressed - resetting configuration to factory defaults. *
1932
* The system will reboot after this completes.                        *
1933
***********************************************************************
1934

    
1935

    
1936
EOD;
1937
		
1938
		reset_factory_defaults();
1939
		system_reboot_sync();
1940
		exit(0);
1941
	}
1942

    
1943
	return 0;
1944
}
1945

    
1946
/* attempt to identify the specific platform (for embedded systems)
1947
   Returns an array with two elements:
1948
	name => platform string (e.g. 'wrap', 'alix' etc.)
1949
	descr => human-readable description (e.g. "PC Engines WRAP")
1950
*/
1951
function system_identify_specific_platform() {
1952
	global $g;
1953
	
1954
	if ($g['platform'] == 'generic-pc')
1955
		return array('name' => 'generic-pc', 'descr' => gettext("Generic PC"));
1956
	
1957
	if ($g['platform'] == 'generic-pc-cdrom')
1958
		return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)"));
1959
	
1960
	/* the rest of the code only deals with 'embedded' platforms */
1961
	if ($g['platform'] != 'nanobsd')
1962
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1963

    
1964
	$dmesg = get_single_sysctl('hw.model');
1965

    
1966
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1967
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
1968
	
1969
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1970
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
1971

    
1972
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1973
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1974
	
1975
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1976
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1977
		
1978
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1979
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1980
	
1981
	/* unknown embedded platform */
1982
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
1983
}
1984

    
1985
function system_get_dmesg_boot() {
1986
	global $g;
1987
		
1988
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1989
}
1990

    
1991
function get_possible_listen_ips($include_ipv6_link_local=false) {
1992
	$interfaces = get_configured_interface_with_descr();
1993
	$carplist = get_configured_carp_interface_list();
1994
	$listenips = array();
1995
	foreach ($carplist as $cif => $carpip)
1996
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1997
	$aliaslist = get_configured_ip_aliases_list();
1998
	foreach ($aliaslist as $aliasip => $aliasif)
1999
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
2000
	foreach ($interfaces as $iface => $ifacename) {
2001
		$tmp["name"]  = $ifacename;
2002
		$tmp["value"] = $iface;
2003
		$listenips[] = $tmp;
2004
		if ($include_ipv6_link_local) {
2005
			$llip = find_interface_ipv6_ll(get_real_interface($iface));
2006
			if (!empty($llip)) {
2007
				$tmp["name"]  = "{$ifacename} IPv6 Link-Local";
2008
				$tmp["value"] = $llip;
2009
				$listenips[] = $tmp;
2010
			}
2011
		}
2012
	}
2013
	$tmp["name"]  = "Localhost";
2014
	$tmp["value"] = "lo0";
2015
	$listenips[] = $tmp;
2016
	return $listenips;
2017
}
2018

    
2019
function get_possible_traffic_source_addresses($include_ipv6_link_local=false) {
2020
	global $config;
2021
	$sourceips = get_possible_listen_ips($include_ipv6_link_local);
2022
	foreach (array('server', 'client') as $mode) {
2023
		if (is_array($config['openvpn']["openvpn-{$mode}"])) {
2024
			foreach ($config['openvpn']["openvpn-{$mode}"] as $id => $setting) {
2025
				if (!isset($setting['disable'])) {
2026
					$vpn = array();
2027
					$vpn['value'] = 'ovpn' . substr($mode, 0, 1) . $setting['vpnid'];
2028
					$vpn['name'] = gettext("OpenVPN") . " ".$mode.": ".htmlspecialchars($setting['description']);
2029
					$sourceips[] = $vpn;
2030
				}
2031
			}
2032
		}
2033
	}
2034
	return $sourceips;
2035
}
2036
?>
(53-53/68)