Projet

Général

Profil

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

univnautes / etc / inc / system.inc @ 26d060bc

1
<?php
2
/* $Id$ */
3
/*
4
	system.inc
5
	part of m0n0wall (http://m0n0.ch/wall)
6

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
106
	if (((isset($config['dnsmasq']['enable']) && (empty($config['dnsmasq']['interface']) || in_array("lo0", explode(",", $config['dnsmasq']['interface']))))
107
		|| (isset($config['unbound']['enable'])) && (empty($config['unbound']['active_interface']) || in_array("lo0", explode(",", $config['unbound']['active_interface']))))
108
		&& !isset($config['system']['dnslocalhost']))
109
		$resolvconf .= "nameserver 127.0.0.1\n";
110

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

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

    
135
	$dnslock = lock('resolvconf', LOCK_EX);
136

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

    
144
	fwrite($fd, $resolvconf);
145
	fclose($fd);
146

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

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

    
175
	unlock($dnslock);
176

    
177
	return 0;
178
}
179

    
180
function get_searchdomains() {
181
	global $config, $g;
182

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

    
199
	return $master_list;
200
}
201

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

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

    
230
	return $master_list;
231
}
232

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

    
240
	$syscfg = $config['system'];
241
	$dnsmasqcfg = $config['dnsmasq'];
242

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

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

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

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

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

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

    
327
	if (isset($config['unbound']['enable'])) {
328
		require_once("unbound.inc");
329
		unbound_hosts_generate();
330
	}
331

    
332
	system_dhcpleases_configure();
333

    
334
	return 0;
335
}
336

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

    
364
function system_hostname_configure() {
365
	global $config, $g;
366
	if(isset($config['system']['developerspew'])) {
367
		$mt = microtime();
368
		echo "system_hostname_configure() being called $mt\n";
369
	}
370

    
371
	$syscfg = $config['system'];
372

    
373
	/* set hostname */
374
	$status = mwexec("/bin/hostname " .
375
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
376

    
377
    /* Setup host GUID ID.  This is used by ZFS. */
378
	mwexec("/etc/rc.d/hostid start");
379

    
380
	return $status;
381
}
382

    
383
function system_routing_configure($interface = "") {
384
	global $config, $g;
385
	if ($g['platform'] == 'jail')
386
		return;
387
	if(isset($config['system']['developerspew'])) {
388
		$mt = microtime();
389
		echo "system_routing_configure() being called $mt\n";
390
	}
391

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

    
457
	if ($dont_add_route == false ) {
458
		if (!empty($interface) && $interface != $interfacegw)
459
			;
460
		else if (($interfacegw <> "bgpd") && (is_ipaddrv4($gatewayip))) {
461
			log_error("ROUTING: setting default route to $gatewayip");
462
			mwexec("/sbin/route change -inet default " . escapeshellarg($gatewayip));
463
		}
464

    
465
		if (!empty($interface) && $interface != $interfacegwv6)
466
			;
467
		else if (($interfacegwv6 <> "bgpd") && (is_ipaddrv6($gatewayipv6))) {
468
			$ifscope = "";
469
			if (is_linklocal($gatewayipv6))
470
				$ifscope = "%{$defaultifv6}";
471
			log_error("ROUTING: setting IPv6 default route to {$gatewayipv6}{$ifscope}");
472
			mwexec("/sbin/route change -inet6 default " . escapeshellarg($gatewayipv6) ."{$ifscope}");
473
		}
474
	}
475

    
476
	system_staticroutes_configure($interface, false);
477

    
478
	return 0;
479
}
480

    
481
function system_staticroutes_configure($interface = "", $update_dns = false) {
482
	global $config, $g, $aliastable;
483

    
484
	$filterdns_list = array();
485

    
486
	$static_routes = get_staticroutes(false, true);
487
	if (count($static_routes)) {
488
		$gateways_arr = return_gateways_array(false, true);
489

    
490
		foreach ($static_routes as $rtent) {
491
			if (empty($gateways_arr[$rtent['gateway']])) {
492
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
493
				continue;
494
			}
495
			$gateway = $gateways_arr[$rtent['gateway']];
496
			if (!empty($interface) && $interface != $gateway['friendlyiface'])
497
				continue;
498

    
499
			$gatewayip = $gateway['gateway'];
500
			$interfacegw = $gateway['interface'];
501

    
502
			$blackhole = "";
503
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 3)))
504
				$blackhole = "-blackhole";
