Project

General

Profile

Download (49.8 KB) Statistics
| Branch: | Tag: | Revision:
1 5b237745 Scott Ullrich
<?php
2 307cd525 Bill Marquette
/* $Id$ */
3 5b237745 Scott Ullrich
/*
4
	system.inc
5
	part of m0n0wall (http://m0n0.ch/wall)
6 0f282d7a Scott Ullrich
7 5b237745 Scott Ullrich
	Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
8
	All rights reserved.
9 0f282d7a Scott Ullrich
10 5b237745 Scott Ullrich
	Redistribution and use in source and binary forms, with or without
11
	modification, are permitted provided that the following conditions are met:
12 0f282d7a Scott Ullrich
13 5b237745 Scott Ullrich
	1. Redistributions of source code must retain the above copyright notice,
14
	   this list of conditions and the following disclaimer.
15 0f282d7a Scott Ullrich
16 5b237745 Scott Ullrich
	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 0f282d7a Scott Ullrich
20 5b237745 Scott Ullrich
	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 523855b0 Scott Ullrich
/*
33
	pfSense_BUILDER_BINARIES:	/usr/sbin/powerd	/usr/bin/killall	/sbin/sysctl	/sbin/route
34 b368b35a Ermal
	pfSense_BUILDER_BINARIES:	/bin/hostname	/bin/ls	/usr/sbin/syslogd	
35 523855b0 Scott Ullrich
	pfSense_BUILDER_BINARIES:	/usr/sbin/pccardd	/usr/local/sbin/lighttpd	/bin/chmod 	/bin/mkdir
36 cf180ccc jim-p
	pfSense_BUILDER_BINARIES:	/usr/bin/tar		/usr/local/bin/ntpd	/usr/sbin/ntpdate
37 c3b13d60 jim-p
	pfSense_BUILDER_BINARIES:	/usr/bin/nohup	/sbin/dmesg	/usr/local/sbin/atareinit	/sbin/kldload
38 523855b0 Scott Ullrich
	pfSense_MODULE:	utils
39
*/
40 0f282d7a Scott Ullrich
41 8e9fa41d Scott Ullrich
function activate_powerd() {
42
	global $config, $g;
43 7734aea6 Andrew Thompson
	if ($g['platform'] == 'jail')
44
		return;
45 53c210dd Cristian Feldman
	if(is_process_running("powerd"))
46
		exec("/usr/bin/killall powerd");
47 8e9fa41d Scott Ullrich
	if(isset($config['system']['powerd_enable'])) {
48 c3b13d60 jim-p
		if ($g["platform"] == "nanobsd")
49
			exec("/sbin/kldload cpufreq");
50 a358eec2 N0YB
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 8e9fa41d Scott Ullrich
	}
61
}
62
63 3a35f55f Scott Ullrich
function get_default_sysctl_value($id) {
64
	global $sysctls;
65 f3c91cb5 Erik Fonnesbeck
66
	if (isset($sysctls[$id]))
67
		return $sysctls[$id];
68 3a35f55f Scott Ullrich
}
69
70 6df9d7e3 Scott Ullrich
function activate_sysctls() {
71
	global $config, $g;
72 7734aea6 Andrew Thompson
	if ($g['platform'] == 'jail')
73
		return;
74 050fd8ad Ermal
	exec("/sbin/sysctl net.enc.out.ipsec_bpf_mask=0x0001");
75
	exec("/sbin/sysctl net.enc.out.ipsec_filter_mask=0x0001");
76 94395d86 Ermal
	exec("/sbin/sysctl net.enc.in.ipsec_bpf_mask=0x0002");
77
	exec("/sbin/sysctl net.enc.in.ipsec_filter_mask=0x0002");
78 99e88aa0 Ermal Luçi
79 3a35f55f Scott Ullrich
	if(is_array($config['sysctl'])) {
80 cac19f50 Scott Ullrich
		foreach($config['sysctl']['item'] as $tunable) {
81 b2d0140c Scott Ullrich
			if($tunable['value'] == "default") {
82
				$value = get_default_sysctl_value($tunable['tunable']);
83
				mwexec("/sbin/sysctl " . $tunable['tunable'] . "=\"" . $value .  "\"");
84
			} else { 
85 09f82b11 Administrator
				mwexec("/sbin/sysctl " . $tunable['tunable'] . "=\"" . $tunable['value'] .  "\"");
86 b2d0140c Scott Ullrich
			}
87 d0b461f5 sullrich
		}
88
	}
89 6df9d7e3 Scott Ullrich
}
90
91 5b237745 Scott Ullrich
function system_resolvconf_generate($dynupdate = false) {
92 c3f535c0 Seth Mos
	global $config, $g;
93
94
	if(isset($config['system']['developerspew'])) {
95
		$mt = microtime();
96
		echo "system_resolvconf_generate() being called $mt\n";
97
	}
98 ef217c69 Scott Ullrich
99 30cee7b2 Scott Ullrich
	$syscfg = $config['system'];
100 ef217c69 Scott Ullrich
101 53bbbf04 Scott Ullrich
	// Do not create blank domain lines, it breaks tools like dig.
102
	if($syscfg['domain'])
103
		$resolvconf = "domain {$syscfg['domain']}\n";
104 ef217c69 Scott Ullrich
105 af6576a8 jim-p
	if (isset($config['dnsmasq']['enable']) && !isset($config['system']['dnslocalhost']))
106 6c86a39f Ermal
		$resolvconf .= "nameserver 127.0.0.1\n";
107 8ac329da Ermal
108 30cee7b2 Scott Ullrich
	if (isset($syscfg['dnsallowoverride'])) {
109 c3f535c0 Seth Mos
		/* get dynamically assigned DNS servers (if any) */
110 86dcdfc9 Ermal
		$ns = array_unique(get_searchdomains());
111
		foreach($ns as $searchserver) {
112 8e866217 Ermal
			if($searchserver)
113 86dcdfc9 Ermal
				$resolvconf .= "search {$searchserver}\n";
114
		}
115 c3f535c0 Seth Mos
		$ns = array_unique(get_nameservers());
116
		foreach($ns as $nameserver) {
117 8e866217 Ermal
			if($nameserver)
118 c3f535c0 Seth Mos
				$resolvconf .= "nameserver $nameserver\n";
119
		}
120 30cee7b2 Scott Ullrich
	}
121 8e866217 Ermal
	if (is_array($syscfg['dnsserver'])) {
122 c3f535c0 Seth Mos
		foreach ($syscfg['dnsserver'] as $ns) {
123 8e866217 Ermal
			if ($ns)
124 c3f535c0 Seth Mos
				$resolvconf .= "nameserver $ns\n";
125 e180a6e3 Scott Ullrich
		}
126 c3f535c0 Seth Mos
	}
127 0f282d7a Scott Ullrich
128 d97ff036 Ermal
	$dnslock = lock('resolvconf', LOCK_EX);
129
130 e1daff07 Ermal
	$fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
131
	if (!$fd) {
132
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
133 d97ff036 Ermal
		unlock($dnslock);
134 e1daff07 Ermal
		return 1;
135
	}
136
137 30cee7b2 Scott Ullrich
	fwrite($fd, $resolvconf);
138
	fclose($fd);
139 0f282d7a Scott Ullrich
140 30cee7b2 Scott Ullrich
	if (!$g['booting']) {
141 c3f535c0 Seth Mos
		/* restart dhcpd (nameservers may have changed) */
142
		if (!$dynupdate)
143
			services_dhcpd_configure();
144 30cee7b2 Scott Ullrich
	}
145 ef217c69 Scott Ullrich
146 c3f535c0 Seth Mos
	/* setup static routes for DNS servers. */
147
	for ($dnscounter=1; $dnscounter<5; $dnscounter++) {
148
		/* setup static routes for dns servers */
149 c935003d Seth Mos
		$dnsgw = "dns{$dnscounter}gw";
150 c3f535c0 Seth Mos
		if (isset($config['system'][$dnsgw])) {
151 c935003d Seth Mos
			$gwname = $config['system'][$dnsgw];
152
			if (($gwname <> "") && ($gwname <> "none")) {
153
				$gatewayip = lookup_gateway_ip_by_name($gwname);
154
				if (is_ipaddrv4($gatewayip)) {
155 c3f535c0 Seth Mos
					/* dns server array starts at 0 */
156 b875f306 Scott Ullrich
					$dnscountermo = $dnscounter - 1;
157 4c41b626 Ermal
					mwexec("route change -host " . $syscfg['dnsserver'][$dnscountermo] . " {$gatewayip}");
158 b875f306 Scott Ullrich
				}
159 c935003d Seth Mos
				if (is_ipaddrv6($gatewayip)) {
160
					/* dns server array starts at 0 */
161
					$dnscountermo = $dnscounter - 1;
162 64a8dbf2 jim-p
					mwexec("route change -host -inet6 " . $syscfg['dnsserver'][$dnscountermo] . " {$gatewayip}");
163 c935003d Seth Mos
				}
164 b875f306 Scott Ullrich
			}
165 e180a6e3 Scott Ullrich
		}
166 c3f535c0 Seth Mos
	}
167 d97ff036 Ermal
168
	unlock($dnslock);
169
170 c3f535c0 Seth Mos
	return 0;
171 5b237745 Scott Ullrich
}
172
173 86dcdfc9 Ermal
function get_searchdomains() {
174
	global $config, $g;
175
176
	$master_list = array();
177
	
178
	// Read in dhclient nameservers
179 e1daff07 Ermal
	$search_list = glob("/var/etc/searchdomain_*");
180 86dcdfc9 Ermal
	if (is_array($search_lists)) {
181 807fd6cd Ermal
		foreach($search_lists 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 86dcdfc9 Ermal
		}
190
	}
191
192
	return $master_list;
193
}
194
195 3d00ccaa Scott Ullrich
function get_nameservers() {
196
	global $config, $g;
197
	$master_list = array();
198 30cee7b2 Scott Ullrich
	
199 2a1226ad Scott Ullrich
	// Read in dhclient nameservers
200 e1daff07 Ermal
	$dns_lists = glob("/var/etc/nameserver_*");
201 1033de74 Ermal
	if (is_array($dns_lists)) {
202 807fd6cd Ermal
		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 60951398 Scott Ullrich
		}
211 3d00ccaa Scott Ullrich
	}
