Project

General

Profile

Download (55.6 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/* $Id$ */
3
/*
4
	system.inc
5
	part of m0n0wall (http://m0n0.ch/wall)
6

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
106
	if ((isset($config['dnsmasq']['enable']) || isset($config['unbound']['enable'])) && !isset($config['system']['dnslocalhost']))
107
		$resolvconf .= "nameserver 127.0.0.1\n";
108

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

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

    
133
	$dnslock = lock('resolvconf', LOCK_EX);
134

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

    
142
	fwrite($fd, $resolvconf);
143
	fclose($fd);
144

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

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

    
173
	unlock($dnslock);
174

    
175
	return 0;
176
}
177

    
178
function get_searchdomains() {
179
	global $config, $g;
180

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

    
197
	return $master_list;
198
}
199

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

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

    
228
	return $master_list;
229
}
230

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

    
238
	$syscfg = $config['system'];
239
	$dnsmasqcfg = $config['dnsmasq'];
240

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

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

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

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

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

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

    
325
	system_dhcpleases_configure();
326

    
327
	return 0;
328
}
329

    
330
function system_dhcpleases_configure() {
331
	global $config, $g;
332
	
333
	if ($g['platform'] == 'jail')
334
		return;
335
	/* Start the monitoring process for dynamic dhcpclients. */
336
	if (isset($config['dnsmasq']['enable']) && isset($config['dnsmasq']['regdhcp'])) {
337
		/* Make sure we do not error out */
338
		mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db");
339
		if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases"))
340
			@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
341
		if (isvalidpid("{$g['varrun_path']}/dhcpleases.pid"))
342
			sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "HUP");
343
		else
344
			mwexec("/usr/local/sbin/dhcpleases -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases -d {$config['system']['domain']} -p {$g['varrun_path']}/dnsmasq.pid -h {$g['varetc_path']}/hosts");
345
	} else {
346
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
347
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
348
	}
349
}
350

    
351
function system_hostname_configure() {
352
	global $config, $g;
353
	if(isset($config['system']['developerspew'])) {
354
		$mt = microtime();
355
		echo "system_hostname_configure() being called $mt\n";
356
	}
357

    
358
	$syscfg = $config['system'];
359

    
360
	/* set hostname */
361
	$status = mwexec("/bin/hostname " .
362
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
363

    
364
    /* Setup host GUID ID.  This is used by ZFS. */
365
	mwexec("/etc/rc.d/hostid start");
366

    
367
	return $status;
368
}
369

    
370
function system_routing_configure($interface = "") {
371
	global $config, $g;
372
	if ($g['platform'] == 'jail')
373
		return;
374
	if(isset($config['system']['developerspew'])) {
375
		$mt = microtime();
376
		echo "system_routing_configure() being called $mt\n";
377
	}
378

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

    
444
	if ($dont_add_route == false ) {
445
		if (!empty($interface) && $interface != $interfacegw)
446
			;
447
		else if (($interfacegw <> "bgpd") && (is_ipaddrv4($gatewayip))) {
448
			log_error("ROUTING: setting default route to $gatewayip");
449
			mwexec("/sbin/route change -inet default " . escapeshellarg($gatewayip));
450
		}
451

    
452
		if (!empty($interface) && $interface != $interfacegwv6)
453
			;
454
		else if (($interfacegwv6 <> "bgpd") && (is_ipaddrv6($gatewayipv6))) {
455
			$ifscope = "";
456
			if (is_linklocal($gatewayipv6))
457
				$ifscope = "%{$defaultifv6}";
458
			log_error("ROUTING: setting IPv6 default route to {$gatewayipv6}{$ifscope}");
459
			mwexec("/sbin/route change -inet6 default " . escapeshellarg($gatewayipv6) ."{$ifscope}");
460
		}
461
	}
462

    
463
	system_staticroutes_configure($interface, false);
464

    
465
	return 0;
466
}
467

    
468
function system_staticroutes_configure($interface = "", $update_dns = false) {
469
	global $config, $g, $aliastable;
470

    
471
	$filterdns_list = array();
472

    
473
	$static_routes = get_staticroutes(false, true);
474
	if (count($static_routes)) {
475
		$gateways_arr = return_gateways_array(false, true);
476

    
477
		foreach ($static_routes as $rtent) {
478
			if (empty($gateways_arr[$rtent['gateway']])) {
479
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
480
				continue;
481
			}
482
			$gateway = $gateways_arr[$rtent['gateway']];
483
			if (!empty($interface) && $interface != $gateway['friendlyiface'])
484
				continue;
485

    
486
			$gatewayip = $gateway['gateway'];
487
			$interfacegw = $gateway['interface'];
488

    
489
			$blackhole = "";
490
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 3)))
491
				$blackhole = "-blackhole";
492

    
493
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network']))
494
				continue;
495

    
496
			$dnscache = array();
497
			if ($update_dns === true) {
498
				if (is_subnet($rtent['network']))
499
					continue;
500
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
501
				if (empty($dnscache))
502
					continue;
503
			}
504

    
505
			if (is_subnet($rtent['network']))
506
				$ips = array($rtent['network']);
507
			else {
508
				if (!isset($rtent['disabled']))
509
					$filterdns_list[] = $rtent['network'];
510
				$ips = add_hostname_to_watch($rtent['network']);
511
			}
512

    
513
			foreach ($dnscache as $ip) {
514
				if (in_array($ip, $ips))
515
					continue;
516
				mwexec("/sbin/route delete " . escapeshellarg($ip), true);
517
			}
518

    
519
			if (isset($rtent['disabled'])) {
520
				/* XXX: This is a bit dangerous in case of routing daemons!? */
521
				foreach ($ips as $ip)
522
					mwexec("/sbin/route delete " . escapeshellarg($ip), true);
523
				continue;
524
			}
525

    
526
			foreach ($ips as $ip) {
527
				if (is_ipaddrv4($ip))
528
					$ip .= "/32";
529
				else if (is_ipaddrv6($ip))
530
					$ip .= "/128";
531

    
532
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
533

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

    
536
				if (is_subnet($ip))
537
					if (is_ipaddr($gatewayip))
538
						mwexec($cmd . escapeshellarg($gatewayip));
539
					else if (!empty($interfacegw))
540
						mwexec($cmd . "-iface " . escapeshellarg($interfacegw));
541
			}
542
		}
