Project

General

Profile

Download (66.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 971de1f9 Renato Botelho
	pfSense_BUILDER_BINARIES:	/usr/sbin/powerd	/usr/bin/killall	/sbin/route
34 61e047a5 Phil Davis
	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 fdfa8f43 jim-p
	pfSense_BUILDER_BINARIES:	/usr/bin/tar		/usr/local/sbin/ntpd	/usr/local/sbin/ntpdate
37 c3b13d60 jim-p
	pfSense_BUILDER_BINARIES:	/usr/bin/nohup	/sbin/dmesg	/usr/local/sbin/atareinit	/sbin/kldload
38 356e86d4 Renato Botelho
	pfSense_BUILDER_BINARIES:	/usr/local/sbin/filterdns
39 523855b0 Scott Ullrich
	pfSense_MODULE:	utils
40
*/
41 0f282d7a Scott Ullrich
42 8e9fa41d Scott Ullrich
function activate_powerd() {
43
	global $config, $g;
44 61e047a5 Phil Davis
	if ($g['platform'] == 'jail') {
45 7734aea6 Andrew Thompson
		return;
46 61e047a5 Phil Davis
	}
47
	if (is_process_running("powerd")) {
48 53c210dd Cristian Feldman
		exec("/usr/bin/killall powerd");
49 61e047a5 Phil Davis
	}
50
	if (isset($config['system']['powerd_enable'])) {
51
		if ($g["platform"] == "nanobsd") {
52 c3b13d60 jim-p
			exec("/sbin/kldload cpufreq");
53 61e047a5 Phil Davis
		}
54 a358eec2 N0YB
55
		$ac_mode = "hadp";
56 61e047a5 Phil Davis
		if (!empty($config['system']['powerd_ac_mode'])) {
57 a358eec2 N0YB
			$ac_mode = $config['system']['powerd_ac_mode'];
58 61e047a5 Phil Davis
		}
59 a358eec2 N0YB
60
		$battery_mode = "hadp";
61 61e047a5 Phil Davis
		if (!empty($config['system']['powerd_battery_mode'])) {
62 a358eec2 N0YB
			$battery_mode = $config['system']['powerd_battery_mode'];
63 61e047a5 Phil Davis
		}
64 a358eec2 N0YB
65 3d77cc35 Steven Selph
		$normal_mode = "hadp";
66 61e047a5 Phil Davis
		if (!empty($config['system']['powerd_normal_mode'])) {
67 3d77cc35 Steven Selph
			$normal_mode = $config['system']['powerd_normal_mode'];
68 61e047a5 Phil Davis
		}
69 3d77cc35 Steven Selph
70
		mwexec("/usr/sbin/powerd -b $battery_mode -a $ac_mode -n $normal_mode");
71 8e9fa41d Scott Ullrich
	}
72
}
73
74 3a35f55f Scott Ullrich
function get_default_sysctl_value($id) {
75
	global $sysctls;
76 f3c91cb5 Erik Fonnesbeck
77 61e047a5 Phil Davis
	if (isset($sysctls[$id])) {
78 f3c91cb5 Erik Fonnesbeck
		return $sysctls[$id];
79 61e047a5 Phil Davis
	}
80 3a35f55f Scott Ullrich
}
81
82 d87fcac9 Ermal
function get_sysctl_descr($sysctl) {
83
	unset($output);
84
	$_gb = exec("/sbin/sysctl -nd {$sysctl}", $output);
85
86
	return $output[0];
87
}
88
89
function system_get_sysctls() {
90
	global $config, $sysctls;
91
92
	$disp_sysctl = array();
93
	$disp_cache = array();
94
	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
95 61e047a5 Phil Davis
		foreach ($config['sysctl']['item'] as $id => $tunable) {
96
			if ($tunable['value'] == "default") {
97 d87fcac9 Ermal
				$value = get_default_sysctl_value($tunable['tunable']);
98 61e047a5 Phil Davis
			} else {
99 d87fcac9 Ermal
				$value = $tunable['value'];
100 61e047a5 Phil Davis
			}
101 d87fcac9 Ermal
102
			$disp_sysctl[$id] = $tunable;
103
			$disp_sysctl[$id]['modified'] = true;
104
			$disp_cache[$tunable['tunable']] = 'set';
105
		}
106
	}
107
108
	foreach ($sysctls as $sysctl => $value) {
109 61e047a5 Phil Davis
		if (isset($disp_cache[$sysctl])) {
110 d87fcac9 Ermal
			continue;
111 61e047a5 Phil Davis
		}
112 d87fcac9 Ermal
113
		$disp_sysctl[$sysctl] = array('tunable' => $sysctl, 'value' => $value, 'descr' => get_sysctl_descr($sysctl));
114
	}
115
	unset($disp_cache);
116
	return $disp_sysctl;
117
}
118
119 6df9d7e3 Scott Ullrich
function activate_sysctls() {
120 c46f9695 Ermal
	global $config, $g, $sysctls;
121 971de1f9 Renato Botelho
122 61e047a5 Phil Davis
	if ($g['platform'] == 'jail') {
123 7734aea6 Andrew Thompson
		return;
124 61e047a5 Phil Davis
	}
125 971de1f9 Renato Botelho
126 d87fcac9 Ermal
	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
127 61e047a5 Phil Davis
		foreach ($config['sysctl']['item'] as $tunable) {
128
			if ($tunable['value'] == "default") {
129 b2d0140c Scott Ullrich
				$value = get_default_sysctl_value($tunable['tunable']);
130 61e047a5 Phil Davis
			} else {
131 971de1f9 Renato Botelho
				$value = $tunable['value'];
132 61e047a5 Phil Davis
			}
133 971de1f9 Renato Botelho
134
			$sysctls[$tunable['tunable']] = $value;
135 d0b461f5 sullrich
		}
136
	}
137 971de1f9 Renato Botelho
138
	set_sysctl($sysctls);
139 6df9d7e3 Scott Ullrich
}
140
141 5b237745 Scott Ullrich
function system_resolvconf_generate($dynupdate = false) {
142 c3f535c0 Seth Mos
	global $config, $g;
143
144 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
145 c3f535c0 Seth Mos
		$mt = microtime();
146
		echo "system_resolvconf_generate() being called $mt\n";
147
	}
148 ef217c69 Scott Ullrich
149 30cee7b2 Scott Ullrich
	$syscfg = $config['system'];
150 ef217c69 Scott Ullrich
151 61e047a5 Phil Davis
	if ((((isset($config['dnsmasq']['enable'])) &&
152
	      (!isset($config['dnsmasq']['port']) || $config['dnsmasq']['port'] == "53") &&
153
	      (empty($config['dnsmasq']['interface']) ||
154
	       in_array("lo0", explode(",", $config['dnsmasq']['interface'])))) ||
155
	     ((isset($config['unbound']['enable'])) &&
156
	      (!isset($config['unbound']['port']) || $config['unbound']['port'] == "53") &&
157
	      (empty($config['unbound']['active_interface']) ||
158
	       in_array("lo0", explode(",", $config['unbound']['active_interface'])) ||
159
	       in_array("all", explode(",", $config['unbound']['active_interface']), true)))) &&
160
	     (!isset($config['system']['dnslocalhost']))) {
161 6c86a39f Ermal
		$resolvconf .= "nameserver 127.0.0.1\n";
162 61e047a5 Phil Davis
	}
163 8ac329da Ermal
164 30cee7b2 Scott Ullrich
	if (isset($syscfg['dnsallowoverride'])) {
165 c3f535c0 Seth Mos
		/* get dynamically assigned DNS servers (if any) */
166 86dcdfc9 Ermal
		$ns = array_unique(get_searchdomains());
167 61e047a5 Phil Davis
		foreach ($ns as $searchserver) {
168
			if ($searchserver) {
169 86dcdfc9 Ermal
				$resolvconf .= "search {$searchserver}\n";
170 61e047a5 Phil Davis
			}
171 86dcdfc9 Ermal
		}
172 c3f535c0 Seth Mos
		$ns = array_unique(get_nameservers());
173 61e047a5 Phil Davis
		foreach ($ns as $nameserver) {
174
			if ($nameserver) {
175 c3f535c0 Seth Mos
				$resolvconf .= "nameserver $nameserver\n";
176 61e047a5 Phil Davis
			}
177 c3f535c0 Seth Mos
		}
178 e8b5f724 Chris Buechler
	} else {
179 4ad1ddf2 Phil Davis
		$ns = array();
180 e8b5f724 Chris Buechler
		// Do not create blank search/domain lines, it can break tools like dig.
181 61e047a5 Phil Davis
		if ($syscfg['domain']) {
182 97383d2b Chris Buechler
			$resolvconf .= "search {$syscfg['domain']}\n";
183 61e047a5 Phil Davis
		}
184 30cee7b2 Scott Ullrich
	}
185 8e866217 Ermal
	if (is_array($syscfg['dnsserver'])) {
186 4ad1ddf2 Phil Davis
		foreach ($syscfg['dnsserver'] as $sys_dnsserver) {
187 14a6c356 Phil Davis
			if ($sys_dnsserver && (!in_array($sys_dnsserver, $ns))) {
188 4ad1ddf2 Phil Davis
				$resolvconf .= "nameserver $sys_dnsserver\n";
189 61e047a5 Phil Davis
			}
190 e180a6e3 Scott Ullrich
		}
191 c3f535c0 Seth Mos
	}
192 0f282d7a Scott Ullrich
193 3b95d9ec Warren Baker
	// Add EDNS support
194 61e047a5 Phil Davis
	if (isset($config['unbound']['enable']) && isset($config['unbound']['edns'])) {
195 3b95d9ec Warren Baker
		$resolvconf .= "options edns0\n";
196 61e047a5 Phil Davis
	}
197 3b95d9ec Warren Baker
198 d97ff036 Ermal
	$dnslock = lock('resolvconf', LOCK_EX);
199
200 e1daff07 Ermal
	$fd = fopen("{$g['varetc_path']}/resolv.conf", "w");
201
	if (!$fd) {
202
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
203 d97ff036 Ermal
		unlock($dnslock);
204 e1daff07 Ermal
		return 1;
205
	}
206
207 30cee7b2 Scott Ullrich
	fwrite($fd, $resolvconf);
208
	fclose($fd);
209 0f282d7a Scott Ullrich
210 30501526 Warren Baker
	// Prevent resolvconf(8) from rewriting our resolv.conf
211
	$fd = fopen("{$g['varetc_path']}/resolvconf.conf", "w");
212
	if (!$fd) {
213
		printf("Error: cannot open resolvconf.conf in system_resolvconf_generate().\n");
214
		return 1;
215
	}
216
	fwrite($fd, "resolv_conf=\"/dev/null\"\n");
217
	fclose($fd);
218
219 285ef132 Ermal LUÇI
	if (!platform_booting()) {
220 c3f535c0 Seth Mos
		/* restart dhcpd (nameservers may have changed) */
221 61e047a5 Phil Davis
		if (!$dynupdate) {
222 c3f535c0 Seth Mos
			services_dhcpd_configure();
223 61e047a5 Phil Davis
		}
224 30cee7b2 Scott Ullrich
	}
225 ef217c69 Scott Ullrich
226 c3f535c0 Seth Mos
	/* setup static routes for DNS servers. */
227
	for ($dnscounter=1; $dnscounter<5; $dnscounter++) {
228
		/* setup static routes for dns servers */
229 c935003d Seth Mos
		$dnsgw = "dns{$dnscounter}gw";
230 c3f535c0 Seth Mos
		if (isset($config['system'][$dnsgw])) {
231 c935003d Seth Mos
			$gwname = $config['system'][$dnsgw];
232
			if (($gwname <> "") && ($gwname <> "none")) {
233
				$gatewayip = lookup_gateway_ip_by_name($gwname);
234
				if (is_ipaddrv4($gatewayip)) {
235 c3f535c0 Seth Mos
					/* dns server array starts at 0 */
236 b875f306 Scott Ullrich
					$dnscountermo = $dnscounter - 1;
237 12f77b03 Ermal
					mwexec("/sbin/route change -host " . $syscfg['dnsserver'][$dnscountermo] . " {$gatewayip}");
238 7bd413eb Chris Buechler
					if (isset($config['system']['route-debug'])) {
239
						$mt = microtime();
240
						log_error("ROUTING debug: $mt - route change -host {$syscfg['dnsserver'][$dnscountermo]} $gatewayip ");
241
					}
242 b875f306 Scott Ullrich
				}
243 c935003d Seth Mos
				if (is_ipaddrv6($gatewayip)) {
244
					/* dns server array starts at 0 */
245
					$dnscountermo = $dnscounter - 1;
246 12f77b03 Ermal
					mwexec("/sbin/route change -host -inet6 " . $syscfg['dnsserver'][$dnscountermo] . " {$gatewayip}");
247 7bd413eb Chris Buechler
					if (isset($config['system']['route-debug'])) {
248
						$mt = microtime();
249
						log_error("ROUTING debug: $mt - route change -host -inet6 {$syscfg['dnsserver'][$dnscountermo]} $gatewayip ");
250 61e047a5 Phil Davis
					}
251 c935003d Seth Mos
				}
252 b875f306 Scott Ullrich
			}
253 e180a6e3 Scott Ullrich
		}
254 c3f535c0 Seth Mos
	}
255 d97ff036 Ermal
256
	unlock($dnslock);
257
258 c3f535c0 Seth Mos
	return 0;