212 2a1226ad Scott Ullrich
213
	// Read in any extra nameservers
214
	if(file_exists("/var/etc/nameservers.conf")) {
215 33818198 Ermal
		$dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
216 e1daff07 Ermal
		if(is_array($dns_s)) {
217 2a1226ad Scott Ullrich
			foreach($dns_s as $dns)
218 1033de74 Ermal
				if (is_ipaddr($dns))
219
					$master_list[] = $dns;
220 e1daff07 Ermal
		}
221 2a1226ad Scott Ullrich
	}
222
223 3d00ccaa Scott Ullrich
	return $master_list;
224
}
225
226 5b237745 Scott Ullrich
function system_hosts_generate() {
227 f19d3b7a Scott Ullrich
	global $config, $g;
228 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
229
		$mt = microtime();
230 dcf0598e Scott Ullrich
		echo "system_hosts_generate() being called $mt\n";
231 f19d3b7a Scott Ullrich
	}
232 0f282d7a Scott Ullrich
233 5b237745 Scott Ullrich
	$syscfg = $config['system'];
234
	$dnsmasqcfg = $config['dnsmasq'];
235
236
	if (!is_array($dnsmasqcfg['hosts'])) {
237
		$dnsmasqcfg['hosts'] = array();
238
	}
239
	$hostscfg = $dnsmasqcfg['hosts'];
240 0f282d7a Scott Ullrich
241 58db1fc4 Ermal
	$hosts = "127.0.0.1	localhost localhost.{$syscfg['domain']}\n";
242 aa994814 Andrew Thompson
	$lhosts = "";
243
	$dhosts = "";
244 a55e9c70 Ermal Lu?i
245 e5995f9d Ermal
	if ($config['interfaces']['lan']) {
246
		$cfgip = get_interface_ip("lan");
247 f38f8062 Ermal
		if (is_ipaddr($cfgip))
248
			$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
249 e5995f9d Ermal
	} else {
250
		$sysiflist = get_configured_interface_list();
251
		foreach ($sysiflist as $sysif) {
252
			if (!interface_has_gateway($sysif)) {
253
				$cfgip = get_interface_ip($sysif);
254
				if (is_ipaddr($cfgip)) {
255
					$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
256
					break;
257
				}
258
			}
259
		}
260 f38f8062 Ermal
	}
261 0f282d7a Scott Ullrich
262 5b237745 Scott Ullrich
	foreach ($hostscfg as $host) {
263
		if ($host['host'])
264 aa994814 Andrew Thompson
			$lhosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
265 5b237745 Scott Ullrich
		else
266 aa994814 Andrew Thompson
			$lhosts .= "{$host['ip']}	{$host['domain']}\n";
267 5db4d1eb jim-p
		if (!is_array($host['aliases']) || !is_array($host['aliases']['item']))
268
			continue;
269 5a2a8349 Lorenz Schori
		foreach ($host['aliases']['item'] as $alias) {
270
			if ($alias['host'])
271
				$lhosts .= "{$host['ip']}	{$alias['host']}.{$alias['domain']} {$alias['host']}\n";
272
			else
273
				$lhosts .= "{$host['ip']}	{$alias['domain']}\n";
274
		}
275 5b237745 Scott Ullrich
	}
276 da6155e0 Erik Fonnesbeck
	if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpd'])) {
277 6a01ea44 Bill Marquette
		foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf)
278
			if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
279 a56e787d Scott Ullrich
					foreach ($dhcpifconf['staticmap'] as $host)
280 6a01ea44 Bill Marquette
						if ($host['ipaddr'] && $host['hostname'])
281 aa994814 Andrew Thompson
							$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
282 4b2bf4fc smos
	}
283
	if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpdv6'])) {
284 7c6856f8 jim-p
		foreach ($config['dhcpdv6'] as $dhcpif => $dhcpifconf)
285
			if(is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable']))
286
					foreach ($dhcpifconf['staticmap'] as $host)
287
						if ($host['ipaddrv6'] && $host['hostname'])
288
							$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
289 a56e787d Scott Ullrich
	}
290 58db1fc4 Ermal
291 aa994814 Andrew Thompson
	if (isset($dnsmasqcfg['dhcpfirst']))
292
		$hosts .= $dhosts . $lhosts;
293
	else
294
		$hosts .= $lhosts . $dhosts;
295
296 58db1fc4 Ermal
	/*
297
	 * Do not remove this because dhcpleases monitors with kqueue it needs to be 
298
	 * killed before writing to hosts files.
299
	 */
300
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
301
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
302
                @unlink("{$g['varrun_path']}/dhcpleases.pid");
303
	}
304
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
305
	if (!$fd) {
306
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
307
		return 1;
308
	}
309 5b237745 Scott Ullrich
	fwrite($fd, $hosts);
310
	fclose($fd);
311 0f282d7a Scott Ullrich
312 24d619f5 Ermal
	system_dhcpleases_configure();
313
314
	return 0;
315
}
316
317
function system_dhcpleases_configure() {
318 15d456b9 gnhb
	global $config, $g;
319
	
320 7734aea6 Andrew Thompson
	if ($g['platform'] == 'jail')
321
		return;
322 956950de Ermal
	/* Start the monitoring process for dynamic dhcpclients. */
323
	if (isset($config['dnsmasq']['regdhcp'])) {
324
		/* Make sure we do not error out */
325 abdd01f5 Ermal
		mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db");
326
		if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases"))
327
			@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
328
		if (isvalidpid("{$g['varrun_path']}/dhcpleases.pid"))
329
			sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "HUP");
330 15d456b9 gnhb
		else
331
			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");
332
	} else {
333
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
334
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
335
	}
336 5b237745 Scott Ullrich
}
337
338
function system_hostname_configure() {
339 f19d3b7a Scott Ullrich
	global $config, $g;
340 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
341
		$mt = microtime();
342 dcf0598e Scott Ullrich
		echo "system_hostname_configure() being called $mt\n";
343 333f8ef0 Scott Ullrich
	}
344 0f282d7a Scott Ullrich
345 5b237745 Scott Ullrich
	$syscfg = $config['system'];
346 0f282d7a Scott Ullrich
347 5b237745 Scott Ullrich
	/* set hostname */
348 6bfccde7 Scott Ullrich
	$status = mwexec("/bin/hostname " .
349 5b237745 Scott Ullrich
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
350 6bfccde7 Scott Ullrich
351
    /* Setup host GUID ID.  This is used by ZFS. */
352
	mwexec("/etc/rc.d/hostid start");
353
354
	return $status;
355 5b237745 Scott Ullrich
}
356
357 1ea67f2e Ermal
function system_routing_configure($interface = "") {
358 962625aa Ermal
	global $config, $g;
359 7734aea6 Andrew Thompson
	if ($g['platform'] == 'jail')
360
		return;
361 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
362
		$mt = microtime();
363 dcf0598e Scott Ullrich
		echo "system_routing_configure() being called $mt\n";
364 58c7450e Scott Ullrich
	}
365 333f8ef0 Scott Ullrich
366 a529aced Ermal
	$gatewayip = "";
367
	$interfacegw = "";
368 3cc07282 Ermal
	$foundgw = false;
369 5a5413bb Seth Mos
	$gatewayipv6 = "";
370
	$interfacegwv6 = "";
371
	$foundgwv6 = false;
372 a529aced Ermal
	/* tack on all the hard defined gateways as well */
373
	if (is_array($config['gateways']['gateway_item'])) {
374 d499c12b Ermal
		mwexec("/bin/rm {$g['tmp_path']}/*_defaultgw", true);
375 a529aced Ermal
		foreach	($config['gateways']['gateway_item'] as $gateway) {
376 f934af33 Ermal
			if (isset($gateway['defaultgw'])) {
377
				if ($gateway['ipprotocol'] != "inet6" && (is_ipaddrv4($gateway['gateway']) || $gateway['gateway'] == "dynamic")) {
378
					if(strstr($gateway['gateway'], ":"))
379
						continue;
380
					if ($gateway['gateway'] == "dynamic")
381
						$gateway['gateway'] = get_interface_gateway($gateway['interface']);
382 9d595f6a Ermal
					$gatewayip = $gateway['gateway'];
383 f934af33 Ermal
					if (!empty($gateway['interface'])) {
384
						$defaultif = get_real_interface($gateway['interface']);
385
						if ($defaultif)
386
							@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gateway['gateway']);
387
					}
388
					$foundgw = true;
389
				} else if ($gateway['ipprotocol'] == "inet6" && (is_ipaddrv6($gateway['gateway']) || $gateway['gateway'] == "dynamic6")) {
390
					if ($gateway['gateway'] == "dynamic6")
391
						$gateway['gateway'] = get_interface_gateway_v6($gateway['interface']);
392 9d595f6a Ermal
					$gatewayipv6 = $gateway['gateway'];
393 f934af33 Ermal
					if (!empty($gateway['interface'])) {
394
						$defaultifv6 = get_real_interface($gateway['interface']);
395
						if ($defaultifv6)
396
							@file_put_contents("{$g['tmp_path']}/{$defaultifv6}_defaultgwv6", $gateway['gateway']);
397
					}
398
					$foundgwv6 = true;
399 924f202e Ermal
				}
400 a529aced Ermal
			}
401 f934af33 Ermal
			if ($foundgw === true && $foundgwv6 === true)
402 5a5413bb Seth Mos
				break;
403
		}
404 b24bda08 Scott Ullrich
	}
405 3cc07282 Ermal
	if ($foundgw == false) {
406
		$defaultif = get_real_interface("wan");
407
		$interfacegw = "wan";
408
		$gatewayip = get_interface_gateway("wan");
409
		@touch("{$g['tmp_path']}/{$defaultif}_defaultgw");
410
	}	
411 5a5413bb Seth Mos
	if ($foundgwv6 == false) {
412 4f332466 Seth Mos
		$defaultifv6 = get_real_interface("wan");
413
		$interfacegwv6 = "wan";
414
		$gatewayipv6 = get_interface_gateway_v6("wan");
415 5a5413bb Seth Mos
		@touch("{$g['tmp_path']}/{$defaultif}_defaultgwv6");
416 17a5b095 Seth Mos
	}
417 d173230c Seth Mos
	$dont_add_route = false;