543
		unset($gateways_arr);
544
	}
545
	unset($static_routes);
546

    
547
	if ($update_dns === false) {
548
		if (count($filterdns_list)) {
549
			$interval = 60;
550
			$hostnames = "";
551
			array_unique($filterdns_list);
552
			foreach ($filterdns_list as $hostname)
553
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
554
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
555
			unset($hostnames);
556

    
557
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid"))
558
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
559
			else
560
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
561
		} else {
562
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
563
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
564
		}
565
	}
566
	unset($filterdns_list);
567

    
568
	return 0;
569
}
570

    
571
function system_routing_enable() {
572
	global $config, $g;
573
	if(isset($config['system']['developerspew'])) {
574
		$mt = microtime();
575
		echo "system_routing_enable() being called $mt\n";
576
	}
577

    
578
	mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
579
	mwexec("/sbin/sysctl net.inet6.ip6.forwarding=1");
580
	return;
581
}
582

    
583
function system_syslogd_fixup_server($server) {
584
	/* If it's an IPv6 IP alone, encase it in brackets */
585
	if (is_ipaddrv6($server))
586
		return "[$server]";
587
	else
588
		return $server;
589
}
590

    
591
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
592
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
593
	$facility .= " ".
594
	$remote_servers = "";
595
	$pad_to  = 56;
596
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
597
	if($syslogcfg['remoteserver'])
598
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
599
	if($syslogcfg['remoteserver2'])
600
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
601
	if($syslogcfg['remoteserver3'])
602
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
603
	return $remote_servers;
