Project

General

Profile

Download (72.4 KB) Statistics
| Branch: | Tag: | Revision:
1 5b237745 Scott Ullrich
<?php
2
/*
3 ac24dc24 Renato Botelho
 * system.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6 38809d47 Renato Botelho do Couto
 * Copyright (c) 2004-2013 BSD Perimeter
7
 * Copyright (c) 2013-2016 Electric Sheep Fencing
8 8f585441 Luiz Souza
 * Copyright (c) 2014-2021 Rubicon Communications, LLC (Netgate)
9 ac24dc24 Renato Botelho
 * All rights reserved.
10
 *
11
 * originally part of m0n0wall (http://m0n0.ch/wall)
12 c5d81585 Renato Botelho
 * Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>.
13 ac24dc24 Renato Botelho
 * All rights reserved.
14
 *
15 b12ea3fb Renato Botelho
 * Licensed under the Apache License, Version 2.0 (the "License");
16
 * you may not use this file except in compliance with the License.
17
 * You may obtain a copy of the License at
18 ac24dc24 Renato Botelho
 *
19 b12ea3fb Renato Botelho
 * http://www.apache.org/licenses/LICENSE-2.0
20 ac24dc24 Renato Botelho
 *
21 b12ea3fb Renato Botelho
 * Unless required by applicable law or agreed to in writing, software
22
 * distributed under the License is distributed on an "AS IS" BASIS,
23
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24
 * See the License for the specific language governing permissions and
25
 * limitations under the License.
26 ac24dc24 Renato Botelho
 */
27 5b237745 Scott Ullrich
28 3a26e715 jim-p
require_once('syslog.inc');
29
30 8e9fa41d Scott Ullrich
function activate_powerd() {
31
	global $config, $g;
32 6fa9f38c Renato Botelho
33 61e047a5 Phil Davis
	if (is_process_running("powerd")) {
34 53c210dd Cristian Feldman
		exec("/usr/bin/killall powerd");
35 61e047a5 Phil Davis
	}
36
	if (isset($config['system']['powerd_enable'])) {
37 a358eec2 N0YB
		$ac_mode = "hadp";
38 61e047a5 Phil Davis
		if (!empty($config['system']['powerd_ac_mode'])) {
39 a358eec2 N0YB
			$ac_mode = $config['system']['powerd_ac_mode'];
40 61e047a5 Phil Davis
		}
41 a358eec2 N0YB
42
		$battery_mode = "hadp";
43 61e047a5 Phil Davis
		if (!empty($config['system']['powerd_battery_mode'])) {
44 a358eec2 N0YB
			$battery_mode = $config['system']['powerd_battery_mode'];
45 61e047a5 Phil Davis
		}
46 a358eec2 N0YB
47 3d77cc35 Steven Selph
		$normal_mode = "hadp";
48 61e047a5 Phil Davis
		if (!empty($config['system']['powerd_normal_mode'])) {
49 3d77cc35 Steven Selph
			$normal_mode = $config['system']['powerd_normal_mode'];
50 61e047a5 Phil Davis
		}
51 3d77cc35 Steven Selph
52 3be69929 jim-p
		mwexec("/usr/sbin/powerd" .
53
			" -b " . escapeshellarg($battery_mode) .
54
			" -a " . escapeshellarg($ac_mode) .
55
			" -n " . escapeshellarg($normal_mode));
56 8e9fa41d Scott Ullrich
	}
57
}
58
59 3a35f55f Scott Ullrich
function get_default_sysctl_value($id) {
60
	global $sysctls;
61 f3c91cb5 Erik Fonnesbeck
62 61e047a5 Phil Davis
	if (isset($sysctls[$id])) {
63 f3c91cb5 Erik Fonnesbeck
		return $sysctls[$id];
64 61e047a5 Phil Davis
	}
65 3a35f55f Scott Ullrich
}
66
67 d87fcac9 Ermal
function get_sysctl_descr($sysctl) {
68
	unset($output);
69 3c44c845 Luiz Souza
	$_gb = exec("/sbin/sysctl -qnd {$sysctl}", $output);
70 d87fcac9 Ermal
71
	return $output[0];
72
}
73
74
function system_get_sysctls() {
75
	global $config, $sysctls;
76
77
	$disp_sysctl = array();
78
	$disp_cache = array();
79
	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
80 61e047a5 Phil Davis
		foreach ($config['sysctl']['item'] as $id => $tunable) {
81
			if ($tunable['value'] == "default") {
82 d87fcac9 Ermal
				$value = get_default_sysctl_value($tunable['tunable']);
83 61e047a5 Phil Davis
			} else {
84 d87fcac9 Ermal
				$value = $tunable['value'];
85 61e047a5 Phil Davis
			}
86 d87fcac9 Ermal
87
			$disp_sysctl[$id] = $tunable;
88
			$disp_sysctl[$id]['modified'] = true;
89
			$disp_cache[$tunable['tunable']] = 'set';
90
		}
91
	}
92
93
	foreach ($sysctls as $sysctl => $value) {
94 61e047a5 Phil Davis
		if (isset($disp_cache[$sysctl])) {
95 d87fcac9 Ermal
			continue;
96 61e047a5 Phil Davis
		}
97 d87fcac9 Ermal
98
		$disp_sysctl[$sysctl] = array('tunable' => $sysctl, 'value' => $value, 'descr' => get_sysctl_descr($sysctl));
99
	}
100
	unset($disp_cache);
101
	return $disp_sysctl;
102
}
103
104 6df9d7e3 Scott Ullrich
function activate_sysctls() {
105 cb0a23f2 jim-p
	global $config, $g, $sysctls, $ipsec_filter_sysctl;
106
107
	if (!is_array($sysctls)) {
108
		$sysctls = array();
109
	}
110
111
	$ipsec_filtermode = empty($config['ipsec']['filtermode']) ? 'enc' : $config['ipsec']['filtermode'];
112
	$sysctls = array_merge($sysctls, $ipsec_filter_sysctl[$ipsec_filtermode]);
113 971de1f9 Renato Botelho
114 d87fcac9 Ermal
	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
115 61e047a5 Phil Davis
		foreach ($config['sysctl']['item'] as $tunable) {
116
			if ($tunable['value'] == "default") {
117 b2d0140c Scott Ullrich
				$value = get_default_sysctl_value($tunable['tunable']);
118 61e047a5 Phil Davis
			} else {
119 971de1f9 Renato Botelho
				$value = $tunable['value'];
120 61e047a5 Phil Davis
			}
121 971de1f9 Renato Botelho
122
			$sysctls[$tunable['tunable']] = $value;
123 d0b461f5 sullrich
		}
124
	}
125 971de1f9 Renato Botelho
126 8f4b8ff2 jim-p
	/* Set net.pf.request_maxcount via sysctl since it is no longer a loader
127
	 *   tunable. See https://redmine.pfsense.org/issues/10861
128
	 *   Set the value dynamically since its default is not static, yet this
129
	 *   still could be overridden by a user tunable. */
130
	if (isset($config['system']['maximumtableentries'])) {
131
		$maximumtableentries = $config['system']['maximumtableentries'];
132
	} else {
133
		$maximumtableentries = pfsense_default_table_entries_size();
134
	}
135
	/* Set the default when there is no tunable or when the tunable is set
136
	 * too low. */
137
	if (empty($sysctls['net.pf.request_maxcount']) ||
138
	    ($sysctls['net.pf.request_maxcount'] < $maximumtableentries)) {
139
		$sysctls['net.pf.request_maxcount'] = $maximumtableentries;
140
	}
141
142 971de1f9 Renato Botelho
	set_sysctl($sysctls);
143 6df9d7e3 Scott Ullrich
}
144
145 5b237745 Scott Ullrich
function system_resolvconf_generate($dynupdate = false) {
146 c3f535c0 Seth Mos
	global $config, $g;
147
148 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
149 c3f535c0 Seth Mos
		$mt = microtime();
150
		echo "system_resolvconf_generate() being called $mt\n";
151
	}
152 ef217c69 Scott Ullrich
153 30cee7b2 Scott Ullrich
	$syscfg = $config['system'];
154 ef217c69 Scott Ullrich
155 f0c51530 jim-p
	foreach(get_dns_nameservers(false, false) as $dns_ns) {
156 b7a4321c Peter Berbec
		$resolvconf .= "nameserver $dns_ns\n";
157 61e047a5 Phil Davis
	}
158 8ac329da Ermal
159 74a8a219 jim-p
	$ns = array();
160 30cee7b2 Scott Ullrich
	if (isset($syscfg['dnsallowoverride'])) {
161 c3f535c0 Seth Mos
		/* get dynamically assigned DNS servers (if any) */
162 86dcdfc9 Ermal
		$ns = array_unique(get_searchdomains());
163 61e047a5 Phil Davis
		foreach ($ns as $searchserver) {
164
			if ($searchserver) {
165 86dcdfc9 Ermal
				$resolvconf .= "search {$searchserver}\n";
166 61e047a5 Phil Davis
			}
167 86dcdfc9 Ermal
		}
168 74a8a219 jim-p
	}
169
	if (empty($ns)) {
170 e8b5f724 Chris Buechler
		// Do not create blank search/domain lines, it can break tools like dig.
171 61e047a5 Phil Davis
		if ($syscfg['domain']) {
172 97383d2b Chris Buechler
			$resolvconf .= "search {$syscfg['domain']}\n";
173 61e047a5 Phil Davis
		}
174 30cee7b2 Scott Ullrich
	}
175 0f282d7a Scott Ullrich
176 3b95d9ec Warren Baker
	// Add EDNS support
177 61e047a5 Phil Davis
	if (isset($config['unbound']['enable']) && isset($config['unbound']['edns'])) {
178 3b95d9ec Warren Baker
		$resolvconf .= "options edns0\n";
179 61e047a5 Phil Davis
	}
180 3b95d9ec Warren Baker
181 d97ff036 Ermal
	$dnslock = lock('resolvconf', LOCK_EX);
182
183 fc84b222 Renato Botelho
	$fd = fopen("{$g['etc_path']}/resolv.conf", "w");
184 e1daff07 Ermal
	if (!$fd) {
185
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
186 d97ff036 Ermal
		unlock($dnslock);
187 e1daff07 Ermal
		return 1;
188
	}
189
190 30cee7b2 Scott Ullrich
	fwrite($fd, $resolvconf);
191
	fclose($fd);
192 0f282d7a Scott Ullrich
193 30501526 Warren Baker
	// Prevent resolvconf(8) from rewriting our resolv.conf
194 fc84b222 Renato Botelho
	$fd = fopen("{$g['etc_path']}/resolvconf.conf", "w");
195 30501526 Warren Baker
	if (!$fd) {
196
		printf("Error: cannot open resolvconf.conf in system_resolvconf_generate().\n");
197
		return 1;
198
	}
199
	fwrite($fd, "resolv_conf=\"/dev/null\"\n");
200
	fclose($fd);
201
202 285ef132 Ermal LUÇI
	if (!platform_booting()) {
203 c3f535c0 Seth Mos
		/* restart dhcpd (nameservers may have changed) */
204 61e047a5 Phil Davis
		if (!$dynupdate) {
205 c3f535c0 Seth Mos
			services_dhcpd_configure();
206 61e047a5 Phil Davis
		}
207 30cee7b2 Scott Ullrich
	}
208 ef217c69 Scott Ullrich
209 f211d7c0 luckman212
	// set up or tear down static routes for DNS servers
210 a2d23e88 Phil Davis
	$dnscounter = 1;
211
	$dnsgw = "dns{$dnscounter}gw";
212
	while (isset($config['system'][$dnsgw])) {
213 c3f535c0 Seth Mos
		/* setup static routes for dns servers */
214 f211d7c0 luckman212
		$gwname = $config['system'][$dnsgw];
215
		unset($gatewayip);
216
		unset($inet6);
217
		if ((!empty($gwname)) && ($gwname != "none")) {
218 c6079517 Renato Botelho
			$gatewayip = lookup_gateway_ip_by_name($gwname);
219 138e4140 Renato Botelho
			$inet6 = is_ipaddrv6($gatewayip) ? '-inet6 ' : '';
220 f211d7c0 luckman212
		}
221
		/* dns server array starts at 0 */
222
		$dnsserver = $syscfg['dnsserver'][$dnscounter - 1];
223
		if (!empty($dnsserver)) {
224 c6079517 Renato Botelho
			if (is_ipaddr($gatewayip)) {
225 c428cdf4 Renato Botelho do Couto
				route_add_or_change($dnsserver, $gatewayip);
226 138e4140 Renato Botelho
			} else {
227
				/* Remove old route when disable gw */
228 c428cdf4 Renato Botelho do Couto
				route_del($dnsserver);
229 b875f306 Scott Ullrich
			}
230 e180a6e3 Scott Ullrich
		}
231 a2d23e88 Phil Davis
		$dnscounter++;
232
		$dnsgw = "dns{$dnscounter}gw";
233 c3f535c0 Seth Mos
	}
234 d97ff036 Ermal
235
	unlock($dnslock);
236
237 c3f535c0 Seth Mos
	return 0;
238 5b237745 Scott Ullrich
}
239
240 86dcdfc9 Ermal
function get_searchdomains() {
241
	global $config, $g;
242
243
	$master_list = array();
244 61e047a5 Phil Davis
245 86dcdfc9 Ermal
	// Read in dhclient nameservers
246 e1daff07 Ermal
	$search_list = glob("/var/etc/searchdomain_*");
247 f4a4bcbc Renato Botelho
	if (is_array($search_list)) {
248 61e047a5 Phil Davis
		foreach ($search_list as $fdns) {
249 807fd6cd Ermal
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
250 61e047a5 Phil Davis
			if (!is_array($contents)) {
251 807fd6cd Ermal
				continue;
252 61e047a5 Phil Davis
			}
253 807fd6cd Ermal
			foreach ($contents as $dns) {
254 61e047a5 Phil Davis
				if (is_hostname($dns)) {
255 807fd6cd Ermal
					$master_list[] = $dns;
256 61e047a5 Phil Davis
				}
257 807fd6cd Ermal
			}
258 86dcdfc9 Ermal
		}
259
	}
260
261
	return $master_list;
262
}
263
264 f0c51530 jim-p
/* Stub for deprecated function name
265
 * See https://redmine.pfsense.org/issues/10931 */
266 3d00ccaa Scott Ullrich
function get_nameservers() {
267 f0c51530 jim-p
	return get_dynamic_nameservers();
268
}
269
270
/****f* system.inc/get_dynamic_nameservers
271
 * NAME
272
 *   get_dynamic_nameservers - Get DNS servers from dynamic sources (DHCP, PPP, etc)
273
 * INPUTS
274
 *   $iface: Interface name used to filter results.
275
 * RESULT
276
 *   $master_list - Array containing DNS servers
277
 ******/
