Project

General

Profile

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

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

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

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

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

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

    
32
/*
33
	pfSense_BUILDER_BINARIES:	/usr/sbin/powerd	/usr/bin/killall	/sbin/sysctl	/sbin/route
34
	pfSense_BUILDER_BINARIES:	/bin/hostname	/bin/ls	/usr/sbin/syslogd	
35
	pfSense_BUILDER_BINARIES:	/usr/sbin/pccardd	/usr/local/sbin/lighttpd	/bin/chmod 	/bin/mkdir
36
	pfSense_BUILDER_BINARIES:	/usr/bin/tar		/usr/local/bin/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
		$mode = "hadp";
51
		if (!empty($config['system']['powerd_mode']))
52
			$mode = $config['system']['powerd_mode'];
53
		mwexec("/usr/sbin/powerd -b $mode -a $mode");
54
	}
55
}
56

    
57
function get_default_sysctl_value($id) {
58
	global $sysctls;
59

    
60
	if (isset($sysctls[$id]))
61
		return $sysctls[$id];
62
}
63

    
64
function activate_sysctls() {
65
	global $config, $g;
66
	if ($g['platform'] == 'jail')
67
		return;
68
	exec("/sbin/sysctl net.enc.out.ipsec_bpf_mask=0x0001");
69
	exec("/sbin/sysctl net.enc.out.ipsec_filter_mask=0x0001");
70
	exec("/sbin/sysctl net.enc.in.ipsec_bpf_mask=0x0002");
71
	exec("/sbin/sysctl net.enc.in.ipsec_filter_mask=0x0002");
72

    
73
	if(is_array($config['sysctl'])) {
74
		foreach($config['sysctl']['item'] as $tunable) {
75
			if($tunable['value'] == "default") {
76
				$value = get_default_sysctl_value($tunable['tunable']);
77
				mwexec("/sbin/sysctl " . $tunable['tunable'] . "=\"" . $value .  "\"");
78
			} else { 
79
				mwexec("/sbin/sysctl " . $tunable['tunable'] . "=\"" . $tunable['value'] .  "\"");
80
			}
81
		}
82
	}
83
}
84

    
85
function system_resolvconf_generate($dynupdate = false) {
86
	global $config, $g;
87

    
88
	if(isset($config['system']['developerspew'])) {
89
		$mt = microtime();
90
		echo "system_resolvconf_generate() being called $mt\n";
91
	}
92

    
93
	$syscfg = $config['system'];
94

    
95
	// Do not create blank domain lines, it breaks tools like dig.
96
	if($syscfg['domain'])
97
		$resolvconf = "domain {$syscfg['domain']}\n";
98

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

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

    
122
	$dnslock = lock('resolvconf', LOCK_EX);
123

    
124
	$fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
125
	if (!$fd) {
126
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
127
		unlock($dnslock);
128
		return 1;
129
	}
130

    
131
	fwrite($fd, $resolvconf);
132
	fclose($fd);
133

    
134
	if (!$g['booting']) {
135
		/* restart dhcpd (nameservers may have changed) */
136
		if (!$dynupdate)
137
			services_dhcpd_configure();
138
	}
139

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

    
162
	unlock($dnslock);
163

    
164
	return 0;
165
}
166

    
167
function get_searchdomains() {
168
	global $config, $g;
169

    
170
	$master_list = array();
171
	
172
	// Read in dhclient nameservers
173
	$search_list = glob("/var/etc/searchdomain_*");
174
	if (is_array($search_lists)) {
175
		foreach($search_lists as $fdns) {
176
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
177
			if (!is_array($contents))
178
				continue;
179
			foreach ($contents as $dns) {
180
				if(is_hostname($dns)) 
181
					$master_list[] = $dns;
182
			}
183
		}
184
	}
185

    
186
	return $master_list;
187
}
188

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

    
207
	// Read in any extra nameservers
208
	if(file_exists("/var/etc/nameservers.conf")) {
209
		$dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
210
		if(is_array($dns_s)) {
211
			foreach($dns_s as $dns)
212
				if (is_ipaddr($dns))
213
					$master_list[] = $dns;
214
		}
215
	}
216

    
217
	return $master_list;
218
}
219

    
220
function system_hosts_generate() {
221
	global $config, $g;
222
	if(isset($config['system']['developerspew'])) {
223
		$mt = microtime();
224
		echo "system_hosts_generate() being called $mt\n";
225
	}
226

    
227
	$syscfg = $config['system'];
228
	$dnsmasqcfg = $config['dnsmasq'];
229

    
230
	if (!is_array($dnsmasqcfg['hosts'])) {
231
		$dnsmasqcfg['hosts'] = array();
232
	}
233
	$hostscfg = $dnsmasqcfg['hosts'];
234

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

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

    
256
	foreach ($hostscfg as $host) {
257
		if ($host['host'])
258
			$lhosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
259
		else
260
			$lhosts .= "{$host['ip']}	{$host['domain']}\n";
261
		if (!is_array($host['aliases']) || !is_array($host['aliases']['item']))
262
			continue;
263
		foreach ($host['aliases']['item'] as $alias) {
264
			if ($alias['host'])
265
				$lhosts .= "{$host['ip']}	{$alias['host']}.{$alias['domain']} {$alias['host']}\n";
266
			else
267
				$lhosts .= "{$host['ip']}	{$alias['domain']}\n";
268
		}
269
	}
270
	if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpd'])) {
271
		foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf)
272
			if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
273
					foreach ($dhcpifconf['staticmap'] as $host)
274
						if ($host['ipaddr'] && $host['hostname'])
275
							$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
276
	}
277
	if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpdv6'])) {
278
		foreach ($config['dhcpdv6'] as $dhcpif => $dhcpifconf)
279
			if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
280
					foreach ($dhcpifconf['staticmap'] as $host)
281
						if ($host['ipaddrv6'] && $host['hostname'])
282
							$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
283
	}
284

    
285
	if (isset($dnsmasqcfg['dhcpfirst']))
286
		$hosts .= $dhosts . $lhosts;
287
	else
288
		$hosts .= $lhosts . $dhosts;
289

    
290
	/*
291
	 * Do not remove this because dhcpleases monitors with kqueue it needs to be 
292
	 * killed before writing to hosts files.
293
	 */
294
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
295
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
296
                @unlink("{$g['varrun_path']}/dhcpleases.pid");
297
	}
