Project

General

Profile

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