Projet

Général

Profil

Télécharger (53,7 ko) Statistiques
| Branche: | Tag: | Révision:

univnautes / etc / inc / system.inc @ 4a3495b3

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) {
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 = 10;
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
	} else {
886
		$captiveportal = ",\"mod_cgi\"";
887
		$captive_portal_rewrite = "";
888
		$captive_portal_mod_evasive = "";
889
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
890
		$server_max_request_size = "server.max-request-size    = 2097152";
891
		$cgi_config = "cgi.assign                 = ( \".cgi\" => \"\" )";
892
	}
893
	
894
	if (empty($port))
895
		$lighty_port = "80";
896
	else
897
		$lighty_port = $port;
898

    
899
	$memory = get_memory();
900
	$realmem = $memory[1];
901

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

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

    
922
	} else {
923
		if ($realmem < 78)
924
			$max_php_children = 0;
925
		else
926
			$max_php_children = 1;
927
	}
928

    
929
	if ($captive_portal !== false)
930
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi-{$captive_portal}.socket";
931
	else
932
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi.socket";
933

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

    
941

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

    
959
EOD;
960

    
961
	$lighty_config = <<<EOD
962
#
963
# lighttpd configuration file
964
#
965
# use a it as base for lighttpd 1.0.0 and above
966
#
967
############ Options you really have to take care of ####################
968

    
969
## FreeBSD!
970
server.event-handler	= "freebsd-kqueue"
971
server.network-backend 	= "writev"
972
#server.use-ipv6 = "enable"
973

    
974
## modules to load
975
server.modules              =   ( "mod_access", "mod_expire", "mod_compress", "mod_redirect",
976
	{$captiveportal}, "mod_fastcgi"
977
)
978

    
979
server.max-keep-alive-requests = 15
980
server.max-keep-alive-idle = 30
981

    
982
## a static document-root, for virtual-hosting take look at the
983
## server.virtual-* options
984
server.document-root        = "{$document_root}"
985
{$captive_portal_rewrite}
986

    
987
# Maximum idle time with nothing being written (php downloading)
988
server.max-write-idle = 999
989

    
990
{$lighty_use_syslog}
991

    
992
# files to check for if .../ is requested
993
server.indexfiles           = ( "index.php", "index.html",
994
                                "index.htm", "default.htm" )
995

    
996
# mimetype mapping
997
mimetype.assign             = (
998
  ".pdf"          =>      "application/pdf",
999
  ".sig"          =>      "application/pgp-signature",
1000
  ".spl"          =>      "application/futuresplash",
1001
  ".class"        =>      "application/octet-stream",
1002
  ".ps"           =>      "application/postscript",
1003
  ".torrent"      =>      "application/x-bittorrent",
1004
  ".dvi"          =>      "application/x-dvi",
1005
  ".gz"           =>      "application/x-gzip",
1006
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
1007
  ".swf"          =>      "application/x-shockwave-flash",
1008
  ".tar.gz"       =>      "application/x-tgz",
1009
  ".tgz"          =>      "application/x-tgz",
1010
  ".tar"          =>      "application/x-tar",
1011
  ".zip"          =>      "application/zip",
1012
  ".mp3"          =>      "audio/mpeg",
1013
  ".m3u"          =>      "audio/x-mpegurl",
1014
  ".wma"          =>      "audio/x-ms-wma",
1015
  ".wax"          =>      "audio/x-ms-wax",
1016
  ".ogg"          =>      "audio/x-wav",
1017
  ".wav"          =>      "audio/x-wav",
1018
  ".gif"          =>      "image/gif",
1019
  ".jpg"          =>      "image/jpeg",
1020
  ".jpeg"         =>      "image/jpeg",
1021
  ".png"          =>      "image/png",
1022
  ".xbm"          =>      "image/x-xbitmap",
1023
  ".xpm"          =>      "image/x-xpixmap",
1024
  ".xwd"          =>      "image/x-xwindowdump",
1025
  ".css"          =>      "text/css",
1026
  ".html"         =>      "text/html",
1027
  ".htm"          =>      "text/html",
1028
  ".js"           =>      "text/javascript",
1029
  ".asc"          =>      "text/plain",
1030
  ".c"            =>      "text/plain",
1031
  ".conf"         =>      "text/plain",
1032
  ".text"         =>      "text/plain",
1033
  ".txt"          =>      "text/plain",
1034
  ".dtd"          =>      "text/xml",
1035
  ".xml"          =>      "text/xml",
1036
  ".mpeg"         =>      "video/mpeg",
1037
  ".mpg"          =>      "video/mpeg",
1038
  ".mov"          =>      "video/quicktime",
1039
  ".qt"           =>      "video/quicktime",
1040
  ".avi"          =>      "video/x-msvideo",
1041
  ".asf"          =>      "video/x-ms-asf",
1042
  ".asx"          =>      "video/x-ms-asf",
1043
  ".wmv"          =>      "video/x-ms-wmv",
1044
  ".bz2"          =>      "application/x-bzip",
1045
  ".tbz"          =>      "application/x-bzip-compressed-tar",
1046
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
1047
 )