259 5b237745 Scott Ullrich
}
260
261 86dcdfc9 Ermal
function get_searchdomains() {
262
	global $config, $g;
263
264
	$master_list = array();
265 61e047a5 Phil Davis
266 86dcdfc9 Ermal
	// Read in dhclient nameservers
267 e1daff07 Ermal
	$search_list = glob("/var/etc/searchdomain_*");
268 f4a4bcbc Renato Botelho
	if (is_array($search_list)) {
269 61e047a5 Phil Davis
		foreach ($search_list as $fdns) {
270 807fd6cd Ermal
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
271 61e047a5 Phil Davis
			if (!is_array($contents)) {
272 807fd6cd Ermal
				continue;
273 61e047a5 Phil Davis
			}
274 807fd6cd Ermal
			foreach ($contents as $dns) {
275 61e047a5 Phil Davis
				if (is_hostname($dns)) {
276 807fd6cd Ermal
					$master_list[] = $dns;
277 61e047a5 Phil Davis
				}
278 807fd6cd Ermal
			}
279 86dcdfc9 Ermal
		}
280
	}
281
282
	return $master_list;
283
}
284
285 3d00ccaa Scott Ullrich
function get_nameservers() {
286
	global $config, $g;
287
	$master_list = array();
288 61e047a5 Phil Davis
289 2a1226ad Scott Ullrich
	// Read in dhclient nameservers
290 e1daff07 Ermal
	$dns_lists = glob("/var/etc/nameserver_*");
291 1033de74 Ermal
	if (is_array($dns_lists)) {
292 61e047a5 Phil Davis
		foreach ($dns_lists as $fdns) {
293 807fd6cd Ermal
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
294 61e047a5 Phil Davis
			if (!is_array($contents)) {
295 807fd6cd Ermal
				continue;
296 61e047a5 Phil Davis
			}
297 807fd6cd Ermal
			foreach ($contents as $dns) {
298 61e047a5 Phil Davis
				if (is_ipaddr($dns)) {
299 807fd6cd Ermal
					$master_list[] = $dns;
300 61e047a5 Phil Davis
				}
301 807fd6cd Ermal
			}
302 60951398 Scott Ullrich
		}
303 3d00ccaa Scott Ullrich
	}
304 2a1226ad Scott Ullrich
305
	// Read in any extra nameservers
306 61e047a5 Phil Davis
	if (file_exists("/var/etc/nameservers.conf")) {
307 33818198 Ermal
		$dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
308 61e047a5 Phil Davis
		if (is_array($dns_s)) {
309
			foreach ($dns_s as $dns) {
310
				if (is_ipaddr($dns)) {
311 1033de74 Ermal
					$master_list[] = $dns;
312 61e047a5 Phil Davis
				}
313
			}
314 e1daff07 Ermal
		}
315 2a1226ad Scott Ullrich
	}
316
317 3d00ccaa Scott Ullrich
	return $master_list;
318
}
319
320 5b237745 Scott Ullrich
function system_hosts_generate() {
321 f19d3b7a Scott Ullrich
	global $config, $g;
322 f6248774 Warren Baker
	if (isset($config['system']['developerspew'])) {
323 58c7450e Scott Ullrich
		$mt = microtime();
324 dcf0598e Scott Ullrich
		echo "system_hosts_generate() being called $mt\n";
325 f19d3b7a Scott Ullrich
	}
326 0f282d7a Scott Ullrich
327 5b237745 Scott Ullrich
	$syscfg = $config['system'];
328 61e047a5 Phil Davis
	if (isset($config['unbound']) && isset($config['unbound']['enable'])) {
329 21713b25 Renato Botelho
		$dnsmasqcfg = $config['unbound'];
330 61e047a5 Phil Davis
	} else {
331 21713b25 Renato Botelho
		$dnsmasqcfg = $config['dnsmasq'];
332 61e047a5 Phil Davis
	}
333 5b237745 Scott Ullrich
334 21713b25 Renato Botelho
	$hosts =  "127.0.0.1	localhost localhost.{$syscfg['domain']}\n";
335
	$hosts .= "::1		localhost localhost.{$syscfg['domain']}\n";
336 aa994814 Andrew Thompson
	$lhosts = "";
337
	$dhosts = "";
338 a55e9c70 Ermal Lu?i
339 e5995f9d Ermal
	if ($config['interfaces']['lan']) {
340
		$cfgip = get_interface_ip("lan");
341 61e047a5 Phil Davis
		if (is_ipaddr($cfgip)) {
342 f38f8062 Ermal
			$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
343 61e047a5 Phil Davis
		}
344 f7dddc86 Chris Buechler
		$cfgipv6 = get_interface_ipv6("lan");
345 61e047a5 Phil Davis
		if (is_ipaddrv6($cfgipv6)) {
346 f7dddc86 Chris Buechler
			$hosts .= "{$cfgipv6}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
347 61e047a5 Phil Davis
		}
348 e5995f9d Ermal
	} else {
349
		$sysiflist = get_configured_interface_list();
350 f7dddc86 Chris Buechler
		$hosts_if_found = false;
351 e5995f9d Ermal
		foreach ($sysiflist as $sysif) {
352
			if (!interface_has_gateway($sysif)) {
353
				$cfgip = get_interface_ip($sysif);
354
				if (is_ipaddr($cfgip)) {
355
					$hosts .= "{$cfgip}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
356 f7dddc86 Chris Buechler
					$hosts_if_found = true;
357
				}
358
				$cfgipv6 = get_interface_ipv6($sysif);
359
				if (is_ipaddrv6($cfgipv6)) {
360
					$hosts .= "{$cfgipv6}	{$syscfg['hostname']}.{$syscfg['domain']} {$syscfg['hostname']}\n";
361
					$hosts_if_found = true;
362 e5995f9d Ermal
				}
363 61e047a5 Phil Davis
				if ($hosts_if_found == true) {
364 f7dddc86 Chris Buechler
					break;
365 61e047a5 Phil Davis
				}
366 e5995f9d Ermal
			}
367
		}
368 f38f8062 Ermal
	}
369 0f282d7a Scott Ullrich
370 a80cb9ca PiBa-NL
	if (isset($dnsmasqcfg['enable'])) {
371 61e047a5 Phil Davis
		if (!is_array($dnsmasqcfg['hosts'])) {
372 ea1aca13 Renato Botelho
			$dnsmasqcfg['hosts'] = array();
373 61e047a5 Phil Davis
		}
374 ea1aca13 Renato Botelho
375
		foreach ($dnsmasqcfg['hosts'] as $host) {
376 6d457361 Chris Buechler
			if ($host['host'] || $host['host'] == "0") {
377 ea1aca13 Renato Botelho
				$lhosts .= "{$host['ip']}	{$host['host']}.{$host['domain']} {$host['host']}\n";
378 61e047a5 Phil Davis
			} else {
379 ea1aca13 Renato Botelho
				$lhosts .= "{$host['ip']}	{$host['domain']}\n";
380 61e047a5 Phil Davis
			}
381
			if (!is_array($host['aliases']) || !is_array($host['aliases']['item'])) {
382 ea1aca13 Renato Botelho
				continue;
383 61e047a5 Phil Davis
			}
384 ea1aca13 Renato Botelho
			foreach ($host['aliases']['item'] as $alias) {
385 6d457361 Chris Buechler
				if ($alias['host'] || $alias['host'] == "0") {
386 ea1aca13 Renato Botelho
					$lhosts .= "{$host['ip']}	{$alias['host']}.{$alias['domain']} {$alias['host']}\n";
387 61e047a5 Phil Davis
				} else {
388 ea1aca13 Renato Botelho
					$lhosts .= "{$host['ip']}	{$alias['domain']}\n";
389 61e047a5 Phil Davis
				}
390 ea1aca13 Renato Botelho
			}
391
		}
392
		if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpd'])) {
393 61e047a5 Phil Davis
			foreach ($config['dhcpd'] as $dhcpif => $dhcpifconf) {
394
				if (is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable'])) {
395
					foreach ($dhcpifconf['staticmap'] as $host) {
396
						if ($host['ipaddr'] && $host['hostname'] && $host['domain']) {
397
							$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$host['domain']} {$host['hostname']}\n";
398
						} else if ($host['ipaddr'] && $host['hostname'] && $dhcpifconf['domain']) {
399
							$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$dhcpifconf['domain']} {$host['hostname']}\n";
400
						} else if ($host['ipaddr'] && $host['hostname']) {
401
							$dhosts .= "{$host['ipaddr']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
402
						}
403
					}
404
				}
405
			}
406 ea1aca13 Renato Botelho
		}
407
		if (isset($dnsmasqcfg['regdhcpstatic']) && is_array($config['dhcpdv6'])) {
408 61e047a5 Phil Davis
			foreach ($config['dhcpdv6'] as $dhcpif => $dhcpifconf) {
409
				if (is_array($dhcpifconf['staticmap']) && isset($dhcpifconf['enable'])) {
410
					foreach ($dhcpifconf['staticmap'] as $host) {
411
						if ($host['ipaddrv6'] && $host['hostname'] && $host['domain']) {
412
							$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$host['domain']} {$host['hostname']}\n";
413
						} else if ($host['ipaddrv6'] && $host['hostname'] && $dhcpifconf['domain']) {
414
							$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$dhcpifconf['domain']} {$host['hostname']}\n";
415
						} else if ($host['ipaddrv6'] && $host['hostname']) {
416
							$dhosts .= "{$host['ipaddrv6']}	{$host['hostname']}.{$syscfg['domain']} {$host['hostname']}\n";
417
						}
418
					}
419
				}
420
			}
421
		}
422
423
		if (isset($dnsmasqcfg['dhcpfirst'])) {
424 ea1aca13 Renato Botelho
			$hosts .= $dhosts . $lhosts;
425 61e047a5 Phil Davis
		} else {
426 ea1aca13 Renato Botelho
			$hosts .= $lhosts . $dhosts;
427 61e047a5 Phil Davis
		}
428 ea1aca13 Renato Botelho
	}
429 aa994814 Andrew Thompson
430 58db1fc4 Ermal
	/*
431 61e047a5 Phil Davis
	 * Do not remove this because dhcpleases monitors with kqueue it needs to be
432 58db1fc4 Ermal
	 * killed before writing to hosts files.
433
	 */
434
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
435
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
436 ea1aca13 Renato Botelho
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
437 58db1fc4 Ermal
	}
438
	$fd = fopen("{$g['varetc_path']}/hosts", "w");
439
	if (!$fd) {
440
		log_error("Error: cannot open hosts file in system_hosts_generate().\n");
441
		return 1;
442
	}
443 5b237745 Scott Ullrich
	fwrite($fd, $hosts);
444
	fclose($fd);
445 0f282d7a Scott Ullrich
446 3f06e538 Warren Baker
	if (isset($config['unbound']['enable'])) {
447
		require_once("unbound.inc");
448 f6248774 Warren Baker
		unbound_hosts_generate();
449 3f06e538 Warren Baker
	}
450 f6248774 Warren Baker
451 24d619f5 Ermal
	return 0;
452
}
453
454
function system_dhcpleases_configure() {
455 15d456b9 gnhb
	global $config, $g;
456 61e047a5 Phil Davis
457
	if ($g['platform'] == 'jail') {
458 7734aea6 Andrew Thompson
		return;
459 61e047a5 Phil Davis
	}
460 956950de Ermal
	/* Start the monitoring process for dynamic dhcpclients. */
461 61e047a5 Phil Davis
	if ((isset($config['dnsmasq']['enable']) && isset($config['dnsmasq']['regdhcp'])) ||
462
	    (isset($config['unbound']['enable']) && isset($config['unbound']['regdhcp']))) {
463 956950de Ermal
		/* Make sure we do not error out */
464 abdd01f5 Ermal
		mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db");
465 61e047a5 Phil Davis
		if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
466 abdd01f5 Ermal
			@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
467 61e047a5 Phil Davis
		}
468 4dbcf2fb Renato Botelho
469 21713b25 Renato Botelho
		if (isset($config['unbound']['enable'])) {
470 4dbcf2fb Renato Botelho
			$dns_pid = "unbound.pid";
471 21713b25 Renato Botelho
			$unbound_conf = "-u {$g['unbound_chroot_path']}/dhcpleases_entries.conf";
472
		} else {
473 4dbcf2fb Renato Botelho
			$dns_pid = "dnsmasq.pid";
474 21713b25 Renato Botelho
			$unbound_conf = "";
475
		}
476 4dbcf2fb Renato Botelho
477
		$pidfile = "{$g['varrun_path']}/dhcpleases.pid";
478
		if (isvalidpid($pidfile)) {
479
			/* Make sure dhcpleases is using correct unbound or dnsmasq */
480
			$_gb = exec("/bin/pgrep -F {$pidfile} -f {$dns_pid}", $output, $retval);
481
			if (intval($retval) == 0) {
482
				sigkillbypid($pidfile, "HUP");
483
				return;
484 61e047a5 Phil Davis
			} else {
485 4dbcf2fb Renato Botelho
				sigkillbypid($pidfile, "TERM");
486 61e047a5 Phil Davis
			}
487 69e593c1 jim-p
		}
488 4dbcf2fb Renato Botelho
489
		/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
490 61e047a5 Phil Davis
		if (is_process_running("dhcpleases")) {
491 21713b25 Renato Botelho
			sigkillbyname('dhcpleases', "TERM");
492 61e047a5 Phil Davis
		}
493 21713b25 Renato Botelho
		@unlink($pidfile);
494
		mwexec("/usr/local/sbin/dhcpleases -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases -d {$config['system']['domain']} -p {$g['varrun_path']}/{$dns_pid} {$unbound_conf} -h {$g['varetc_path']}/hosts");
495 15d456b9 gnhb
	} else {
496 21713b25 Renato Botelho
		sigkillbypid($pidfile, "TERM");
497
		@unlink($pidfile);
498 15d456b9 gnhb
	}
499 5b237745 Scott Ullrich
}
500
501
function system_hostname_configure() {
502 f19d3b7a Scott Ullrich
	global $config, $g;
503 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
504 58c7450e Scott Ullrich
		$mt = microtime();
505 dcf0598e Scott Ullrich
		echo "system_hostname_configure() being called $mt\n";
506 333f8ef0 Scott Ullrich
	}
507 0f282d7a Scott Ullrich
508 5b237745 Scott Ullrich
	$syscfg = $config['system'];
509 0f282d7a Scott Ullrich
510 5b237745 Scott Ullrich
	/* set hostname */
511 6bfccde7 Scott Ullrich
	$status = mwexec("/bin/hostname " .
512 5b237745 Scott Ullrich
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
513 6bfccde7 Scott Ullrich
514 61e047a5 Phil Davis
	/* Setup host GUID ID.  This is used by ZFS. */
515 6bfccde7 Scott Ullrich
	mwexec("/etc/rc.d/hostid start");
516
517
	return $status;
518 5b237745 Scott Ullrich
}
519
520 1ea67f2e Ermal
function system_routing_configure($interface = "") {
521 962625aa Ermal
	global $config, $g;
522 61e047a5 Phil Davis
	if ($g['platform'] == 'jail') {
523 7734aea6 Andrew Thompson
		return;
524 61e047a5 Phil Davis
	}
525
	if (isset($config['system']['developerspew'])) {
526 58c7450e Scott Ullrich
		$mt = microtime();
527 dcf0598e Scott Ullrich
		echo "system_routing_configure() being called $mt\n";
528 58c7450e Scott Ullrich
	}
529 333f8ef0 Scott Ullrich
530 a529aced Ermal
	$gatewayip = "";
531
	$interfacegw = "";
532 5a5413bb Seth Mos
	$gatewayipv6 = "";
533
	$interfacegwv6 = "";
534 d35dfaae Ermal
	$foundgw = false;
535 5a5413bb Seth Mos
	$foundgwv6 = false;
536 a529aced Ermal
	/* tack on all the hard defined gateways as well */
537
	if (is_array($config['gateways']['gateway_item'])) {
538 873c1701 Renato Botelho
		array_map('unlink', glob("{$g['tmp_path']}/*_defaultgw{,v6}", GLOB_BRACE));
539 a529aced Ermal
		foreach	($config['gateways']['gateway_item'] as $gateway) {
540 f934af33 Ermal
			if (isset($gateway['defaultgw'])) {
541 d35dfaae Ermal
				if ($foundgw == false && ($gateway['ipprotocol'] != "inet6" && (is_ipaddrv4($gateway['gateway']) || $gateway['gateway'] == "dynamic"))) {
542 61e047a5 Phil Davis
					if (strpos($gateway['gateway'], ":")) {
543 f934af33 Ermal
						continue;
544 61e047a5 Phil Davis
					}
545
					if ($gateway['gateway'] == "dynamic") {
546 f934af33 Ermal
						$gateway['gateway'] = get_interface_gateway($gateway['interface']);
547 61e047a5 Phil Davis
					}
548 9d595f6a Ermal
					$gatewayip = $gateway['gateway'];
549 03e96afb Renato Botelho
					$interfacegw = $gateway['interface'];
550 f934af33 Ermal
					if (!empty($gateway['interface'])) {
551
						$defaultif = get_real_interface($gateway['interface']);
552 61e047a5 Phil Davis
						if ($defaultif) {
553 f934af33 Ermal
							@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gateway['gateway']);
554 61e047a5 Phil Davis
						}
555 f934af33 Ermal
					}
556
					$foundgw = true;
557 d35dfaae Ermal
				} else if ($foundgwv6 == false && ($gateway['ipprotocol'] == "inet6" && (is_ipaddrv6($gateway['gateway']) || $gateway['gateway'] == "dynamic"))) {
558 61e047a5 Phil Davis
					if ($gateway['gateway'] == "dynamic") {
559 f934af33 Ermal
						$gateway['gateway'] = get_interface_gateway_v6($gateway['interface']);
560 61e047a5 Phil Davis
					}
561 9d595f6a Ermal
					$gatewayipv6 = $gateway['gateway'];
562 03e96afb Renato Botelho
					$interfacegwv6 = $gateway['interface'];
563 f934af33 Ermal
					if (!empty($gateway['interface'])) {
564 c79f717a Ermal
						$defaultifv6 = get_real_interface($gateway['interface']);
565 61e047a5 Phil Davis
						if ($defaultifv6) {
566 f934af33 Ermal
							@file_put_contents("{$g['tmp_path']}/{$defaultifv6}_defaultgwv6", $gateway['gateway']);
567 61e047a5 Phil Davis
						}
568 f934af33 Ermal
					}
569
					$foundgwv6 = true;
570 924f202e Ermal
				}
571 a529aced Ermal
			}
572 61e047a5 Phil Davis
			if ($foundgw === true && $foundgwv6 === true) {
573 5a5413bb Seth Mos
				break;
574 61e047a5 Phil Davis
			}
575 5a5413bb Seth Mos
		}
576 b24bda08 Scott Ullrich
	}
