Projet

Général

Profil

Télécharger (64,9 ko) Statistiques
| Branche: | Tag: | Révision:

univnautes / etc / inc / system.inc @ 340ce958

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 get_sysctl_descr($sysctl) {
76
	unset($output);
77
	$_gb = exec("/sbin/sysctl -nd {$sysctl}", $output);
78

    
79
	return $output[0];
80
}
81

    
82
function system_get_sysctls() {
83
	global $config, $sysctls;
84

    
85
	$disp_sysctl = array();
86
	$disp_cache = array();
87
	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
88
		foreach($config['sysctl']['item'] as $id => $tunable) {
89
			if ($tunable['value'] == "default")
90
				$value = get_default_sysctl_value($tunable['tunable']);
91
			else
92
				$value = $tunable['value'];
93

    
94
			$disp_sysctl[$id] = $tunable;
95
			$disp_sysctl[$id]['modified'] = true;
96
			$disp_cache[$tunable['tunable']] = 'set';
97
		}
98
	}
99

    
100
	foreach ($sysctls as $sysctl => $value) {
101
		if (isset($disp_cache[$sysctl]))
102
			continue;
103

    
104
		$disp_sysctl[$sysctl] = array('tunable' => $sysctl, 'value' => $value, 'descr' => get_sysctl_descr($sysctl));
105
		
106
		
107
	}
108
	unset($disp_cache);
109
	return $disp_sysctl;
110
}
111

    
112
function activate_sysctls() {
113
	global $config, $g, $sysctls;
114

    
115
	if ($g['platform'] == 'jail')
116
		return;
117

    
118
	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
119
		foreach($config['sysctl']['item'] as $tunable) {
120
			if($tunable['value'] == "default")
121
				$value = get_default_sysctl_value($tunable['tunable']);
122
			else
123
				$value = $tunable['value'];
124

    
125
			$sysctls[$tunable['tunable']] = $value;
126
		}
127
	}
128

    
129
	set_sysctl($sysctls);
130
}
131

    
132
function system_resolvconf_generate($dynupdate = false) {
133
	global $config, $g;
134

    
135
	if(isset($config['system']['developerspew'])) {
136
		$mt = microtime();
137
		echo "system_resolvconf_generate() being called $mt\n";
138
	}
139

    
140
	$syscfg = $config['system'];
141

    
142
	if (((isset($config['dnsmasq']['enable']) && (empty($config['dnsmasq']['interface']) || in_array("lo0", explode(",", $config['dnsmasq']['interface']))))
143
		|| (isset($config['unbound']['enable'])) && (empty($config['unbound']['active_interface']) || in_array("lo0", explode(",", $config['unbound']['active_interface']))))
144
		&& !isset($config['system']['dnslocalhost']))
145
		$resolvconf .= "nameserver 127.0.0.1\n";
146

    
147
	if (isset($syscfg['dnsallowoverride'])) {
148
		/* get dynamically assigned DNS servers (if any) */
149
		$ns = array_unique(get_searchdomains());
150
		foreach($ns as $searchserver) {
151
			if($searchserver)
152
				$resolvconf .= "search {$searchserver}\n";
153
		}
154
		$ns = array_unique(get_nameservers());
155
		foreach($ns as $nameserver) {
156
			if($nameserver)
157
				$resolvconf .= "nameserver $nameserver\n";
158
		}
159
	} else {
160
		// Do not create blank search/domain lines, it can break tools like dig.
161
		if($syscfg['domain'])
162
			$resolvconf = "search {$syscfg['domain']}\n";
163
	}
164
	if (is_array($syscfg['dnsserver'])) {
165
		foreach ($syscfg['dnsserver'] as $ns) {
166
			if ($ns)
167
				$resolvconf .= "nameserver $ns\n";
168
		}
169
	}
170

    
171
	// Add EDNS support
172
	if (isset($config['unbound']['enable']) && isset($config['unbound']['edns']))
173
		$resolvconf .= "options edns0\n";
174

    
175
	$dnslock = lock('resolvconf', LOCK_EX);
176

    
177
	$fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
178
	if (!$fd) {
179
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
180
		unlock($dnslock);
181
		return 1;
182
	}
183

    
184
	fwrite($fd, $resolvconf);
185
	fclose($fd);
186

    
187
	if (!$g['booting']) {
188
		/* restart dhcpd (nameservers may have changed) */
189
		if (!$dynupdate)
190
			services_dhcpd_configure();
191
	}
192

    
193
	/* setup static routes for DNS servers. */
194
	for ($dnscounter=1; $dnscounter<5; $dnscounter++) {
195
		/* setup static routes for dns servers */
196
		$dnsgw = "dns{$dnscounter}gw";
197
		if (isset($config['system'][$dnsgw])) {
198
			$gwname = $config['system'][$dnsgw];
199
			if (($gwname <> "") && ($gwname <> "none")) {
200
				$gatewayip = lookup_gateway_ip_by_name($gwname);
201
				if (is_ipaddrv4($gatewayip)) {
202
					/* dns server array starts at 0 */
203
					$dnscountermo = $dnscounter - 1;
204
					mwexec("/sbin/route change -host " . $syscfg['dnsserver'][$dnscountermo] . " {$gatewayip}");
205
					if (isset($config['system']['route-debug'])) {
206
						$mt = microtime();
207
						log_error("ROUTING debug: $mt - route change -host {$syscfg['dnsserver'][$dnscountermo]} $gatewayip ");
208
					}
209
				}
210
				if (is_ipaddrv6($gatewayip)) {
211
					/* dns server array starts at 0 */
212
					$dnscountermo = $dnscounter - 1;
213
					mwexec("/sbin/route change -host -inet6 " . $syscfg['dnsserver'][$dnscountermo] . " {$gatewayip}");
214
					if (isset($config['system']['route-debug'])) {
215
						$mt = microtime();
216
						log_error("ROUTING debug: $mt - route change -host -inet6 {$syscfg['dnsserver'][$dnscountermo]} $gatewayip ");
217
					}					
218
				}
219
			}
220
		}
221
	}
222

    
223
	unlock($dnslock);
224

    
225
	return 0;
226
}
227

    
228
function get_searchdomains() {
229
	global $config, $g;
230

    
231
	$master_list = array();
232
	
233
	// Read in dhclient nameservers
234
	$search_list = glob("/var/etc/searchdomain_*");
235
	if (is_array($search_list)) {
236
		foreach($search_list as $fdns) {
237
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
238
			if (!is_array($contents))
239
				continue;
240
			foreach ($contents as $dns) {
241
				if(is_hostname($dns)) 
242
					$master_list[] = $dns;
243
			}
244
		}
245
	}
246

    
247
	return $master_list;
248
}
249

    
250
function get_nameservers() {
251
	global $config, $g;
252
	$master_list = array();
253
	
254
	// Read in dhclient nameservers
255
	$dns_lists = glob("/var/etc/nameserver_*");
256
	if (is_array($dns_lists)) {
257
		foreach($dns_lists as $fdns) {
258
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
259
			if (!is_array($contents))
260
				continue;
261
			foreach ($contents as $dns) {
262
				if(is_ipaddr($dns)) 
263
					$master_list[] = $dns;
264
			}
265
		}
266
	}
267

    
268
	// Read in any extra nameservers
269
	if(file_exists("/var/etc/nameservers.conf")) {
270
		$dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
271
		if(is_array($dns_s)) {
272
			foreach($dns_s as $dns)
273
				if (is_ipaddr($dns))
274
					$master_list[] = $dns;
275
		}
276
	}
277

    
278
	return $master_list;
279
}
280

    
281
function system_hosts_generate() {
282
	global $config, $g;
283
	if (isset($config['system']['developerspew'])) {
284
		$mt = microtime();
285
		echo "system_hosts_generate() being called $mt\n";
286
	}
287

    
288
	$syscfg = $config['system'];
289
	$dnsmasqcfg = $config['dnsmasq'];
290

    
291
	$hosts = "127.0.0.1	localhost localhost.{$syscfg['domain']}\n";
292
	$lhosts = "";
293
	$dhosts = "";
294

    
295
	if ($config['interfaces']['lan']) {
296
		$cfgip = get_interface_ip("lan");
297
		if (is_ipaddr($cfgip))
298
			$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
299
	} else {
300
		$sysiflist = get_configured_interface_list();
301
		foreach ($sysiflist as $sysif) {
302
			if (!interface_has_gateway($sysif)) {
303
				$cfgip = get_interface_ip($sysif);
304
				if (is_ipaddr($cfgip)) {
305
					$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
306
					break;
307
				}
308
			}
309
		}
310
	}
311

    
312
	if (isset($dnsmasqcfg['enable'])) {
313
		if (!is_array($dnsmasqcfg['hosts']))
314
			$dnsmasqcfg['hosts'] = array();
315

    
316
		foreach ($dnsmasqcfg['hosts'] as $host) {
317
			if ($host['host'])
318
				$lhosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
319
			else
320
				$lhosts .= "{$host['ip']}	{$host['domain']}\n";
321
			if (!is_array($host['aliases']) || !is_array($host['aliases']['item']))
322
				continue;
323
			foreach ($host['aliases']['item'] as $alias) {
324
				if ($alias['host'])
325
					$lhosts .= "{$host['ip']}	{$alias['host']}.{$alias['domain']} {$alias['host']}\n";
326
				else
327
					$lhosts .= "{$host['ip']}	{$alias['domain']}\n";
328
			}
329
		}
330
		if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpd'])) {
331
			foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf)
332
				if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
333
						foreach ($dhcpifconf['staticmap'] as $host)
334
							if ($host['ipaddr'] && $host['hostname'] && $host['domain'])
335
								$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$host['domain']} {$host['hostname']}\n";