1048

    
1049
# Use the "Content-Type" extended attribute to obtain mime type if possible
1050
#mimetypes.use-xattr        = "enable"
1051

    
1052
## deny access the file-extensions
1053
#
1054
# ~    is for backupfiles from vi, emacs, joe, ...
1055
# .inc is often used for code includes which should in general not be part
1056
#      of the document-root
1057
url.access-deny             = ( "~", ".inc" )
1058

    
1059

    
1060
######### Options that are good to be but not neccesary to be changed #######
1061

    
1062
## bind to port (default: 80)
1063

    
1064
EOD;
1065

    
1066
	$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1067
	$lighty_config .= "server.port  = {$lighty_port}\n";
1068
	$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1069
	$lighty_config .= "\$SERVER[\"socket\"]  == \"[::]:{$lighty_port}\" { \n";
1070
	if($cert <> "" and $key <> "") {
1071
		$lighty_config .= "\n";
1072
		$lighty_config .= "## ssl configuration\n";
1073
		$lighty_config .= "ssl.engine = \"enable\"\n";
1074
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1075
		if($ca <> "")
1076
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1077
	}
1078
	$lighty_config .= " }\n";
1079

    
1080

    
1081
	$lighty_config .= <<<EOD
1082

    
1083
## error-handler for status 404
1084
#server.error-handler-404   = "/error-handler.html"
1085
#server.error-handler-404   = "/error-handler.php"
1086

    
1087
## to help the rc.scripts
1088
server.pid-file            = "{$g['varrun_path']}/{$pid_file}"
1089

    
1090
## virtual directory listings
1091
server.dir-listing         = "disable"
1092

    
1093
## enable debugging
1094
debug.log-request-header   = "disable"
1095
debug.log-response-header  = "disable"
1096
debug.log-request-handling = "disable"
1097
debug.log-file-not-found   = "disable"
1098

    
1099
# gzip compression
1100
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1101
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1102

    
1103
{$server_upload_dirs}
1104

    
1105
{$server_max_request_size}
1106

    
1107
{$fastcgi_config}
1108

    
1109
{$cgi_config}
1110

    
1111
{$captive_portal_mod_evasive}
1112

    
1113
expire.url = (
1114
				"" => "access 50 hours",	
1115
        )
1116

    
1117
EOD;
1118

    
1119
	$cert = str_replace("\r", "", $cert);
1120
	$key = str_replace("\r", "", $key);
1121
	$ca = str_replace("\r", "", $ca);
1122

    
1123
	$cert = str_replace("\n\n", "\n", $cert);
1124
	$key = str_replace("\n\n", "\n", $key);
1125
	$ca = str_replace("\n\n", "\n", $ca);