577 3cc07282 Ermal
	if ($foundgw == false) {
578
		$defaultif = get_real_interface("wan");
579
		$interfacegw = "wan";
580
		$gatewayip = get_interface_gateway("wan");
581 d35dfaae Ermal
		@file_put_contents("{$g['tmp_path']}/{$defaultif}_defaultgw", $gatewayip);
582 61e047a5 Phil Davis
	}
583 5a5413bb Seth Mos
	if ($foundgwv6 == false) {
584 c79f717a Ermal
		$defaultifv6 = get_real_interface("wan");
585 4f332466 Seth Mos
		$interfacegwv6 = "wan";
586
		$gatewayipv6 = get_interface_gateway_v6("wan");
587 d35dfaae Ermal
		@file_put_contents("{$g['tmp_path']}/{$defaultifv6}_defaultgwv6", $gatewayipv6);
588 17a5b095 Seth Mos
	}
589 d173230c Seth Mos
	$dont_add_route = false;
590
	/* if OLSRD is enabled, allow WAN to house DHCP. */
591 f934af33 Ermal
	if (is_array($config['installedpackages']['olsrd'])) {
592 61e047a5 Phil Davis
		foreach ($config['installedpackages']['olsrd']['config'] as $olsrd) {
593
			if (($olsrd['enabledyngw'] == "on") && ($olsrd['enable'] == "on")) {
594 d173230c Seth Mos
				$dont_add_route = true;
595 f581cb10 Chris Buechler
				log_error(sprintf(gettext("Not adding default route because OLSR dynamic gateway is enabled.")));
596 6e17413e Ermal Lu?i
				break;
597 d173230c Seth Mos
			}
598
		}
599
	}
600 07b54e8c smos
601 61e047a5 Phil Davis
	if ($dont_add_route == false) {
602
		if (!empty($interface) && $interface != $interfacegw) {
603 1ea67f2e Ermal
			;
604 61e047a5 Phil Davis
		} else if (is_ipaddrv4($gatewayip)) {
605 b368b35a Ermal
			log_error("ROUTING: setting default route to $gatewayip");
606
			mwexec("/sbin/route change -inet default " . escapeshellarg($gatewayip));
607 d173230c Seth Mos
		}
608
609 61e047a5 Phil Davis
		if (!empty($interface) && $interface != $interfacegwv6) {
610 5a5413bb Seth Mos
			;
611 61e047a5 Phil Davis
		} else if (is_ipaddrv6($gatewayipv6)) {
612 8be135cd Ermal
			$ifscope = "";
613 61e047a5 Phil Davis
			if (is_linklocal($gatewayipv6) && !strpos($gatewayipv6, '%')) {
614 26ecc19c smos
				$ifscope = "%{$defaultifv6}";
615 61e047a5 Phil Davis
			}
616 ea91a8c0 smos
			log_error("ROUTING: setting IPv6 default route to {$gatewayipv6}{$ifscope}");
617 ef74c9e4 Renato Botelho
			mwexec("/sbin/route change -inet6 default " . escapeshellarg("{$gatewayipv6}{$ifscope}"));
618 5a5413bb Seth Mos
		}
619
	}
620
621 2a2b9eea Renato Botelho
	system_staticroutes_configure($interface, false);
622
623
	return 0;
624
}
625
626
function system_staticroutes_configure($interface = "", $update_dns = false) {
627
	global $config, $g, $aliastable;
628
629 356e86d4 Renato Botelho
	$filterdns_list = array();
630
631 e47d24e4 Renato Botelho
	$static_routes = get_staticroutes(false, true);
632 f898c1a9 jim-p
	if (count($static_routes)) {
633 6fdea6a2 smos
		$gateways_arr = return_gateways_array(false, true);
634 0f282d7a Scott Ullrich
635 f898c1a9 jim-p
		foreach ($static_routes as $rtent) {
636 a02708b1 Ermal
			if (empty($gateways_arr[$rtent['gateway']])) {
637 4a896b86 Carlos Eduardo Ramos
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
638 a529aced Ermal
				continue;
639
			}
640 a02708b1 Ermal
			$gateway = $gateways_arr[$rtent['gateway']];
641 61e047a5 Phil Davis
			if (!empty($interface) && $interface != $gateway['friendlyiface']) {
642 a02708b1 Ermal
				continue;
643 61e047a5 Phil Davis
			}
644 9740fad8 Seth Mos
645 a02708b1 Ermal
			$gatewayip = $gateway['gateway'];
646
			$interfacegw = $gateway['interface'];
647 a529aced Ermal
648 1e5f47bb smos
			$blackhole = "";
649 61e047a5 Phil Davis
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 3))) {
650 1e5f47bb smos
				$blackhole = "-blackhole";
651 61e047a5 Phil Davis
			}
652 1e5f47bb smos
653 61e047a5 Phil Davis
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network'])) {
654 2a2b9eea Renato Botelho
				continue;
655 61e047a5 Phil Davis
			}
656 046583c3 Renato Botelho
657 e47d24e4 Renato Botelho
			$dnscache = array();
658
			if ($update_dns === true) {
659 61e047a5 Phil Davis
				if (is_subnet($rtent['network'])) {
660 2a2b9eea Renato Botelho
					continue;
661 61e047a5 Phil Davis
				}
662 e47d24e4 Renato Botelho
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
663 61e047a5 Phil Davis
				if (empty($dnscache)) {
664 e47d24e4 Renato Botelho
					continue;
665 61e047a5 Phil Davis
				}
666 e47d24e4 Renato Botelho
			}
667 046583c3 Renato Botelho
668 61e047a5 Phil Davis
			if (is_subnet($rtent['network'])) {
669 e47d24e4 Renato Botelho
				$ips = array($rtent['network']);
670 61e047a5 Phil Davis
			} else {
671
				if (!isset($rtent['disabled'])) {
672 e47d24e4 Renato Botelho
					$filterdns_list[] = $rtent['network'];
673 61e047a5 Phil Davis
				}
674 e47d24e4 Renato Botelho
				$ips = add_hostname_to_watch($rtent['network']);
675
			}
676 2a2b9eea Renato Botelho
677 e47d24e4 Renato Botelho
			foreach ($dnscache as $ip) {
678 61e047a5 Phil Davis
				if (in_array($ip, $ips)) {
679 e47d24e4 Renato Botelho
					continue;
680 61e047a5 Phil Davis
				}
681 e47d24e4 Renato Botelho
				mwexec("/sbin/route delete " . escapeshellarg($ip), true);
682 7bd413eb Chris Buechler
				if (isset($config['system']['route-debug'])) {
683
					$mt = microtime();
684
					log_error("ROUTING debug: $mt - route delete $ip ");
685
				}
686 e47d24e4 Renato Botelho
			}
687 2a2b9eea Renato Botelho
688 e47d24e4 Renato Botelho
			if (isset($rtent['disabled'])) {
689 1f4ad8f4 Chris Buechler
				/* XXX: This can break things by deleting routes that shouldn't be deleted - OpenVPN, dynamic routing scenarios, etc. redmine #3709 */
690 7bd413eb Chris Buechler
				foreach ($ips as $ip) {
691 2a2b9eea Renato Botelho
					mwexec("/sbin/route delete " . escapeshellarg($ip), true);
692 7bd413eb Chris Buechler
					if (isset($config['system']['route-debug'])) {
693
						$mt = microtime();
694
						log_error("ROUTING debug: $mt - route delete $ip ");
695
					}
696
				}
697 e47d24e4 Renato Botelho
				continue;
698
			}
699 2a2b9eea Renato Botelho
700 e47d24e4 Renato Botelho
			foreach ($ips as $ip) {
701 61e047a5 Phil Davis
				if (is_ipaddrv4($ip)) {
702 e47d24e4 Renato Botelho
					$ip .= "/32";
703 61e047a5 Phil Davis
				}
704 e78509cc Chris Buechler
				// do NOT do the same check here on v6, is_ipaddrv6 returns true when including the CIDR mask. doing so breaks v6 routes
705 61e047a5 Phil Davis
706 e47d24e4 Renato Botelho
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
707 2a2b9eea Renato Botelho
708 e47d24e4 Renato Botelho
				$cmd = "/sbin/route change {$inet} {$blackhole} " . escapeshellarg($ip) . " ";
709
710 61e047a5 Phil Davis
				if (is_subnet($ip)) {
711 7bd413eb Chris Buechler
					if (is_ipaddr($gatewayip)) {
712 e47d24e4 Renato Botelho
						mwexec($cmd . escapeshellarg($gatewayip));
713 7bd413eb Chris Buechler
						if (isset($config['system']['route-debug'])) {
714
							$mt = microtime();
715
							log_error("ROUTING debug: $mt - $cmd $gatewayip");
716
						}
717
					} else if (!empty($interfacegw)) {
718 e47d24e4 Renato Botelho
						mwexec($cmd . "-iface " . escapeshellarg($interfacegw));
719 7bd413eb Chris Buechler
						if (isset($config['system']['route-debug'])) {
720
							$mt = microtime();
721
							log_error("ROUTING debug: $mt - $cmd -iface $interfacegw ");
722
						}
723
					}
724 61e047a5 Phil Davis
				}
725 2a2b9eea Renato Botelho
			}
726 5b237745 Scott Ullrich
		}
727 6a205b6a Ermal
		unset($gateways_arr);
728 5b237745 Scott Ullrich
	}
729 6a205b6a Ermal
	unset($static_routes);
730 67ee1ec5 Ermal Luçi
731 e47d24e4 Renato Botelho
	if ($update_dns === false) {
732
		if (count($filterdns_list)) {
733
			$interval = 60;
734
			$hostnames = "";
735
			array_unique($filterdns_list);
736 61e047a5 Phil Davis
			foreach ($filterdns_list as $hostname) {
737 e47d24e4 Renato Botelho
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
738 61e047a5 Phil Davis
			}
739 e47d24e4 Renato Botelho
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
740
			unset($hostnames);
741
742 61e047a5 Phil Davis
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid")) {
743 e47d24e4 Renato Botelho
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
744 61e047a5 Phil Davis
			} else {
745 e47d24e4 Renato Botelho
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
746 61e047a5 Phil Davis
			}
747 e47d24e4 Renato Botelho
		} else {
748
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
749
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
750
		}
751 356e86d4 Renato Botelho
	}
752 e47d24e4 Renato Botelho
	unset($filterdns_list);
753 356e86d4 Renato Botelho
754 b9c501ea Seth Mos
	return 0;
755 5b237745 Scott Ullrich
}
756
757
function system_routing_enable() {
758 f19d3b7a Scott Ullrich
	global $config, $g;
759 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
760 58c7450e Scott Ullrich
		$mt = microtime();
761 dcf0598e Scott Ullrich
		echo "system_routing_enable() being called $mt\n";
762 58c7450e Scott Ullrich
	}
763 0f282d7a Scott Ullrich
764 971de1f9 Renato Botelho
	set_sysctl(array(
765
		"net.inet.ip.forwarding" => "1",
766
		"net.inet6.ip6.forwarding" => "1"
767
	));
768
769 6da3df4e Seth Mos
	return;
770 5b237745 Scott Ullrich
}
771
772 bd29bb7b jim-p
function system_syslogd_fixup_server($server) {
773
	/* If it's an IPv6 IP alone, encase it in brackets */
774 61e047a5 Phil Davis
	if (is_ipaddrv6($server)) {
775 bd29bb7b jim-p
		return "[$server]";
776 61e047a5 Phil Davis
	} else {
777 bd29bb7b jim-p
		return $server;
778 61e047a5 Phil Davis
	}
779 bd29bb7b jim-p
}
780
781 236524c2 jim-p
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
782
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
783
	$facility .= " ".
784
	$remote_servers = "";
785
	$pad_to  = 56;
786
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
787 61e047a5 Phil Davis
	if ($syslogcfg['remoteserver']) {
788 bd29bb7b jim-p
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
789 61e047a5 Phil Davis
	}
790
	if ($syslogcfg['remoteserver2']) {
791 bd29bb7b jim-p
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
792 61e047a5 Phil Davis
	}
793
	if ($syslogcfg['remoteserver3']) {
794 bd29bb7b jim-p
		$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
795 61e047a5 Phil Davis
	}
796 236524c2 jim-p
	return $remote_servers;
797
}
798
799 5b237745 Scott Ullrich
function system_syslogd_start() {
800 f19d3b7a Scott Ullrich
	global $config, $g;
801 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
802 58c7450e Scott Ullrich
		$mt = microtime();
803 dcf0598e Scott Ullrich
		echo "system_syslogd_start() being called $mt\n";
804 58c7450e Scott Ullrich
	}
805 0f282d7a Scott Ullrich
806 1fd3fe31 Scott Ullrich
	mwexec("/etc/rc.d/hostid start");
807
808 5b237745 Scott Ullrich
	$syslogcfg = $config['syslog'];
809
810 61e047a5 Phil Davis
	if (platform_booting()) {
811 4a896b86 Carlos Eduardo Ramos
		echo gettext("Starting syslog...");
812 61e047a5 Phil Davis
	}
813 0f282d7a Scott Ullrich
814 61e047a5 Phil Davis
	if (is_process_running("fifolog_writer")) {
815 236524c2 jim-p
		mwexec('/bin/pkill fifolog_writer');
816 61e047a5 Phil Davis
	}
817 7ee97cb3 Scott Ullrich
818
	// Which logging type are we using this week??