418
	/* if OLSRD is enabled, allow WAN to house DHCP. */
419 f934af33 Ermal
	if (is_array($config['installedpackages']['olsrd'])) {
420 d173230c Seth Mos
		foreach($config['installedpackages']['olsrd']['config'] as $olsrd) {
421 f581cb10 Chris Buechler
			if(($olsrd['enabledyngw'] == "on") && ($olsrd['enable'] == "on")) {
422 d173230c Seth Mos
				$dont_add_route = true;
423 f581cb10 Chris Buechler
				log_error(sprintf(gettext("Not adding default route because OLSR dynamic gateway is enabled.")));
424 6e17413e Ermal Lu?i
				break;
425 d173230c Seth Mos
			}
426
		}
427
	}
428 07b54e8c smos
429 1ea67f2e Ermal
	if ($dont_add_route == false ) {
430 8d29cef4 Ermal
		if (!empty($interface) && $interface != $interfacegw)
431 1ea67f2e Ermal
			;
432 5a5413bb Seth Mos
		else if (($interfacegw <> "bgpd") && (is_ipaddrv4($gatewayip))) {
433 b368b35a Ermal
			log_error("ROUTING: setting default route to $gatewayip");
434
			mwexec("/sbin/route change -inet default " . escapeshellarg($gatewayip));
435 d173230c Seth Mos
		}
436
437 17a5b095 Seth Mos
		if (!empty($interface) && $interface != $interfacegwv6)
438 5a5413bb Seth Mos
			;
439
		else if (($interfacegwv6 <> "bgpd") && (is_ipaddrv6($gatewayipv6))) {
440 8be135cd Ermal
			$ifscope = "";
441 26ecc19c smos
			if(preg_match("/fe80::/i", $gatewayipv6))
442
				$ifscope = "%{$defaultifv6}";
443 ea91a8c0 smos
			log_error("ROUTING: setting IPv6 default route to {$gatewayipv6}{$ifscope}");
444 02091d23 smos
			mwexec("/sbin/route change -inet6 default " . escapeshellarg($gatewayipv6) ."{$ifscope}");
445 5a5413bb Seth Mos
		}
446
	}
447
448 f898c1a9 jim-p
	$static_routes = get_staticroutes();
449
	if (count($static_routes)) {
450 6fdea6a2 smos
		$gateways_arr = return_gateways_array(false, true);
451 0f282d7a Scott Ullrich
452 f898c1a9 jim-p
		foreach ($static_routes as $rtent) {
453 a529aced Ermal
			$gatewayip = "";
454 a02708b1 Ermal
			if (empty($gateways_arr[$rtent['gateway']])) {
455 4a896b86 Carlos Eduardo Ramos
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
456 a529aced Ermal
				continue;
457
			}
458 a02708b1 Ermal
			$gateway = $gateways_arr[$rtent['gateway']];
459 1801c223 Ermal
			if (!empty($interface) && $interface != $gateway['friendlyiface'])
460 a02708b1 Ermal
				continue;
461 9740fad8 Seth Mos
462 8be135cd Ermal
			/* XXX: This is a bit dangerous in case of routing daemons!? */
463 bfe407e5 Warren Baker
			if(isset($rtent['disabled'])) {
464
				mwexec("/sbin/route delete " . escapeshellarg($rtent['network']), true);
465
				continue;
466
			}
467
468 a02708b1 Ermal
			$gatewayip = $gateway['gateway'];
469
			$interfacegw = $gateway['interface'];
470 a529aced Ermal
471 1e5f47bb smos
			$blackhole = "";
472 8be135cd Ermal
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 3)))
473 1e5f47bb smos
				$blackhole = "-blackhole";
474
475 8be135cd Ermal
			if (is_subnetv6($rtent['network'])) {
476
				if (is_ipaddrv6($gatewayip))
477
					mwexec("/sbin/route change -inet6 {$blackhole} " . escapeshellarg($rtent['network']) .
478
						" " . escapeshellarg($gatewayip));
479
				else if (!empty($interfacegw))
480
					mwexec("/sbin/route change -inet6 {$blackhole} " . escapeshellarg($rtent['network']) .
481
						" -iface " . escapeshellarg($interfacegw));
482
			 } else if (is_subnetv4($rtent['network'])) {
483
				if (is_ipaddrv4($gatewayip))
484
					mwexec("/sbin/route change -inet {$blackhole} " . escapeshellarg($rtent['network']) .
485
						" " . escapeshellarg($gatewayip));
486
				else if (!empty($interfacegw))
487
					mwexec("/sbin/route change -inet {$blackhole} " . escapeshellarg($rtent['network']) .
488
						" -iface " . escapeshellarg($interfacegw));
489 7a98edde Seth Mos
			}
490 5b237745 Scott Ullrich
		}
491 6a205b6a Ermal
		unset($gateways_arr);
492 5b237745 Scott Ullrich
	}
493 6a205b6a Ermal
	unset($static_routes);
494 67ee1ec5 Ermal Luçi
495 b9c501ea Seth Mos
	return 0;
496 5b237745 Scott Ullrich
}
497
498
function system_routing_enable() {
499 f19d3b7a Scott Ullrich
	global $config, $g;
500 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
501
		$mt = microtime();
502 dcf0598e Scott Ullrich
		echo "system_routing_enable() being called $mt\n";
503 58c7450e Scott Ullrich
	}
504 0f282d7a Scott Ullrich
505 6da3df4e Seth Mos
	mwexec("/sbin/sysctl net.inet.ip.forwarding=1");
506
	mwexec("/sbin/sysctl net.inet6.ip6.forwarding=1");
507
	return;
508 5b237745 Scott Ullrich
}
509
510 bd29bb7b jim-p
function system_syslogd_fixup_server($server) {
511
	/* If it's an IPv6 IP alone, encase it in brackets */
512
	if (is_ipaddrv6($server))
513
		return "[$server]";
514
	else
515
		return $server;
516
}
517
518 236524c2 jim-p
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
519
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
520
	$facility .= " ".
521
	$remote_servers = "";
522
	$pad_to  = 56;
523
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
524
	if($syslogcfg['remoteserver'])
525 bd29bb7b jim-p
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
526 236524c2 jim-p
	if($syslogcfg['remoteserver2'])
527 bd29bb7b jim-p
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
528 236524c2 jim-p
	if($syslogcfg['remoteserver3'])
529 bd29bb7b jim-p
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
530 236524c2 jim-p
	return $remote_servers;
531
}
532
533 5b237745 Scott Ullrich
function system_syslogd_start() {
534 f19d3b7a Scott Ullrich
	global $config, $g;
535 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
536
		$mt = microtime();
537 dcf0598e Scott Ullrich
		echo "system_syslogd_start() being called $mt\n";
538 58c7450e Scott Ullrich
	}
539 0f282d7a Scott Ullrich
540 1fd3fe31 Scott Ullrich
	mwexec("/etc/rc.d/hostid start");
541
542 5b237745 Scott Ullrich
	$syslogcfg = $config['syslog'];
543
544 0f282d7a Scott Ullrich
	if ($g['booting'])
545 4a896b86 Carlos Eduardo Ramos
		echo gettext("Starting syslog...");
546 5b237745 Scott Ullrich
	else
547
		killbypid("{$g['varrun_path']}/syslog.pid");
548 0f282d7a Scott Ullrich
549 100f3e71 Ermal
	if (is_process_running("syslogd"))
550 236524c2 jim-p
		mwexec('/bin/pkill syslogd');
551 100f3e71 Ermal
	if (is_process_running("fifolog_writer"))
552 236524c2 jim-p
		mwexec('/bin/pkill fifolog_writer');
553 7ee97cb3 Scott Ullrich
554
	// Which logging type are we using this week??
555 100f3e71 Ermal
	if (isset($config['system']['disablesyslogclog'])) {
556
		$log_directive = "";
557
		$log_create_directive = "/usr/bin/touch ";
558
		$log_size = "";
559
	} else if (isset($config['system']['usefifolog'])) {
560
		$log_directive = "|/usr/sbin/fifolog_writer ";
561
		$log_size = "10240";
562
		$log_create_directive = "/usr/sbin/fifolog_create -s ";
563 7ee97cb3 Scott Ullrich
	} else { // Defaults to CLOG
564 100f3e71 Ermal
		$log_directive = "%";
565
		$log_size = "10240";
566
		$log_create_directive = "/usr/sbin/clog -i -s ";
567 7ee97cb3 Scott Ullrich
	}
568
	
