Projet

Général

Profil

Télécharger (62,6 ko) Statistiques
| Branche: | Tag: | Révision:

univnautes / etc / inc / system.inc @ 1f4ad8f4

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_start() {
834
	global $config, $g;
835

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

    
839
	chdir($g['www_path']);
840

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

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

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

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

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

    
895
	sleep(1);
896

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

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

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

    
909
	return $res;
910
}
911

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

    
923
	global $config, $g;
924

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

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

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

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

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

    
961
	$memory = get_memory();
962
	$realmem = $memory[1];
963

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

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

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

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

    
998

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

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

    
1033
EOD;
1034
	}
1035

    
1036

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

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

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

    
1055
server.max-keep-alive-requests = 15
1056
server.max-keep-alive-idle = 30
1057

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

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

    
1066
{$lighty_use_syslog}
1067

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

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

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

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

    
1135

    
1136
######### Options that are good to be but not neccesary to be changed #######
1137

    
1138
## bind to port (default: 80)
1139

    
1140
EOD;
1141

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

    
1156

    
1157
	$lighty_config .= <<<EOD
1158

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

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

    
1166
## virtual directory listings
1167
server.dir-listing         = "disable"
1168

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

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

    
1179
{$server_upload_dirs}
1180

    
1181
{$server_max_request_size}
1182

    
1183
{$fastcgi_config}
1184

    
1185
{$cgi_config}
1186

    
1187
{$captive_portal_mod_evasive}
1188

    
1189
expire.url = (
1190
				"" => "access 50 hours",	
1191
        )
1192

    
1193
EOD;
1194

    
1195
	$cert = str_replace("\r", "", $cert);
1196
	$key = str_replace("\r", "", $key);
1197
	$ca = str_replace("\r", "", $ca);
1198

    
1199
	$cert = str_replace("\n\n", "\n", $cert);
1200
	$key = str_replace("\n\n", "\n", $key);
1201
	$ca = str_replace("\n\n", "\n", $ca);
1202

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

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

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

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

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

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

    
1275
	$fd = fopen("{$filename}", "w");
1276
	if (!$fd) {
1277
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1278
		return 1;
1279
	}
1280
	fwrite($fd, $lighty_config);
1281
	fclose($fd);
1282

    
1283
	return 0;
1284

    
1285
}
1286

    
1287
function system_timezone_configure() {
1288
	global $config, $g;
1289
	if(isset($config['system']['developerspew'])) {
1290
		$mt = microtime();
1291
		echo "system_timezone_configure() being called $mt\n";
1292
	}
1293

    
1294
	$syscfg = $config['system'];
1295

    
1296
	if ($g['booting'])
1297
		echo gettext("Setting timezone...");
1298

    
1299
	/* extract appropriate timezone file */
1300
	$timezone = $syscfg['timezone'];
1301
	if ($timezone) {
1302
		exec('/usr/bin/tar -tvzf /usr/share/zoneinfo.tgz', $tzs);
1303
		foreach ($tzs as $tz) {
1304
			if (preg_match(",{$timezone}$,", $tz))
1305
				break;
1306
			if (preg_match(",{$timezone} link to *(.*)$,", $tz, $matches)) {
1307
				$timezone = $matches[1];
1308
				break;
1309
			}
1310
		}
1311
	} else
1312
		$timezone = "Etc/UTC";
1313

    
1314
	conf_mount_rw();
1315

    
1316
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1317
		escapeshellarg($timezone) . " > /etc/localtime");
1318

    
1319
	mwexec("sync");
1320
	conf_mount_ro();
1321

    
1322
	if ($g['booting'])
1323
		echo gettext("done.") . "\n";
1324
}
1325

    
1326
function system_ntp_setup_gps($serialport) {
1327
	global $config, $g;
1328
	$gps_device = '/dev/gps0';
1329
	$serialport = '/dev/'.$serialport;
1330

    
1331
	if (!file_exists($serialport))
1332
		return false;
1333

    
1334
	conf_mount_rw();
1335
	// Create symlink that ntpd requires
1336
	unlink_if_exists($gps_device);
1337
	symlink($serialport, $gps_device);
1338

    
1339
	/* Send the following to the GPS port to initialize the GPS */
1340
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
1341
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
1342
	}else{
1343
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1344
	}
1345

    
1346
	/* XXX: Why not file_put_contents to the device */
1347
	@file_put_contents('/tmp/gps.init', $gps_init);
1348
	`cat /tmp/gps.init > $serialport`;
1349

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

    
1375
	conf_mount_ro();
1376

    
1377
	return true;