819 100f3e71 Ermal
	if (isset($config['system']['disablesyslogclog'])) {
820
		$log_directive = "";
821
		$log_create_directive = "/usr/bin/touch ";
822
		$log_size = "";
823
	} else if (isset($config['system']['usefifolog'])) {
824
		$log_directive = "|/usr/sbin/fifolog_writer ";
825 c7a3356e jim-p
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
826 100f3e71 Ermal
		$log_create_directive = "/usr/sbin/fifolog_create -s ";
827 7ee97cb3 Scott Ullrich
	} else { // Defaults to CLOG
828 100f3e71 Ermal
		$log_directive = "%";
829 c7a3356e jim-p
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
830 2a50fd8a Renato Botelho
		$log_create_directive = "/usr/local/sbin/clog -i -s ";
831 7ee97cb3 Scott Ullrich
	}
832 66201c96 Ermal
833
	$syslogd_extra = "";
834 88ebd635 Scott Ullrich
	if (isset($syslogcfg)) {
835 20a95904 Ermal
		$separatelogfacilities = array('ntp','ntpd','ntpdate','charon','ipsec_starter','openvpn','pptps','poes','l2tps','relayd','hostapd','dnsmasq','filterdns','unbound','dhcpd','dhcrelay','dhclient','dhcp6c','apinger','radvd','routed','olsrd','zebra','ospfd','bgpd','miniupnpd','filterlog');
836 344016a8 Ermal
		$syslogconf = "";
837 61e047a5 Phil Davis
		if ($config['installedpackages']['package']) {
838
			foreach ($config['installedpackages']['package'] as $package) {
839
				if ($package['logging']) {
840 d589cccf Warren Baker
					array_push($separatelogfacilities, $package['logging']['facilityname']);
841 100f3e71 Ermal
					mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
842 eeb52fea Warren Baker
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
843 a728d2ea Colin Smith
				}
844 0d9d2a1b Scott Ullrich
			}
845
		}
846 d2834563 Scott Ullrich
		$facilitylist = implode(',', array_unique($separatelogfacilities));
847 5c8cbb26 jim-p
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,bgpd,miniupnpd\n";
848 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
849 e0c45357 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
850 61e047a5 Phil Davis
		}
851 e0c45357 jim-p
852
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
853 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
854 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
855 61e047a5 Phil Davis
		}
856 236524c2 jim-p
857 295e19dd Scott Ullrich
		$syslogconf .= "!ppp\n";
858 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
859 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
860 61e047a5 Phil Davis
		}
861 236524c2 jim-p
862 a6607b5f jim-p
		$syslogconf .= "!pptps\n";
863 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
864 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/pptps.log\n";
865 61e047a5 Phil Davis
		}
866 236524c2 jim-p
867 a6607b5f jim-p
		$syslogconf .= "!poes\n";
868 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
869 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
870 61e047a5 Phil Davis
		}
871 236524c2 jim-p
872 a6607b5f jim-p
		$syslogconf .= "!l2tps\n";
873 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
874 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/l2tps.log\n";
875 61e047a5 Phil Davis
		}
876 236524c2 jim-p
877 20a95904 Ermal
		$syslogconf .= "!charon,ipsec_starter\n";
878 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
879 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ipsec.log\n";
880 61e047a5 Phil Davis
		}
881
		if (isset($syslogcfg['vpn'])) {
882 236524c2 jim-p
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
883 61e047a5 Phil Davis
		}
884 236524c2 jim-p
885 d2834563 Scott Ullrich
		$syslogconf .= "!openvpn\n";
886 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
887 236524c2 jim-p
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/openvpn.log\n";
888 61e047a5 Phil Davis
		}
889
		if (isset($syslogcfg['vpn'])) {
890 236524c2 jim-p
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
891 61e047a5 Phil Davis
		}
892 236524c2 jim-p
893 7bc41b19 jim-p
		$syslogconf .= "!apinger\n";
894 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
895 e0977fed smos
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/gateways.log\n";
896 61e047a5 Phil Davis
		}
897
		if (isset($syslogcfg['apinger'])) {
898 e0977fed smos
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
899 61e047a5 Phil Davis
		}
900 e0977fed smos
901 a89b7342 jim-p
		$syslogconf .= "!dnsmasq,filterdns,unbound\n";
902 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
903 e0977fed smos
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
904 61e047a5 Phil Davis
		}
905 e0977fed smos
906 b462fc5e Renato Botelho
		$syslogconf .= "!dhcpd,dhcrelay,dhclient,dhcp6c\n";
907 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
908 e0977fed smos
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/dhcpd.log\n";
909 61e047a5 Phil Davis
		}
910
		if (isset($syslogcfg['dhcp'])) {
911 236524c2 jim-p
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
912 61e047a5 Phil Davis
		}
913 236524c2 jim-p
914 087a89f8 Chris Buechler
		$syslogconf .= "!relayd\n";
915 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
916 236524c2 jim-p
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/relayd.log\n";
917 61e047a5 Phil Davis
		}
918
		if (isset($syslogcfg['relayd'])) {
919 236524c2 jim-p
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
920 61e047a5 Phil Davis
		}
921 236524c2 jim-p
922 689eaa4d jim-p
		$syslogconf .= "!hostapd\n";
923 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
924 236524c2 jim-p
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
925 61e047a5 Phil Davis
		}
926
		if (isset($syslogcfg['hostapd'])) {
927 236524c2 jim-p
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
928 61e047a5 Phil Davis
		}
929 236524c2 jim-p
930 686777c4 Ermal
		$syslogconf .= "!filterlog\n";
931
		$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/filter.log\n";
932 61e047a5 Phil Davis
		if (isset($syslogcfg['filter'])) {
933 686777c4 Ermal
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
934 61e047a5 Phil Davis
		}
935 686777c4 Ermal
936 d2834563 Scott Ullrich
		$syslogconf .= "!-{$facilitylist}\n";
937 61e047a5 Phil Davis
		if (!isset($syslogcfg['disablelocallogging'])) {
938 5b237745 Scott Ullrich
			$syslogconf .= <<<EOD
939 236524c2 jim-p
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
940
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
941
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
942 2ba3ea05 Renato Botelho
*.notice;kern.debug;lpr.info;mail.crit;daemon.none;		{$log_directive}{$g['varlog_path']}/system.log
943 236524c2 jim-p
news.err;local0.none;local3.none;local4.none;			{$log_directive}{$g['varlog_path']}/system.log
944
local7.none							{$log_directive}{$g['varlog_path']}/system.log
945
security.*							{$log_directive}{$g['varlog_path']}/system.log
946
auth.info;authpriv.info;daemon.info				{$log_directive}{$g['varlog_path']}/system.log
947
auth.info;authpriv.info 					|exec /usr/local/sbin/sshlockout_pf 15
948
*.emerg								*
949 be5d59d7 Scott Ullrich
950
EOD;
951 61e047a5 Phil Davis
		}
952
		if (isset($syslogcfg['vpn'])) {
953 236524c2 jim-p
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
954 61e047a5 Phil Davis
		}
955
		if (isset($syslogcfg['portalauth'])) {
956 236524c2 jim-p
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
957 61e047a5 Phil Davis
		}
958
		if (isset($syslogcfg['dhcp'])) {
959 236524c2 jim-p
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
960 61e047a5 Phil Davis
		}
961 be5d59d7 Scott Ullrich
		if (isset($syslogcfg['system'])) {
962 236524c2 jim-p
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.notice;kern.debug;lpr.info;mail.crit;");
963
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "news.err;local0.none;local3.none;local7.none");
964
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "security.*");
965
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "auth.info;authpriv.info;daemon.info");
966
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.emerg");
967
		}
968 4ef2d703 Chris Buechler
		if (isset($syslogcfg['logall'])) {
969 236524c2 jim-p
			// Make everything mean everything, including facilities excluded above.
970
			$syslogconf .= "!*\n";
971
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
972
		}
973 be5d59d7 Scott Ullrich
974 a213ad18 Andrew Thompson
		if (isset($syslogcfg['zmqserver'])) {
975
				$syslogconf .= <<<EOD
976
*.*								^{$syslogcfg['zmqserver']}
977
978
EOD;
979
		}
980 61e047a5 Phil Davis
		/* write syslog.conf */
981 344016a8 Ermal
		if (!@file_put_contents("{$g['varetc_path']}/syslog.conf", $syslogconf)) {
982
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
983
			unset($syslogconf);
984
			return 1;
985
		}
986
		unset($syslogconf);
987 42ee8bde Scott Ullrich
988
		// Ensure that the log directory exists
989 61e047a5 Phil Davis
		if (!is_dir("{$g['dhcpd_chroot_path']}/var/run")) {
990 42ee8bde Scott Ullrich
			exec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/run");
991 61e047a5 Phil Davis
		}
992 42ee8bde Scott Ullrich
993 cbe12b8d jim-p
		$sourceip = "";
994
		if (!empty($syslogcfg['sourceip'])) {
995
			if ($syslogcfg['ipproto'] == "ipv6") {
996
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
997 61e047a5 Phil Davis
				if (!is_ipaddr($ifaddr)) {
998 cbe12b8d jim-p
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
999 61e047a5 Phil Davis
				}
1000 cbe12b8d jim-p
			} else {
1001
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
1002 61e047a5 Phil Davis
				if (!is_ipaddr($ifaddr)) {
1003 cbe12b8d jim-p
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
1004 61e047a5 Phil Davis
				}
1005 cbe12b8d jim-p
			}
1006
			if (is_ipaddr($ifaddr)) {
1007
				$sourceip = "-b {$ifaddr}";
1008
			}
1009
		}
1010
1011 66201c96 Ermal
		$syslogd_extra = "-f {$g['varetc_path']}/syslog.conf {$sourceip}";
1012 5b237745 Scott Ullrich
	}
1013 0f282d7a Scott Ullrich
1014 209ba3aa Chris Buechler
	if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1015 f1905a3e Chris Buechler
		sigkillbypid("{$g['varrun_path']}/syslog.pid", "TERM");
1016 209ba3aa Chris Buechler
		usleep(100000); // syslogd often doesn't respond to a TERM quickly enough for the starting of syslogd below to be successful
1017
	}
1018 61e047a5 Phil Davis
1019 209ba3aa Chris Buechler
	if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1020 61e047a5 Phil Davis
		// if it still hasn't responded to the TERM, KILL it.
1021 209ba3aa Chris Buechler
		sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
1022 61e047a5 Phil Davis
		usleep(100000);
1023 209ba3aa Chris Buechler
	}
1024
1025 61e047a5 Phil Davis
1026 f1905a3e Chris Buechler
	$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c -l {$g['dhcpd_chroot_path']}/var/run/log -P {$g['varrun_path']}/syslog.pid {$syslogd_extra}");
1027 66201c96 Ermal
1028 61e047a5 Phil Davis
	if (platform_booting()) {
1029 4a896b86 Carlos Eduardo Ramos
		echo gettext("done.") . "\n";
1030 61e047a5 Phil Davis
	}
1031 0f282d7a Scott Ullrich
1032 5b237745 Scott Ullrich
	return $retval;
1033
}
1034
1035 7c4c77ee jim-p
function system_webgui_create_certificate() {
1036
	global $config, $g;
1037
1038 61e047a5 Phil Davis
	if (!is_array($config['ca'])) {
1039 7c4c77ee jim-p
		$config['ca'] = array();
1040 61e047a5 Phil Davis
	}
1041 7c4c77ee jim-p
	$a_ca =& $config['ca'];
1042 61e047a5 Phil Davis
	if (!is_array($config['cert'])) {
1043 7c4c77ee jim-p
		$config['cert'] = array();
1044 61e047a5 Phil Davis
	}
1045 7c4c77ee jim-p
	$a_cert =& $config['cert'];
1046
	log_error("Creating SSL Certificate for this host");
1047
1048
	$cert = array();
1049
	$cert['refid'] = uniqid();
1050 2cf2c62b jim-p
	$cert['descr'] = gettext("webConfigurator default ({$cert['refid']})");
1051 7c4c77ee jim-p
1052
	$dn = array(
1053
		'countryName' => "US",
1054
		'stateOrProvinceName' => "State",
1055
		'localityName' => "Locality",
1056
		'organizationName' => "{$g['product_name']} webConfigurator Self-Signed Certificate",
1057
		'emailAddress' => "admin@{$config['system']['hostname']}.{$config['system']['domain']}",
1058 2cf2c62b jim-p
		'commonName' => "{$config['system']['hostname']}-{$cert['refid']}");
1059 f416763b Phil Davis
	$old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warnings directly to a page screwing menu tab */
1060 61e047a5 Phil Davis
	if (!cert_create($cert, null, 2048, 2000, $dn, "self-signed", "sha256")) {
1061
		while ($ssl_err = openssl_error_string()) {
1062 7c4c77ee jim-p
			log_error("Error creating WebGUI Certificate: openssl library returns: " . $ssl_err);
1063
		}
1064
		error_reporting($old_err_level);
1065
		return null;
1066
	}
1067
	error_reporting($old_err_level);
1068
1069
	$a_cert[] = $cert;
1070
	$config['system']['webgui']['ssl-certref'] = $cert['refid'];
1071 2cf2c62b jim-p
	write_config(gettext("Generated new self-signed HTTPS certificate ({$cert['refid']})"));
1072 7c4c77ee jim-p
	return $cert;
1073
}
1074
1075 5b237745 Scott Ullrich
function system_webgui_start() {
1076 f19d3b7a Scott Ullrich
	global $config, $g;
1077 877ac35d Scott Ullrich
1078 61e047a5 Phil Davis
	if (platform_booting()) {
1079 4a896b86 Carlos Eduardo Ramos
		echo gettext("Starting webConfigurator...");
1080 61e047a5 Phil Davis
	}
1081 877ac35d Scott Ullrich
1082
	chdir($g['www_path']);
1083
1084 fb1266d3 Matthew Grooms
	/* defaults */
1085
	$portarg = "80";
1086
	$crt = "";
1087
	$key = "";
1088 2cf6ddcb Nigel Graham
	$ca = "";
1089 fb1266d3 Matthew Grooms
1090 877ac35d Scott Ullrich
	/* non-standard port? */
1091 61e047a5 Phil Davis
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "") {
1092 528df9a7 Scott Ullrich
		$portarg = "{$config['system']['webgui']['port']}";
1093 61e047a5 Phil Davis
	}
1094 877ac35d Scott Ullrich
1095
	if ($config['system']['webgui']['protocol'] == "https") {
1096 02b383fe sullrich
		// Ensure that we have a webConfigurator CERT
1097 fb1266d3 Matthew Grooms
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
1098 61e047a5 Phil Davis
		if (!is_array($cert) || !$cert['crt'] || !$cert['prv']) {
1099 7c4c77ee jim-p
			$cert = system_webgui_create_certificate();
1100 61e047a5 Phil Davis
		}
1101 0a8dd27b Renato Botelho
		$crt = base64_decode($cert['crt']);
1102
		$key = base64_decode($cert['prv']);
1103 7c4c77ee jim-p
1104 61e047a5 Phil Davis
		if (!$config['system']['webgui']['port']) {
1105 7c4c77ee jim-p
			$portarg = "443";
1106 61e047a5 Phil Davis
		}
1107 7c4c77ee jim-p
		$ca  = ca_chain($cert);
1108 877ac35d Scott Ullrich
	}
1109
1110
	/* generate lighttpd configuration */
1111
	system_generate_lighty_config("{$g['varetc_path']}/lighty-webConfigurator.conf",
1112 c41602e1 jim-p
		$crt, $key, $ca, "lighty-webConfigurator.pid", $portarg, "/usr/local/www/",
1113 98f20e35 Irving Popovetsky
		"cert.pem", "ca.pem");