1126

    
1127
	if($cert <> "" and $key <> "") {
1128
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1129
		if (!$fd) {
1130
			printf(gettext("Error: cannot open cert.pem in system_webgui_start().%s"), "\n");
1131
			return 1;
1132
		}
1133
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1134
		fwrite($fd, $cert);
1135
		fwrite($fd, "\n");
1136
		fwrite($fd, $key);
1137
		fclose($fd);
1138
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
1139
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1140
			if (!$fd) {
1141
				printf(gettext("Error: cannot open ca.pem in system_webgui_start().%s"), "\n");
1142
				return 1;
1143
			}
1144
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1145
			fwrite($fd, $ca);
1146
			fclose($fd);
1147
		}
1148
		$lighty_config .= "\n";
1149
		$lighty_config .= "## " . gettext("ssl configuration") . "\n";
1150
		$lighty_config .= "ssl.engine = \"enable\"\n";
1151
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1152

    
1153
		// Harden SSL a bit for PCI conformance testing
1154
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
1155

    
1156
		/* Hifn accelerators do NOT work with the BEAST mitigation code. Do not allow it to be enabled if a Hifn card has been detected. */
1157
		$fd = @fopen("{$g['varlog_path']}/dmesg.boot", "r");
1158
		if ($fd) {
1159
			while (!feof($fd)) {
1160
				$dmesgl = fgets($fd);
1161
				if (preg_match("/^hifn.: (.*?),/", $dmesgl, $matches) && isset($config['system']['webgui']['beast_protection'])) {
1162
						unset($config['system']['webgui']['beast_protection']);
1163
						log_error("BEAST Protection disabled because a conflicting cryptographic accelerator card has been detected (" . $matches[1] . ")");
1164
					break;
1165
				}
1166
			}
1167
			fclose($fd);
1168
		}
1169

    
1170
		if (isset($config['system']['webgui']['beast_protection'])) {
1171
			$lighty_config .= "ssl.honor-cipher-order = \"enable\"\n";
1172
			$lighty_config .= "ssl.cipher-list = \"ECDHE-RSA-AES256-SHA384:AES256-SHA256:RC4-SHA:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM\"\n";
1173
		} else {
1174
			$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";
1175
		}
1176

    
1177
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1178
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1179
	}
1180

    
1181
	// Add HTTP to HTTPS redirect	
1182
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1183
		if($lighty_port != "443") 
1184
			$redirectport = ":{$lighty_port}";
1185
		$lighty_config .= <<<EOD
1186
\$SERVER["socket"] == ":80" {
1187
	\$HTTP["host"] =~ "(.*)" {
1188
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1189
	}
1190
}
1191
EOD;
1192
	}
1193

    
1194
	$fd = fopen("{$filename}", "w");
1195
	if (!$fd) {
1196
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1197
		return 1;
1198
	}
1199
	fwrite($fd, $lighty_config);
1200
	fclose($fd);
1201

    
1202
	return 0;
1203

    
1204
}
1205

    
1206
function system_timezone_configure() {
1207
	global $config, $g;
1208
	if(isset($config['system']['developerspew'])) {
1209
		$mt = microtime();
1210
		echo "system_timezone_configure() being called $mt\n";
1211
	}
1212

    
1213
	$syscfg = $config['system'];
1214

    
1215
	if ($g['booting'])
1216
		echo gettext("Setting timezone...");
1217

    
1218
	/* extract appropriate timezone file */
1219
	$timezone = $syscfg['timezone'];
1220
	if ($timezone) {
1221
		exec('/usr/bin/tar -tvzf /usr/share/zoneinfo.tgz', $tzs);
1222
		foreach ($tzs as $tz) {
1223
			if (preg_match(",{$timezone}$,", $tz))
1224
				break;
1225
			if (preg_match(",{$timezone} link to *(.*)$,", $tz, $matches)) {
1226
				$timezone = $matches[1];
1227
				break;
1228
			}
1229
		}
1230
	} else
1231
		$timezone = "Etc/UTC";
1232

    
1233
	conf_mount_rw();
1234

    
1235
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1236
		escapeshellarg($timezone) . " > /etc/localtime");