278
function get_dynamic_nameservers($iface = '') {
279 3d00ccaa Scott Ullrich
	global $config, $g;
280
	$master_list = array();
281 61e047a5 Phil Davis
282 f0c51530 jim-p
	if (!empty($iface)) {
283 cd60d729 Viktor G
		$realif = get_real_interface($iface);
284 f0c51530 jim-p
	}
285
286
	// Read in dynamic nameservers
287 cd60d729 Viktor G
	$dns_lists = array_merge(glob("/var/etc/nameserver_{$realif}*"), glob("/var/etc/nameserver_v6{$iface}*"));
288 1033de74 Ermal
	if (is_array($dns_lists)) {
289 61e047a5 Phil Davis
		foreach ($dns_lists as $fdns) {
290 807fd6cd Ermal
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
291 61e047a5 Phil Davis
			if (!is_array($contents)) {
292 807fd6cd Ermal
				continue;
293 61e047a5 Phil Davis
			}
294 807fd6cd Ermal
			foreach ($contents as $dns) {
295 61e047a5 Phil Davis
				if (is_ipaddr($dns)) {
296 807fd6cd Ermal
					$master_list[] = $dns;
297 61e047a5 Phil Davis
				}
298 807fd6cd Ermal
			}
299 60951398 Scott Ullrich
		}
300 3d00ccaa Scott Ullrich
	}
301 2a1226ad Scott Ullrich
302 3d00ccaa Scott Ullrich
	return $master_list;
303
}
304
305 2da0fc77 Renato Botelho
/* Create localhost + local interfaces entries for /etc/hosts */
306
function system_hosts_local_entries() {
307
	global $config;
308
309
	$syscfg = $config['system'];
310
311
	$hosts = array();
312
	$hosts[] = array(
313
	    'ipaddr' => '127.0.0.1',
314 4541f84d jim-p
	    'fqdn' => 'localhost.' . $syscfg['domain'],
315
	    'name' => 'localhost',
316
	    'domain' => $syscfg['domain']
317 2da0fc77 Renato Botelho
	);
318
	$hosts[] = array(
319
	    'ipaddr' => '::1',
320 4541f84d jim-p
	    'fqdn' => 'localhost.' . $syscfg['domain'],
321
	    'name' => 'localhost',
322
	    'domain' => $syscfg['domain']
323 2da0fc77 Renato Botelho
	);
324
325
	if ($config['interfaces']['lan']) {
326
		$sysiflist = array('lan' => "lan");
327
	} else {
328
		$sysiflist = get_configured_interface_list();
329
	}
330
331
	$hosts_if_found = false;
332
	$local_fqdn = "{$syscfg['hostname']}.{$syscfg['domain']}";
333
	foreach ($sysiflist as $sysif) {
334
		if ($sysif != 'lan' && interface_has_gateway($sysif)) {
335
			continue;
336
		}
337
		$cfgip = get_interface_ip($sysif);
338
		if (is_ipaddrv4($cfgip)) {
339
			$hosts[] = array(
340
			    'ipaddr' => $cfgip,
341 4541f84d jim-p
			    'fqdn' => $local_fqdn,
342
			    'name' => $syscfg['hostname'],
343
			    'domain' => $syscfg['domain']
344 2da0fc77 Renato Botelho
			);
345
			$hosts_if_found = true;
346
		}
347 cd1ae328 lukehamburg
		if (!isset($syscfg['ipv6dontcreatelocaldns'])) {
348
			$cfgipv6 = get_interface_ipv6($sysif);
349
			if (is_ipaddrv6($cfgipv6)) {
350
				$hosts[] = array(
351
					'ipaddr' => $cfgipv6,
352 4541f84d jim-p
					'fqdn' => $local_fqdn,
353
					'name' => $syscfg['hostname'],
354
					'domain' => $syscfg['domain']
355 cd1ae328 lukehamburg
				);
356
				$hosts_if_found = true;
357
			}
358 2da0fc77 Renato Botelho
		}
359
		if ($hosts_if_found == true) {
360
			break;
361
		}
362
	}
363
364
	return $hosts;
365
}
366
367 46ff0dee Renato Botelho
/* Read host override entries from dnsmasq or unbound */
368
function system_hosts_override_entries($dnscfg) {
369
	$hosts = array();
370
371 71e53a40 Renato Botelho
	if (!is_array($dnscfg) ||
372
	    !is_array($dnscfg['hosts']) ||
373
	    !isset($dnscfg['enable'])) {
374 46ff0dee Renato Botelho
		return $hosts;
375
	}
376
377
	foreach ($dnscfg['hosts'] as $host) {
378
		$fqdn = '';
379
		if ($host['host'] || $host['host'] == "0") {
380
			$fqdn .= "{$host['host']}.";
381
		}
382
		$fqdn .= $host['domain'];
383
384 dfd5754a Viktor G
		foreach (explode(',', $host['ip']) as $ip) {
385
			$hosts[] = array(
386
			    'ipaddr' => $ip,
387
			    'fqdn' => $fqdn,
388
			    'name' => $host['host'],
389
			    'domain' => $host['domain']
390
			);
391
		}
392 46ff0dee Renato Botelho
393
		if (!is_array($host['aliases']) ||
394
		    !is_array($host['aliases']['item'])) {
395
			continue;
396
		}
397
398
		foreach ($host['aliases']['item'] as $alias) {
399
			$fqdn = '';
400
			if ($alias['host'] || $alias['host'] == "0") {
401
				$fqdn .= "{$alias['host']}.";
402
			}
403
			$fqdn .= $alias['domain'];
404
405 dfd5754a Viktor G
			foreach (explode(',', $host['ip']) as $ip) {
406
				$hosts[] = array(
407
				    'ipaddr' => $ip,
408
				    'fqdn' => $fqdn,
409
				    'name' => $alias['host'],
410
				    'domain' => $alias['domain']
411
				);
412
			}
413 46ff0dee Renato Botelho
		}
414
	}
415
416
	return $hosts;
417
}
418
419 236d5816 Renato Botelho
/* Read all dhcpd/dhcpdv6 staticmap entries */
420
function system_hosts_dhcpd_entries() {
421
	global $config;
422
423
	$hosts = array();
424
	$syscfg = $config['system'];
425
426
	if (is_array($config['dhcpd'])) {
427
		$conf_dhcpd = $config['dhcpd'];
428
	} else {
429
		$conf_dhcpd = array();
430
	}
431
432
	foreach ($conf_dhcpd as $dhcpif => $dhcpifconf) {
433
		if (!is_array($dhcpifconf['staticmap']) ||
434
		    !isset($dhcpifconf['enable'])) {
435
			continue;
436
		}
437
		foreach ($dhcpifconf['staticmap'] as $host) {
438
			if (!$host['ipaddr'] ||
439
			    !$host['hostname']) {
440
				continue;
441
			}
442
443
			$fqdn = $host['hostname'] . ".";
444 4541f84d jim-p
			$domain = "";
445 236d5816 Renato Botelho
			if ($host['domain']) {
446 4541f84d jim-p
				$domain = $host['domain'];
447 236d5816 Renato Botelho
			} elseif ($dhcpifconf['domain']) {
448 4541f84d jim-p
				$domain = $dhcpifconf['domain'];
449 236d5816 Renato Botelho
			} else {
450 4541f84d jim-p
				$domain = $syscfg['domain'];
451 236d5816 Renato Botelho
			}
452
453
			$hosts[] = array(
454
			    'ipaddr' => $host['ipaddr'],
455 4541f84d jim-p
			    'fqdn' => $fqdn . $domain,
456
			    'name' => $host['hostname'],
457
			    'domain' => $domain
458 236d5816 Renato Botelho
			);
459
		}
460
	}
461
	unset($conf_dhcpd);
462
463
	if (is_array($config['dhcpdv6'])) {
464
		$conf_dhcpdv6 = $config['dhcpdv6'];
465
	} else {
466
		$conf_dhcpdv6 = array();
467
	}
468
469
	foreach ($conf_dhcpdv6 as $dhcpif => $dhcpifconf) {
470
		if (!is_array($dhcpifconf['staticmap']) ||
471
		    !isset($dhcpifconf['enable'])) {
472
			continue;
473
		}
474
475
		if (isset($config['interfaces'][$dhcpif]['ipaddrv6']) &&
476
		    $config['interfaces'][$dhcpif]['ipaddrv6'] ==
477
		    'track6') {
478
			$isdelegated = true;
479
		} else {
480
			$isdelegated = false;
481
		}
482
483
		foreach ($dhcpifconf['staticmap'] as $host) {
484
			$ipaddrv6 = $host['ipaddrv6'];
485
486
			if (!$ipaddrv6 || !$host['hostname']) {
487
				continue;
488
			}
489
490
			if ($isdelegated) {
491
				/*
492
				 * We are always in an "end-user" subnet
493
				 * here, which all are /64 for IPv6.
494
				 */
495 47f05aa1 Viktor G
				$prefix6 = 64;
496
			} else {
497
				$prefix6 = get_interface_subnetv6($dhcpif);
498 236d5816 Renato Botelho
			}
499 47f05aa1 Viktor G
			$ipaddrv6 = merge_ipv6_delegated_prefix(get_interface_ipv6($dhcpif), $ipaddrv6, $prefix6);
500 236d5816 Renato Botelho
501
			$fqdn = $host['hostname'] . ".";
502 4541f84d jim-p
			$domain = "";
503 236d5816 Renato Botelho
			if ($host['domain']) {
504 4541f84d jim-p
				$domain = $host['domain'];
505
			} elseif ($dhcpifconf['domain']) {
506
				$domain = $dhcpifconf['domain'];
507 236d5816 Renato Botelho
			} else {
508 4541f84d jim-p
				$domain = $syscfg['domain'];
509 236d5816 Renato Botelho
			}
510
511
			$hosts[] = array(
512
			    'ipaddr' => $ipaddrv6,
513 4541f84d jim-p
			    'fqdn' => $fqdn . $domain,
514
			    'name' => $host['hostname'],
515
			    'domain' => $domain
516 236d5816 Renato Botelho
			);
517
		}
518
	}
519
	unset($conf_dhcpdv6);
520
521
	return $hosts;
522
}
523
524 878b7736 Renato Botelho
/* Concatenate local, dnsmasq/unbound and dhcpd/dhcpdv6 hosts entries */
525
function system_hosts_entries($dnscfg) {
526 49d9b45f Robbert Rijkse
	$local = array();
527
	if (!isset($dnscfg['disable_auto_added_host_entries'])) {
528
		$local = system_hosts_local_entries();
529
	}
530 878b7736 Renato Botelho
531
	$dns = array();
532
	$dhcpd = array();
533
	if (isset($dnscfg['enable'])) {
534
		$dns = system_hosts_override_entries($dnscfg);
535
		if (isset($dnscfg['regdhcpstatic'])) {
536
			$dhcpd = system_hosts_dhcpd_entries();
537
		}
538
	}
539
540
	if (isset($dnscfg['dhcpfirst'])) {
541
		return array_merge($local, $dns, $dhcpd);
542
	} else {
543
		return array_merge($local, $dhcpd, $dns);
544
	}
545
}
546
547 5b237745 Scott Ullrich
function system_hosts_generate() {
548 f19d3b7a Scott Ullrich
	global $config, $g;
549 f6248774 Warren Baker
	if (isset($config['system']['developerspew'])) {
550 58c7450e Scott Ullrich
		$mt = microtime();
551 dcf0598e Scott Ullrich
		echo "system_hosts_generate() being called $mt\n";
552 f19d3b7a Scott Ullrich
	}
553 0f282d7a Scott Ullrich
554 d6fa0b47 Chris Buechler
	// prefer dnsmasq for hosts generation where it's enabled. It relies
555
	// on hosts for name resolution of its overrides, unbound does not.
556
	if (isset($config['dnsmasq']) && isset($config['dnsmasq']['enable'])) {
557 21713b25 Renato Botelho
		$dnsmasqcfg = $config['dnsmasq'];
558 d6fa0b47 Chris Buechler
	} else {
559
		$dnsmasqcfg = $config['unbound'];
560 61e047a5 Phil Davis
	}
561 5b237745 Scott Ullrich
562 2da0fc77 Renato Botelho
	$syscfg = $config['system'];
563
	$hosts = "";
564 aa994814 Andrew Thompson
	$lhosts = "";
565
	$dhosts = "";
566 a55e9c70 Ermal Lu?i
567 878b7736 Renato Botelho
	$hosts_array = system_hosts_entries($dnsmasqcfg);
568 2da0fc77 Renato Botelho
	foreach ($hosts_array as $host) {
569 4541f84d jim-p
		$hosts .= "{$host['ipaddr']}\t";
570 0e78c2f5 jim-p
		if ($host['name'] == "localhost") {
571
			$hosts .= "{$host['name']} {$host['fqdn']}";
572
		} else {
573
			$hosts .= "{$host['fqdn']} {$host['name']}";
574 e5995f9d Ermal
		}
575 2da0fc77 Renato Botelho
		$hosts .= "\n";
576 f38f8062 Ermal
	}
577 46ff0dee Renato Botelho
	unset($hosts_array);
578 0f282d7a Scott Ullrich
579 58db1fc4 Ermal
	/*
580 d015d543 Renato Botelho
	 * Do not remove this because dhcpleases monitors with kqueue it needs
581
	 * to be killed before writing to hosts files.
582 58db1fc4 Ermal
	 */
583
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
584
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
585 ea1aca13 Renato Botelho
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
586 58db1fc4 Ermal
	}
587 509e9357 NewEraCracker
588 c968ef7e Luiz Souza
	$fd = fopen("{$g['etc_path']}/hosts", "w");
589
	if (!$fd) {
590
		log_error(gettext(
591
		    "Error: cannot open hosts file in system_hosts_generate()."
592
		    ));
593
		return 1;
594
	}
595
596 5b237745 Scott Ullrich
	fwrite($fd, $hosts);
597
	fclose($fd);
598 0f282d7a Scott Ullrich
599 3f06e538 Warren Baker
	if (isset($config['unbound']['enable'])) {
600
		require_once("unbound.inc");
601 f6248774 Warren Baker
		unbound_hosts_generate();
602 3f06e538 Warren Baker
	}
603 f6248774 Warren Baker
604 509e9357 NewEraCracker
	/* restart dhcpleases */
605
	if (!platform_booting()) {
606
		system_dhcpleases_configure();
607
	}
608
609 24d619f5 Ermal
	return 0;
610
}
611
612
function system_dhcpleases_configure() {
613 15d456b9 gnhb
	global $config, $g;
614 3d8b01e8 doktornotor
	if (!function_exists('is_dhcp_server_enabled')) {
615
		require_once('pfsense-utils.inc');
616
	}
617 4509abc3 NewEraCracker
	$pidfile = "{$g['varrun_path']}/dhcpleases.pid";
618
619 956950de Ermal
	/* Start the monitoring process for dynamic dhcpclients. */
620 3d8b01e8 doktornotor
	if (((isset($config['dnsmasq']['enable']) && isset($config['dnsmasq']['regdhcp'])) ||
621
	    (isset($config['unbound']['enable']) && isset($config['unbound']['regdhcp']))) &&
622
	    (is_dhcp_server_enabled())) {
623 956950de Ermal
		/* Make sure we do not error out */
624 abdd01f5 Ermal
		mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db");
625 61e047a5 Phil Davis
		if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
626 abdd01f5 Ermal
			@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
627 61e047a5 Phil Davis
		}
628 4dbcf2fb Renato Botelho
629 21713b25 Renato Botelho
		if (isset($config['unbound']['enable'])) {
630 4dbcf2fb Renato Botelho
			$dns_pid = "unbound.pid";
631 21713b25 Renato Botelho
			$unbound_conf = "-u {$g['unbound_chroot_path']}/dhcpleases_entries.conf";
632
		} else {
633 4dbcf2fb Renato Botelho
			$dns_pid = "dnsmasq.pid";
634 21713b25 Renato Botelho
			$unbound_conf = "";
635
		}
636 4dbcf2fb Renato Botelho
637
		if (isvalidpid($pidfile)) {
638
			/* Make sure dhcpleases is using correct unbound or dnsmasq */
639
			$_gb = exec("/bin/pgrep -F {$pidfile} -f {$dns_pid}", $output, $retval);
640
			if (intval($retval) == 0) {
641
				sigkillbypid($pidfile, "HUP");
642
				return;
643 61e047a5 Phil Davis
			} else {
644 4dbcf2fb Renato Botelho
				sigkillbypid($pidfile, "TERM");
645 61e047a5 Phil Davis
			}
646 69e593c1 jim-p
		}
647 4dbcf2fb Renato Botelho
648
		/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
649 61e047a5 Phil Davis
		if (is_process_running("dhcpleases")) {
650 21713b25 Renato Botelho
			sigkillbyname('dhcpleases', "TERM");
651 61e047a5 Phil Davis
		}
652 21713b25 Renato Botelho
		@unlink($pidfile);
653 fc84b222 Renato Botelho
		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['etc_path']}/hosts");
654 7e79c173 Viktor Gurov
	} else {
655
		if (isvalidpid($pidfile)) {
656
			sigkillbypid($pidfile, "TERM");
657
			@unlink($pidfile);
658
		}
659
		if (file_exists("{$g['unbound_chroot_path']}/dhcpleases_entries.conf")) {
660
			$dhcpleases = fopen("{$g['unbound_chroot_path']}/dhcpleases_entries.conf", "w");
661
			ftruncate($dhcpleases, 0);
662
			fclose($dhcpleases);
663
		}
664 15d456b9 gnhb
	}