1114 877ac35d Scott Ullrich
1115 a11bc497 Ermal
	/* kill any running lighttpd */
1116
	killbypid("{$g['varrun_path']}/lighty-webConfigurator.pid");
1117
1118
	sleep(1);
1119
1120
	@unlink("{$g['varrun_path']}/lighty-webConfigurator.pid");
1121
1122 877ac35d Scott Ullrich
	/* attempt to start lighthttpd */
1123
	$res = mwexec("/usr/local/sbin/lighttpd -f {$g['varetc_path']}/lighty-webConfigurator.conf");
1124
1125 285ef132 Ermal LUÇI
	if (platform_booting()) {
1126 61e047a5 Phil Davis
		if ($res == 0) {
1127 4a896b86 Carlos Eduardo Ramos
			echo gettext("done.") . "\n";
1128 61e047a5 Phil Davis
		} else {
1129 4a896b86 Carlos Eduardo Ramos
			echo gettext("failed!") . "\n";
1130 61e047a5 Phil Davis
		}
1131 877ac35d Scott Ullrich
	}
1132
1133
	return $res;
1134
}
1135
1136 eb0f441c Scott Ullrich
function system_generate_lighty_config($filename,
1137
	$cert,
1138
	$key,
1139 2cf6ddcb Nigel Graham
	$ca,
1140 eb0f441c Scott Ullrich
	$pid_file,
1141
	$port = 80,
1142
	$document_root = "/usr/local/www/",
1143
	$cert_location = "cert.pem",
1144 2cf6ddcb Nigel Graham
	$ca_location = "ca.pem",
1145 eb0f441c Scott Ullrich
	$captive_portal = false) {
1146 58c7450e Scott Ullrich
1147 f19d3b7a Scott Ullrich
	global $config, $g;
1148
1149 61e047a5 Phil Davis
	if (!is_dir("{$g['tmp_path']}/lighttpdcompress")) {
1150 6955830f Ermal Lu?i
		mkdir("{$g['tmp_path']}/lighttpdcompress");
1151 61e047a5 Phil Davis
	}
1152 570ef08c sullrich
1153 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
1154 58c7450e Scott Ullrich
		$mt = microtime();
1155 dcf0598e Scott Ullrich
		echo "system_generate_lighty_config() being called $mt\n";
1156 58c7450e Scott Ullrich
	}
1157
1158 a96f2d3d Ermal
	if ($captive_portal !== false)  {
1159 f7bddb24 Ermal
		$captiveportal = ",\"mod_rewrite\",\"mod_evasive\"";
1160 b4792bf8 Ermal
		$captive_portal_rewrite = "url.rewrite-once = ( \"(.*captiveportal.*)\" => \"$1\", \"(.*)\" => \"/index.php?zone={$captive_portal}&redirurl=$1\" )\n";
1161 74a4edc3 Ermal
1162 6844896c bcyrill
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1163 61e047a5 Phil Davis
		if (empty($maxprocperip)) {
1164 f7bddb24 Ermal
			$maxprocperip = 10;
1165 61e047a5 Phil Davis
		}
1166 74a4edc3 Ermal
		$captive_portal_mod_evasive = "evasive.max-conns-per-ip = {$maxprocperip}";
1167
1168 6955830f Ermal Lu?i
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['tmp_path']}/captiveportal/\" )\n";
1169 61e047a5 Phil Davis
		if (!is_dir("{$g['tmp_path']}/captiveportal")) {
1170 e570f0eb Ermal
			@mkdir("{$g['tmp_path']}/captiveportal", 0555);
1171 61e047a5 Phil Davis
		}
1172 775556ab Scott Ullrich
		$server_max_request_size = "server.max-request-size    = 384";
1173 b35fdb17 Ermal
		$cgi_config = "";
1174 b0bdc06e Scott Ullrich
	} else {
1175 b35fdb17 Ermal
		$captiveportal = ",\"mod_cgi\"";
1176 3435dc35 Ermal Lu?i
		$captive_portal_rewrite = "";
1177 b0bdc06e Scott Ullrich
		$captive_portal_mod_evasive = "";
1178 6955830f Ermal Lu?i
		$server_upload_dirs = "server.upload-dirs = ( \"{$g['upload_path']}/\", \"{$g['tmp_path']}/\", \"/var/\" )\n";
1179 775556ab Scott Ullrich
		$server_max_request_size = "server.max-request-size    = 2097152";
1180 b35fdb17 Ermal
		$cgi_config = "cgi.assign                 = ( \".cgi\" => \"\" )";
1181 eb0f441c Scott Ullrich
	}
1182 61e047a5 Phil Davis
1183
	if (empty($port)) {
1184 28cae949 Scott Ullrich
		$lighty_port = "80";
1185 61e047a5 Phil Davis
	} else {
1186 a96f2d3d Ermal
		$lighty_port = $port;
1187 61e047a5 Phil Davis
	}
1188 3d77d4c4 Scott Ullrich
1189
	$memory = get_memory();
1190 6b0739ac Phil Davis
	$realmem = $memory[1];
1191 3d77d4c4 Scott Ullrich
1192 98f20e35 Irving Popovetsky
	// Determine web GUI process settings and take into account low memory systems
1193 61e047a5 Phil Davis
	if ($realmem < 255) {
1194 a96f2d3d Ermal
		$max_procs = 1;
1195 61e047a5 Phil Davis
	} else {
1196 98f20e35 Irving Popovetsky
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
1197 61e047a5 Phil Davis
	}
1198 f4ebc84a Scott Ullrich
1199 61e047a5 Phil Davis
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM
1200 70e454e1 Ermal
	if ($captive_portal !== false)  {
1201 6b0739ac Phil Davis
		if ($realmem > 135 and $realmem < 256) {
1202 98f20e35 Irving Popovetsky
			$max_procs += 1; // 2 worker processes
1203 6b0739ac Phil Davis
		} else if ($realmem > 255 and $realmem < 513) {
1204 a96f2d3d Ermal
			$max_procs += 2; // 3 worker processes
1205 6b0739ac Phil Davis
		} else if ($realmem > 512) {
1206 98f20e35 Irving Popovetsky
			$max_procs += 4; // 6 worker processes
1207 70cc6249 Scott Ullrich
		}
1208 61e047a5 Phil Davis
		if ($max_procs > 1) {
1209 a96f2d3d Ermal
			$max_php_children = intval($max_procs/2);
1210 61e047a5 Phil Davis
		} else {
1211 a96f2d3d Ermal
			$max_php_children = 1;
1212 61e047a5 Phil Davis
		}
1213 a96f2d3d Ermal
1214 e384f16e Ermal
	} else {
1215 61e047a5 Phil Davis
		if ($realmem < 78) {
1216 e384f16e Ermal
			$max_php_children = 0;
1217 61e047a5 Phil Davis
		} else {
1218 e384f16e Ermal
			$max_php_children = 1;
1219 61e047a5 Phil Davis
		}
1220 e384f16e Ermal
	}
1221 980df75c Scott Ullrich
1222 61e047a5 Phil Davis
	if (!isset($config['syslog']['nologlighttpd'])) {
1223 1cf24f0a jim-p
		$lighty_use_syslog = <<<EOD
1224
## where to send error-messages to
1225
server.errorlog-use-syslog="enable"
1226
EOD;
1227
	}
1228
1229
1230 4aea91d8 Ermal
	if ($captive_portal !== false) {
1231
		$fast_cgi_path = "{$g['tmp_path']}/php-fastcgi-{$captive_portal}.socket";
1232
		$fastcgi_config = <<<EOD
1233 4edb490d Scott Ullrich
#### fastcgi module
1234
## read fastcgi.txt for more info
1235 b0bdc06e Scott Ullrich
fastcgi.server = ( ".php" =>
1236 a96f2d3d Ermal
	( "localhost" =>
1237
		(
1238
			"socket" => "{$fast_cgi_path}",
1239
			"max-procs" => {$max_procs},
1240 70e454e1 Ermal
			"bin-environment" => (
1241
				"PHP_FCGI_CHILDREN" => "{$max_php_children}",
1242
				"PHP_FCGI_MAX_REQUESTS" => "500"
1243
			),
1244 a96f2d3d Ermal
			"bin-path" => "/usr/local/bin/php"
1245
		)
1246 b0bdc06e Scott Ullrich
	)
1247
)
1248 333f8ef0 Scott Ullrich
1249 4edb490d Scott Ullrich
EOD;
1250 4aea91d8 Ermal
	} else {
1251
		$fast_cgi_path = "{$g['varrun_path']}/php-fpm.socket";
1252
		$fastcgi_config = <<<EOD
1253
#### fastcgi module
1254
## read fastcgi.txt for more info
1255
fastcgi.server = ( ".php" =>
1256
	( "localhost" =>
1257
		(
1258
			"socket" => "{$fast_cgi_path}",
1259
			"broken-scriptfilename" => "enable"
1260
		)
1261
	)
1262
)
1263
1264
EOD;
1265
	}
1266
1267 333f8ef0 Scott Ullrich
1268 a96f2d3d Ermal
	$lighty_config = <<<EOD
1269 28cae949 Scott Ullrich
#
1270 a632cf43 Scott Ullrich
# lighttpd configuration file
1271
#
1272
# use a it as base for lighttpd 1.0.0 and above
1273 28cae949 Scott Ullrich
#
1274 a632cf43 Scott Ullrich
############ Options you really have to take care of ####################
1275
1276 770b4b9c Scott Ullrich
## FreeBSD!
1277 60ff6204 Scott Ullrich
server.event-handler	= "freebsd-kqueue"
1278
server.network-backend 	= "writev"
1279 543ecd59 Seth Mos
#server.use-ipv6 = "enable"
1280 096261af Scott Ullrich
1281 a632cf43 Scott Ullrich
## modules to load
1282 f7bddb24 Ermal
server.modules              =   ( "mod_access", "mod_expire", "mod_compress", "mod_redirect",
1283
	{$captiveportal}, "mod_fastcgi"
1284 a41c5253 Seth Mos
)
1285 28cae949 Scott Ullrich
1286 d9acea75 Scott Ullrich
server.max-keep-alive-requests = 15
1287
server.max-keep-alive-idle = 30
1288
1289 a632cf43 Scott Ullrich
## a static document-root, for virtual-hosting take look at the
1290
## server.virtual-* options
1291 332b4ac0 Scott Ullrich
server.document-root        = "{$document_root}"
1292 eb0f441c Scott Ullrich
{$captive_portal_rewrite}
1293 a632cf43 Scott Ullrich
1294 38a9a1ab Scott Ullrich
# Maximum idle time with nothing being written (php downloading)
1295
server.max-write-idle = 999
1296
1297 1cf24f0a jim-p
{$lighty_use_syslog}
1298 a632cf43 Scott Ullrich
1299
# files to check for if .../ is requested
1300
server.indexfiles           = ( "index.php", "index.html",
1301
                                "index.htm", "default.htm" )
1302
1303
# mimetype mapping
1304
mimetype.assign             = (
1305
  ".pdf"          =>      "application/pdf",
1306
  ".sig"          =>      "application/pgp-signature",
1307
  ".spl"          =>      "application/futuresplash",
1308
  ".class"        =>      "application/octet-stream",
1309
  ".ps"           =>      "application/postscript",
1310
  ".torrent"      =>      "application/x-bittorrent",
1311
  ".dvi"          =>      "application/x-dvi",
1312
  ".gz"           =>      "application/x-gzip",
1313
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
1314
  ".swf"          =>      "application/x-shockwave-flash",
1315
  ".tar.gz"       =>      "application/x-tgz",
1316
  ".tgz"          =>      "application/x-tgz",
1317
  ".tar"          =>      "application/x-tar",
1318
  ".zip"          =>      "application/zip",
1319
  ".mp3"          =>      "audio/mpeg",
1320
  ".m3u"          =>      "audio/x-mpegurl",
1321
  ".wma"          =>      "audio/x-ms-wma",
1322
  ".wax"          =>      "audio/x-ms-wax",
1323
  ".ogg"          =>      "audio/x-wav",
1324
  ".wav"          =>      "audio/x-wav",
1325
  ".gif"          =>      "image/gif",
1326
  ".jpg"          =>      "image/jpeg",
1327
  ".jpeg"         =>      "image/jpeg",
1328
  ".png"          =>      "image/png",
1329
  ".xbm"          =>      "image/x-xbitmap",
1330
  ".xpm"          =>      "image/x-xpixmap",
1331
  ".xwd"          =>      "image/x-xwindowdump",
1332
  ".css"          =>      "text/css",
1333
  ".html"         =>      "text/html",
1334
  ".htm"          =>      "text/html",
1335
  ".js"           =>      "text/javascript",
1336
  ".asc"          =>      "text/plain",
1337
  ".c"            =>      "text/plain",
1338
  ".conf"         =>      "text/plain",
1339
  ".text"         =>      "text/plain",
1340
  ".txt"          =>      "text/plain",
1341
  ".dtd"          =>      "text/xml",
1342
  ".xml"          =>      "text/xml",
1343
  ".mpeg"         =>      "video/mpeg",
1344
  ".mpg"          =>      "video/mpeg",
1345
  ".mov"          =>      "video/quicktime",
1346
  ".qt"           =>      "video/quicktime",
1347
  ".avi"          =>      "video/x-msvideo",
1348
  ".asf"          =>      "video/x-ms-asf",
1349
  ".asx"          =>      "video/x-ms-asf",
1350
  ".wmv"          =>      "video/x-ms-wmv",
1351
  ".bz2"          =>      "application/x-bzip",
1352
  ".tbz"          =>      "application/x-bzip-compressed-tar",
1353
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
1354
 )
1355
1356
# Use the "Content-Type" extended attribute to obtain mime type if possible
1357
#mimetypes.use-xattr        = "enable"
1358
1359
## deny access the file-extensions
1360
#
1361
# ~    is for backupfiles from vi, emacs, joe, ...
1362
# .inc is often used for code includes which should in general not be part
1363
#      of the document-root
1364
url.access-deny             = ( "~", ".inc" )
1365
1366
1367 f416763b Phil Davis
######### Options that are good to be but not necessary to be changed #######
1368 a632cf43 Scott Ullrich
1369 2400f545 Jose Luis Duran
## disable server header
1370
server.tag = ""
1371
1372 a632cf43 Scott Ullrich
## bind to port (default: 80)
1373 9cb94dd4 Ermal
1374
EOD;
1375
1376 6839a678 Ermal
	$lighty_config .= "server.bind  = \"0.0.0.0\"\n";
1377
	$lighty_config .= "server.port  = {$lighty_port}\n";
1378
	$lighty_config .= "\$SERVER[\"socket\"]  == \"0.0.0.0:{$lighty_port}\" { }\n";
1379
	$lighty_config .= "\$SERVER[\"socket\"]  == \"[::]:{$lighty_port}\" { \n";
1380 61e047a5 Phil Davis
	if ($cert <> "" and $key <> "") {
1381 6839a678 Ermal
		$lighty_config .= "\n";
1382
		$lighty_config .= "## ssl configuration\n";
1383
		$lighty_config .= "ssl.engine = \"enable\"\n";
1384
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1385 61e047a5 Phil Davis
		if ($ca <> "") {
1386 6839a678 Ermal
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1387 61e047a5 Phil Davis
		}
1388 543ecd59 Seth Mos
	}