336
							else if ($host['ipaddr'] && $host['hostname'] && $dhcpifconf['domain'])
337
								$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$dhcpifconf['domain']} {$host['hostname']}\n";
338
							else if ($host['ipaddr'] && $host['hostname'])
339
								$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
340
		}
341
		if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpdv6'])) {
342
			foreach ($config['dhcpdv6'] as $dhcpif => $dhcpifconf)
343
				if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
344
						foreach ($dhcpifconf['staticmap'] as $host)
345
							if ($host['ipaddrv6'] && $host['hostname'] && $host['domain'])
346
								$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$host['domain']} {$host['hostname']}\n";
347
							else if ($host['ipaddrv6'] && $host['hostname'] && $dhcpifconf['domain'])
348
								$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$dhcpifconf['domain']} {$host['hostname']}\n";
349
							else if ($host['ipaddrv6'] && $host['hostname'])
350
								$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
351
		}
352

    
353
		if (isset($dnsmasqcfg['dhcpfirst']))
354
			$hosts .= $dhosts . $lhosts;
355
		else
356
			$hosts .= $lhosts . $dhosts;
357
	}
358

    
359
	/*
360
	 * Do not remove this because dhcpleases monitors with kqueue it needs to be 
361
	 * killed before writing to hosts files.
362
	 */
363
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
364
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
365
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
366
	}
367
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
368
	if (!$fd) {
369
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
370
		return 1;
371
	}
372
	fwrite($fd, $hosts);
373
	fclose($fd);
374

    
375
	if (isset($config['unbound']['enable'])) {
376
		require_once("unbound.inc");
377
		unbound_hosts_generate();
378
	}
379

    
380
	system_dhcpleases_configure();
381

    
382
	return 0;
383
}
384

    
385
function system_dhcpleases_configure() {
386
	global $config, $g;
387
	
388
	if ($g['platform'] == 'jail')
389
		return;
390
	/* Start the monitoring process for dynamic dhcpclients. */
391
	if ((isset($config['dnsmasq']['enable']) && isset($config['dnsmasq']['regdhcp'])) 
392
		|| (isset($config['unbound']['enable']) && isset($config['unbound']['regdhcp']))) {
393
		/* Make sure we do not error out */
394
		mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db");
395
		if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases"))
396
			@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
397
		if (isvalidpid("{$g['varrun_path']}/dhcpleases.pid"))
398
			sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "HUP");
399
		else {
400
			/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
401
			if (is_process_running("dhcpleases"))
402
				mwexec('/bin/pkill dhcpleases');
403
			@unlink("{$g['varrun_path']}/dhcpleases.pid");
404
			if (isset($config['unbound']['enable']))
405
				$dns_pid = "unbound.pid";
406
			else
407
				$dns_pid = "dnsmasq.pid";
408
			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");
409
		}
410
	} else {
411
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
412
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
413
	}
414
}
415

    
416
function system_hostname_configure() {
417
	global $config, $g;
418
	if(isset($config['system']['developerspew'])) {
419
		$mt = microtime();
420
		echo "system_hostname_configure() being called $mt\n";
421
	}
422

    
423
	$syscfg = $config['system'];
424

    
425
	/* set hostname */
426
	$status = mwexec("/bin/hostname " .
427
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
428

    
429
    /* Setup host GUID ID.  This is used by ZFS. */
430
	mwexec("/etc/rc.d/hostid start");
431

    
432
	return $status;
433
}
434

    
435
function system_routing_configure($interface = "") {
436
	global $config, $g;
437
	if ($g['platform'] == 'jail')
438
		return;
439
	if(isset($config['system']['developerspew'])) {
440
		$mt = microtime();
441
		echo "system_routing_configure() being called $mt\n";
442
	}
443

    
444
	$gatewayip = "";
445
	$interfacegw = "";
446
	$gatewayipv6 = "";
447
	$interfacegwv6 = "";
448
	$foundgw = false;
449
	$foundgwv6 = false;
450
	/* tack on all the hard defined gateways as well */
451
	if (is_array($config['gateways']['gateway_item'])) {
452
		array_map('unlink', glob("{$g['tmp_path']}/*_defaultgw{,v6}", GLOB_BRACE));
453
		foreach	($config['gateways']['gateway_item'] as $gateway) {
454
			if (isset($gateway['defaultgw'])) {
455
				if ($foundgw == false && ($gateway['ipprotocol'] != "inet6" && (is_ipaddrv4($gateway['gateway']) || $gateway['gateway'] == "dynamic"))) {
456
					if(strpos($gateway['gateway'], ":"))
457
						continue;
458
					if ($gateway['gateway'] == "dynamic")
459
						$gateway['gateway'] = get_interface_gateway($gateway['interface']);
460
					$gatewayip = $gateway['gateway'];
461
					$interfacegw = $gateway['interface'];
462
					if (!empty($gateway['interface'])) {
463
						$defaultif = get_real_interface($gateway['interface']);
464
						if ($defaultif)
465
							@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gateway['gateway']);
466
					}
467
					$foundgw = true;
468
				} else if ($foundgwv6 == false && ($gateway['ipprotocol'] == "inet6" && (is_ipaddrv6($gateway['gateway']) || $gateway['gateway'] == "dynamic"))) {
469
					if ($gateway['gateway'] == "dynamic")
470
						$gateway['gateway'] = get_interface_gateway_v6($gateway['interface']);
471
					$gatewayipv6 = $gateway['gateway'];
472
					$interfacegwv6 = $gateway['interface'];
473
					if (!empty($gateway['interface'])) {
474
						$defaultifv6 = get_real_interface($gateway['interface']);
475
						if ($defaultifv6)
476
							@file_put_contents("{$g['tmp_path']}/{$defaultifv6}_defaultgwv6", $gateway['gateway']);
477
					}
478
					$foundgwv6 = true;
479
				}
480
			}
481
			if ($foundgw === true && $foundgwv6 === true)
482
				break;
483
		}
484
	}
485
	if ($foundgw == false) {
486
		$defaultif = get_real_interface("wan");
487
		$interfacegw = "wan";
488
		$gatewayip = get_interface_gateway("wan");
489
		@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gatewayip);
490
	}	
491
	if ($foundgwv6 == false) {
492
		$defaultifv6 = get_real_interface("wan");
493
		$interfacegwv6 = "wan";
494
		$gatewayipv6 = get_interface_gateway_v6("wan");
495
		@file_put_contents("{$g['tmp_path']}/{$defaultifv6}_defaultgwv6", $gatewayipv6);
496
	}
497
	$dont_add_route = false;
498
	/* if OLSRD is enabled, allow WAN to house DHCP. */
499
	if (is_array($config['installedpackages']['olsrd'])) {
500
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
501
			if(($olsrd['enabledyngw'] == "on") && ($olsrd['enable'] == "on")) {
502
				$dont_add_route = true;
503
				log_error(sprintf(gettext("Not adding default route because OLSR dynamic gateway is enabled.")));
504
				break;
505
			}
506
		}
507
	}
508

    
509
	if ($dont_add_route == false ) {
510
		if (!empty($interface) && $interface != $interfacegw)
511
			;
512
		else if (is_ipaddrv4($gatewayip)) {
513
			log_error("ROUTING: setting default route to $gatewayip");
514
			mwexec("/sbin/route change -inet default " . escapeshellarg($gatewayip));
515
		}
516

    
517
		if (!empty($interface) && $interface != $interfacegwv6)
518
			;
519
		else if (is_ipaddrv6($gatewayipv6)) {
520
			$ifscope = "";
521
			if (is_linklocal($gatewayipv6) && !strpos($gatewayipv6, '%'))
522
				$ifscope = "%{$defaultifv6}";
523
			log_error("ROUTING: setting IPv6 default route to {$gatewayipv6}{$ifscope}");
524
			mwexec("/sbin/route change -inet6 default " . escapeshellarg("{$gatewayipv6}{$ifscope}"));
525
		}
526
	}
527

    
528
	system_staticroutes_configure($interface, false);
529

    
530
	return 0;
531
}
532

    
533
function system_staticroutes_configure($interface = "", $update_dns = false) {
534
	global $config, $g, $aliastable;
535

    
536
	$filterdns_list = array();
537

    
538
	$static_routes = get_staticroutes(false, true);
539
	if (count($static_routes)) {
540
		$gateways_arr = return_gateways_array(false, true);
541

    
542
		foreach ($static_routes as $rtent) {
543
			if (empty($gateways_arr[$rtent['gateway']])) {
544
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
545
				continue;
546
			}
547
			$gateway = $gateways_arr[$rtent['gateway']];
548
			if (!empty($interface) && $interface != $gateway['friendlyiface'])
549
				continue;
550

    
551
			$gatewayip = $gateway['gateway'];
552
			$interfacegw = $gateway['interface'];
553

    
554
			$blackhole = "";
555
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 3)))
556
				$blackhole = "-blackhole";
