Projet

Général

Profil

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

univnautes / etc / inc / system.inc @ 505cddae

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/sbin/ntpdate
37
	pfSense_BUILDER_BINARIES:	/usr/bin/nohup	/sbin/dmesg	/usr/local/sbin/atareinit	/sbin/kldload
38
	pfSense_MODULE:	utils
39
*/
40

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
128
	$dnslock = lock('resolvconf', LOCK_EX);
129

    
130
	$fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
131
	if (!$fd) {
132
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
133
		unlock($dnslock);
134
		return 1;
135
	}
136

    
137
	fwrite($fd, $resolvconf);
138
	fclose($fd);
139

    
140
	if (!$g['booting']) {
141
		/* restart dhcpd (nameservers may have changed) */
142
		if (!$dynupdate)
143
			services_dhcpd_configure();
144
	}
145

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

    
168
	unlock($dnslock);
169

    
170
	return 0;
171
}
172

    
173
function get_searchdomains() {
174
	global $config, $g;
175

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

    
192
	return $master_list;
193
}
194

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

    
213
	// Read in any extra nameservers
214
	if(file_exists("/var/etc/nameservers.conf")) {
215
		$dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
216
		if(is_array($dns_s)) {
217
			foreach($dns_s as $dns)
218
				if (is_ipaddr($dns))
219
					$master_list[] = $dns;
220
		}
221
	}
222

    
223
	return $master_list;
224
}
225

    
226
function system_hosts_generate() {
227
	global $config, $g;
228
	if(isset($config['system']['developerspew'])) {
229
		$mt = microtime();
230
		echo "system_hosts_generate() being called $mt\n";
231
	}
232

    
233
	$syscfg = $config['system'];
234
	$dnsmasqcfg = $config['dnsmasq'];
235

    
236
	$hosts = "127.0.0.1	localhost localhost.{$syscfg['domain']}\n";
237
	$lhosts = "";
238
	$dhosts = "";
239

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

    
257
	if (isset($dnsmasqcfg['enable'])) {
258
		if (!is_array($dnsmasqcfg['hosts']))
259
			$dnsmasqcfg['hosts'] = array();
260

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

    
298
		if (isset($dnsmasqcfg['dhcpfirst']))
299
			$hosts .= $dhosts . $lhosts;
300
		else
301
			$hosts .= $lhosts . $dhosts;
302
	}
303

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

    
320
	system_dhcpleases_configure();
321

    
322
	return 0;
323
}
324

    
325
function system_dhcpleases_configure() {
326
	global $config, $g;
327
	
328
	if ($g['platform'] == 'jail')
329
		return;
330
	/* Start the monitoring process for dynamic dhcpclients. */
331
	if (isset($config['dnsmasq']['enable']) && isset($config['dnsmasq']['regdhcp'])) {
332
		/* Make sure we do not error out */
333
		mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db");
334
		if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases"))
335
			@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
336
		if (isvalidpid("{$g['varrun_path']}/dhcpleases.pid"))
337
			sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "HUP");
338
		else {
339
			/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
340
			if (is_process_running("dhcpleases"))
341
				mwexec('/bin/pkill dhcpleases');
342
			@unlink("{$g['varrun_path']}/dhcpleases.pid");
343
			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");
344
		}
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'] == "dynamic")) {
404
					if ($gateway['gateway'] == "dynamic")
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']);
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");
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 (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 (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
	$static_routes = get_staticroutes();
464
	if (count($static_routes)) {
465
		$gateways_arr = return_gateways_array(false, true);
466

    
467
		foreach ($static_routes as $rtent) {
468
			$gatewayip = "";
469
			if (empty($gateways_arr[$rtent['gateway']])) {
470
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
471
				continue;
472
			}
473
			$gateway = $gateways_arr[$rtent['gateway']];
474
			if (!empty($interface) && $interface != $gateway['friendlyiface'])
475
				continue;
476

    
477
			/* XXX: This is a bit dangerous in case of routing daemons!? */
478
			if(isset($rtent['disabled'])) {
479
				mwexec("/sbin/route delete " . escapeshellarg($rtent['network']), true);
480
				continue;
481
			}
482

    
483
			$gatewayip = $gateway['gateway'];
484
			$interfacegw = $gateway['interface'];
485

    
486
			$blackhole = "";
487
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 3)))
488
				$blackhole = "-blackhole";
489

    
490
			if (is_subnetv6($rtent['network'])) {
491
				if (is_ipaddrv6($gatewayip))
492
					mwexec("/sbin/route change -inet6 {$blackhole} " . escapeshellarg($rtent['network']) .
493
						" " . escapeshellarg($gatewayip));
494
				else if (!empty($interfacegw))
495
					mwexec("/sbin/route change -inet6 {$blackhole} " . escapeshellarg($rtent['network']) .
496
						" -iface " . escapeshellarg($interfacegw));
497
			 } else if (is_subnetv4($rtent['network'])) {
498
				if (is_ipaddrv4($gatewayip))
499
					mwexec("/sbin/route change -inet {$blackhole} " . escapeshellarg($rtent['network']) .
500
						" " . escapeshellarg($gatewayip));
501
				else if (!empty($interfacegw))
502
					mwexec("/sbin/route change -inet {$blackhole} " . escapeshellarg($rtent['network']) .
503
						" -iface " . escapeshellarg($interfacegw));
504
			}
505
		}
506
		unset($gateways_arr);
507
	}
508
	unset($static_routes);
509

    
510
	return 0;
511
}
512

    
513
function system_routing_enable() {
514
	global $config, $g;
515
	if(isset($config['system']['developerspew'])) {
516
		$mt = microtime();
517
		echo "system_routing_enable() being called $mt\n";
518
	}
519

    
520
	mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
521
	mwexec("/sbin/sysctl net.inet6.ip6.forwarding=1");
522
	return;
523
}
524

    
525
function system_syslogd_fixup_server($server) {
526
	/* If it's an IPv6 IP alone, encase it in brackets */
527
	if (is_ipaddrv6($server))
528
		return "[$server]";
529
	else
530
		return $server;
531
}
532

    
533
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
534
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
535
	$facility .= " ".
