Project

General

Profile

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