Projet

Général

Profil

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

univnautes / etc / inc / system.inc @ b462fc5e

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
		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

    
74
	if ($g['platform'] == 'jail')
75
		return;
76

    
77
	$sysctls = array(
78
		"net.enc.out.ipsec_bpf_mask" => "0x0001",
79
		"net.enc.out.ipsec_filter_mask" => "0x0001",
80
		"net.enc.in.ipsec_bpf_mask" => "0x0002",
81
		"net.enc.in.ipsec_filter_mask" => "0x0002"
82
	);
83

    
84
	if(is_array($config['sysctl'])) {
85
		foreach($config['sysctl']['item'] as $tunable) {
86
			if($tunable['value'] == "default")
87
				$value = get_default_sysctl_value($tunable['tunable']);
88
			else
89
				$value = $tunable['value'];
90

    
91
			$sysctls[$tunable['tunable']] = $value;
92
		}
93
	}
94

    
95
	set_sysctl($sysctls);
96
}
97

    
98
function system_resolvconf_generate($dynupdate = false) {
99
	global $config, $g;
100

    
101
	if(isset($config['system']['developerspew'])) {
102
		$mt = microtime();
103
		echo "system_resolvconf_generate() being called $mt\n";
104
	}
105

    
106
	$syscfg = $config['system'];
107

    
108
	// Do not create blank domain lines, it breaks tools like dig.
109
	if($syscfg['domain'])
110
		$resolvconf = "domain {$syscfg['domain']}\n";
111

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

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

    
137
	// Add EDNS support
138
	if (isset($config['unbound']['enable']) && isset($config['unbound']['edns']))
139
		$resolvconf .= "options edns0\n";
140

    
141
	$dnslock = lock('resolvconf', LOCK_EX);
142

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

    
150
	fwrite($fd, $resolvconf);
151
	fclose($fd);
152

    
153
	if (!$g['booting']) {
154
		/* restart dhcpd (nameservers may have changed) */
155
		if (!$dynupdate)
156
			services_dhcpd_configure();
157
	}
158

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

    
181
	unlock($dnslock);
182

    
183
	return 0;
184
}
185

    
186
function get_searchdomains() {
187
	global $config, $g;
188

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

    
205
	return $master_list;
206
}
207

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

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

    
236
	return $master_list;
237
}
238

    
239
function system_hosts_generate() {
240
	global $config, $g;
241
	if (isset($config['system']['developerspew'])) {
242
		$mt = microtime();
243
		echo "system_hosts_generate() being called $mt\n";
244
	}
245

    
246
	$syscfg = $config['system'];
247
	$dnsmasqcfg = $config['dnsmasq'];
248

    
249
	$hosts = "127.0.0.1	localhost localhost.{$syscfg['domain']}\n";
250
	$lhosts = "";
251
	$dhosts = "";
252

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

    
270
	if (isset($dnsmasqcfg['enable'])) {
271
		if (!is_array($dnsmasqcfg['hosts']))
272
			$dnsmasqcfg['hosts'] = array();
273

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

    
311
		if (isset($dnsmasqcfg['dhcpfirst']))
312
			$hosts .= $dhosts . $lhosts;
313
		else
314
			$hosts .= $lhosts . $dhosts;
315
	}
316

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

    
333
	if (isset($config['unbound']['enable'])) {
334
		require_once("unbound.inc");
335
		unbound_hosts_generate();
336
	}
337

    
338
	system_dhcpleases_configure();
339

    
340
	return 0;
341
}
342

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

    
374
function system_hostname_configure() {
375
	global $config, $g;
376
	if(isset($config['system']['developerspew'])) {
377
		$mt = microtime();
378
		echo "system_hostname_configure() being called $mt\n";
379
	}
380

    
381
	$syscfg = $config['system'];
382

    
383
	/* set hostname */
384
	$status = mwexec("/bin/hostname " .
385
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
386

    
387
    /* Setup host GUID ID.  This is used by ZFS. */
388
	mwexec("/etc/rc.d/hostid start");
389

    
390
	return $status;
391
}
392

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

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

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

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

    
486
	system_staticroutes_configure($interface, false);
487

    
488
	return 0;
489
}
490

    
491
function system_staticroutes_configure($interface = "", $update_dns = false) {
492
	global $config, $g, $aliastable;
493

    
494
	$filterdns_list = array();
495

    
496
	$static_routes = get_staticroutes(false, true);
497
	if (count($static_routes)) {
498
		$gateways_arr = return_gateways_array(false, true);
499

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

    
509
			$gatewayip = $gateway['gateway'];
510
			$interfacegw = $gateway['interface'];
511

    
512
			$blackhole = "";
513
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 3)))
514
				$blackhole = "-blackhole";