536
	$remote_servers = "";
537
	$pad_to  = 56;
538
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
539
	if($syslogcfg['remoteserver'])
540
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
541
	if($syslogcfg['remoteserver2'])
542
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
543
	if($syslogcfg['remoteserver3'])
544
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
545
	return $remote_servers;
546
}
547

    
548
function system_syslogd_start() {
549
	global $config, $g;
550
	if(isset($config['system']['developerspew'])) {
551
		$mt = microtime();
552
		echo "system_syslogd_start() being called $mt\n";
553
	}
554

    
555
	mwexec("/etc/rc.d/hostid start");
556

    
557
	$syslogcfg = $config['syslog'];
558

    
559
	if ($g['booting'])
560
		echo gettext("Starting syslog...");
561
	else
562
		killbypid("{$g['varrun_path']}/syslog.pid");
563

    
564
	if (is_process_running("syslogd"))
565
		mwexec('/bin/pkill syslogd');
566
	if (is_process_running("fifolog_writer"))
567
		mwexec('/bin/pkill fifolog_writer');
568

    
569
	// Which logging type are we using this week??
570
	if (isset($config['system']['disablesyslogclog'])) {
571
		$log_directive = "";
572
		$log_create_directive = "/usr/bin/touch ";
573
		$log_size = "";
574
	} else if (isset($config['system']['usefifolog'])) {
575
		$log_directive = "|/usr/sbin/fifolog_writer ";
576
		$log_size = "10240";
577
		$log_create_directive = "/usr/sbin/fifolog_create -s ";
578
	} else { // Defaults to CLOG
579
		$log_directive = "%";
580
		$log_size = "10240";
581
		$log_create_directive = "/usr/local/sbin/clog -i -s ";
582
	}
583
	
584
	if (isset($syslogcfg)) {
585
		$separatelogfacilities = array('ntp','ntpd','ntpdate','racoon','openvpn','pptps','poes','l2tps','relayd','hostapd','dnsmasq','filterdns','unbound','dhcpd','dhcrelay','dhclient','dhcp6c','apinger','radvd','routed','olsrd','zebra','ospfd','bgpd','miniupnpd');
586
		$syslogconf = "";
587
		if($config['installedpackages']['package']) {
588
			foreach($config['installedpackages']['package'] as $package) {
589
				if($package['logging']) {
590
					array_push($separatelogfacilities, $package['logging']['facilityname']);
591
					mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
592
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
593
				}
594
			}
595
		}
596
		$facilitylist = implode(',', array_unique($separatelogfacilities));
597
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd,miniupnpd\n";
598
		if (!isset($syslogcfg['disablelocallogging']))
599
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
600

    
601
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
602
		if (!isset($syslogcfg['disablelocallogging'])) 
603
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
604

    
605
		$syslogconf .= "!ppp\n";
606
		if (!isset($syslogcfg['disablelocallogging'])) 
607
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
608

    
609
		$syslogconf .= "!pptps\n";
610
		if (!isset($syslogcfg['disablelocallogging'])) 
611
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/pptps.log\n";
612

    
613
		$syslogconf .= "!poes\n";
614
		if (!isset($syslogcfg['disablelocallogging'])) 
615
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
616

    
617
		$syslogconf .= "!l2tps\n";
618
		if (!isset($syslogcfg['disablelocallogging'])) 
619
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/l2tps.log\n";
620

    
621
		$syslogconf .= "!racoon\n";
622
		if (!isset($syslogcfg['disablelocallogging'])) 
623
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ipsec.log\n";
624
		if (isset($syslogcfg['vpn']))
625
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
626

    
627
		$syslogconf .= "!openvpn\n";
628
		if (!isset($syslogcfg['disablelocallogging'])) 
629
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/openvpn.log\n";
630
		if (isset($syslogcfg['vpn']))
631
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
632

    
633
		$syslogconf .= "!apinger\n";
634
		if (!isset($syslogcfg['disablelocallogging']))
635
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/gateways.log\n";
636
		if (isset($syslogcfg['apinger']))
637
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
638

    
639
		$syslogconf .= "!dnsmasq,filterdns,unbound\n";
640
		if (!isset($syslogcfg['disablelocallogging']))
641
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
642

    
643
		$syslogconf .= "!dhcpd,dhcrelay,dhclient,dhcp6c\n";
644
		if (!isset($syslogcfg['disablelocallogging']))
645
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/dhcpd.log\n";
646
		if (isset($syslogcfg['dhcp']))
647
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
648

    
649
		$syslogconf .= "!relayd\n";
650
		if (!isset($syslogcfg['disablelocallogging']))
651
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/relayd.log\n";
652
		if (isset($syslogcfg['relayd']))
653
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
654

    
655
		$syslogconf .= "!hostapd\n";
656
		if (!isset($syslogcfg['disablelocallogging']))
657
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
658
		if (isset($syslogcfg['hostapd']))
659
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
660

    
661
		$syslogconf .= "!-{$facilitylist}\n";
662
		if (!isset($syslogcfg['disablelocallogging'])) 
663
			$syslogconf .= <<<EOD
664
local0.*							{$log_directive}{$g['varlog_path']}/filter.log
665
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
666
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
667
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
668
*.notice;kern.debug;lpr.info;mail.crit;daemon.none;		{$log_directive}{$g['varlog_path']}/system.log
669
news.err;local0.none;local3.none;local4.none;			{$log_directive}{$g['varlog_path']}/system.log
670
local7.none							{$log_directive}{$g['varlog_path']}/system.log
671
security.*							{$log_directive}{$g['varlog_path']}/system.log
672
auth.info;authpriv.info;daemon.info				{$log_directive}{$g['varlog_path']}/system.log
673
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
674
*.emerg								*
675

    
676
EOD;
677
		if (isset($syslogcfg['filter']))
678
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local0.*");
679
		if (isset($syslogcfg['vpn']))
680
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
681
		if (isset($syslogcfg['portalauth']))
682
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
683
		if (isset($syslogcfg['dhcp']))
684
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
685
		if (isset($syslogcfg['system'])) {
686
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.notice;kern.debug;lpr.info;mail.crit;");
687
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "news.err;local0.none;local3.none;local7.none");
688
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "security.*");
689
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "auth.info;authpriv.info;daemon.info");
690
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.emerg");
691
		}