298
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
299
	if (!$fd) {
300
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
301
		return 1;
302
	}
303
	fwrite($fd, $hosts);
304
	fclose($fd);
305

    
306
	system_dhcpleases_configure();
307

    
308
	return 0;
309
}
310

    
311
function system_dhcpleases_configure() {
312
	global $config, $g;
313
	
314
	if ($g['platform'] == 'jail')
315
		return;
316
	/* Start the monitoring process for dynamic dhcpclients. */
317
	if (isset($config['dnsmasq']['regdhcp'])) {
318
		/* Make sure we do not error out */
319
		mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db");
320
		if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases"))
321
			@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
322
		if (isvalidpid("{$g['varrun_path']}/dhcpleases.pid"))
323
			sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "HUP");
324
		else
325
			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");
326
	} else {
327
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
328
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
329
	}
330
}
331

    
332
function system_hostname_configure() {
333
	global $config, $g;
334
	if(isset($config['system']['developerspew'])) {
335
		$mt = microtime();
336
		echo "system_hostname_configure() being called $mt\n";
337
	}
338

    
339
	$syscfg = $config['system'];
340

    
341
	/* set hostname */
342
	$status = mwexec("/bin/hostname " .
343
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
344

    
345
    /* Setup host GUID ID.  This is used by ZFS. */
346
	mwexec("/etc/rc.d/hostid start");
347

    
348
	return $status;
349
}
350

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

    
360
	$gatewayip = "";
361
	$interfacegw = "";
362
	$foundgw = false;
363
	$gatewayipv6 = "";
364
	$interfacegwv6 = "";
365
	$foundgwv6 = false;
366
	/* tack on all the hard defined gateways as well */
367
	if (is_array($config['gateways']['gateway_item'])) {
368
		mwexec("/bin/rm {$g['tmp_path']}/*_defaultgw", true);
369
		foreach	($config['gateways']['gateway_item'] as $gateway) {
370
			if (isset($gateway['defaultgw']) && ((is_ipaddrv4($gateway['gateway'])) || ($gateway['gateway'] == "dynamic"))) {
371
				if(strstr($gateway['gateway'], ":"))
372
					break;
373
				if ($gateway['gateway'] == "dynamic")
374
					$gateway['gateway'] = get_interface_gateway($gateway['interface']);
375
				$gatewayip = $gateway['gateway'];
376
				$interfacegw = $gateway['interface'];
377
				if (!empty($interfacegw)) {
378
					$defaultif = get_real_interface($gateway['interface']);
379
					if ($defaultif)
380
						@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gatewayip);
381
				}
382
				$foundgw = true;
383
				break;
384
			}
385
		}
386
		foreach	($config['gateways']['gateway_item'] as $gateway) {
387
			if (isset($gateway['defaultgw']) && ((is_ipaddrv6($gateway['gateway'])) || ($gateway['gateway'] == "dynamic6"))) {
388
				if ($gateway['gateway'] == "dynamic6")
389
					$gateway['gateway'] = get_interface_gateway_v6($gateway['interface']);
390
				$gatewayipv6 = $gateway['gateway'];
391
				$interfacegwv6 = $gateway['interface'];
392
				if (!empty($interfacegwv6)) {
393
					$defaultifv6 = get_real_interface($gateway['interface']);
394
					if ($defaultifv6)
395
						@file_put_contents("{$g['tmp_path']}/{$defaultifv6}_defaultgwv6", $gatewayipv6);
396
				}
397
				$foundgwv6 = true;
398
				break;
399
			}
400
		}
401
	}
402
	if ($foundgw == false) {
403
		$defaultif = get_real_interface("wan");
404
		$interfacegw = "wan";
405
		$gatewayip = get_interface_gateway("wan");
406
		@touch("{$g['tmp_path']}/{$defaultif}_defaultgw");
407
	}	
408
	if ($foundgwv6 == false) {
409
		$defaultifv6 = get_real_interface("wan");
410
		$interfacegwv6 = "wan";
411
		$gatewayipv6 = get_interface_gateway_v6("wan");
412
		@touch("{$g['tmp_path']}/{$defaultif}_defaultgwv6");
413
	}
414
	$dont_add_route = false;
415
	/* if OLSRD is enabled, allow WAN to house DHCP. */
416
	if($config['installedpackages']['olsrd']) {
417
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
418
			if(($olsrd['enabledyngw'] == "on") && ($olsrd['enable'] == "on")) {
419
				$dont_add_route = true;
420
				log_error(sprintf(gettext("Not adding default route because OLSR dynamic gateway is enabled.")));
421
				break;
422
			}
423
		}
424
	}
425

    
426
	if ($dont_add_route == false ) {
427
		if (!empty($interface) && $interface != $interfacegw)
428
			;
429
		else if (($interfacegw <> "bgpd") && (is_ipaddrv4($gatewayip))) {
430
			log_error("ROUTING: setting default route to $gatewayip");
431
			mwexec("/sbin/route change -inet default " . escapeshellarg($gatewayip));
432
		}
433

    
434
		if (!empty($interface) && $interface != $interfacegwv6)
435
			;
436
		else if (($interfacegwv6 <> "bgpd") && (is_ipaddrv6($gatewayipv6))) {
437
			if(preg_match("/fe80::/i", $gatewayipv6))
438
				$ifscope = "%{$defaultifv6}";
439
			log_error("ROUTING: setting IPv6 default route to {$gatewayipv6}{$ifscope}");
440
			mwexec("/sbin/route change -inet6 default " . escapeshellarg($gatewayipv6) ."{$ifscope}");
441
		}
442
	}
443

    
444
	$static_routes = get_staticroutes();