569 88ebd635 Scott Ullrich
	if (isset($syslogcfg)) {
570 e0c45357 jim-p
		$separatelogfacilities = array('ntp','ntpd','ntpdate','racoon','openvpn','pptps','poes','l2tps','relayd','hostapd','dnsmasq','unbound','dhcpd','dhcrelay','apinger','radvd','routed','olsrd','zebra','ospfd','bgpd');
571 344016a8 Ermal
		$syslogconf = "";
572 a728d2ea Colin Smith
		if($config['installedpackages']['package']) {
573 0d9d2a1b Scott Ullrich
			foreach($config['installedpackages']['package'] as $package) {
574
				if($package['logging']) {
575 d589cccf Warren Baker
					array_push($separatelogfacilities, $package['logging']['facilityname']);
576 100f3e71 Ermal
					mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
577 eeb52fea Warren Baker
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
578 a728d2ea Colin Smith
				}
579 0d9d2a1b Scott Ullrich
			}
580
		}
581 d2834563 Scott Ullrich
		$facilitylist = implode(',', array_unique($separatelogfacilities));
582 e0c45357 jim-p
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd\n";
583
		if (!isset($syslogcfg['disablelocallogging']))
584
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
585
586
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
587 0d9d2a1b Scott Ullrich
		if (!isset($syslogcfg['disablelocallogging'])) 
588 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
589
590 295e19dd Scott Ullrich
		$syslogconf .= "!ppp\n";
591
		if (!isset($syslogcfg['disablelocallogging'])) 
592 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
593
594 a6607b5f jim-p
		$syslogconf .= "!pptps\n";
595 328efaba Ermal
		if (!isset($syslogcfg['disablelocallogging'])) 
596 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/pptps.log\n";
597
598 a6607b5f jim-p
		$syslogconf .= "!poes\n";
599 328efaba Ermal
		if (!isset($syslogcfg['disablelocallogging'])) 
600 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
601
602 a6607b5f jim-p
		$syslogconf .= "!l2tps\n";
603 328efaba Ermal
		if (!isset($syslogcfg['disablelocallogging'])) 
604 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/l2tps.log\n";
605
606 0260caec Scott Ullrich
		$syslogconf .= "!racoon\n";
607 0d9d2a1b Scott Ullrich
		if (!isset($syslogcfg['disablelocallogging'])) 
608 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ipsec.log\n";
609
		if (isset($syslogcfg['vpn']))
610
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
611
612 d2834563 Scott Ullrich
		$syslogconf .= "!openvpn\n";
613 0d9d2a1b Scott Ullrich
		if (!isset($syslogcfg['disablelocallogging'])) 
614 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/openvpn.log\n";
615
		if (isset($syslogcfg['vpn']))
616
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
617
618 7bc41b19 jim-p
		$syslogconf .= "!apinger\n";
619
		if (!isset($syslogcfg['disablelocallogging']))
620 e0977fed smos
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/gateways.log\n";
621
		if (isset($syslogcfg['apinger']))
622
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
623
624
		$syslogconf .= "!dnsmasq,unbound\n";
625
		if (!isset($syslogcfg['disablelocallogging']))
626
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
627
		if (isset($syslogcfg['apinger']))
628
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
629
630
		$syslogconf .= "!dhcpd,dhcrelay\n";
631
		if (!isset($syslogcfg['disablelocallogging']))
632
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/dhcpd.log\n";
633 236524c2 jim-p
		if (isset($syslogcfg['apinger']))
634
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
635
636 087a89f8 Chris Buechler
		$syslogconf .= "!relayd\n";
637 236524c2 jim-p
		if (!isset($syslogcfg['disablelocallogging']))
638
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/relayd.log\n";
639
		if (isset($syslogcfg['relayd']))
640
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
641
642 689eaa4d jim-p
		$syslogconf .= "!hostapd\n";
643 236524c2 jim-p
		if (!isset($syslogcfg['disablelocallogging']))
644
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
645
		if (isset($syslogcfg['hostapd']))
646
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
647
648 d2834563 Scott Ullrich
		$syslogconf .= "!-{$facilitylist}\n";
649 0d9d2a1b Scott Ullrich
		if (!isset($syslogcfg['disablelocallogging'])) 
650 5b237745 Scott Ullrich
			$syslogconf .= <<<EOD
651 236524c2 jim-p
local0.*							{$log_directive}{$g['varlog_path']}/filter.log
652
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
653
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
654
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
655 2ba3ea05 Renato Botelho
*.notice;kern.debug;lpr.info;mail.crit;daemon.none;		{$log_directive}{$g['varlog_path']}/system.log
656 236524c2 jim-p
news.err;local0.none;local3.none;local4.none;			{$log_directive}{$g['varlog_path']}/system.log
657
local7.none							{$log_directive}{$g['varlog_path']}/system.log
658
security.*							{$log_directive}{$g['varlog_path']}/system.log
659
auth.info;authpriv.info;daemon.info				{$log_directive}{$g['varlog_path']}/system.log
660
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
661
*.emerg								*
662 be5d59d7 Scott Ullrich
663
EOD;
664 236524c2 jim-p
		if (isset($syslogcfg['filter']))
665
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local0.*");
666
		if (isset($syslogcfg['vpn']))
667
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
668
		if (isset($syslogcfg['portalauth']))
669
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
670
		if (isset($syslogcfg['dhcp']))
671
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
672 be5d59d7 Scott Ullrich
		if (isset($syslogcfg['system'])) {
673 236524c2 jim-p
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.notice;kern.debug;lpr.info;mail.crit;");
674
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "news.err;local0.none;local3.none;local7.none");
675
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "security.*");
676
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "auth.info;authpriv.info;daemon.info");
677
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.emerg");
678
		}
679 4ef2d703 Chris Buechler
		if (isset($syslogcfg['logall'])) {
680 236524c2 jim-p
			// Make everything mean everything, including facilities excluded above.
681
			$syslogconf .= "!*\n";
682
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
683
		}
684 be5d59d7 Scott Ullrich
685 a213ad18 Andrew Thompson
		if (isset($syslogcfg['zmqserver'])) {
686
				$syslogconf .= <<<EOD
687
*.*								^{$syslogcfg['zmqserver']}
688
689
EOD;
690
		}
691 344016a8 Ermal
		/* write syslog.conf */		
692
		if (!@file_put_contents("{$g['varetc_path']}/syslog.conf", $syslogconf)) {
693
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
694
			unset($syslogconf);
695
			return 1;
696
		}
697
		unset($syslogconf);
698 42ee8bde Scott Ullrich
699
		// Ensure that the log directory exists
700 344016a8 Ermal
		if (!is_dir("{$g['dhcpd_chroot_path']}/var/run"))
701 42ee8bde Scott Ullrich
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
702
703 526102c1 jim-p
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c -l {$g['dhcpd_chroot_path']}/var/run/log -f {$g['varetc_path']}/syslog.conf");
704 5b237745 Scott Ullrich
705
	} else {
706 526102c1 jim-p
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c -l {$g['dhcpd_chroot_path']}/var/run/log");
707 5b237745 Scott Ullrich
	}
708 0f282d7a Scott Ullrich
709 5b237745 Scott Ullrich
	if ($g['booting'])
710 4a896b86 Carlos Eduardo Ramos
		echo gettext("done.") . "\n";
711 0f282d7a Scott Ullrich
712 5b237745 Scott Ullrich
	return $retval;
713
}
714
715
function system_pccard_start() {
716 f19d3b7a Scott Ullrich
	global $config, $g;
717 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
718
		$mt = microtime();
719 dcf0598e Scott Ullrich
		echo "system_pccard_start() being called $mt\n";
720 58c7450e Scott Ullrich
	}
721 0f282d7a Scott Ullrich
722 5b237745 Scott Ullrich
	if ($g['booting'])
723 4a896b86 Carlos Eduardo Ramos
		echo gettext("Initializing PCMCIA...");
724 0f282d7a Scott Ullrich
725 5b237745 Scott Ullrich
	/* kill any running pccardd */
726
	killbypid("{$g['varrun_path']}/pccardd.pid");
727 0f282d7a Scott Ullrich
728 5b237745 Scott Ullrich
	/* fire up pccardd */
729
	$res = mwexec("/usr/sbin/pccardd -z -f {$g['etc_path']}/pccard.conf");
730 0f282d7a Scott Ullrich
731 5b237745 Scott Ullrich
	if ($g['booting']) {
732
		if ($res == 0)
733 4a896b86 Carlos Eduardo Ramos
			echo gettext("done.") . "\n";
734 5b237745 Scott Ullrich
		else
735 4a896b86 Carlos Eduardo Ramos
			echo gettext("failed!") . "\n";
736 5b237745 Scott Ullrich
	}
737 0f282d7a Scott Ullrich
738 5b237745 Scott Ullrich
	return $res;
739
}
740
741 819197a8 Scott Ullrich
742 5b237745 Scott Ullrich
function system_webgui_start() {
743 f19d3b7a Scott Ullrich
	global $config, $g;
744 877ac35d Scott Ullrich
745
	if ($g['booting'])
746 4a896b86 Carlos Eduardo Ramos
		echo gettext("Starting webConfigurator...");
747 877ac35d Scott Ullrich
748
	chdir($g['www_path']);
749
750 fb1266d3 Matthew Grooms
	/* defaults */
751
	$portarg = "80";
752
	$crt = "";
753
	$key = "";
754 2cf6ddcb Nigel Graham
	$ca = "";
755 fb1266d3 Matthew Grooms
756 877ac35d Scott Ullrich
	/* non-standard port? */
757 f4875d35 Ermal Lu?i
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "")
758 528df9a7 Scott Ullrich
		$portarg = "{$config['system']['webgui']['port']}";
759 877ac35d Scott Ullrich
760
	if ($config['system']['webgui']['protocol'] == "https") {
761 02b383fe sullrich
		// Ensure that we have a webConfigurator CERT
762 fb1266d3 Matthew Grooms
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
763 02b383fe sullrich
		if(!is_array($cert) && !$cert['crt'] && !$cert['prv']) {
764 1e332e98 jim-p
			if (!is_array($config['ca']))
765
				$config['ca'] = array();
766
			$a_ca =& $config['ca'];
767
			if (!is_array($config['cert']))
768
				$config['cert'] = array();
769
			$a_cert =& $config['cert'];
770 e9954aef Scott Ullrich
			log_error("Creating SSL Certificate for this host");
771 aab4ca82 Scott Ullrich
			$cert = array();
772
			$cert['refid'] = uniqid();
773 4816e5ca Renato Botelho
			$cert['descr'] = gettext("webConfigurator default");
774 dae707f5 jim-p
			mwexec("/usr/local/bin/openssl genrsa 1024 > {$g['tmp_path']}/ssl.key");
775
			mwexec("/usr/local/bin/openssl req -new -x509 -nodes -sha256 -days 2000 -key {$g['tmp_path']}/ssl.key > {$g['tmp_path']}/ssl.crt");
776 6955830f Ermal Lu?i
			$crt = file_get_contents("{$g['tmp_path']}/ssl.crt");
777
			$key = file_get_contents("{$g['tmp_path']}/ssl.key");
778
			unlink("{$g['tmp_path']}/ssl.key");
779
			unlink("{$g['tmp_path']}/ssl.crt");
780 aab4ca82 Scott Ullrich
			cert_import($cert, $crt, $key);
781
			$a_cert[] = $cert;
782
			$config['system']['webgui']['ssl-certref'] = $cert['refid'];
783 4a896b86 Carlos Eduardo Ramos
			write_config(gettext("Importing HTTPS certificate"));
784 aab4ca82 Scott Ullrich
			if(!$config['system']['webgui']['port'])
785
				$portarg = "443";
786
			$ca = ca_chain($cert);
787 edc8a9f8 jim-p
		} else {
788 fb1266d3 Matthew Grooms
			$crt = base64_decode($cert['crt']);
789
			$key = base64_decode($cert['prv']);
790
			if(!$config['system']['webgui']['port'])
791
				$portarg = "443";
792 2cf6ddcb Nigel Graham
			$ca = ca_chain($cert);
793 edc8a9f8 jim-p
		}
794 877ac35d Scott Ullrich
	}