604
}
605

    
606
function system_syslogd_start() {
607
	global $config, $g;
608
	if(isset($config['system']['developerspew'])) {
609
		$mt = microtime();
610
		echo "system_syslogd_start() being called $mt\n";
611
	}
612

    
613
	mwexec("/etc/rc.d/hostid start");
614

    
615
	$syslogcfg = $config['syslog'];
616

    
617
	if ($g['booting'])
618
		echo gettext("Starting syslog...");
619
	else
620
		killbypid("{$g['varrun_path']}/syslog.pid");
621

    
622
	if (is_process_running("syslogd"))
623
		mwexec('/bin/pkill syslogd');
624
	if (is_process_running("fifolog_writer"))
625
		mwexec('/bin/pkill fifolog_writer');
626

    
627
	// Which logging type are we using this week??
628
	if (isset($config['system']['disablesyslogclog'])) {
629
		$log_directive = "";
630
		$log_create_directive = "/usr/bin/touch ";
631
		$log_size = "";
632
	} else if (isset($config['system']['usefifolog'])) {
633
		$log_directive = "|/usr/sbin/fifolog_writer ";
634
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
635
		$log_create_directive = "/usr/sbin/fifolog_create -s ";
636
	} else { // Defaults to CLOG
637
		$log_directive = "%";
638
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
639
		$log_create_directive = "/usr/sbin/clog -i -s ";
640
	}
641
	
642
	if (isset($syslogcfg)) {
643
		$separatelogfacilities = array('ntp','ntpd','ntpdate','racoon','openvpn','pptps','poes','l2tps','relayd','hostapd','dnsmasq','filterdns','unbound','dhcpd','dhcrelay','dhclient','apinger','radvd','routed','olsrd','zebra','ospfd','bgpd','miniupnpd');
644
		$syslogconf = "";
645
		if($config['installedpackages']['package']) {
646
			foreach($config['installedpackages']['package'] as $package) {
647
				if($package['logging']) {
648
					array_push($separatelogfacilities, $package['logging']['facilityname']);
649
					mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
650
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
651
				}
652
			}
653
		}
654
		$facilitylist = implode(',', array_unique($separatelogfacilities));
655
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd,miniupnpd\n";
656
		if (!isset($syslogcfg['disablelocallogging']))
657
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
658

    
659
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
660
		if (!isset($syslogcfg['disablelocallogging'])) 
661
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
662

    
663
		$syslogconf .= "!ppp\n";
664
		if (!isset($syslogcfg['disablelocallogging'])) 
665
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
666

    
667
		$syslogconf .= "!pptps\n";
668
		if (!isset($syslogcfg['disablelocallogging'])) 
669
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/pptps.log\n";
670

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

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

    
679
		$syslogconf .= "!racoon\n";
680
		if (!isset($syslogcfg['disablelocallogging'])) 
681
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ipsec.log\n";
682
		if (isset($syslogcfg['vpn']))
683
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
684

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

    
691
		$syslogconf .= "!apinger\n";
692
		if (!isset($syslogcfg['disablelocallogging']))
693
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/gateways.log\n";
694
		if (isset($syslogcfg['apinger']))
695
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
696

    
697
		$syslogconf .= "!dnsmasq,filterdns,unbound\n";
698
		if (!isset($syslogcfg['disablelocallogging']))
699
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
700
		if (isset($syslogcfg['apinger']))
701
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
702

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

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

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

    
721
		$syslogconf .= "!-{$facilitylist}\n";
722
		if (!isset($syslogcfg['disablelocallogging'])) 
723
			$syslogconf .= <<<EOD
724
local0.*							{$log_directive}{$g['varlog_path']}/filter.log
725
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
726
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
727
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
728
*.notice;kern.debug;lpr.info;mail.crit;daemon.none;		{$log_directive}{$g['varlog_path']}/system.log
729
news.err;local0.none;local3.none;local4.none;			{$log_directive}{$g['varlog_path']}/system.log
730
local7.none							{$log_directive}{$g['varlog_path']}/system.log
731
security.*							{$log_directive}{$g['varlog_path']}/system.log
732
auth.info;authpriv.info;daemon.info				{$log_directive}{$g['varlog_path']}/system.log
733
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
734
*.emerg								*
735

    
736
EOD;
737
		if (isset($syslogcfg['filter']))
738
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local0.*");
739
		if (isset($syslogcfg['vpn']))
740
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
741
		if (isset($syslogcfg['portalauth']))
742
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
743
		if (isset($syslogcfg['dhcp']))
744
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
745
		if (isset($syslogcfg['system'])) {
746
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.notice;kern.debug;lpr.info;mail.crit;");
747
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "news.err;local0.none;local3.none;local7.none");
748
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "security.*");
749
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "auth.info;authpriv.info;daemon.info");
750
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.emerg");
751
		}