665 5b237745 Scott Ullrich
}
666
667 88326a6b Renato Botelho
function system_get_dhcpleases() {
668
	global $config, $g;
669
670
	$leases = array();
671
	$leases['lease'] = array();
672
	$leases['failover'] = array();
673
674
	$leases_file = "{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases";
675
676
	if (!file_exists($leases_file)) {
677
		return $leases;
678
	}
679
680
	$leases_content = file($leases_file, FILE_IGNORE_NEW_LINES |
681
	    FILE_IGNORE_NEW_LINES);
682
683
	if ($leases_content === FALSE) {
684
		return $leases;
685
	}
686
687
	$arp_table = system_get_arp_table();
688
689
	$arpdata_ip = array();
690
	$arpdata_mac = array();
691
	foreach ($arp_table as $arp_entry) {
692
		if (isset($arpentry['incomplete'])) {
693
			continue;
694
		}
695
		$arpdata_ip[] = $arp_entry['ip-address'];
696
		$arpdata_mac[] = $arp_entry['mac-address'];
697
	}
698
	unset($arp_table);
699
700
	/*
701
	 * Translate these once so we don't do it over and over in the loops
702
	 * below.
703
	 */
704
	$online_string = gettext("online");
705
	$offline_string = gettext("offline");
706
	$active_string = gettext("active");
707
	$expired_string = gettext("expired");
708
	$reserved_string = gettext("reserved");
709
	$dynamic_string = gettext("dynamic");
710
	$static_string = gettext("static");
711
712
	$lease_regex = '/^lease\s+([^\s]+)\s+{$/';
713
	$starts_regex = '/^\s*(starts|ends)\s+\d+\s+([\d\/]+|never)\s*(|[\d:]*);$/';
714
	$binding_regex = '/^\s*binding\s+state\s+(.+);$/';
715
	$mac_regex = '/^\s*hardware\s+ethernet\s+(.+);$/';
716
	$hostname_regex = '/^\s*client-hostname\s+"(.+)";$/';
717
718
	$failover_regex = '/^failover\s+peer\s+"(.+)"\s+state\s+{$/';
719
	$state_regex = '/\s*(my|partner)\s+state\s+(.+)\s+at\s+\d+\s+([\d\/]+)\s+([\d:]+);$/';
720
721
	$lease = false;
722
	$failover = false;
723
	$dedup_lease = false;
724
	$dedup_failover = false;
725
	foreach ($leases_content as $line) {
726
		/* Skip comments */
727
		if (preg_match('/^\s*(|#.*)$/', $line)) {
728
			continue;
729
		}
730
731
		if (preg_match('/}$/', $line)) {
732
			if ($lease) {
733
				if (empty($item['hostname'])) {
734
					$hostname = gethostbyaddr($item['ip']);
735
					if (!empty($hostname)) {
736
						$item['hostname'] = $hostname;
737
					}
738
				}
739
				$leases['lease'][] = $item;
740
				$lease = false;
741
				$dedup_lease = true;
742
			} else if ($failover) {
743
				$leases['failover'][] = $item;
744
				$failover = false;
745
				$dedup_failover = true;
746
			}
747
			continue;
748
		}
749
750
		if (preg_match($lease_regex, $line, $m)) {
751
			$lease = true;
752
			$item = array();
753
			$item['ip'] = $m[1];
754
			$item['type'] = $dynamic_string;
755
			continue;
756
		}
757
758
		if ($lease) {
759
			if (preg_match($starts_regex, $line, $m)) {
760
				/*
761
				 * Quote from dhcpd.leases(5) man page:
762
				 * If a lease will never expire, date is never
763
				 * instead of an actual date
764
				 */
765
				if ($m[2] == "never") {
766
					$item[$m[1]] = gettext("Never");
767
				} else {
768
					$item[$m[1]] = dhcpd_date_adjust_gmt(
769
					    $m[2] . ' ' . $m[3]);
770
				}
771
				continue;
772
			}
773
774
			if (preg_match($binding_regex, $line, $m)) {
775
				switch ($m[1]) {
776
					case "active":
777
						$item['act'] = $active_string;
778
						break;
779
					case "free":
780
						$item['act'] = $expired_string;
781
						$item['online'] =
782
						    $offline_string;
783
						break;
784
					case "backup":
785
						$item['act'] = $reserved_string;
786
						$item['online'] =
787
						    $offline_string;
788
						break;
789
				}
790
				continue;
791
			}
792
793
			if (preg_match($mac_regex, $line, $m) &&
794
			    is_macaddr($m[1])) {
795
				$item['mac'] = $m[1];
796
797
				if (in_array($item['ip'], $arpdata_ip)) {
798
					$item['online'] = $online_string;
799
				} else {
800
					$item['online'] = $offline_string;
801
				}
802
				continue;
803
			}
804
805
			if (preg_match($hostname_regex, $line, $m)) {
806
				$item['hostname'] = $m[1];
807
			}
808
		}
809
810
		if (preg_match($failover_regex, $line, $m)) {
811
			$failover = true;
812
			$item = array();
813
			$item['name'] = $m[1] . ' (' .
814
			    convert_friendly_interface_to_friendly_descr(
815
			    substr($m[1],5)) . ')';
816
			continue;
817
		}
818
819
		if ($failover && preg_match($state_regex, $line, $m)) {
820
			$item[$m[1] . 'state'] = $m[2];
821
			$item[$m[1] . 'date'] = dhcpd_date_adjust_gmt($m[3] .
822
			    ' ' . $m[4]);
823
			continue;
824
		}
825
	}
826
827
	foreach ($config['interfaces'] as $ifname => $ifarr) {
828
		if (!is_array($config['dhcpd'][$ifname]) ||
829
		    !is_array($config['dhcpd'][$ifname]['staticmap'])) {
830
			continue;
831
		}
832
833
		foreach ($config['dhcpd'][$ifname]['staticmap'] as $idx =>
834
		    $static) {
835
			if (empty($static['mac']) && empty($static['cid'])) {
836
				continue;
837
			}
838
839
			$slease = array();
840
			$slease['ip'] = $static['ipaddr'];
841
			$slease['type'] = $static_string;
842
			if (!empty($static['cid'])) {
843
				$slease['cid'] = $static['cid'];
844
			}
845
			$slease['mac'] = $static['mac'];
846
			$slease['if'] = $ifname;
847
			$slease['starts'] = "";
848
			$slease['ends'] = "";
849
			$slease['hostname'] = $static['hostname'];
850
			$slease['descr'] = $static['descr'];
851
			$slease['act'] = $static_string;
852
			$slease['online'] = in_array(strtolower($slease['mac']),
853
			    $arpdata_mac) ? $online_string : $offline_string;
854
			$slease['staticmap_array_index'] = $idx;
855
			$leases['lease'][] = $slease;
856
			$dedup_lease = true;
857
		}
858
	}
859
860
	if ($dedup_lease) {
861
		$leases['lease'] = array_remove_duplicate($leases['lease'],
862
		    'ip');
863
	}
864
	if ($dedup_failover) {
865
		$leases['failover'] = array_remove_duplicate(
866
		    $leases['failover'], 'name');
867
		asort($leases['failover']);
868
	}
869
870
	return $leases;
871
}
872
873 5b237745 Scott Ullrich
function system_hostname_configure() {
874 f19d3b7a Scott Ullrich
	global $config, $g;
875 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
876 58c7450e Scott Ullrich
		$mt = microtime();
877 dcf0598e Scott Ullrich
		echo "system_hostname_configure() being called $mt\n";
878 333f8ef0 Scott Ullrich
	}
879 0f282d7a Scott Ullrich
880 5b237745 Scott Ullrich
	$syscfg = $config['system'];
881 0f282d7a Scott Ullrich
882 5b237745 Scott Ullrich
	/* set hostname */
883 6bfccde7 Scott Ullrich
	$status = mwexec("/bin/hostname " .
884 5b237745 Scott Ullrich
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
885 6bfccde7 Scott Ullrich
886 61e047a5 Phil Davis
	/* Setup host GUID ID.  This is used by ZFS. */
887 6bfccde7 Scott Ullrich
	mwexec("/etc/rc.d/hostid start");
888
889
	return $status;
890 5b237745 Scott Ullrich
}
891
892 1ea67f2e Ermal
function system_routing_configure($interface = "") {
893 962625aa Ermal
	global $config, $g;
894 6fa9f38c Renato Botelho
895 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
896 58c7450e Scott Ullrich
		$mt = microtime();
897 dcf0598e Scott Ullrich
		echo "system_routing_configure() being called $mt\n";
898 58c7450e Scott Ullrich
	}
899 333f8ef0 Scott Ullrich
900 de34f1fc PiBa-NL
	$gateways_arr = return_gateways_array(false, true);
901 4e322e2c Phil Davis
	foreach ($gateways_arr as $gateway) {
902 de34f1fc PiBa-NL
		// setup static interface routes for nonlocal gateways
903
		if (isset($gateway["nonlocalgateway"])) {
904
			$srgatewayip = $gateway['gateway'];
905
			$srinterfacegw = $gateway['interface'];
906
			if (is_ipaddr($srgatewayip) && !empty($srinterfacegw)) {
907 c428cdf4 Renato Botelho do Couto
				route_add_or_change($srgatewayip, '',
908
				    $srinterfacegw);
909 de34f1fc PiBa-NL
			}
910
		}
911
	}
912
913 592bec81 jim-p
	$gateways_status = return_gateways_status(true);
914
	fixup_default_gateway("inet", $gateways_status, $gateways_arr);
915
	fixup_default_gateway("inet6", $gateways_status, $gateways_arr);
916 5a5413bb Seth Mos
917 2a2b9eea Renato Botelho
	system_staticroutes_configure($interface, false);
918
919
	return 0;
920
}
921
922
function system_staticroutes_configure($interface = "", $update_dns = false) {
923
	global $config, $g, $aliastable;
924
925 356e86d4 Renato Botelho
	$filterdns_list = array();
926
927 e47d24e4 Renato Botelho
	$static_routes = get_staticroutes(false, true);
928 f898c1a9 jim-p
	if (count($static_routes)) {
929 6fdea6a2 smos
		$gateways_arr = return_gateways_array(false, true);
930 0f282d7a Scott Ullrich
931 f898c1a9 jim-p
		foreach ($static_routes as $rtent) {
932 a02708b1 Ermal
			if (empty($gateways_arr[$rtent['gateway']])) {
933 4a896b86 Carlos Eduardo Ramos
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
934 a529aced Ermal
				continue;
935
			}
936 a02708b1 Ermal
			$gateway = $gateways_arr[$rtent['gateway']];
937 61e047a5 Phil Davis
			if (!empty($interface) && $interface != $gateway['friendlyiface']) {
938 a02708b1 Ermal
				continue;
939 61e047a5 Phil Davis
			}
940 9740fad8 Seth Mos
941 a02708b1 Ermal
			$gatewayip = $gateway['gateway'];
942
			$interfacegw = $gateway['interface'];
943 a529aced Ermal
944 1e5f47bb smos
			$blackhole = "";
945 580bef1e phroggie
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 4))) {
946 1e5f47bb smos
				$blackhole = "-blackhole";
947 61e047a5 Phil Davis
			}
948 1e5f47bb smos
949 61e047a5 Phil Davis
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network'])) {
950 2a2b9eea Renato Botelho
				continue;
951 61e047a5 Phil Davis
			}
952 046583c3 Renato Botelho
953 e47d24e4 Renato Botelho
			$dnscache = array();
954
			if ($update_dns === true) {
955 61e047a5 Phil Davis
				if (is_subnet($rtent['network'])) {
956 2a2b9eea Renato Botelho
					continue;
957 61e047a5 Phil Davis
				}
958 e47d24e4 Renato Botelho
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
959 61e047a5 Phil Davis
				if (empty($dnscache)) {
960 e47d24e4 Renato Botelho
					continue;
961 61e047a5 Phil Davis
				}
962 e47d24e4 Renato Botelho
			}
963 046583c3 Renato Botelho
964 61e047a5 Phil Davis
			if (is_subnet($rtent['network'])) {
965 e47d24e4 Renato Botelho
				$ips = array($rtent['network']);
966 61e047a5 Phil Davis
			} else {
967
				if (!isset($rtent['disabled'])) {
968 e47d24e4 Renato Botelho
					$filterdns_list[] = $rtent['network'];
969 61e047a5 Phil Davis
				}
970 e47d24e4 Renato Botelho
				$ips = add_hostname_to_watch($rtent['network']);
971
			}
972 2a2b9eea Renato Botelho
973 e47d24e4 Renato Botelho
			foreach ($dnscache as $ip) {
974 61e047a5 Phil Davis
				if (in_array($ip, $ips)) {
975 e47d24e4 Renato Botelho
					continue;
976 61e047a5 Phil Davis
				}
977 c428cdf4 Renato Botelho do Couto
				route_del($ip);
978 e47d24e4 Renato Botelho
			}
979 2a2b9eea Renato Botelho
980 e47d24e4 Renato Botelho
			if (isset($rtent['disabled'])) {
981 c428cdf4 Renato Botelho do Couto
				/*
982
				 * XXX: This can break things by deleting
983
				 * routes that shouldn't be deleted - OpenVPN,
984
				 * dynamic routing scenarios, etc.
985
				 * redmine #3709
986
				 */
987 7bd413eb Chris Buechler
				foreach ($ips as $ip) {
988 c428cdf4 Renato Botelho do Couto
					route_del($ip);
989 7bd413eb Chris Buechler
				}
990 e47d24e4 Renato Botelho
				continue;
991
			}
992 2a2b9eea Renato Botelho
993 e47d24e4 Renato Botelho
			foreach ($ips as $ip) {
994 61e047a5 Phil Davis
				if (is_ipaddrv4($ip)) {
995 e47d24e4 Renato Botelho
					$ip .= "/32";
996 61e047a5 Phil Davis
				}
997 c428cdf4 Renato Botelho do Couto
				/*
998
				 * do NOT do the same check here on v6,
999
				 * is_ipaddrv6 returns true when including
1000
				 * the CIDR mask. doing so breaks v6 routes
1001
				 */
1002 61e047a5 Phil Davis
				if (is_subnet($ip)) {
1003 7bd413eb Chris Buechler
					if (is_ipaddr($gatewayip)) {
1004 c428cdf4 Renato Botelho do Couto
						if (is_linklocal($gatewayip) == "6" &&
1005
						    !strpos($gatewayip, '%')) {
1006
							/*
1007
							 * add interface scope
1008
							 * for link local v6
1009
							 * routes
1010
							 */
1011 eea84f0a Chris Buechler
							$gatewayip .= "%$interfacegw";
1012
						}
1013 c428cdf4 Renato Botelho do Couto
						route_add_or_change($ip,
1014
						    $gatewayip, '', $blackhole);
1015 7bd413eb Chris Buechler
					} else if (!empty($interfacegw)) {
1016 c428cdf4 Renato Botelho do Couto
						route_add_or_change($ip,
1017
						    '', $interfacegw, $blackhole);
1018 7bd413eb Chris Buechler
					}
1019 61e047a5 Phil Davis
				}
1020 2a2b9eea Renato Botelho
			}
1021 5b237745 Scott Ullrich
		}
1022 6a205b6a Ermal
		unset($gateways_arr);
1023 5b237745 Scott Ullrich
	}
1024 6a205b6a Ermal
	unset($static_routes);
1025 67ee1ec5 Ermal Luçi
1026 e47d24e4 Renato Botelho
	if ($update_dns === false) {
1027
		if (count($filterdns_list)) {
1028
			$interval = 60;
1029
			$hostnames = "";
1030
			array_unique($filterdns_list);
1031 61e047a5 Phil Davis
			foreach ($filterdns_list as $hostname) {
1032 e47d24e4 Renato Botelho
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
1033 61e047a5 Phil Davis
			}
1034 e47d24e4 Renato Botelho
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
1035
			unset($hostnames);
1036
1037 61e047a5 Phil Davis
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid")) {
1038 e47d24e4 Renato Botelho
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
1039 61e047a5 Phil Davis
			} else {
1040 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");
1041 61e047a5 Phil Davis
			}
1042 e47d24e4 Renato Botelho
		} else {
1043
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
1044
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
1045
		}
1046 356e86d4 Renato Botelho
	}
1047 e47d24e4 Renato Botelho
	unset($filterdns_list);
1048 356e86d4 Renato Botelho
1049 b9c501ea Seth Mos
	return 0;
1050 5b237745 Scott Ullrich
}
1051
1052
function system_routing_enable() {
1053 f19d3b7a Scott Ullrich
	global $config, $g;
1054 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
1055 58c7450e Scott Ullrich
		$mt = microtime();
1056 dcf0598e Scott Ullrich
		echo "system_routing_enable() being called $mt\n";
1057 58c7450e Scott Ullrich
	}
1058 0f282d7a Scott Ullrich
1059 971de1f9 Renato Botelho
	set_sysctl(array(
1060
		"net.inet.ip.forwarding" => "1",
1061
		"net.inet6.ip6.forwarding" => "1"
1062
	));
1063
1064 6da3df4e Seth Mos
	return;