515

    
516
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network']))
517
				continue;
518

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

    
528
			if (is_subnet($rtent['network']))
529
				$ips = array($rtent['network']);
530
			else {
531
				if (!isset($rtent['disabled']))
532
					$filterdns_list[] = $rtent['network'];
533
				$ips = add_hostname_to_watch($rtent['network']);
534
			}
535

    
536
			foreach ($dnscache as $ip) {
537
				if (in_array($ip, $ips))
538
					continue;
539
				mwexec("/sbin/route delete " . escapeshellarg($ip), true);
540
			}
541

    
542
			if (isset($rtent['disabled'])) {
543
				/* XXX: This is a bit dangerous in case of routing daemons!? */
544
				foreach ($ips as $ip)
545
					mwexec("/sbin/route delete " . escapeshellarg($ip), true);
546
				continue;
547
			}
548

    
549
			foreach ($ips as $ip) {
550
				if (is_ipaddrv4($ip))
551
					$ip .= "/32";
552
				else if (is_ipaddrv6($ip))
553
					$ip .= "/128";
554

    
555
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
556

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

    
559
				if (is_subnet($ip))
560
					if (is_ipaddr($gatewayip))
561
						mwexec($cmd . escapeshellarg($gatewayip));
562
					else if (!empty($interfacegw))
563
						mwexec($cmd . "-iface " . escapeshellarg($interfacegw));
564
			}
565
		}
566
		unset($gateways_arr);
567
	}
568
	unset($static_routes);
569

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

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

    
591
	return 0;
592
}
593

    
594
function system_routing_enable() {
595
	global $config, $g;
596
	if(isset($config['system']['developerspew'])) {
597
		$mt = microtime();
598
		echo "system_routing_enable() being called $mt\n";
599
	}
600

    
601
	set_sysctl(array(
602
		"net.inet.ip.forwarding" => "1",
603
		"net.inet6.ip6.forwarding" => "1"
604
	));
605

    
606
	return;
607
}
608

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

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

    
632
function system_syslogd_start() {
633
	global $config, $g;
634
	if(isset($config['system']['developerspew'])) {
635
		$mt = microtime();
636
		echo "system_syslogd_start() being called $mt\n";
637
	}
638

    
639
	mwexec("/etc/rc.d/hostid start");
640

    
641
	$syslogcfg = $config['syslog'];
642

    
643
	if ($g['booting'])
644
		echo gettext("Starting syslog...");
645

    
646
	if (is_process_running("fifolog_writer"))
647
		mwexec('/bin/pkill fifolog_writer');
648

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

    
664
	$syslogd_extra = "";
665
	if (isset($syslogcfg)) {
666
		$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');
667
		$syslogconf = "";
668
		if($config['installedpackages']['package']) {
669
			foreach($config['installedpackages']['package'] as $package) {
670
				if($package['logging']) {
671
					array_push($separatelogfacilities, $package['logging']['facilityname']);
672
					mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
673
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
674
				}
675
			}
676
		}
677
		$facilitylist = implode(',', array_unique($separatelogfacilities));
678
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd,miniupnpd\n";
679
		if (!isset($syslogcfg['disablelocallogging']))
680
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
681

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

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

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

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

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

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

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

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

    
720
		$syslogconf .= "!dnsmasq,filterdns,unbound\n";
721
		if (!isset($syslogcfg['disablelocallogging']))
722
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
723

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

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

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

    
742
		$syslogconf .= "!filterlog\n";
743
		$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/filter.log\n";
744
		if (isset($syslogcfg['filter']))
745
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
746

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

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

    
781
		if (isset($syslogcfg['zmqserver'])) {
782
				$syslogconf .= <<<EOD
783
*.*								^{$syslogcfg['zmqserver']}
784

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

    
795
		// Ensure that the log directory exists
796
		if (!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
797
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
798

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

    
815
		$syslogd_extra = "-f {$g['varetc_path']}/syslog.conf {$sourceip}";
816
	}
817

    
818
	if (isvalidpid("{$g['varrun_path']}/syslog.pid"))
819
		sigkillbypid("{$g['varrun_path']}/syslog.pid", "HUP");
820
	else
821
		$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}");
822

    
823
	if ($g['booting'])
824
		echo gettext("done.") . "\n";
825

    
826
	return $retval;
827
}
828

    
829
function system_webgui_start() {
830
	global $config, $g;
831

    
832
	if ($g['booting'])
833
		echo gettext("Starting webConfigurator...");
834

    
835
	chdir($g['www_path']);
836

    
837
	/* defaults */
838
	$portarg = "80";
839
	$crt = "";
840
	$key = "";
841
	$ca = "";
842

    
843
	/* non-standard port? */
844
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
845
		$portarg = "{$config['system']['webgui']['port']}";
846

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

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

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

    
891
	sleep(1);
892

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

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

    
898
	if ($g['booting']) {
899
		if ($res == 0)
900
			echo gettext("done.") . "\n";
901
		else
902
			echo gettext("failed!") . "\n";
903
	}
904

    
905
	return $res;
906
}
907

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

    
919
	global $config, $g;
920

    
921
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
922
		mkdir("{$g['tmp_path']}/lighttpdcompress");
923

    
924
	if(isset($config['system']['developerspew'])) {
925
		$mt = microtime();
926
		echo "system_generate_lighty_config() being called $mt\n";
927
	}
928

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

    
933
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
934
		if (empty($maxprocperip))
935
			$maxprocperip = 10;
936
		$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
937

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

    
957
	$memory = get_memory();
958
	$realmem = $memory[1];
959

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

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

    
980
	} else {
981
		if ($realmem < 78)
982
			$max_php_children = 0;
983
		else
984
			$max_php_children = 1;
985
	}