1237

    
1238
	mwexec("sync");
1239
	conf_mount_ro();
1240

    
1241
	if ($g['booting'])
1242
		echo gettext("done.") . "\n";
1243
}
1244

    
1245
function system_ntp_setup_gps($serialport) {
1246
	$gps_device = '/dev/gps0';
1247
	$serialport = '/dev/'.$serialport;
1248

    
1249
	if (!file_exists($serialport))
1250
		return false;
1251

    
1252
	conf_mount_rw();
1253
	// Create symlink that ntpd requires
1254
	unlink_if_exists($gps_device);
1255
	symlink($serialport, $gps_device);
1256

    
1257
	/* Send the following to the GPS port to initialize the GPS */
1258
	$gps_init = <<<EOF
1259
\$PUBX,40,GSV,0,0,0,0*59
1260
\$PUBX,40,GLL,0,0,0,0*5C
1261
\$PUBX,40,ZDA,0,0,0,0*44
1262
\$PUBX,40,VTG,0,0,0,0*5E
1263
\$PUBX,40,GSV,0,0,0,0*59
1264
\$PUBX,40,GSA,0,0,0,0*4E
1265
\$PUBX,40,GGA,0,0,0,0
1266
\$PUBX,40,TXT,0,0,0,0
1267
\$PUBX,40,RMC,0,0,0,0*46
1268
\$PUBX,41,1,0007,0003,4800,0
1269
\$PUBX,40,ZDA,1,1,1,1
1270
EOF;
1271
	file_put_contents("/tmp/gps.init", $gps_init);
1272
	`cat /tmp/gps.init > $serialport`;
1273

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

    
1278
	conf_mount_ro();
1279

    
1280
	return true;
1281
}
1282

    
1283
function system_ntp_configure($start_ntpd=true) {
1284
	global $config, $g;
1285
	$driftfile = "/var/db/ntpd.drift";
1286
	$statsdir = "/var/log/ntp";
1287
	$gps_device = '/dev/gps0';
1288

    
1289
	if ($g['platform'] == 'jail')
1290
		return;
1291

    
1292
	safe_mkdir($statsdir);
1293

    
1294
	$ntpcfg = "# \n";
1295
	$ntpcfg .= "# pfSense ntp configuration file \n";
1296
	$ntpcfg .= "# \n\n";
1297
	$ntpcfg .= "tinker panic 0 \n";
1298

    
1299
	if (!empty($config['ntpd']['gpsport'])
1300
		&& file_exists('/dev/'.$config['ntpd']['gpsport'])
1301
		&& system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1302
		$ntpcfg .= "# GPS Setup\n";
1303
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1304
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1305
		// Fall back to local clock if GPS is out of sync?
1306
		$ntpcfg .= "server 127.127.1.0\n";
1307
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1308
	}
1309

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

    
1315
	$ntpcfg .= "disable monitor\n";
1316
	$ntpcfg .= "enable stats\n";
1317
	$ntpcfg .= "statistics clockstats\n";
1318
	$ntpcfg .= "statsdir {$statsdir}\n";
1319
	$ntpcfg .= "logconfig =syncall +clockall\n";
1320
	$ntpcfg .= "driftfile {$driftfile}\n";
1321
	$ntpcfg .= "restrict default kod nomodify notrap nopeer\n";
1322
	$ntpcfg .= "restrict -6 default kod nomodify notrap nopeer\n";
1323

    
1324
	if (empty($config['ntpd']['interface']))
1325
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface']))
1326
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1327
		else
1328
			$interfaces = array();
1329
	else
1330
		$interfaces = explode(",", $config['ntpd']['interface']);
1331

    
1332
	if (is_array($interfaces) && count($interfaces)) {
1333
		$ntpcfg .= "interface ignore all\n";
1334
		foreach ($interfaces as $interface) {
1335
			if (!is_ipaddr($interface)) {
1336
				$interface = get_real_interface($interface);
1337
			}
1338
			if (!empty($interface))
1339
				$ntpcfg .= "interface listen {$interface}\n";
1340
		}
1341
	}
1342

    
1343
	/* open configuration for wrting or bail */
1344
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
1345
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1346
		return;
1347
	}