505

    
506
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network']))
507
				continue;
508

    
509
			$dnscache = array();
510
			if ($update_dns === true) {
511
				if (is_subnet($rtent['network']))
512
					continue;
513
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
514
				if (empty($dnscache))
515
					continue;
516
			}
517

    
518
			if (is_subnet($rtent['network']))
519
				$ips = array($rtent['network']);
520
			else {
521
				if (!isset($rtent['disabled']))
522
					$filterdns_list[] = $rtent['network'];
523
				$ips = add_hostname_to_watch($rtent['network']);
524
			}
525

    
526
			foreach ($dnscache as $ip) {
527
				if (in_array($ip, $ips))
528
					continue;
529
				mwexec("/sbin/route delete " . escapeshellarg($ip), true);
530
			}
531

    
532
			if (isset($rtent['disabled'])) {
533
				/* XXX: This is a bit dangerous in case of routing daemons!? */
534
				foreach ($ips as $ip)
535
					mwexec("/sbin/route delete " . escapeshellarg($ip), true);
536
				continue;
537
			}
538

    
539
			foreach ($ips as $ip) {
540
				if (is_ipaddrv4($ip))
541
					$ip .= "/32";
542
				else if (is_ipaddrv6($ip))
543
					$ip .= "/128";
544

    
545
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
546

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

    
549
				if (is_subnet($ip))
550
					if (is_ipaddr($gatewayip))
551
						mwexec($cmd . escapeshellarg($gatewayip));
552
					else if (!empty($interfacegw))
553
						mwexec($cmd . "-iface " . escapeshellarg($interfacegw));
554
			}
555
		}
556
		unset($gateways_arr);
557
	}
558
	unset($static_routes);
559

    
560
	if ($update_dns === false) {
561
		if (count($filterdns_list)) {
562
			$interval = 60;
563
			$hostnames = "";
564
			array_unique($filterdns_list);
565
			foreach ($filterdns_list as $hostname)
566
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
567
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
568
			unset($hostnames);
569

    
570
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid"))
571
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
572
			else
573
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
574
		} else {
575
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
576
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
577
		}
578
	}
579
	unset($filterdns_list);
580

    
581
	return 0;
582
}
583

    
584
function system_routing_enable() {
585
	global $config, $g;
586
	if(isset($config['system']['developerspew'])) {
587
		$mt = microtime();
588
		echo "system_routing_enable() being called $mt\n";
589
	}
590

    
591
	mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
592
	mwexec("/sbin/sysctl net.inet6.ip6.forwarding=1");
593
	return;
594
}
595

    
596
function system_syslogd_fixup_server($server) {
597
	/* If it's an IPv6 IP alone, encase it in brackets */
598
	if (is_ipaddrv6($server))
599
		return "[$server]";
600
	else
601
		return $server;
602
}
603

    
604
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
605
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
606
	$facility .= " ".
607
	$remote_servers = "";
608
	$pad_to  = 56;
609
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
610
	if($syslogcfg['remoteserver'])
611
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
612
	if($syslogcfg['remoteserver2'])
613
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
614
	if($syslogcfg['remoteserver3'])
615
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
616
	return $remote_servers;