1065 5b237745 Scott Ullrich
}
1066
1067 7c4c77ee jim-p
function system_webgui_create_certificate() {
1068 f944f4a7 jim-p
	global $config, $g, $cert_strict_values;
1069 7c4c77ee jim-p
1070 c6c398c6 jim-p
	init_config_arr(array('ca'));
1071
	$a_ca = &$config['ca'];
1072
	init_config_arr(array('cert'));
1073
	$a_cert = &$config['cert'];
1074 f764f63a jim-p
	log_error(gettext("Creating SSL/TLS Certificate for this host"));
1075 7c4c77ee jim-p
1076
	$cert = array();
1077
	$cert['refid'] = uniqid();
1078 e8c516a0 Phil Davis
	$cert['descr'] = sprintf(gettext("webConfigurator default (%s)"), $cert['refid']);
1079 a636256c jim-p
	$cert_hostname = "{$config['system']['hostname']}-{$cert['refid']}";
1080 7c4c77ee jim-p
1081
	$dn = array(
1082 573ec19d Renato Botelho do Couto
		'organizationName' => "{$g['product_label']} webConfigurator Self-Signed Certificate",
1083 a636256c jim-p
		'commonName' => $cert_hostname,
1084
		'subjectAltName' => "DNS:{$cert_hostname}");
1085 f416763b Phil Davis
	$old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warnings directly to a page screwing menu tab */
1086 f944f4a7 jim-p
	if (!cert_create($cert, null, 2048, $cert_strict_values['max_server_cert_lifetime'], $dn, "self-signed", "sha256")) {
1087 61e047a5 Phil Davis
		while ($ssl_err = openssl_error_string()) {
1088 e8c516a0 Phil Davis
			log_error(sprintf(gettext("Error creating WebGUI Certificate: openssl library returns: %s"), $ssl_err));
1089 7c4c77ee jim-p
		}
1090
		error_reporting($old_err_level);
1091
		return null;
1092
	}
1093
	error_reporting($old_err_level);
1094
1095
	$a_cert[] = $cert;
1096
	$config['system']['webgui']['ssl-certref'] = $cert['refid'];
1097 f764f63a jim-p
	write_config(sprintf(gettext("Generated new self-signed SSL/TLS certificate for HTTPS (%s)"), $cert['refid']));
1098 7c4c77ee jim-p
	return $cert;
1099
}
1100
1101 5b237745 Scott Ullrich
function system_webgui_start() {
1102 f19d3b7a Scott Ullrich
	global $config, $g;
1103 877ac35d Scott Ullrich
1104 61e047a5 Phil Davis
	if (platform_booting()) {
1105 4a896b86 Carlos Eduardo Ramos
		echo gettext("Starting webConfigurator...");
1106 61e047a5 Phil Davis
	}
1107 877ac35d Scott Ullrich
1108
	chdir($g['www_path']);
1109
1110 fb1266d3 Matthew Grooms
	/* defaults */
1111
	$portarg = "80";
1112
	$crt = "";
1113
	$key = "";
1114 2cf6ddcb Nigel Graham
	$ca = "";
1115 fb1266d3 Matthew Grooms
1116 877ac35d Scott Ullrich
	/* non-standard port? */
1117 61e047a5 Phil Davis
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "") {
1118 528df9a7 Scott Ullrich
		$portarg = "{$config['system']['webgui']['port']}";
1119 61e047a5 Phil Davis
	}
1120 877ac35d Scott Ullrich
1121
	if ($config['system']['webgui']['protocol'] == "https") {
1122 02b383fe sullrich
		// Ensure that we have a webConfigurator CERT
1123 fb1266d3 Matthew Grooms
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
1124 61e047a5 Phil Davis
		if (!is_array($cert) || !$cert['crt'] || !$cert['prv']) {
1125 7c4c77ee jim-p
			$cert = system_webgui_create_certificate();
1126 61e047a5 Phil Davis
		}
1127 0a8dd27b Renato Botelho
		$crt = base64_decode($cert['crt']);
1128
		$key = base64_decode($cert['prv']);
1129 7c4c77ee jim-p
1130 61e047a5 Phil Davis
		if (!$config['system']['webgui']['port']) {
1131 7c4c77ee jim-p
			$portarg = "443";
1132 61e047a5 Phil Davis
		}
1133 6c07db48 Phil Davis
		$ca = ca_chain($cert);
1134 a257c4c9 doktornotor
		$hsts = isset($config['system']['webgui']['disablehsts']) ? false : true;
1135 877ac35d Scott Ullrich
	}
1136
1137 1e8599e5 Chris Buechler
	/* generate nginx configuration */
1138
	system_generate_nginx_config("{$g['varetc_path']}/nginx-webConfigurator.conf",
1139 257fdefe Chris Buechler
		$crt, $key, $ca, "nginx-webConfigurator.pid", $portarg, "/usr/local/www/",
1140 a257c4c9 doktornotor
		"cert.crt", "cert.key", false, $hsts);
1141 877ac35d Scott Ullrich
1142 1e8599e5 Chris Buechler
	/* kill any running nginx */
1143
	killbypid("{$g['varrun_path']}/nginx-webConfigurator.pid");
1144 a11bc497 Ermal
1145
	sleep(1);
1146
1147 1e8599e5 Chris Buechler
	@unlink("{$g['varrun_path']}/nginx-webConfigurator.pid");
1148 a11bc497 Ermal
1149 1e8599e5 Chris Buechler
	/* start nginx */
1150
	$res = mwexec("/usr/local/sbin/nginx -c {$g['varetc_path']}/nginx-webConfigurator.conf");
1151 877ac35d Scott Ullrich
1152 285ef132 Ermal LUÇI
	if (platform_booting()) {
1153 61e047a5 Phil Davis
		if ($res == 0) {
1154 4a896b86 Carlos Eduardo Ramos
			echo gettext("done.") . "\n";
1155 61e047a5 Phil Davis
		} else {
1156 4a896b86 Carlos Eduardo Ramos
			echo gettext("failed!") . "\n";
1157 61e047a5 Phil Davis
		}
1158 877ac35d Scott Ullrich
	}
1159
1160
	return $res;
1161
}
1162
1163 f0c51530 jim-p
/****f* system.inc/get_dns_nameservers
1164
 * NAME
1165
 *   get_dns_nameservers - Get system DNS servers
1166
 * INPUTS
1167
 *   $add_v6_brackets: (boolean, false)
1168
 *                     Add brackets around IPv6 DNS servers, as expected by some
1169
 *                     daemons such as nginx.
1170
 *   $hostns         : (boolean, true)
1171
 *                     true : Return only DNS servers used by the firewall
1172
 *                            itself as upstream forwarding servers
1173
 *                     false: Return all DNS servers from the configuration and
1174
 *                            overrides (if allowed).
1175
 * RESULT
1176
 *   $dns_nameservers - An array of the requested DNS servers
1177
 ******/
1178
function get_dns_nameservers($add_v6_brackets = false, $hostns=true) {
1179 b7a4321c Peter Berbec
	global $config;
1180 3aebb242 Laurent Quillerou
1181 b7a4321c Peter Berbec
	$dns_nameservers = array();
1182 3aebb242 Laurent Quillerou
1183 b7a4321c Peter Berbec
	if (isset($config['system']['developerspew'])) {
1184
		$mt = microtime();
1185
		echo "get_dns_nameservers() being called $mt\n";
1186
	}
1187 3aebb242 Laurent Quillerou
1188 b7a4321c Peter Berbec
	$syscfg = $config['system'];
1189
	if ((((isset($config['dnsmasq']['enable'])) &&
1190 f0c51530 jim-p
	    (empty($config['dnsmasq']['port']) || $config['dnsmasq']['port'] == "53") &&
1191
	    (empty($config['dnsmasq']['interface']) ||
1192
	    in_array("lo0", explode(",", $config['dnsmasq']['interface'])))) ||
1193
	    ((isset($config['unbound']['enable'])) &&
1194
	    (empty($config['unbound']['port']) || $config['unbound']['port'] == "53") &&
1195
	    (empty($config['unbound']['active_interface']) ||
1196
	    in_array("lo0", explode(",", $config['unbound']['active_interface'])) ||
1197
	    in_array("all", explode(",", $config['unbound']['active_interface']), true)))) &&
1198
	    ($config['system']['dnslocalhost'] != 'remote')) {
1199
		$dns_nameservers[] = "127.0.0.1";
1200 b7a4321c Peter Berbec
	}
1201 f0c51530 jim-p
1202
	if ($hostns || ($config['system']['dnslocalhost'] != 'local')) {
1203
		if (isset($syscfg['dnsallowoverride'])) {
1204
			/* get dynamically assigned DNS servers (if any) */
1205
			foreach (array_unique(get_dynamic_nameservers()) as $nameserver) {
1206
				if ($nameserver) {
1207
					if ($add_v6_brackets && is_ipaddrv6($nameserver)) {
1208
						$nameserver = "[{$nameserver}]";
1209
					}
1210
					$dns_nameservers[] = $nameserver;
1211 4c6e3de4 jim-p
				}
1212 b7a4321c Peter Berbec
			}
1213
		}
1214 f0c51530 jim-p
		if (is_array($syscfg['dnsserver'])) {
1215
			foreach ($syscfg['dnsserver'] as $sys_dnsserver) {
1216
				if ($sys_dnsserver && (!in_array($sys_dnsserver, $dns_nameservers))) {
1217
					if ($add_v6_brackets && is_ipaddrv6($sys_dnsserver)) {
1218
						$sys_dnsserver = "[{$sys_dnsserver}]";
1219
					}
1220
					$dns_nameservers[] = $sys_dnsserver;
1221 4c6e3de4 jim-p
				}
1222 b7a4321c Peter Berbec
			}
1223
		}
1224
	}
1225 1e238af4 Peter Berbec
	return array_unique($dns_nameservers);
1226 b7a4321c Peter Berbec
}
1227
1228 1e8599e5 Chris Buechler
function system_generate_nginx_config($filename,
1229 eb0f441c Scott Ullrich
	$cert,
1230
	$key,
1231 257fdefe Chris Buechler
	$ca,
1232 eb0f441c Scott Ullrich
	$pid_file,
1233
	$port = 80,
1234
	$document_root = "/usr/local/www/",
1235 1e8599e5 Chris Buechler
	$cert_location = "cert.crt",
1236
	$key_location = "cert.key",
1237 3684280d doktornotor
	$captive_portal = false,
1238
	$hsts = true) {
1239 58c7450e Scott Ullrich
1240 f19d3b7a Scott Ullrich
	global $config, $g;
1241
1242 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
1243 58c7450e Scott Ullrich
		$mt = microtime();
1244 1e8599e5 Chris Buechler
		echo "system_generate_nginx_config() being called $mt\n";
1245 58c7450e Scott Ullrich
	}
1246
1247 6c07db48 Phil Davis
	if ($captive_portal !== false) {
1248 1d0c3a10 Chris Buechler
		$cp_interfaces = explode(",", $config['captiveportal'][$captive_portal]['interface']);
1249
		$cp_hostcheck = "";
1250
		foreach ($cp_interfaces as $cpint) {
1251
			$cpint_ip = get_interface_ip($cpint);
1252
			if (is_ipaddr($cpint_ip)) {
1253 8f10bc95 Chris Buechler
				$cp_hostcheck .= "\t\tif (\$http_host ~* $cpint_ip) {\n";
1254 1d0c3a10 Chris Buechler
				$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1255 d1f9426a Renato Botelho
				$cp_hostcheck .= "\t\t}\n";
1256 1d0c3a10 Chris Buechler
			}
1257
		}
1258 716d10e0 Renato Botelho
		if (isset($config['captiveportal'][$captive_portal]['httpsname']) &&
1259
		    is_domain($config['captiveportal'][$captive_portal]['httpsname'])) {
1260 8f10bc95 Chris Buechler
			$cp_hostcheck .= "\t\tif (\$http_host ~* {$config['captiveportal'][$captive_portal]['httpsname']}) {\n";
1261 1d0c3a10 Chris Buechler
			$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1262
			$cp_hostcheck .= "\t\t}\n";
1263
		}
1264
		$cp_rewrite = "\t\tif (\$cp_redirect = '') {\n";
1265 d47fe949 Chris Buechler
		$cp_rewrite .= "\t\t\trewrite	^ /index.php?zone=$captive_portal&redirurl=\$request_uri break;\n";
1266 1d0c3a10 Chris Buechler
		$cp_rewrite .= "\t\t}\n";
1267
1268 6844896c bcyrill
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1269 61e047a5 Phil Davis
		if (empty($maxprocperip)) {
1270 f7bddb24 Ermal
			$maxprocperip = 10;
1271 61e047a5 Phil Davis
		}
1272 f225cb92 Chris Buechler
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1273 d1f9426a Renato Botelho
	}
1274 61e047a5 Phil Davis
1275
	if (empty($port)) {
1276 1e8599e5 Chris Buechler
		$nginx_port = "80";
1277 61e047a5 Phil Davis
	} else {
1278 1e8599e5 Chris Buechler
		$nginx_port = $port;
1279 61e047a5 Phil Davis
	}
1280 3d77d4c4 Scott Ullrich
1281
	$memory = get_memory();
1282 6b0739ac Phil Davis
	$realmem = $memory[1];
1283 3d77d4c4 Scott Ullrich
1284 98f20e35 Irving Popovetsky
	// Determine web GUI process settings and take into account low memory systems
1285 61e047a5 Phil Davis
	if ($realmem < 255) {
1286 a96f2d3d Ermal
		$max_procs = 1;
1287 61e047a5 Phil Davis
	} else {
1288 98f20e35 Irving Popovetsky
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
1289 61e047a5 Phil Davis
	}
1290 f4ebc84a Scott Ullrich
1291 61e047a5 Phil Davis
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM
1292 6c07db48 Phil Davis
	if ($captive_portal !== false) {
1293 6b0739ac Phil Davis
		if ($realmem > 135 and $realmem < 256) {
1294 98f20e35 Irving Popovetsky
			$max_procs += 1; // 2 worker processes
1295 6b0739ac Phil Davis
		} else if ($realmem > 255 and $realmem < 513) {
1296 a96f2d3d Ermal
			$max_procs += 2; // 3 worker processes
1297 6b0739ac Phil Davis
		} else if ($realmem > 512) {
1298 98f20e35 Irving Popovetsky
			$max_procs += 4; // 6 worker processes
1299 70cc6249 Scott Ullrich
		}
1300 d1f9426a Renato Botelho
	}
1301 980df75c Scott Ullrich
1302 1e8599e5 Chris Buechler
	$nginx_config = <<<EOD
1303 28cae949 Scott Ullrich
#
1304 1e8599e5 Chris Buechler
# nginx configuration file
1305 a632cf43 Scott Ullrich
1306 1e8599e5 Chris Buechler
pid {$g['varrun_path']}/{$pid_file};
1307 096261af Scott Ullrich
1308 1e8599e5 Chris Buechler
user  root wheel;
1309
worker_processes  {$max_procs};
1310 28cae949 Scott Ullrich
1311 f77f43ff Chris Buechler
EOD;
1312
1313 db948c42 jim-p
	/* Disable file logging */
1314
	$nginx_config .= "error_log /dev/null;\n";
1315 8e2090a1 Jose Luis Duran
	if (!isset($config['syslog']['nolognginx'])) {
1316 db948c42 jim-p
		/* Send nginx error log to syslog */
1317 8e2090a1 Jose Luis Duran
		$nginx_config .= "error_log  syslog:server=unix:/var/run/log,facility=local5;\n";
1318
	}
1319 f77f43ff Chris Buechler
1320 8e2090a1 Jose Luis Duran
	$nginx_config .= <<<EOD
