Projet

Général

Profil

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

univnautes / etc / inc / system.inc @ 29be59ad

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
		$lighty_config .= "ssl.use-sslv3 = \"disable\"\n";
1156

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

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

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

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

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

    
1203
	return 0;
1204

    
1205
}
1206

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

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

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

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

    
1234
	conf_mount_rw();
1235

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

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

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

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

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

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

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

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

    
1279
	conf_mount_ro();
1280

    
1281
	return true;
1282
}
1283

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

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

    
1293
	safe_mkdir($statsdir);
1294

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1391
	system_reboot_cleanup();
1392

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

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

    
1399
	system_reboot_cleanup();
1400

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

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

    
1407
	system_reboot_cleanup();
1408

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

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

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

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

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

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

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

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

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

    
1453
	}
1454
}
1455

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

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

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

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

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

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

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

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

    
1497
	fclose($fd);
1498

    
1499
	return 0;
1500
}
1501

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

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

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

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

    
1541
	activate_sysctls();	
1542

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

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

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

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

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

    
1591
	$specplatform = system_identify_specific_platform();
1592

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

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

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

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

    
1608

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

    
1616
	return 0;
1617
}
1618

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

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

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

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

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