795
796
	/* generate lighttpd configuration */
797
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
798 c41602e1 jim-p
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
799 98f20e35 Irving Popovetsky
		"cert.pem", "ca.pem");
800 877ac35d Scott Ullrich
801 a11bc497 Ermal
	/* kill any running lighttpd */
802
	killbypid("{$g['varrun_path']}/lighty-webConfigurator.pid");
803
804
	sleep(1);
805
806
	@unlink("{$g['varrun_path']}/lighty-webConfigurator.pid");
807
808 877ac35d Scott Ullrich
	/* attempt to start lighthttpd */
809
	$res = mwexec("/usr/local/sbin/lighttpd -f {$g['varetc_path']}/lighty-webConfigurator.conf");
810
811
	if ($g['booting']) {
812
		if ($res == 0)
813 4a896b86 Carlos Eduardo Ramos
			echo gettext("done.") . "\n";
814 877ac35d Scott Ullrich
		else
815 4a896b86 Carlos Eduardo Ramos
			echo gettext("failed!") . "\n";
816 877ac35d Scott Ullrich
	}
817
818
	return $res;
819
}
820
821 eb0f441c Scott Ullrich
function system_generate_lighty_config($filename,
822
	$cert,
823
	$key,
824 2cf6ddcb Nigel Graham
	$ca,
825 eb0f441c Scott Ullrich
	$pid_file,
826
	$port = 80,
827
	$document_root = "/usr/local/www/",
828
	$cert_location = "cert.pem",
829 2cf6ddcb Nigel Graham
	$ca_location = "ca.pem",
830 eb0f441c Scott Ullrich
	$captive_portal = false) {
831 58c7450e Scott Ullrich
832 f19d3b7a Scott Ullrich
	global $config, $g;
833
834 6955830f Ermal Lu?i
	if(!is_dir("{$g['tmp_path']}/lighttpdcompress"))
835
		mkdir("{$g['tmp_path']}/lighttpdcompress");
836 570ef08c sullrich
837 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
838
		$mt = microtime();
839 dcf0598e Scott Ullrich
		echo "system_generate_lighty_config() being called $mt\n";
840 58c7450e Scott Ullrich
	}
841
842 a96f2d3d Ermal
	if ($captive_portal !== false)  {
843 f7bddb24 Ermal
		$captiveportal = ",\"mod_rewrite\",\"mod_evasive\"";
844 b4792bf8 Ermal
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?zone={$captive_portal}&redirurl=$1\" )\n";
845 74a4edc3 Ermal
846 6844896c bcyrill
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
847 a96f2d3d Ermal
		if (empty($maxprocperip))
848 f7bddb24 Ermal
			$maxprocperip = 10;
849 74a4edc3 Ermal
		$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
850
851 6955830f Ermal Lu?i
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
852
		exec("mkdir -p {$g['tmp_path']}/captiveportal");
853
		exec("chmod a-w {$g['tmp_path']}/captiveportal");
854 775556ab Scott Ullrich
		$server_max_request_size = "server.max-request-size    = 384";
855 b35fdb17 Ermal
		$cgi_config = "";
856 b0bdc06e Scott Ullrich
	} else {
857 b35fdb17 Ermal
		$captiveportal = ",\"mod_cgi\"";
858 3435dc35 Ermal Lu?i
		$captive_portal_rewrite = "";
859 b0bdc06e Scott Ullrich
		$captive_portal_mod_evasive = "";
860 6955830f Ermal Lu?i
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
861 775556ab Scott Ullrich
		$server_max_request_size = "server.max-request-size    = 2097152";
862 b35fdb17 Ermal
		$cgi_config = "cgi.assign                 = ( \".cgi\" => \"\" )";
863 eb0f441c Scott Ullrich
	}
864 3306a341 Scott Ullrich
	
865 a96f2d3d Ermal
	if (empty($port))
866 28cae949 Scott Ullrich
		$lighty_port = "80";
867 a96f2d3d Ermal
	else
868
		$lighty_port = $port;
869 3d77d4c4 Scott Ullrich
870
	$memory = get_memory();
871 76a7d8e4 Ermal
	$avail = $memory[1];
872 3d77d4c4 Scott Ullrich
873 98f20e35 Irving Popovetsky
	// Determine web GUI process settings and take into account low memory systems
874 a96f2d3d Ermal
	if ($avail < 255)
875
		$max_procs = 1;
876
	else
877 98f20e35 Irving Popovetsky
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
878 f4ebc84a Scott Ullrich
879 98f20e35 Irving Popovetsky
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM 
880 70e454e1 Ermal
	if ($captive_portal !== false)  {
881 a96f2d3d Ermal
		if ($avail > 135 and $avail < 256) {
882 98f20e35 Irving Popovetsky
			$max_procs += 1; // 2 worker processes
883 a96f2d3d Ermal
		} else if ($avail > 255 and $avail < 513) {
884
			$max_procs += 2; // 3 worker processes
885
		} else if ($avail > 512) {
886 98f20e35 Irving Popovetsky
			$max_procs += 4; // 6 worker processes
887 70cc6249 Scott Ullrich
		}
888 a96f2d3d Ermal
		if ($max_procs > 1)
889
			$max_php_children = intval($max_procs/2);
890
		else
891
			$max_php_children = 1;
892
893 e384f16e Ermal
	} else {
894
		if ($avail < 78)
895
			$max_php_children = 0;
896
		else
897
			$max_php_children = 1;
898
	}
899 980df75c Scott Ullrich
900 f7bddb24 Ermal
	if ($captive_portal !== false)
901
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi-{$captive_portal}.socket";
902
	else
903
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi.socket";
904 a96f2d3d Ermal
905 f7bddb24 Ermal
	$fastcgi_config = <<<EOD
906 4edb490d Scott Ullrich
#### fastcgi module
907
## read fastcgi.txt for more info
908 b0bdc06e Scott Ullrich
fastcgi.server = ( ".php" =>
909 a96f2d3d Ermal
	( "localhost" =>
910
		(
911
			"socket" => "{$fast_cgi_path}",
912
			"max-procs" => {$max_procs},
913 70e454e1 Ermal
			"bin-environment" => (
914
				"PHP_FCGI_CHILDREN" => "{$max_php_children}",
915
				"PHP_FCGI_MAX_REQUESTS" => "500"
916
			),
917 a96f2d3d Ermal
			"bin-path" => "/usr/local/bin/php"
918
		)
919 b0bdc06e Scott Ullrich
	)
920
)
921 333f8ef0 Scott Ullrich
922 4edb490d Scott Ullrich
EOD;
923 333f8ef0 Scott Ullrich
924 a96f2d3d Ermal
	$lighty_config = <<<EOD
925 28cae949 Scott Ullrich
#
926 a632cf43 Scott Ullrich
# lighttpd configuration file
927
#
928
# use a it as base for lighttpd 1.0.0 and above
929 28cae949 Scott Ullrich
#
930 a632cf43 Scott Ullrich
############ Options you really have to take care of ####################
931
932 770b4b9c Scott Ullrich
## FreeBSD!
933 60ff6204 Scott Ullrich
server.event-handler	= "freebsd-kqueue"
934
server.network-backend 	= "writev"
935 543ecd59 Seth Mos
#server.use-ipv6 = "enable"
936 096261af Scott Ullrich
937 a632cf43 Scott Ullrich
## modules to load
938 f7bddb24 Ermal
server.modules              =   ( "mod_access", "mod_expire", "mod_compress", "mod_redirect",
939
	{$captiveportal}, "mod_fastcgi"
940 a41c5253 Seth Mos
)
941 28cae949 Scott Ullrich
942 d9acea75 Scott Ullrich
server.max-keep-alive-requests = 15
943
server.max-keep-alive-idle = 30
944
945 a632cf43 Scott Ullrich
## a static document-root, for virtual-hosting take look at the
946
## server.virtual-* options
947 332b4ac0 Scott Ullrich
server.document-root        = "{$document_root}"
948 eb0f441c Scott Ullrich
{$captive_portal_rewrite}
949 a632cf43 Scott Ullrich
950 38a9a1ab Scott Ullrich
# Maximum idle time with nothing being written (php downloading)
951
server.max-write-idle = 999
952
953 a632cf43 Scott Ullrich
## where to send error-messages to
954 f7bddb24 Ermal
server.errorlog-use-syslog="enable"
955 a632cf43 Scott Ullrich
956
# files to check for if .../ is requested
957
server.indexfiles           = ( "index.php", "index.html",
958
                                "index.htm", "default.htm" )
959
960
# mimetype mapping
961
mimetype.assign             = (
962
  ".pdf"          =>      "application/pdf",
963
  ".sig"          =>      "application/pgp-signature",
964
  ".spl"          =>      "application/futuresplash",
965
  ".class"        =>      "application/octet-stream",
966
  ".ps"           =>      "application/postscript",
967
  ".torrent"      =>      "application/x-bittorrent",
968
  ".dvi"          =>      "application/x-dvi",
969
  ".gz"           =>      "application/x-gzip",
970
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
971
  ".swf"          =>      "application/x-shockwave-flash",
972
  ".tar.gz"       =>      "application/x-tgz",
973
  ".tgz"          =>      "application/x-tgz",
974
  ".tar"          =>      "application/x-tar",
975
  ".zip"          =>      "application/zip",
976
  ".mp3"          =>      "audio/mpeg",
977
  ".m3u"          =>      "audio/x-mpegurl",
978
  ".wma"          =>      "audio/x-ms-wma",
979
  ".wax"          =>      "audio/x-ms-wax",
980
  ".ogg"          =>      "audio/x-wav",
981
  ".wav"          =>      "audio/x-wav",
982
  ".gif"          =>      "image/gif",
983
  ".jpg"          =>      "image/jpeg",
984
  ".jpeg"         =>      "image/jpeg",
985
  ".png"          =>      "image/png",
986
  ".xbm"          =>      "image/x-xbitmap",
987
  ".xpm"          =>      "image/x-xpixmap",
988
  ".xwd"          =>      "image/x-xwindowdump",
989
  ".css"          =>      "text/css",
990
  ".html"         =>      "text/html",
991
  ".htm"          =>      "text/html",
992
  ".js"           =>      "text/javascript",
993
  ".asc"          =>      "text/plain",
994
  ".c"            =>      "text/plain",
995
  ".conf"         =>      "text/plain",
996
  ".text"         =>      "text/plain",
997
  ".txt"          =>      "text/plain",
998
  ".dtd"          =>      "text/xml",
999
  ".xml"          =>      "text/xml",
1000
  ".mpeg"         =>      "video/mpeg",
1001
  ".mpg"          =>      "video/mpeg",
1002
  ".mov"          =>      "video/quicktime",
1003
  ".qt"           =>      "video/quicktime",
1004
  ".avi"          =>      "video/x-msvideo",
1005
  ".asf"          =>      "video/x-ms-asf",
1006
  ".asx"          =>      "video/x-ms-asf",
1007
  ".wmv"          =>      "video/x-ms-wmv",
1008
  ".bz2"          =>      "application/x-bzip",
1009
  ".tbz"          =>      "application/x-bzip-compressed-tar",
1010
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
1011
 )