752
		if (isset($syslogcfg['logall'])) {
753
			// Make everything mean everything, including facilities excluded above.
754
			$syslogconf .= "!*\n";
755
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
756
		}
757

    
758
		if (isset($syslogcfg['zmqserver'])) {
759
				$syslogconf .= <<<EOD
760
*.*								^{$syslogcfg['zmqserver']}
761

    
762
EOD;
763
		}
764
		/* write syslog.conf */		
765
		if (!@file_put_contents("{$g['varetc_path']}/syslog.conf", $syslogconf)) {
766
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
767
			unset($syslogconf);
768
			return 1;
769
		}
770
		unset($syslogconf);
771

    
772
		// Ensure that the log directory exists
773
		if (!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
774
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
775

    
776
		$sourceip = "";
777
		if (!empty($syslogcfg['sourceip'])) {
778
			if ($syslogcfg['ipproto'] == "ipv6") {
779
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
780
				if (!is_ipaddr($ifaddr))
781
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
782
			} else {
783
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
784
				if (!is_ipaddr($ifaddr))
785
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
786
			}
787
			if (is_ipaddr($ifaddr)) {
788
				$sourceip = "-b {$ifaddr}";
789
			}
790
		}
791

    
792
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c -l {$g['dhcpd_chroot_path']}/var/run/log -f {$g['varetc_path']}/syslog.conf {$sourceip}");
793

    
794
	} else {
795
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c -l {$g['dhcpd_chroot_path']}/var/run/log");
796
	}
797

    
798
	if ($g['booting'])
799
		echo gettext("done.") . "\n";
800

    
801
	return $retval;
802
}
803

    
804
function system_pccard_start() {
805
	global $config, $g;
806
	if(isset($config['system']['developerspew'])) {
807
		$mt = microtime();
808
		echo "system_pccard_start() being called $mt\n";
809
	}
810

    
811
	if ($g['booting'])
812
		echo gettext("Initializing PCMCIA...");
813

    
814
	/* kill any running pccardd */
815
	killbypid("{$g['varrun_path']}/pccardd.pid");
816

    
817
	/* fire up pccardd */
818
	$res = mwexec("/usr/sbin/pccardd -z -f {$g['etc_path']}/pccard.conf");
819

    
820
	if ($g['booting']) {
821
		if ($res == 0)
822
			echo gettext("done.") . "\n";
823
		else
824
			echo gettext("failed!") . "\n";
825
	}
826

    
827
	return $res;
828
}
829

    
830

    
831
function system_webgui_start() {
832
	global $config, $g;
833

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

    
837
	chdir($g['www_path']);
838

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

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

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

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

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

    
893
	sleep(1);
894

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

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

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

    
907
	return $res;
908
}
909

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

    
921
	global $config, $g;
922

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

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

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

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

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

    
959
	$memory = get_memory();
960
	$realmem = $memory[1];
961

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

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

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

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

    
996

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

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

    
1031
EOD;
1032
	}
1033

    
1034

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

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

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

    
1053
server.max-keep-alive-requests = 15
1054
server.max-keep-alive-idle = 30
1055

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

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

    
1064
{$lighty_use_syslog}
1065

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

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

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

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

    
1133

    
1134
######### Options that are good to be but not neccesary to be changed #######
1135

    
1136
## bind to port (default: 80)
1137

    
1138
EOD;
1139

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

    
1154

    
1155
	$lighty_config .= <<<EOD
1156

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

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

    
1164
## virtual directory listings
1165
server.dir-listing         = "disable"
1166

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

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

    
1177
{$server_upload_dirs}
1178

    
1179
{$server_max_request_size}
1180

    
1181
{$fastcgi_config}
1182

    
1183
{$cgi_config}
1184

    
1185
{$captive_portal_mod_evasive}
1186

    
1187
expire.url = (
1188
				"" => "access 50 hours",	
1189
        )
1190

    
1191
EOD;
1192

    
1193
	$cert = str_replace("\r", "", $cert);
1194
	$key = str_replace("\r", "", $key);
1195
	$ca = str_replace("\r", "", $ca);
1196

    
1197
	$cert = str_replace("\n\n", "\n", $cert);
