Project

General

Profile

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