1389 6839a678 Ermal
	$lighty_config .= " }\n";
1390 543ecd59 Seth Mos
1391 9cb94dd4 Ermal
1392
	$lighty_config .= <<<EOD
1393 a632cf43 Scott Ullrich
1394
## error-handler for status 404
1395
#server.error-handler-404   = "/error-handler.html"
1396
#server.error-handler-404   = "/error-handler.php"
1397
1398
## to help the rc.scripts
1399 e141ea70 Ermal
server.pid-file            = "{$g['varrun_path']}/{$pid_file}"
1400 a632cf43 Scott Ullrich
1401
## virtual directory listings
1402 28cae949 Scott Ullrich
server.dir-listing         = "disable"
1403 a632cf43 Scott Ullrich
1404
## enable debugging
1405 28cae949 Scott Ullrich
debug.log-request-header   = "disable"
1406
debug.log-response-header  = "disable"
1407
debug.log-request-handling = "disable"
1408
debug.log-file-not-found   = "disable"
1409 a632cf43 Scott Ullrich
1410 570ef08c sullrich
# gzip compression
1411 6955830f Ermal Lu?i
compress.cache-dir = "{$g['tmp_path']}/lighttpdcompress/"
1412 570ef08c sullrich
compress.filetype  = ("text/plain","text/css", "text/xml", "text/javascript" )
1413
1414 3306a341 Scott Ullrich
{$server_upload_dirs}
1415 1ef7b568 Scott Ullrich
1416 a6e8af9c Scott Ullrich
{$server_max_request_size}
1417 ee959dc4 Scott Ullrich
1418 4edb490d Scott Ullrich
{$fastcgi_config}
1419
1420 b35fdb17 Ermal
{$cgi_config}
1421
1422 b0bdc06e Scott Ullrich
{$captive_portal_mod_evasive}
1423
1424 569f47e9 Scott Ullrich
expire.url = (
1425 61e047a5 Phil Davis
		"" => "access 50 hours",
1426
	)
1427 569f47e9 Scott Ullrich
1428 a632cf43 Scott Ullrich
EOD;
1429
1430 7aae518a Scott Ullrich
	$cert = str_replace("\r", "", $cert);
1431 333f8ef0 Scott Ullrich
	$key = str_replace("\r", "", $key);
1432 2cf6ddcb Nigel Graham
	$ca = str_replace("\r", "", $ca);
1433 7aae518a Scott Ullrich
1434
	$cert = str_replace("\n\n", "\n", $cert);
1435 333f8ef0 Scott Ullrich
	$key = str_replace("\n\n", "\n", $key);
1436 2cf6ddcb Nigel Graham
	$ca = str_replace("\n\n", "\n", $ca);
1437 7aae518a Scott Ullrich
1438 61e047a5 Phil Davis
	if ($cert <> "" and $key <> "") {
1439 3a66b621 Scott Ullrich
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1440 5b237745 Scott Ullrich
		if (!$fd) {
1441 4a896b86 Carlos Eduardo Ramos
			printf(gettext("Error: cannot open cert.pem in system_webgui_start().%s"), "\n");
1442 5b237745 Scott Ullrich
			return 1;
1443
		}
1444 3a66b621 Scott Ullrich
		chmod("{$g['varetc_path']}/{$cert_location}", 0600);
1445 5b237745 Scott Ullrich
		fwrite($fd, $cert);
1446
		fwrite($fd, "\n");
1447
		fwrite($fd, $key);
1448
		fclose($fd);
1449 61e047a5 Phil Davis
		if (!(empty($ca) || (strlen(trim($ca)) == 0))) {
1450 2cf6ddcb Nigel Graham
			$fd = fopen("{$g['varetc_path']}/{$ca_location}", "w");
1451
			if (!$fd) {
1452 4a896b86 Carlos Eduardo Ramos
				printf(gettext("Error: cannot open ca.pem in system_webgui_start().%s"), "\n");
1453 2cf6ddcb Nigel Graham
				return 1;
1454
			}
1455
			chmod("{$g['varetc_path']}/{$ca_location}", 0600);
1456
			fwrite($fd, $ca);
1457
			fclose($fd);
1458
		}
1459 5e041d5f Scott Ullrich
		$lighty_config .= "\n";
1460 4a896b86 Carlos Eduardo Ramos
		$lighty_config .= "## " . gettext("ssl configuration") . "\n";
1461 a632cf43 Scott Ullrich
		$lighty_config .= "ssl.engine = \"enable\"\n";
1462 333f8ef0 Scott Ullrich
		$lighty_config .= "ssl.pemfile = \"{$g['varetc_path']}/{$cert_location}\"\n\n";
1463 673ee7b1 Scott Ullrich
1464 756d867a Chris Buechler
		// SSLv2/3 is deprecated, force use of TLS
1465 673ee7b1 Scott Ullrich
		$lighty_config .= "ssl.use-sslv2 = \"disable\"\n";
1466 5ff7f58e jim-p
		$lighty_config .= "ssl.use-sslv3 = \"disable\"\n";
1467 dce51b01 jim-p
1468 0f575511 Chris Buechler
		// where ssl.cipher-list is set, this is automatically enabled, but set it explicitly anyway.
1469
		$lighty_config .= "ssl.honor-cipher-order = \"enable\"\n";
1470 3a0a59c8 Renato Botelho
1471
		$lighty_config .= "ssl.cipher-list = \"AES128+EECDH:AES256+EECDH:AES128+EDH:AES256+EDH:AES128-SHA:AES256-SHA:!aNULL:!eNULL:!DSS\"\n";
1472 673ee7b1 Scott Ullrich
1473 61e047a5 Phil Davis
		if (!(empty($ca) || (strlen(trim($ca)) == 0))) {
1474 2cf6ddcb Nigel Graham
			$lighty_config .= "ssl.ca-file = \"{$g['varetc_path']}/{$ca_location}\"\n\n";
1475 61e047a5 Phil Davis
		}
1476 5b237745 Scott Ullrich
	}
1477 a978a0ff Chris Buechler
1478 61e047a5 Phil Davis
	// Add HTTP to HTTPS redirect
1479 6839a678 Ermal
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1480 61e047a5 Phil Davis
		if ($lighty_port != "443") {
1481 7921e8e5 Chris Buechler
			$redirectport = ":{$lighty_port}";
1482 61e047a5 Phil Davis
		}
1483 d7e230ae Chris Buechler
		$lighty_config .= <<<EOD
1484
\$SERVER["socket"] == ":80" {
1485
	\$HTTP["host"] =~ "(.*)" {
1486 7921e8e5 Chris Buechler
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1487 d7e230ae Chris Buechler
	}
1488
}
1489 64a2da80 Chris Buechler
\$SERVER["socket"] == "[::]:80" {
1490
	\$HTTP["host"] =~ "(.*)" {
1491
		url.redirect = ( "^/(.*)" => "https://%1{$redirectport}/$1" )
1492
	}
1493
}
1494 d7e230ae Chris Buechler
EOD;
1495
	}
1496 0f282d7a Scott Ullrich
1497 4f3756f3 Scott Ullrich
	$fd = fopen("{$filename}", "w");
1498 a632cf43 Scott Ullrich
	if (!$fd) {
1499 4a896b86 Carlos Eduardo Ramos
		printf(gettext("Error: cannot open %s in system_generate_lighty_config().%s"), $filename, "\n");
1500 a632cf43 Scott Ullrich
		return 1;
1501 5b237745 Scott Ullrich
	}
1502 a632cf43 Scott Ullrich
	fwrite($fd, $lighty_config);
1503
	fclose($fd);
1504
1505
	return 0;
1506 0f282d7a Scott Ullrich
1507 5b237745 Scott Ullrich
}
1508
1509
function system_timezone_configure() {
1510 f19d3b7a Scott Ullrich
	global $config, $g;
1511 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
1512 58c7450e Scott Ullrich
		$mt = microtime();
1513 dcf0598e Scott Ullrich
		echo "system_timezone_configure() being called $mt\n";
1514 333f8ef0 Scott Ullrich
	}
1515 5b237745 Scott Ullrich
1516
	$syscfg = $config['system'];
1517
1518 61e047a5 Phil Davis
	if (platform_booting()) {
1519 4a896b86 Carlos Eduardo Ramos
		echo gettext("Setting timezone...");
1520 61e047a5 Phil Davis
	}
1521 5b237745 Scott Ullrich
1522
	/* extract appropriate timezone file */
1523
	$timezone = $syscfg['timezone'];
1524 add913b1 Renato Botelho
	if ($timezone) {
1525
		exec('/usr/bin/tar -tvzf /usr/share/zoneinfo.tgz', $tzs);
1526
		foreach ($tzs as $tz) {
1527 61e047a5 Phil Davis
			if (preg_match(",{$timezone}$,", $tz)) {
1528 add913b1 Renato Botelho
				break;
1529 61e047a5 Phil Davis
			}
1530 add913b1 Renato Botelho
			if (preg_match(",{$timezone} link to *(.*)$,", $tz, $matches)) {
1531
				$timezone = $matches[1];
1532
				break;
1533
			}
1534
		}
1535 61e047a5 Phil Davis
	} else {
1536 5b237745 Scott Ullrich
		$timezone = "Etc/UTC";
1537 61e047a5 Phil Davis
	}
1538 0f282d7a Scott Ullrich
1539 34febcde Scott Ullrich
	conf_mount_rw();
1540
1541 029d1a71 Scott Ullrich
	exec("LANG=C /usr/bin/tar xzfO /usr/share/zoneinfo.tgz " .
1542 5b237745 Scott Ullrich
		escapeshellarg($timezone) . " > /etc/localtime");
1543
1544 4efd4885 Scott Ullrich
	mwexec("sync");
1545 27150275 Scott Ullrich
	conf_mount_ro();
1546 34febcde Scott Ullrich
1547 61e047a5 Phil Davis
	if (platform_booting()) {
1548 4a896b86 Carlos Eduardo Ramos
		echo gettext("done.") . "\n";
1549 61e047a5 Phil Davis
	}
1550 5b237745 Scott Ullrich
}
1551
1552 5c8843d5 jim-p
function system_ntp_setup_gps($serialport) {
1553 142f7393 nagyrobi
	global $config, $g;
1554 5c8843d5 jim-p
	$gps_device = '/dev/gps0';
1555
	$serialport = '/dev/'.$serialport;
1556
1557 61e047a5 Phil Davis
	if (!file_exists($serialport)) {
1558 5c8843d5 jim-p
		return false;
1559 61e047a5 Phil Davis
	}
1560 5c8843d5 jim-p
1561
	conf_mount_rw();
1562
	// Create symlink that ntpd requires
1563
	unlink_if_exists($gps_device);
1564 11caacf6 Ermal LUÇI
	@symlink($serialport, $gps_device);
1565 5c8843d5 jim-p
1566
	/* Send the following to the GPS port to initialize the GPS */
1567 ec7bc948 Ermal
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
1568 142f7393 nagyrobi
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
1569 61e047a5 Phil Davis
	} else {
1570 142f7393 nagyrobi
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1571
	}
1572 ec7bc948 Ermal
1573
	/* XXX: Why not file_put_contents to the device */
1574
	@file_put_contents('/tmp/gps.init', $gps_init);
1575 18080a21 jim-p
	`cat /tmp/gps.init > $serialport`;
1576 5c8843d5 jim-p
1577
	/* Add /etc/remote entry in case we need to read from the GPS with tip */
1578 ec7bc948 Ermal
	if (intval(`grep -c '^gps0' /etc/remote`) == 0) {
1579 142f7393 nagyrobi
		$gpsbaud = '4800';
1580 ec7bc948 Ermal
		if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['speed'])) {
1581 61e047a5 Phil Davis
			switch ($config['ntpd']['gps']['speed']) {
1582 142f7393 nagyrobi
				case '16':
1583
					$gpsbaud = '9600';
1584
					break;
1585
				case '32':
1586
					$gpsbaud = '19200';
1587
					break;
1588
				case '48':
1589
					$gpsbaud = '38400';
1590
					break;
1591
				case '64':
1592
					$gpsbaud = '57600';
1593
					break;
1594
				case '80':
1595
					$gpsbaud = '115200';
1596
					break;
1597
			}
1598
		}
1599 ec7bc948 Ermal
		@file_put_contents("/etc/remote", "gps0:dv={$serialport}:br#{$gpsbaud}:pa=none:", FILE_APPEND);
1600
	}
1601 5c8843d5 jim-p
1602
	conf_mount_ro();
1603
1604
	return true;
1605
}
1606
1607 142f7393 nagyrobi
function system_ntp_setup_pps($serialport) {
1608
	global $config, $g;
1609 ec7bc948 Ermal
1610 142f7393 nagyrobi
	$pps_device = '/dev/pps0';
1611
	$serialport = '/dev/'.$serialport;
1612
1613 61e047a5 Phil Davis
	if (!file_exists($serialport)) {
1614 142f7393 nagyrobi
		return false;
1615 61e047a5 Phil Davis
	}
1616 142f7393 nagyrobi
1617
	conf_mount_rw();
1618
	// Create symlink that ntpd requires
1619
	unlink_if_exists($pps_device);
1620 ec7bc948 Ermal
	@symlink($serialport, $pps_device);
1621 142f7393 nagyrobi
1622
	conf_mount_ro();
1623
1624
	return true;
1625
}
1626
1627
1628 0b8e9d38 jim-p
function system_ntp_configure($start_ntpd=true) {
1629 f19d3b7a Scott Ullrich
	global $config, $g;
1630 ec7bc948 Ermal
1631 42135f07 jim-p
	$driftfile = "/var/db/ntpd.drift";
1632 5c8843d5 jim-p
	$statsdir = "/var/log/ntp";
1633
	$gps_device = '/dev/gps0';
1634 5b237745 Scott Ullrich
1635 61e047a5 Phil Davis
	if ($g['platform'] == 'jail') {
1636 7734aea6 Andrew Thompson
		return;
1637 61e047a5 Phil Davis
	}
1638 7734aea6 Andrew Thompson
1639 5c8843d5 jim-p
	safe_mkdir($statsdir);
1640
1641 61e047a5 Phil Davis
	if (!is_array($config['ntpd'])) {
1642 ec7bc948 Ermal
		$config['ntpd'] = array();
1643 61e047a5 Phil Davis
	}
1644 ec7bc948 Ermal
1645 b2305621 Ermal
	$ntpcfg = "# \n";
1646 42135f07 jim-p
	$ntpcfg .= "# pfSense ntp configuration file \n";
1647 b2305621 Ermal
	$ntpcfg .= "# \n\n";
1648 362c9bb0 jim-p
	$ntpcfg .= "tinker panic 0 \n";
1649 0f282d7a Scott Ullrich
1650 142f7393 nagyrobi
	/* Add Orphan mode */
1651
	$ntpcfg .= "# Orphan mode stratum\n";
1652
	$ntpcfg .= 'tos orphan ';
1653
	if (!empty($config['ntpd']['orphan'])) {
1654
		$ntpcfg .= $config['ntpd']['orphan'];
1655 61e047a5 Phil Davis
	} else {
1656 142f7393 nagyrobi
		$ntpcfg .= '12';
1657
	}
1658
	$ntpcfg .= "\n";
1659
1660
	/* Add PPS configuration */
1661 61e047a5 Phil Davis
	if (is_array($config['ntpd']['pps']) && !empty($config['ntpd']['pps']['port']) &&
1662
	    file_exists('/dev/'.$config['ntpd']['pps']['port']) &&
1663
	    system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
1664 142f7393 nagyrobi
		$ntpcfg .= "\n";
1665
		$ntpcfg .= "# PPS Setup\n";
1666
		$ntpcfg .= 'server 127.127.22.0';
1667
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1668
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
1669 61e047a5 Phil Davis
			$ntpcfg .= ' prefer';
1670 142f7393 nagyrobi
		}
1671
		if (!empty($config['ntpd']['pps']['noselect'])) {
1672
			$ntpcfg .= ' noselect ';
1673
		}
1674
		$ntpcfg .= "\n";
1675
		$ntpcfg .= 'fudge 127.127.22.0';
1676
		if (!empty($config['ntpd']['pps']['fudge1'])) {
1677
			$ntpcfg .= ' time1 ';
1678
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
1679
		}
1680
		if (!empty($config['ntpd']['pps']['flag2'])) {
1681
			$ntpcfg .= ' flag2 1';
1682
		}
1683
		if (!empty($config['ntpd']['pps']['flag3'])) {
1684
			$ntpcfg .= ' flag3 1';
1685 61e047a5 Phil Davis
		} else {
1686 142f7393 nagyrobi
			$ntpcfg .= ' flag3 0';
1687
		}
1688
		if (!empty($config['ntpd']['pps']['flag4'])) {
1689
			$ntpcfg .= ' flag4 1';
1690
		}
1691
		if (!empty($config['ntpd']['pps']['refid'])) {
1692
			$ntpcfg .= ' refid ';
1693
			$ntpcfg .= $config['ntpd']['pps']['refid'];
1694
		}
1695
		$ntpcfg .= "\n";
1696
	}