1198
	$key = str_replace("\n\n", "\n", $key);
1199
	$ca = str_replace("\n\n", "\n", $ca);
1200

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

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

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

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

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

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

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

    
1276
	return 0;
1277

    
1278
}
1279

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

    
1287
	$syscfg = $config['system'];
1288

    
1289
	if ($g['booting'])
1290
		echo gettext("Setting timezone...");
1291

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

    
1307
	conf_mount_rw();
1308

    
1309
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1310
		escapeshellarg($timezone) . " > /etc/localtime");
1311

    
1312
	mwexec("sync");
1313
	conf_mount_ro();
1314

    
1315
	if ($g['booting'])
1316
		echo gettext("done.") . "\n";
1317
}
1318

    
1319
function system_ntp_setup_gps($serialport) {
1320
	$gps_device = '/dev/gps0';
1321
	$serialport = '/dev/'.$serialport;
1322

    
1323
	if (!file_exists($serialport))
1324
		return false;
1325

    
1326
	conf_mount_rw();
1327
	// Create symlink that ntpd requires
1328
	unlink_if_exists($gps_device);
1329
	symlink($serialport, $gps_device);
1330

    
1331
	/* Send the following to the GPS port to initialize the GPS */
1332
	$gps_init = <<<EOF
1333
\$PUBX,40,GSV,0,0,0,0*59
1334
\$PUBX,40,GLL,0,0,0,0*5C
1335
\$PUBX,40,ZDA,0,0,0,0*44
1336
\$PUBX,40,VTG,0,0,0,0*5E
1337
\$PUBX,40,GSV,0,0,0,0*59
1338
\$PUBX,40,GSA,0,0,0,0*4E
1339
\$PUBX,40,GGA,0,0,0,0
1340
\$PUBX,40,TXT,0,0,0,0
1341
\$PUBX,40,RMC,0,0,0,0*46
1342
\$PUBX,41,1,0007,0003,4800,0
1343
\$PUBX,40,ZDA,1,1,1,1
1344
EOF;
1345
	file_put_contents("/tmp/gps.init", $gps_init);
1346
	`cat /tmp/gps.init > $serialport`;
1347

    
1348
	/* Add /etc/remote entry in case we need to read from the GPS with tip */
1349
	if (intval(`grep -c '^gps0' /etc/remote`) == 0)
1350
		`echo "gps0:dv={$serialport}:br#4800:pa=none:" >> /etc/remote`;
1351

    
1352
	conf_mount_ro();
1353

    
1354
	return true;
1355
}
1356

    
1357
function system_ntp_configure($start_ntpd=true) {
1358
	global $config, $g;
1359
	$driftfile = "/var/db/ntpd.drift";
1360
	$statsdir = "/var/log/ntp";
1361
	$gps_device = '/dev/gps0';
1362

    
1363
	if ($g['platform'] == 'jail')
1364
		return;
1365

    
1366
	safe_mkdir($statsdir);
1367

    
1368
	$ntpcfg = "# \n";
1369
	$ntpcfg .= "# pfSense ntp configuration file \n";
1370
	$ntpcfg .= "# \n\n";
1371
	$ntpcfg .= "tinker panic 0 \n";
1372

    
1373
	if (!empty($config['ntpd']['gpsport'])
1374
		&& file_exists('/dev/'.$config['ntpd']['gpsport'])
1375
		&& system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1376
		$ntpcfg .= "# GPS Setup\n";
1377
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1378
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1379
		// Fall back to local clock if GPS is out of sync?
1380
		$ntpcfg .= "server 127.127.1.0\n";
1381
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1382
	}
1383

    
1384
	$ntpcfg .= "\n\n# Upstream Servers\n";
1385
	/* foreach through servers and write out to ntpd.conf */
1386
	foreach (explode(' ', $config['system']['timeservers']) as $ts)
1387
		$ntpcfg .= "server {$ts} iburst maxpoll 9\n";
1388

    
1389
	$ntpcfg .= "disable monitor\n";
1390
	$ntpcfg .= "enable stats\n";
1391
	$ntpcfg .= "statistics clockstats\n";
1392
	$ntpcfg .= "statsdir {$statsdir}\n";
1393
	$ntpcfg .= "logconfig =syncall +clockall\n";
1394
	$ntpcfg .= "driftfile {$driftfile}\n";
1395
	$ntpcfg .= "restrict default kod nomodify notrap nopeer\n";
1396
	$ntpcfg .= "restrict -6 default kod nomodify notrap nopeer\n";
1397

    
1398
	if (empty($config['ntpd']['interface']))
1399
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface']))
1400
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1401
		else
1402
			$interfaces = array();
1403
	else
1404
		$interfaces = explode(",", $config['ntpd']['interface']);
1405

    
1406
	if (is_array($interfaces) && count($interfaces)) {
1407
		$ntpcfg .= "interface ignore all\n";
1408
		foreach ($interfaces as $interface) {
1409
			if (!is_ipaddr($interface)) {
1410
				$interface = get_real_interface($interface);
1411
			}
1412
			$ntpcfg .= "interface listen {$interface}\n";
1413
		}
1414
	}
1415

    
1416
	/* open configuration for wrting or bail */
1417
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
1418
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1419
		return;
1420
	}