1321 1e8599e5 Chris Buechler
1322
events {
1323
    worker_connections  1024;
1324
}
1325 a632cf43 Scott Ullrich
1326 1e8599e5 Chris Buechler
http {
1327
	include       /usr/local/etc/nginx/mime.types;
1328
	default_type  application/octet-stream;
1329
	add_header X-Frame-Options SAMEORIGIN;
1330
	server_tokens off;
1331 a632cf43 Scott Ullrich
1332 1e8599e5 Chris Buechler
	sendfile        on;
1333 a632cf43 Scott Ullrich
1334 be6da8a4 Chris Buechler
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1335 2400f545 Jose Luis Duran
1336 f225cb92 Chris Buechler
EOD;
1337
1338 8e2090a1 Jose Luis Duran
	if ($captive_portal !== false) {
1339
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1340 754f7091 Chris Buechler
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1341
	} else {
1342
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1343 8e2090a1 Jose Luis Duran
	}
1344 9cb94dd4 Ermal
1345 61e047a5 Phil Davis
	if ($cert <> "" and $key <> "") {
1346 8e2090a1 Jose Luis Duran
		$nginx_config .= "\n";
1347
		$nginx_config .= "\tserver {\n";
1348 3aebb242 Laurent Quillerou
		$nginx_config .= "\t\tlisten {$nginx_port} ssl http2;\n";
1349
		$nginx_config .= "\t\tlisten [::]:{$nginx_port} ssl http2;\n";
1350 8e2090a1 Jose Luis Duran
		$nginx_config .= "\n";
1351 1e8599e5 Chris Buechler
		$nginx_config .= "\t\tssl_certificate         {$g['varetc_path']}/{$cert_location};\n";
1352
		$nginx_config .= "\t\tssl_certificate_key     {$g['varetc_path']}/{$key_location};\n";
1353 d1f9426a Renato Botelho
		$nginx_config .= "\t\tssl_session_timeout     10m;\n";
1354
		$nginx_config .= "\t\tkeepalive_timeout       70;\n";
1355 66a962cb Chris Buechler
		$nginx_config .= "\t\tssl_session_cache       shared:SSL:10m;\n";
1356 677f0a18 Chris Buechler
		if ($captive_portal !== false) {
1357 bb1692e4 jim-p
			// leave TLSv1.1 for CP for now for compatibility
1358 aa618753 jim-p
			$nginx_config .= "\t\tssl_protocols   TLSv1.1 TLSv1.2 TLSv1.3;\n";
1359 677f0a18 Chris Buechler
		} else {
1360 aa618753 jim-p
			$nginx_config .= "\t\tssl_protocols   TLSv1.2 TLSv1.3;\n";
1361 677f0a18 Chris Buechler
		}
1362 b58fe676 Viktor Gurov
		$nginx_config .= "\t\tssl_ciphers \"EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305\";\n";
1363 1e8599e5 Chris Buechler
		$nginx_config .= "\t\tssl_prefer_server_ciphers       on;\n";
1364 3684280d doktornotor
		if ($captive_portal === false && $hsts !== false) {
1365
			$nginx_config .= "\t\tadd_header Strict-Transport-Security \"max-age=31536000\";\n";
1366
		}
1367 1e8599e5 Chris Buechler
		$nginx_config .= "\t\tadd_header X-Content-Type-Options nosniff;\n";
1368
		$nginx_config .= "\t\tssl_session_tickets off;\n";
1369 02ba2c97 Chris Buechler
		$nginx_config .= "\t\tssl_dhparam /etc/dh-parameters.4096;\n";
1370 2d0f86ba Peter Berbec
		$cert_temp = lookup_cert($config['system']['webgui']['ssl-certref']);
1371
		if (($config['system']['webgui']['ocsp-staple'] == true) or
1372
		    (cert_get_ocspstaple($cert_temp['crt']) == true)) {
1373 2bf437ba Peter Berbec
			$nginx_config .= "\t\tssl_stapling on;\n";
1374 63a0cb97 Peter Berbec
			$nginx_config .= "\t\tssl_stapling_verify on;\n";
1375 4c6e3de4 jim-p
			$nginx_config .= "\t\tresolver " . implode(" ", get_dns_nameservers(true)) . " valid=300s;\n";
1376 2bf437ba Peter Berbec
			$nginx_config .= "\t\tresolver_timeout 5s;\n";
1377
		}
1378 8e2090a1 Jose Luis Duran
	} else {
1379 1e8599e5 Chris Buechler
		$nginx_config .= "\n";
1380 8e2090a1 Jose Luis Duran
		$nginx_config .= "\tserver {\n";
1381
		$nginx_config .= "\t\tlisten {$nginx_port};\n";
1382
		$nginx_config .= "\t\tlisten [::]:{$nginx_port};\n";
1383 1e8599e5 Chris Buechler
	}
1384
1385 8e2090a1 Jose Luis Duran
	$nginx_config .= <<<EOD
1386
1387
		client_max_body_size 200m;
1388
1389
		gzip on;
1390
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
1391
1392
1393
EOD;
1394
1395 1d0c3a10 Chris Buechler
	if ($captive_portal !== false) {
1396
		$nginx_config .= <<<EOD
1397 f225cb92 Chris Buechler
$captive_portal_maxprocperip
1398 1d0c3a10 Chris Buechler
$cp_hostcheck
1399
$cp_rewrite
1400 2f004405 Chris Buechler
		log_not_found off;
1401 1d0c3a10 Chris Buechler
1402
EOD;
1403
1404
	}
1405
1406 1e8599e5 Chris Buechler
	$nginx_config .= <<<EOD
1407
		root "{$document_root}";
1408
		location / {
1409 3a643eb8 Chris Buechler
			index  index.php index.html index.htm;
1410 1e8599e5 Chris Buechler
		}
1411 b1fccd42 jim-p
		location ~ \.inc$ {
1412
			deny all;
1413
			return 403;
1414
		}
1415 1e8599e5 Chris Buechler
		location ~ \.php$ {
1416
			try_files \$uri =404; #  This line closes a potential security hole
1417 d1f9426a Renato Botelho
			# ensuring users can't execute uploaded files
1418
			# see: http://forum.nginx.org/read.php?2,88845,page=3
1419 1e8599e5 Chris Buechler
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1420
			fastcgi_index  index.php;
1421
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1422 2039a3c1 Renato Botelho
			# Fix httpoxy - https://httpoxy.org/#fix-now
1423
			fastcgi_param  HTTP_PROXY  "";
1424 3fafb89b Chris Buechler
			fastcgi_read_timeout 180;
1425 1e8599e5 Chris Buechler
			include        /usr/local/etc/nginx/fastcgi_params;
1426 61e047a5 Phil Davis
		}
1427 418fdfb3 PiBa-NL
		location ~ (^/status$) {
1428
			allow 127.0.0.1;
1429
			deny all;
1430
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1431
			fastcgi_index  index.php;
1432
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1433
			# Fix httpoxy - https://httpoxy.org/#fix-now
1434
			fastcgi_param  HTTP_PROXY  "";
1435
			fastcgi_read_timeout 360;
1436
			include        /usr/local/etc/nginx/fastcgi_params;
1437
		}
1438 543ecd59 Seth Mos
	}
1439 569f47e9 Scott Ullrich
1440 a632cf43 Scott Ullrich
EOD;
1441
1442 7aae518a Scott Ullrich
	$cert = str_replace("\r", "", $cert);
1443 333f8ef0 Scott Ullrich
	$key = str_replace("\r", "", $key);
1444 7aae518a Scott Ullrich
1445
	$cert = str_replace("\n\n", "\n", $cert);
1446 333f8ef0 Scott Ullrich
	$key = str_replace("\n\n", "\n", $key);
1447 7aae518a Scott Ullrich
1448 61e047a5 Phil Davis
	if ($cert <> "" and $key <> "") {
1449 3a66b621 Scott Ullrich
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1450 5b237745 Scott Ullrich
		if (!$fd) {
1451 1e8599e5 Chris Buechler
			printf(gettext("Error: cannot open certificate file in system_webgui_start().%s"), "\n");
1452 5b237745 Scott Ullrich
			return 1;
1453
		}
1454 6e2f015a doktornotor
		chmod("{$g['varetc_path']}/{$cert_location}", 0644);
1455 32818dd9 Chris Buechler
		if ($ca <> "") {
1456
			$cert_chain = $cert . "\n" . $ca;
1457
		} else {
1458
			$cert_chain = $cert;
1459
		}
1460
		fwrite($fd, $cert_chain);
1461 5b237745 Scott Ullrich
		fclose($fd);
1462 1e8599e5 Chris Buechler
		$fd = fopen("{$g['varetc_path']}/{$key_location}", "w");
1463
		if (!$fd) {
1464
			printf(gettext("Error: cannot open certificate key file in system_webgui_start().%s"), "\n");
1465
			return 1;
1466 61e047a5 Phil Davis
		}
1467 1e8599e5 Chris Buechler
		chmod("{$g['varetc_path']}/{$key_location}", 0600);
1468
		fwrite($fd, $key);
1469
		fclose($fd);
1470 5b237745 Scott Ullrich
	}
1471 a978a0ff Chris Buechler
1472 61e047a5 Phil Davis
	// Add HTTP to HTTPS redirect
1473 6839a678 Ermal
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1474 1e8599e5 Chris Buechler
		if ($nginx_port != "443") {
1475
			$redirectport = ":{$nginx_port}";
1476 61e047a5 Phil Davis
		}
1477 1e8599e5 Chris Buechler
		$nginx_config .= <<<EOD
1478
	server {
1479
		listen 80;
1480
		listen [::]:80;
1481 8e2090a1 Jose Luis Duran
		return 301 https://\$http_host$redirectport\$request_uri;
1482 64a2da80 Chris Buechler
	}
1483 1e8599e5 Chris Buechler
1484 d7e230ae Chris Buechler
EOD;
1485
	}
1486 d1f9426a Renato Botelho
1487 1e8599e5 Chris Buechler
	$nginx_config .= "}\n";
1488 0f282d7a Scott Ullrich
1489 4f3756f3 Scott Ullrich
	$fd = fopen("{$filename}", "w");
1490 a632cf43 Scott Ullrich
	if (!$fd) {
1491 1579e70f Phil Davis
		printf(gettext('Error: cannot open %1$s in system_generate_nginx_config().%2$s'), $filename, "\n");
1492 a632cf43 Scott Ullrich
		return 1;
1493 5b237745 Scott Ullrich
	}
1494 1e8599e5 Chris Buechler
	fwrite($fd, $nginx_config);
1495 a632cf43 Scott Ullrich
	fclose($fd);
1496
1497 ab4e9539 jim-p
	/* nginx will fail to start if this directory does not exist. */
1498
	safe_mkdir("/var/tmp/nginx/");
1499
1500 a632cf43 Scott Ullrich
	return 0;
1501 0f282d7a Scott Ullrich
1502 5b237745 Scott Ullrich
}
1503
1504 60ff91f1 Renato Botelho
function system_get_timezone_list() {
1505
	global $g;
1506
1507 fc3bec29 Renato Botelho
	$file_list = array_merge(
1508
		glob("/usr/share/zoneinfo/[A-Z]*"),
1509 97433447 jim-p
		glob("/usr/share/zoneinfo/*/*"),
1510
		glob("/usr/share/zoneinfo/*/*/*")
1511 fc3bec29 Renato Botelho
	);
1512 60ff91f1 Renato Botelho
1513
	if (empty($file_list)) {
1514
		$file_list[] = $g['default_timezone'];
1515 fc3bec29 Renato Botelho
	} else {
1516
		/* Remove directories from list */
1517
		$file_list = array_filter($file_list, function($v) {
1518
			return !is_dir($v);
1519
		});
1520 60ff91f1 Renato Botelho
	}
1521
1522 fc3bec29 Renato Botelho
	/* Remove directory prefix */
1523
	$file_list = str_replace('/usr/share/zoneinfo/', '', $file_list);
1524
1525
	sort($file_list);
1526
1527
	return $file_list;
1528 60ff91f1 Renato Botelho
}
1529
1530 5b237745 Scott Ullrich
function system_timezone_configure() {
1531 f19d3b7a Scott Ullrich
	global $config, $g;
1532 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
1533 58c7450e Scott Ullrich
		$mt = microtime();
1534 dcf0598e Scott Ullrich
		echo "system_timezone_configure() being called $mt\n";
1535 333f8ef0 Scott Ullrich
	}
1536 5b237745 Scott Ullrich
1537
	$syscfg = $config['system'];
1538
1539 61e047a5 Phil Davis
	if (platform_booting()) {
1540 4a896b86 Carlos Eduardo Ramos
		echo gettext("Setting timezone...");
1541 61e047a5 Phil Davis
	}
1542 5b237745 Scott Ullrich
1543
	/* extract appropriate timezone file */
1544 60ff91f1 Renato Botelho
	$timezone = (isset($syscfg['timezone']) ? $syscfg['timezone'] : $g['default_timezone']);
1545 c9ab2622 Chris Buechler
	/* DO NOT remove \n otherwise tzsetup will fail */
1546 60ff91f1 Renato Botelho
	@file_put_contents("/var/db/zoneinfo", $timezone . "\n");
1547
	mwexec("/usr/sbin/tzsetup -r");
1548 34febcde Scott Ullrich
1549 61e047a5 Phil Davis
	if (platform_booting()) {
1550 4a896b86 Carlos Eduardo Ramos
		echo gettext("done.") . "\n";
1551 61e047a5 Phil Davis
	}
1552 5b237745 Scott Ullrich
}
1553
1554 f6626804 Viktor G
function check_gps_speed($device) {
1555
	usleep(1000);
1556
	// Set timeout to 5s
1557
	$timeout=microtime(true)+5;
1558
	if ($fp = fopen($device, 'r')) {
1559
		stream_set_blocking($fp, 0);
1560
		stream_set_timeout($fp, 5);
1561
		$contents = "";
1562
		$cnt = 0;
1563
		$buffersize = 256;
1564
		do {
1565
			$c = fread($fp, $buffersize - $cnt);
1566
1567
			// Wait for data to arive
1568
			if (($c === false) || (strlen($c) == 0)) {
1569
				usleep(500);
1570
				continue;
1571
			}
1572
1573
			$contents.=$c;
1574
			$cnt = $cnt + strlen($c);
1575
		} while (($cnt < $buffersize) && (microtime(true) < $timeout));
1576
		fclose($fp);
1577
1578
		$nmeasentences = ['RMC', 'GGA', 'GLL', 'ZDA', 'ZDG', 'PGRMF'];
1579
		foreach ($nmeasentences as $sentence) {
1580
			if (strpos($contents, $sentence) > 0) {
1581
				return true;
1582
			}
1583
		}
1584
		if (strpos($contents, '0') > 0) {
1585
			$filters = ['`', '?', '/', '~'];
1586
			foreach ($filters as $filter) {
1587
				if (strpos($contents, $filter) !== false) {
1588
					return false;
1589
				}
1590
			}
1591
			return true;
1592
		}
1593
	}
1594
	return false;
1595
}
1596
1597 8ef6844a jim-p
/* Generate list of possible NTP poll values
1598
 * https://redmine.pfsense.org/issues/9439 */
1599
global $ntp_poll_min_value, $ntp_poll_max_value;
1600
global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
1601
global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
1602
global $ntp_poll_min_default, $ntp_poll_max_default;
1603 9108d083 Viktor G
global $ntp_auth_halgos;
1604 8ef6844a jim-p
$ntp_poll_min_value = 4;
1605
$ntp_poll_max_value = 17;
1606
$ntp_poll_min_default_gps = 4;
1607
$ntp_poll_max_default_gps = 4;
1608
$ntp_poll_min_default_pps = 4;
1609
$ntp_poll_max_default_pps = 4;
1610
$ntp_poll_min_default = 'omit';
1611
$ntp_poll_max_default = 9;
1612 9108d083 Viktor G
$ntp_auth_halgos = array(
1613
	'md5' => 'MD5',
1614
	'sha1' => 'SHA1'
1615
);
1616 8ef6844a jim-p
1617
function system_ntp_poll_values() {
1618
	global $ntp_poll_min_value, $ntp_poll_max_value;
1619
	$poll_values = array("" => gettext('Default'));
1620
1621
	for ($i = $ntp_poll_min_value; $i <= $ntp_poll_max_value; $i++) {
1622
		$sec = 2 ** $i;
1623
		$poll_values[$i] = $i . ': ' . number_format($sec) . ' ' . gettext('seconds') .
1624
					' (' . convert_seconds_to_dhms($sec) . ')';
1625
	}
1626
1627
	$poll_values['omit'] = gettext('Omit (Do not set)');
1628
	return $poll_values;
1629
}
1630
1631
function system_ntp_fixup_poll_value($type, $configvalue, $default) {
1632
	$pollstring = "";
1633
1634
	if (empty($configvalue)) {
1635
		$configvalue = $default;
1636
	}
1637
1638
	if ($configvalue != 'omit') {
1639
		$pollstring = " {$type} {$configvalue}";
1640
	}
1641
1642
	return $pollstring;
1643
}
1644
1645 5c8843d5 jim-p
function system_ntp_setup_gps($serialport) {
1646 142f7393 nagyrobi
	global $config, $g;
1647 f6626804 Viktor G
1648 b5d5da0c Viktor Gurov
	if (is_array($config['ntpd']) && ($config['ntpd']['enable'] == 'disabled')) {
1649
		return false;
1650
	}
1651
1652 cec1d944 Viktor Gurov
	init_config_arr(array('ntpd', 'gps'));
1653
1654 5c8843d5 jim-p
	$gps_device = '/dev/gps0';
1655
	$serialport = '/dev/'.$serialport;
1656
1657 61e047a5 Phil Davis
	if (!file_exists($serialport)) {
1658 5c8843d5 jim-p
		return false;
1659 61e047a5 Phil Davis
	}
1660 5c8843d5 jim-p
1661
	// Create symlink that ntpd requires
1662
	unlink_if_exists($gps_device);
1663 11caacf6 Ermal LUÇI
	@symlink($serialport, $gps_device);
1664 5c8843d5 jim-p
1665 1e329241 Robert Noland
	$gpsbaud = '4800';
1666 f6626804 Viktor G
	$speeds = array(
1667
		0 => '4800', 
1668
		16 => '9600', 
1669
		32 => '19200', 
1670
		48 => '38400', 
1671
		64 => '57600', 
1672
		80 => '115200'
1673
	);
1674
	if (!empty($config['ntpd']['gps']['speed']) && array_key_exists($config['ntpd']['gps']['speed'], $speeds)) {
1675
		$gpsbaud = $speeds[$config['ntpd']['gps']['speed']];
1676
	}
1677
1678
	system_ntp_setup_rawspeed($serialport, $gpsbaud);
1679
1680
	$autospeed = ($config['ntpd']['gps']['speed'] == 'autoalways' || $config['ntpd']['gps']['speed'] == 'autoset');
1681
	if ($autospeed || ($config['ntpd']['gps']['autobaudinit'] && !check_gps_speed($gps_device))) {
1682
		$found = false;
1683
		foreach ($speeds as $baud) {
1684
			system_ntp_setup_rawspeed($serialport, $baud);
1685
			if ($found = check_gps_speed($gps_device)) {
1686
				if ($autospeed) {
1687
					$saveconfig = ($config['ntpd']['gps']['speed'] == 'autoset');
1688
					$config['ntpd']['gps']['speed'] = array_search($baud, $speeds);
1689
					$gpsbaud = $baud;
1690
					if ($saveconfig) {
1691
						write_config(sprintf(gettext('Autoset GPS baud rate to %s'), $baud));
1692
					}
1693
				}
1694 1e329241 Robert Noland
				break;
1695 f6626804 Viktor G
			}
1696
		}
1697
		if ($found === false) {
1698
			log_error(gettext("Could not find correct GPS baud rate."));
1699
			return false;
1700 1e329241 Robert Noland
		}
1701
	}
1702
1703 5c8843d5 jim-p
	/* Send the following to the GPS port to initialize the GPS */
1704 ec7bc948 Ermal
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
1705 142f7393 nagyrobi
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
1706 61e047a5 Phil Davis
	} else {
1707 142f7393 nagyrobi
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1708
	}