692
		if (isset($syslogcfg['logall'])) {
693
			// Make everything mean everything, including facilities excluded above.
694
			$syslogconf .= "!*\n";
695
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
696
		}
697

    
698
		if (isset($syslogcfg['zmqserver'])) {
699
				$syslogconf .= <<<EOD
700
*.*								^{$syslogcfg['zmqserver']}
701

    
702
EOD;
703
		}
704
		/* write syslog.conf */		
705
		if (!@file_put_contents("{$g['varetc_path']}/syslog.conf", $syslogconf)) {
706
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
707
			unset($syslogconf);
708
			return 1;
709
		}
710
		unset($syslogconf);
711

    
712
		// Ensure that the log directory exists
713
		if (!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
714
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
715

    
716
		$sourceip = "";
717
		if (!empty($syslogcfg['sourceip'])) {
718
			if ($syslogcfg['ipproto'] == "ipv6") {
719
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
720
				if (!is_ipaddr($ifaddr))
721
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
722
			} else {
723
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
724
				if (!is_ipaddr($ifaddr))
725
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
726
			}
727
			if (is_ipaddr($ifaddr)) {
728
				$sourceip = "-b {$ifaddr}";
729
			}
730
		}
731

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

    
734
	} else {
735
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c -l {$g['dhcpd_chroot_path']}/var/run/log");
736
	}
737

    
738
	if ($g['booting'])
739
		echo gettext("done.") . "\n";
740

    
741
	return $retval;
742
}
743

    
744
function system_pccard_start() {
745
	global $config, $g;
746
	if(isset($config['system']['developerspew'])) {
747
		$mt = microtime();
748
		echo "system_pccard_start() being called $mt\n";
749
	}
750

    
751
	if ($g['booting'])
752
		echo gettext("Initializing PCMCIA...");
753

    
754
	/* kill any running pccardd */
755
	killbypid("{$g['varrun_path']}/pccardd.pid");
756

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

    
760
	if ($g['booting']) {
761
		if ($res == 0)
762
			echo gettext("done.") . "\n";
763
		else
764
			echo gettext("failed!") . "\n";
765
	}
766

    
767
	return $res;
768
}
769

    
770

    
771
function system_webgui_start() {
772
	global $config, $g;
773

    
774
	if ($g['booting'])
775
		echo gettext("Starting webConfigurator...");
776

    
777
	chdir($g['www_path']);
778

    
779
	/* defaults */
780
	$portarg = "80";
781
	$crt = "";
782
	$key = "";
783
	$ca = "";
784

    
785
	/* non-standard port? */
786
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
787
		$portarg = "{$config['system']['webgui']['port']}";
788

    
789
	if ($config['system']['webgui']['protocol'] == "https") {
790
		// Ensure that we have a webConfigurator CERT
791
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
792
		if(!is_array($cert) && !$cert['crt'] && !$cert['prv']) {
793
			if (!is_array($config['ca']))
794
				$config['ca'] = array();
795
			$a_ca =& $config['ca'];
796
			if (!is_array($config['cert']))
797
				$config['cert'] = array();
798
			$a_cert =& $config['cert'];
799
			log_error("Creating SSL Certificate for this host");
800
			$cert = array();
801
			$cert['refid'] = uniqid();
802
			$cert['descr'] = gettext("webConfigurator default");
803
			mwexec("/usr/local/bin/openssl genrsa 1024 > {$g['tmp_path']}/ssl.key");
804
			mwexec("/usr/local/bin/openssl req -new -x509 -nodes -sha256 -days 2000 -key {$g['tmp_path']}/ssl.key > {$g['tmp_path']}/ssl.crt");
805
			$crt = file_get_contents("{$g['tmp_path']}/ssl.crt");
806
			$key = file_get_contents("{$g['tmp_path']}/ssl.key");
807
			unlink("{$g['tmp_path']}/ssl.key");
808
			unlink("{$g['tmp_path']}/ssl.crt");
809
			cert_import($cert, $crt, $key);
810
			$a_cert[] = $cert;
811
			$config['system']['webgui']['ssl-certref'] = $cert['refid'];
812
			write_config(gettext("Importing HTTPS certificate"));
813
			if(!$config['system']['webgui']['port'])
814
				$portarg = "443";
815
			$ca = ca_chain($cert);
816
		} else {
817
			$crt = base64_decode($cert['crt']);
818
			$key = base64_decode($cert['prv']);
819
			if(!$config['system']['webgui']['port'])
820
				$portarg = "443";
821
			$ca = ca_chain($cert);
822
		}
823
	}
824

    
825
	/* generate lighttpd configuration */
826
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
827
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
828
		"cert.pem", "ca.pem");
829

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

    
833
	sleep(1);
834

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

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

    
840
	if ($g['booting']) {
841
		if ($res == 0)
842
			echo gettext("done.") . "\n";
843
		else
844
			echo gettext("failed!") . "\n";
845
	}
846

    
847
	return $res;
