Projet

Général

Profil

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

univnautes / etc / inc / system.inc @ 7c4c77ee

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

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

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

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

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

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

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

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

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

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

    
60
		$normal_mode = "hadp";
61
		if (!empty($config['system']['powerd_normal_mode']))
62
			$normal_mode = $config['system']['powerd_normal_mode'];
63

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

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

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

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

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

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

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

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

    
99
	set_sysctl($sysctls);
100
}
101

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

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

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

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

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

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

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

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

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

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

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

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

    
185
	unlock($dnslock);
186

    
187
	return 0;
188
}
189

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

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

    
209
	return $master_list;
210
}
211

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

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

    
240
	return $master_list;
241
}
242

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

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

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

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

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

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

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

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

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

    
342
	system_dhcpleases_configure();
343

    
344
	return 0;
345
}
346

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

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

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

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

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

    
394
	return $status;
395
}
396

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

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

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

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

    
490
	system_staticroutes_configure($interface, false);
491

    
492
	return 0;
493
}
494

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

    
498
	$filterdns_list = array();
499

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
595
	return 0;
596
}
597

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

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

    
610
	return;
611
}
612

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
830
	return $retval;
831
}
832

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
914
	sleep(1);
915

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

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

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

    
928
	return $res;
929
}
930

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

    
942
	global $config, $g;
943

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

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

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

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

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

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

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

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

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

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

    
1017

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

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

    
1052
EOD;
1053
	}
1054

    
1055

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

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

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

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

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

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

    
1085
{$lighty_use_syslog}
1086

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

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

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

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

    
1154

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

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

    
1159
EOD;
1160

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

    
1175

    
1176
	$lighty_config .= <<<EOD
1177

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

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

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

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

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

    
1198
{$server_upload_dirs}
1199

    
1200
{$server_max_request_size}
1201

    
1202
{$fastcgi_config}
1203

    
1204
{$cgi_config}
1205

    
1206
{$captive_portal_mod_evasive}
1207

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

    
1212
EOD;
1213

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

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

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

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

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

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

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

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

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

    
1302
	return 0;
1303

    
1304
}
1305

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

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

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

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

    
1333
	conf_mount_rw();
1334

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

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

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

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

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

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

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

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

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

    
1394
	conf_mount_ro();
1395

    
1396
	return true;
1397
}
1398

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

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

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

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

    
1413
	conf_mount_ro();
1414

    
1415
	return true;
1416
}
1417

    
1418

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

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

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

    
1429
	safe_mkdir($statsdir);
1430

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1712
	system_reboot_cleanup();
1713

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

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

    
1720
	system_reboot_cleanup();
1721

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

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

    
1728
	system_reboot_cleanup();
1729

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

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

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

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

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

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

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

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

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

    
1774
	}
1775
}
1776

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

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

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

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

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

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

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

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

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

    
1821
	return 0;
1822
}
1823

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

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

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

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

    
1863
	activate_sysctls();	
1864

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

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

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

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

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

    
1917
	$specplatform = system_identify_specific_platform();
1918

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

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

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

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

    
1934

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

    
1942
	return 0;
1943
}
1944

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

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

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

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

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

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

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