1348

    
1349
	/* At bootup we just want to write out the config. */
1350
	if (!$start_ntpd)
1351
		return;
1352

    
1353
	/* if ntpd is running, kill it */
1354
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1355
		killbypid("{$g['varrun_path']}/ntpd.pid");
1356
	}
1357
	@unlink("{$g['varrun_path']}/ntpd.pid");
1358

    
1359
	/* if /var/empty does not exist, create it */
1360
	if(!is_dir("/var/empty"))
1361
		mkdir("/var/empty", 0775, true);
1362

    
1363
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1364
	mwexec("/usr/local/sbin/ntpd -g -c {$g['varetc_path']}/ntpd.conf -p {$g['varrun_path']}/ntpd.pid", false, true);
1365
	
1366
	// Note that we are starting up
1367
	log_error("NTPD is starting up.");
1368
	return;
1369
}
1370

    
1371
function sync_system_time() {
1372
	global $config, $g;
1373

    
1374
	if ($g['booting'])
1375
		echo gettext("Syncing system time before startup...");
1376

    
1377
	/* foreach through servers and write out to ntpd.conf */
1378
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1379
		mwexec("/usr/sbin/ntpdate -s $ts");
1380
	}
1381
	
1382
	if ($g['booting'])
1383
		echo gettext("done.") . "\n";
1384
	
1385
}
1386

    
1387
function system_halt() {
1388
	global $g;
1389

    
1390
	system_reboot_cleanup();
1391

    
1392
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1393
}
1394

    
1395
function system_reboot() {
1396
	global $g;
1397

    
1398
	system_reboot_cleanup();
1399

    
1400
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1401
}
1402

    
1403
function system_reboot_sync() {
1404
	global $g;
1405

    
1406
	system_reboot_cleanup();
1407

    
1408
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1409
}
1410

    
1411
function system_reboot_cleanup() {
1412
	global $config, $cpzone;
1413

    
1414
	mwexec("/usr/local/bin/beep.sh stop");
1415
	require_once("captiveportal.inc");
1416
	if (is_array($config['captiveportal'])) {
1417
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
1418
			captiveportal_radius_stop_all();
1419
			captiveportal_send_server_accounting(true);
1420
		}
1421
	}
1422
	require_once("voucher.inc");
1423
	voucher_save_db_to_config();
1424
	require_once("pkg-utils.inc");
1425
	stop_packages();