848
}
849

    
850
function system_generate_lighty_config($filename,
851
	$cert,
852
	$key,
853
	$ca,
854
	$pid_file,
855
	$port = 80,
856
	$document_root = "/usr/local/www/",
857
	$cert_location = "cert.pem",
858
	$ca_location = "ca.pem",
859
	$captive_portal = false, $captive_portal_saml = false) {
860

    
861
	global $config, $g;
862

    
863
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
864
		mkdir("{$g['tmp_path']}/lighttpdcompress");
865

    
866
	if(isset($config['system']['developerspew'])) {
867
		$mt = microtime();
868
		echo "system_generate_lighty_config() being called $mt\n";
869
	}
870

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

    
875
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
876
		if (empty($maxprocperip))
877
			$maxprocperip = 64;
878
		$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
879

    
880
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
881
		if (!is_dir("{$g['tmp_path']}/captiveportal"))
882
			@mkdir("{$g['tmp_path']}/captiveportal", 0555);
883
		$server_max_request_size = "server.max-request-size    = 384";
884
		$cgi_config = "";
885

    
886
		if ($captive_portal_saml)
887
			$captive_portal_rewrite = "";
888

    
889
	} else {
890
		$captiveportal = ",\"mod_cgi\"";
891
		$captive_portal_rewrite = "";
892
		$captive_portal_mod_evasive = "";
893
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
894
		$server_max_request_size = "server.max-request-size    = 2097152";
895
		$cgi_config = "cgi.assign                 = ( \".cgi\" => \"\" )";
896
	}
897
	
898
	if (empty($port))
899
		$lighty_port = "80";
900
	else
901
		$lighty_port = $port;
902

    
903
	$memory = get_memory();
904
	$realmem = $memory[1];
905

    
906
	// Determine web GUI process settings and take into account low memory systems
907
	if ($realmem < 255)
908
		$max_procs = 1;
909
	else
910
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
911

    
912
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM 
913
	if ($captive_portal !== false)  {
914
		if ($realmem > 135 and $realmem < 256) {
915
			$max_procs += 1; // 2 worker processes
916
		} else if ($realmem > 255 and $realmem < 513) {
917
			$max_procs += 2; // 3 worker processes
918
		} else if ($realmem > 512) {
919
			$max_procs += 4; // 6 worker processes
920
		}
921
		if ($max_procs > 1)
922
			$max_php_children = intval($max_procs/2);
923
		else
924
			$max_php_children = 1;
925

    
926
	} else {
927
		if ($realmem < 78)
928
			$max_php_children = 0;
929
		else
930
			$max_php_children = 1;
931
	}
932

    
933
	if ($captive_portal !== false)
934
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi-{$captive_portal}.socket";
935
	else
936
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi.socket";
937

    
938
	if(!isset($config['syslog']['nologlighttpd'])) {
939
		$lighty_use_syslog = <<<EOD
940
## where to send error-messages to
941
server.errorlog-use-syslog="enable"
942
EOD;
943
	}
944

    
945

    
946
	$fastcgi_config = <<<EOD
947
#### fastcgi module
948
## read fastcgi.txt for more info
949
fastcgi.server = ( ".php" =>
950
	( "localhost" =>
951
		(
952
			"socket" => "{$fast_cgi_path}",
953
			"max-procs" => {$max_procs},
954
			"bin-environment" => (
955
				"PHP_FCGI_CHILDREN" => "{$max_php_children}",
956
				"PHP_FCGI_MAX_REQUESTS" => "500"
957
			),
958
			"bin-path" => "/usr/local/bin/php"
959
		)
960
	)
961
)
962

    
963
EOD;
964

    
965
	if ($captive_portal_saml) {
966
		$fastcgi_config = <<<EOD
967
#### fastcgi module
968
fastcgi.server = (
969
    "/django.fcgi" => (
970
        "main" => (
971
            "socket" => "/tmp/univnautes-sp-fcgi.sock",
972
            "check-local" => "disable",
973
        )
974
    ),
975
)
976

    
977
url.rewrite-if-not-file = (
978
    "^/map/(.*)$" => "/django.fcgi/proxymap/$1",
979
)
980

    
981
url.rewrite-once = (
982
    "^/favicon\.ico$" => "/static/favicon.ico",
983
    "^/*$" => "/django.fcgi/",
984
    "^/(accounts|authsaml2|page)(.*)$" => "/django.fcgi/$1$2",
985
)
986

    
987
EOD;
988
	}
989

    
990
	$lighty_config = <<<EOD
991
#
992
# lighttpd configuration file
993
#
994
# use a it as base for lighttpd 1.0.0 and above
995
#
996
############ Options you really have to take care of ####################
997

    
998
## FreeBSD!
999
server.event-handler	= "freebsd-kqueue"
1000
server.network-backend 	= "writev"
1001
#server.use-ipv6 = "enable"
1002

    
1003
## modules to load
1004
server.modules              =   ( "mod_access", "mod_expire", "mod_compress", "mod_redirect",
1005
	{$captiveportal}, "mod_fastcgi", "mod_setenv",
1006
)
1007

    
1008
setenv.add-request-header = ( "X-pfsense-cpzone" => "${captive_portal}" )
1009

    
1010
server.max-keep-alive-requests = 15
1011
server.max-keep-alive-idle = 30
1012

    
1013
## a static document-root, for virtual-hosting take look at the
1014
## server.virtual-* options
1015
server.document-root        = "{$document_root}"
1016
{$captive_portal_rewrite}
1017

    
1018
# Maximum idle time with nothing being written (php downloading)
1019
server.max-write-idle = 999
1020

    
1021
{$lighty_use_syslog}
1022

    
1023
# files to check for if .../ is requested
1024
server.indexfiles           = ( "index.php", "index.html",
1025
                                "index.htm", "default.htm" )
