Project

General

Profile

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