1426
}
1427

    
1428
function system_do_shell_commands($early = 0) {
1429
	global $config, $g;
1430
	if(isset($config['system']['developerspew'])) {
1431
		$mt = microtime();
1432
		echo "system_do_shell_commands() being called $mt\n";
1433
	}
1434

    
1435
	if ($early)
1436
		$cmdn = "earlyshellcmd";
1437
	else
1438
		$cmdn = "shellcmd";
1439

    
1440
	if (is_array($config['system'][$cmdn])) {
1441

    
1442
		/* *cmd is an array, loop through */
1443
		foreach ($config['system'][$cmdn] as $cmd) {
1444
			exec($cmd);
1445
		}
1446

    
1447
	} elseif($config['system'][$cmdn] <> "") {
1448

    
1449
		/* execute single item */
1450
		exec($config['system'][$cmdn]);
1451

    
1452
	}
1453
}
1454

    
1455
function system_console_configure() {
1456
	global $config, $g;
1457
	if(isset($config['system']['developerspew'])) {
1458
		$mt = microtime();
1459
		echo "system_console_configure() being called $mt\n";
1460
	}
1461

    
1462
	if (isset($config['system']['disableconsolemenu'])) {
1463
		touch("{$g['varetc_path']}/disableconsole");
1464
	} else {
1465
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1466
	}
1467
}
1468

    
1469
function system_dmesg_save() {
1470
	global $g;
1471
	if(isset($config['system']['developerspew'])) {
1472
		$mt = microtime();
1473
		echo "system_dmesg_save() being called $mt\n";
1474
	}
1475

    
1476
	$dmesg = "";
1477
	exec("/sbin/dmesg", $dmesg);
1478

    
1479
	/* find last copyright line (output from previous boots may be present) */
1480
	$lastcpline = 0;
1481

    
1482
	for ($i = 0; $i < count($dmesg); $i++) {
1483
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1484
			$lastcpline = $i;
1485
	}
1486

    
1487
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1488
	if (!$fd) {
1489
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1490
		return 1;
1491
	}
1492

    
1493
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1494
		fwrite($fd, $dmesg[$i] . "\n");
1495

    
1496
	fclose($fd);
1497

    
1498
	return 0;
1499
}
1500

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

    
1508
	if (isset($config['system']['harddiskstandby'])) {
1509
		if ($g['booting']) {
1510
			echo gettext('Setting hard disk standby... ');
1511
		}
1512

    
1513
		$standby = $config['system']['harddiskstandby'];
1514
		// Check for a numeric value
1515
		if (is_numeric($standby)) {
1516
			// Sync the disk(s)
1517
			pfSense_sync();
1518
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1519
				// Reinitialize ATA-drives
1520
				mwexec('/usr/local/sbin/atareinit');
1521
				if ($g['booting']) {
1522
					echo gettext("done.") . "\n";
1523
				}
1524
			} else if ($g['booting']) {
1525
				echo gettext("failed!") . "\n";
1526
			}
1527
		} else if ($g['booting']) {
1528
			echo gettext("failed!") . "\n";
1529
		}
1530
	}
1531
}
1532

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

    
1540
	activate_sysctls();	
1541

    
1542
	if (isset($config['system']['sharednet'])) {
1543
		system_disable_arp_wrong_if();
1544
	}
1545
}
1546

    
1547
function system_disable_arp_wrong_if() {
1548
	global $config;
1549
	if(isset($config['system']['developerspew'])) {
1550
		$mt = microtime();
1551
		echo "system_disable_arp_wrong_if() being called $mt\n";
1552
	}
1553
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1554
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1555
}
1556

    
1557
function system_enable_arp_wrong_if() {
1558
	global $config;
1559
	if(isset($config['system']['developerspew'])) {
1560
		$mt = microtime();
1561
		echo "system_enable_arp_wrong_if() being called $mt\n";
1562
	}
1563
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1564
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1565
}
1566

    
1567
function enable_watchdog() {
1568
	global $config;
1569
	return;
1570
	$install_watchdog = false;
1571
	$supported_watchdogs = array("Geode");
1572
	$file = file_get_contents("/var/log/dmesg.boot");
1573
	foreach($supported_watchdogs as $sd) {
1574
		if(stristr($file, "Geode")) {
1575
			$install_watchdog = true;
1576
		}
1577
	}
1578
	if($install_watchdog == true) {
1579
		if(is_process_running("watchdogd"))
1580
			mwexec("/usr/bin/killall watchdogd", true);
1581
		exec("/usr/sbin/watchdogd");
1582
	}
1583
}
1584

    
1585
function system_check_reset_button() {
1586
	global $g;
1587
	if($g['platform'] != "nanobsd")
1588
		return 0;
1589

    
1590
	$specplatform = system_identify_specific_platform();
1591

    
1592
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1593
		return 0;
1594

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

    
1597
	if ($retval == 99) {
1598
		/* user has pressed reset button for 2 seconds - 
1599
		   reset to factory defaults */
1600
		echo <<<EOD
1601

    
1602
***********************************************************************
1603
* Reset button pressed - resetting configuration to factory defaults. *
1604
* The system will reboot after this completes.                        *
1605
***********************************************************************
1606

    
1607

    
1608
EOD;
1609
		
1610
		reset_factory_defaults();
1611
		system_reboot_sync();
1612
		exit(0);
1613
	}
1614

    
1615
	return 0;
1616
}
1617

    
1618
/* attempt to identify the specific platform (for embedded systems)
1619
   Returns an array with two elements:
1620
	name => platform string (e.g. 'wrap', 'alix' etc.)
1621
	descr => human-readable description (e.g. "PC Engines WRAP")
1622
*/
1623
function system_identify_specific_platform() {
1624
	global $g;
1625
	
1626
	if ($g['platform'] == 'generic-pc')
1627
		return array('name' => 'generic-pc', 'descr' => gettext("Generic PC"));
1628
	
1629
	if ($g['platform'] == 'generic-pc-cdrom')
1630
		return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)"));