445
	if (count($static_routes)) {
446
		$gateways_arr = return_gateways_array(false, true);
447

    
448
		foreach ($static_routes as $rtent) {
449
			$gatewayip = "";
450
			if (empty($gateways_arr[$rtent['gateway']])) {
451
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
452
				continue;
453
			}
454
			$gateway = $gateways_arr[$rtent['gateway']];
455
			if (!empty($interface) && $interface != $gateway['friendlyiface'])
456
				continue;
457

    
458
			if(isset($rtent['disabled'])) {
459
				mwexec("/sbin/route delete " . escapeshellarg($rtent['network']), true);
460
				continue;
461
			}
462

    
463
			$gatewayip = $gateway['gateway'];
464
			$interfacegw = $gateway['interface'];
465

    
466
			if(is_ipaddrv6($gatewayip)) {
467
				$inetfamily = "-inet6";
468
			} else {
469
				$inetfamily = "-inet";
470
			}
471
			$blackhole = "";
472
			if(preg_match("/^Null/i", $rtent['gateway']))
473
				$blackhole = "-blackhole";
474

    
475
			if (is_ipaddr($gatewayip) && ((is_ipaddrv6($gatewayip) && is_subnetv6($rtent['network'])) || (is_ipaddrv4($gatewayip) && is_subnetv4($rtent['network'])))) {
476
				mwexec("/sbin/route change {$inetfamily} {$blackhole} " . escapeshellarg($rtent['network']) .
477
					" " . escapeshellarg($gatewayip));
478
			} else if (!empty($interfacegw) &&  ((is_ipaddrv6($gatewayip) && is_subnetv6($rtent['network'])) || (is_ipaddrv4($gatewayip) && is_subnetv4($rtent['network'])))) {
479
				mwexec("/sbin/route change {$inetfamily} {$blackhole} " . escapeshellarg($rtent['network']) .
480
					" -iface " . escapeshellarg($interfacegw));
481
			}
482
		}
483
	}
484

    
485
	return 0;
486
}
487

    
488
function system_routing_enable() {
489
	global $config, $g;
490
	if(isset($config['system']['developerspew'])) {
491
		$mt = microtime();
492
		echo "system_routing_enable() being called $mt\n";
493
	}
494

    
495
	mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
496
	mwexec("/sbin/sysctl net.inet6.ip6.forwarding=1");
497
	return;
498
}
499

    
500
function system_syslogd_fixup_server($server) {
501
	/* If it's an IPv6 IP alone, encase it in brackets */
502
	if (is_ipaddrv6($server))
503
		return "[$server]";
504
	else
505
		return $server;
506
}
507

    
508
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
509
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
510
	$facility .= " ".
511
	$remote_servers = "";
512
	$pad_to  = 56;
513
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
514
	if($syslogcfg['remoteserver'])
515
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
516
	if($syslogcfg['remoteserver2'])
517
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
518
	if($syslogcfg['remoteserver3'])
519
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
520
	return $remote_servers;
521
}
522

    
523
function system_syslogd_start() {
524
	global $config, $g;
525
	if(isset($config['system']['developerspew'])) {
526
		$mt = microtime();
527
		echo "system_syslogd_start() being called $mt\n";
528
	}
529

    
530
	mwexec("/etc/rc.d/hostid start");
531

    
532
	$syslogcfg = $config['syslog'];
533

    
534
	if ($g['booting'])
535
		echo gettext("Starting syslog...");
536
	else
537
		killbypid("{$g['varrun_path']}/syslog.pid");
538

    
539
	if(is_process_running("syslogd"))
540
		mwexec('/bin/pkill syslogd');
541
	if(is_process_running("fifolog_writer"))
542
		mwexec('/bin/pkill fifolog_writer');
543
	
544
	// Define carious commands for logging
545
	$fifolog_create = "/usr/sbin/fifolog_create -s ";
546
	$fifolog_log = "|/usr/sbin/fifolog_writer ";
547
	$clog_create = "/usr/sbin/clog -i -s ";
548
	$clog_log = "%";
549

    
550
	// Which logging type are we using this week??
551
	if(isset($config['system']['usefifolog'])) {
552
		$log_directive = $fifolog_log;
553
		$log_create_directive = $fifolog_create;
554
	} else { // Defaults to CLOG
555
		$log_directive = $clog_log;
556
		$log_create_directive = $clog_create;
557
	}
558
	
559
	if (isset($syslogcfg)) {
560
		$separatelogfacilities = array('ntp','ntpd','ntpdate','racoon','openvpn','pptps','poes','l2tps','relayd','hostapd','dnsmasq','unbound','dhcpd','dhcrelay','apinger','radvd','routed','olsrd','zebra','ospfd','bgpd');
561
		$syslogconf = "";
562
		if($config['installedpackages']['package']) {
563
			foreach($config['installedpackages']['package'] as $package) {
564
				if($package['logging']) {
565
					array_push($separatelogfacilities, $package['logging']['facilityname']);
566
					mwexec("{$log_create_directive} 10240 {$g['varlog_path']}/{$package['logging']['logfilename']}");
567
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
568
				}
569
			}
570
		}
571
		$facilitylist = implode(',', array_unique($separatelogfacilities));
572
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd\n";
573
		if (!isset($syslogcfg['disablelocallogging']))
574
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
575

    
576
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
577
		if (!isset($syslogcfg['disablelocallogging'])) 
578
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
579

    
580
		$syslogconf .= "!ppp\n";
581
		if (!isset($syslogcfg['disablelocallogging'])) 
582
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
583

    
584
		$syslogconf .= "!pptps\n";
585
		if (!isset($syslogcfg['disablelocallogging'])) 
586
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/pptps.log\n";
587

    
588
		$syslogconf .= "!poes\n";
589
		if (!isset($syslogcfg['disablelocallogging'])) 
590
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
591

    
592
		$syslogconf .= "!l2tps\n";
593
		if (!isset($syslogcfg['disablelocallogging'])) 
594
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/l2tps.log\n";
595

    
596
		$syslogconf .= "!racoon\n";
597
		if (!isset($syslogcfg['disablelocallogging'])) 
598
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ipsec.log\n";
599
		if (isset($syslogcfg['vpn']))
600
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
601

    
602
		$syslogconf .= "!openvpn\n";
603
		if (!isset($syslogcfg['disablelocallogging'])) 
604
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/openvpn.log\n";
605
		if (isset($syslogcfg['vpn']))
606
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
607

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

    
614
		$syslogconf .= "!dnsmasq,unbound\n";
615
		if (!isset($syslogcfg['disablelocallogging']))
616
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
617
		if (isset($syslogcfg['apinger']))
618
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
619

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

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

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

    
638
		$syslogconf .= "!-{$facilitylist}\n";
639
		if (!isset($syslogcfg['disablelocallogging'])) 
640
			$syslogconf .= <<<EOD
641
local0.*							{$log_directive}{$g['varlog_path']}/filter.log
642
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
643
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
644
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
645
*.notice;kern.debug;lpr.info;mail.crit;daemon.none;		{$log_directive}{$g['varlog_path']}/system.log
646
news.err;local0.none;local3.none;local4.none;			{$log_directive}{$g['varlog_path']}/system.log
647
local7.none							{$log_directive}{$g['varlog_path']}/system.log
648
security.*							{$log_directive}{$g['varlog_path']}/system.log
649
auth.info;authpriv.info;daemon.info				{$log_directive}{$g['varlog_path']}/system.log
650
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
651
*.emerg								*
652

    
653
EOD;
654
		if (isset($syslogcfg['filter']))
655
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local0.*");
656
		if (isset($syslogcfg['vpn']))
657
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
658
		if (isset($syslogcfg['portalauth']))
659
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
660
		if (isset($syslogcfg['dhcp']))
661
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
662
		if (isset($syslogcfg['system'])) {
663
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.notice;kern.debug;lpr.info;mail.crit;");
664
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "news.err;local0.none;local3.none;local7.none");
665
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "security.*");
666
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "auth.info;authpriv.info;daemon.info");
667
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.emerg");
668
		}