1421

    
1422
	/* At bootup we just want to write out the config. */
1423
	if (!$start_ntpd)
1424
		return;
1425

    
1426
	/* if ntpd is running, kill it */
1427
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1428
		killbypid("{$g['varrun_path']}/ntpd.pid");
1429
	}
1430
	@unlink("{$g['varrun_path']}/ntpd.pid");
1431

    
1432
	/* if /var/empty does not exist, create it */
1433
	if(!is_dir("/var/empty"))
1434
		mkdir("/var/empty", 0775, true);
1435

    
1436
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1437
	mwexec("/usr/local/sbin/ntpd -g -c {$g['varetc_path']}/ntpd.conf -p {$g['varrun_path']}/ntpd.pid", false, true);
1438
	
1439
	// Note that we are starting up
1440
	log_error("NTPD is starting up.");
1441
	return;
1442
}
1443

    
1444
function sync_system_time() {
1445
	global $config, $g;
1446

    
1447
	if ($g['booting'])
1448
		echo gettext("Syncing system time before startup...");
1449

    
1450
	/* foreach through servers and write out to ntpd.conf */
1451
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1452
		mwexec("/usr/local/sbin/ntpdate -s $ts");
1453
	}
1454
	
1455
	if ($g['booting'])
1456
		echo gettext("done.") . "\n";
1457
	
1458
}
1459

    
1460
function system_halt() {
1461
	global $g;
1462

    
1463
	system_reboot_cleanup();
1464

    
1465
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1466
}
1467

    
1468
function system_reboot() {
1469
	global $g;
1470

    
1471
	system_reboot_cleanup();
1472

    
1473
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1474
}
1475

    
1476
function system_reboot_sync() {
1477
	global $g;
1478

    
1479
	system_reboot_cleanup();
1480

    
1481
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1482
}
1483

    
1484
function system_reboot_cleanup() {
1485
	global $config, $cpzone;
1486

    
1487
	mwexec("/usr/local/bin/beep.sh stop");
1488
	require_once("captiveportal.inc");
1489
	if (is_array($config['captiveportal'])) {
1490
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
1491
			captiveportal_radius_stop_all();
1492
			captiveportal_send_server_accounting(true);
1493
		}
1494
	}
1495
	require_once("voucher.inc");
1496
	voucher_save_db_to_config();
1497
	require_once("pkg-utils.inc");
1498
	stop_packages();