1378
}
1379

    
1380
function system_ntp_setup_pps($serialport) {
1381
	global $config, $g;
1382

    
1383
	$pps_device = '/dev/pps0';
1384
	$serialport = '/dev/'.$serialport;
1385

    
1386
	if (!file_exists($serialport))
1387
		return false;
1388

    
1389
	conf_mount_rw();
1390
	// Create symlink that ntpd requires
1391
	unlink_if_exists($pps_device);
1392
	@symlink($serialport, $pps_device);
1393

    
1394
	conf_mount_ro();
1395

    
1396
	return true;
1397
}
1398

    
1399

    
1400
function system_ntp_configure($start_ntpd=true) {
1401
	global $config, $g;
1402

    
1403
	$driftfile = "/var/db/ntpd.drift";
1404
	$statsdir = "/var/log/ntp";
1405
	$gps_device = '/dev/gps0';
1406

    
1407
	if ($g['platform'] == 'jail')
1408
		return;
1409

    
1410
	safe_mkdir($statsdir);
1411

    
1412
	if (!is_array($config['ntpd']))
1413
		$config['ntpd'] = array();
1414

    
1415
	$ntpcfg = "# \n";
1416
	$ntpcfg .= "# pfSense ntp configuration file \n";
1417
	$ntpcfg .= "# \n\n";
1418
	$ntpcfg .= "tinker panic 0 \n";
1419

    
1420
	/* Add Orphan mode */
1421
	$ntpcfg .= "# Orphan mode stratum\n";
1422
	$ntpcfg .= 'tos orphan ';
1423
	if (!empty($config['ntpd']['orphan'])) {
1424
		$ntpcfg .= $config['ntpd']['orphan'];
1425
	}else{
1426
		$ntpcfg .= '12';
1427
	}
1428
	$ntpcfg .= "\n";
1429

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

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

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

    
1618
	/* A leapseconds file is really only useful if this clock is stratum 1 */
1619
	$ntpcfg .= "\n";
1620
	if (!empty($config['ntpd']['leapsec'])) {
1621
		$leapsec .= base64_decode($config['ntpd']['leapsec']);
1622
		file_put_contents('/var/db/leap-seconds', $leapsec);
1623
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
1624
	}
1625
	
1626

    
1627
	if (empty($config['ntpd']['interface']))
1628
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface']))
1629
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1630
		else
1631
			$interfaces = array();
1632
	else
1633
		$interfaces = explode(",", $config['ntpd']['interface']);
1634

    
1635
	if (is_array($interfaces) && count($interfaces)) {
1636
		$ntpcfg .= "interface ignore all\n";
1637
		foreach ($interfaces as $interface) {
1638
			if (!is_ipaddr($interface)) {
1639
				$interface = get_real_interface($interface);
1640
			}
1641
			if (!empty($interface))
1642
				$ntpcfg .= "interface listen {$interface}\n";
1643
		}
1644
	}
1645

    
1646
	/* open configuration for wrting or bail */
1647
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
1648
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1649
		return;
1650
	}
1651

    
1652
	/* At bootup we just want to write out the config. */
1653
	if (!$start_ntpd)
1654
		return;
1655

    
1656
	/* if ntpd is running, kill it */
1657
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1658
		killbypid("{$g['varrun_path']}/ntpd.pid");
1659
	}
1660
	@unlink("{$g['varrun_path']}/ntpd.pid");
1661

    
1662
	/* if /var/empty does not exist, create it */
1663
	if(!is_dir("/var/empty"))
1664
		mkdir("/var/empty", 0775, true);
1665

    
1666
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1667
	mwexec("/usr/local/sbin/ntpd -g -c {$g['varetc_path']}/ntpd.conf -p {$g['varrun_path']}/ntpd.pid", false, true);
1668
	
1669
	// Note that we are starting up
1670
	log_error("NTPD is starting up.");
1671
	return;
1672
}
1673

    
1674
function sync_system_time() {
1675
	global $config, $g;
1676

    
1677
	if ($g['booting'])
1678
		echo gettext("Syncing system time before startup...");
1679

    
1680
	/* foreach through servers and write out to ntpd.conf */
1681
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1682
		mwexec("/usr/local/sbin/ntpdate -s $ts");
1683
	}
1684
	
1685
	if ($g['booting'])
1686
		echo gettext("done.") . "\n";
1687
	
1688
}
1689

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

    
1693
	system_reboot_cleanup();
1694

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

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

    
1701
	system_reboot_cleanup();
1702

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

    
1706
function system_reboot_sync() {
1707
	global $g;
1708

    
1709
	system_reboot_cleanup();
1710

    
1711
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1712
}
1713

    
1714
function system_reboot_cleanup() {
1715
	global $config, $cpzone;
1716

    
1717
	mwexec("/usr/local/bin/beep.sh stop");
1718
	require_once("captiveportal.inc");
1719
	if (is_array($config['captiveportal'])) {
1720
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
1721
			captiveportal_radius_stop_all();
1722
			captiveportal_send_server_accounting(true);
1723
		}
1724
	}