669
		if (isset($syslogcfg['logall'])) {
670
			// Make everything mean everything, including facilities excluded above.
671
			$syslogconf .= "!*\n";
672
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
673
		}
674

    
675
		if (isset($syslogcfg['zmqserver'])) {
676
				$syslogconf .= <<<EOD
677
*.*								^{$syslogcfg['zmqserver']}
678

    
679
EOD;
680
		}
681
		/* write syslog.conf */		
682
		if (!@file_put_contents("{$g['varetc_path']}/syslog.conf", $syslogconf)) {
683
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
684
			unset($syslogconf);
685
			return 1;
686
		}
687
		unset($syslogconf);
688

    
689
		// Ensure that the log directory exists
690
		if (!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
691
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
692

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

    
695
	} else {
696
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c -l {$g['dhcpd_chroot_path']}/var/run/log");
697
	}
698

    
699
	if ($g['booting'])
700
		echo gettext("done.") . "\n";
701

    
702
	return $retval;
703
}
704

    
705
function system_pccard_start() {
706
	global $config, $g;
707
	if(isset($config['system']['developerspew'])) {
708
		$mt = microtime();
709
		echo "system_pccard_start() being called $mt\n";
710
	}
711

    
712
	if ($g['booting'])
713
		echo gettext("Initializing PCMCIA...");
714

    
715
	/* kill any running pccardd */
716
	killbypid("{$g['varrun_path']}/pccardd.pid");
717

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

    
721
	if ($g['booting']) {
722
		if ($res == 0)
723
			echo gettext("done.") . "\n";
724
		else
725
			echo gettext("failed!") . "\n";
726
	}
727

    
728
	return $res;
729
}
730

    
731

    
732
function system_webgui_start() {
733
	global $config, $g;
734

    
735
	if ($g['booting'])
736
		echo gettext("Starting webConfigurator...");
737

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

    
741
	sleep(1);
742

    
743
	chdir($g['www_path']);
744

    
745
	/* defaults */
746
	$portarg = "80";
747
	$crt = "";
748
	$key = "";
749
	$ca = "";
750

    
751
	/* non-standard port? */
752
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
753
		$portarg = "{$config['system']['webgui']['port']}";
754

    
755
	if ($config['system']['webgui']['protocol'] == "https") {
756
		// Ensure that we have a webConfigurator CERT
757
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
758
		if(!is_array($cert) && !$cert['crt'] && !$cert['prv']) {
759
			if (!is_array($config['ca']))
760
				$config['ca'] = array();
761
			$a_ca =& $config['ca'];
762
			if (!is_array($config['cert']))
763
				$config['cert'] = array();
764
			$a_cert =& $config['cert'];
765
			log_error("Creating SSL Certificate for this host");
766
			$cert = array();
767
			$cert['refid'] = uniqid();
768
			$cert['descr'] = gettext("webConfigurator default");
769
			mwexec("/usr/local/bin/openssl genrsa 1024 > {$g['tmp_path']}/ssl.key");
770
			mwexec("/usr/local/bin/openssl req -new -x509 -nodes -sha256 -days 2000 -key {$g['tmp_path']}/ssl.key > {$g['tmp_path']}/ssl.crt");
771
			$crt = file_get_contents("{$g['tmp_path']}/ssl.crt");
772
			$key = file_get_contents("{$g['tmp_path']}/ssl.key");
773
			unlink("{$g['tmp_path']}/ssl.key");
774
			unlink("{$g['tmp_path']}/ssl.crt");
775
			cert_import($cert, $crt, $key);
776
			$a_cert[] = $cert;
777
			$config['system']['webgui']['ssl-certref'] = $cert['refid'];
778
			write_config(gettext("Importing HTTPS certificate"));
779
			if(!$config['system']['webgui']['port'])
780
				$portarg = "443";
781
			$ca = ca_chain($cert);
782
		} else {
783
			$crt = base64_decode($cert['crt']);
784
			$key = base64_decode($cert['prv']);
785
			if(!$config['system']['webgui']['port'])
786
				$portarg = "443";
787
			$ca = ca_chain($cert);
788
		}
789
	}
790

    
791
	/* generate lighttpd configuration */
792
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
793
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
794
		"cert.pem", "ca.pem");
795

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

    
799
	if ($g['booting']) {
800
		if ($res == 0)
801
			echo gettext("done.") . "\n";
802
		else
803
			echo gettext("failed!") . "\n";
804
	}
805

    
806
	return $res;
807
}
808

    
809
function system_generate_lighty_config($filename,
810
	$cert,
811
	$key,
812
	$ca,
813
	$pid_file,
814
	$port = 80,
815
	$document_root = "/usr/local/www/",
816
	$cert_location = "cert.pem",
817
	$ca_location = "ca.pem",
818
	$captive_portal = false) {
819

    
820
	global $config, $g;
821

    
822
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
823
		mkdir("{$g['tmp_path']}/lighttpdcompress");
824

    
825
	if(isset($config['system']['developerspew'])) {
826
		$mt = microtime();
827
		echo "system_generate_lighty_config() being called $mt\n";
828
	}
829

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

    
834
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
835
		if (empty($maxprocperip))
836
			$maxprocperip = 10;
837
		$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
838

    
839
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
840
		exec("mkdir -p {$g['tmp_path']}/captiveportal");
841
		exec("chmod a-w {$g['tmp_path']}/captiveportal");
842
		$server_max_request_size = "server.max-request-size    = 384";
843
		$cgi_config = "";
844
	} else {
845
		$captiveportal = ",\"mod_cgi\"";
846
		$captive_portal_rewrite = "";
847
		$captive_portal_mod_evasive = "";
848
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
849
		$server_max_request_size = "server.max-request-size    = 2097152";
850
		$cgi_config = "cgi.assign                 = ( \".cgi\" => \"\" )";
851
	}