557

    
558
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network']))
559
				continue;
560

    
561
			$dnscache = array();
562
			if ($update_dns === true) {
563
				if (is_subnet($rtent['network']))
564
					continue;
565
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
566
				if (empty($dnscache))
567
					continue;
568
			}
569

    
570
			if (is_subnet($rtent['network']))
571
				$ips = array($rtent['network']);
572
			else {
573
				if (!isset($rtent['disabled']))
574
					$filterdns_list[] = $rtent['network'];
575
				$ips = add_hostname_to_watch($rtent['network']);
576
			}
577

    
578
			foreach ($dnscache as $ip) {
579
				if (in_array($ip, $ips))
580
					continue;
581
				mwexec("/sbin/route delete " . escapeshellarg($ip), true);
582
				if (isset($config['system']['route-debug'])) {
583
					$mt = microtime();
584
					log_error("ROUTING debug: $mt - route delete $ip ");
585
				}
586
			}
587

    
588
			if (isset($rtent['disabled'])) {
589
				/* XXX: This can break things by deleting routes that shouldn't be deleted - OpenVPN, dynamic routing scenarios, etc. redmine #3709 */
590
				foreach ($ips as $ip) {
591
					mwexec("/sbin/route delete " . escapeshellarg($ip), true);
592
					if (isset($config['system']['route-debug'])) {
593
						$mt = microtime();
594
						log_error("ROUTING debug: $mt - route delete $ip ");
595
					}
596
				}
597
				continue;
598
			}
599

    
600
			foreach ($ips as $ip) {
601
				if (is_ipaddrv4($ip))
602
					$ip .= "/32";
603
				else if (is_ipaddrv6($ip))
604
					$ip .= "/128";
605

    
606
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
607

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

    
610
				if (is_subnet($ip))
611
					if (is_ipaddr($gatewayip)) {
612
						mwexec($cmd . escapeshellarg($gatewayip));
613
						if (isset($config['system']['route-debug'])) {
614
							$mt = microtime();
615
							log_error("ROUTING debug: $mt - $cmd $gatewayip");
616
						}
617
					} else if (!empty($interfacegw)) {
618
						mwexec($cmd . "-iface " . escapeshellarg($interfacegw));
619
						if (isset($config['system']['route-debug'])) {
620
							$mt = microtime();
621
							log_error("ROUTING debug: $mt - $cmd -iface $interfacegw ");
622
						}
623
					}
624
			}
625
		}
626
		unset($gateways_arr);
627
	}
628
	unset($static_routes);
629

    
630
	if ($update_dns === false) {
631
		if (count($filterdns_list)) {
632
			$interval = 60;
633
			$hostnames = "";
634
			array_unique($filterdns_list);
635
			foreach ($filterdns_list as $hostname)
636
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
637
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
638
			unset($hostnames);
639

    
640
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid"))
641
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
642
			else
643
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
644
		} else {
645
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
646
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
647
		}
648
	}
649
	unset($filterdns_list);
650

    
651
	return 0;
652
}
653

    
654
function system_routing_enable() {
655
	global $config, $g;
656
	if(isset($config['system']['developerspew'])) {
657
		$mt = microtime();
658
		echo "system_routing_enable() being called $mt\n";
659
	}
660

    
661
	set_sysctl(array(
662
		"net.inet.ip.forwarding" => "1",
663
		"net.inet6.ip6.forwarding" => "1"
664
	));
665

    
666
	return;
667
}
668

    
669
function system_syslogd_fixup_server($server) {
670
	/* If it's an IPv6 IP alone, encase it in brackets */
671
	if (is_ipaddrv6($server))
672
		return "[$server]";
673
	else
674
		return $server;
675
}
676

    
677
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
678
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
679
	$facility .= " ".
680
	$remote_servers = "";
681
	$pad_to  = 56;
682
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
683
	if($syslogcfg['remoteserver'])
684
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
685
	if($syslogcfg['remoteserver2'])
686
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
687
	if($syslogcfg['remoteserver3'])
688
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
689
	return $remote_servers;
690
}
691

    
692
function system_syslogd_start() {
693
	global $config, $g;
694
	if(isset($config['system']['developerspew'])) {
695
		$mt = microtime();
696
		echo "system_syslogd_start() being called $mt\n";
697
	}
698

    
699
	mwexec("/etc/rc.d/hostid start");
700

    
701
	$syslogcfg = $config['syslog'];
702

    
703
	if ($g['booting'])
704
		echo gettext("Starting syslog...");
705

    
706
	if (is_process_running("fifolog_writer"))
707
		mwexec('/bin/pkill fifolog_writer');
708

    
709
	// Which logging type are we using this week??
710
	if (isset($config['system']['disablesyslogclog'])) {
711
		$log_directive = "";
712
		$log_create_directive = "/usr/bin/touch ";
713
		$log_size = "";
714
	} else if (isset($config['system']['usefifolog'])) {
715
		$log_directive = "|/usr/sbin/fifolog_writer ";
716
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
717
		$log_create_directive = "/usr/sbin/fifolog_create -s ";
718
	} else { // Defaults to CLOG
719
		$log_directive = "%";
720
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
721
		$log_create_directive = "/usr/local/sbin/clog -i -s ";
722
	}
723

    
724
	$syslogd_extra = "";
725
	if (isset($syslogcfg)) {
726
		$separatelogfacilities = array('ntp','ntpd','ntpdate','charon','ipsec_starter','openvpn','pptps','poes','l2tps','relayd','hostapd','dnsmasq','filterdns','unbound','dhcpd','dhcrelay','dhclient','dhcp6c','apinger','radvd','routed','olsrd','zebra','ospfd','bgpd','miniupnpd','filterlog');
727
		$syslogconf = "";
728
		if($config['installedpackages']['package']) {
729
			foreach($config['installedpackages']['package'] as $package) {
730
				if($package['logging']) {
731
					array_push($separatelogfacilities, $package['logging']['facilityname']);
732
					mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
733
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
734
				}
735
			}
736
		}
737
		$facilitylist = implode(',', array_unique($separatelogfacilities));
738
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd,miniupnpd\n";
739
		if (!isset($syslogcfg['disablelocallogging']))
740
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
741

    
742
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
743
		if (!isset($syslogcfg['disablelocallogging'])) 
744
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
745

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

    
750
		$syslogconf .= "!pptps\n";
751
		if (!isset($syslogcfg['disablelocallogging'])) 
752
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/pptps.log\n";
753

    
754
		$syslogconf .= "!poes\n";
755
		if (!isset($syslogcfg['disablelocallogging'])) 
756
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
757

    
758
		$syslogconf .= "!l2tps\n";
759
		if (!isset($syslogcfg['disablelocallogging'])) 
760
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/l2tps.log\n";
761

    
762
		$syslogconf .= "!charon,ipsec_starter\n";
763
		if (!isset($syslogcfg['disablelocallogging'])) 
764
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ipsec.log\n";
765
		if (isset($syslogcfg['vpn']))
766
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
767

    
768
		$syslogconf .= "!openvpn\n";
769
		if (!isset($syslogcfg['disablelocallogging'])) 
770
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/openvpn.log\n";
771
		if (isset($syslogcfg['vpn']))
772
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
773

    
774
		$syslogconf .= "!apinger\n";
775
		if (!isset($syslogcfg['disablelocallogging']))
776
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/gateways.log\n";
777
		if (isset($syslogcfg['apinger']))
778
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
779

    
780
		$syslogconf .= "!dnsmasq,filterdns,unbound\n";
781
		if (!isset($syslogcfg['disablelocallogging']))
782
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
783

    
784
		$syslogconf .= "!dhcpd,dhcrelay,dhclient,dhcp6c\n";
785
		if (!isset($syslogcfg['disablelocallogging']))
786
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/dhcpd.log\n";
787
		if (isset($syslogcfg['dhcp']))
788
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
789

    
790
		$syslogconf .= "!relayd\n";
791
		if (!isset($syslogcfg['disablelocallogging']))
792
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/relayd.log\n";
793
		if (isset($syslogcfg['relayd']))
794
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
795

    
796
		$syslogconf .= "!hostapd\n";
797
		if (!isset($syslogcfg['disablelocallogging']))
798
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
799
		if (isset($syslogcfg['hostapd']))
800
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
801

    
802
		$syslogconf .= "!filterlog\n";
803
		$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/filter.log\n";
804
		if (isset($syslogcfg['filter']))
805
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
806

    
807
		$syslogconf .= "!-{$facilitylist}\n";
808
		if (!isset($syslogcfg['disablelocallogging'])) 
809
			$syslogconf .= <<<EOD
810
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
811
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
812
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
813
*.notice;kern.debug;lpr.info;mail.crit;daemon.none;		{$log_directive}{$g['varlog_path']}/system.log
814
news.err;local0.none;local3.none;local4.none;			{$log_directive}{$g['varlog_path']}/system.log
815
local7.none							{$log_directive}{$g['varlog_path']}/system.log
816
security.*							{$log_directive}{$g['varlog_path']}/system.log
817
auth.info;authpriv.info;daemon.info				{$log_directive}{$g['varlog_path']}/system.log
818
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
819
*.emerg								*
820

    
821
EOD;
822
		if (isset($syslogcfg['vpn']))
823
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
824
		if (isset($syslogcfg['portalauth']))
825
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
826
		if (isset($syslogcfg['dhcp']))
827
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
828
		if (isset($syslogcfg['system'])) {
829
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.notice;kern.debug;lpr.info;mail.crit;");
830
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "news.err;local0.none;local3.none;local7.none");
831
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "security.*");
832
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "auth.info;authpriv.info;daemon.info");
833
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.emerg");
834
		}