1709 ec7bc948 Ermal
1710
	/* XXX: Why not file_put_contents to the device */
1711
	@file_put_contents('/tmp/gps.init', $gps_init);
1712 417008f7 Renato Botelho
	mwexec("cat /tmp/gps.init > {$serialport}");
1713 5c8843d5 jim-p
1714 f6626804 Viktor G
	if ($found && $config['ntpd']['gps']['autobaudinit']) {
1715
		system_ntp_setup_rawspeed($serialport, $gpsbaud);
1716
	}
1717
1718
	/* Remove old /etc/remote entry if it exists */
1719 cec1d944 Viktor Gurov
	if (mwexec("/usr/bin/grep -c '^gps0' /etc/remote") == 0) {
1720 f6626804 Viktor G
		mwexec("/usr/bin/sed -i '' -n '/gps0/!p' /etc/remote");
1721
	}
1722
1723 5c8843d5 jim-p
	/* Add /etc/remote entry in case we need to read from the GPS with tip */
1724 cec1d944 Viktor Gurov
	if (mwexec("/usr/bin/grep -c '^gps0' /etc/remote") != 0) {
1725 0771de32 jim-p
		@file_put_contents("/etc/remote", "gps0:dv={$serialport}:br#{$gpsbaud}:pa=none:\n", FILE_APPEND);
1726 ec7bc948 Ermal
	}
1727 5c8843d5 jim-p
1728
	return true;
1729
}
1730
1731 f6626804 Viktor G
// Configure the serial port for raw IO and set the speed
1732
function system_ntp_setup_rawspeed($serialport, $baud) {
1733
	mwexec("/bin/stty -f " .  escapeshellarg($serialport) . " raw speed " . escapeshellarg($baud));
1734
	mwexec("/bin/stty -f " .  escapeshellarg($serialport) . ".init raw speed " . escapeshellarg($baud));
1735
}
1736
1737 142f7393 nagyrobi
function system_ntp_setup_pps($serialport) {
1738
	global $config, $g;
1739 ec7bc948 Ermal
1740 142f7393 nagyrobi
	$pps_device = '/dev/pps0';
1741
	$serialport = '/dev/'.$serialport;
1742
1743 61e047a5 Phil Davis
	if (!file_exists($serialport)) {
1744 142f7393 nagyrobi
		return false;
1745 61e047a5 Phil Davis
	}
1746 b5d5da0c Viktor Gurov
	// If ntpd is disabled, just return
1747
	if (is_array($config['ntpd']) && ($config['ntpd']['enable'] == 'disabled')) {
1748
		return false;
1749
	}
1750 142f7393 nagyrobi
1751
	// Create symlink that ntpd requires
1752
	unlink_if_exists($pps_device);
1753 ec7bc948 Ermal
	@symlink($serialport, $pps_device);
1754 142f7393 nagyrobi
1755
1756
	return true;
1757
}
1758
1759 2dced82f Renato Botelho
function system_ntp_configure() {
1760 f19d3b7a Scott Ullrich
	global $config, $g;
1761 8ef6844a jim-p
	global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
1762
	global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
1763
	global $ntp_poll_min_default, $ntp_poll_max_default;
1764 ec7bc948 Ermal
1765 42135f07 jim-p
	$driftfile = "/var/db/ntpd.drift";
1766 5c8843d5 jim-p
	$statsdir = "/var/log/ntp";
1767
	$gps_device = '/dev/gps0';
1768 5b237745 Scott Ullrich
1769 5c8843d5 jim-p
	safe_mkdir($statsdir);
1770
1771 61e047a5 Phil Davis
	if (!is_array($config['ntpd'])) {
1772 ec7bc948 Ermal
		$config['ntpd'] = array();
1773 61e047a5 Phil Davis
	}
1774 b5d5da0c Viktor Gurov
	// ntpd is disabled, just stop it and return
1775
	if ($config['ntpd']['enable'] == 'disabled') {
1776
		while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1777
			killbypid("{$g['varrun_path']}/ntpd.pid");
1778
		}
1779
		@unlink("{$g['varrun_path']}/ntpd.pid");
1780
		@unlink("{$g['varetc_path']}/ntpd.conf");
1781 9108d083 Viktor G
		@unlink("{$g['varetc_path']}/ntp.keys");
1782 b5d5da0c Viktor Gurov
		log_error("NTPD is disabled.");
1783
		return;
1784
	}
1785
1786
	if (platform_booting()) {
1787
		echo gettext("Starting NTP Server...");
1788
	}
1789 ec7bc948 Ermal
1790 f6626804 Viktor G
	/* if ntpd is running, kill it */
1791
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1792
		killbypid("{$g['varrun_path']}/ntpd.pid");
1793
	}
1794
	@unlink("{$g['varrun_path']}/ntpd.pid");
1795
1796 9108d083 Viktor G
	/* set NTP server authentication key */
1797
	if ($config['ntpd']['serverauth'] == 'yes') {
1798
		$ntpkeyscfg = "1 " . strtoupper($config['ntpd']['serverauthalgo']) . " " . base64_decode($config['ntpd']['serverauthkey']) . "\n";
1799
		if (!@file_put_contents("{$g['varetc_path']}/ntp.keys", $ntpkeyscfg)) {
1800
			log_error(sprintf(gettext("Could not open %s/ntp.keys for writing"), $g['varetc_path']));
1801
			return;
1802
		}
1803
	} else {
1804
		unlink_if_exists("{$g['varetc_path']}/ntp.keys");
1805
	}
1806
1807 b2305621 Ermal
	$ntpcfg = "# \n";
1808 42135f07 jim-p
	$ntpcfg .= "# pfSense ntp configuration file \n";
1809 b2305621 Ermal
	$ntpcfg .= "# \n\n";
1810 9108d083 Viktor G
	$ntpcfg .= "tinker panic 0 \n\n";
1811
1812
	if ($config['ntpd']['serverauth'] == 'yes') {
1813
		$ntpcfg .= "# Authentication settings \n";
1814
		$ntpcfg .= "keys /var/etc/ntp.keys \n";
1815
		$ntpcfg .= "trustedkey 1 \n";
1816
		$ntpcfg .= "requestkey 1 \n";
1817
		$ntpcfg .= "controlkey 1 \n";
1818
		$ntpcfg .= "\n";
1819
	}
1820 0f282d7a Scott Ullrich
1821 142f7393 nagyrobi
	/* Add Orphan mode */
1822 8258cd02 kiokoman
	$ntpcfg .= "# Orphan mode stratum and Maximum candidate NTP peers\n";
1823 142f7393 nagyrobi
	$ntpcfg .= 'tos orphan ';
1824
	if (!empty($config['ntpd']['orphan'])) {
1825
		$ntpcfg .= $config['ntpd']['orphan'];
1826 61e047a5 Phil Davis
	} else {
1827 142f7393 nagyrobi
		$ntpcfg .= '12';
1828
	}
1829 8258cd02 kiokoman
	/* Add Maximum candidate NTP peers */
1830 8ab59ef3 kiokoman
	$ntpcfg .= ' maxclock ';
1831 169f9eea kiokoman
	if (!empty($config['ntpd']['ntpmaxpeers'])) {
1832
		$ntpcfg .= $config['ntpd']['ntpmaxpeers'];
1833
	} else {
1834 8ab59ef3 kiokoman
		$ntpcfg .= '5';
1835 169f9eea kiokoman
	}
1836 142f7393 nagyrobi
	$ntpcfg .= "\n";
1837
1838
	/* Add PPS configuration */
1839 61e047a5 Phil Davis
	if (is_array($config['ntpd']['pps']) && !empty($config['ntpd']['pps']['port']) &&
1840
	    file_exists('/dev/'.$config['ntpd']['pps']['port']) &&
1841
	    system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
1842 142f7393 nagyrobi
		$ntpcfg .= "\n";
1843
		$ntpcfg .= "# PPS Setup\n";
1844
		$ntpcfg .= 'server 127.127.22.0';
1845 8ef6844a jim-p
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', $config['ntpd']['pps']['ppsminpoll'], $ntp_poll_min_default_pps);
1846
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', $config['ntpd']['pps']['ppsmaxpoll'], $ntp_poll_max_default_pps);
1847 142f7393 nagyrobi
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
1848 61e047a5 Phil Davis
			$ntpcfg .= ' prefer';
1849 142f7393 nagyrobi
		}
1850
		if (!empty($config['ntpd']['pps']['noselect'])) {
1851
			$ntpcfg .= ' noselect ';
1852
		}
1853
		$ntpcfg .= "\n";
1854
		$ntpcfg .= 'fudge 127.127.22.0';
1855
		if (!empty($config['ntpd']['pps']['fudge1'])) {
1856
			$ntpcfg .= ' time1 ';
1857
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
1858
		}
1859
		if (!empty($config['ntpd']['pps']['flag2'])) {
1860
			$ntpcfg .= ' flag2 1';
1861
		}
1862
		if (!empty($config['ntpd']['pps']['flag3'])) {
1863
			$ntpcfg .= ' flag3 1';
1864 61e047a5 Phil Davis
		} else {
1865 142f7393 nagyrobi
			$ntpcfg .= ' flag3 0';
1866
		}
1867
		if (!empty($config['ntpd']['pps']['flag4'])) {
1868
			$ntpcfg .= ' flag4 1';
1869
		}
1870
		if (!empty($config['ntpd']['pps']['refid'])) {
1871
			$ntpcfg .= ' refid ';
1872
			$ntpcfg .= $config['ntpd']['pps']['refid'];
1873
		}
1874
		$ntpcfg .= "\n";
1875
	}
1876
	/* End PPS configuration */
1877
1878
	/* Add GPS configuration */
1879 61e047a5 Phil Davis
	if (is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['port']) &&
1880
	    system_ntp_setup_gps($config['ntpd']['gps']['port'])) {
1881 142f7393 nagyrobi
		$ntpcfg .= "\n";
1882
		$ntpcfg .= "# GPS Setup\n";
1883
		$ntpcfg .= 'server 127.127.20.0 mode ';
1884 821110e8 jskyboo
		if (!empty($config['ntpd']['gps']['nmea']) || !empty($config['ntpd']['gps']['speed']) || !empty($config['ntpd']['gps']['subsec']) || !empty($config['ntpd']['gps']['processpgrmf'])) {
1885 142f7393 nagyrobi
			if (!empty($config['ntpd']['gps']['nmea'])) {
1886
				$ntpmode = (int) $config['ntpd']['gps']['nmea'];
1887
			}
1888
			if (!empty($config['ntpd']['gps']['speed'])) {
1889
				$ntpmode += (int) $config['ntpd']['gps']['speed'];
1890
			}
1891
			if (!empty($config['ntpd']['gps']['subsec'])) {
1892
				$ntpmode += 128;
1893
			}
1894 6924a2bf jskyboo
			if (!empty($config['ntpd']['gps']['processpgrmf'])) {
1895
				$ntpmode += 256;
1896
			}
1897 142f7393 nagyrobi
			$ntpcfg .= (string) $ntpmode;
1898 61e047a5 Phil Davis
		} else {
1899 142f7393 nagyrobi
			$ntpcfg .= '0';
1900
		}
1901 8ef6844a jim-p
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', $config['ntpd']['gps']['gpsminpoll'], $ntp_poll_min_default_gps);
1902
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', $config['ntpd']['gps']['gpsmaxpoll'], $ntp_poll_max_default_gps);
1903
1904 142f7393 nagyrobi
		if (empty($config['ntpd']['gps']['prefer'])) { /*note: this one works backwards */
1905 61e047a5 Phil Davis
			$ntpcfg .= ' prefer';
1906 142f7393 nagyrobi
		}
1907
		if (!empty($config['ntpd']['gps']['noselect'])) {
1908
			$ntpcfg .= ' noselect ';
1909
		}
1910
		$ntpcfg .= "\n";
1911
		$ntpcfg .= 'fudge 127.127.20.0';
1912
		if (!empty($config['ntpd']['gps']['fudge1'])) {
1913
			$ntpcfg .= ' time1 ';
1914
			$ntpcfg .= $config['ntpd']['gps']['fudge1'];
1915
		}
1916
		if (!empty($config['ntpd']['gps']['fudge2'])) {
1917
			$ntpcfg .= ' time2 ';
1918
			$ntpcfg .= $config['ntpd']['gps']['fudge2'];
1919
		}
1920
		if (!empty($config['ntpd']['gps']['flag1'])) {
1921
			$ntpcfg .= ' flag1 1';
1922 61e047a5 Phil Davis
		} else {
1923 142f7393 nagyrobi
			$ntpcfg .= ' flag1 0';
1924
		}
1925
		if (!empty($config['ntpd']['gps']['flag2'])) {
1926
			$ntpcfg .= ' flag2 1';
1927
		}
1928
		if (!empty($config['ntpd']['gps']['flag3'])) {
1929
			$ntpcfg .= ' flag3 1';
1930 61e047a5 Phil Davis
		} else {
1931 142f7393 nagyrobi
			$ntpcfg .= ' flag3 0';
1932
		}
1933
		if (!empty($config['ntpd']['gps']['flag4'])) {
1934
			$ntpcfg .= ' flag4 1';
1935
		}
1936
		if (!empty($config['ntpd']['gps']['refid'])) {
1937
			$ntpcfg .= ' refid ';
1938
			$ntpcfg .= $config['ntpd']['gps']['refid'];
1939
		}
1940 66937f5c Jean Cyr
		if (!empty($config['ntpd']['gps']['stratum'])) {
1941
			$ntpcfg .= ' stratum ';
1942
			$ntpcfg .= $config['ntpd']['gps']['stratum'];
1943
		}
1944 142f7393 nagyrobi
		$ntpcfg .= "\n";
1945 61e047a5 Phil Davis
	} elseif (is_array($config['ntpd']) && !empty($config['ntpd']['gpsport']) &&
1946
	    system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1947 142f7393 nagyrobi
		/* This handles a 2.1 and earlier config */
1948 5c8843d5 jim-p
		$ntpcfg .= "# GPS Setup\n";
1949
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1950
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1951
		// Fall back to local clock if GPS is out of sync?
1952
		$ntpcfg .= "server 127.127.1.0\n";
1953
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1954
	}
1955 142f7393 nagyrobi
	/* End GPS configuration */
1956 fbb652ed jim-p
	$auto_pool_suffix = "pool.ntp.org";
1957
	$have_pools = false;
1958 5c8843d5 jim-p
	$ntpcfg .= "\n\n# Upstream Servers\n";
1959 142f7393 nagyrobi
	/* foreach through ntp servers and write out to ntpd.conf */
1960
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1961 fbb652ed jim-p
		if ((substr_compare($ts, $auto_pool_suffix, strlen($ts) - strlen($auto_pool_suffix), strlen($auto_pool_suffix)) === 0)
1962
		    || substr_count($config['ntpd']['ispool'], $ts)) {
1963
			$ntpcfg .= 'pool ';
1964
			$have_pools = true;
1965
		} else {
1966
			$ntpcfg .= 'server ';
1967 bdb26b26 Viktor G
			if ($config['ntpd']['dnsresolv'] == 'inet') {
1968
				$ntpcfg .= '-4 ';
1969
			} elseif ($config['ntpd']['dnsresolv'] == 'inet6') {
1970
				$ntpcfg .= '-6 ';
1971
			}
1972 fbb652ed jim-p
		}
1973
1974 8ef6844a jim-p
		$ntpcfg .= "{$ts} iburst";
1975
1976
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', $config['ntpd']['ntpminpoll'], $ntp_poll_min_default);
1977
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', $config['ntpd']['ntpmaxpoll'], $ntp_poll_max_default);
1978
1979 61e047a5 Phil Davis
		if (substr_count($config['ntpd']['prefer'], $ts)) {
1980
			$ntpcfg .= ' prefer';
1981
		}
1982
		if (substr_count($config['ntpd']['noselect'], $ts)) {
1983
			$ntpcfg .= ' noselect';
1984
		}
1985 142f7393 nagyrobi
		$ntpcfg .= "\n";
1986
	}
1987
	unset($ts);
1988
1989
	$ntpcfg .= "\n\n";
1990
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
1991
		$ntpcfg .= "enable stats\n";
1992
		$ntpcfg .= 'statistics';
1993
		if (!empty($config['ntpd']['clockstats'])) {
1994
			$ntpcfg .= ' clockstats';
1995
		}
1996
		if (!empty($config['ntpd']['loopstats'])) {
1997
			$ntpcfg .= ' loopstats';
1998
		}
1999
		if (!empty($config['ntpd']['peerstats'])) {
2000
			$ntpcfg .= ' peerstats';
2001
		}
2002
		$ntpcfg .= "\n";
2003
	}
2004 5c8843d5 jim-p
	$ntpcfg .= "statsdir {$statsdir}\n";
2005 142f7393 nagyrobi
	$ntpcfg .= 'logconfig =syncall +clockall';