852
	
853
	if (empty($port))
854
		$lighty_port = "80";
855
	else
856
		$lighty_port = $port;
857

    
858
	$memory = get_memory();
859
	$avail = $memory[1];
860

    
861
	// Determine web GUI process settings and take into account low memory systems
862
	if ($avail < 255)
863
		$max_procs = 1;
864
	else
865
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
866

    
867
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM 
868
	if ($captive_portal !== false)  {
869
		if ($avail > 135 and $avail < 256) {
870
			$max_procs += 1; // 2 worker processes
871
		} else if ($avail > 255 and $avail < 513) {
872
			$max_procs += 2; // 3 worker processes
873
		} else if ($avail > 512) {
874
			$max_procs += 4; // 6 worker processes
875
		}
876
		if ($max_procs > 1)
877
			$max_php_children = intval($max_procs/2);
878
		else
879
			$max_php_children = 1;
880

    
881
	} else {
882
		if ($avail < 78)
883
			$max_php_children = 0;
884
		else
885
			$max_php_children = 1;
886
	}
887

    
888
	if ($captive_portal !== false)
889
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi-{$captive_portal}.socket";
890
	else
891
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi.socket";
892

    
893
	$fastcgi_config = <<<EOD
894
#### fastcgi module
895
## read fastcgi.txt for more info
896
fastcgi.server = ( ".php" =>
897
	( "localhost" =>
898
		(
899
			"socket" => "{$fast_cgi_path}",
900
			"max-procs" => {$max_procs},
901
			"bin-environment" => (
902
				"PHP_FCGI_CHILDREN" => "{$max_php_children}",
903
				"PHP_FCGI_MAX_REQUESTS" => "500"
904
			),
905
			"bin-path" => "/usr/local/bin/php"
906
		)
907
	)
908
)
909

    
910
EOD;
911

    
912
	$lighty_config = <<<EOD
913
#
914
# lighttpd configuration file
915
#
916
# use a it as base for lighttpd 1.0.0 and above
917
#
918
############ Options you really have to take care of ####################
919

    
920
## FreeBSD!
921
server.event-handler	= "freebsd-kqueue"
922
server.network-backend 	= "writev"
923
#server.use-ipv6 = "enable"
924

    
925
## modules to load
926
server.modules              =   ( "mod_access", "mod_expire", "mod_compress", "mod_redirect",
927
	{$captiveportal}, "mod_fastcgi"
928
)
929

    
930
server.max-keep-alive-requests = 15
931
server.max-keep-alive-idle = 30
932

    
933
## a static document-root, for virtual-hosting take look at the
934
## server.virtual-* options
935
server.document-root        = "{$document_root}"
936
{$captive_portal_rewrite}
937

    
938
# Maximum idle time with nothing being written (php downloading)
939
server.max-write-idle = 999
940

    
941
## where to send error-messages to
942
server.errorlog-use-syslog="enable"
943

    
944
# files to check for if .../ is requested
945
server.indexfiles           = ( "index.php", "index.html",
946
                                "index.htm", "default.htm" )
947

    
948
# mimetype mapping
949
mimetype.assign             = (
950
  ".pdf"          =>      "application/pdf",
951
  ".sig"          =>      "application/pgp-signature",
952
  ".spl"          =>      "application/futuresplash",
953
  ".class"        =>      "application/octet-stream",
954
  ".ps"           =>      "application/postscript",
955
  ".torrent"      =>      "application/x-bittorrent",
956
  ".dvi"          =>      "application/x-dvi",
957
  ".gz"           =>      "application/x-gzip",
958
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
959
  ".swf"          =>      "application/x-shockwave-flash",
960
  ".tar.gz"       =>      "application/x-tgz",
961
  ".tgz"          =>      "application/x-tgz",
962
  ".tar"          =>      "application/x-tar",
963
  ".zip"          =>      "application/zip",
964
  ".mp3"          =>      "audio/mpeg",
965
  ".m3u"          =>      "audio/x-mpegurl",
966
  ".wma"          =>      "audio/x-ms-wma",
967
  ".wax"          =>      "audio/x-ms-wax",
968
  ".ogg"          =>      "audio/x-wav",
969
  ".wav"          =>      "audio/x-wav",
970
  ".gif"          =>      "image/gif",
971
  ".jpg"          =>      "image/jpeg",
972
  ".jpeg"         =>      "image/jpeg",
973
  ".png"          =>      "image/png",
974
  ".xbm"          =>      "image/x-xbitmap",
975
  ".xpm"          =>      "image/x-xpixmap",
976
  ".xwd"          =>      "image/x-xwindowdump",
977
  ".css"          =>      "text/css",
978
  ".html"         =>      "text/html",
979
  ".htm"          =>      "text/html",
980
  ".js"           =>      "text/javascript",
981
  ".asc"          =>      "text/plain",
982
  ".c"            =>      "text/plain",
983
  ".conf"         =>      "text/plain",
984
  ".text"         =>      "text/plain",
985
  ".txt"          =>      "text/plain",
986
  ".dtd"          =>      "text/xml",
987
  ".xml"          =>      "text/xml",
988
  ".mpeg"         =>      "video/mpeg",
989
  ".mpg"          =>      "video/mpeg",
990
  ".mov"          =>      "video/quicktime",
991
  ".qt"           =>      "video/quicktime",
992
  ".avi"          =>      "video/x-msvideo",
993
  ".asf"          =>      "video/x-ms-asf",
994
  ".asx"          =>      "video/x-ms-asf",
995
  ".wmv"          =>      "video/x-ms-wmv",
996
  ".bz2"          =>      "application/x-bzip",
997
  ".tbz"          =>      "application/x-bzip-compressed-tar",
998
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
999
 )