835
		if (isset($syslogcfg['logall'])) {
836
			// Make everything mean everything, including facilities excluded above.
837
			$syslogconf .= "!*\n";
838
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
839
		}
840

    
841
		if (isset($syslogcfg['zmqserver'])) {
842
				$syslogconf .= <<<EOD
843
*.*								^{$syslogcfg['zmqserver']}
844

    
845
EOD;
846
		}
847
		/* write syslog.conf */		
848
		if (!@file_put_contents("{$g['varetc_path']}/syslog.conf", $syslogconf)) {
849
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
850
			unset($syslogconf);
851
			return 1;
852
		}
853
		unset($syslogconf);
854

    
855
		// Ensure that the log directory exists
856
		if (!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
857
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
858

    
859
		$sourceip = "";
860
		if (!empty($syslogcfg['sourceip'])) {
861
			if ($syslogcfg['ipproto'] == "ipv6") {
862
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
863
				if (!is_ipaddr($ifaddr))
864
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
865
			} else {
866
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
867
				if (!is_ipaddr($ifaddr))
868
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
869
			}
870
			if (is_ipaddr($ifaddr)) {
871
				$sourceip = "-b {$ifaddr}";
872
			}
873
		}
874

    
875
		$syslogd_extra = "-f {$g['varetc_path']}/syslog.conf {$sourceip}";
876
	}
877

    
878
	if (isvalidpid("{$g['varrun_path']}/syslog.pid"))
879
		sigkillbypid("{$g['varrun_path']}/syslog.pid", "HUP");
880
	else
881
		$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}");
882

    
883
	if ($g['booting'])
884
		echo gettext("done.") . "\n";
885

    
886
	return $retval;
887
}
888

    
889
function system_webgui_create_certificate() {
890
	global $config, $g;
891

    
892
	if (!is_array($config['ca']))
893
		$config['ca'] = array();
894
	$a_ca =& $config['ca'];
895
	if (!is_array($config['cert']))
896
		$config['cert'] = array();
897
	$a_cert =& $config['cert'];
898
	log_error("Creating SSL Certificate for this host");
899

    
900
	$cert = array();
901
	$cert['refid'] = uniqid();
902
	$cert['descr'] = gettext("webConfigurator default ({$cert['refid']})");
903

    
904
	$dn = array(
905
		'countryName' => "US",
906
		'stateOrProvinceName' => "State",
907
		'localityName' => "Locality",
908
		'organizationName' => "{$g['product_name']} webConfigurator Self-Signed Certificate",
909
		'emailAddress' => "admin@{$config['system']['hostname']}.{$config['system']['domain']}",
910
		'commonName' => "{$config['system']['hostname']}-{$cert['refid']}");
911
	$old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warings directly to a page screwing menu tab */
912
	if (!cert_create($cert, null, 2048, 2000, $dn, "self-signed", "sha256")){
913
		while($ssl_err = openssl_error_string()){
914
			log_error("Error creating WebGUI Certificate: openssl library returns: " . $ssl_err);
915
		}
916
		error_reporting($old_err_level);
917
		return null;
918
	}
919
	error_reporting($old_err_level);
920

    
921
	$a_cert[] = $cert;
922
	$config['system']['webgui']['ssl-certref'] = $cert['refid'];
923
	write_config(gettext("Generated new self-signed HTTPS certificate ({$cert['refid']})"));
924
	return $cert;
925
}
926

    
927
function system_webgui_start() {
928
	global $config, $g;
929

    
930
	if ($g['booting'])
931
		echo gettext("Starting webConfigurator...");
932

    
933
	chdir($g['www_path']);
934

    
935
	/* defaults */
936
	$portarg = "80";
937
	$crt = "";
938
	$key = "";
939
	$ca = "";
940

    
941
	/* non-standard port? */
942
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
943
		$portarg = "{$config['system']['webgui']['port']}";
944

    
945
	if ($config['system']['webgui']['protocol'] == "https") {
946
		// Ensure that we have a webConfigurator CERT
947
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
948
		if(!is_array($cert) || !$cert['crt'] || !$cert['prv'])
949
			$cert = system_webgui_create_certificate();
950
		$crt = base64_decode($cert['crt']);
951
		$key = base64_decode($cert['prv']);
952

    
953
		if(!$config['system']['webgui']['port'])
954
			$portarg = "443";
955
		$ca  = ca_chain($cert);
956
	}
957

    
958
	/* generate lighttpd configuration */
959
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
960
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
961
		"cert.pem", "ca.pem");
962

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

    
966
	sleep(1);
967

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

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

    
973
	if ($g['booting']) {
974
		if ($res == 0)
975
			echo gettext("done.") . "\n";
976
		else
977
			echo gettext("failed!") . "\n";
978
	}
979

    
980
	return $res;
981
}
982

    
983
function system_generate_lighty_config($filename,
984
	$cert,
985
	$key,
986
	$ca,
987
	$pid_file,
988
	$port = 80,
989
	$document_root = "/usr/local/www/",
990
	$cert_location = "cert.pem",
991
	$ca_location = "ca.pem",
992
	$captive_portal = false) {
993

    
994
	global $config, $g;
995

    
996
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
997
		mkdir("{$g['tmp_path']}/lighttpdcompress");
998

    
999
	if(isset($config['system']['developerspew'])) {
1000
		$mt = microtime();
1001
		echo "system_generate_lighty_config() being called $mt\n";
1002
	}
1003

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

    
1008
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1009
		if (empty($maxprocperip))
1010
			$maxprocperip = 10;
1011
		$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
1012

    
1013
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
1014
		if(!is_dir("{$g['tmp_path']}/captiveportal"))
1015
			@mkdir("{$g['tmp_path']}/captiveportal", 0555);
1016
		$server_max_request_size = "server.max-request-size    = 384";
1017
		$cgi_config = "";
1018
	} else {
1019
		$captiveportal = ",\"mod_cgi\"";
1020
		$captive_portal_rewrite = "";
1021
		$captive_portal_mod_evasive = "";
1022
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
1023
		$server_max_request_size = "server.max-request-size    = 2097152";
1024
		$cgi_config = "cgi.assign                 = ( \".cgi\" => \"\" )";
1025
	}
1026
	
1027
	if (empty($port))
1028
		$lighty_port = "80";
1029
	else
1030
		$lighty_port = $port;
1031

    
1032
	$memory = get_memory();
1033
	$realmem = $memory[1];
1034

    
1035
	// Determine web GUI process settings and take into account low memory systems
1036
	if ($realmem < 255)
1037
		$max_procs = 1;
1038
	else
1039
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
1040

    
1041
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM 
1042
	if ($captive_portal !== false)  {
1043
		if ($realmem > 135 and $realmem < 256) {
1044
			$max_procs += 1; // 2 worker processes
1045
		} else if ($realmem > 255 and $realmem < 513) {
1046
			$max_procs += 2; // 3 worker processes
1047
		} else if ($realmem > 512) {
1048
			$max_procs += 4; // 6 worker processes
1049
		}
1050
		if ($max_procs > 1)
1051
			$max_php_children = intval($max_procs/2);
1052
		else
1053
			$max_php_children = 1;
1054

    
1055
	} else {
1056
		if ($realmem < 78)
1057
			$max_php_children = 0;
1058
		else
1059
			$max_php_children = 1;
1060
	}
1061

    
1062
	if(!isset($config['syslog']['nologlighttpd'])) {
1063
		$lighty_use_syslog = <<<EOD
1064
## where to send error-messages to
1065
server.errorlog-use-syslog="enable"
1066
EOD;
1067
	}
1068

    
1069

    
1070
	if ($captive_portal !== false) {
1071
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi-{$captive_portal}.socket";
1072
		$fastcgi_config = <<<EOD
1073
#### fastcgi module
1074
## read fastcgi.txt for more info
1075
fastcgi.server = ( ".php" =>
1076
	( "localhost" =>
1077
		(
1078
			"socket" => "{$fast_cgi_path}",
1079
			"max-procs" => {$max_procs},
1080
			"bin-environment" => (
1081
				"PHP_FCGI_CHILDREN" => "{$max_php_children}",
1082
				"PHP_FCGI_MAX_REQUESTS" => "500"
1083
			),
1084
			"bin-path" => "/usr/local/bin/php"
1085
		)
1086
	)
1087
)
1088

    
1089
EOD;
1090
	} else {
1091
		$fast_cgi_path = "{$g['varrun_path']}/php-fpm.socket";
1092
		$fastcgi_config = <<<EOD
1093
#### fastcgi module
1094
## read fastcgi.txt for more info
1095
fastcgi.server = ( ".php" =>
1096
	( "localhost" =>
1097
		(
1098
			"socket" => "{$fast_cgi_path}",
1099
			"broken-scriptfilename" => "enable"
1100
		)
1101
	)
1102
)
1103

    
1104
EOD;
1105
	}
