Project

General

Profile

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