1000

    
1001
# Use the "Content-Type" extended attribute to obtain mime type if possible
1002
#mimetypes.use-xattr        = "enable"
1003

    
1004
## deny access the file-extensions
1005
#
1006
# ~    is for backupfiles from vi, emacs, joe, ...
1007
# .inc is often used for code includes which should in general not be part
1008
#      of the document-root
1009
url.access-deny             = ( "~", ".inc" )
1010

    
1011

    
1012
######### Options that are good to be but not neccesary to be changed #######
1013

    
1014
## bind to port (default: 80)
1015

    
1016
EOD;
1017

    
1018
	$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1019
	$lighty_config .= "server.port  = {$lighty_port}\n";
1020
	$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1021
	$lighty_config .= "\$SERVER[\"socket\"]  == \"[::]:{$lighty_port}\" { \n";
1022
	if($cert <> "" and $key <> "") {
1023
		$lighty_config .= "\n";
1024
		$lighty_config .= "## ssl configuration\n";
1025
		$lighty_config .= "ssl.engine = \"enable\"\n";
1026
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1027
		if($ca <> "")
1028
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1029
	}
1030
	$lighty_config .= " }\n";
1031

    
1032

    
1033
	$lighty_config .= <<<EOD
1034

    
1035
## error-handler for status 404
1036
#server.error-handler-404   = "/error-handler.html"
1037
#server.error-handler-404   = "/error-handler.php"
1038

    
1039
## to help the rc.scripts
1040
server.pid-file            = "/var/run/{$pid_file}"
1041

    
1042
## virtual directory listings
1043
server.dir-listing         = "disable"
1044

    
1045
## enable debugging
1046
debug.log-request-header   = "disable"
1047
debug.log-response-header  = "disable"
1048
debug.log-request-handling = "disable"
1049
debug.log-file-not-found   = "disable"
1050

    
1051
# gzip compression
1052
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1053
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1054

    
1055
{$server_upload_dirs}
1056

    
1057
{$server_max_request_size}
1058

    
1059
{$fastcgi_config}
1060

    
1061
{$cgi_config}
1062

    
1063
{$captive_portal_mod_evasive}
1064

    
1065
expire.url = (
1066
				"" => "access 50 hours",	
1067
        )
1068

    
1069
EOD;
1070

    
1071
	$cert = str_replace("\r", "", $cert);
1072
	$key = str_replace("\r", "", $key);
1073
	$ca = str_replace("\r", "", $ca);
1074

    
1075
	$cert = str_replace("\n\n", "\n", $cert);
1076
	$key = str_replace("\n\n", "\n", $key);
1077
	$ca = str_replace("\n\n", "\n", $ca);
1078

    
1079
	if($cert <> "" and $key <> "") {
1080
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1081
		if (!$fd) {
1082
			printf(gettext("Error: cannot open cert.pem in system_webgui_start().%s"), "\n");
1083
			return 1;
1084
		}
1085
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1086
		fwrite($fd, $cert);
1087
		fwrite($fd, "\n");
1088
		fwrite($fd, $key);
1089
		fclose($fd);
1090
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
1091
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1092
			if (!$fd) {
1093
				printf(gettext("Error: cannot open ca.pem in system_webgui_start().%s"), "\n");
1094
				return 1;
1095
			}
1096
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1097
			fwrite($fd, $ca);
1098
			fclose($fd);
1099
		}
1100
		$lighty_config .= "\n";
1101
		$lighty_config .= "## " . gettext("ssl configuration") . "\n";
1102
		$lighty_config .= "ssl.engine = \"enable\"\n";
1103
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1104

    
1105
		// Harden SSL a bit for PCI conformance testing
1106
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
1107
		$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";
1108

    
1109
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1110
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1111
	}
1112

    
1113
	// Add HTTP to HTTPS redirect	
1114
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1115
		if($lighty_port != "443") 
1116
			$redirectport = ":{$lighty_port}";
1117
		$lighty_config .= <<<EOD
1118
\$SERVER["socket"] == ":80" {
1119
	\$HTTP["host"] =~ "(.*)" {
1120
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1121
	}
1122
}
1123
EOD;
1124
	}
1125

    
1126
	$fd = fopen("{$filename}", "w");
1127
	if (!$fd) {
1128
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1129
		return 1;
1130
	}
1131
	fwrite($fd, $lighty_config);
1132
	fclose($fd);
1133

    
1134
	return 0;
1135

    
1136
}
1137

    
1138
function system_timezone_configure() {
1139
	global $config, $g;
1140
	if(isset($config['system']['developerspew'])) {
1141
		$mt = microtime();
1142
		echo "system_timezone_configure() being called $mt\n";
1143
	}
1144

    
1145
	$syscfg = $config['system'];
1146

    
1147
	if ($g['booting'])
1148
		echo gettext("Setting timezone...");
1149

    
1150
	/* extract appropriate timezone file */
1151
	$timezone = $syscfg['timezone'];
1152
	if (!$timezone)
1153
		$timezone = "Etc/UTC";
1154

    
1155
	conf_mount_rw();
1156

    
1157
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1158
		escapeshellarg($timezone) . " > /etc/localtime");
1159

    
1160
	mwexec("sync");
1161
	conf_mount_ro();
1162

    
1163
	if ($g['booting'])
1164
		echo gettext("done.") . "\n";