1106

    
1107

    
1108
	$lighty_config = <<<EOD
1109
#
1110
# lighttpd configuration file
1111
#
1112
# use a it as base for lighttpd 1.0.0 and above
1113
#
1114
############ Options you really have to take care of ####################
1115

    
1116
## FreeBSD!
1117
server.event-handler	= "freebsd-kqueue"
1118
server.network-backend 	= "writev"
1119
#server.use-ipv6 = "enable"
1120

    
1121
## modules to load
1122
server.modules              =   ( "mod_access", "mod_expire", "mod_compress", "mod_redirect",
1123
	{$captiveportal}, "mod_fastcgi"
1124
)
1125

    
1126
server.max-keep-alive-requests = 15
1127
server.max-keep-alive-idle = 30
1128

    
1129
## a static document-root, for virtual-hosting take look at the
1130
## server.virtual-* options
1131
server.document-root        = "{$document_root}"
1132
{$captive_portal_rewrite}
1133

    
1134
# Maximum idle time with nothing being written (php downloading)
1135
server.max-write-idle = 999
1136

    
1137
{$lighty_use_syslog}
1138

    
1139
# files to check for if .../ is requested
1140
server.indexfiles           = ( "index.php", "index.html",
1141
                                "index.htm", "default.htm" )
1142

    
1143
# mimetype mapping
1144
mimetype.assign             = (
1145
  ".pdf"          =>      "application/pdf",
1146
  ".sig"          =>      "application/pgp-signature",
1147
  ".spl"          =>      "application/futuresplash",
1148
  ".class"        =>      "application/octet-stream",
1149
  ".ps"           =>      "application/postscript",
1150
  ".torrent"      =>      "application/x-bittorrent",
1151
  ".dvi"          =>      "application/x-dvi",
1152
  ".gz"           =>      "application/x-gzip",
1153
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
1154
  ".swf"          =>      "application/x-shockwave-flash",
1155
  ".tar.gz"       =>      "application/x-tgz",
1156
  ".tgz"          =>      "application/x-tgz",
1157
  ".tar"          =>      "application/x-tar",
1158
  ".zip"          =>      "application/zip",
1159
  ".mp3"          =>      "audio/mpeg",
1160
  ".m3u"          =>      "audio/x-mpegurl",
1161
  ".wma"          =>      "audio/x-ms-wma",
1162
  ".wax"          =>      "audio/x-ms-wax",
1163
  ".ogg"          =>      "audio/x-wav",
1164
  ".wav"          =>      "audio/x-wav",
1165
  ".gif"          =>      "image/gif",
1166
  ".jpg"          =>      "image/jpeg",
1167
  ".jpeg"         =>      "image/jpeg",
1168
  ".png"          =>      "image/png",
1169
  ".xbm"          =>      "image/x-xbitmap",
1170
  ".xpm"          =>      "image/x-xpixmap",
1171
  ".xwd"          =>      "image/x-xwindowdump",
1172
  ".css"          =>      "text/css",
1173
  ".html"         =>      "text/html",
1174
  ".htm"          =>      "text/html",
1175
  ".js"           =>      "text/javascript",
1176
  ".asc"          =>      "text/plain",
1177
  ".c"            =>      "text/plain",
1178
  ".conf"         =>      "text/plain",
1179
  ".text"         =>      "text/plain",
1180
  ".txt"          =>      "text/plain",
1181
  ".dtd"          =>      "text/xml",
1182
  ".xml"          =>      "text/xml",
1183
  ".mpeg"         =>      "video/mpeg",
1184
  ".mpg"          =>      "video/mpeg",
1185
  ".mov"          =>      "video/quicktime",
1186
  ".qt"           =>      "video/quicktime",
1187
  ".avi"          =>      "video/x-msvideo",
1188
  ".asf"          =>      "video/x-ms-asf",
1189
  ".asx"          =>      "video/x-ms-asf",
1190
  ".wmv"          =>      "video/x-ms-wmv",
1191
  ".bz2"          =>      "application/x-bzip",
1192
  ".tbz"          =>      "application/x-bzip-compressed-tar",
1193
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
1194
 )
1195

    
1196
# Use the "Content-Type" extended attribute to obtain mime type if possible
1197
#mimetypes.use-xattr        = "enable"
1198

    
1199
## deny access the file-extensions
1200
#
1201
# ~    is for backupfiles from vi, emacs, joe, ...
1202
# .inc is often used for code includes which should in general not be part
1203
#      of the document-root
1204
url.access-deny             = ( "~", ".inc" )
1205

    
1206

    
1207
######### Options that are good to be but not neccesary to be changed #######
1208

    
1209
## bind to port (default: 80)
1210

    
1211
EOD;
1212

    
1213
	$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1214
	$lighty_config .= "server.port  = {$lighty_port}\n";
1215
	$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1216
	$lighty_config .= "\$SERVER[\"socket\"]  == \"[::]:{$lighty_port}\" { \n";
1217
	if($cert <> "" and $key <> "") {
1218
		$lighty_config .= "\n";
1219
		$lighty_config .= "## ssl configuration\n";
1220
		$lighty_config .= "ssl.engine = \"enable\"\n";
1221
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1222
		if($ca <> "")
1223
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1224
	}
1225
	$lighty_config .= " }\n";
1226

    
1227

    
1228
	$lighty_config .= <<<EOD
1229

    
1230
## error-handler for status 404
1231
#server.error-handler-404   = "/error-handler.html"
1232
#server.error-handler-404   = "/error-handler.php"
1233

    
1234
## to help the rc.scripts
1235
server.pid-file            = "{$g['varrun_path']}/{$pid_file}"
1236

    
1237
## virtual directory listings
1238
server.dir-listing         = "disable"
1239

    
1240
## enable debugging
1241
debug.log-request-header   = "disable"
1242
debug.log-response-header  = "disable"
1243
debug.log-request-handling = "disable"
1244
debug.log-file-not-found   = "disable"
1245

    
1246
# gzip compression
1247
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1248
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1249

    
1250
{$server_upload_dirs}
1251

    
1252
{$server_max_request_size}
1253

    
1254
{$fastcgi_config}
1255

    
1256
{$cgi_config}
1257

    
1258
{$captive_portal_mod_evasive}
1259

    
1260
expire.url = (
1261
				"" => "access 50 hours",	
1262
        )
1263

    
1264
EOD;
1265

    
1266
	$cert = str_replace("\r", "", $cert);
1267
	$key = str_replace("\r", "", $key);
1268
	$ca = str_replace("\r", "", $ca);
1269

    
1270
	$cert = str_replace("\n\n", "\n", $cert);
1271
	$key = str_replace("\n\n", "\n", $key);
1272
	$ca = str_replace("\n\n", "\n", $ca);
1273

    
1274
	if($cert <> "" and $key <> "") {
1275
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1276
		if (!$fd) {
1277
			printf(gettext("Error: cannot open cert.pem in system_webgui_start().%s"), "\n");
1278
			return 1;
1279
		}
1280
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1281
		fwrite($fd, $cert);
1282
		fwrite($fd, "\n");
1283
		fwrite($fd, $key);
1284
		fclose($fd);
1285
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
1286
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1287
			if (!$fd) {
1288
				printf(gettext("Error: cannot open ca.pem in system_webgui_start().%s"), "\n");
1289
				return 1;
1290
			}
1291
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1292
			fwrite($fd, $ca);
1293
			fclose($fd);
1294
		}
1295
		$lighty_config .= "\n";
1296
		$lighty_config .= "## " . gettext("ssl configuration") . "\n";
1297
		$lighty_config .= "ssl.engine = \"enable\"\n";
1298
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1299

    
1300
		// SSLv2/3 is deprecated, force use of TLS
1301
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
1302
		$lighty_config .= "ssl.use-sslv3 = \"disable\"\n";
1303

    
1304
		/* Hifn accelerators do NOT work with the BEAST mitigation code. Do not allow it to be enabled if a Hifn card has been detected. */
1305
		$fd = @fopen("{$g['varlog_path']}/dmesg.boot", "r");
1306
		if ($fd) {
1307
			while (!feof($fd)) {
1308
				$dmesgl = fgets($fd);
1309
				if (preg_match("/^hifn.: (.*?),/", $dmesgl, $matches) && isset($config['system']['webgui']['beast_protection'])) {
1310
						unset($config['system']['webgui']['beast_protection']);
1311
						log_error("BEAST Protection disabled because a conflicting cryptographic accelerator card has been detected (" . $matches[1] . ")");
1312
					break;
1313
				}
1314
			}
1315
			fclose($fd);
1316
		}
1317

    
1318
		if (isset($config['system']['webgui']['beast_protection'])) {
1319
			$lighty_config .= "ssl.honor-cipher-order = \"enable\"\n";
1320
			$lighty_config .= "ssl.cipher-list = \"ECDHE-RSA-AES256-SHA384:AES256-SHA256:RC4-SHA:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM\"\n";
1321
		} else {
1322
			$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";
1323
		}
1324

    
1325
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1326
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1327
	}