986

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

    
994

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

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

    
1029
EOD;
1030
	}
1031

    
1032

    
1033
	$lighty_config = <<<EOD
1034
#
1035
# lighttpd configuration file
1036
#
1037
# use a it as base for lighttpd 1.0.0 and above
1038
#
1039
############ Options you really have to take care of ####################
1040

    
1041
## FreeBSD!
1042
server.event-handler	= "freebsd-kqueue"
1043
server.network-backend 	= "writev"
1044
#server.use-ipv6 = "enable"
1045

    
1046
## modules to load
1047
server.modules              =   ( "mod_access", "mod_expire", "mod_compress", "mod_redirect",
1048
	{$captiveportal}, "mod_fastcgi"
1049
)
1050

    
1051
server.max-keep-alive-requests = 15
1052
server.max-keep-alive-idle = 30
1053

    
1054
## a static document-root, for virtual-hosting take look at the
1055
## server.virtual-* options
1056
server.document-root        = "{$document_root}"
1057
{$captive_portal_rewrite}
1058

    
1059
# Maximum idle time with nothing being written (php downloading)
1060
server.max-write-idle = 999
1061

    
1062
{$lighty_use_syslog}
1063

    
1064
# files to check for if .../ is requested
1065
server.indexfiles           = ( "index.php", "index.html",
1066
                                "index.htm", "default.htm" )
1067

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

    
1121
# Use the "Content-Type" extended attribute to obtain mime type if possible
1122
#mimetypes.use-xattr        = "enable"
1123

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

    
1131

    
1132
######### Options that are good to be but not neccesary to be changed #######
1133

    
1134
## bind to port (default: 80)
1135

    
1136
EOD;
1137

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

    
1152

    
1153
	$lighty_config .= <<<EOD
1154

    
1155
## error-handler for status 404
1156
#server.error-handler-404   = "/error-handler.html"
1157
#server.error-handler-404   = "/error-handler.php"
1158

    
1159
## to help the rc.scripts
1160
server.pid-file            = "{$g['varrun_path']}/{$pid_file}"
1161

    
1162
## virtual directory listings
1163
server.dir-listing         = "disable"
1164

    
1165
## enable debugging
1166
debug.log-request-header   = "disable"
1167
debug.log-response-header  = "disable"
1168
debug.log-request-handling = "disable"
1169
debug.log-file-not-found   = "disable"
1170

    
1171
# gzip compression
1172
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1173
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1174

    
1175
{$server_upload_dirs}
1176

    
1177
{$server_max_request_size}
1178

    
1179
{$fastcgi_config}
1180

    
1181
{$cgi_config}
1182

    
1183
{$captive_portal_mod_evasive}
1184

    
1185
expire.url = (
1186
				"" => "access 50 hours",	
1187
        )