1165
}
1166

    
1167
function system_ntp_setup_gps($serialport) {
1168
	$gps_device = '/dev/gps0';
1169
	$serialport = '/dev/'.$serialport;
1170

    
1171
	if (!file_exists($serialport))
1172
		return false;
1173

    
1174
	conf_mount_rw();
1175
	// Create symlink that ntpd requires
1176
	unlink_if_exists($gps_device);
1177
	symlink($serialport, $gps_device);
1178

    
1179
	/* Send the following to the GPS port to initialize the GPS */
1180
	$gps_init = <<<EOF
1181
\$PUBX,40,GSV,0,0,0,0*59
1182
\$PUBX,40,GLL,0,0,0,0*5C
1183
\$PUBX,40,ZDA,0,0,0,0*44
1184
\$PUBX,40,VTG,0,0,0,0*5E
1185
\$PUBX,40,GSV,0,0,0,0*59
1186
\$PUBX,40,GSA,0,0,0,0*4E
1187
\$PUBX,40,GGA,0,0,0,0
1188
\$PUBX,40,TXT,0,0,0,0
1189
\$PUBX,40,RMC,0,0,0,0*46
1190
\$PUBX,41,1,0007,0003,4800,0
1191
\$PUBX,40,ZDA,1,1,1,1
1192
EOF;
1193
	file_put_contents("/tmp/gps.init", $gps_init);
1194
	`cat /tmp/gps.init > $serialport`;
1195

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

    
1200
	conf_mount_ro();
1201

    
1202
	return true;
1203
}
1204

    
1205
function system_ntp_configure($start_ntpd=true) {
1206
	global $config, $g;
1207
	$driftfile = "/var/db/ntpd.drift";
1208
	$statsdir = "/var/log/ntp";
1209
	$gps_device = '/dev/gps0';
1210

    
1211
	if ($g['platform'] == 'jail')
1212
		return;
1213

    
1214
	safe_mkdir($statsdir);
1215

    
1216
	$ntpcfg = "# \n";
1217
	$ntpcfg .= "# pfSense ntp configuration file \n";
1218
	$ntpcfg .= "# \n\n";
1219
	$ntpcfg .= "tinker panic 0 \n";
1220

    
1221
	if (!empty($config['ntpd']['gpsport'])
1222
		&& file_exists('/dev/'.$config['ntpd']['gpsport'])
1223
		&& system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1224
		$ntpcfg .= "# GPS Setup\n";
1225
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1226
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1227
		// Fall back to local clock if GPS is out of sync?
1228
		$ntpcfg .= "server 127.127.1.0\n";
1229
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1230
	}
1231

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

    
1237
	$ntpcfg .= "enable monitor\n";
1238
	$ntpcfg .= "enable stats\n";
1239
	$ntpcfg .= "statistics clockstats\n";
1240
	$ntpcfg .= "statsdir {$statsdir}\n";
1241
	$ntpcfg .= "logconfig =syncall +clockall\n";
1242
	$ntpcfg .= "driftfile {$driftfile}\n";
1243
	$ntpcfg .= "restrict default kod nomodify notrap nopeer\n";
1244
	$ntpcfg .= "restrict -6 default kod nomodify notrap nopeer\n";
1245

    
1246
	if (empty($config['ntpd']['interface']))
1247
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface']))
1248
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1249
		else
1250
			$interfaces = array();
1251
	else
1252
		$interfaces = explode(",", $config['ntpd']['interface']);
1253

    
1254
	if (is_array($interfaces) && count($interfaces)) {
1255
		$ntpcfg .= "interface ignore all\n";
1256
		foreach ($interfaces as $interface) {
1257
			if (!is_ipaddr($interface)) {
1258
				$interface = get_real_interface($interface);
1259
			}
1260
			$ntpcfg .= "interface listen {$interface}\n";
1261
		}
1262
	}
1263

    
1264
	/* open configuration for wrting or bail */
1265
	$fd = fopen("{$g['varetc_path']}/ntpd.conf","w");
1266
	if(!$fd) {
1267
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1268
		return;
1269
	}
1270
	fwrite($fd, $ntpcfg);
1271

    
1272
	/* slurp! */
1273
	fclose($fd);
1274

    
1275
	/* At bootup we just want to write out the config. */
1276
	if (!$start_ntpd)
1277
		return;
1278

    
1279
	/* if ntpd is running, kill it */
1280
	while(is_process_running("ntpd")) {
1281
		killbyname("ntpd");
1282
	}
1283

    
1284
	/* if /var/empty does not exist, create it */
1285
	if(!is_dir("/var/empty"))
1286
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1287

    
1288
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1289
	$oldset = array();
1290
	pcntl_sigprocmask(SIG_SETMASK, array(), $oldset);
1291
	exec("/usr/local/bin/ntpd -g -c {$g['varetc_path']}/ntpd.conf");
1292
	pcntl_sigprocmask(SIG_SETMASK, $oldset);
1293
	
1294
	// Note that we are starting up
1295
	log_error("NTPD is starting up.");
1296
	return;
1297
}
1298

    
1299
function sync_system_time() {
1300
	global $config, $g;
1301

    
1302
	if ($g['booting'])
1303
		echo gettext("Syncing system time before startup...");
1304

    
1305
	/* foreach through servers and write out to ntpd.conf */
1306
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1307
		mwexec("/usr/sbin/ntpdate -s $ts");
1308
	}
1309
	
1310
	if ($g['booting'])
1311
		echo gettext("done.") . "\n";
1312
	
1313
}
1314

    
1315
function system_halt() {
1316
	global $g;
1317

    
1318
	system_reboot_cleanup();
1319

    
1320
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1321
}
1322

    
1323
function system_reboot() {
1324
	global $g;
1325

    
1326
	system_reboot_cleanup();
1327

    
1328
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1329
}
1330

    
1331
function system_reboot_sync() {
1332
	global $g;
1333

    
1334
	system_reboot_cleanup();
1335

    
1336
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1337
}
1338

    
1339
function system_reboot_cleanup() {
1340
	mwexec("/usr/local/bin/beep.sh stop");
1341
	require_once("captiveportal.inc");
1342
	captiveportal_radius_stop_all();
1343
	require_once("voucher.inc");
1344
	voucher_save_db_to_config();
1345
	require_once("pkg-utils.inc");
1346
	stop_packages();
1347
}
1348

    
1349
function system_do_shell_commands($early = 0) {
1350
	global $config, $g;
1351
	if(isset($config['system']['developerspew'])) {
1352
		$mt = microtime();
1353
		echo "system_do_shell_commands() being called $mt\n";
1354
	}
1355

    
1356
	if ($early)
1357
		$cmdn = "earlyshellcmd";
1358
	else
1359
		$cmdn = "shellcmd";
1360

    
1361
	if (is_array($config['system'][$cmdn])) {
1362

    
1363
		/* *cmd is an array, loop through */
1364
		foreach ($config['system'][$cmdn] as $cmd) {
1365
			exec($cmd);
1366
		}
1367

    
1368
	} elseif($config['system'][$cmdn] <> "") {
1369

    
1370
		/* execute single item */
1371
		exec($config['system'][$cmdn]);
1372

    
1373
	}
1374
}
1375

    
1376
function system_console_configure() {
1377
	global $config, $g;
1378
	if(isset($config['system']['developerspew'])) {
1379
		$mt = microtime();
1380
		echo "system_console_configure() being called $mt\n";
1381
	}
1382

    
1383
	if (isset($config['system']['disableconsolemenu'])) {
1384
		touch("{$g['varetc_path']}/disableconsole");
1385
	} else {
1386
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1387
	}
1388
}
1389

    
1390
function system_dmesg_save() {
1391
	global $g;
1392
	if(isset($config['system']['developerspew'])) {
1393
		$mt = microtime();
1394
		echo "system_dmesg_save() being called $mt\n";
1395
	}
1396

    
1397
	$dmesg = "";
1398
	exec("/sbin/dmesg", $dmesg);
1399

    
1400
	/* find last copyright line (output from previous boots may be present) */
1401
	$lastcpline = 0;
1402

    
1403
	for ($i = 0; $i < count($dmesg); $i++) {
1404
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1405
			$lastcpline = $i;
1406
	}
1407

    
1408
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1409
	if (!$fd) {
1410
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1411
		return 1;
1412
	}
1413

    
1414
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1415
		fwrite($fd, $dmesg[$i] . "\n");
1416

    
1417
	fclose($fd);
1418

    
1419
	return 0;
1420
}
1421

    
1422
function system_set_harddisk_standby() {
1423
	global $g, $config;
1424
	if(isset($config['system']['developerspew'])) {
1425
		$mt = microtime();
1426
		echo "system_set_harddisk_standby() being called $mt\n";
1427
	}
1428

    
1429
	if (isset($config['system']['harddiskstandby'])) {
1430
		if ($g['booting']) {
1431
			echo gettext('Setting hard disk standby... ');
1432
		}
1433

    
1434
		$standby = $config['system']['harddiskstandby'];
1435
		// Check for a numeric value
1436
		if (is_numeric($standby)) {
1437
			// Sync the disk(s)
1438
			pfSense_sync();
1439
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1440
				// Reinitialize ATA-drives
1441
				mwexec('/usr/local/sbin/atareinit');
1442
				if ($g['booting']) {
1443
					echo gettext("done.") . "\n";
1444
				}
1445
			} else if ($g['booting']) {
1446
				echo gettext("failed!") . "\n";
1447
			}
1448
		} else if ($g['booting']) {
1449
			echo gettext("failed!") . "\n";
1450
		}
1451
	}