1725
	require_once("voucher.inc");
1726
	voucher_save_db_to_config();
1727
	require_once("pkg-utils.inc");
1728
	stop_packages();
1729
}
1730

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

    
1738
	if ($early)
1739
		$cmdn = "earlyshellcmd";
1740
	else
1741
		$cmdn = "shellcmd";
1742

    
1743
	if (is_array($config['system'][$cmdn])) {
1744

    
1745
		/* *cmd is an array, loop through */
1746
		foreach ($config['system'][$cmdn] as $cmd) {
1747
			exec($cmd);
1748
		}
1749

    
1750
	} elseif($config['system'][$cmdn] <> "") {
1751

    
1752
		/* execute single item */
1753
		exec($config['system'][$cmdn]);
1754

    
1755
	}
1756
}
1757

    
1758
function system_console_configure() {
1759
	global $config, $g;
1760
	if(isset($config['system']['developerspew'])) {
1761
		$mt = microtime();
1762
		echo "system_console_configure() being called $mt\n";
1763
	}
1764

    
1765
	if (isset($config['system']['disableconsolemenu'])) {
1766
		touch("{$g['varetc_path']}/disableconsole");
1767
	} else {
1768
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1769
	}
1770
}
1771

    
1772
function system_dmesg_save() {
1773
	global $g;
1774
	if(isset($config['system']['developerspew'])) {
1775
		$mt = microtime();
1776
		echo "system_dmesg_save() being called $mt\n";
1777
	}
1778

    
1779
	$dmesg = "";
1780
	$_gb = exec("/sbin/dmesg", $dmesg);
1781

    
1782
	/* find last copyright line (output from previous boots may be present) */
1783
	$lastcpline = 0;
1784

    
1785
	for ($i = 0; $i < count($dmesg); $i++) {
1786
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1787
			$lastcpline = $i;
1788
	}
1789

    
1790
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1791
	if (!$fd) {
1792
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1793
		return 1;
1794
	}
1795

    
1796
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1797
		fwrite($fd, $dmesg[$i] . "\n");
1798

    
1799
	fclose($fd);
1800
	unset($dmesg);
1801

    
1802
	return 0;
1803
}
1804

    
1805
function system_set_harddisk_standby() {
1806
	global $g, $config;
1807
	if(isset($config['system']['developerspew'])) {
1808
		$mt = microtime();
1809
		echo "system_set_harddisk_standby() being called $mt\n";
1810
	}
1811

    
1812
	if (isset($config['system']['harddiskstandby'])) {
1813
		if ($g['booting']) {
1814
			echo gettext('Setting hard disk standby... ');
1815
		}
1816

    
1817
		$standby = $config['system']['harddiskstandby'];
1818
		// Check for a numeric value
1819
		if (is_numeric($standby)) {
1820
			// Sync the disk(s)
1821
			pfSense_sync();
1822
			if (set_single_sysctl('hw.ata.standby', (int)$standby)) {
1823
				// Reinitialize ATA-drives
1824
				mwexec('/usr/local/sbin/atareinit');
1825
				if ($g['booting']) {
1826
					echo gettext("done.") . "\n";
1827
				}
1828
			} else if ($g['booting']) {
1829
				echo gettext("failed!") . "\n";
1830
			}
1831
		} else if ($g['booting']) {
1832
			echo gettext("failed!") . "\n";
1833
		}
1834
	}
1835
}
1836

    
1837
function system_setup_sysctl() {
1838
	global $config;
1839
	if(isset($config['system']['developerspew'])) {
1840
		$mt = microtime();
1841
		echo "system_setup_sysctl() being called $mt\n";
1842
	}
1843

    
1844
	activate_sysctls();	
1845

    
1846
	if (isset($config['system']['sharednet'])) {
1847
		system_disable_arp_wrong_if();
1848
	}
1849
}
1850

    
1851
function system_disable_arp_wrong_if() {
1852
	global $config;
1853
	if(isset($config['system']['developerspew'])) {
1854
		$mt = microtime();
1855
		echo "system_disable_arp_wrong_if() being called $mt\n";
1856
	}
1857
	set_sysctl(array(
1858
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
1859
		"net.link.ether.inet.log_arp_movements" => "0"
1860
	));
1861
}
1862

    
1863
function system_enable_arp_wrong_if() {
1864
	global $config;
1865
	if(isset($config['system']['developerspew'])) {
1866
		$mt = microtime();
1867
		echo "system_enable_arp_wrong_if() being called $mt\n";
1868
	}
1869
	set_sysctl(array(
1870
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
1871
		"net.link.ether.inet.log_arp_movements" => "1"
1872
	));
1873
}
1874

    
1875
function enable_watchdog() {
1876
	global $config;
1877
	return;
1878
	$install_watchdog = false;
1879
	$supported_watchdogs = array("Geode");
1880
	$file = file_get_contents("/var/log/dmesg.boot");
1881
	foreach($supported_watchdogs as $sd) {
1882
		if(stristr($file, "Geode")) {
1883
			$install_watchdog = true;
1884
		}
1885
	}
1886
	if($install_watchdog == true) {
1887
		if(is_process_running("watchdogd"))
1888
			mwexec("/usr/bin/killall watchdogd", true);
1889
		exec("/usr/sbin/watchdogd");
1890
	}
1891
}
1892

    
1893
function system_check_reset_button() {
1894
	global $g;
1895
	if($g['platform'] != "nanobsd")
1896
		return 0;
1897

    
1898
	$specplatform = system_identify_specific_platform();
1899

    
1900
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1901
		return 0;
1902

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

    
1905
	if ($retval == 99) {
1906
		/* user has pressed reset button for 2 seconds - 
1907
		   reset to factory defaults */
1908
		echo <<<EOD
1909

    
1910
***********************************************************************
1911
* Reset button pressed - resetting configuration to factory defaults. *
1912
* The system will reboot after this completes.                        *
1913
***********************************************************************
1914

    
1915

    
1916
EOD;
1917
		
1918
		reset_factory_defaults();
1919
		system_reboot_sync();
1920
		exit(0);
1921
	}
1922

    
1923
	return 0;
1924
}
1925

    
1926
/* attempt to identify the specific platform (for embedded systems)
1927
   Returns an array with two elements:
1928
	name => platform string (e.g. 'wrap', 'alix' etc.)
1929
	descr => human-readable description (e.g. "PC Engines WRAP")
1930
*/
1931
function system_identify_specific_platform() {
1932
	global $g;
1933
	
1934
	if ($g['platform'] == 'generic-pc')
1935
		return array('name' => 'generic-pc', 'descr' => gettext("Generic PC"));
1936
	
1937
	if ($g['platform'] == 'generic-pc-cdrom')
1938
		return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)"));