1328

    
1329
	// Add HTTP to HTTPS redirect	
1330
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1331
		if($lighty_port != "443") 
1332
			$redirectport = ":{$lighty_port}";
1333
		$lighty_config .= <<<EOD
1334
\$SERVER["socket"] == ":80" {
1335
	\$HTTP["host"] =~ "(.*)" {
1336
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1337
	}
1338
}
1339
\$SERVER["socket"] == "[::]:80" {
1340
	\$HTTP["host"] =~ "(.*)" {
1341
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1342
	}
1343
}
1344
EOD;
1345
	}
1346

    
1347
	$fd = fopen("{$filename}", "w");
1348
	if (!$fd) {
1349
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1350
		return 1;
1351
	}
1352
	fwrite($fd, $lighty_config);
1353
	fclose($fd);
1354

    
1355
	return 0;
1356

    
1357
}
1358

    
1359
function system_timezone_configure() {
1360
	global $config, $g;
1361
	if(isset($config['system']['developerspew'])) {
1362
		$mt = microtime();
1363
		echo "system_timezone_configure() being called $mt\n";
1364
	}
1365

    
1366
	$syscfg = $config['system'];
1367

    
1368
	if ($g['booting'])
1369
		echo gettext("Setting timezone...");
1370

    
1371
	/* extract appropriate timezone file */
1372
	$timezone = $syscfg['timezone'];
1373
	if ($timezone) {
1374
		exec('/usr/bin/tar -tvzf /usr/share/zoneinfo.tgz', $tzs);
1375
		foreach ($tzs as $tz) {
1376
			if (preg_match(",{$timezone}$,", $tz))
1377
				break;
1378
			if (preg_match(",{$timezone} link to *(.*)$,", $tz, $matches)) {
1379
				$timezone = $matches[1];
1380
				break;
1381
			}
1382
		}
1383
	} else
1384
		$timezone = "Etc/UTC";
1385

    
1386
	conf_mount_rw();
1387

    
1388
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1389
		escapeshellarg($timezone) . " > /etc/localtime");
1390

    
1391
	mwexec("sync");
1392
	conf_mount_ro();
1393

    
1394
	if ($g['booting'])
1395
		echo gettext("done.") . "\n";
1396
}
1397

    
1398
function system_ntp_setup_gps($serialport) {
1399
	global $config, $g;
1400
	$gps_device = '/dev/gps0';
1401
	$serialport = '/dev/'.$serialport;
1402

    
1403
	if (!file_exists($serialport))
1404
		return false;
1405

    
1406
	conf_mount_rw();
1407
	// Create symlink that ntpd requires
1408
	unlink_if_exists($gps_device);
1409
	symlink($serialport, $gps_device);
1410

    
1411
	/* Send the following to the GPS port to initialize the GPS */
1412
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
1413
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
1414
	}else{
1415
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1416
	}
1417

    
1418
	/* XXX: Why not file_put_contents to the device */
1419
	@file_put_contents('/tmp/gps.init', $gps_init);
1420
	`cat /tmp/gps.init > $serialport`;
1421

    
1422
	/* Add /etc/remote entry in case we need to read from the GPS with tip */
1423
	if (intval(`grep -c '^gps0' /etc/remote`) == 0) {
1424
		$gpsbaud = '4800';
1425
		if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['speed'])) {
1426
			switch($config['ntpd']['gps']['speed']) {
1427
				case '16':
1428
					$gpsbaud = '9600';
1429
					break;
1430
				case '32':
1431
					$gpsbaud = '19200';
1432
					break;
1433
				case '48':
1434
					$gpsbaud = '38400';
1435
					break;
1436
				case '64':
1437
					$gpsbaud = '57600';
1438
					break;
1439
				case '80':
1440
					$gpsbaud = '115200';
1441
					break;
1442
			}
1443
		}
1444
		@file_put_contents("/etc/remote", "gps0:dv={$serialport}:br#{$gpsbaud}:pa=none:", FILE_APPEND);
1445
	}
1446

    
1447
	conf_mount_ro();
1448

    
1449
	return true;
1450
}
1451

    
1452
function system_ntp_setup_pps($serialport) {
1453
	global $config, $g;
1454

    
1455
	$pps_device = '/dev/pps0';
1456
	$serialport = '/dev/'.$serialport;
1457

    
1458
	if (!file_exists($serialport))
1459
		return false;
1460

    
1461
	conf_mount_rw();
1462
	// Create symlink that ntpd requires
1463
	unlink_if_exists($pps_device);
1464
	@symlink($serialport, $pps_device);
1465

    
1466
	conf_mount_ro();
1467

    
1468
	return true;
1469
}
1470

    
1471

    
1472
function system_ntp_configure($start_ntpd=true) {
1473
	global $config, $g;
1474

    
1475
	$driftfile = "/var/db/ntpd.drift";
1476
	$statsdir = "/var/log/ntp";
1477
	$gps_device = '/dev/gps0';
1478

    
1479
	if ($g['platform'] == 'jail')
1480
		return;
1481

    
1482
	safe_mkdir($statsdir);
1483

    
1484
	if (!is_array($config['ntpd']))
1485
		$config['ntpd'] = array();
1486

    
1487
	$ntpcfg = "# \n";
1488
	$ntpcfg .= "# pfSense ntp configuration file \n";
1489
	$ntpcfg .= "# \n\n";
1490
	$ntpcfg .= "tinker panic 0 \n";
1491

    
1492
	/* Add Orphan mode */
1493
	$ntpcfg .= "# Orphan mode stratum\n";
1494
	$ntpcfg .= 'tos orphan ';
1495
	if (!empty($config['ntpd']['orphan'])) {
1496
		$ntpcfg .= $config['ntpd']['orphan'];
1497
	}else{
1498
		$ntpcfg .= '12';
1499
	}
1500
	$ntpcfg .= "\n";
1501

    
1502
	/* Add PPS configuration */
1503
	if (!empty($config['ntpd']['pps'])
1504
		&& file_exists('/dev/'.$config['ntpd']['pps']['port'])
1505
		&& system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
1506
		$ntpcfg .= "\n";
1507
		$ntpcfg .= "# PPS Setup\n";
1508
		$ntpcfg .= 'server 127.127.22.0';
1509
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1510
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
1511
			$ntpcfg .= ' prefer'; 
1512
		}
1513
		if (!empty($config['ntpd']['pps']['noselect'])) {
1514
			$ntpcfg .= ' noselect ';
1515
		}
1516
		$ntpcfg .= "\n";
1517
		$ntpcfg .= 'fudge 127.127.22.0';
1518
		if (!empty($config['ntpd']['pps']['fudge1'])) {
1519
			$ntpcfg .= ' time1 ';
1520
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
1521
		}
1522
		if (!empty($config['ntpd']['pps']['flag2'])) {
1523
			$ntpcfg .= ' flag2 1';
1524
		}
1525
		if (!empty($config['ntpd']['pps']['flag3'])) {
1526
			$ntpcfg .= ' flag3 1';
1527
		}else{
1528
			$ntpcfg .= ' flag3 0';
1529
		}
1530
		if (!empty($config['ntpd']['pps']['flag4'])) {
1531
			$ntpcfg .= ' flag4 1';
1532
		}
1533
		if (!empty($config['ntpd']['pps']['refid'])) {
1534
			$ntpcfg .= ' refid ';
1535
			$ntpcfg .= $config['ntpd']['pps']['refid'];
1536
		}
1537
		$ntpcfg .= "\n";
1538
	}
1539
	/* End PPS configuration */
1540

    
1541
	/* Add GPS configuration */