617
}
618

    
619
function system_syslogd_start() {
620
	global $config, $g;
621
	if(isset($config['system']['developerspew'])) {
622
		$mt = microtime();
623
		echo "system_syslogd_start() being called $mt\n";
624
	}
625

    
626
	mwexec("/etc/rc.d/hostid start");
627

    
628
	$syslogcfg = $config['syslog'];
629

    
630
	if ($g['booting'])
631
		echo gettext("Starting syslog...");
632

    
633
	if (is_process_running("fifolog_writer"))
634
		mwexec('/bin/pkill fifolog_writer');
635

    
636
	// Which logging type are we using this week??
637
	if (isset($config['system']['disablesyslogclog'])) {
638
		$log_directive = "";
639
		$log_create_directive = "/usr/bin/touch ";
640
		$log_size = "";
641
	} else if (isset($config['system']['usefifolog'])) {
642
		$log_directive = "|/usr/sbin/fifolog_writer ";
643
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
644
		$log_create_directive = "/usr/sbin/fifolog_create -s ";
645
	} else { // Defaults to CLOG
646
		$log_directive = "%";
647
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
648
		$log_create_directive = "/usr/local/sbin/clog -i -s ";
649
	}
650

    
651
	$syslogd_extra = "";
652
	if (isset($syslogcfg)) {
653
		$separatelogfacilities = array('ntp','ntpd','ntpdate','charon','openvpn','pptps','poes','l2tps','relayd','hostapd','dnsmasq','filterdns','unbound','dhcpd','dhcrelay','dhclient','apinger','radvd','routed','olsrd','zebra','ospfd','bgpd','miniupnpd','filterlog');
654
		$syslogconf = "";
655
		if($config['installedpackages']['package']) {
656
			foreach($config['installedpackages']['package'] as $package) {
657
				if($package['logging']) {
658
					array_push($separatelogfacilities, $package['logging']['facilityname']);
659
					mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
660
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
661
				}
662
			}
663
		}
664
		$facilitylist = implode(',', array_unique($separatelogfacilities));
665
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd,miniupnpd\n";
666
		if (!isset($syslogcfg['disablelocallogging']))
667
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
668

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

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

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

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

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

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

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

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

    
707
		$syslogconf .= "!dnsmasq,filterdns,unbound\n";
708
		if (!isset($syslogcfg['disablelocallogging']))
709
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
710

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

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

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

    
729
		$syslogconf .= "!filterlog\n";
730
		$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/filter.log\n";
731
		if (isset($syslogcfg['filter']))
732
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
733

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

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

    
768
		if (isset($syslogcfg['zmqserver'])) {
769
				$syslogconf .= <<<EOD
770
*.*								^{$syslogcfg['zmqserver']}
771

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

    
782
		// Ensure that the log directory exists
783
		if (!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
784
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
785

    
786
		$sourceip = "";
787
		if (!empty($syslogcfg['sourceip'])) {
788
			if ($syslogcfg['ipproto'] == "ipv6") {
789
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
790
				if (!is_ipaddr($ifaddr))
791
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
792
			} else {
793
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
794
				if (!is_ipaddr($ifaddr))
795
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
796
			}
797
			if (is_ipaddr($ifaddr)) {
798
				$sourceip = "-b {$ifaddr}";
799
			}
800
		}
801

    
802
		$syslogd_extra = "-f {$g['varetc_path']}/syslog.conf {$sourceip}";
803
	}
804

    
805
	if (isvalidpid("{$g['varrun_path']}/syslog.pid"))
806
		sigkillbypid("{$g['varrun_path']}/syslog.pid", "HUP");
807
	else
808
		$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}");
809

    
810
	if ($g['booting'])
811
		echo gettext("done.") . "\n";
812

    
813
	return $retval;
814
}
815

    
816
function system_webgui_start() {
817
	global $config, $g;
818

    
819
	if ($g['booting'])
820
		echo gettext("Starting webConfigurator...");
821

    
822
	chdir($g['www_path']);
823

    
824
	/* defaults */
825
	$portarg = "80";
826
	$crt = "";
827
	$key = "";
828
	$ca = "";
829

    
830
	/* non-standard port? */
831
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
832
		$portarg = "{$config['system']['webgui']['port']}";
833

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

    
870
	/* generate lighttpd configuration */
871
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
872
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
873
		"cert.pem", "ca.pem");
874

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

    
878
	sleep(1);
879

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

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

    
885
	if ($g['booting']) {
886
		if ($res == 0)
887
			echo gettext("done.") . "\n";
888
		else
889
			echo gettext("failed!") . "\n";
890
	}
891

    
892
	return $res;
893
}
894

    
895
function system_generate_lighty_config($filename,
896
	$cert,
897
	$key,
898
	$ca,
899
	$pid_file,
900
	$port = 80,
901
	$document_root = "/usr/local/www/",
902
	$cert_location = "cert.pem",
903
	$ca_location = "ca.pem",
904
	$captive_portal = false) {
905

    
906
	global $config, $g;
907

    
908
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
909
		mkdir("{$g['tmp_path']}/lighttpdcompress");
910

    
911
	if(isset($config['system']['developerspew'])) {
912
		$mt = microtime();
913
		echo "system_generate_lighty_config() being called $mt\n";
914
	}
915

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

    
920
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
921
		if (empty($maxprocperip))
922
			$maxprocperip = 10;
923
		$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
924

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

    
944
	$memory = get_memory();
945
	$realmem = $memory[1];
946

    
947
	// Determine web GUI process settings and take into account low memory systems
948
	if ($realmem < 255)
949
		$max_procs = 1;
950
	else
951
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
952

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

    
967
	} else {
968
		if ($realmem < 78)
969
			$max_php_children = 0;
970
		else
971
			$max_php_children = 1;
972
	}