1631
	
1632
	/* the rest of the code only deals with 'embedded' platforms */
1633
	if ($g['platform'] != 'nanobsd')
1634
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1635
	
1636
	$dmesg = system_get_dmesg_boot();
1637
	
1638
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1639
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
1640
	
1641
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1642
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
1643

    
1644
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1645
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1646
	
1647
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1648
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1649
		
1650
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1651
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1652
	
1653
	/* unknown embedded platform */
1654
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
1655
}
1656

    
1657
function system_get_dmesg_boot() {
1658
	global $g;
1659
		
1660
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1661
}
1662

    
1663
function get_possible_listen_ips($include_ipv6_link_local=false) {
1664
	$interfaces = get_configured_interface_with_descr();
1665
	$carplist = get_configured_carp_interface_list();
1666
	$listenips = array();
1667
	foreach ($carplist as $cif => $carpip)
1668
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1669
	$aliaslist = get_configured_ip_aliases_list();
1670
	foreach ($aliaslist as $aliasip => $aliasif)
1671
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1672
	foreach ($interfaces as $iface => $ifacename) {
1673
		$tmp["name"]  = $ifacename;
1674
		$tmp["value"] = $iface;
1675
		$listenips[] = $tmp;
1676
		if ($include_ipv6_link_local) {
1677
			$llip = find_interface_ipv6_ll(get_real_interface($iface));
1678
			if (!empty($llip)) {
1679
				$tmp["name"]  = "{$ifacename} IPv6 Link-Local";
1680
				$tmp["value"] = $llip;
1681
				$listenips[] = $tmp;
1682
			}
1683
		}
1684
	}
1685
	$tmp["name"]  = "Localhost";
1686
	$tmp["value"] = "lo0";
1687
	$listenips[] = $tmp;
1688
	return $listenips;
1689
}
1690

    
1691
function get_possible_traffic_source_addresses($include_ipv6_link_local=false) {
1692
	global $config;
1693
	$sourceips = get_possible_listen_ips($include_ipv6_link_local);
1694
	foreach (array('server', 'client') as $mode) {
1695
		if (is_array($config['openvpn']["openvpn-{$mode}"])) {
1696
			foreach ($config['openvpn']["openvpn-{$mode}"] as $id => $setting) {
1697
				if (!isset($setting['disable'])) {
1698
					$vpn = array();
1699
					$vpn['value'] = 'ovpn' . substr($mode, 0, 1) . $setting['vpnid'];
1700
					$vpn['name'] = gettext("OpenVPN") . " ".$mode.": ".htmlspecialchars($setting['description']);
1701
					$sourceips[] = $vpn;
1702
				}
1703
			}
1704
		}
1705
	}
1706
	return $sourceips;
1707
}
1708
?>
(52-52/66)