1188

    
1189
EOD;
1190

    
1191
	$cert = str_replace("\r", "", $cert);
1192
	$key = str_replace("\r", "", $key);
1193
	$ca = str_replace("\r", "", $ca);
1194

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

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

    
1225
		// Harden SSL a bit for PCI conformance testing
1226
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
1227

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

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

    
1249
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1250
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1251
	}
1252

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

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

    
1279
	return 0;
1280

    
1281
}
1282

    
1283
function system_timezone_configure() {
1284
	global $config, $g;
1285
	if(isset($config['system']['developerspew'])) {
1286
		$mt = microtime();
1287
		echo "system_timezone_configure() being called $mt\n";
1288
	}
1289

    
1290
	$syscfg = $config['system'];
1291

    
1292
	if ($g['booting'])
1293
		echo gettext("Setting timezone...");
1294

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

    
1310
	conf_mount_rw();
1311

    
1312
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1313
		escapeshellarg($timezone) . " > /etc/localtime");
1314

    
1315
	mwexec("sync");
1316
	conf_mount_ro();
1317

    
1318
	if ($g['booting'])
1319
		echo gettext("done.") . "\n";
1320
}
1321

    
1322
function system_ntp_setup_gps($serialport) {
1323
	global $config, $g;
1324
	$gps_device = '/dev/gps0';
1325
	$serialport = '/dev/'.$serialport;
1326

    
1327
	if (!file_exists($serialport))
1328
		return false;
1329

    
1330
	conf_mount_rw();
1331
	// Create symlink that ntpd requires
1332
	unlink_if_exists($gps_device);
1333
	symlink($serialport, $gps_device);
1334

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

    
1342
	/* XXX: Why not file_put_contents to the device */
1343
	@file_put_contents('/tmp/gps.init', $gps_init);
1344
	`cat /tmp/gps.init > $serialport`;
1345

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

    
1371
	conf_mount_ro();
1372

    
1373
	return true;
1374
}
1375

    
1376
function system_ntp_setup_pps($serialport) {
1377
	global $config, $g;
1378

    
1379
	$pps_device = '/dev/pps0';
1380
	$serialport = '/dev/'.$serialport;
1381

    
1382
	if (!file_exists($serialport))
1383
		return false;
1384

    
1385
	conf_mount_rw();
1386
	// Create symlink that ntpd requires
1387
	unlink_if_exists($pps_device);
1388
	@symlink($serialport, $pps_device);
1389

    
1390
	conf_mount_ro();
1391

    
1392
	return true;
1393
}
1394

    
1395

    
1396
function system_ntp_configure($start_ntpd=true) {
1397
	global $config, $g;
1398

    
1399
	$driftfile = "/var/db/ntpd.drift";
1400
	$statsdir = "/var/log/ntp";
1401
	$gps_device = '/dev/gps0';
1402

    
1403
	if ($g['platform'] == 'jail')
1404
		return;
1405

    
1406
	safe_mkdir($statsdir);
1407

    
1408
	if (!is_array($config['ntpd']))
1409
		$config['ntpd'] = array();
1410

    
1411
	$ntpcfg = "# \n";
1412
	$ntpcfg .= "# pfSense ntp configuration file \n";
1413
	$ntpcfg .= "# \n\n";
1414
	$ntpcfg .= "tinker panic 0 \n";
1415

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

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

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

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

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

    
1623
	if (empty($config['ntpd']['interface']))
1624
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface']))
1625
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1626
		else
1627
			$interfaces = array();
1628
	else
1629
		$interfaces = explode(",", $config['ntpd']['interface']);
1630

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

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

    
1648
	/* At bootup we just want to write out the config. */
1649
	if (!$start_ntpd)
1650
		return;
1651

    
1652
	/* if ntpd is running, kill it */
1653
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1654
		killbypid("{$g['varrun_path']}/ntpd.pid");
1655
	}
1656
	@unlink("{$g['varrun_path']}/ntpd.pid");
1657

    
1658
	/* if /var/empty does not exist, create it */
1659
	if(!is_dir("/var/empty"))
1660
		mkdir("/var/empty", 0775, true);