973

    
974
	if(!isset($config['syslog']['nologlighttpd'])) {
975
		$lighty_use_syslog = <<<EOD
976
## where to send error-messages to
977
server.errorlog-use-syslog="enable"
978
EOD;
979
	}
980

    
981

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

    
1001
EOD;
1002
	} else {
1003
		$fast_cgi_path = "{$g['varrun_path']}/php-fpm.socket";
1004
		$fastcgi_config = <<<EOD
1005
#### fastcgi module
1006
## read fastcgi.txt for more info
1007
fastcgi.server = ( ".php" =>
1008
	( "localhost" =>
1009
		(
1010
			"socket" => "{$fast_cgi_path}",
1011
			"broken-scriptfilename" => "enable"
1012
		)
1013
	)
1014
)
1015

    
1016
EOD;
1017
	}
1018

    
1019

    
1020
	$lighty_config = <<<EOD
1021
#
1022
# lighttpd configuration file
1023
#
1024
# use a it as base for lighttpd 1.0.0 and above
1025
#
1026
############ Options you really have to take care of ####################
1027

    
1028
## FreeBSD!
1029
server.event-handler	= "freebsd-kqueue"
1030
server.network-backend 	= "writev"
1031
#server.use-ipv6 = "enable"
1032

    
1033
## modules to load
1034
server.modules              =   ( "mod_access", "mod_expire", "mod_compress", "mod_redirect",
1035
	{$captiveportal}, "mod_fastcgi"
1036
)
1037

    
1038
server.max-keep-alive-requests = 15
1039
server.max-keep-alive-idle = 30
1040

    
1041
## a static document-root, for virtual-hosting take look at the
1042
## server.virtual-* options
1043
server.document-root        = "{$document_root}"
1044
{$captive_portal_rewrite}
1045

    
1046
# Maximum idle time with nothing being written (php downloading)
1047
server.max-write-idle = 999
1048

    
1049
{$lighty_use_syslog}
1050

    
1051
# files to check for if .../ is requested
1052
server.indexfiles           = ( "index.php", "index.html",
1053
                                "index.htm", "default.htm" )
1054

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

    
1108
# Use the "Content-Type" extended attribute to obtain mime type if possible
1109
#mimetypes.use-xattr        = "enable"
1110

    
1111
## deny access the file-extensions
1112
#
1113
# ~    is for backupfiles from vi, emacs, joe, ...
1114
# .inc is often used for code includes which should in general not be part
1115
#      of the document-root
1116
url.access-deny             = ( "~", ".inc" )
1117

    
1118

    
1119
######### Options that are good to be but not neccesary to be changed #######
1120

    
1121
## bind to port (default: 80)
1122

    
1123
EOD;
1124

    
1125
	$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1126
	$lighty_config .= "server.port  = {$lighty_port}\n";