1542
	if (!empty($config['ntpd']['gps'])
1543
		&& file_exists('/dev/'.$config['ntpd']['gps']['port'])
1544
		&& system_ntp_setup_gps($config['ntpd']['gps']['port'])) {
1545
		$ntpcfg .= "\n";
1546
		$ntpcfg .= "# GPS Setup\n";
1547
		$ntpcfg .= 'server 127.127.20.0 mode ';
1548
		if (!empty($config['ntpd']['gps']['nmea']) || !empty($config['ntpd']['gps']['speed']) || !empty($config['ntpd']['gps']['subsec'])) {
1549
			if (!empty($config['ntpd']['gps']['nmea'])) {
1550
				$ntpmode = (int) $config['ntpd']['gps']['nmea'];
1551
			}
1552
			if (!empty($config['ntpd']['gps']['speed'])) {
1553
				$ntpmode += (int) $config['ntpd']['gps']['speed'];
1554
			}
1555
			if (!empty($config['ntpd']['gps']['subsec'])) {
1556
				$ntpmode += 128;
1557
			}
1558
			$ntpcfg .= (string) $ntpmode;
1559
		}else{
1560
			$ntpcfg .= '0';
1561
		}
1562
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1563
		if (empty($config['ntpd']['gps']['prefer'])) { /*note: this one works backwards */
1564
			$ntpcfg .= ' prefer'; 
1565
		}
1566
		if (!empty($config['ntpd']['gps']['noselect'])) {
1567
			$ntpcfg .= ' noselect ';
1568
		}
1569
		$ntpcfg .= "\n";
1570
		$ntpcfg .= 'fudge 127.127.20.0';
1571
		if (!empty($config['ntpd']['gps']['fudge1'])) {
1572
			$ntpcfg .= ' time1 ';
1573
			$ntpcfg .= $config['ntpd']['gps']['fudge1'];
1574
		}
1575
		if (!empty($config['ntpd']['gps']['fudge2'])) {
1576
			$ntpcfg .= ' time2 ';
1577
			$ntpcfg .= $config['ntpd']['gps']['fudge2'];
1578
		}
1579
		if (!empty($config['ntpd']['gps']['flag1'])) {
1580
			$ntpcfg .= ' flag1 1';
1581
		}else{
1582
			$ntpcfg .= ' flag1 0';
1583
		}
1584
		if (!empty($config['ntpd']['gps']['flag2'])) {
1585
			$ntpcfg .= ' flag2 1';
1586
		}
1587
		if (!empty($config['ntpd']['gps']['flag3'])) {
1588
			$ntpcfg .= ' flag3 1';
1589
		}else{
1590
			$ntpcfg .= ' flag3 0';
1591
		}
1592
		if (!empty($config['ntpd']['gps']['flag4'])) {
1593
			$ntpcfg .= ' flag4 1';
1594
		}
1595
		if (!empty($config['ntpd']['gps']['refid'])) {
1596
			$ntpcfg .= ' refid ';
1597
			$ntpcfg .= $config['ntpd']['gps']['refid'];
1598
		}
1599
		$ntpcfg .= "\n";
1600
	}elseif (!empty($config['ntpd']['gpsport'])
1601
		&& file_exists('/dev/'.$config['ntpd']['gpsport'])
1602
		&& system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1603
		/* This handles a 2.1 and earlier config */
1604
		$ntpcfg .= "# GPS Setup\n";
1605
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1606
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1607
		// Fall back to local clock if GPS is out of sync?
1608
		$ntpcfg .= "server 127.127.1.0\n";
1609
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1610
	}
1611
	/* End GPS configuration */
1612
	
1613
	$ntpcfg .= "\n\n# Upstream Servers\n";
1614
	/* foreach through ntp servers and write out to ntpd.conf */
1615
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1616
		$ntpcfg .= "server {$ts} iburst maxpoll 9";
1617
		if (substr_count($config['ntpd']['prefer'], $ts)) $ntpcfg .= ' prefer';
1618
		if (substr_count($config['ntpd']['noselect'], $ts)) $ntpcfg .= ' noselect';
1619
		$ntpcfg .= "\n";
1620
	}
1621
	unset($ts);
1622

    
1623
	$ntpcfg .= "\n\n";
1624
	$ntpcfg .= "disable monitor\n"; //prevent NTP reflection attack, see https://forum.pfsense.org/index.php/topic,67189.msg389132.html#msg389132
1625
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
1626
		$ntpcfg .= "enable stats\n";
1627
		$ntpcfg .= 'statistics';
1628
		if (!empty($config['ntpd']['clockstats'])) {
1629
			$ntpcfg .= ' clockstats';
1630
		}
1631
		if (!empty($config['ntpd']['loopstats'])) {
1632
			$ntpcfg .= ' loopstats';
1633
		}
1634
		if (!empty($config['ntpd']['peerstats'])) {
1635
			$ntpcfg .= ' peerstats';
1636
		}
1637
		$ntpcfg .= "\n";
1638
	}
1639
	$ntpcfg .= "statsdir {$statsdir}\n";
1640
	$ntpcfg .= 'logconfig =syncall +clockall';
1641
	if (!empty($config['ntpd']['logpeer'])) {
1642
		$ntpcfg .= ' +peerall';
1643
	}
1644
	if (!empty($config['ntpd']['logsys'])) {
1645
		$ntpcfg .= ' +sysall';
1646
	}
1647
	$ntpcfg .= "\n";
1648
	$ntpcfg .= "driftfile {$driftfile}\n";
1649
	/* Access restrictions */
1650
	$ntpcfg .= 'restrict default';
1651
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1652
		$ntpcfg .= ' kod limited'; 
1653
	}
1654
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1655
		$ntpcfg .= ' nomodify'; 
1656
	}
1657
	if (!empty($config['ntpd']['noquery'])) {
1658
		$ntpcfg .= ' noquery';
1659
	}
1660
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1661
		$ntpcfg .= ' nopeer'; 
1662
	}
1663
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1664
		$ntpcfg .= ' notrap'; 
1665
	}
1666
	if (!empty($config['ntpd']['noserve'])) {
1667
		$ntpcfg .= ' noserve';
1668
	}
1669
	$ntpcfg .= "\nrestrict -6 default";
1670
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1671
		$ntpcfg .= ' kod limited'; 
1672
	}
1673
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1674
		$ntpcfg .= ' nomodify'; 
1675
	}
1676
	if (!empty($config['ntpd']['noquery'])) {
1677
		$ntpcfg .= ' noquery';
1678
	}
1679
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1680
		$ntpcfg .= ' nopeer'; 
1681
	}
1682
	if (!empty($config['ntpd']['noserve'])) {
1683
		$ntpcfg .= ' noserve';
1684
	}
1685
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1686
		$ntpcfg .= ' notrap'; 
1687
	}
1688
	$ntpcfg .= "\n";
1689

    
1690
	/* A leapseconds file is really only useful if this clock is stratum 1 */
1691
	$ntpcfg .= "\n";
1692
	if (!empty($config['ntpd']['leapsec'])) {
1693
		$leapsec .= base64_decode($config['ntpd']['leapsec']);
1694
		file_put_contents('/var/db/leap-seconds', $leapsec);
1695
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
1696
	}
1697
	
1698

    
1699
	if (empty($config['ntpd']['interface']))
1700
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface']))
1701
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1702
		else
1703
			$interfaces = array();
1704
	else
1705
		$interfaces = explode(",", $config['ntpd']['interface']);
1706

    
1707
	if (is_array($interfaces) && count($interfaces)) {
1708
		$ntpcfg .= "interface ignore all\n";
1709
		foreach ($interfaces as $interface) {
1710
			if (!is_ipaddr($interface)) {
1711
				$interface = get_real_interface($interface);
1712
			}
1713
			if (!empty($interface))
1714
				$ntpcfg .= "interface listen {$interface}\n";
1715
		}
1716
	}
1717

    
1718
	/* open configuration for wrting or bail */
1719
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
1720
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1721
		return;
1722
	}
1723

    
1724
	/* At bootup we just want to write out the config. */
1725
	if (!$start_ntpd)
1726
		return;
1727

    
1728
	/* if ntpd is running, kill it */
1729
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1730
		killbypid("{$g['varrun_path']}/ntpd.pid");
1731
	}
1732
	@unlink("{$g['varrun_path']}/ntpd.pid");
1733

    
1734
	/* if /var/empty does not exist, create it */
1735
	if(!is_dir("/var/empty"))
1736
		mkdir("/var/empty", 0775, true);
1737

    
1738
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1739
	mwexec("/usr/local/sbin/ntpd -g -c {$g['varetc_path']}/ntpd.conf -p {$g['varrun_path']}/ntpd.pid", false, true);
1740
	
1741
	// Note that we are starting up
1742
	log_error("NTPD is starting up.");
1743
	return;
1744
}
1745

    
1746
function sync_system_time() {
1747
	global $config, $g;
1748

    
1749
	if ($g['booting'])
1750
		echo gettext("Syncing system time before startup...");
1751

    
1752
	/* foreach through servers and write out to ntpd.conf */
1753
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1754
		mwexec("/usr/local/sbin/ntpdate -s $ts");
1755
	}
1756
	
1757
	if ($g['booting'])
1758
		echo gettext("done.") . "\n";
1759
	
1760
}
1761

    
1762
function system_halt() {
1763
	global $g;
1764

    
1765
	system_reboot_cleanup();
1766

    
1767
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1768
}
1769

    
1770
function system_reboot() {
1771
	global $g;
1772

    
1773
	system_reboot_cleanup();
1774

    
1775
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1776
}
1777

    
1778
function system_reboot_sync() {
1779
	global $g;
1780

    
1781
	system_reboot_cleanup();
1782

    
1783
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1784
}
1785

    
1786
function system_reboot_cleanup() {
1787
	global $config, $cpzone;
1788

    
1789
	mwexec("/usr/local/bin/beep.sh stop");
1790
	require_once("captiveportal.inc");
1791
	if (is_array($config['captiveportal'])) {
1792
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
1793
			captiveportal_radius_stop_all();
1794
			captiveportal_send_server_accounting(true);
1795
		}
1796
	}
1797
	require_once("voucher.inc");
1798
	voucher_save_db_to_config();
1799
	require_once("pkg-utils.inc");
1800
	stop_packages();
1801
}
1802

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

    
1810
	if ($early)
1811
		$cmdn = "earlyshellcmd";
1812
	else
1813
		$cmdn = "shellcmd";
1814

    
1815
	if (is_array($config['system'][$cmdn])) {
1816

    
1817
		/* *cmd is an array, loop through */
1818
		foreach ($config['system'][$cmdn] as $cmd) {
1819
			exec($cmd);
1820
		}
1821

    
1822
	} elseif($config['system'][$cmdn] <> "") {
1823

    
1824
		/* execute single item */
1825
		exec($config['system'][$cmdn]);
1826

    
1827
	}