1499
}
1500

    
1501
function system_do_shell_commands($early = 0) {
1502
	global $config, $g;
1503
	if(isset($config['system']['developerspew'])) {
1504
		$mt = microtime();
1505
		echo "system_do_shell_commands() being called $mt\n";
1506
	}
1507

    
1508
	if ($early)
1509
		$cmdn = "earlyshellcmd";
1510
	else
1511
		$cmdn = "shellcmd";
1512

    
1513
	if (is_array($config['system'][$cmdn])) {
1514

    
1515
		/* *cmd is an array, loop through */
1516
		foreach ($config['system'][$cmdn] as $cmd) {
1517
			exec($cmd);
1518
		}
1519

    
1520
	} elseif($config['system'][$cmdn] <> "") {
1521

    
1522
		/* execute single item */
1523
		exec($config['system'][$cmdn]);
1524

    
1525
	}
1526
}
1527

    
1528
function system_console_configure() {
1529
	global $config, $g;
1530
	if(isset($config['system']['developerspew'])) {
1531
		$mt = microtime();
1532
		echo "system_console_configure() being called $mt\n";
1533
	}
1534

    
1535
	if (isset($config['system']['disableconsolemenu'])) {
1536
		touch("{$g['varetc_path']}/disableconsole");
1537
	} else {
1538
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1539
	}
1540
}
1541

    
1542
function system_dmesg_save() {
1543
	global $g;
1544
	if(isset($config['system']['developerspew'])) {
1545
		$mt = microtime();
1546
		echo "system_dmesg_save() being called $mt\n";
1547
	}
1548

    
1549
	$dmesg = "";
1550
	exec("/sbin/dmesg", $dmesg);
1551

    
1552
	/* find last copyright line (output from previous boots may be present) */
1553
	$lastcpline = 0;
1554

    
1555
	for ($i = 0; $i < count($dmesg); $i++) {
1556
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1557
			$lastcpline = $i;
1558
	}
1559

    
1560
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1561
	if (!$fd) {
1562
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1563
		return 1;
1564
	}
1565

    
1566
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1567
		fwrite($fd, $dmesg[$i] . "\n");
1568

    
1569
	fclose($fd);
1570

    
1571
	return 0;
1572
}
1573

    
1574
function system_set_harddisk_standby() {
1575
	global $g, $config;
1576
	if(isset($config['system']['developerspew'])) {
1577
		$mt = microtime();
1578
		echo "system_set_harddisk_standby() being called $mt\n";
1579
	}
1580

    
1581
	if (isset($config['system']['harddiskstandby'])) {
1582
		if ($g['booting']) {
1583
			echo gettext('Setting hard disk standby... ');
1584
		}
1585

    
1586
		$standby = $config['system']['harddiskstandby'];
1587
		// Check for a numeric value
1588
		if (is_numeric($standby)) {
1589
			// Sync the disk(s)
1590
			pfSense_sync();
1591
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1592
				// Reinitialize ATA-drives
1593
				mwexec('/usr/local/sbin/atareinit');
1594
				if ($g['booting']) {
1595
					echo gettext("done.") . "\n";
1596
				}
1597
			} else if ($g['booting']) {
1598
				echo gettext("failed!") . "\n";
1599
			}
1600
		} else if ($g['booting']) {
1601
			echo gettext("failed!") . "\n";
1602
		}
1603
	}
1604
}
1605

    
1606
function system_setup_sysctl() {
1607
	global $config;
1608
	if(isset($config['system']['developerspew'])) {
1609
		$mt = microtime();
1610
		echo "system_setup_sysctl() being called $mt\n";
1611
	}
1612

    
1613
	activate_sysctls();	
1614

    
1615
	if (isset($config['system']['sharednet'])) {
1616
		system_disable_arp_wrong_if();
1617
	}
1618
}
1619

    
1620
function system_disable_arp_wrong_if() {
1621
	global $config;
1622
	if(isset($config['system']['developerspew'])) {
1623
		$mt = microtime();
1624
		echo "system_disable_arp_wrong_if() being called $mt\n";
1625
	}
1626
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1627
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1628
}
1629

    
1630
function system_enable_arp_wrong_if() {
1631
	global $config;
1632
	if(isset($config['system']['developerspew'])) {
1633
		$mt = microtime();
1634
		echo "system_enable_arp_wrong_if() being called $mt\n";
1635
	}
1636
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1637
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1638
}
1639

    
1640
function enable_watchdog() {
1641
	global $config;
1642
	return;
1643
	$install_watchdog = false;
1644
	$supported_watchdogs = array("Geode");
1645
	$file = file_get_contents("/var/log/dmesg.boot");
1646
	foreach($supported_watchdogs as $sd) {
1647
		if(stristr($file, "Geode")) {
1648
			$install_watchdog = true;
1649
		}
1650
	}
1651
	if($install_watchdog == true) {
1652
		if(is_process_running("watchdogd"))
1653
			mwexec("/usr/bin/killall watchdogd", true);
1654
		exec("/usr/sbin/watchdogd");
1655
	}
1656
}
1657

    
1658
function system_check_reset_button() {
1659
	global $g;
1660
	if($g['platform'] != "nanobsd")
1661
		return 0;
1662

    
1663
	$specplatform = system_identify_specific_platform();
1664

    
1665
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1666
		return 0;
1667

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

    
1670
	if ($retval == 99) {
1671
		/* user has pressed reset button for 2 seconds - 
1672
		   reset to factory defaults */
1673
		echo <<<EOD
1674

    
1675
***********************************************************************
1676
* Reset button pressed - resetting configuration to factory defaults. *
1677
* The system will reboot after this completes.                        *
1678
***********************************************************************
1679

    
1680

    
1681
EOD;
1682
		
1683
		reset_factory_defaults();
1684
		system_reboot_sync();
1685
		exit(0);
1686
	}
1687

    
1688
	return 0;
1689
}
1690

    
1691
/* attempt to identify the specific platform (for embedded systems)
1692
   Returns an array with two elements:
1693
	name => platform string (e.g. 'wrap', 'alix' etc.)
1694
	descr => human-readable description (e.g. "PC Engines WRAP")
1695
*/
1696
function system_identify_specific_platform() {
1697
	global $g;
1698
	
1699
	if ($g['platform'] == 'generic-pc')
1700
		return array('name' => 'generic-pc', 'descr' => gettext("Generic PC"));
1701
	
1702
	if ($g['platform'] == 'generic-pc-cdrom')
1703
		return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)"));