1697
	/* End PPS configuration */
1698
1699
	/* Add GPS configuration */
1700 61e047a5 Phil Davis
	if (is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['port']) &&
1701
	    file_exists('/dev/'.$config['ntpd']['gps']['port']) &&
1702
	    system_ntp_setup_gps($config['ntpd']['gps']['port'])) {
1703 142f7393 nagyrobi
		$ntpcfg .= "\n";
1704
		$ntpcfg .= "# GPS Setup\n";
1705
		$ntpcfg .= 'server 127.127.20.0 mode ';
1706
		if (!empty($config['ntpd']['gps']['nmea']) || !empty($config['ntpd']['gps']['speed']) || !empty($config['ntpd']['gps']['subsec'])) {
1707
			if (!empty($config['ntpd']['gps']['nmea'])) {
1708
				$ntpmode = (int) $config['ntpd']['gps']['nmea'];
1709
			}
1710
			if (!empty($config['ntpd']['gps']['speed'])) {
1711
				$ntpmode += (int) $config['ntpd']['gps']['speed'];
1712
			}
1713
			if (!empty($config['ntpd']['gps']['subsec'])) {
1714
				$ntpmode += 128;
1715
			}
1716
			$ntpcfg .= (string) $ntpmode;
1717 61e047a5 Phil Davis
		} else {
1718 142f7393 nagyrobi
			$ntpcfg .= '0';
1719
		}
1720
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1721
		if (empty($config['ntpd']['gps']['prefer'])) { /*note: this one works backwards */
1722 61e047a5 Phil Davis
			$ntpcfg .= ' prefer';
1723 142f7393 nagyrobi
		}
1724
		if (!empty($config['ntpd']['gps']['noselect'])) {
1725
			$ntpcfg .= ' noselect ';
1726
		}
1727
		$ntpcfg .= "\n";
1728
		$ntpcfg .= 'fudge 127.127.20.0';
1729
		if (!empty($config['ntpd']['gps']['fudge1'])) {
1730
			$ntpcfg .= ' time1 ';
1731
			$ntpcfg .= $config['ntpd']['gps']['fudge1'];
1732
		}
1733
		if (!empty($config['ntpd']['gps']['fudge2'])) {
1734
			$ntpcfg .= ' time2 ';
1735
			$ntpcfg .= $config['ntpd']['gps']['fudge2'];
1736
		}
1737
		if (!empty($config['ntpd']['gps']['flag1'])) {
1738
			$ntpcfg .= ' flag1 1';
1739 61e047a5 Phil Davis
		} else {
1740 142f7393 nagyrobi
			$ntpcfg .= ' flag1 0';
1741
		}
1742
		if (!empty($config['ntpd']['gps']['flag2'])) {
1743
			$ntpcfg .= ' flag2 1';
1744
		}
1745
		if (!empty($config['ntpd']['gps']['flag3'])) {
1746
			$ntpcfg .= ' flag3 1';
1747 61e047a5 Phil Davis
		} else {
1748 142f7393 nagyrobi
			$ntpcfg .= ' flag3 0';
1749
		}
1750
		if (!empty($config['ntpd']['gps']['flag4'])) {
1751
			$ntpcfg .= ' flag4 1';
1752
		}
1753
		if (!empty($config['ntpd']['gps']['refid'])) {
1754
			$ntpcfg .= ' refid ';
1755
			$ntpcfg .= $config['ntpd']['gps']['refid'];
1756
		}
1757
		$ntpcfg .= "\n";
1758 61e047a5 Phil Davis
	} elseif (is_array($config['ntpd']) && !empty($config['ntpd']['gpsport']) &&
1759
	    file_exists('/dev/'.$config['ntpd']['gpsport']) &&
1760
	    system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1761 142f7393 nagyrobi
		/* This handles a 2.1 and earlier config */
1762 5c8843d5 jim-p
		$ntpcfg .= "# GPS Setup\n";
1763
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1764
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1765
		// Fall back to local clock if GPS is out of sync?
1766
		$ntpcfg .= "server 127.127.1.0\n";
1767
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1768
	}
1769 142f7393 nagyrobi
	/* End GPS configuration */
1770 61e047a5 Phil Davis
1771 5c8843d5 jim-p
	$ntpcfg .= "\n\n# Upstream Servers\n";
1772 142f7393 nagyrobi
	/* foreach through ntp servers and write out to ntpd.conf */
1773
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1774
		$ntpcfg .= "server {$ts} iburst maxpoll 9";
1775 61e047a5 Phil Davis
		if (substr_count($config['ntpd']['prefer'], $ts)) {
1776
			$ntpcfg .= ' prefer';
1777
		}
1778
		if (substr_count($config['ntpd']['noselect'], $ts)) {
1779
			$ntpcfg .= ' noselect';
1780
		}
1781 142f7393 nagyrobi
		$ntpcfg .= "\n";
1782
	}
1783
	unset($ts);
1784
1785
	$ntpcfg .= "\n\n";
1786 e1a456e6 Chris Buechler
	$ntpcfg .= "disable monitor\n"; //prevent NTP reflection attack, see https://forum.pfsense.org/index.php/topic,67189.msg389132.html#msg389132
1787 142f7393 nagyrobi
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
1788
		$ntpcfg .= "enable stats\n";
1789
		$ntpcfg .= 'statistics';
1790
		if (!empty($config['ntpd']['clockstats'])) {
1791
			$ntpcfg .= ' clockstats';
1792
		}
1793
		if (!empty($config['ntpd']['loopstats'])) {
1794
			$ntpcfg .= ' loopstats';
1795
		}
1796
		if (!empty($config['ntpd']['peerstats'])) {
1797
			$ntpcfg .= ' peerstats';
1798
		}
1799
		$ntpcfg .= "\n";
1800
	}
1801 5c8843d5 jim-p
	$ntpcfg .= "statsdir {$statsdir}\n";
1802 142f7393 nagyrobi
	$ntpcfg .= 'logconfig =syncall +clockall';
1803
	if (!empty($config['ntpd']['logpeer'])) {
1804
		$ntpcfg .= ' +peerall';
1805
	}
1806
	if (!empty($config['ntpd']['logsys'])) {
1807
		$ntpcfg .= ' +sysall';
1808
	}
1809
	$ntpcfg .= "\n";
1810 42135f07 jim-p
	$ntpcfg .= "driftfile {$driftfile}\n";
1811 142f7393 nagyrobi
	/* Access restrictions */
1812
	$ntpcfg .= 'restrict default';
1813
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1814 61e047a5 Phil Davis
		$ntpcfg .= ' kod limited';
1815 142f7393 nagyrobi
	}
1816
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1817 61e047a5 Phil Davis
		$ntpcfg .= ' nomodify';
1818 142f7393 nagyrobi
	}
1819
	if (!empty($config['ntpd']['noquery'])) {
1820
		$ntpcfg .= ' noquery';
1821
	}
1822
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1823 61e047a5 Phil Davis
		$ntpcfg .= ' nopeer';
1824 142f7393 nagyrobi
	}
1825
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1826 61e047a5 Phil Davis
		$ntpcfg .= ' notrap';
1827 142f7393 nagyrobi
	}
1828
	if (!empty($config['ntpd']['noserve'])) {
1829
		$ntpcfg .= ' noserve';
1830
	}
1831
	$ntpcfg .= "\nrestrict -6 default";
1832
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1833 61e047a5 Phil Davis
		$ntpcfg .= ' kod limited';
1834 142f7393 nagyrobi
	}
1835
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1836 61e047a5 Phil Davis
		$ntpcfg .= ' nomodify';
1837 142f7393 nagyrobi
	}
1838
	if (!empty($config['ntpd']['noquery'])) {
1839
		$ntpcfg .= ' noquery';
1840
	}
1841
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1842 61e047a5 Phil Davis
		$ntpcfg .= ' nopeer';
1843 142f7393 nagyrobi
	}
1844
	if (!empty($config['ntpd']['noserve'])) {
1845
		$ntpcfg .= ' noserve';
1846
	}
1847
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1848 61e047a5 Phil Davis
		$ntpcfg .= ' notrap';
1849 142f7393 nagyrobi
	}
1850
	$ntpcfg .= "\n";
1851
1852
	/* A leapseconds file is really only useful if this clock is stratum 1 */
1853
	$ntpcfg .= "\n";
1854
	if (!empty($config['ntpd']['leapsec'])) {
1855
		$leapsec .= base64_decode($config['ntpd']['leapsec']);
1856
		file_put_contents('/var/db/leap-seconds', $leapsec);
1857
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
1858
	}
1859 61e047a5 Phil Davis
1860 95594e5a Scott Ullrich
1861 51e76899 Ermal LUÇI
	if (empty($config['ntpd']['interface'])) {
1862 61e047a5 Phil Davis
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface'])) {
1863 cf180ccc jim-p
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1864 61e047a5 Phil Davis
		} else {
1865 cf180ccc jim-p
			$interfaces = array();
1866 61e047a5 Phil Davis
		}
1867
	} else {
1868 cf180ccc jim-p
		$interfaces = explode(",", $config['ntpd']['interface']);
1869 61e047a5 Phil Davis
	}
1870 cf180ccc jim-p
1871
	if (is_array($interfaces) && count($interfaces)) {
1872
		$ntpcfg .= "interface ignore all\n";
1873
		foreach ($interfaces as $interface) {
1874
			if (!is_ipaddr($interface)) {
1875
				$interface = get_real_interface($interface);
1876
			}
1877 61e047a5 Phil Davis
			if (!empty($interface)) {
1878 8b650e57 jim-p
				$ntpcfg .= "interface listen {$interface}\n";
1879 61e047a5 Phil Davis
			}
1880 cf180ccc jim-p
		}
1881
	}
1882
1883 f416763b Phil Davis
	/* open configuration for writing or bail */
1884 b9f29f84 Ermal
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
1885 b2305621 Ermal
		log_error("Could not open {$g['varetc_path']}/ntpd.conf for writing");
1886
		return;
1887
	}
1888 20b90e0a Scott Ullrich
1889 0b8e9d38 jim-p
	/* At bootup we just want to write out the config. */
1890 61e047a5 Phil Davis
	if (!$start_ntpd) {
1891 0b8e9d38 jim-p
		return;
1892 61e047a5 Phil Davis
	}
1893 0b8e9d38 jim-p
1894 42135f07 jim-p
	/* if ntpd is running, kill it */
1895 df40755d Ermal
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1896 b9f29f84 Ermal
		killbypid("{$g['varrun_path']}/ntpd.pid");
1897 5f3e1f12 Scott Ullrich
	}
1898 b9f29f84 Ermal
	@unlink("{$g['varrun_path']}/ntpd.pid");
1899 5f3e1f12 Scott Ullrich
1900
	/* if /var/empty does not exist, create it */
1901 61e047a5 Phil Davis
	if (!is_dir("/var/empty")) {
1902 0fd64e94 nagyrobi
		mkdir("/var/empty", 0775, true);
1903 61e047a5 Phil Davis
	}
1904 5f3e1f12 Scott Ullrich
1905 20b90e0a Scott Ullrich
	/* start opentpd, set time now and use /var/etc/ntpd.conf */
1906 0fd64e94 nagyrobi
	mwexec("/usr/local/sbin/ntpd -g -c {$g['varetc_path']}/ntpd.conf -p {$g['varrun_path']}/ntpd.pid", false, true);
1907 61e047a5 Phil Davis
1908 83eb4567 Scott Ullrich
	// Note that we are starting up
1909 42135f07 jim-p
	log_error("NTPD is starting up.");
1910 0b8e9d38 jim-p
	return;
1911 5b237745 Scott Ullrich
}
1912
1913 652cf082 Seth Mos
function sync_system_time() {
1914
	global $config, $g;
1915
1916 61e047a5 Phil Davis
	if (platform_booting()) {
1917 4a896b86 Carlos Eduardo Ramos
		echo gettext("Syncing system time before startup...");
1918 61e047a5 Phil Davis
	}
1919 652cf082 Seth Mos
1920
	/* foreach through servers and write out to ntpd.conf */
1921 b2305621 Ermal
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1922 fdfa8f43 jim-p
		mwexec("/usr/local/sbin/ntpdate -s $ts");
1923 652cf082 Seth Mos
	}
1924 61e047a5 Phil Davis
1925
	if (platform_booting()) {
1926 4a896b86 Carlos Eduardo Ramos
		echo gettext("done.") . "\n";
1927 61e047a5 Phil Davis
	}
1928
1929 652cf082 Seth Mos
}
1930
1931 405e5de0 Scott Ullrich
function system_halt() {
1932
	global $g;
1933
1934
	system_reboot_cleanup();
1935
1936 523855b0 Scott Ullrich
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1937 405e5de0 Scott Ullrich
}
1938
1939 5b237745 Scott Ullrich
function system_reboot() {
1940
	global $g;
1941 0f282d7a Scott Ullrich
1942 5b237745 Scott Ullrich
	system_reboot_cleanup();
1943 0f282d7a Scott Ullrich
1944 5b237745 Scott Ullrich
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1945
}
1946
1947
function system_reboot_sync() {
1948
	global $g;
1949 0f282d7a Scott Ullrich
1950 5b237745 Scott Ullrich
	system_reboot_cleanup();
1951 0f282d7a Scott Ullrich
1952 5b237745 Scott Ullrich
	mwexec("/etc/rc.reboot > /dev/null 2>&1");
1953
}
1954
1955
function system_reboot_cleanup() {
1956 62f20eab Michael Newton
	global $config, $cpzone;
1957
1958 97d4e30b Seth Mos
	mwexec("/usr/local/bin/beep.sh stop");
1959 04967d99 jim-p
	require_once("captiveportal.inc");
1960 52034432 Renato Botelho
	if (is_array($config['captiveportal'])) {
1961 34cb8645 Jean Cyr
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
1962
			captiveportal_radius_stop_all();
1963
			captiveportal_send_server_accounting(true);
1964
		}
1965 62f20eab Michael Newton
	}