1012
1013
# Use the "Content-Type" extended attribute to obtain mime type if possible
1014
#mimetypes.use-xattr        = "enable"
1015
1016
## deny access the file-extensions
1017
#
1018
# ~    is for backupfiles from vi, emacs, joe, ...
1019
# .inc is often used for code includes which should in general not be part
1020
#      of the document-root
1021
url.access-deny             = ( "~", ".inc" )
1022
1023
1024
######### Options that are good to be but not neccesary to be changed #######
1025
1026
## bind to port (default: 80)
1027 9cb94dd4 Ermal
1028
EOD;
1029
1030 6839a678 Ermal
	$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1031
	$lighty_config .= "server.port  = {$lighty_port}\n";
1032
	$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1033
	$lighty_config .= "\$SERVER[\"socket\"]  == \"[::]:{$lighty_port}\" { \n";
1034
	if($cert <> "" and $key <> "") {
1035
		$lighty_config .= "\n";
1036
		$lighty_config .= "## ssl configuration\n";
1037
		$lighty_config .= "ssl.engine = \"enable\"\n";
1038
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1039
		if($ca <> "")
1040
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1041 543ecd59 Seth Mos
	}
1042 6839a678 Ermal
	$lighty_config .= " }\n";
1043 543ecd59 Seth Mos
1044 9cb94dd4 Ermal
1045
	$lighty_config .= <<<EOD
1046 a632cf43 Scott Ullrich
1047
## error-handler for status 404
1048
#server.error-handler-404   = "/error-handler.html"
1049
#server.error-handler-404   = "/error-handler.php"
1050
1051
## to help the rc.scripts
1052 e141ea70 Ermal
server.pid-file            = "{$g['varrun_path']}/{$pid_file}"
1053 a632cf43 Scott Ullrich
1054
## virtual directory listings
1055 28cae949 Scott Ullrich
server.dir-listing         = "disable"
1056 a632cf43 Scott Ullrich
1057
## enable debugging
1058 28cae949 Scott Ullrich
debug.log-request-header   = "disable"
1059
debug.log-response-header  = "disable"
1060
debug.log-request-handling = "disable"
1061
debug.log-file-not-found   = "disable"
1062 a632cf43 Scott Ullrich
1063 570ef08c sullrich
# gzip compression
1064 6955830f Ermal Lu?i
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1065 570ef08c sullrich
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1066
1067 3306a341 Scott Ullrich
{$server_upload_dirs}
1068 1ef7b568 Scott Ullrich
1069 a6e8af9c Scott Ullrich
{$server_max_request_size}
1070 ee959dc4 Scott Ullrich
1071 4edb490d Scott Ullrich
{$fastcgi_config}
1072
1073 b35fdb17 Ermal
{$cgi_config}
1074
1075 b0bdc06e Scott Ullrich
{$captive_portal_mod_evasive}
1076
1077 569f47e9 Scott Ullrich
expire.url = (
1078 05a5e5c5 Scott Ullrich
				"" => "access 50 hours",	
1079 569f47e9 Scott Ullrich
        )
1080
1081 a632cf43 Scott Ullrich
EOD;
1082
1083 7aae518a Scott Ullrich
	$cert = str_replace("\r", "", $cert);
1084 333f8ef0 Scott Ullrich
	$key = str_replace("\r", "", $key);
1085 2cf6ddcb Nigel Graham
	$ca = str_replace("\r", "", $ca);
1086 7aae518a Scott Ullrich
1087
	$cert = str_replace("\n\n", "\n", $cert);
1088 333f8ef0 Scott Ullrich
	$key = str_replace("\n\n", "\n", $key);
1089 2cf6ddcb Nigel Graham
	$ca = str_replace("\n\n", "\n", $ca);
1090 7aae518a Scott Ullrich
1091 a632cf43 Scott Ullrich
	if($cert <> "" and $key <> "") {
1092 3a66b621 Scott Ullrich
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1093 5b237745 Scott Ullrich
		if (!$fd) {
1094 4a896b86 Carlos Eduardo Ramos
			printf(gettext("Error: cannot open cert.pem in system_webgui_start().%s"), "\n");
1095 5b237745 Scott Ullrich
			return 1;
1096
		}
1097 3a66b621 Scott Ullrich
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1098 5b237745 Scott Ullrich
		fwrite($fd, $cert);
1099
		fwrite($fd, "\n");
1100
		fwrite($fd, $key);
1101
		fclose($fd);
1102 546f30ca jim-p
		if(!(empty($ca) || (strlen(trim($ca)) == 0))) {
1103 2cf6ddcb Nigel Graham
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1104
			if (!$fd) {
1105 4a896b86 Carlos Eduardo Ramos
				printf(gettext("Error: cannot open ca.pem in system_webgui_start().%s"), "\n");
1106 2cf6ddcb Nigel Graham
				return 1;
1107
			}
1108
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1109
			fwrite($fd, $ca);
1110
			fclose($fd);
1111
		}
1112 5e041d5f Scott Ullrich
		$lighty_config .= "\n";
1113 4a896b86 Carlos Eduardo Ramos
		$lighty_config .= "## " . gettext("ssl configuration") . "\n";
1114 a632cf43 Scott Ullrich
		$lighty_config .= "ssl.engine = \"enable\"\n";
1115 333f8ef0 Scott Ullrich
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1116 673ee7b1 Scott Ullrich
1117
		// Harden SSL a bit for PCI conformance testing
1118
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
1119 3cd2ea2c jim-p
		$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";
1120 673ee7b1 Scott Ullrich
1121 75e9ed89 jim-p
		if(!(empty($ca) || (strlen(trim($ca)) == 0)))
1122 2cf6ddcb Nigel Graham
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1123 5b237745 Scott Ullrich
	}
1124 a978a0ff Chris Buechler
1125
	// Add HTTP to HTTPS redirect	
1126 6839a678 Ermal
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1127 7921e8e5 Chris Buechler
		if($lighty_port != "443") 
1128
			$redirectport = ":{$lighty_port}";
1129 d7e230ae Chris Buechler
		$lighty_config .= <<<EOD
1130
\$SERVER["socket"] == ":80" {
1131
	\$HTTP["host"] =~ "(.*)" {
1132 7921e8e5 Chris Buechler
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1133 d7e230ae Chris Buechler
	}
1134
}
1135
EOD;
1136
	}
1137 0f282d7a Scott Ullrich
1138 4f3756f3 Scott Ullrich
	$fd = fopen("{$filename}", "w");
1139 a632cf43 Scott Ullrich
	if (!$fd) {
1140 4a896b86 Carlos Eduardo Ramos
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1141 a632cf43 Scott Ullrich
		return 1;
1142 5b237745 Scott Ullrich
	}
1143 a632cf43 Scott Ullrich
	fwrite($fd, $lighty_config);
1144
	fclose($fd);
1145
1146
	return 0;
1147 0f282d7a Scott Ullrich
1148 5b237745 Scott Ullrich
}
1149
1150
function system_timezone_configure() {
1151 f19d3b7a Scott Ullrich
	global $config, $g;
1152 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
1153
		$mt = microtime();
1154 dcf0598e Scott Ullrich
		echo "system_timezone_configure() being called $mt\n";
1155 333f8ef0 Scott Ullrich
	}
1156 5b237745 Scott Ullrich
1157
	$syscfg = $config['system'];
1158
1159
	if ($g['booting'])
1160 4a896b86 Carlos Eduardo Ramos
		echo gettext("Setting timezone...");
1161 5b237745 Scott Ullrich
1162
	/* extract appropriate timezone file */
1163
	$timezone = $syscfg['timezone'];
1164
	if (!$timezone)
1165
		$timezone = "Etc/UTC";
1166 0f282d7a Scott Ullrich
1167 34febcde Scott Ullrich
	conf_mount_rw();
1168
1169 029d1a71 Scott Ullrich
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1170 5b237745 Scott Ullrich
		escapeshellarg($timezone) . " > /etc/localtime");
1171
1172 4efd4885 Scott Ullrich
	mwexec("sync");
1173 27150275 Scott Ullrich
	conf_mount_ro();
1174 34febcde Scott Ullrich
1175 5b237745 Scott Ullrich
	if ($g['booting'])
1176 4a896b86 Carlos Eduardo Ramos
		echo gettext("done.") . "\n";