1026

    
1027
# mimetype mapping
1028
mimetype.assign             = (
1029
  ".pdf"          =>      "application/pdf",
1030
  ".sig"          =>      "application/pgp-signature",
1031
  ".spl"          =>      "application/futuresplash",
1032
  ".class"        =>      "application/octet-stream",
1033
  ".ps"           =>      "application/postscript",
1034
  ".torrent"      =>      "application/x-bittorrent",
1035
  ".dvi"          =>      "application/x-dvi",
1036
  ".gz"           =>      "application/x-gzip",
1037
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
1038
  ".swf"          =>      "application/x-shockwave-flash",
1039
  ".tar.gz"       =>      "application/x-tgz",
1040
  ".tgz"          =>      "application/x-tgz",
1041
  ".tar"          =>      "application/x-tar",
1042
  ".zip"          =>      "application/zip",
1043
  ".mp3"          =>      "audio/mpeg",
1044
  ".m3u"          =>      "audio/x-mpegurl",
1045
  ".wma"          =>      "audio/x-ms-wma",
1046
  ".wax"          =>      "audio/x-ms-wax",
1047
  ".ogg"          =>      "audio/x-wav",
1048
  ".wav"          =>      "audio/x-wav",
1049
  ".gif"          =>      "image/gif",
1050
  ".jpg"          =>      "image/jpeg",
1051
  ".jpeg"         =>      "image/jpeg",
1052
  ".png"          =>      "image/png",
1053
  ".xbm"          =>      "image/x-xbitmap",
1054
  ".xpm"          =>      "image/x-xpixmap",
1055
  ".xwd"          =>      "image/x-xwindowdump",
1056
  ".css"          =>      "text/css",
1057
  ".html"         =>      "text/html",
1058
  ".htm"          =>      "text/html",
1059
  ".js"           =>      "text/javascript",
1060
  ".asc"          =>      "text/plain",
1061
  ".c"            =>      "text/plain",
1062
  ".conf"         =>      "text/plain",
1063
  ".text"         =>      "text/plain",
1064
  ".txt"          =>      "text/plain",
1065
  ".dtd"          =>      "text/xml",
1066
  ".xml"          =>      "text/xml",
1067
  ".mpeg"         =>      "video/mpeg",
1068
  ".mpg"          =>      "video/mpeg",
1069
  ".mov"          =>      "video/quicktime",
1070
  ".qt"           =>      "video/quicktime",
1071
  ".avi"          =>      "video/x-msvideo",
1072
  ".asf"          =>      "video/x-ms-asf",
1073
  ".asx"          =>      "video/x-ms-asf",
1074
  ".wmv"          =>      "video/x-ms-wmv",
1075
  ".bz2"          =>      "application/x-bzip",
1076
  ".tbz"          =>      "application/x-bzip-compressed-tar",
1077
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
1078
 )
1079

    
1080
# Use the "Content-Type" extended attribute to obtain mime type if possible
1081
#mimetypes.use-xattr        = "enable"
1082

    
1083
## deny access the file-extensions
1084
#
1085
# ~    is for backupfiles from vi, emacs, joe, ...
1086
# .inc is often used for code includes which should in general not be part
1087
#      of the document-root
1088
url.access-deny             = ( "~", ".inc" )
1089

    
1090

    
1091
######### Options that are good to be but not neccesary to be changed #######
1092

    
1093
## bind to port (default: 80)
1094

    
1095
EOD;
1096

    
1097
	$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1098
	$lighty_config .= "server.port  = {$lighty_port}\n";
1099
	$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1100
	$lighty_config .= "\$SERVER[\"socket\"]  == \"[::]:{$lighty_port}\" { \n";
1101
	if($cert <> "" and $key <> "") {
1102
		$lighty_config .= "\n";
1103
		$lighty_config .= "## ssl configuration\n";
1104
		$lighty_config .= "ssl.engine = \"enable\"\n";
1105
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1106
		if($ca <> "")
1107
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1108
	}
1109
	$lighty_config .= " }\n";
1110

    
1111

    
1112
	$lighty_config .= <<<EOD
1113

    
1114
## error-handler for status 404
1115
#server.error-handler-404   = "/error-handler.html"
1116
#server.error-handler-404   = "/error-handler.php"
1117

    
1118
## to help the rc.scripts
1119
server.pid-file            = "{$g['varrun_path']}/{$pid_file}"
1120

    
1121
## virtual directory listings
1122
server.dir-listing         = "disable"
1123

    
1124
## enable debugging
1125
debug.log-request-header   = "disable"
1126
debug.log-response-header  = "disable"
1127
debug.log-request-handling = "disable"
1128
debug.log-file-not-found   = "disable"
1129

    
1130
# gzip compression
1131
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1132
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1133

    
1134
{$server_upload_dirs}
1135

    
1136
{$server_max_request_size}
1137

    
1138
{$fastcgi_config}
1139

    
1140
{$cgi_config}
1141

    
1142
{$captive_portal_mod_evasive}
1143

    
1144
expire.url = (
1145
				"" => "access 50 hours",	
1146
        )
1147

    
1148
EOD;
1149

    
1150
	$cert = str_replace("\r", "", $cert);
1151
	$key = str_replace("\r", "", $key);
1152
	$ca = str_replace("\r", "", $ca);
1153

    
1154
	$cert = str_replace("\n\n", "\n", $cert);
1155
	$key = str_replace("\n\n", "\n", $key);
1156
	$ca = str_replace("\n\n", "\n", $ca);
1157

    
1158
	if($cert <> "" and $key <> "") {
1159
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1160
		if (!$fd) {
1161
			printf(gettext("Error: cannot open cert.pem in system_webgui_start().%s"), "\n");
1162
			return 1;
1163
		}
1164
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1165
		fwrite($fd, $cert);
1166
		fwrite($fd, "\n");
1167
		fwrite($fd, $key);
1168
		fclose($fd);
1169
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
1170
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1171
			if (!$fd) {
1172
				printf(gettext("Error: cannot open ca.pem in system_webgui_start().%s"), "\n");
1173
				return 1;
1174
			}
1175
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1176
			fwrite($fd, $ca);
1177
			fclose($fd);
1178
		}
1179
		$lighty_config .= "\n";
1180
		$lighty_config .= "## " . gettext("ssl configuration") . "\n";
1181
		$lighty_config .= "ssl.engine = \"enable\"\n";
1182
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1183

    
1184
		// Harden SSL a bit for PCI conformance testing
1185
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
1186

    
1187
		/* Hifn accelerators do NOT work with the BEAST mitigation code. Do not allow it to be enabled if a Hifn card has been detected. */
1188
		$fd = @fopen("{$g['varlog_path']}/dmesg.boot", "r");