1828
}
1829

    
1830
function system_console_configure() {
1831
	global $config, $g;
1832
	if(isset($config['system']['developerspew'])) {
1833
		$mt = microtime();
1834
		echo "system_console_configure() being called $mt\n";
1835
	}
1836

    
1837
	if (isset($config['system']['disableconsolemenu'])) {
1838
		touch("{$g['varetc_path']}/disableconsole");
1839
	} else {
1840
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1841
	}
1842
}
1843

    
1844
function system_dmesg_save() {
1845
	global $g;
1846
	if(isset($config['system']['developerspew'])) {
1847
		$mt = microtime();
1848
		echo "system_dmesg_save() being called $mt\n";
1849
	}
1850

    
1851
	$dmesg = "";
1852
	$_gb = exec("/sbin/dmesg", $dmesg);
1853

    
1854
	/* find last copyright line (output from previous boots may be present) */
1855
	$lastcpline = 0;
1856

    
1857
	for ($i = 0; $i < count($dmesg); $i++) {
1858
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1859
			$lastcpline = $i;
1860
	}
1861

    
1862
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1863
	if (!$fd) {
1864
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1865
		return 1;
1866
	}
1867

    
1868
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1869
		fwrite($fd, $dmesg[$i] . "\n");
1870

    
1871
	fclose($fd);
1872
	unset($dmesg);
1873

    
1874
	return 0;
1875
}
1876

    
1877
function system_set_harddisk_standby() {
1878
	global $g, $config;
1879
	if(isset($config['system']['developerspew'])) {
1880
		$mt = microtime();
1881
		echo "system_set_harddisk_standby() being called $mt\n";
1882
	}
1883

    
1884
	if (isset($config['system']['harddiskstandby'])) {
1885
		if ($g['booting']) {
1886
			echo gettext('Setting hard disk standby... ');
1887
		}
1888

    
1889
		$standby = $config['system']['harddiskstandby'];
1890
		// Check for a numeric value
1891
		if (is_numeric($standby)) {
1892
			// Sync the disk(s)
1893
			pfSense_sync();
1894
			if (set_single_sysctl('hw.ata.standby', (int)$standby)) {
1895
				// Reinitialize ATA-drives
1896
				mwexec('/usr/local/sbin/atareinit');
1897
				if ($g['booting']) {
1898
					echo gettext("done.") . "\n";
1899
				}
1900
			} else if ($g['booting']) {
1901
				echo gettext("failed!") . "\n";
1902
			}
1903
		} else if ($g['booting']) {
1904
			echo gettext("failed!") . "\n";
1905
		}
1906
	}
1907
}
1908

    
1909
function system_setup_sysctl() {
1910
	global $config;
1911
	if(isset($config['system']['developerspew'])) {
1912
		$mt = microtime();
1913
		echo "system_setup_sysctl() being called $mt\n";
1914
	}
1915

    
1916
	activate_sysctls();	
1917

    
1918
	if (isset($config['system']['sharednet'])) {
1919
		system_disable_arp_wrong_if();
1920
	}
1921
}
1922

    
1923
function system_disable_arp_wrong_if() {
1924
	global $config;
1925
	if(isset($config['system']['developerspew'])) {
1926
		$mt = microtime();
1927
		echo "system_disable_arp_wrong_if() being called $mt\n";
1928
	}
1929
	set_sysctl(array(
1930
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
1931
		"net.link.ether.inet.log_arp_movements" => "0"
1932
	));
1933
}
1934

    
1935
function system_enable_arp_wrong_if() {
1936
	global $config;
1937
	if(isset($config['system']['developerspew'])) {
1938
		$mt = microtime();
1939
		echo "system_enable_arp_wrong_if() being called $mt\n";
1940
	}
1941
	set_sysctl(array(
1942
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
1943
		"net.link.ether.inet.log_arp_movements" => "1"
1944
	));
1945
}
1946

    
1947
function enable_watchdog() {
1948
	global $config;
1949
	return;
1950
	$install_watchdog = false;
1951
	$supported_watchdogs = array("Geode");
1952
	$file = file_get_contents("/var/log/dmesg.boot");
1953
	foreach($supported_watchdogs as $sd) {
1954
		if(stristr($file, "Geode")) {
1955
			$install_watchdog = true;
1956
		}
1957
	}
1958
	if($install_watchdog == true) {
1959
		if(is_process_running("watchdogd"))
1960
			mwexec("/usr/bin/killall watchdogd", true);
1961
		exec("/usr/sbin/watchdogd");
1962
	}
1963
}
1964

    
1965
function system_check_reset_button() {
1966
	global $g;
1967
	if($g['platform'] != "nanobsd")
1968
		return 0;
1969

    
1970
	$specplatform = system_identify_specific_platform();
1971

    
1972
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1973
		return 0;
1974

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

    
1977
	if ($retval == 99) {
1978
		/* user has pressed reset button for 2 seconds - 
1979
		   reset to factory defaults */
1980
		echo <<<EOD
1981

    
1982
***********************************************************************
1983
* Reset button pressed - resetting configuration to factory defaults. *
1984
* The system will reboot after this completes.                        *
1985
***********************************************************************
1986

    
1987

    
1988
EOD;
1989
		
1990
		reset_factory_defaults();
1991
		system_reboot_sync();
1992
		exit(0);
1993
	}
1994

    
1995
	return 0;
1996
}
1997

    
1998
/* attempt to identify the specific platform (for embedded systems)
1999
   Returns an array with two elements:
2000
	name => platform string (e.g. 'wrap', 'alix' etc.)
2001
	descr => human-readable description (e.g. "PC Engines WRAP")
2002
*/
2003
function system_identify_specific_platform() {
2004
	global $g;
2005
	
2006
	if ($g['platform'] == 'generic-pc')
2007
		return array('name' => 'generic-pc', 'descr' => gettext("Generic PC"));
2008
	
2009
	if ($g['platform'] == 'generic-pc-cdrom')
2010
		return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)"));
2011
	
2012
	/* the rest of the code only deals with 'embedded' platforms */
2013
	if ($g['platform'] != 'nanobsd')
2014
		return array('name' => $g['platform'], 'descr' => $g['platform']);
2015

    
2016
	$dmesg = get_single_sysctl('hw.model');
2017

    
2018
	if (strpos($dmesg, "PC Engines WRAP") !== false)
2019
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
2020
	
2021
	if (strpos($dmesg, "PC Engines ALIX") !== false)
2022
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2023

    
2024
	if (preg_match("/Soekris net45../", $dmesg, $matches))
2025
		return array('name' => 'net45xx', 'descr' => $matches[0]);
2026
	
2027
	if (preg_match("/Soekris net48../", $dmesg, $matches))
2028
		return array('name' => 'net48xx', 'descr' => $matches[0]);
2029
		
2030
	if (preg_match("/Soekris net55../", $dmesg, $matches))
2031
		return array('name' => 'net55xx', 'descr' => $matches[0]);
2032
	
2033
	/* unknown embedded platform */
2034
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
2035
}
2036

    
2037
function system_get_dmesg_boot() {
2038
	global $g;
2039
		
2040
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2041
}
2042

    
2043
function get_possible_listen_ips($include_ipv6_link_local=false) {
2044
	$interfaces = get_configured_interface_with_descr();
2045
	$carplist = get_configured_carp_interface_list();
2046
	$listenips = array();
2047
	foreach ($carplist as $cif => $carpip)
2048
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
2049
	$aliaslist = get_configured_ip_aliases_list();
2050
	foreach ($aliaslist as $aliasip => $aliasif)
2051
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
2052
	foreach ($interfaces as $iface => $ifacename) {
2053
		$tmp["name"]  = $ifacename;
2054
		$tmp["value"] = $iface;
2055
		$listenips[] = $tmp;
2056
		if ($include_ipv6_link_local) {
2057
			$llip = find_interface_ipv6_ll(get_real_interface($iface));
2058
			if (!empty($llip)) {
2059
				$tmp["name"]  = "{$ifacename} IPv6 Link-Local";
2060
				$tmp["value"] = $llip;
2061
				$listenips[] = $tmp;
2062
			}
2063
		}
2064
	}
2065
	$tmp["name"]  = "Localhost";
2066
	$tmp["value"] = "lo0";
2067
	$listenips[] = $tmp;
2068
	return $listenips;
2069
}
2070

    
2071
function get_possible_traffic_source_addresses($include_ipv6_link_local=false) {
2072
	global $config;
2073
	$sourceips = get_possible_listen_ips($include_ipv6_link_local);
2074
	foreach (array('server', 'client') as $mode) {
2075
		if (is_array($config['openvpn']["openvpn-{$mode}"])) {
2076
			foreach ($config['openvpn']["openvpn-{$mode}"] as $id => $setting) {
2077
				if (!isset($setting['disable'])) {
2078
					$vpn = array();
2079
					$vpn['value'] = 'ovpn' . substr($mode, 0, 1) . $setting['vpnid'];
2080
					$vpn['name'] = gettext("OpenVPN") . " ".$mode.": ".htmlspecialchars($setting['description']);
2081
					$sourceips[] = $vpn;
2082
				}
2083
			}
2084
		}
2085
	}
2086
	return $sourceips;
2087
}
2088
?>
(53-53/68)