1661

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

    
1670
function sync_system_time() {
1671
	global $config, $g;
1672

    
1673
	if ($g['booting'])
1674
		echo gettext("Syncing system time before startup...");
1675

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

    
1686
function system_halt() {
1687
	global $g;
1688

    
1689
	system_reboot_cleanup();
1690

    
1691
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1692
}
1693

    
1694
function system_reboot() {
1695
	global $g;
1696

    
1697
	system_reboot_cleanup();
1698

    
1699
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1700
}
1701

    
1702
function system_reboot_sync() {
1703
	global $g;
1704

    
1705
	system_reboot_cleanup();
1706

    
1707
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1708
}
1709

    
1710
function system_reboot_cleanup() {
1711
	global $config, $cpzone;
1712

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

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

    
1734
	if ($early)
1735
		$cmdn = "earlyshellcmd";
1736
	else
1737
		$cmdn = "shellcmd";
1738

    
1739
	if (is_array($config['system'][$cmdn])) {
1740

    
1741
		/* *cmd is an array, loop through */
1742
		foreach ($config['system'][$cmdn] as $cmd) {
1743
			exec($cmd);
1744
		}
1745

    
1746
	} elseif($config['system'][$cmdn] <> "") {
1747

    
1748
		/* execute single item */
1749
		exec($config['system'][$cmdn]);
1750

    
1751
	}
1752
}
1753

    
1754
function system_console_configure() {
1755
	global $config, $g;
1756
	if(isset($config['system']['developerspew'])) {
1757
		$mt = microtime();
1758
		echo "system_console_configure() being called $mt\n";
1759
	}
1760

    
1761
	if (isset($config['system']['disableconsolemenu'])) {
1762
		touch("{$g['varetc_path']}/disableconsole");
1763
	} else {
1764
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1765
	}
1766
}
1767

    
1768
function system_dmesg_save() {
1769
	global $g;
1770
	if(isset($config['system']['developerspew'])) {
1771
		$mt = microtime();
1772
		echo "system_dmesg_save() being called $mt\n";
1773
	}
1774

    
1775
	$dmesg = "";
1776
	$_gb = exec("/sbin/dmesg", $dmesg);
1777

    
1778
	/* find last copyright line (output from previous boots may be present) */
1779
	$lastcpline = 0;
1780

    
1781
	for ($i = 0; $i < count($dmesg); $i++) {
1782
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1783
			$lastcpline = $i;
1784
	}
1785

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

    
1792
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1793
		fwrite($fd, $dmesg[$i] . "\n");
1794

    
1795
	fclose($fd);
1796
	unset($dmesg);
1797

    
1798
	return 0;
1799
}
1800

    
1801
function system_set_harddisk_standby() {
1802
	global $g, $config;
1803
	if(isset($config['system']['developerspew'])) {
1804
		$mt = microtime();
1805
		echo "system_set_harddisk_standby() being called $mt\n";
1806
	}
1807

    
1808
	if (isset($config['system']['harddiskstandby'])) {
1809
		if ($g['booting']) {
1810
			echo gettext('Setting hard disk standby... ');
1811
		}
1812

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

    
1833
function system_setup_sysctl() {
1834
	global $config;
1835
	if(isset($config['system']['developerspew'])) {
1836
		$mt = microtime();
1837
		echo "system_setup_sysctl() being called $mt\n";
1838
	}
1839

    
1840
	activate_sysctls();	
1841

    
1842
	if (isset($config['system']['sharednet'])) {
1843
		system_disable_arp_wrong_if();
1844
	}
1845
}
1846

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

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

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

    
1889
function system_check_reset_button() {
1890
	global $g;
1891
	if($g['platform'] != "nanobsd")
1892
		return 0;
1893

    
1894
	$specplatform = system_identify_specific_platform();
1895

    
1896
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1897
		return 0;
1898

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

    
1901
	if ($retval == 99) {
1902
		/* user has pressed reset button for 2 seconds - 
1903
		   reset to factory defaults */
1904
		echo <<<EOD
1905

    
1906
***********************************************************************
1907
* Reset button pressed - resetting configuration to factory defaults. *
1908
* The system will reboot after this completes.                        *
1909
***********************************************************************
1910

    
1911

    
1912
EOD;
1913
		
1914
		reset_factory_defaults();
1915
		system_reboot_sync();
1916
		exit(0);
1917
	}
1918

    
1919
	return 0;
1920
}
1921

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

    
1940
	$dmesg = get_single_sysctl('hw.model');
1941

    
1942
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1943
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
1944
	
1945
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1946
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
1947

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

    
1961
function system_get_dmesg_boot() {
1962
	global $g;
1963
		
1964
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1965
}
1966

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

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