1177 5b237745 Scott Ullrich
}
1178
1179 5c8843d5 jim-p
function system_ntp_setup_gps($serialport) {
1180
	$gps_device = '/dev/gps0';
1181
	$serialport = '/dev/'.$serialport;
1182
1183
	if (!file_exists($serialport))
1184
		return false;
1185
1186
	conf_mount_rw();
1187
	// Create symlink that ntpd requires
1188
	unlink_if_exists($gps_device);
1189
	symlink($serialport, $gps_device);
1190
1191
	/* Send the following to the GPS port to initialize the GPS */
1192
	$gps_init = <<<EOF
1193
\$PUBX,40,GSV,0,0,0,0*59
1194
\$PUBX,40,GLL,0,0,0,0*5C
1195
\$PUBX,40,ZDA,0,0,0,0*44
1196
\$PUBX,40,VTG,0,0,0,0*5E
1197
\$PUBX,40,GSV,0,0,0,0*59
1198
\$PUBX,40,GSA,0,0,0,0*4E
1199
\$PUBX,40,GGA,0,0,0,0
1200
\$PUBX,40,TXT,0,0,0,0
1201
\$PUBX,40,RMC,0,0,0,0*46
1202
\$PUBX,41,1,0007,0003,4800,0
1203
\$PUBX,40,ZDA,1,1,1,1
1204
EOF;
1205 18080a21 jim-p
	file_put_contents("/tmp/gps.init", $gps_init);
1206
	`cat /tmp/gps.init > $serialport`;
1207 5c8843d5 jim-p
1208
	/* Add /etc/remote entry in case we need to read from the GPS with tip */
1209
	if (intval(`grep -c '^gps0' /etc/remote`) == 0)
1210
		`echo "gps0:dv={$serialport}:br#4800:pa=none:" >> /etc/remote`;
1211
1212
	conf_mount_ro();
1213
1214
	return true;
1215
}
1216
1217 0b8e9d38 jim-p
function system_ntp_configure($start_ntpd=true) {
1218 f19d3b7a Scott Ullrich
	global $config, $g;
1219 42135f07 jim-p
	$driftfile = "/var/db/ntpd.drift";
1220 5c8843d5 jim-p
	$statsdir = "/var/log/ntp";
1221
	$gps_device = '/dev/gps0';
1222 5b237745 Scott Ullrich
1223 7734aea6 Andrew Thompson
	if ($g['platform'] == 'jail')
1224
		return;
1225
1226 5c8843d5 jim-p
	safe_mkdir($statsdir);
1227
1228 b2305621 Ermal
	$ntpcfg = "# \n";
1229 42135f07 jim-p
	$ntpcfg .= "# pfSense ntp configuration file \n";
1230 b2305621 Ermal
	$ntpcfg .= "# \n\n";
1231 362c9bb0 jim-p
	$ntpcfg .= "tinker panic 0 \n";
1232 0f282d7a Scott Ullrich
1233 5c8843d5 jim-p
	if (!empty($config['ntpd']['gpsport'])
1234
		&& file_exists('/dev/'.$config['ntpd']['gpsport'])
1235
		&& system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1236
		$ntpcfg .= "# GPS Setup\n";
1237
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1238
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1239
		// Fall back to local clock if GPS is out of sync?
1240
		$ntpcfg .= "server 127.127.1.0\n";
1241
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1242
	}
1243
1244
	$ntpcfg .= "\n\n# Upstream Servers\n";
1245 20b90e0a Scott Ullrich
	/* foreach through servers and write out to ntpd.conf */
1246 c4680ae2 jim-p
	foreach (explode(' ', $config['system']['timeservers']) as $ts)
1247
		$ntpcfg .= "server {$ts} iburst maxpoll 9\n";
1248 42135f07 jim-p
1249 5c8843d5 jim-p
	$ntpcfg .= "enable monitor\n";
1250 d9c72958 jim-p
	$ntpcfg .= "enable stats\n";
1251
	$ntpcfg .= "statistics clockstats\n";
1252 5c8843d5 jim-p
	$ntpcfg .= "statsdir {$statsdir}\n";
1253
	$ntpcfg .= "logconfig =syncall +clockall\n";
1254 42135f07 jim-p
	$ntpcfg .= "driftfile {$driftfile}\n";
1255 7b27db03 jim-p
	$ntpcfg .= "restrict default kod nomodify notrap nopeer\n";
1256
	$ntpcfg .= "restrict -6 default kod nomodify notrap nopeer\n";
1257 95594e5a Scott Ullrich
1258 cf180ccc jim-p
	if (empty($config['ntpd']['interface']))
1259 e43d53b4 Phil Davis
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface']))
1260 cf180ccc jim-p
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1261
		else
1262
			$interfaces = array();
1263
	else
1264
		$interfaces = explode(",", $config['ntpd']['interface']);
1265
1266
	if (is_array($interfaces) && count($interfaces)) {
1267
		$ntpcfg .= "interface ignore all\n";
1268
		foreach ($interfaces as $interface) {
1269
			if (!is_ipaddr($interface)) {
1270
				$interface = get_real_interface($interface);
1271
			}
1272
			$ntpcfg .= "interface listen {$interface}\n";
1273
		}
1274
	}
1275
1276 b2305621 Ermal
	/* open configuration for wrting or bail */
1277 b9f29f84 Ermal
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
1278 b2305621 Ermal
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1279
		return;
1280
	}
1281 20b90e0a Scott Ullrich
1282 0b8e9d38 jim-p
	/* At bootup we just want to write out the config. */
1283
	if (!$start_ntpd)
1284
		return;
1285
1286 42135f07 jim-p
	/* if ntpd is running, kill it */
1287 df40755d Ermal
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1288 b9f29f84 Ermal
		killbypid("{$g['varrun_path']}/ntpd.pid");
1289 5f3e1f12 Scott Ullrich
	}
1290 b9f29f84 Ermal
	@unlink("{$g['varrun_path']}/ntpd.pid");
1291 5f3e1f12 Scott Ullrich
1292
	/* if /var/empty does not exist, create it */
1293
	if(!is_dir("/var/empty"))
1294
		exec("/bin/mkdir -p /var/empty && chmod ug+rw /var/empty/.");
1295
1296 20b90e0a Scott Ullrich
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1297 b9f29f84 Ermal
	mwexec("/usr/local/bin/ntpd -g -c {$g['varetc_path']}/ntpd.conf -p {$g['varrun_path']}/ntpd.pid", false, true);
1298 83eb4567 Scott Ullrich
	
1299
	// Note that we are starting up
1300 42135f07 jim-p
	log_error("NTPD is starting up.");
1301 0b8e9d38 jim-p
	return;
1302 5b237745 Scott Ullrich
}
1303
1304 652cf082 Seth Mos
function sync_system_time() {
1305
	global $config, $g;
1306
1307
	if ($g['booting'])
1308 4a896b86 Carlos Eduardo Ramos
		echo gettext("Syncing system time before startup...");
1309 652cf082 Seth Mos
1310
	/* foreach through servers and write out to ntpd.conf */
1311 b2305621 Ermal
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1312 652cf082 Seth Mos
		mwexec("/usr/sbin/ntpdate -s $ts");
1313
	}
1314 4582b281 Scott Ullrich
	
1315
	if ($g['booting'])
1316 4a896b86 Carlos Eduardo Ramos
		echo gettext("done.") . "\n";
1317 4582b281 Scott Ullrich
	
1318 652cf082 Seth Mos
}
1319
1320 405e5de0 Scott Ullrich
function system_halt() {
1321
	global $g;
1322
1323
	system_reboot_cleanup();
1324
1325 523855b0 Scott Ullrich
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1326 405e5de0 Scott Ullrich
}
1327
1328 5b237745 Scott Ullrich
function system_reboot() {
1329
	global $g;
1330 0f282d7a Scott Ullrich
1331 5b237745 Scott Ullrich
	system_reboot_cleanup();
1332 0f282d7a Scott Ullrich
1333 5b237745 Scott Ullrich
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1334
}
1335
1336
function system_reboot_sync() {
1337
	global $g;
1338 0f282d7a Scott Ullrich
1339 5b237745 Scott Ullrich
	system_reboot_cleanup();
1340 0f282d7a Scott Ullrich
1341 5b237745 Scott Ullrich
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1342
}
1343
1344
function system_reboot_cleanup() {
1345 97d4e30b Seth Mos
	mwexec("/usr/local/bin/beep.sh stop");
1346 04967d99 jim-p
	require_once("captiveportal.inc");
1347 5b237745 Scott Ullrich
	captiveportal_radius_stop_all();
1348 336e3c1c Charlie
	require_once("voucher.inc");
1349
	voucher_save_db_to_config();
1350 60dd7649 jim-p
	require_once("pkg-utils.inc");
1351
	stop_packages();
1352 5b237745 Scott Ullrich
}
1353
1354
function system_do_shell_commands($early = 0) {
1355 f19d3b7a Scott Ullrich
	global $config, $g;
1356 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
1357
		$mt = microtime();
1358 dcf0598e Scott Ullrich
		echo "system_do_shell_commands() being called $mt\n";
1359 58c7450e Scott Ullrich
	}
1360 0f282d7a Scott Ullrich
1361 5b237745 Scott Ullrich
	if ($early)
1362
		$cmdn = "earlyshellcmd";
1363
	else
1364
		$cmdn = "shellcmd";
1365 0f282d7a Scott Ullrich
1366 5b237745 Scott Ullrich
	if (is_array($config['system'][$cmdn])) {
1367 333f8ef0 Scott Ullrich
1368 245388b4 Scott Ullrich
		/* *cmd is an array, loop through */
1369 5b237745 Scott Ullrich
		foreach ($config['system'][$cmdn] as $cmd) {
1370
			exec($cmd);
1371
		}
1372 245388b4 Scott Ullrich
1373
	} elseif($config['system'][$cmdn] <> "") {
1374 333f8ef0 Scott Ullrich
1375 245388b4 Scott Ullrich
		/* execute single item */
1376
		exec($config['system'][$cmdn]);
1377
1378 5b237745 Scott Ullrich
	}
1379
}
1380
1381
function system_console_configure() {
1382 f19d3b7a Scott Ullrich
	global $config, $g;
1383 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
1384
		$mt = microtime();
1385 dcf0598e Scott Ullrich
		echo "system_console_configure() being called $mt\n";
1386 333f8ef0 Scott Ullrich
	}
1387 0f282d7a Scott Ullrich
1388 5b237745 Scott Ullrich
	if (isset($config['system']['disableconsolemenu'])) {
1389
		touch("{$g['varetc_path']}/disableconsole");
1390
	} else {
1391
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
1392
	}
1393
}
1394
1395
function system_dmesg_save() {
1396 f19d3b7a Scott Ullrich
	global $g;
1397 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
1398
		$mt = microtime();
1399 dcf0598e Scott Ullrich
		echo "system_dmesg_save() being called $mt\n";
1400 f19d3b7a Scott Ullrich
	}
1401 0f282d7a Scott Ullrich
1402 767a716e Scott Ullrich
	$dmesg = "";
1403 5b237745 Scott Ullrich
	exec("/sbin/dmesg", $dmesg);
1404 0f282d7a Scott Ullrich
1405 5b237745 Scott Ullrich
	/* find last copyright line (output from previous boots may be present) */