1939
	
1940
	/* the rest of the code only deals with 'embedded' platforms */
1941
	if ($g['platform'] != 'nanobsd')
1942
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1943

    
1944
	$dmesg = get_single_sysctl('hw.model');
1945

    
1946
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1947
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
1948
	
1949
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1950
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
1951

    
1952
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1953
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1954
	
1955
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1956
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1957
		
1958
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1959
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1960
	
1961
	/* unknown embedded platform */
1962
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
1963
}
1964

    
1965
function system_get_dmesg_boot() {
1966
	global $g;
1967
		
1968
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1969
}
1970

    
1971
function get_possible_listen_ips($include_ipv6_link_local=false) {
1972
	$interfaces = get_configured_interface_with_descr();
1973
	$carplist = get_configured_carp_interface_list();
1974
	$listenips = array();
1975
	foreach ($carplist as $cif => $carpip)
1976
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1977
	$aliaslist = get_configured_ip_aliases_list();
1978
	foreach ($aliaslist as $aliasip => $aliasif)
1979
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1980
	foreach ($interfaces as $iface => $ifacename) {
1981
		$tmp["name"]  = $ifacename;
1982
		$tmp["value"] = $iface;
1983
		$listenips[] = $tmp;
1984
		if ($include_ipv6_link_local) {
1985
			$llip = find_interface_ipv6_ll(get_real_interface($iface));
1986
			if (!empty($llip)) {
1987
				$tmp["name"]  = "{$ifacename} IPv6 Link-Local";
1988
				$tmp["value"] = $llip;
1989
				$listenips[] = $tmp;
1990
			}
1991
		}
1992
	}
1993
	$tmp["name"]  = "Localhost";
1994
	$tmp["value"] = "lo0";
1995
	$listenips[] = $tmp;
1996
	return $listenips;
1997
}
1998

    
1999
function get_possible_traffic_source_addresses($include_ipv6_link_local=false) {
2000
	global $config;
2001
	$sourceips = get_possible_listen_ips($include_ipv6_link_local);
2002
	foreach (array('server', 'client') as $mode) {
2003
		if (is_array($config['openvpn']["openvpn-{$mode}"])) {
2004
			foreach ($config['openvpn']["openvpn-{$mode}"] as $id => $setting) {
2005
				if (!isset($setting['disable'])) {
2006
					$vpn = array();
2007
					$vpn['value'] = 'ovpn' . substr($mode, 0, 1) . $setting['vpnid'];
2008
					$vpn['name'] = gettext("OpenVPN") . " ".$mode.": ".htmlspecialchars($setting['description']);
2009
					$sourceips[] = $vpn;
2010
				}
2011
			}
2012
		}
2013
	}
2014
	return $sourceips;
2015
}
2016
?>
(53-53/68)