1127
	$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1128
	$lighty_config .= "\$SERVER[\"socket\"]  == \"[::]:{$lighty_port}\" { \n";
1129
	if($cert <> "" and $key <> "") {
1130
		$lighty_config .= "\n";
1131
		$lighty_config .= "## ssl configuration\n";
1132
		$lighty_config .= "ssl.engine = \"enable\"\n";
1133
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1134
		if($ca <> "")
1135
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1136
	}
1137
	$lighty_config .= " }\n";
1138

    
1139

    
1140
	$lighty_config .= <<<EOD
1141

    
1142
## error-handler for status 404
1143
#server.error-handler-404   = "/error-handler.html"
1144
#server.error-handler-404   = "/error-handler.php"
1145

    
1146
## to help the rc.scripts
1147
server.pid-file            = "{$g['varrun_path']}/{$pid_file}"
1148

    
1149
## virtual directory listings
1150
server.dir-listing         = "disable"
1151

    
1152
## enable debugging
1153
debug.log-request-header   = "disable"
1154
debug.log-response-header  = "disable"
1155
debug.log-request-handling = "disable"
1156
debug.log-file-not-found   = "disable"
1157

    
1158
# gzip compression
1159
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1160
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1161

    
1162
{$server_upload_dirs}
1163

    
1164
{$server_max_request_size}
1165

    
1166
{$fastcgi_config}
1167

    
1168
{$cgi_config}
1169

    
1170
{$captive_portal_mod_evasive}
1171

    
1172
expire.url = (
1173
				"" => "access 50 hours",	
1174
        )
1175

    
1176
EOD;
1177

    
1178
	$cert = str_replace("\r", "", $cert);
1179
	$key = str_replace("\r", "", $key);
1180
	$ca = str_replace("\r", "", $ca);
1181

    
1182
	$cert = str_replace("\n\n", "\n", $cert);
1183
	$key = str_replace("\n\n", "\n", $key);
1184
	$ca = str_replace("\n\n", "\n", $ca);
1185

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

    
1212
		// Harden SSL a bit for PCI conformance testing
1213
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
1214

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

    
1229
		if (isset($config['system']['webgui']['beast_protection'])) {
1230
			$lighty_config .= "ssl.honor-cipher-order = \"enable\"\n";
1231
			$lighty_config .= "ssl.cipher-list = \"ECDHE-RSA-AES256-SHA384:AES256-SHA256:RC4-SHA:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM\"\n";
1232
		} else {
1233
			$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";
1234
		}
1235

    
1236
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1237
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1238
	}
1239

    
1240
	// Add HTTP to HTTPS redirect	
1241
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1242
		if($lighty_port != "443") 
1243
			$redirectport = ":{$lighty_port}";
1244
		$lighty_config .= <<<EOD
1245
\$SERVER["socket"] == ":80" {
1246
	\$HTTP["host"] =~ "(.*)" {
1247
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1248
	}
1249
}
1250
EOD;
1251
	}
1252

    
1253
	$fd = fopen("{$filename}", "w");
1254
	if (!$fd) {
1255
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1256
		return 1;
1257
	}
1258
	fwrite($fd, $lighty_config);
1259
	fclose($fd);
1260

    
1261
	return 0;
1262

    
1263
}
1264

    
1265
function system_timezone_configure() {
1266
	global $config, $g;
1267
	if(isset($config['system']['developerspew'])) {
1268
		$mt = microtime();
1269
		echo "system_timezone_configure() being called $mt\n";
1270
	}
1271

    
1272
	$syscfg = $config['system'];
1273

    
1274
	if ($g['booting'])
1275
		echo gettext("Setting timezone...");
1276

    
1277
	/* extract appropriate timezone file */
1278
	$timezone = $syscfg['timezone'];
1279
	if ($timezone) {
1280
		exec('/usr/bin/tar -tvzf /usr/share/zoneinfo.tgz', $tzs);
1281
		foreach ($tzs as $tz) {
1282
			if (preg_match(",{$timezone}$,", $tz))
1283
				break;
1284
			if (preg_match(",{$timezone} link to *(.*)$,", $tz, $matches)) {
1285
				$timezone = $matches[1];
1286
				break;
1287
			}
1288
		}
1289
	} else
1290
		$timezone = "Etc/UTC";
1291

    
1292
	conf_mount_rw();
1293

    
1294
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1295
		escapeshellarg($timezone) . " > /etc/localtime");