1452
}
1453

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

    
1461
	activate_sysctls();	
1462

    
1463
	if (isset($config['system']['sharednet'])) {
1464
		system_disable_arp_wrong_if();
1465
	}
1466
}
1467

    
1468
function system_disable_arp_wrong_if() {
1469
	global $config;
1470
	if(isset($config['system']['developerspew'])) {
1471
		$mt = microtime();
1472
		echo "system_disable_arp_wrong_if() being called $mt\n";
1473
	}
1474
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1475
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1476
}
1477

    
1478
function system_enable_arp_wrong_if() {
1479
	global $config;
1480
	if(isset($config['system']['developerspew'])) {
1481
		$mt = microtime();
1482
		echo "system_enable_arp_wrong_if() being called $mt\n";
1483
	}
1484
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1485
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1486
}
1487

    
1488
function enable_watchdog() {
1489
	global $config;
1490
	return;
1491
	$install_watchdog = false;
1492
	$supported_watchdogs = array("Geode");
1493
	$file = file_get_contents("/var/log/dmesg.boot");
1494
	foreach($supported_watchdogs as $sd) {
1495
		if(stristr($file, "Geode")) {
1496
			$install_watchdog = true;
1497
		}
1498
	}
1499
	if($install_watchdog == true) {
1500
		if(is_process_running("watchdogd"))
1501
			mwexec("/usr/bin/killall watchdogd", true);
1502
		exec("/usr/sbin/watchdogd");
1503
	}
1504
}
1505

    
1506
function system_check_reset_button() {
1507
	global $g;
1508
	if($g['platform'] != "nanobsd")
1509
		return 0;
1510

    
1511
	$specplatform = system_identify_specific_platform();
1512

    
1513
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1514
		return 0;
1515

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

    
1518
	if ($retval == 99) {
1519
		/* user has pressed reset button for 2 seconds - 
1520
		   reset to factory defaults */
1521
		echo <<<EOD
1522

    
1523
***********************************************************************
1524
* Reset button pressed - resetting configuration to factory defaults. *
1525
* The system will reboot after this completes.                        *
1526
***********************************************************************
1527

    
1528

    
1529
EOD;
1530
		
1531
		reset_factory_defaults();
1532
		system_reboot_sync();
1533
		exit(0);
1534
	}
1535

    
1536
	return 0;
1537
}
1538

    
1539
/* attempt to identify the specific platform (for embedded systems)
1540
   Returns an array with two elements:
1541
	name => platform string (e.g. 'wrap', 'alix' etc.)
1542
	descr => human-readable description (e.g. "PC Engines WRAP")
1543
*/
1544
function system_identify_specific_platform() {
1545
	global $g;
1546
	
1547
	if ($g['platform'] == 'generic-pc')
1548
		return array('name' => 'generic-pc', 'descr' => gettext("Generic PC"));
1549
	
1550
	if ($g['platform'] == 'generic-pc-cdrom')
1551
		return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)"));
1552
	
1553
	/* the rest of the code only deals with 'embedded' platforms */
1554
	if ($g['platform'] != 'nanobsd')
1555
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1556
	
1557
	$dmesg = system_get_dmesg_boot();
1558
	
1559
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1560
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
1561
	
1562
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1563
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
1564

    
1565
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1566
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1567
	
1568
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1569
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1570
		
1571
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1572
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1573
	
1574
	/* unknown embedded platform */
1575
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
1576
}
1577

    
1578
function system_get_dmesg_boot() {
1579
	global $g;
1580
		
1581
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1582
}
1583

    
1584
function get_possible_listen_ips() {
1585
	$interfaces = get_configured_interface_with_descr();
1586
	$carplist = get_configured_carp_interface_list();
1587
	$listenips = array();
1588
	foreach ($carplist as $cif => $carpip)
1589
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1590
	$aliaslist = get_configured_ip_aliases_list();
1591
	foreach ($aliaslist as $aliasip => $aliasif)
1592
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1593
	foreach ($interfaces as $iface => $ifacename) {
1594
		$tmp["name"]  = $ifacename;
1595
		$tmp["value"] = $iface;
1596
		$listenips[] = $tmp;
1597
	}
1598
	$tmp["name"]  = "Localhost";
1599
	$tmp["value"] = "lo0";
1600
	$listenips[] = $tmp;
1601
	return $listenips;
1602
}
1603

    
1604
?>
(52-52/67)