2006
	if (!empty($config['ntpd']['logpeer'])) {
2007
		$ntpcfg .= ' +peerall';
2008
	}
2009
	if (!empty($config['ntpd']['logsys'])) {
2010
		$ntpcfg .= ' +sysall';
2011
	}
2012
	$ntpcfg .= "\n";
2013 42135f07 jim-p
	$ntpcfg .= "driftfile {$driftfile}\n";
2014 31b15180 jim-p
2015
	/* Default Access restrictions */
2016 142f7393 nagyrobi
	$ntpcfg .= 'restrict default';
2017
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
2018 61e047a5 Phil Davis
		$ntpcfg .= ' kod limited';
2019 142f7393 nagyrobi
	}
2020
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
2021 61e047a5 Phil Davis
		$ntpcfg .= ' nomodify';
2022 142f7393 nagyrobi
	}
2023
	if (!empty($config['ntpd']['noquery'])) {
2024
		$ntpcfg .= ' noquery';
2025
	}
2026
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
2027 61e047a5 Phil Davis
		$ntpcfg .= ' nopeer';
2028 142f7393 nagyrobi
	}
2029
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
2030 61e047a5 Phil Davis
		$ntpcfg .= ' notrap';
2031 142f7393 nagyrobi
	}
2032
	if (!empty($config['ntpd']['noserve'])) {
2033
		$ntpcfg .= ' noserve';
2034
	}
2035
	$ntpcfg .= "\nrestrict -6 default";
2036
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
2037 61e047a5 Phil Davis
		$ntpcfg .= ' kod limited';
2038 142f7393 nagyrobi
	}
2039
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
2040 61e047a5 Phil Davis
		$ntpcfg .= ' nomodify';
2041 142f7393 nagyrobi
	}
2042
	if (!empty($config['ntpd']['noquery'])) {
2043
		$ntpcfg .= ' noquery';
2044
	}
2045
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
2046 61e047a5 Phil Davis
		$ntpcfg .= ' nopeer';
2047 142f7393 nagyrobi
	}
2048
	if (!empty($config['ntpd']['noserve'])) {
2049
		$ntpcfg .= ' noserve';
2050
	}
2051
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
2052 61e047a5 Phil Davis
		$ntpcfg .= ' notrap';
2053 142f7393 nagyrobi
	}
2054 fbb652ed jim-p
2055 61452020 Viktor G
	/* Pools require "restrict source" and cannot contain "nopeer" and "noserve". */
2056 fbb652ed jim-p
	if ($have_pools) {
2057
		$ntpcfg .= "\nrestrict source";
2058
		if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
2059
			$ntpcfg .= ' kod limited';
2060
		}
2061
		if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
2062
			$ntpcfg .= ' nomodify';
2063
		}
2064
		if (!empty($config['ntpd']['noquery'])) {
2065
			$ntpcfg .= ' noquery';
2066
		}
2067
		if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
2068
			$ntpcfg .= ' notrap';
2069
		}
2070
	}
2071
2072 31b15180 jim-p
	/* Custom Access Restrictions */
2073
	if (is_array($config['ntpd']['restrictions']) && is_array($config['ntpd']['restrictions']['row'])) {
2074
		$networkacl = $config['ntpd']['restrictions']['row'];
2075
		foreach ($networkacl as $acl) {
2076 d90beba6 jim-p
			$restrict = "";
2077 31b15180 jim-p
			if (is_ipaddrv6($acl['acl_network'])) {
2078 d90beba6 jim-p
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask_v6($acl['mask']) . " ";
2079 31b15180 jim-p
			} elseif (is_ipaddrv4($acl['acl_network'])) {
2080 d90beba6 jim-p
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask($acl['mask']) . " ";
2081 31b15180 jim-p
			} else {
2082
				continue;
2083
			}
2084
			if (!empty($acl['kod'])) {
2085 d90beba6 jim-p
				$restrict .= ' kod limited';
2086 31b15180 jim-p
			}
2087
			if (!empty($acl['nomodify'])) {
2088 d90beba6 jim-p
				$restrict .= ' nomodify';
2089 31b15180 jim-p
			}
2090
			if (!empty($acl['noquery'])) {
2091 d90beba6 jim-p
				$restrict .= ' noquery';
2092 31b15180 jim-p
			}
2093
			if (!empty($acl['nopeer'])) {
2094 d90beba6 jim-p
				$restrict .= ' nopeer';
2095 31b15180 jim-p
			}
2096
			if (!empty($acl['noserve'])) {
2097 d90beba6 jim-p
				$restrict .= ' noserve';
2098 31b15180 jim-p
			}
2099
			if (!empty($acl['notrap'])) {
2100 d90beba6 jim-p
				$restrict .= ' notrap';
2101
			}
2102
			if (!empty($restrict)) {
2103
				$ntpcfg .= "\nrestrict {$restrict} ";
2104 31b15180 jim-p
			}
2105
		}
2106
	}
2107
	/* End Custom Access Restrictions */
2108 142f7393 nagyrobi
2109
	/* A leapseconds file is really only useful if this clock is stratum 1 */
2110
	$ntpcfg .= "\n";
2111
	if (!empty($config['ntpd']['leapsec'])) {
2112
		$leapsec .= base64_decode($config['ntpd']['leapsec']);
2113
		file_put_contents('/var/db/leap-seconds', $leapsec);
2114
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
2115
	}
2116 61e047a5 Phil Davis
2117 95594e5a Scott Ullrich
2118 51e76899 Ermal LUÇI
	if (empty($config['ntpd']['interface'])) {
2119 61e047a5 Phil Davis
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface'])) {
2120 cf180ccc jim-p
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
2121 61e047a5 Phil Davis
		} else {
2122 cf180ccc jim-p
			$interfaces = array();
2123 61e047a5 Phil Davis
		}
2124
	} else {
2125 cf180ccc jim-p
		$interfaces = explode(",", $config['ntpd']['interface']);
2126 61e047a5 Phil Davis
	}
2127 cf180ccc jim-p
2128
	if (is_array($interfaces) && count($interfaces)) {
2129 2a5960b0 Luiz Otavio O Souza
		$finterfaces = array();
2130 cf180ccc jim-p
		$ntpcfg .= "interface ignore all\n";
2131 c2a52440 jim-p
		$ntpcfg .= "interface ignore wildcard\n";
2132 cf180ccc jim-p
		foreach ($interfaces as $interface) {
2133 2a5960b0 Luiz Otavio O Souza
			$interface = get_real_interface($interface);
2134 d9901ff4 Chris Buechler
			if (!empty($interface)) {
2135 2a5960b0 Luiz Otavio O Souza
				$finterfaces[] = $interface;
2136 d9901ff4 Chris Buechler
			}
2137 2a5960b0 Luiz Otavio O Souza
		}
2138
		foreach ($finterfaces as $interface) {
2139
			$ntpcfg .= "interface listen {$interface}\n";
2140 cf180ccc jim-p
		}
2141
	}
2142
2143 f416763b Phil Davis
	/* open configuration for writing or bail */
2144 b9f29f84 Ermal
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
2145 e8c516a0 Phil Davis
		log_error(sprintf(gettext("Could not open %s/ntpd.conf for writing"), $g['varetc_path']));
2146 b2305621 Ermal
		return;
2147
	}
2148 20b90e0a Scott Ullrich
2149 5f3e1f12 Scott Ullrich
	/* if /var/empty does not exist, create it */
2150 61e047a5 Phil Davis
	if (!is_dir("/var/empty")) {
2151 c01bdca9 Renato Botelho
		mkdir("/var/empty", 0555, true);
2152 61e047a5 Phil Davis
	}
2153 5f3e1f12 Scott Ullrich
2154 b5d5da0c Viktor Gurov
	/* start ntpd, set time now and use /var/etc/ntpd.conf */
2155 0fd64e94 nagyrobi
	mwexec("/usr/local/sbin/ntpd -g -c {$g['varetc_path']}/ntpd.conf -p {$g['varrun_path']}/ntpd.pid", false, true);
2156 61e047a5 Phil Davis
2157 83eb4567 Scott Ullrich
	// Note that we are starting up
2158 42135f07 jim-p
	log_error("NTPD is starting up.");
2159 b5d5da0c Viktor Gurov
2160
	if (platform_booting()) {
2161
		echo gettext("done.") . "\n";
2162
	}
2163
2164 0b8e9d38 jim-p
	return;
2165 5b237745 Scott Ullrich
}
2166
2167 405e5de0 Scott Ullrich
function system_halt() {
2168
	global $g;
2169
2170
	system_reboot_cleanup();
2171
2172 523855b0 Scott Ullrich
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
2173 405e5de0 Scott Ullrich
}
2174
2175 5b237745 Scott Ullrich
function system_reboot() {
2176
	global $g;
2177 0f282d7a Scott Ullrich
2178 5b237745 Scott Ullrich
	system_reboot_cleanup();
2179 0f282d7a Scott Ullrich
2180 5b237745 Scott Ullrich
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
2181
}
2182
2183 a2c453fd jim-p
function system_reboot_sync($reroot=false) {
2184 5b237745 Scott Ullrich
	global $g;
2185 0f282d7a Scott Ullrich
2186 a2c453fd jim-p
	if ($reroot) {
2187
		$args = " -r ";
2188
	}
2189
2190 5b237745 Scott Ullrich
	system_reboot_cleanup();
2191 0f282d7a Scott Ullrich
2192 a2c453fd jim-p
	mwexec("/etc/rc.reboot {$args} > /dev/null 2>&1");
2193 5b237745 Scott Ullrich
}
2194
2195
function system_reboot_cleanup() {
2196 445c97fc Augustin-FL
	global $config, $g, $cpzone;
2197 62f20eab Michael Newton
2198 97d4e30b Seth Mos
	mwexec("/usr/local/bin/beep.sh stop");
2199 04967d99 jim-p
	require_once("captiveportal.inc");
2200 52034432 Renato Botelho
	if (is_array($config['captiveportal'])) {
2201 34cb8645 Jean Cyr
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
2202 445c97fc Augustin-FL
			if (!isset($cp['preservedb'])) {
2203
				/* send Accounting-Stop packet for all clients, termination cause 'Admin-Reboot' */
2204
				captiveportal_radius_stop_all(7); // Admin-Reboot
2205
				unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
2206
				captiveportal_free_dnrules();
2207
			}
2208 3ece6d54 plumbeo
			/* Send Accounting-Off packet to the RADIUS server */
2209 e42ea151 Augustin FL
			captiveportal_send_server_accounting('off');
2210 34cb8645 Jean Cyr
		}
2211 49dc4244 plumbeo
		/* Remove the pipe database */
2212
		unlink_if_exists("{$g['vardb_path']}/captiveportaldn.rules");
2213 62f20eab Michael Newton
	}
2214 336e3c1c Charlie
	require_once("voucher.inc");
2215
	voucher_save_db_to_config();
2216 60dd7649 jim-p
	require_once("pkg-utils.inc");
2217
	stop_packages();
2218 5b237745 Scott Ullrich
}
2219
2220
function system_do_shell_commands($early = 0) {
2221 f19d3b7a Scott Ullrich
	global $config, $g;
2222 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
2223 58c7450e Scott Ullrich
		$mt = microtime();
2224 dcf0598e Scott Ullrich
		echo "system_do_shell_commands() being called $mt\n";
2225 58c7450e Scott Ullrich
	}
2226 0f282d7a Scott Ullrich
2227 61e047a5 Phil Davis
	if ($early) {
2228 5b237745 Scott Ullrich
		$cmdn = "earlyshellcmd";
2229 61e047a5 Phil Davis
	} else {
2230 5b237745 Scott Ullrich
		$cmdn = "shellcmd";
2231 61e047a5 Phil Davis
	}
2232 0f282d7a Scott Ullrich
2233 5b237745 Scott Ullrich
	if (is_array($config['system'][$cmdn])) {
2234 333f8ef0 Scott Ullrich
2235 245388b4 Scott Ullrich
		/* *cmd is an array, loop through */
2236 5b237745 Scott Ullrich
		foreach ($config['system'][$cmdn] as $cmd) {
2237
			exec($cmd);
2238
		}
2239 245388b4 Scott Ullrich
2240 61e047a5 Phil Davis
	} elseif ($config['system'][$cmdn] <> "") {
2241 333f8ef0 Scott Ullrich
2242 245388b4 Scott Ullrich
		/* execute single item */
2243
		exec($config['system'][$cmdn]);
2244
2245 5b237745 Scott Ullrich
	}
2246
}
2247
2248
function system_dmesg_save() {
2249 f19d3b7a Scott Ullrich
	global $g;
2250 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
2251 58c7450e Scott Ullrich
		$mt = microtime();
2252 dcf0598e Scott Ullrich
		echo "system_dmesg_save() being called $mt\n";
2253 f19d3b7a Scott Ullrich
	}
2254 0f282d7a Scott Ullrich
2255 767a716e Scott Ullrich
	$dmesg = "";
2256 703b1ce1 Ermal
	$_gb = exec("/sbin/dmesg", $dmesg);
2257 0f282d7a Scott Ullrich
2258 5b237745 Scott Ullrich
	/* find last copyright line (output from previous boots may be present) */
2259
	$lastcpline = 0;
2260 0f282d7a Scott Ullrich
2261 5b237745 Scott Ullrich
	for ($i = 0; $i < count($dmesg); $i++) {
2262 61e047a5 Phil Davis
		if (strstr($dmesg[$i], "Copyright (c) 1992-")) {
2263 5b237745 Scott Ullrich
			$lastcpline = $i;
2264 61e047a5 Phil Davis
		}
2265 5b237745 Scott Ullrich
	}
2266 0f282d7a Scott Ullrich
2267 5b237745 Scott Ullrich
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
2268
	if (!$fd) {
2269 4a896b86 Carlos Eduardo Ramos
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
2270 5b237745 Scott Ullrich
		return 1;
2271
	}
2272 0f282d7a Scott Ullrich
2273 61e047a5 Phil Davis
	for ($i = $lastcpline; $i < count($dmesg); $i++) {
2274 5b237745 Scott Ullrich
		fwrite($fd, $dmesg[$i] . "\n");
2275 61e047a5 Phil Davis
	}
2276 0f282d7a Scott Ullrich
2277 5b237745 Scott Ullrich
	fclose($fd);
2278 703b1ce1 Ermal
	unset($dmesg);
2279 49d9b45f Robbert Rijkse
2280 25ff3fc9 doktornotor
	// vm-bhyve expects dmesg.boot at the standard location
2281 2e6883c5 doktornotor
	@symlink("{$g['varlog_path']}/dmesg.boot", "{$g['varrun_path']}/dmesg.boot");
2282 0f282d7a Scott Ullrich
2283 5b237745 Scott Ullrich
	return 0;
2284
}
2285
2286
function system_set_harddisk_standby() {
2287 f19d3b7a Scott Ullrich
	global $g, $config;
2288 3e4f8fc4 doktornotor
2289 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
2290 58c7450e Scott Ullrich
		$mt = microtime();
2291 dcf0598e Scott Ullrich
		echo "system_set_harddisk_standby() being called $mt\n";
2292 58c7450e Scott Ullrich
	}
2293 5b237745 Scott Ullrich
2294
	if (isset($config['system']['harddiskstandby'])) {
2295 285ef132 Ermal LUÇI
		if (platform_booting()) {
2296 4a896b86 Carlos Eduardo Ramos
			echo gettext('Setting hard disk standby... ');
2297 5b237745 Scott Ullrich
		}
2298
2299
		$standby = $config['system']['harddiskstandby'];
2300
		// Check for a numeric value
2301
		if (is_numeric($standby)) {
2302 0357ecfc doktornotor
			// Get only suitable candidates for standby; using get_smart_drive_list()
2303
			// from utils.inc to get the list of drives.
2304
			$harddisks = get_smart_drive_list();
2305
2306 3e4f8fc4 doktornotor
			// Since get_smart_drive_list() only matches ad|da|ada; lets put the check below
2307
			// just in case of some weird pfSense platform installs.
2308
			if (count($harddisks) > 0) {
2309
				// Iterate disks and run the camcontrol command for each
2310
				foreach ($harddisks as $harddisk) {
2311
					mwexec("/sbin/camcontrol standby {$harddisk} -t {$standby}");
2312
				}
2313 285ef132 Ermal LUÇI
				if (platform_booting()) {
2314 4a896b86 Carlos Eduardo Ramos
					echo gettext("done.") . "\n";
2315 5b237745 Scott Ullrich
				}
2316 285ef132 Ermal LUÇI
			} else if (platform_booting()) {
2317 4a896b86 Carlos Eduardo Ramos
				echo gettext("failed!") . "\n";
2318 5b237745 Scott Ullrich
			}
2319 285ef132 Ermal LUÇI
		} else if (platform_booting()) {
2320 4a896b86 Carlos Eduardo Ramos
			echo gettext("failed!") . "\n";
2321 5b237745 Scott Ullrich
		}
2322
	}