1296

    
1297
	mwexec("sync");
1298
	conf_mount_ro();
1299

    
1300
	if ($g['booting'])
1301
		echo gettext("done.") . "\n";
1302
}
1303

    
1304
function system_ntp_setup_gps($serialport) {
1305
	global $config, $g;
1306
	$gps_device = '/dev/gps0';
1307
	$serialport = '/dev/'.$serialport;
1308

    
1309
	if (!file_exists($serialport))
1310
		return false;
1311

    
1312
	conf_mount_rw();
1313
	// Create symlink that ntpd requires
1314
	unlink_if_exists($gps_device);
1315
	symlink($serialport, $gps_device);
1316

    
1317
	/* Send the following to the GPS port to initialize the GPS */
1318
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
1319
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
1320
	}else{
1321
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1322
	}
1323

    
1324
	/* XXX: Why not file_put_contents to the device */
1325
	@file_put_contents('/tmp/gps.init', $gps_init);
1326
	`cat /tmp/gps.init > $serialport`;
1327

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

    
1353
	conf_mount_ro();
1354

    
1355
	return true;
1356
}
1357

    
1358
function system_ntp_setup_pps($serialport) {
1359
	global $config, $g;
1360

    
1361
	$pps_device = '/dev/pps0';
1362
	$serialport = '/dev/'.$serialport;
1363

    
1364
	if (!file_exists($serialport))
1365
		return false;
1366

    
1367
	conf_mount_rw();
1368
	// Create symlink that ntpd requires
1369
	unlink_if_exists($pps_device);
1370
	@symlink($serialport, $pps_device);
1371

    
1372
	conf_mount_ro();
1373

    
1374
	return true;
1375
}
1376

    
1377

    
1378
function system_ntp_configure($start_ntpd=true) {
1379
	global $config, $g;
1380

    
1381
	$driftfile = "/var/db/ntpd.drift";
1382
	$statsdir = "/var/log/ntp";
1383
	$gps_device = '/dev/gps0';
1384

    
1385
	if ($g['platform'] == 'jail')
1386
		return;
1387

    
1388
	safe_mkdir($statsdir);
1389

    
1390
	if (!is_array($config['ntpd']))
1391
		$config['ntpd'] = array();
1392

    
1393
	$ntpcfg = "# \n";
1394
	$ntpcfg .= "# pfSense ntp configuration file \n";
1395
	$ntpcfg .= "# \n\n";
1396
	$ntpcfg .= "tinker panic 0 \n";
1397

    
1398
	/* Add Orphan mode */
1399
	$ntpcfg .= "# Orphan mode stratum\n";
1400
	$ntpcfg .= 'tos orphan ';
1401
	if (!empty($config['ntpd']['orphan'])) {
1402
		$ntpcfg .= $config['ntpd']['orphan'];
1403
	}else{
1404
		$ntpcfg .= '12';
1405
	}
1406
	$ntpcfg .= "\n";
1407

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

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

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

    
1596
	/* A leapseconds file is really only useful if this clock is stratum 1 */
1597
	$ntpcfg .= "\n";
1598
	if (!empty($config['ntpd']['leapsec'])) {
1599
		$leapsec .= base64_decode($config['ntpd']['leapsec']);
1600
		file_put_contents('/var/db/leap-seconds', $leapsec);
1601
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
1602
	}
1603
	
1604

    
1605
	if (empty($config['ntpd']['interface']))
1606
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface']))
1607
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1608
		else
1609
			$interfaces = array();
1610
	else
1611
		$interfaces = explode(",", $config['ntpd']['interface']);
1612

    
1613
	if (is_array($interfaces) && count($interfaces)) {
1614
		$ntpcfg .= "interface ignore all\n";
1615
		foreach ($interfaces as $interface) {
1616
			if (!is_ipaddr($interface)) {
1617
				$interface = get_real_interface($interface);
1618
			}
1619
			if (!empty($interface))
1620
				$ntpcfg .= "interface listen {$interface}\n";
1621
		}
1622
	}
1623

    
1624
	/* open configuration for wrting or bail */
1625
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
1626
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1627
		return;
1628
	}