1189
		if ($fd) {
1190
			while (!feof($fd)) {
1191
				$dmesgl = fgets($fd);
1192
				if (preg_match("/^hifn.: (.*?),/", $dmesgl, $matches) && isset($config['system']['webgui']['beast_protection'])) {
1193
						unset($config['system']['webgui']['beast_protection']);
1194
						log_error("BEAST Protection disabled because a conflicting cryptographic accelerator card has been detected (" . $matches[1] . ")");
1195
					break;
1196
				}
1197
			}
1198
			fclose($fd);
1199
		}
1200

    
1201
		if (isset($config['system']['webgui']['beast_protection'])) {
1202
			$lighty_config .= "ssl.honor-cipher-order = \"enable\"\n";
1203
			$lighty_config .= "ssl.cipher-list = \"ECDHE-RSA-AES256-SHA384:AES256-SHA256:RC4-SHA:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM\"\n";
1204
		} else {
1205
			$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";
1206
		}
1207

    
1208
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1209
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1210
	}
1211

    
1212
	// Add HTTP to HTTPS redirect	
1213
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1214
		if($lighty_port != "443") 
1215
			$redirectport = ":{$lighty_port}";
1216
		$lighty_config .= <<<EOD
1217
\$SERVER["socket"] == ":80" {
1218
	\$HTTP["host"] =~ "(.*)" {
1219
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1220
	}
1221
}
1222
EOD;
1223
	}
1224

    
1225
	$fd = fopen("{$filename}", "w");
1226
	if (!$fd) {
1227
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1228
		return 1;
1229
	}
1230
	fwrite($fd, $lighty_config);
1231
	fclose($fd);
1232

    
1233
	return 0;
1234

    
1235
}
1236

    
1237
function system_timezone_configure() {
1238
	global $config, $g;
1239
	if(isset($config['system']['developerspew'])) {
1240
		$mt = microtime();
1241
		echo "system_timezone_configure() being called $mt\n";
1242
	}
1243

    
1244
	$syscfg = $config['system'];
1245

    
1246
	if ($g['booting'])
1247
		echo gettext("Setting timezone...");
1248

    
1249
	/* extract appropriate timezone file */
1250
	$timezone = $syscfg['timezone'];
1251
	if ($timezone) {
1252
		exec('/usr/bin/tar -tvzf /usr/share/zoneinfo.tgz', $tzs);
1253
		foreach ($tzs as $tz) {
1254
			if (preg_match(",{$timezone}$,", $tz))
1255
				break;
1256
			if (preg_match(",{$timezone} link to *(.*)$,", $tz, $matches)) {
1257
				$timezone = $matches[1];
1258
				break;
1259
			}
1260
		}
1261
	} else
1262
		$timezone = "Etc/UTC";
1263

    
1264
	conf_mount_rw();
1265

    
1266
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1267
		escapeshellarg($timezone) . " > /etc/localtime");
1268

    
1269
	mwexec("sync");
1270
	conf_mount_ro();
1271

    
1272
	if ($g['booting'])
1273
		echo gettext("done.") . "\n";
1274
}
1275

    
1276
function system_ntp_setup_gps($serialport) {
1277
	$gps_device = '/dev/gps0';
1278
	$serialport = '/dev/'.$serialport;
1279

    
1280
	if (!file_exists($serialport))
1281
		return false;
1282

    
1283
	conf_mount_rw();
1284
	// Create symlink that ntpd requires
1285
	unlink_if_exists($gps_device);
1286
	symlink($serialport, $gps_device);
1287

    
1288
	/* Send the following to the GPS port to initialize the GPS */
1289
	$gps_init = <<<EOF
1290
\$PUBX,40,GSV,0,0,0,0*59
1291
\$PUBX,40,GLL,0,0,0,0*5C
1292
\$PUBX,40,ZDA,0,0,0,0*44
1293
\$PUBX,40,VTG,0,0,0,0*5E
1294
\$PUBX,40,GSV,0,0,0,0*59
1295
\$PUBX,40,GSA,0,0,0,0*4E
1296
\$PUBX,40,GGA,0,0,0,0
1297
\$PUBX,40,TXT,0,0,0,0
1298
\$PUBX,40,RMC,0,0,0,0*46
1299
\$PUBX,41,1,0007,0003,4800,0
1300
\$PUBX,40,ZDA,1,1,1,1
1301
EOF;
1302
	file_put_contents("/tmp/gps.init", $gps_init);
1303
	`cat /tmp/gps.init > $serialport`;
1304

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

    
1309
	conf_mount_ro();
1310

    
1311
	return true;
1312
}
1313

    
1314
function system_ntp_configure($start_ntpd=true) {
1315
	global $config, $g;
1316
	$driftfile = "/var/db/ntpd.drift";
1317
	$statsdir = "/var/log/ntp";
1318
	$gps_device = '/dev/gps0';
1319

    
1320
	if ($g['platform'] == 'jail')
1321
		return;
1322

    
1323
	safe_mkdir($statsdir);
1324

    
1325
	$ntpcfg = "# \n";
1326
	$ntpcfg .= "# pfSense ntp configuration file \n";
1327
	$ntpcfg .= "# \n\n";
1328
	$ntpcfg .= "tinker panic 0 \n";
1329

    
1330
	if (!empty($config['ntpd']['gpsport'])
1331
		&& file_exists('/dev/'.$config['ntpd']['gpsport'])
1332
		&& system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1333
		$ntpcfg .= "# GPS Setup\n";
1334
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1335
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1336
		// Fall back to local clock if GPS is out of sync?
1337
		$ntpcfg .= "server 127.127.1.0\n";
1338
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1339
	}
1340

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

    
1346
	$ntpcfg .= "disable monitor\n";
1347
	$ntpcfg .= "enable stats\n";
1348
	$ntpcfg .= "statistics clockstats\n";
1349
	$ntpcfg .= "statsdir {$statsdir}\n";
1350
	$ntpcfg .= "logconfig =syncall +clockall\n";
1351
	$ntpcfg .= "driftfile {$driftfile}\n";
1352
	$ntpcfg .= "restrict default kod nomodify notrap nopeer\n";
1353
	$ntpcfg .= "restrict -6 default kod nomodify notrap nopeer\n";
1354

    
1355
	if (empty($config['ntpd']['interface']))
1356
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface']))
1357
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1358
		else
1359
			$interfaces = array();
1360
	else
1361
		$interfaces = explode(",", $config['ntpd']['interface']);
1362

    
1363
	if (is_array($interfaces) && count($interfaces)) {
1364
		$ntpcfg .= "interface ignore all\n";
1365
		foreach ($interfaces as $interface) {
1366
			if (!is_ipaddr($interface)) {
1367
				$interface = get_real_interface($interface);
1368
			}
1369
			if (!empty($interface))
1370
				$ntpcfg .= "interface listen {$interface}\n";
1371
		}
1372
	}
1373

    
1374
	/* open configuration for wrting or bail */
1375
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
1376
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1377
		return;
1378
	}