2323
}
2324
2325 3ff9d424 Scott Ullrich
function system_setup_sysctl() {
2326 f19d3b7a Scott Ullrich
	global $config;
2327 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
2328 58c7450e Scott Ullrich
		$mt = microtime();
2329 dcf0598e Scott Ullrich
		echo "system_setup_sysctl() being called $mt\n";
2330 58c7450e Scott Ullrich
	}
2331 243aa7b9 Scott Ullrich
2332 61e047a5 Phil Davis
	activate_sysctls();
2333 6df9d7e3 Scott Ullrich
2334 243aa7b9 Scott Ullrich
	if (isset($config['system']['sharednet'])) {
2335
		system_disable_arp_wrong_if();
2336
	}
2337
}
2338
2339
function system_disable_arp_wrong_if() {
2340 f19d3b7a Scott Ullrich
	global $config;
2341 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
2342 58c7450e Scott Ullrich
		$mt = microtime();
2343 dcf0598e Scott Ullrich
		echo "system_disable_arp_wrong_if() being called $mt\n";
2344 333f8ef0 Scott Ullrich
	}
2345 971de1f9 Renato Botelho
	set_sysctl(array(
2346
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
2347
		"net.link.ether.inet.log_arp_movements" => "0"
2348
	));
2349 3ff9d424 Scott Ullrich
}
2350
2351 243aa7b9 Scott Ullrich
function system_enable_arp_wrong_if() {
2352 f19d3b7a Scott Ullrich
	global $config;
2353 61e047a5 Phil Davis
	if (isset($config['system']['developerspew'])) {
2354 58c7450e Scott Ullrich
		$mt = microtime();
2355 dcf0598e Scott Ullrich
		echo "system_enable_arp_wrong_if() being called $mt\n";
2356 58c7450e Scott Ullrich
	}
2357 971de1f9 Renato Botelho
	set_sysctl(array(
2358
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
2359
		"net.link.ether.inet.log_arp_movements" => "1"
2360
	));
2361 243aa7b9 Scott Ullrich
}
2362
2363 a199b93e Scott Ullrich
function enable_watchdog() {
2364
	global $config;
2365 1a479479 Scott Ullrich
	return;
2366 a199b93e Scott Ullrich
	$install_watchdog = false;
2367
	$supported_watchdogs = array("Geode");
2368
	$file = file_get_contents("/var/log/dmesg.boot");
2369 61e047a5 Phil Davis
	foreach ($supported_watchdogs as $sd) {
2370
		if (stristr($file, "Geode")) {
2371 a199b93e Scott Ullrich
			$install_watchdog = true;
2372
		}
2373
	}
2374 61e047a5 Phil Davis
	if ($install_watchdog == true) {
2375
		if (is_process_running("watchdogd")) {
2376 e0b4e47f Seth Mos
			mwexec("/usr/bin/killall watchdogd", true);
2377 61e047a5 Phil Davis
		}
2378 333f8ef0 Scott Ullrich
		exec("/usr/sbin/watchdogd");
2379 a199b93e Scott Ullrich
	}
2380
}
2381 15f14889 Scott Ullrich
2382
function system_check_reset_button() {
2383 fa83737d Scott Ullrich
	global $g;
2384 15f14889 Scott Ullrich
2385 31c9379c Scott Ullrich
	$specplatform = system_identify_specific_platform();
2386
2387 365fc95d Renato Botelho
	switch ($specplatform['name']) {
2388 d940d2b2 Renato Botelho
		case 'SG-2220':
2389
			$binprefix = "RCC-DFF";
2390
			break;
2391 61e047a5 Phil Davis
		case 'alix':
2392
		case 'wrap':
2393
		case 'FW7541':
2394
		case 'APU':
2395 80e47bb0 Chris Buechler
		case 'RCC-VE':
2396 bf648a15 Chris Buechler
		case 'RCC':
2397 d940d2b2 Renato Botelho
			$binprefix = $specplatform['name'];
2398 61e047a5 Phil Davis
			break;
2399
		default:
2400
			return 0;
2401 365fc95d Renato Botelho
	}
2402 15f14889 Scott Ullrich
2403 d940d2b2 Renato Botelho
	$retval = mwexec("/usr/local/sbin/" . $binprefix . "resetbtn");
2404 15f14889 Scott Ullrich
2405
	if ($retval == 99) {
2406 61e047a5 Phil Davis
		/* user has pressed reset button for 2 seconds -
2407 15f14889 Scott Ullrich
		   reset to factory defaults */
2408
		echo <<<EOD
2409
2410
***********************************************************************
2411
* Reset button pressed - resetting configuration to factory defaults. *
2412 7222324e Renato Botelho
* All additional packages installed will be removed                   *
2413 15f14889 Scott Ullrich
* The system will reboot after this completes.                        *
2414
***********************************************************************
2415
2416
2417
EOD;
2418 61e047a5 Phil Davis
2419 15f14889 Scott Ullrich
		reset_factory_defaults();
2420
		system_reboot_sync();
2421
		exit(0);
2422
	}
2423
2424
	return 0;
2425
}
2426
2427 884914ce Renato Botelho
function system_get_serial() {
2428 7b084fd3 Renato Botelho
	$platform = system_identify_specific_platform();
2429
2430 884914ce Renato Botelho
	unset($output);
2431 7b084fd3 Renato Botelho
	if ($platform['name'] == 'Turbot Dual-E') {
2432
		$if_info = pfSense_get_interface_addresses('igb0');
2433
		if (!empty($if_info['hwaddr'])) {
2434
			$serial = str_replace(":", "", $if_info['hwaddr']);
2435
		}
2436
	} else {
2437 323f378b Renato Botelho
		foreach (array('system', 'planar', 'chassis') as $key) {
2438
			unset($output);
2439
			$_gb = exec("/bin/kenv -q smbios.{$key}.serial",
2440
			    $output);
2441 b088052a Renato Botelho
			if (!empty($output[0]) && $output[0] != "0123456789" &&
2442
			    preg_match('/^[\w\d]{10,16}$/', $output[0]) === 1) {
2443 323f378b Renato Botelho
				$serial = $output[0];
2444
				break;
2445
			}
2446
		}
2447 7b084fd3 Renato Botelho
	}
2448 884914ce Renato Botelho
2449
	$vm_guest = get_single_sysctl('kern.vm_guest');
2450
2451
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2452
	    $vm_guest == 'none') {
2453
		return $serial;
2454
	}
2455
2456 4368d367 Renato Botelho
	return "";
2457 884914ce Renato Botelho
}
2458
2459 2f8793b7 Renato Botelho
function system_get_uniqueid() {
2460
	global $g;
2461
2462
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2463
2464
	if (empty($g['uniqueid'])) {
2465
		if (!file_exists($uniqueid_file)) {
2466
			mwexec("/usr/sbin/gnid > {$g['vardb_path']}/uniqueid " .
2467
			    "2>/dev/null");
2468
		}
2469
		if (file_exists($uniqueid_file)) {
2470
			$g['uniqueid'] = @file_get_contents($uniqueid_file);
2471
		}
2472
	}
2473
2474
	return ($g['uniqueid'] ?: '');
2475
}
2476
2477 d1f9426a Renato Botelho
/*
2478
 * attempt to identify the specific platform (for embedded systems)
2479
 * Returns an array with two elements:
2480
 * name => platform string (e.g. 'wrap', 'alix' etc.)
2481
 * descr => human-readable description (e.g. "PC Engines WRAP")
2482
 */
2483 31c9379c Scott Ullrich
function system_identify_specific_platform() {
2484
	global $g;
2485 61e047a5 Phil Davis
2486 042326a3 Renato Botelho
	$hw_model = get_single_sysctl('hw.model');
2487 8b3345dc Renato Botelho
	$hw_ncpu = get_single_sysctl('hw.ncpu');
2488 042326a3 Renato Botelho
2489 5a8519bb Chris Buechler
	/* Try to guess from smbios strings */
2490 b4594d39 Chris Buechler
	unset($product);
2491
	unset($maker);
2492 f3df1d3e Steve Beaver
	unset($bios);
2493 411f439a Renato Botelho
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $product);
2494
	$_gb = exec('/bin/kenv -q smbios.system.maker 2>/dev/null', $maker);
2495 f3df1d3e Steve Beaver
	$_gb = exec('/bin/kenv -q smbios.bios.version 2>/dev/null', $bios);
2496
2497
	// AWS can only be identified via the bios version
2498
	if (stripos($bios[0], "amazon") !== false) {
2499
		return (array('name' => 'AWS', 'descr' => 'Amazon Web Services'));
2500
	} else  if (stripos($bios[0], "Google") !== false) {
2501 8a162959 Steve Beaver
		return (array('name' => 'Google', 'descr' => 'Google Cloud Platform'));
2502 f3df1d3e Steve Beaver
	}
2503
2504 b4594d39 Chris Buechler
	switch ($product[0]) {
2505 61e047a5 Phil Davis
		case 'FW7541':
2506
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2507
			break;
2508
		case 'APU':
2509
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2510
			break;
2511
		case 'RCC-VE':
2512 042326a3 Renato Botelho
			$result = array();
2513
			$result['name'] = 'RCC-VE';
2514
2515
			/* Detect specific models */
2516
			if (!function_exists('does_interface_exist')) {
2517
				require_once("interfaces.inc");
2518
			}
2519
			if (!does_interface_exist('igb4')) {
2520
				$result['model'] = 'SG-2440';
2521
			} elseif (strpos($hw_model, "C2558") !== false) {
2522
				$result['model'] = 'SG-4860';
2523
			} elseif (strpos($hw_model, "C2758") !== false) {
2524
				$result['model'] = 'SG-8860';
2525
			} else {
2526
				$result['model'] = 'RCC-VE';
2527
			}
2528
			$result['descr'] = 'Netgate ' . $result['model'];
2529
			return $result;
2530 61e047a5 Phil Davis
			break;
2531 ba8c6e37 Renato Botelho
		case 'DFFv2':
2532 0a031fc7 Renato Botelho
			return (array('name' => 'SG-2220', 'descr' => 'Netgate SG-2220'));
2533 ba8c6e37 Renato Botelho
			break;
2534 bf648a15 Chris Buechler
		case 'RCC':
2535 2ae79c20 Chris Buechler
			return (array('name' => 'RCC', 'descr' => 'Netgate XG-2758'));
2536 bf648a15 Chris Buechler
			break;
2537 40318232 jim-p
		case 'SG-5100':
2538
			return (array('name' => 'SG-5100', 'descr' => 'Netgate SG-5100'));
2539
			break;
2540 8b3345dc Renato Botelho
		case 'Minnowboard Turbot D0 PLATFORM':
2541 f4479f0d Renato Botelho do Couto
		case 'Minnowboard Turbot D0/D1 PLATFORM':
2542 8b3345dc Renato Botelho
			$result = array();
2543
			$result['name'] = 'Turbot Dual-E';
2544
			/* Detect specific model */
2545
			switch ($hw_ncpu) {
2546
			case '4':
2547 45fbd1bd Renato Botelho
				$result['model'] = 'MBT-4220';
2548 8b3345dc Renato Botelho
				break;
2549
			case '2':
2550 45fbd1bd Renato Botelho
				$result['model'] = 'MBT-2220';
2551 8b3345dc Renato Botelho
				break;
2552
			default:
2553
				$result['model'] = $result['name'];
2554
				break;
2555
			}
2556
			$result['descr'] = 'Netgate ' . $result['model'];
2557
			return $result;
2558
			break;
2559 be2191af Jeremy Porter
		case 'SYS-5018A-FTN4':
2560 bc09b90a Renato Botelho
		case 'A1SAi':
2561 4de6f04d Renato Botelho do Couto
			if (strpos($hw_model, "C2558") !== false) {
2562
				return (array(
2563
				    'name' => 'C2558',
2564
				    'descr' => 'Super Micro C2558'));
2565
			} elseif (strpos($hw_model, "C2758") !== false) {
2566
				return (array(
2567
				    'name' => 'C2758',
2568
				    'descr' => 'Super Micro C2758'));
2569
			}
2570 bc09b90a Renato Botelho
			break;
2571 47b09af7 Matt Smith
		case 'SYS-5018D-FN4T':
2572 40318232 jim-p
			if (strpos($hw_model, "D-1541") !== false) {
2573
				return (array('name' => 'XG-1541', 'descr' => 'Super Micro XG-1541'));
2574
			} else {
2575
				return (array('name' => 'XG-1540', 'descr' => 'Super Micro XG-1540'));
2576
			}
2577 47b09af7 Matt Smith
			break;
2578 ffda0181 Brett Keller
		case 'apu2':
2579 9457d0f6 doktornotor
		case 'APU2':
2580 ffda0181 Brett Keller
			return (array('name' => 'apu2', 'descr' => 'PC Engines APU2'));
2581
			break;
2582 d4d86e3e PiBa-NL
		case 'VirtualBox':
2583
			return (array('name' => 'VirtualBox', 'descr' => 'VirtualBox Virtual Machine'));
2584
			break;
2585 b4594d39 Chris Buechler
		case 'Virtual Machine':
2586
			if ($maker[0] == "Microsoft Corporation") {
2587 1279a7ac Steve Beaver
				if (stripos($bios[0], "Hyper") !== false) {
2588
					return (array('name' => 'Hyper-V', 'descr' => 'Hyper-V Virtual Machine'));
2589
				} else {
2590
					return (array('name' => 'Azure', 'descr' => 'Microsoft Azure'));
2591
				}
2592 b4594d39 Chris Buechler
			}
2593
			break;
2594 9a548240 jim-p
		case 'VMware Virtual Platform':
2595
			if ($maker[0] == "VMware, Inc.") {
2596
				return (array('name' => 'VMware', 'descr' => 'VMware Virtual Machine'));
2597
			}
2598
			break;
2599 5a8519bb Chris Buechler
	}
2600
2601 e4f613db Renato Botelho
	$_gb = exec('/bin/kenv -q smbios.planar.product 2>/dev/null',
2602
	    $planar_product);
2603
	if (isset($planar_product[0]) &&
2604
	    $planar_product[0] == 'X10SDV-8C-TLN4F+') {
2605
		return array('name' => 'XG-1537', 'descr' => 'Super Micro XG-1537');
2606
	}
2607
2608 24d4fdde Renato Botelho
	if (strpos($hw_model, "PC Engines WRAP") !== false) {
2609 4a896b86 Carlos Eduardo Ramos
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
2610 61e047a5 Phil Davis
	}
2611
2612 24d4fdde Renato Botelho
	if (strpos($hw_model, "PC Engines ALIX") !== false) {
2613 4a896b86 Carlos Eduardo Ramos
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2614 61e047a5 Phil Davis
	}
2615 31c9379c Scott Ullrich
2616 24d4fdde Renato Botelho
	if (preg_match("/Soekris net45../", $hw_model, $matches)) {
2617 31c9379c Scott Ullrich
		return array('name' => 'net45xx', 'descr' => $matches[0]);
2618 61e047a5 Phil Davis
	}
2619
2620 24d4fdde Renato Botelho
	if (preg_match("/Soekris net48../", $hw_model, $matches)) {
2621 31c9379c Scott Ullrich
		return array('name' => 'net48xx', 'descr' => $matches[0]);
2622 61e047a5 Phil Davis
	}
2623
2624 24d4fdde Renato Botelho
	if (preg_match("/Soekris net55../", $hw_model, $matches)) {
2625 31c9379c Scott Ullrich
		return array('name' => 'net55xx', 'descr' => $matches[0]);
2626 61e047a5 Phil Davis
	}
2627 1f97f379 Renato Botelho
2628 24d4fdde Renato Botelho
	unset($hw_model);
2629 1f97f379 Renato Botelho
2630
	$dmesg_boot = system_get_dmesg_boot();
2631 61e047a5 Phil Davis
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
2632 1f97f379 Renato Botelho
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2633 61e047a5 Phil Davis
	}
2634 1f97f379 Renato Botelho
	unset($dmesg_boot);
2635
2636 573ec19d Renato Botelho do Couto
	return array('name' => $g['product_name'], 'descr' => $g['product_label']);
2637 31c9379c Scott Ullrich
}
2638
2639
function system_get_dmesg_boot() {
2640
	global $g;
2641 61e047a5 Phil Davis
2642 31c9379c Scott Ullrich
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2643
}
2644
2645 16ee6ca2 Renato Botelho
function system_get_arp_table($resolve_hostnames = false) {
2646
	$params="-a";
2647
	if (!$resolve_hostnames) {
2648
		$params .= "n";
2649
	}
2650
2651
	$arp_table = array();
2652
	$_gb = exec("/usr/sbin/arp --libxo json {$params}", $rawdata, $rc);
2653
	if ($rc == 0) {
2654
		$arp_table = json_decode(implode(" ", $rawdata),
2655
		    JSON_OBJECT_AS_ARRAY);
2656
		if ($rc == 0) {
2657
			$arp_table = $arp_table['arp']['arp-cache'];
2658
		}
2659
	}
2660
2661
	return $arp_table;
2662
}
2663
2664 bc09b90a Renato Botelho
?>