1629

    
1630
	/* At bootup we just want to write out the config. */
1631
	if (!$start_ntpd)
1632
		return;
1633

    
1634
	/* if ntpd is running, kill it */
1635
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1636
		killbypid("{$g['varrun_path']}/ntpd.pid");
1637
	}
1638
	@unlink("{$g['varrun_path']}/ntpd.pid");
1639

    
1640
	/* if /var/empty does not exist, create it */
1641
	if(!is_dir("/var/empty"))
1642
		mkdir("/var/empty", 0775, true);
1643

    
1644
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1645
	mwexec("/usr/local/sbin/ntpd -g -c {$g['varetc_path']}/ntpd.conf -p {$g['varrun_path']}/ntpd.pid", false, true);
1646
	
1647
	// Note that we are starting up
1648
	log_error("NTPD is starting up.");
1649
	return;
1650
}
1651

    
1652
function sync_system_time() {
1653
	global $config, $g;
1654

    
1655
	if ($g['booting'])
1656
		echo gettext("Syncing system time before startup...");
1657

    
1658
	/* foreach through servers and write out to ntpd.conf */
1659
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1660
		mwexec("/usr/local/sbin/ntpdate -s $ts");
1661
	}
1662
	
1663
	if ($g['booting'])
1664
		echo gettext("done.") . "\n";
1665
	
1666
}
1667

    
1668
function system_halt() {
1669
	global $g;
1670

    
1671
	system_reboot_cleanup();
1672

    
1673
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1674
}
1675

    
1676
function system_reboot() {
1677
	global $g;
1678

    
1679
	system_reboot_cleanup();
1680

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

    
1684
function system_reboot_sync() {
1685
	global $g;
1686

    
1687
	system_reboot_cleanup();
1688

    
1689
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1690
}
1691

    
1692
function system_reboot_cleanup() {
1693
	global $config, $cpzone;
1694

    
1695
	mwexec("/usr/local/bin/beep.sh stop");
1696
	require_once("captiveportal.inc");
1697
	if (is_array($config['captiveportal'])) {
1698
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
1699
			captiveportal_radius_stop_all();
1700
			captiveportal_send_server_accounting(true);
1701
		}
1702
	}
1703
	require_once("voucher.inc");
1704
	voucher_save_db_to_config();
1705
	require_once("pkg-utils.inc");
1706
	stop_packages();
1707
}
1708

    
1709
function system_do_shell_commands($early = 0) {
1710
	global $config, $g;
1711
	if(isset($config['system']['developerspew'])) {
1712
		$mt = microtime();
1713
		echo "system_do_shell_commands() being called $mt\n";
1714
	}
1715

    
1716
	if ($early)
1717
		$cmdn = "earlyshellcmd";
1718
	else
1719
		$cmdn = "shellcmd";
1720

    
1721
	if (is_array($config['system'][$cmdn])) {
1722

    
1723
		/* *cmd is an array, loop through */
1724
		foreach ($config['system'][$cmdn] as $cmd) {
1725
			exec($cmd);
1726
		}
1727

    
1728
	} elseif($config['system'][$cmdn] <> "") {
1729

    
1730
		/* execute single item */
1731
		exec($config['system'][$cmdn]);
1732

    
1733
	}
1734
}
1735

    
1736
function system_console_configure() {
1737
	global $config, $g;
1738
	if(isset($config['system']['developerspew'])) {
1739
		$mt = microtime();
1740
		echo "system_console_configure() being called $mt\n";
1741
	}
1742

    
1743
	if (isset($config['system']['disableconsolemenu'])) {
1744
		touch("{$g['varetc_path']}/disableconsole");
1745
	} else {
1746
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1747
	}
1748
}
1749

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

    
1757
	$dmesg = "";