1379

    
1380
	/* At bootup we just want to write out the config. */
1381
	if (!$start_ntpd)
1382
		return;
1383

    
1384
	/* if ntpd is running, kill it */
1385
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1386
		killbypid("{$g['varrun_path']}/ntpd.pid");
1387
	}
1388
	@unlink("{$g['varrun_path']}/ntpd.pid");
1389

    
1390
	/* if /var/empty does not exist, create it */
1391
	if(!is_dir("/var/empty"))
1392
		mkdir("/var/empty", 0775, true);
1393

    
1394
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1395
	mwexec("/usr/local/sbin/ntpd -g -c {$g['varetc_path']}/ntpd.conf -p {$g['varrun_path']}/ntpd.pid", false, true);
1396
	
1397
	// Note that we are starting up
1398
	log_error("NTPD is starting up.");
1399
	return;
1400
}
1401

    
1402
function sync_system_time() {
1403
	global $config, $g;
1404

    
1405
	if ($g['booting'])
1406
		echo gettext("Syncing system time before startup...");
1407

    
1408
	/* foreach through servers and write out to ntpd.conf */
1409
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1410
		mwexec("/usr/sbin/ntpdate -s $ts");
1411
	}
1412
	
1413
	if ($g['booting'])
1414
		echo gettext("done.") . "\n";
1415
	
1416
}
1417

    
1418
function system_halt() {
1419
	global $g;
1420

    
1421
	system_reboot_cleanup();
1422

    
1423
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1424
}
1425

    
1426
function system_reboot() {
1427
	global $g;
1428

    
1429
	system_reboot_cleanup();
1430

    
1431
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1432
}
1433

    
1434
function system_reboot_sync() {
1435
	global $g;
1436

    
1437
	system_reboot_cleanup();
1438

    
1439
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1440
}
1441

    
1442
function system_reboot_cleanup() {
1443
	global $config, $cpzone;
1444

    
1445
	mwexec("/usr/local/bin/beep.sh stop");
1446
	require_once("captiveportal.inc");
1447
	if (is_array($config['captiveportal'])) {
1448
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
1449
			captiveportal_radius_stop_all();
1450
			captiveportal_send_server_accounting(true);
1451
		}
1452
	}
1453
	require_once("voucher.inc");
1454
	voucher_save_db_to_config();
1455
	require_once("pkg-utils.inc");
1456
	stop_packages();
1457
}
1458

    
1459
function system_do_shell_commands($early = 0) {
1460
	global $config, $g;
1461
	if(isset($config['system']['developerspew'])) {
1462
		$mt = microtime();
1463
		echo "system_do_shell_commands() being called $mt\n";
1464
	}
1465

    
1466
	if ($early)
1467
		$cmdn = "earlyshellcmd";
1468
	else
1469
		$cmdn = "shellcmd";
1470

    
1471
	if (is_array($config['system'][$cmdn])) {
1472

    
1473
		/* *cmd is an array, loop through */
1474
		foreach ($config['system'][$cmdn] as $cmd) {
1475
			exec($cmd);
1476
		}
1477

    
1478
	} elseif($config['system'][$cmdn] <> "") {
1479

    
1480
		/* execute single item */
1481
		exec($config['system'][$cmdn]);
1482

    
1483
	}
1484
}
1485

    
1486
function system_console_configure() {
1487
	global $config, $g;
1488
	if(isset($config['system']['developerspew'])) {
1489
		$mt = microtime();
1490
		echo "system_console_configure() being called $mt\n";
1491
	}
1492

    
1493
	if (isset($config['system']['disableconsolemenu'])) {
1494
		touch("{$g['varetc_path']}/disableconsole");
1495
	} else {
1496
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1497
	}
1498
}
1499

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

    
1507
	$dmesg = "";
1508
	exec("/sbin/dmesg", $dmesg);
1509

    
1510
	/* find last copyright line (output from previous boots may be present) */
1511
	$lastcpline = 0;
1512

    
1513
	for ($i = 0; $i < count($dmesg); $i++) {
1514
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1515
			$lastcpline = $i;
1516
	}
1517

    
1518
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1519
	if (!$fd) {
1520
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1521
		return 1;
1522
	}
1523

    
1524
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1525
		fwrite($fd, $dmesg[$i] . "\n");
1526

    
1527
	fclose($fd);
1528

    
1529
	return 0;
1530
}
1531

    
1532
function system_set_harddisk_standby() {
1533
	global $g, $config;
1534
	if(isset($config['system']['developerspew'])) {
1535
		$mt = microtime();
1536
		echo "system_set_harddisk_standby() being called $mt\n";
1537
	}
1538

    
1539
	if (isset($config['system']['harddiskstandby'])) {
1540
		if ($g['booting']) {
1541
			echo gettext('Setting hard disk standby... ');
1542
		}
1543

    
1544
		$standby = $config['system']['harddiskstandby'];
1545
		// Check for a numeric value
1546
		if (is_numeric($standby)) {
1547
			// Sync the disk(s)
1548
			pfSense_sync();
1549
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1550
				// Reinitialize ATA-drives
1551
				mwexec('/usr/local/sbin/atareinit');
1552
				if ($g['booting']) {
1553
					echo gettext("done.") . "\n";
1554
				}
1555
			} else if ($g['booting']) {
1556
				echo gettext("failed!") . "\n";
1557
			}
1558
		} else if ($g['booting']) {
1559
			echo gettext("failed!") . "\n";
1560
		}
1561
	}