1704
	
1705
	/* the rest of the code only deals with 'embedded' platforms */
1706
	if ($g['platform'] != 'nanobsd')
1707
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1708
	
1709
	$dmesg = system_get_dmesg_boot();
1710
	
1711
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1712
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
1713
	
1714
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1715
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
1716

    
1717
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1718
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1719
	
1720
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1721
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1722
		
1723
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1724
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1725
	
1726
	/* unknown embedded platform */
1727
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
1728
}
1729

    
1730
function system_get_dmesg_boot() {
1731
	global $g;
1732
		
1733
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1734
}
1735

    
1736
function get_possible_listen_ips($include_ipv6_link_local=false) {
1737
	$interfaces = get_configured_interface_with_descr();
1738
	$carplist = get_configured_carp_interface_list();
1739
	$listenips = array();
1740
	foreach ($carplist as $cif => $carpip)
1741
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1742
	$aliaslist = get_configured_ip_aliases_list();
1743
	foreach ($aliaslist as $aliasip => $aliasif)
1744
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1745
	foreach ($interfaces as $iface => $ifacename) {
1746
		$tmp["name"]  = $ifacename;
1747
		$tmp["value"] = $iface;
1748
		$listenips[] = $tmp;
1749
		if ($include_ipv6_link_local) {
1750
			$llip = find_interface_ipv6_ll(get_real_interface($iface));
1751
			if (!empty($llip)) {
1752
				$tmp["name"]  = "{$ifacename} IPv6 Link-Local";
1753
				$tmp["value"] = $llip;
1754
				$listenips[] = $tmp;
1755
			}
1756
		}
1757
	}
1758
	$tmp["name"]  = "Localhost";
1759
	$tmp["value"] = "lo0";
1760
	$listenips[] = $tmp;
1761
	return $listenips;
1762
}
1763

    
1764
function get_possible_traffic_source_addresses($include_ipv6_link_local=false) {
1765
	global $config;
1766
	$sourceips = get_possible_listen_ips($include_ipv6_link_local);
1767
	foreach (array('server', 'client') as $mode) {
1768
		if (is_array($config['openvpn']["openvpn-{$mode}"])) {
1769
			foreach ($config['openvpn']["openvpn-{$mode}"] as $id => $setting) {
1770
				if (!isset($setting['disable'])) {
1771
					$vpn = array();
1772
					$vpn['value'] = 'ovpn' . substr($mode, 0, 1) . $setting['vpnid'];
1773
					$vpn['name'] = gettext("OpenVPN") . " ".$mode.": ".htmlspecialchars($setting['description']);
1774
					$sourceips[] = $vpn;
1775
				}
1776
			}
1777
		}
1778
	}
1779
	return $sourceips;
1780
}
1781
?>
(52-52/67)