1758
	$_gb = exec("/sbin/dmesg", $dmesg);
1759

    
1760
	/* find last copyright line (output from previous boots may be present) */
1761
	$lastcpline = 0;
1762

    
1763
	for ($i = 0; $i < count($dmesg); $i++) {
1764
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1765
			$lastcpline = $i;
1766
	}
1767

    
1768
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1769
	if (!$fd) {
1770
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1771
		return 1;
1772
	}
1773

    
1774
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1775
		fwrite($fd, $dmesg[$i] . "\n");
1776

    
1777
	fclose($fd);
1778
	unset($dmesg);
1779

    
1780
	return 0;
1781
}
1782

    
1783
function system_set_harddisk_standby() {
1784
	global $g, $config;
1785
	if(isset($config['system']['developerspew'])) {
1786
		$mt = microtime();
1787
		echo "system_set_harddisk_standby() being called $mt\n";
1788
	}
1789

    
1790
	if (isset($config['system']['harddiskstandby'])) {
1791
		if ($g['booting']) {
1792
			echo gettext('Setting hard disk standby... ');
1793
		}
1794

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

    
1815
function system_setup_sysctl() {
1816
	global $config;
1817
	if(isset($config['system']['developerspew'])) {
1818
		$mt = microtime();
1819
		echo "system_setup_sysctl() being called $mt\n";
1820
	}
1821

    
1822
	activate_sysctls();	
1823

    
1824
	if (isset($config['system']['sharednet'])) {
1825
		system_disable_arp_wrong_if();
1826
	}
1827
}
1828

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

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

    
1849
function enable_watchdog() {
1850
	global $config;
1851
	return;
1852
	$install_watchdog = false;
1853
	$supported_watchdogs = array("Geode");
1854
	$file = file_get_contents("/var/log/dmesg.boot");
1855
	foreach($supported_watchdogs as $sd) {
1856
		if(stristr($file, "Geode")) {
1857
			$install_watchdog = true;
1858
		}
1859
	}
1860
	if($install_watchdog == true) {
1861
		if(is_process_running("watchdogd"))
1862
			mwexec("/usr/bin/killall watchdogd", true);
1863
		exec("/usr/sbin/watchdogd");
1864
	}
1865
}
1866

    
1867
function system_check_reset_button() {
1868
	global $g;
1869
	if($g['platform'] != "nanobsd")
1870
		return 0;
1871

    
1872
	$specplatform = system_identify_specific_platform();
1873

    
1874
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1875
		return 0;
1876

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

    
1879
	if ($retval == 99) {
1880
		/* user has pressed reset button for 2 seconds - 
1881
		   reset to factory defaults */
1882
		echo <<<EOD
1883

    
1884
***********************************************************************
1885
* Reset button pressed - resetting configuration to factory defaults. *
1886
* The system will reboot after this completes.                        *
1887
***********************************************************************
1888

    
1889

    
1890
EOD;
1891
		
1892
		reset_factory_defaults();
1893
		system_reboot_sync();
1894
		exit(0);
1895
	}
1896

    
1897
	return 0;
1898
}
1899

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

    
1918
	unset($output);
1919
	$_gb = exec('/sbin/sysctl -n hw.model', $output);
1920
	$dmesg = $output[0];
1921

    
1922
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1923
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
1924
	
1925
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1926
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
1927

    
1928
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1929
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1930
	
1931
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1932
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1933
		
1934
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1935
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1936
	
1937
	/* unknown embedded platform */
1938
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
1939
}
1940

    
1941
function system_get_dmesg_boot() {
1942
	global $g;
1943
		
1944
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1945
}
1946

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

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