1966 336e3c1c Charlie
	require_once("voucher.inc");
1967
	voucher_save_db_to_config();
1968 60dd7649 jim-p
	require_once("pkg-utils.inc");
1969
	stop_packages();
1970 5b237745 Scott Ullrich
}
1971
1972
function system_do_shell_commands($early = 0) {
1973 f19d3b7a Scott Ullrich
	global $config, $g;
1974 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
1975 58c7450e Scott Ullrich
		$mt = microtime();
1976 dcf0598e Scott Ullrich
		echo "system_do_shell_commands() being called $mt\n";
1977 58c7450e Scott Ullrich
	}
1978 0f282d7a Scott Ullrich
1979 61e047a5 Phil Davis
	if ($early) {
1980 5b237745 Scott Ullrich
		$cmdn = "earlyshellcmd";
1981 61e047a5 Phil Davis
	} else {
1982 5b237745 Scott Ullrich
		$cmdn = "shellcmd";
1983 61e047a5 Phil Davis
	}
1984 0f282d7a Scott Ullrich
1985 5b237745 Scott Ullrich
	if (is_array($config['system'][$cmdn])) {
1986 333f8ef0 Scott Ullrich
1987 245388b4 Scott Ullrich
		/* *cmd is an array, loop through */
1988 5b237745 Scott Ullrich
		foreach ($config['system'][$cmdn] as $cmd) {
1989
			exec($cmd);
1990
		}
1991 245388b4 Scott Ullrich
1992 61e047a5 Phil Davis
	} elseif ($config['system'][$cmdn] <> "") {
1993 333f8ef0 Scott Ullrich
1994 245388b4 Scott Ullrich
		/* execute single item */
1995
		exec($config['system'][$cmdn]);
1996
1997 5b237745 Scott Ullrich
	}
1998
}
1999
2000
function system_console_configure() {
2001 f19d3b7a Scott Ullrich
	global $config, $g;
2002 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
2003 58c7450e Scott Ullrich
		$mt = microtime();
2004 dcf0598e Scott Ullrich
		echo "system_console_configure() being called $mt\n";
2005 333f8ef0 Scott Ullrich
	}
2006 0f282d7a Scott Ullrich
2007 5b237745 Scott Ullrich
	if (isset($config['system']['disableconsolemenu'])) {
2008
		touch("{$g['varetc_path']}/disableconsole");
2009
	} else {
2010
		unlink_if_exists("{$g['varetc_path']}/disableconsole");
2011
	}
2012
}
2013
2014
function system_dmesg_save() {
2015 f19d3b7a Scott Ullrich
	global $g;
2016 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
2017 58c7450e Scott Ullrich
		$mt = microtime();
2018 dcf0598e Scott Ullrich
		echo "system_dmesg_save() being called $mt\n";
2019 f19d3b7a Scott Ullrich
	}
2020 0f282d7a Scott Ullrich
2021 767a716e Scott Ullrich
	$dmesg = "";
2022 703b1ce1 Ermal
	$_gb = exec("/sbin/dmesg", $dmesg);
2023 0f282d7a Scott Ullrich
2024 5b237745 Scott Ullrich
	/* find last copyright line (output from previous boots may be present) */
2025
	$lastcpline = 0;
2026 0f282d7a Scott Ullrich
2027 5b237745 Scott Ullrich
	for ($i = 0; $i < count($dmesg); $i++) {
2028 61e047a5 Phil Davis
		if (strstr($dmesg[$i], "Copyright (c) 1992-")) {
2029 5b237745 Scott Ullrich
			$lastcpline = $i;
2030 61e047a5 Phil Davis
		}
2031 5b237745 Scott Ullrich
	}
2032 0f282d7a Scott Ullrich
2033 5b237745 Scott Ullrich
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
2034
	if (!$fd) {
2035 4a896b86 Carlos Eduardo Ramos
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
2036 5b237745 Scott Ullrich
		return 1;
2037
	}
2038 0f282d7a Scott Ullrich
2039 61e047a5 Phil Davis
	for ($i = $lastcpline; $i < count($dmesg); $i++) {
2040 5b237745 Scott Ullrich
		fwrite($fd, $dmesg[$i] . "\n");
2041 61e047a5 Phil Davis
	}
2042 0f282d7a Scott Ullrich
2043 5b237745 Scott Ullrich
	fclose($fd);
2044 703b1ce1 Ermal
	unset($dmesg);
2045 0f282d7a Scott Ullrich
2046 5b237745 Scott Ullrich
	return 0;
2047
}
2048
2049
function system_set_harddisk_standby() {
2050 f19d3b7a Scott Ullrich
	global $g, $config;
2051 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
2052 58c7450e Scott Ullrich
		$mt = microtime();
2053 dcf0598e Scott Ullrich
		echo "system_set_harddisk_standby() being called $mt\n";
2054 58c7450e Scott Ullrich
	}
2055 5b237745 Scott Ullrich
2056
	if (isset($config['system']['harddiskstandby'])) {
2057 285ef132 Ermal LUÇI
		if (platform_booting()) {
2058 4a896b86 Carlos Eduardo Ramos
			echo gettext('Setting hard disk standby... ');
2059 5b237745 Scott Ullrich
		}
2060
2061
		$standby = $config['system']['harddiskstandby'];
2062
		// Check for a numeric value
2063
		if (is_numeric($standby)) {
2064
			// Sync the disk(s)
2065 5ba5a8de Scott Ullrich
			pfSense_sync();
2066 971de1f9 Renato Botelho
			if (set_single_sysctl('hw.ata.standby', (int)$standby)) {
2067 5b237745 Scott Ullrich
				// Reinitialize ATA-drives
2068
				mwexec('/usr/local/sbin/atareinit');
2069 285ef132 Ermal LUÇI
				if (platform_booting()) {
2070 4a896b86 Carlos Eduardo Ramos
					echo gettext("done.") . "\n";
2071 5b237745 Scott Ullrich
				}
2072 285ef132 Ermal LUÇI
			} else if (platform_booting()) {
2073 4a896b86 Carlos Eduardo Ramos
				echo gettext("failed!") . "\n";
2074 5b237745 Scott Ullrich
			}
2075 285ef132 Ermal LUÇI
		} else if (platform_booting()) {
2076 4a896b86 Carlos Eduardo Ramos
			echo gettext("failed!") . "\n";
2077 5b237745 Scott Ullrich
		}
2078
	}
2079
}
2080
2081 3ff9d424 Scott Ullrich
function system_setup_sysctl() {
2082 f19d3b7a Scott Ullrich
	global $config;
2083 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
2084 58c7450e Scott Ullrich
		$mt = microtime();
2085 dcf0598e Scott Ullrich
		echo "system_setup_sysctl() being called $mt\n";
2086 58c7450e Scott Ullrich
	}
2087 243aa7b9 Scott Ullrich
2088 61e047a5 Phil Davis
	activate_sysctls();
2089 6df9d7e3 Scott Ullrich
2090 243aa7b9 Scott Ullrich
	if (isset($config['system']['sharednet'])) {
2091
		system_disable_arp_wrong_if();
2092
	}
2093
}
2094
2095
function system_disable_arp_wrong_if() {
2096 f19d3b7a Scott Ullrich
	global $config;
2097 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
2098 58c7450e Scott Ullrich
		$mt = microtime();
2099 dcf0598e Scott Ullrich
		echo "system_disable_arp_wrong_if() being called $mt\n";
2100 333f8ef0 Scott Ullrich
	}
2101 971de1f9 Renato Botelho
	set_sysctl(array(
2102
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
2103
		"net.link.ether.inet.log_arp_movements" => "0"
2104
	));
2105 3ff9d424 Scott Ullrich
}
2106
2107 243aa7b9 Scott Ullrich
function system_enable_arp_wrong_if() {
2108 f19d3b7a Scott Ullrich
	global $config;
2109 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
2110 58c7450e Scott Ullrich
		$mt = microtime();
2111 dcf0598e Scott Ullrich
		echo "system_enable_arp_wrong_if() being called $mt\n";
2112 58c7450e Scott Ullrich
	}
2113 971de1f9 Renato Botelho
	set_sysctl(array(
2114
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
2115
		"net.link.ether.inet.log_arp_movements" => "1"
2116
	));
2117 243aa7b9 Scott Ullrich
}
2118
2119 a199b93e Scott Ullrich
function enable_watchdog() {
2120
	global $config;
2121 1a479479 Scott Ullrich
	return;
2122 a199b93e Scott Ullrich
	$install_watchdog = false;
2123
	$supported_watchdogs = array("Geode");
2124
	$file = file_get_contents("/var/log/dmesg.boot");
2125 61e047a5 Phil Davis
	foreach ($supported_watchdogs as $sd) {
2126
		if (stristr($file, "Geode")) {
2127 a199b93e Scott Ullrich
			$install_watchdog = true;
2128
		}
2129
	}
2130 61e047a5 Phil Davis
	if ($install_watchdog == true) {
2131
		if (is_process_running("watchdogd")) {
2132 e0b4e47f Seth Mos
			mwexec("/usr/bin/killall watchdogd", true);
2133 61e047a5 Phil Davis
		}
2134 333f8ef0 Scott Ullrich
		exec("/usr/sbin/watchdogd");
2135 a199b93e Scott Ullrich
	}
2136
}
2137 15f14889 Scott Ullrich
2138
function system_check_reset_button() {
2139 fa83737d Scott Ullrich
	global $g;
2140 15f14889 Scott Ullrich
2141 31c9379c Scott Ullrich
	$specplatform = system_identify_specific_platform();
2142
2143 365fc95d Renato Botelho
	switch ($specplatform['name']) {
2144 61e047a5 Phil Davis
		case 'alix':
2145
		case 'wrap':
2146
		case 'FW7541':
2147
		case 'APU':
2148 80e47bb0 Chris Buechler
		case 'RCC-VE':
2149 61e047a5 Phil Davis
			break;
2150
		default:
2151
			return 0;
2152 365fc95d Renato Botelho
	}
2153 15f14889 Scott Ullrich
2154
	$retval = mwexec("/usr/local/sbin/" . $specplatform['name'] . "resetbtn");
2155
2156
	if ($retval == 99) {
2157 61e047a5 Phil Davis
		/* user has pressed reset button for 2 seconds -
2158 15f14889 Scott Ullrich
		   reset to factory defaults */
2159
		echo <<<EOD
2160
2161
***********************************************************************
2162
* Reset button pressed - resetting configuration to factory defaults. *
2163
* The system will reboot after this completes.                        *
2164
***********************************************************************
2165
2166
2167
EOD;
2168 61e047a5 Phil Davis
2169 15f14889 Scott Ullrich
		reset_factory_defaults();
2170
		system_reboot_sync();
2171
		exit(0);
2172
	}
2173
2174
	return 0;
2175
}
2176
2177 31c9379c Scott Ullrich
/* attempt to identify the specific platform (for embedded systems)
2178
   Returns an array with two elements:
2179
	name => platform string (e.g. 'wrap', 'alix' etc.)
2180
	descr => human-readable description (e.g. "PC Engines WRAP")
2181
*/
2182
function system_identify_specific_platform() {
2183
	global $g;
2184 61e047a5 Phil Davis
2185
	if ($g['platform'] == 'generic-pc') {
2186 4a896b86 Carlos Eduardo Ramos
		return array('name' => 'generic-pc', 'descr' => gettext("Generic PC"));
2187 61e047a5 Phil Davis
	}
2188
2189
	if ($g['platform'] == 'generic-pc-cdrom') {
2190 4a896b86 Carlos Eduardo Ramos
		return array('name' => 'generic-pc-cdrom', 'descr' => gettext("Generic PC (CD-ROM)"));
2191 61e047a5 Phil Davis
	}
2192
2193 5a8519bb Chris Buechler
	/* Try to guess from smbios strings */
2194
	unset($output);
2195 7e36f71c Renato Botelho
	$_gb = exec('/bin/kenv smbios.system.product 2>/dev/null', $output);
2196 5a8519bb Chris Buechler
	switch ($output[0]) {
2197 61e047a5 Phil Davis
		case 'FW7541':
2198
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2199
			break;
2200
		case 'APU':
2201
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2202
			break;
2203
		case 'RCC-VE':
2204 80e47bb0 Chris Buechler
			return (array('name' => 'RCC-VE', 'descr' => 'Netgate RCC-VE'));
2205 61e047a5 Phil Davis
			break;
2206 5a8519bb Chris Buechler
	}
2207
2208 31c9379c Scott Ullrich
	/* the rest of the code only deals with 'embedded' platforms */
2209 61e047a5 Phil Davis
	if ($g['platform'] != 'nanobsd') {
2210 31c9379c Scott Ullrich
		return array('name' => $g['platform'], 'descr' => $g['platform']);
2211 61e047a5 Phil Davis
	}
2212 f0014c64 Ermal
2213 971de1f9 Renato Botelho
	$dmesg = get_single_sysctl('hw.model');
2214 f0014c64 Ermal
2215 61e047a5 Phil Davis
	if (strpos($dmesg, "PC Engines WRAP") !== false) {
2216 4a896b86 Carlos Eduardo Ramos
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
2217 61e047a5 Phil Davis
	}
2218
2219
	if (strpos($dmesg, "PC Engines ALIX") !== false) {
2220 4a896b86 Carlos Eduardo Ramos
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2221 61e047a5 Phil Davis
	}
2222 31c9379c Scott Ullrich
2223 61e047a5 Phil Davis
	if (preg_match("/Soekris net45../", $dmesg, $matches)) {
2224 31c9379c Scott Ullrich
		return array('name' => 'net45xx', 'descr' => $matches[0]);
2225 61e047a5 Phil Davis
	}
2226
2227
	if (preg_match("/Soekris net48../", $dmesg, $matches)) {
2228 31c9379c Scott Ullrich
		return array('name' => 'net48xx', 'descr' => $matches[0]);
2229 61e047a5 Phil Davis
	}
2230
2231
	if (preg_match("/Soekris net55../", $dmesg, $matches)) {
2232 31c9379c Scott Ullrich
		return array('name' => 'net55xx', 'descr' => $matches[0]);
2233 61e047a5 Phil Davis
	}
2234 1f97f379 Renato Botelho
2235
	unset($dmesg);
2236
2237
	$dmesg_boot = system_get_dmesg_boot();
2238 61e047a5 Phil Davis
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
2239 1f97f379 Renato Botelho
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2240 61e047a5 Phil Davis
	}
2241 1f97f379 Renato Botelho
	unset($dmesg_boot);
2242
2243 31c9379c Scott Ullrich
	/* unknown embedded platform */
2244 4a896b86 Carlos Eduardo Ramos
	return array('name' => 'embedded', 'descr' => gettext('embedded (unknown)'));
2245 31c9379c Scott Ullrich
}
2246
2247
function system_get_dmesg_boot() {
2248
	global $g;
2249 61e047a5 Phil Davis
2250 31c9379c Scott Ullrich
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2251
}
2252
2253 6d457361 Chris Buechler
?>