1562
}
1563

    
1564
function system_setup_sysctl() {
1565
	global $config;
1566
	if(isset($config['system']['developerspew'])) {
1567
		$mt = microtime();
1568
		echo "system_setup_sysctl() being called $mt\n";
1569
	}
1570

    
1571
	activate_sysctls();	
1572

    
1573
	if (isset($config['system']['sharednet'])) {
1574
		system_disable_arp_wrong_if();
1575
	}
1576
}
1577

    
1578
function system_disable_arp_wrong_if() {
1579
	global $config;
1580
	if(isset($config['system']['developerspew'])) {
1581
		$mt = microtime();
1582
		echo "system_disable_arp_wrong_if() being called $mt\n";
1583
	}
1584
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1585
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1586
}
1587

    
1588
function system_enable_arp_wrong_if() {
1589
	global $config;
1590
	if(isset($config['system']['developerspew'])) {
1591
		$mt = microtime();
1592
		echo "system_enable_arp_wrong_if() being called $mt\n";
1593
	}
1594
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1595
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1596
}
1597

    
1598
function enable_watchdog() {
1599
	global $config;
1600
	return;
1601
	$install_watchdog = false;
1602
	$supported_watchdogs = array("Geode");
1603
	$file = file_get_contents("/var/log/dmesg.boot");
1604
	foreach($supported_watchdogs as $sd) {
1605
		if(stristr($file, "Geode")) {
1606
			$install_watchdog = true;
1607
		}
1608
	}
1609
	if($install_watchdog == true) {
1610
		if(is_process_running("watchdogd"))
1611
			mwexec("/usr/bin/killall watchdogd", true);
1612
		exec("/usr/sbin/watchdogd");
1613
	}
1614
}
1615

    
1616
function system_check_reset_button() {
1617
	global $g;
1618
	if($g['platform'] != "nanobsd")
1619
		return 0;
1620

    
1621
	$specplatform = system_identify_specific_platform();
1622

    
1623
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1624
		return 0;
1625

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

    
1628
	if ($retval == 99) {
1629
		/* user has pressed reset button for 2 seconds - 
1630
		   reset to factory defaults */
1631
		echo <<<EOD
1632

    
1633
***********************************************************************
1634
* Reset button pressed - resetting configuration to factory defaults. *
1635
* The system will reboot after this completes.                        *
1636
***********************************************************************
1637

    
1638

    
1639
EOD;
1640
		
1641
		reset_factory_defaults();
1642
		system_reboot_sync();
1643
		exit(0);
1644
	}
1645

    
1646
	return 0;
1647
}
1648

    
1649
/* attempt to identify the specific platform (for embedded systems)
1650
   Returns an array with two elements:
1651
	name => platform string (e.g. 'wrap', 'alix' etc.)
1652
	descr => human-readable description (e.g. "PC Engines WRAP")
1653
*/
1654
function system_identify_specific_platform() {
1655
	global $g;
1656
	
1657
	if ($g['platform'] == 'generic-pc')
1658
		return array('name' => 'generic-pc', 'descr' => gettext("Generic PC"));
1659
	
1660
	if ($g['platform'] == 'generic-pc-cdrom')
1661
		return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)"));
1662
	
1663
	/* the rest of the code only deals with 'embedded' platforms */
1664
	if ($g['platform'] != 'nanobsd')
1665
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1666
	
1667
	$dmesg = system_get_dmesg_boot();
1668
	
1669
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1670
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
1671
	
1672
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1673
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
1674

    
1675
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1676
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1677
	
1678
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1679
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1680
		
1681
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1682
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1683
	
1684
	/* unknown embedded platform */
1685
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
1686
}
1687

    
1688
function system_get_dmesg_boot() {
1689
	global $g;
1690
		
1691
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1692
}
1693

    
1694
function get_possible_listen_ips($include_ipv6_link_local=false) {
1695
	$interfaces = get_configured_interface_with_descr();
1696
	$carplist = get_configured_carp_interface_list();
1697
	$listenips = array();
1698
	foreach ($carplist as $cif => $carpip)
1699
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1700
	$aliaslist = get_configured_ip_aliases_list();
1701
	foreach ($aliaslist as $aliasip => $aliasif)
1702
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1703
	foreach ($interfaces as $iface => $ifacename) {
1704
		$tmp["name"]  = $ifacename;
1705
		$tmp["value"] = $iface;
1706
		$listenips[] = $tmp;
1707
		if ($include_ipv6_link_local) {
1708
			$llip = find_interface_ipv6_ll(get_real_interface($iface));
1709
			if (!empty($llip)) {
1710
				$tmp["name"]  = "{$ifacename} IPv6 Link-Local";
1711
				$tmp["value"] = $llip;
1712
				$listenips[] = $tmp;
1713
			}
1714
		}
1715
	}
1716
	$tmp["name"]  = "Localhost";
1717
	$tmp["value"] = "lo0";
1718
	$listenips[] = $tmp;
1719
	return $listenips;
1720
}
1721

    
1722
function get_possible_traffic_source_addresses($include_ipv6_link_local=false) {
1723
	global $config;
1724
	$sourceips = get_possible_listen_ips($include_ipv6_link_local);
1725
	foreach (array('server', 'client') as $mode) {
1726
		if (is_array($config['openvpn']["openvpn-{$mode}"])) {
1727
			foreach ($config['openvpn']["openvpn-{$mode}"] as $id => $setting) {
1728
				if (!isset($setting['disable'])) {
1729
					$vpn = array();
1730
					$vpn['value'] = 'ovpn' . substr($mode, 0, 1) . $setting['vpnid'];
1731
					$vpn['name'] = gettext("OpenVPN") . " ".$mode.": ".htmlspecialchars($setting['description']);
1732
					$sourceips[] = $vpn;
1733
				}
1734
			}
1735
		}
1736
	}
1737
	return $sourceips;
1738
}
1739
?>
(53-53/67)