1406
	$lastcpline = 0;
1407 0f282d7a Scott Ullrich
1408 5b237745 Scott Ullrich
	for ($i = 0; $i < count($dmesg); $i++) {
1409
		if (strstr($dmesg[$i], "Copyright (c) 1992-"))
1410
			$lastcpline = $i;
1411
	}
1412 0f282d7a Scott Ullrich
1413 5b237745 Scott Ullrich
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
1414
	if (!$fd) {
1415 4a896b86 Carlos Eduardo Ramos
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
1416 5b237745 Scott Ullrich
		return 1;
1417
	}
1418 0f282d7a Scott Ullrich
1419 5b237745 Scott Ullrich
	for ($i = $lastcpline; $i < count($dmesg); $i++)
1420
		fwrite($fd, $dmesg[$i] . "\n");
1421 0f282d7a Scott Ullrich
1422 5b237745 Scott Ullrich
	fclose($fd);
1423 0f282d7a Scott Ullrich
1424 5b237745 Scott Ullrich
	return 0;
1425
}
1426
1427
function system_set_harddisk_standby() {
1428 f19d3b7a Scott Ullrich
	global $g, $config;
1429 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
1430
		$mt = microtime();
1431 dcf0598e Scott Ullrich
		echo "system_set_harddisk_standby() being called $mt\n";
1432 58c7450e Scott Ullrich
	}
1433 5b237745 Scott Ullrich
1434
	if (isset($config['system']['harddiskstandby'])) {
1435
		if ($g['booting']) {
1436 4a896b86 Carlos Eduardo Ramos
			echo gettext('Setting hard disk standby... ');
1437 5b237745 Scott Ullrich
		}
1438
1439
		$standby = $config['system']['harddiskstandby'];
1440
		// Check for a numeric value
1441
		if (is_numeric($standby)) {
1442
			// Sync the disk(s)
1443 5ba5a8de Scott Ullrich
			pfSense_sync();
1444 5b237745 Scott Ullrich
			if (!mwexec('/sbin/sysctl hw.ata.standby=' . ((int)$standby))) {
1445
				// Reinitialize ATA-drives
1446
				mwexec('/usr/local/sbin/atareinit');
1447
				if ($g['booting']) {
1448 4a896b86 Carlos Eduardo Ramos
					echo gettext("done.") . "\n";
1449 5b237745 Scott Ullrich
				}
1450
			} else if ($g['booting']) {
1451 4a896b86 Carlos Eduardo Ramos
				echo gettext("failed!") . "\n";
1452 5b237745 Scott Ullrich
			}
1453
		} else if ($g['booting']) {
1454 4a896b86 Carlos Eduardo Ramos
			echo gettext("failed!") . "\n";
1455 5b237745 Scott Ullrich
		}
1456
	}
1457
}
1458
1459 3ff9d424 Scott Ullrich
function system_setup_sysctl() {
1460 f19d3b7a Scott Ullrich
	global $config;
1461 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
1462
		$mt = microtime();
1463 dcf0598e Scott Ullrich
		echo "system_setup_sysctl() being called $mt\n";
1464 58c7450e Scott Ullrich
	}
1465 243aa7b9 Scott Ullrich
1466 6df9d7e3 Scott Ullrich
	activate_sysctls();	
1467
1468 243aa7b9 Scott Ullrich
	if (isset($config['system']['sharednet'])) {
1469
		system_disable_arp_wrong_if();
1470
	}
1471
}
1472
1473
function system_disable_arp_wrong_if() {
1474 f19d3b7a Scott Ullrich
	global $config;
1475 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
1476
		$mt = microtime();
1477 dcf0598e Scott Ullrich
		echo "system_disable_arp_wrong_if() being called $mt\n";
1478 333f8ef0 Scott Ullrich
	}
1479 6cb438cf Scott Ullrich
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=0");
1480 89f4b6a3 Scott Ullrich
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=0");
1481 3ff9d424 Scott Ullrich
}
1482
1483 243aa7b9 Scott Ullrich
function system_enable_arp_wrong_if() {
1484 f19d3b7a Scott Ullrich
	global $config;
1485 58c7450e Scott Ullrich
	if(isset($config['system']['developerspew'])) {
1486
		$mt = microtime();
1487 dcf0598e Scott Ullrich
		echo "system_enable_arp_wrong_if() being called $mt\n";
1488 58c7450e Scott Ullrich
	}
1489 243aa7b9 Scott Ullrich
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_wrong_iface=1");
1490 89f4b6a3 Scott Ullrich
	mwexec("/sbin/sysctl -n net.link.ether.inet.log_arp_movements=1");
1491 243aa7b9 Scott Ullrich
}
1492
1493 a199b93e Scott Ullrich
function enable_watchdog() {
1494
	global $config;
1495 1a479479 Scott Ullrich
	return;
1496 a199b93e Scott Ullrich
	$install_watchdog = false;
1497
	$supported_watchdogs = array("Geode");
1498
	$file = file_get_contents("/var/log/dmesg.boot");
1499
	foreach($supported_watchdogs as $sd) {
1500
		if(stristr($file, "Geode")) {
1501
			$install_watchdog = true;
1502
		}
1503
	}
1504
	if($install_watchdog == true) {
1505 2e44fb05 Scott Ullrich
		if(is_process_running("watchdogd"))
1506 e0b4e47f Seth Mos
			mwexec("/usr/bin/killall watchdogd", true);
1507 333f8ef0 Scott Ullrich
		exec("/usr/sbin/watchdogd");
1508 a199b93e Scott Ullrich
	}
1509
}
1510 15f14889 Scott Ullrich
1511
function system_check_reset_button() {
1512 fa83737d Scott Ullrich
	global $g;
1513 223ef06a Scott Ullrich
	if($g['platform'] != "nanobsd")
1514 fa83737d Scott Ullrich
		return 0;
1515 15f14889 Scott Ullrich
1516 31c9379c Scott Ullrich
	$specplatform = system_identify_specific_platform();
1517
1518 15f14889 Scott Ullrich
	if ($specplatform['name'] != "wrap" && $specplatform['name'] != "alix")
1519
		return 0;
1520
1521
	$retval = mwexec("/usr/local/sbin/" . $specplatform['name'] . "resetbtn");
1522
1523
	if ($retval == 99) {
1524
		/* user has pressed reset button for 2 seconds - 
1525
		   reset to factory defaults */
1526
		echo <<<EOD
1527
1528
***********************************************************************
1529
* Reset button pressed - resetting configuration to factory defaults. *
1530
* The system will reboot after this completes.                        *
1531
***********************************************************************
1532
1533
1534
EOD;
1535
		
1536
		reset_factory_defaults();
1537
		system_reboot_sync();
1538
		exit(0);
1539
	}
1540
1541
	return 0;
1542
}
1543
1544 31c9379c Scott Ullrich
/* attempt to identify the specific platform (for embedded systems)
1545
   Returns an array with two elements:
1546
	name => platform string (e.g. 'wrap', 'alix' etc.)
1547
	descr => human-readable description (e.g. "PC Engines WRAP")
1548
*/
1549
function system_identify_specific_platform() {
1550
	global $g;
1551
	
1552
	if ($g['platform'] == 'generic-pc')
1553 4a896b86 Carlos Eduardo Ramos
		return array('name' => 'generic-pc', 'descr' => gettext("Generic PC"));
1554 31c9379c Scott Ullrich
	
1555
	if ($g['platform'] == 'generic-pc-cdrom')
1556 4a896b86 Carlos Eduardo Ramos
		return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)"));
1557 31c9379c Scott Ullrich
	
1558
	/* the rest of the code only deals with 'embedded' platforms */
1559 1a2911a7 Scott Ullrich
	if ($g['platform'] != 'nanobsd')
1560 31c9379c Scott Ullrich
		return array('name' => $g['platform'], 'descr' => $g['platform']);
1561
	
1562
	$dmesg = system_get_dmesg_boot();
1563
	
1564
	if (strpos($dmesg, "PC Engines WRAP") !== false)
1565 4a896b86 Carlos Eduardo Ramos
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
1566 31c9379c Scott Ullrich
	
1567
	if (strpos($dmesg, "PC Engines ALIX") !== false)
1568 4a896b86 Carlos Eduardo Ramos
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
1569 31c9379c Scott Ullrich
1570
	if (preg_match("/Soekris net45../", $dmesg, $matches))
1571
		return array('name' => 'net45xx', 'descr' => $matches[0]);
1572
	
1573
	if (preg_match("/Soekris net48../", $dmesg, $matches))
1574
		return array('name' => 'net48xx', 'descr' => $matches[0]);
1575
		
1576
	if (preg_match("/Soekris net55../", $dmesg, $matches))
1577
		return array('name' => 'net55xx', 'descr' => $matches[0]);
1578
	
1579
	/* unknown embedded platform */
1580 4a896b86 Carlos Eduardo Ramos
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
1581 31c9379c Scott Ullrich
}
1582
1583
function system_get_dmesg_boot() {
1584
	global $g;
1585 d16af75d Scott Ullrich
		
1586 31c9379c Scott Ullrich
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
1587
}
1588
1589 c82b2c3f jim-p
function get_possible_listen_ips() {
1590 7401c8c4 jim-p
	$interfaces = get_configured_interface_with_descr();
1591
	$carplist = get_configured_carp_interface_list();
1592
	$listenips = array();
1593
	foreach ($carplist as $cif => $carpip)
1594
		$interfaces[$cif] = $carpip." (".get_vip_descr($carpip).")";
1595
	$aliaslist = get_configured_ip_aliases_list();
1596
	foreach ($aliaslist as $aliasip => $aliasif)
1597
		$interfaces[$aliasip] = $aliasip." (".get_vip_descr($aliasip).")";
1598
	foreach ($interfaces as $iface => $ifacename) {
1599
		$tmp["name"]  = $ifacename;
1600
		$tmp["value"] = $iface;
1601
		$listenips[] = $tmp;
1602
	}
1603
	$tmp["name"]  = "Localhost";
1604
	$tmp["value"] = "lo0";
1605
	$listenips[] = $tmp;
1606
	return $listenips;
1607
}
1608 943994ff Scott Ullrich
1609 3b8a17a1 Ermal
?>