Projet

Général

Profil

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

univnautes / etc / inc / system.inc @ cbfd5449

1
<?php
2
/* $Id$ */
3
/*
4
	system.inc
5
	part of m0n0wall (http://m0n0.ch/wall)
6

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
168
	unlock($dnslock);
169

    
170
	return 0;
171
}
172

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

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

    
192
	return $master_list;
193
}
194

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

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

    
223
	return $master_list;
224
}
225

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

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

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

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

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

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

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

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

    
320
	system_dhcpleases_configure();
321

    
322
	return 0;
323
}
324

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

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

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

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

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

    
367
	return $status;
368
}
369

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

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

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

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

    
463
	$static_routes = get_staticroutes();
464
	if (count($static_routes)) {
465
		$gateways_arr = return_gateways_array(false, true);
466

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

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

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

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

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

    
510
	return 0;
511
}
512

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
741
	return $retval;
742
}
743

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

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

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

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

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

    
767
	return $res;
768
}
769

    
770

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

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

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

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

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

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

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

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

    
833
	sleep(1);
834

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

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

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

    
847
	return $res;
848
}
849

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

    
861
	global $config, $g;
862

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

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

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

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

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

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

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

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

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

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

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

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

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

    
945

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

    
963
EOD;
964

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

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

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

    
987
EOD;
988
	}
989

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

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

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

    
1008
server.max-keep-alive-requests = 15
1009
server.max-keep-alive-idle = 30
1010

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

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

    
1019
{$lighty_use_syslog}
1020

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

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

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

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

    
1088

    
1089
######### Options that are good to be but not neccesary to be changed #######
1090

    
1091
## bind to port (default: 80)
1092

    
1093
EOD;
1094

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

    
1109

    
1110
	$lighty_config .= <<<EOD
1111

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

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

    
1119
## virtual directory listings
1120
server.dir-listing         = "disable"
1121

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

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

    
1132
{$server_upload_dirs}
1133

    
1134
{$server_max_request_size}
1135

    
1136
{$fastcgi_config}
1137

    
1138
{$cgi_config}
1139

    
1140
{$captive_portal_mod_evasive}
1141

    
1142
expire.url = (
1143
				"" => "access 50 hours",	
1144
        )
1145

    
1146
EOD;
1147

    
1148
	$cert = str_replace("\r", "", $cert);
1149
	$key = str_replace("\r", "", $key);
1150
	$ca = str_replace("\r", "", $ca);
1151

    
1152
	$cert = str_replace("\n\n", "\n", $cert);
1153
	$key = str_replace("\n\n", "\n", $key);
1154
	$ca = str_replace("\n\n", "\n", $ca);
1155

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

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

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

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

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

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

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

    
1231
	return 0;
1232

    
1233
}
1234

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

    
1242
	$syscfg = $config['system'];
1243

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

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

    
1262
	conf_mount_rw();
1263

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

    
1267
	mwexec("sync");
1268
	conf_mount_ro();
1269

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

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

    
1278
	if (!file_exists($serialport))
1279
		return false;
1280

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

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

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

    
1307
	conf_mount_ro();
1308

    
1309
	return true;
1310
}
1311

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

    
1318
	if ($g['platform'] == 'jail')
1319
		return;
1320

    
1321
	safe_mkdir($statsdir);
1322

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

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

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

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

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

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

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

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

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

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

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

    
1400
function sync_system_time() {
1401
	global $config, $g;
1402

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

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

    
1416
function system_halt() {
1417
	global $g;
1418

    
1419
	system_reboot_cleanup();
1420

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

    
1424
function system_reboot() {
1425
	global $g;
1426

    
1427
	system_reboot_cleanup();
1428

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

    
1432
function system_reboot_sync() {
1433
	global $g;
1434

    
1435
	system_reboot_cleanup();
1436

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

    
1440
function system_reboot_cleanup() {
1441
	global $config, $cpzone;
1442

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

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

    
1464
	if ($early)
1465
		$cmdn = "earlyshellcmd";
1466
	else
1467
		$cmdn = "shellcmd";
1468

    
1469
	if (is_array($config['system'][$cmdn])) {
1470

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

    
1476
	} elseif($config['system'][$cmdn] <> "") {
1477

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

    
1481
	}
1482
}
1483

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

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

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

    
1505
	$dmesg = "";
1506
	exec("/sbin/dmesg", $dmesg);
1507

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

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

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

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

    
1525
	fclose($fd);
1526

    
1527
	return 0;
1528
}
1529

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

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

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

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

    
1569
	activate_sysctls();	
1570

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

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

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

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

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

    
1619
	$specplatform = system_identify_specific_platform();
1620

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

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

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

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

    
1636

    
1637
EOD;
1638
		
1639
		reset_factory_defaults();
1640
		system_reboot_sync();
1641
		exit(0);
1642
	}
1643

    
1644
	return 0;
1645
}
1646

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

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

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

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

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