Project

General

Profile

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