Project

General

Profile

Download (87.5 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * system.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2004-2013 BSD Perimeter
7
 * Copyright (c) 2013-2016 Electric Sheep Fencing
8
 * Copyright (c) 2014-2023 Rubicon Communications, LLC (Netgate)
9
 * All rights reserved.
10
 *
11
 * originally part of m0n0wall (http://m0n0.ch/wall)
12
 * Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>.
13
 * All rights reserved.
14
 *
15
 * 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
 *
19
 * http://www.apache.org/licenses/LICENSE-2.0
20
 *
21
 * 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
 */
27

    
28
require_once('config.lib.inc');
29
require_once('syslog.inc');
30

    
31
function system_hwpstate_active() {
32
	return (get_single_sysctl('dev.cpufreq.0.freq_driver') == 'hwpstate_intel0');
33
}
34

    
35
function system_hwpstate_disabled() {
36
	/* Is hwpstate disabled? */
37
	$hwpstate_disabled_kenv = [];
38
	exec('/bin/kenv -q hint.hwpstate_intel.0.disabled 2>/dev/null', $hwpstate_disabled_kenv);
39
	if (empty($hwpstate_disabled_kenv) || !is_array($hwpstate_disabled_kenv)) {
40
		/* Invalid result, so assume not explicitly disabled */
41
		$hwpstate_disabled = false;
42
	} else {
43
		/* Compare value of kenv variable to 1 (disabled) */
44
		$hwpstate_disabled = (array_shift($hwpstate_disabled_kenv) == '1');
45
	}
46
	return $hwpstate_disabled;
47
}
48

    
49
/*
50
 * Attempt to determine if this system supports hwpstate power control.
51
 * Three possible outcomes: No support, Disabled, Active
52
 */
53
function system_has_hwpstate() {
54
	if (system_hwpstate_active()) {
55
		/* Active, so system has hwpstate support */
56
		return true;
57
	} elseif (system_hwpstate_disabled()) {
58
		/* Disabled via loader tunable so there is no way to know if
59
		 * it is disabled or lacking support, so assume disabled. */
60
		return -1;
61
	} else {
62
		/* Not active nor disabled, so no hardware support */
63
		return false;
64
	}
65
}
66

    
67
function system_hwpstate_setepp() {
68
	$epp = config_get_path('system/hwpstate_epp', -1);
69
	$cpu_count = get_single_sysctl('hw.ncpu');
70
	if (($epp >= 0) && ($epp <= 100)) {
71
		for ($cpu=0; $cpu < $cpu_count; $cpu++) {
72
			set_single_sysctl("dev.hwpstate_intel.{$cpu}.epp", $epp);
73
		}
74
	}
75
}
76

    
77
function activate_powerd() {
78
	if (is_process_running("powerd")) {
79
		exec("/usr/bin/killall powerd");
80
	}
81
	if (config_path_enabled('system', 'powerd_enable')) {
82
		$ac_mode = "hadp";
83
		if (!empty(config_get_path('system/powerd_ac_mode'))) {
84
			$ac_mode = config_get_path('system/powerd_ac_mode');
85
		}
86

    
87
		$battery_mode = "hadp";
88
		if (!empty(config_get_path('system/powerd_battery_mode'))) {
89
			$battery_mode = config_get_path('system/powerd_battery_mode');
90
		}
91

    
92
		$normal_mode = "hadp";
93
		if (!empty(config_get_path('system/powerd_normal_mode'))) {
94
			$normal_mode = config_get_path('system/powerd_normal_mode');
95
		}
96

    
97
		mwexec("/usr/sbin/powerd" .
98
			" -b " . escapeshellarg($battery_mode) .
99
			" -a " . escapeshellarg($ac_mode) .
100
			" -n " . escapeshellarg($normal_mode));
101
	}
102
}
103

    
104
function get_default_sysctl_value($id) {
105
	global $sysctls;
106

    
107
	if (isset($sysctls[$id])) {
108
		return $sysctls[$id];
109
	}
110
}
111

    
112
function get_sysctl_descr($sysctl) {
113
	unset($output);
114
	$_gb = exec("/sbin/sysctl -qnd {$sysctl}", $output);
115

    
116
	return $output[0];
117
}
118

    
119
function system_get_sysctls() {
120
	global $sysctls;
121

    
122
	$disp_sysctl = array();
123
	$disp_cache = array();
124
	foreach (config_get_path('sysctl/item', []) as $id => $tunable) {
125
		if ($tunable['value'] == "default") {
126
			$value = get_default_sysctl_value($tunable['tunable']);
127
		} else {
128
			$value = $tunable['value'];
129
		}
130

    
131
		$disp_sysctl[$id] = $tunable;
132
		$disp_sysctl[$id]['modified'] = true;
133
		$disp_cache[$tunable['tunable']] = 'set';
134
	}
135

    
136
	foreach ($sysctls as $sysctl => $value) {
137
		if (isset($disp_cache[$sysctl])) {
138
			continue;
139
		}
140

    
141
		$disp_sysctl[$sysctl] = array('tunable' => $sysctl, 'value' => $value, 'descr' => get_sysctl_descr($sysctl));
142
	}
143
	unset($disp_cache);
144
	return $disp_sysctl;
145
}
146

    
147
function activate_sysctls() {
148
	global $sysctls, $ipsec_filter_sysctl;
149

    
150
	if (!is_array($sysctls)) {
151
		$sysctls = array();
152
	}
153

    
154
	/* Speed Shift */
155
	$epp = config_get_path('system/hwpstate_epp', -1);
156
	$cpu_count = get_single_sysctl('hw.ncpu');
157
	if (($epp >= 0) && ($epp <= 100)) {
158
		for ($cpu=0; $cpu < $cpu_count; $cpu++) {
159
			$sysctls["dev.hwpstate_intel.{$cpu}.epp"] = $epp;
160
		}
161
	}
162

    
163
	$ipsec_filtermode = config_get_path('ipsec/filtermode', 'enc');
164
	$sysctls = array_merge($sysctls, $ipsec_filter_sysctl[$ipsec_filtermode]);
165

    
166
	/*
167
	 * See https://redmine.pfsense.org/issues/13938
168
	 *
169
	 * We need to disable unmapped mbufs to work around a bug
170
	 * that can cause sendfile to crash.
171
	 */
172
	$sysctls['kern.ipc.mb_use_ext_pgs'] = '0';
173

    
174
	if (config_get_path('system/consolebell', 'enabled') == 'enabled') {
175
		$sysctls['kern.vt.enable_bell'] = '1';
176
	} else {
177
		$sysctls['kern.vt.enable_bell'] = '0';
178
	}
179

    
180
	foreach (config_get_path('sysctl/item', []) as $tunable) {
181
		if ($tunable['value'] == "default") {
182
			$value = get_default_sysctl_value($tunable['tunable']);
183
		} else {
184
			$value = $tunable['value'];
185
		}
186

    
187
		$sysctls[$tunable['tunable']] = $value;
188
	}
189

    
190
	/* Set net.pf.request_maxcount via sysctl since it is no longer a loader
191
	 *   tunable. See https://redmine.pfsense.org/issues/10861
192
	 *   Set the value dynamically since its default is not static, yet this
193
	 *   still could be overridden by a user tunable. */
194
	$maximumtableentries = config_get_path('system/maximumtableentries',
195
										   pfsense_current_table_entries_size());
196

    
197
	/* Set the default when there is no tunable or when the tunable is set
198
	 * too low. */
199
	if (empty($sysctls['net.pf.request_maxcount']) ||
200
	    ($sysctls['net.pf.request_maxcount'] < $maximumtableentries)) {
201
		$sysctls['net.pf.request_maxcount'] = $maximumtableentries;
202
	}
203

    
204
	set_sysctl($sysctls);
205
}
206

    
207
function system_resolvconf_generate($dynupdate = false) {
208
	global $g;
209

    
210
	if (config_path_enabled('system', 'developerspew')) {
211
		$mt = microtime();
212
		echo "system_resolvconf_generate() being called $mt\n";
213
	}
214

    
215
	$syscfg = config_get_path('system', []);
216

    
217
	foreach(get_dns_nameservers(false, false) as $dns_ns) {
218
		$resolvconf .= "nameserver $dns_ns\n";
219
	}
220

    
221
	$ns = array();
222
	if (isset($syscfg['dnsallowoverride'])) {
223
		/* get dynamically assigned DNS servers (if any) */
224
		$ns = array_unique(get_searchdomains());
225
		foreach ($ns as $searchserver) {
226
			if ($searchserver) {
227
				$resolvconf .= "search {$searchserver}\n";
228
			}
229
		}
230
	}
231
	if (empty($ns)) {
232
		// Do not create blank search/domain lines, it can break tools like dig.
233
		if ($syscfg['domain']) {
234
			$resolvconf .= "search {$syscfg['domain']}\n";
235
		}
236
	}
237

    
238
	// Add EDNS support
239
	if (config_path_enabled('unbound') && (config_get_path('unbound/edns') != null)) {
240
		$resolvconf .= "options edns0\n";
241
	}
242

    
243
	$dnslock = lock('resolvconf', LOCK_EX);
244

    
245
	$fd = fopen("{$g['etc_path']}/resolv.conf", "w");
246
	if (!$fd) {
247
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
248
		unlock($dnslock);
249
		return 1;
250
	}
251

    
252
	fwrite($fd, $resolvconf);
253
	fclose($fd);
254

    
255
	// Prevent resolvconf(8) from rewriting our resolv.conf
256
	$fd = fopen("{$g['etc_path']}/resolvconf.conf", "w");
257
	if (!$fd) {
258
		printf("Error: cannot open resolvconf.conf in system_resolvconf_generate().\n");
259
		return 1;
260
	}
261
	fwrite($fd, "resolv_conf=\"/dev/null\"\n");
262
	fclose($fd);
263

    
264
	if (!platform_booting()) {
265
		/* restart dhcpd (nameservers may have changed) */
266
		if (!$dynupdate) {
267
			services_dhcpd_configure();
268
		}
269
	}
270

    
271
	// set up or tear down static routes for DNS servers
272
	$dnscounter = 1;
273
	$dnsgw = "dns{$dnscounter}gw";
274
	$exempt_addresses = array_unique(array_merge(get_interface_addresses_all('lo0'),
275
	    get_configured_ip_addresses(), get_configured_ipv6_addresses()));
276
	while (!empty(config_get_path("system/{$dnsgw}"))) {
277
		/* setup static routes for dns servers */
278
		$gwname = config_get_path("system/{$dnsgw}");		unset($gatewayip);
279
		unset($inet6);
280
		if ((!empty($gwname)) && ($gwname != "none")) {
281
			$gatewayip = lookup_gateway_ip_by_name($gwname);
282
			$inet6 = is_ipaddrv6($gatewayip) ? '-inet6 ' : '';
283
		}
284
		/* dns server array starts at 0 */
285
		$dnsserver = $syscfg['dnsserver'][$dnscounter - 1];
286

    
287
		/* Only modify routes for non-interface addresses;
288
		 * see https://redmine.pfsense.org/issues/14288 */
289
		if (!empty($dnsserver) && !in_array($dnsserver, $exempt_addresses)) {
290
			// specify IP protocol version for correct add/del
291
			if (is_ipaddrv4($dnsserver)) {
292
				$ipprotocol = 'inet';
293
			} else {
294
				$ipprotocol = 'inet6';
295
			}
296

    
297
			if (is_ipaddr($gatewayip)) {
298
				route_add_or_change($dnsserver, $gatewayip, '', '', $ipprotocol);
299
			} else {
300
				/* Remove old route when disable gw */
301
				route_del($dnsserver, $ipprotocol);
302
			}
303
		}
304
		$dnscounter++;
305
		$dnsgw = "dns{$dnscounter}gw";
306
	}
307

    
308
	unlock($dnslock);
309

    
310
	return 0;
311
}
312

    
313
function get_searchdomains() {
314
	$master_list = array();
315

    
316
	// Read in dhclient nameservers
317
	$search_list = glob("/var/etc/searchdomain_*");
318
	if (is_array($search_list)) {
319
		foreach ($search_list as $fdns) {
320
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
321
			if (!is_array($contents)) {
322
				continue;
323
			}
324
			foreach ($contents as $dns) {
325
				if (is_hostname($dns)) {
326
					$master_list[] = $dns;
327
				}
328
			}
329
		}
330
	}
331

    
332
	return $master_list;
333
}
334

    
335
/* Stub for deprecated function name
336
 * See https://redmine.pfsense.org/issues/10931 */
337
function get_nameservers() {
338
	return get_dynamic_nameservers();
339
}
340

    
341
/****f* system.inc/get_dynamic_nameservers
342
 * NAME
343
 *   get_dynamic_nameservers - Get DNS servers from dynamic sources (DHCP, PPP, etc)
344
 * INPUTS
345
 *   $iface: Interface name used to filter results.
346
 * RESULT
347
 *   $master_list - Array containing DNS servers
348
 ******/
349
function get_dynamic_nameservers($iface = '') {
350
	$master_list = array();
351

    
352
	if (!empty($iface)) {
353
		$realif = get_real_interface($iface);
354
	}
355

    
356
	// Read in dynamic nameservers
357
	$dns_lists = array_merge(glob("/var/etc/nameserver_{$realif}*"), glob("/var/etc/nameserver_v6{$iface}*"));
358
	if (is_array($dns_lists)) {
359
		foreach ($dns_lists as $fdns) {
360
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
361
			if (!is_array($contents)) {
362
				continue;
363
			}
364
			foreach ($contents as $dns) {
365
				if (is_ipaddr($dns)) {
366
					$master_list[] = $dns;
367
				}
368
			}
369
		}
370
	}
371

    
372
	return $master_list;
373
}
374

    
375
/* Create localhost + local interfaces entries for /etc/hosts */
376
function system_hosts_local_entries() {
377
	$syscfg = config_get_path('system', []);
378

    
379
	$hosts = array();
380
	$hosts[] = array(
381
	    'ipaddr' => '127.0.0.1',
382
	    'fqdn' => 'localhost.' . $syscfg['domain'],
383
	    'name' => 'localhost',
384
	    'domain' => $syscfg['domain']
385
	);
386
	$hosts[] = array(
387
	    'ipaddr' => '::1',
388
	    'fqdn' => 'localhost.' . $syscfg['domain'],
389
	    'name' => 'localhost',
390
	    'domain' => $syscfg['domain']
391
	);
392

    
393
	if (config_get_path('interfaces/lan')) {
394
		$sysiflist = array('lan' => "lan");
395
	} else {
396
		$sysiflist = get_configured_interface_list();
397
	}
398

    
399
	$hosts_if_found = false;
400
	$local_fqdn = "{$syscfg['hostname']}.{$syscfg['domain']}";
401
	foreach ($sysiflist as $sysif) {
402
		if ($sysif != 'lan' && interface_has_gateway($sysif)) {
403
			continue;
404
		}
405
		$cfgip = get_interface_ip($sysif);
406
		if (is_ipaddrv4($cfgip)) {
407
			$hosts[] = array(
408
			    'ipaddr' => $cfgip,
409
			    'fqdn' => $local_fqdn,
410
			    'name' => $syscfg['hostname'],
411
			    'domain' => $syscfg['domain']
412
			);
413
			$hosts_if_found = true;
414
		}
415
		if (!isset($syscfg['ipv6dontcreatelocaldns'])) {
416
			$cfgipv6 = get_interface_ipv6($sysif);
417
			if (is_ipaddrv6($cfgipv6)) {
418
				$hosts[] = array(
419
					'ipaddr' => $cfgipv6,
420
					'fqdn' => $local_fqdn,
421
					'name' => $syscfg['hostname'],
422
					'domain' => $syscfg['domain']
423
				);
424
				$hosts_if_found = true;
425
			}
426
		}
427
		if ($hosts_if_found == true) {
428
			break;
429
		}
430
	}
431

    
432
	return $hosts;
433
}
434

    
435
/* Read host override entries from dnsmasq or unbound */
436
function system_hosts_override_entries($dnscfg) {
437
	$hosts = array();
438

    
439
	if (!is_array($dnscfg) ||
440
	    !is_array($dnscfg['hosts']) ||
441
	    !isset($dnscfg['enable'])) {
442
		return $hosts;
443
	}
444

    
445
	foreach ($dnscfg['hosts'] as $host) {
446
		$fqdn = '';
447
		if ($host['host'] || $host['host'] == "0") {
448
			$fqdn .= "{$host['host']}.";
449
		}
450
		$fqdn .= $host['domain'];
451

    
452
		foreach (explode(',', $host['ip']) as $ip) {
453
			$hosts[] = array(
454
			    'ipaddr' => $ip,
455
			    'fqdn' => $fqdn,
456
			    'name' => $host['host'],
457
			    'domain' => $host['domain']
458
			);
459
		}
460

    
461
		if (!is_array($host['aliases']) ||
462
		    !is_array($host['aliases']['item'])) {
463
			continue;
464
		}
465

    
466
		foreach ($host['aliases']['item'] as $alias) {
467
			$fqdn = '';
468
			if ($alias['host'] || $alias['host'] == "0") {
469
				$fqdn .= "{$alias['host']}.";
470
			}
471
			$fqdn .= $alias['domain'];
472

    
473
			foreach (explode(',', $host['ip']) as $ip) {
474
				$hosts[] = array(
475
				    'ipaddr' => $ip,
476
				    'fqdn' => $fqdn,
477
				    'name' => $alias['host'],
478
				    'domain' => $alias['domain']
479
				);
480
			}
481
		}
482
	}
483

    
484
	return $hosts;
485
}
486

    
487
/* Read all dhcpd/dhcpdv6 staticmap entries */
488
function system_hosts_dhcpd_entries() {
489
	$hosts = array();
490
	$syscfg = config_get_path('system');
491

    
492
	$conf_dhcpd = config_get_path('dhcpd', []);
493

    
494
	foreach ($conf_dhcpd as $dhcpif => $dhcpifconf) {
495
		if (empty($dhcpifconf)) {
496
			continue;
497
		}
498
		if (!is_array($dhcpifconf['staticmap']) ||
499
		    !isset($dhcpifconf['enable'])) {
500
			continue;
501
		}
502
		foreach ($dhcpifconf['staticmap'] as $host) {
503
			if (!$host['ipaddr'] ||
504
			    !$host['hostname']) {
505
				continue;
506
			}
507

    
508
			$fqdn = $host['hostname'] . ".";
509
			$domain = "";
510
			if ($host['domain']) {
511
				$domain = $host['domain'];
512
			} elseif ($dhcpifconf['domain']) {
513
				$domain = $dhcpifconf['domain'];
514
			} else {
515
				$domain = $syscfg['domain'];
516
			}
517

    
518
			$hosts[] = array(
519
			    'ipaddr' => $host['ipaddr'],
520
			    'fqdn' => $fqdn . $domain,
521
			    'name' => $host['hostname'],
522
			    'domain' => $domain
523
			);
524
		}
525
	}
526
	unset($conf_dhcpd);
527

    
528
	$conf_dhcpdv6 = config_get_path('dhcpdv6', []);
529

    
530
	foreach ($conf_dhcpdv6 as $dhcpif => $dhcpifconf) {
531
		if (empty($dhcpifconf)) {
532
			continue;
533
		}
534
		if (!is_array($dhcpifconf['staticmap']) ||
535
		    !isset($dhcpifconf['enable'])) {
536
			continue;
537
		}
538

    
539
		if (config_get_path("interfaces/{$dhcpif}/ipaddrv6") ==
540
		    'track6') {
541
			$isdelegated = true;
542
		} else {
543
			$isdelegated = false;
544
		}
545

    
546
		foreach ($dhcpifconf['staticmap'] as $host) {
547
			$ipaddrv6 = $host['ipaddrv6'];
548

    
549
			if (!$ipaddrv6 || !$host['hostname']) {
550
				continue;
551
			}
552

    
553
			if ($isdelegated) {
554
				/*
555
				 * We are always in an "end-user" subnet
556
				 * here, which all are /64 for IPv6.
557
				 */
558
				$prefix6 = 64;
559
			} else {
560
				$prefix6 = get_interface_subnetv6($dhcpif);
561
			}
562
			$ipaddrv6 = merge_ipv6_delegated_prefix(get_interface_ipv6($dhcpif), $ipaddrv6, $prefix6);
563

    
564
			$fqdn = $host['hostname'] . ".";
565
			$domain = "";
566
			if ($host['domain']) {
567
				$domain = $host['domain'];
568
			} elseif ($dhcpifconf['domain']) {
569
				$domain = $dhcpifconf['domain'];
570
			} else {
571
				$domain = $syscfg['domain'];
572
			}
573

    
574
			$hosts[] = array(
575
			    'ipaddr' => $ipaddrv6,
576
			    'fqdn' => $fqdn . $domain,
577
			    'name' => $host['hostname'],
578
			    'domain' => $domain
579
			);
580
		}
581
	}
582
	unset($conf_dhcpdv6);
583

    
584
	return $hosts;
585
}
586

    
587
/* Concatenate local, dnsmasq/unbound and dhcpd/dhcpdv6 hosts entries */
588
function system_hosts_entries($dnscfg) {
589
	$local = array();
590
	if (!isset($dnscfg['disable_auto_added_host_entries'])) {
591
		$local = system_hosts_local_entries();
592
	}
593

    
594
	$dns = array();
595
	$dhcpd = array();
596
	if (isset($dnscfg['enable'])) {
597
		$dns = system_hosts_override_entries($dnscfg);
598
		if (isset($dnscfg['regdhcpstatic'])) {
599
			$dhcpd = system_hosts_dhcpd_entries();
600
		}
601
	}
602

    
603
	if (isset($dnscfg['dhcpfirst'])) {
604
		return array_merge($local, $dns, $dhcpd);
605
	} else {
606
		return array_merge($local, $dhcpd, $dns);
607
	}
608
}
609

    
610
function system_hosts_generate() {
611
	global $g;
612
	if (config_path_enabled('system', 'developerspew')) {
613
		$mt = microtime();
614
		echo "system_hosts_generate() being called $mt\n";
615
	}
616

    
617
	// prefer dnsmasq for hosts generation where it's enabled. It relies
618
	// on hosts for name resolution of its overrides, unbound does not.
619
	if (config_path_enabled('dnsmasq')) {
620
		$dnsmasqcfg = config_get_path('dnsmasq');
621
	} else {
622
		$dnsmasqcfg = config_get_path('unbound');
623
	}
624

    
625
	$syscfg = config_get_path('system');
626
	$hosts = "";
627
	$lhosts = "";
628
	$dhosts = "";
629

    
630
	$hosts_array = system_hosts_entries($dnsmasqcfg);
631
	foreach ($hosts_array as $host) {
632
		$hosts .= "{$host['ipaddr']}\t";
633
		if ($host['name'] == "localhost") {
634
			$hosts .= "{$host['name']} {$host['fqdn']}";
635
		} else {
636
			$hosts .= "{$host['fqdn']} {$host['name']}";
637
		}
638
		$hosts .= "\n";
639
	}
640
	unset($hosts_array);
641

    
642
	/*
643
	 * Do not remove this because dhcpleases monitors with kqueue it needs
644
	 * to be killed before writing to hosts files.
645
	 */
646
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
647
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
648
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
649
	}
650

    
651
	$fd = fopen("{$g['etc_path']}/hosts", "w");
652
	if (!$fd) {
653
		log_error(gettext(
654
		    "Error: cannot open hosts file in system_hosts_generate()."
655
		    ));
656
		return 1;
657
	}
658

    
659
	fwrite($fd, $hosts);
660
	fclose($fd);
661

    
662
	if (config_path_enabled('unbound')) {
663
		require_once("unbound.inc");
664
		unbound_hosts_generate();
665
	}
666

    
667
	/* restart dhcpleases */
668
	if (!platform_booting()) {
669
		system_dhcpleases_configure();
670
	}
671

    
672
	return 0;
673
}
674

    
675
function system_dhcpleases_configure() {
676
	global $g;
677
	if (!function_exists('is_dhcp_server_enabled')) {
678
		require_once('pfsense-utils.inc');
679
	}
680
	$pidfile = "{$g['varrun_path']}/dhcpleases.pid";
681

    
682
	/* Start the monitoring process for dynamic dhcpclients. */
683
	if (((config_path_enabled('dnsmasq') && (config_get_path('dnsmasq/regdhcp') !== null)) ||
684
	    (config_path_enabled('unbound') && (config_get_path('unbound/regdhcp') !== null))) &&
685
	    (is_dhcp_server_enabled())) {
686
		/* Make sure we do not error out */
687
		mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db");
688
		if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
689
			@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
690
		}
691

    
692
		if (config_path_enabled('unbound')) {
693
			$dns_pid = "unbound.pid";
694
			$unbound_conf = "-u {$g['unbound_chroot_path']}/dhcpleases_entries.conf";
695
		} else {
696
			$dns_pid = "dnsmasq.pid";
697
			$unbound_conf = "";
698
		}
699

    
700
		if (isvalidpid($pidfile)) {
701
			/* Make sure dhcpleases is using correct unbound or dnsmasq */
702
			$_gb = exec("/bin/pgrep -F {$pidfile} -f {$dns_pid}", $output, $retval);
703
			if (intval($retval) == 0) {
704
				sigkillbypid($pidfile, "HUP");
705
				return;
706
			} else {
707
				sigkillbypid($pidfile, "TERM");
708
			}
709
		}
710

    
711
		/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
712
		if (is_process_running("dhcpleases")) {
713
			sigkillbyname('dhcpleases', "TERM");
714
		}
715
		@unlink($pidfile);
716
		mwexec("/usr/local/sbin/dhcpleases -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases -d " .
717
			   config_get_path('system/domain', '') .
718
			   " -p {$g['varrun_path']}/{$dns_pid} {$unbound_conf} -h {$g['etc_path']}/hosts");
719
	} else {
720
		if (isvalidpid($pidfile)) {
721
			sigkillbypid($pidfile, "TERM");
722
			@unlink($pidfile);
723
		}
724
		if (file_exists("{$g['unbound_chroot_path']}/dhcpleases_entries.conf")) {
725
			$dhcpleases = fopen("{$g['unbound_chroot_path']}/dhcpleases_entries.conf", "w");
726
			ftruncate($dhcpleases, 0);
727
			fclose($dhcpleases);
728
		}
729
	}
730
}
731

    
732
function system_clear_all_kea4leases()
733
{
734
	$socket_path = '/tmp/kea4-ctrl-socket';
735
	$rlen = 1024;
736
	$rbuf = NULL;
737

    
738
	if (!file_exists($socket_path)) {
739
		return;
740
	}
741

    
742
	$fd = socket_create(AF_UNIX, SOCK_STREAM, 0);
743

    
744
	if (!socket_connect($fd, $socket_path, 0)) {
745
		goto cleanup;
746
	}
747

    
748
	$cmdjson = json_encode(['command' => 'lease4-wipe']);
749

    
750
	socket_send($fd, $cmdjson, strlen($cmdjson), 0);
751

    
752
	/* Kea sends status that we are not really interested in, so just eat it */
753
	for (;;) {
754
		$bytes = socket_recv($fd, $rbuf, $rlen, MSG_WAITALL);
755
		if ($bytes > 0) {
756
			continue;
757
		}
758

    
759
		break;
760
	}
761

    
762
cleanup:
763
	socket_close($fd);
764
}
765

    
766
function system_del_kea4lease(string $ip)
767
{
768
	$socket_path = '/tmp/kea4-ctrl-socket';
769
	$rlen = 1024;
770
	$rbuf = NULL;
771

    
772
	if (!file_exists($socket_path)) {
773
		return;
774
	}
775

    
776
	$fd = socket_create(AF_UNIX, SOCK_STREAM, 0);
777

    
778
	if (!socket_connect($fd, $socket_path, 0)) {
779
		goto cleanup;
780
	}
781

    
782
	$cmdjson = json_encode([
783
		'command' => 'lease4-del',
784
		'arguments' => [
785
			'ip-address' => $ip
786
		]
787
	]);
788

    
789
	socket_send($fd, $cmdjson, strlen($cmdjson), 0);
790

    
791
	/* Kea sends status that we are not really interested in, so just eat it */
792
	for (;;) {
793
		$bytes = socket_recv($fd, $rbuf, $rlen, MSG_WAITALL);
794
		if ($bytes > 0) {
795
			continue;
796
		}
797

    
798
		break;
799
	}
800

    
801
cleanup:
802
	socket_close($fd);
803
}
804

    
805
function system_clear_all_kea6leases()
806
{
807
	$socket_path = '/tmp/kea6-ctrl-socket';
808
	$rlen = 1024;
809
	$rbuf = NULL;
810

    
811
	if (!file_exists($socket_path)) {
812
		return;
813
	}
814

    
815
	$fd = socket_create(AF_UNIX, SOCK_STREAM, 0);
816

    
817
	if (!socket_connect($fd, $socket_path, 0)) {
818
		goto cleanup;
819
	}
820

    
821
	$cmdjson = json_encode(['command' => 'lease6-wipe']);
822

    
823
	socket_send($fd, $cmdjson, strlen($cmdjson), 0);
824

    
825
	/* Kea sends status that we are not really interested in, so just eat it */
826
	for (;;) {
827
		$bytes = socket_recv($fd, $rbuf, $rlen, MSG_WAITALL);
828
		if ($bytes > 0) {
829
			continue;
830
		}
831

    
832
		break;
833
	}
834

    
835
cleanup:
836
	socket_close($fd);
837
}
838

    
839
function system_del_kea6lease(string $ip)
840
{
841
	$socket_path = '/tmp/kea6-ctrl-socket';
842
	$rlen = 1024;
843
	$rbuf = NULL;
844

    
845
	if (!file_exists($socket_path)) {
846
		return;
847
	}
848

    
849
	$fd = socket_create(AF_UNIX, SOCK_STREAM, 0);
850

    
851
	if (!socket_connect($fd, $socket_path, 0)) {
852
		goto cleanup;
853
	}
854

    
855
	$cmdjson = json_encode([
856
		'command' => 'lease6-del',
857
		'arguments' => [
858
			'ip-address' => $ip
859
		]
860
	]);
861

    
862
	socket_send($fd, $cmdjson, strlen($cmdjson), 0);
863

    
864
	/* Kea sends status that we are not really interested in, so just eat it */
865
	for (;;) {
866
		$bytes = socket_recv($fd, $rbuf, $rlen, MSG_WAITALL);
867
		if ($bytes > 0) {
868
			continue;
869
		}
870

    
871
		break;
872
	}
873

    
874
cleanup:
875
	socket_close($fd);
876
}
877

    
878

    
879
function system_get_kea6leases()
880
{
881
	$leases = [];
882
	$leases['lease'] = [];
883
	$leases['failover'] = [];
884

    
885
	$socket_path = '/tmp/kea6-ctrl-socket';
886
	$rlen = 1024;
887
	$rbuf = NULL;
888

    
889
	if (!file_exists($socket_path)) {
890
		goto out;
891
	}
892

    
893
	$fd = socket_create(AF_UNIX, SOCK_STREAM, 0);
894

    
895
	if (!socket_connect($fd, $socket_path, 0)) {
896
		goto cleanup;
897
	}
898

    
899
	$cmdjson = json_encode(['command' => 'lease6-get-all']);
900

    
901
	if (socket_send($fd, $cmdjson, strlen($cmdjson), 0) === false) {
902
		goto cleanup;
903
	}
904

    
905
	$retjson = NULL;
906
	for (;;) {
907
		$bytes = socket_recv($fd, $rbuf, $rlen, MSG_WAITALL);
908

    
909
		/* error occured, just bail out */
910
		if ($bytes === false) {
911
			goto cleanup;
912
		/* we got some data, append it to the json buffer */
913
		} elseif ($bytes > 0) {
914
			$retjson .= $rbuf;
915
		} else {
916
			break;
917
		}
918
	}
919

    
920
	/* sanity check in case we received malformed json */
921
	if (($ret = json_decode($retjson, true)) === false) {
922
		goto cleanup;
923
	}
924

    
925
	$ndpdata = get_ndpdata();
926

    
927
	$online_string = gettext("active/online");
928
	$offline_string = gettext("idle/offline");
929
	$active_string = gettext("active");
930
	$expired_string = gettext("expired");
931
	$reserved_string = gettext("reserved");
932
	$released_string = gettext("released");
933
	$dynamic_string = gettext("dynamic");
934
	$static_string = gettext("static");
935

    
936
	$leasem = [];
937

    
938
	foreach ($ret['arguments']['leases'] as $lease) {
939
		$startsts = (int)$lease['cltt'];
940
		$endsts = $startsts + (int)$lease['valid-lft'];
941

    
942
		$item = [];
943
		$item['act'] = $active_string;
944
		if (time() > $endsts) {
945
			$item['act'] = $expired_string;
946
		}
947

    
948
		$item['type'] = $dynamic_string;
949
		$item['ip'] = $lease['ip-address'];
950
		$item['duid'] = $lease['duid'];
951
		$item['iaid'] = $lease['iaid'];
952

    
953
		if (in_array($item['ip'], array_keys($ndpdata))) {
954
			$item['online'] = $online_string;
955
		} else {
956
			$item['online'] = $offline_string;
957
		}
958

    
959
		$item['hostname'] = rtrim($lease['hostname'], '.');
960

    
961
		$format = 'Y/m/d H:i:s';
962
		$item['starts'] = date($format, $startsts);
963
		$item['ends'] = date($format, $endsts);
964

    
965
		$leasem[$item['ip']] = $item;
966
	}
967

    
968
	foreach (config_get_path('interfaces', []) as $ifname => $ifarr) {
969
		foreach (config_get_path("dhcpdv6/{$ifname}/staticmap", []) as $idx => $static) {
970
			$slease = array();
971
			$slease['ip'] = merge_ipv6_delegated_prefix(get_interface_ipv6($ifname), $static['ipaddrv6'], get_interface_subnetv6($ifname));
972

    
973
			/* we've seen this entry before, so just modify it */
974
			if (array_key_exists($slease['ip'], $leasem)) {
975
				$leasem[$slease['ip']]['if'] = $ifname;
976
				$leasem[$slease['ip']]['type'] = $static_string;
977
				$leasem[$slease['ip']]['act'] = $static_string;
978
				$leasem[$slease['ip']]['descr'] = $static['descr'];
979
				$leasem[$slease['ip']]['staticmap_array_index'] = $idx;
980
				continue;
981
			}
982

    
983
			/* we still want to show static leases even if Kea doesn't see them */
984
			$slease['if'] = $ifname;
985
			$slease['type'] = $static_string;
986
			$slease['duid'] = $static['duid'];
987
			$slease['start'] = "";
988
			$slease['end'] = "";
989
			$slease['descr'] = $static['descr'];
990
			$slease['hostname'] = $static['hostname'];
991
			$slease['act'] = $static_string;
992
			if (in_array($slease['ip'], array_keys($ndpdata))) {
993
				$slease['online'] = $online_string;
994
			} else {
995
				$slease['online'] = $offline_string;
996
			}
997
			$slease['staticmap_array_index'] = $idx;
998

    
999
			$leasem[$slease['ip']] = $slease;
1000
		}
1001
	}
1002

    
1003
	$leases['lease'] = $leasem;
1004

    
1005
cleanup:
1006
	socket_close($fd);
1007
out:
1008
	return $leases;
1009
}
1010

    
1011
function system_get_kea4leases()
1012
{
1013
	$leases = [];
1014
	$leases['lease'] = [];
1015
	$leases['failover'] = [];
1016

    
1017
	$socket_path = '/tmp/kea4-ctrl-socket';
1018
	$rlen = 1024;
1019
	$rbuf = NULL;
1020

    
1021
	if (!file_exists($socket_path)) {
1022
		goto out;
1023
	}
1024

    
1025
	$fd = socket_create(AF_UNIX, SOCK_STREAM, 0);
1026

    
1027
	if (!socket_connect($fd, $socket_path, 0)) {
1028
		goto cleanup;
1029
	}
1030

    
1031
	$cmdjson = json_encode(['command' => 'lease4-get-all']);
1032

    
1033
	if (socket_send($fd, $cmdjson, strlen($cmdjson), 0) === false) {
1034
		goto cleanup;
1035
	}
1036

    
1037
	$retjson = NULL;
1038
	for (;;) {
1039
		$bytes = socket_recv($fd, $rbuf, $rlen, MSG_WAITALL);
1040

    
1041
		/* error occured, just bail out */
1042
		if ($bytes === false) {
1043
			goto cleanup;
1044
		/* we got some data, append it to the json buffer */
1045
		} elseif ($bytes > 0) {
1046
			$retjson .= $rbuf;
1047
		/* we must be done reading */
1048
		} else {
1049
			break;
1050
		}
1051
	}
1052

    
1053
	/* sanity check in case we received malformed json */
1054
	if (($ret = json_decode($retjson, true)) === false) {
1055
		goto cleanup;
1056
	}
1057

    
1058
	$arp_table = system_get_arp_table();
1059

    
1060
	$arpdata_ip = array();
1061
	$arpdata_mac = array();
1062
	foreach ($arp_table as $arp_entry) {
1063
		if (isset($arpentry['incomplete'])) {
1064
			continue;
1065
		}
1066
		$arpdata_ip[] = $arp_entry['ip-address'];
1067
		$arpdata_mac[] = $arp_entry['mac-address'];
1068
	}
1069

    
1070
	$online_string = gettext("active/online");
1071
	$offline_string = gettext("idle/offline");
1072
	$active_string = gettext("active");
1073
	$expired_string = gettext("expired");
1074
	$reserved_string = gettext("reserved");
1075
	$dynamic_string = gettext("dynamic");
1076
	$static_string = gettext("static");
1077

    
1078
	foreach ($ret['arguments']['leases'] as $lease) {
1079
		if (empty($lease['hw-address'])) {
1080
			continue;
1081
		}
1082

    
1083
		$startsts = (int)$lease['cltt'];
1084
		$endsts = $startsts + (int)$lease['valid-lft'];
1085

    
1086
		$item = [];
1087
		$item['act'] = $active_string;
1088
		if (time() > $endsts) {
1089
			$item['act'] = $expired_string;
1090
		}
1091

    
1092
		$item['type'] = $dynamic_string;
1093
		$item['ip'] = $lease['ip-address'];
1094
		$item['mac'] = $lease['hw-address'];
1095
		$item['cid'] = $lease['client-id'];
1096

    
1097
		if (in_array($item['ip'], $arpdata_ip) &&
1098
		    in_array(strtolower($item['mac']), $arpdata_mac)) {
1099
			$item['online'] = $online_string;
1100
		} else {
1101
			$item['online'] = $offline_string;
1102
		}
1103

    
1104
		$item['hostname'] = $lease['hostname'];
1105

    
1106
		$format = 'Y/m/d H:i:s';
1107
		$item['starts'] = date($format, $startsts);
1108
		$item['ends'] = date($format, $endsts);
1109

    
1110
		$leases['lease'][] = $item;
1111
	}
1112

    
1113
	$dedup_lease = false;
1114
	foreach (config_get_path('interfaces', []) as $ifname => $ifarr) {
1115
		foreach (config_get_path("dhcpd/{$ifname}/staticmap", []) as $idx => $static) {
1116
			if (empty($static['mac']) && empty($static['cid'])) {
1117
				continue;
1118
			}
1119

    
1120
			$slease = array();
1121
			$slease['ip'] = $static['ipaddr'];
1122
			$slease['type'] = $static_string;
1123
			if (!empty($static['cid'])) {
1124
				$slease['cid'] = $static['cid'];
1125
			}
1126
			$slease['mac'] = $static['mac'];
1127
			$slease['if'] = $ifname;
1128
			$slease['starts'] = "";
1129
			$slease['ends'] = "";
1130
			$slease['hostname'] = $static['hostname'];
1131
			$slease['descr'] = $static['descr'];
1132
			$slease['act'] = $static_string;
1133
			$slease['online'] = in_array(strtolower($slease['mac']),
1134
			    $arpdata_mac) ? $online_string : $offline_string;
1135
			$slease['staticmap_array_index'] = $idx;
1136
			$leases['lease'][] = $slease;
1137
			$dedup_lease = true;
1138
		}
1139
	}
1140

    
1141
	if ($dedup_lease) {
1142
		$leases['lease'] = array_remove_duplicate($leases['lease'],
1143
		    'ip');
1144
	}
1145

    
1146
cleanup:
1147
	socket_close($fd);
1148
out:
1149
	return $leases;
1150
}
1151

    
1152
function system_get_dhcpleases($dnsavailable=null)
1153
{
1154
	global $g;
1155

    
1156
	if (dhcp_is_backend('kea')) {
1157
		return system_get_kea4leases();
1158
	}
1159

    
1160
	$leases = array();
1161
	$leases['lease'] = array();
1162
	$leases['failover'] = array();
1163

    
1164
	$leases_file = "{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases";
1165

    
1166
	if (!file_exists($leases_file)) {
1167
		return $leases;
1168
	}
1169

    
1170
	$leases_content = file($leases_file, FILE_IGNORE_NEW_LINES |
1171
	    FILE_IGNORE_NEW_LINES);
1172

    
1173
	if ($leases_content === FALSE) {
1174
		return $leases;
1175
	}
1176

    
1177
	$arp_table = system_get_arp_table();
1178

    
1179
	$arpdata_ip = array();
1180
	$arpdata_mac = array();
1181
	foreach ($arp_table as $arp_entry) {
1182
		if (isset($arpentry['incomplete'])) {
1183
			continue;
1184
		}
1185
		$arpdata_ip[] = $arp_entry['ip-address'];
1186
		$arpdata_mac[] = $arp_entry['mac-address'];
1187
	}
1188
	unset($arp_table);
1189

    
1190
	/*
1191
	 * Translate these once so we don't do it over and over in the loops
1192
	 * below.
1193
	 */
1194
	$online_string = gettext("active/online");
1195
	$offline_string = gettext("idle/offline");
1196
	$active_string = gettext("active");
1197
	$expired_string = gettext("expired");
1198
	$reserved_string = gettext("reserved");
1199
	$dynamic_string = gettext("dynamic");
1200
	$static_string = gettext("static");
1201

    
1202
	$lease_regex = '/^lease\s+([^\s]+)\s+{$/';
1203
	$starts_regex = '/^\s*(starts|ends)\s+\d+\s+([\d\/]+|never)\s*(|[\d:]*);$/';
1204
	$binding_regex = '/^\s*binding\s+state\s+(.+);$/';
1205
	$mac_regex = '/^\s*hardware\s+ethernet\s+(.+);$/';
1206
	$hostname_regex = '/^\s*client-hostname\s+"(.+)";$/';
1207

    
1208
	$failover_regex = '/^failover\s+peer\s+"(.+)"\s+state\s+{$/';
1209
	$state_regex = '/\s*(my|partner)\s+state\s+(.+)\s+at\s+\d+\s+([\d\/]+)\s+([\d:]+);$/';
1210

    
1211
	$lease = false;
1212
	$failover = false;
1213
	$dedup_lease = false;
1214
	$dedup_failover = false;
1215

    
1216
	foreach ($leases_content as $line) {
1217
		/* Skip comments */
1218
		if (preg_match('/^\s*(|#.*)$/', $line)) {
1219
			continue;
1220
		}
1221

    
1222
		if (preg_match('/}$/', $line)) {
1223
			if ($lease) {
1224
				if (empty($item['hostname'])) {
1225
					if (is_null($dnsavailable)) {
1226
						$dnsavailable = check_dnsavailable();
1227
					}
1228
					if ($dnsavailable) {
1229
						$hostname = gethostbyaddr($item['ip']);
1230
						if (!empty($hostname)) {
1231
							$item['hostname'] = $hostname;
1232
						}
1233
					}
1234
				}
1235
				$leases['lease'][] = $item;
1236
				$lease = false;
1237
				$dedup_lease = true;
1238
			} else if ($failover) {
1239
				$leases['failover'][] = $item;
1240
				$failover = false;
1241
				$dedup_failover = true;
1242
			}
1243
			continue;
1244
		}
1245

    
1246
		if (preg_match($lease_regex, $line, $m)) {
1247
			$lease = true;
1248
			$item = array();
1249
			$item['ip'] = $m[1];
1250
			$item['type'] = $dynamic_string;
1251
			continue;
1252
		}
1253

    
1254
		if ($lease) {
1255
			if (preg_match($starts_regex, $line, $m)) {
1256
				/*
1257
				 * Quote from dhcpd.leases(5) man page:
1258
				 * If a lease will never expire, date is never
1259
				 * instead of an actual date
1260
				 */
1261
				if ($m[2] == "never") {
1262
					$item[$m[1]] = gettext("Never");
1263
				} else {
1264
					$item[$m[1]] = dhcpd_date_adjust_gmt(
1265
					    $m[2] . ' ' . $m[3]);
1266
				}
1267
				continue;
1268
			}
1269

    
1270
			if (preg_match($binding_regex, $line, $m)) {
1271
				switch ($m[1]) {
1272
					case "active":
1273
						$item['act'] = $active_string;
1274
						break;
1275
					case "free":
1276
						$item['act'] = $expired_string;
1277
						$item['online'] =
1278
						    $offline_string;
1279
						break;
1280
					case "backup":
1281
						$item['act'] = $reserved_string;
1282
						$item['online'] =
1283
						    $offline_string;
1284
						break;
1285
				}
1286
				continue;
1287
			}
1288

    
1289
			if (preg_match($mac_regex, $line, $m) &&
1290
			    is_macaddr($m[1])) {
1291
				$item['mac'] = $m[1];
1292

    
1293
				if (in_array($item['ip'], $arpdata_ip)) {
1294
					$item['online'] = $online_string;
1295
				} else {
1296
					$item['online'] = $offline_string;
1297
				}
1298
				continue;
1299
			}
1300

    
1301
			if (preg_match($hostname_regex, $line, $m)) {
1302
				$item['hostname'] = $m[1];
1303
			}
1304
		}
1305

    
1306
		if (preg_match($failover_regex, $line, $m)) {
1307
			$failover = true;
1308
			$item = array();
1309
			$item['name'] = $m[1] . ' (' .
1310
			    convert_friendly_interface_to_friendly_descr(
1311
			    substr($m[1],5)) . ')';
1312
			continue;
1313
		}
1314

    
1315
		if ($failover && preg_match($state_regex, $line, $m)) {
1316
			$item[$m[1] . 'state'] = $m[2];
1317
			$item[$m[1] . 'date'] = dhcpd_date_adjust_gmt($m[3] .
1318
			    ' ' . $m[4]);
1319
			continue;
1320
		}
1321
	}
1322

    
1323
	foreach (config_get_path('interfaces', []) as $ifname => $ifarr) {
1324
		foreach (config_get_path("dhcpd/{$ifname}/staticmap", []) as $idx =>
1325
		    $static) {
1326
			if (empty($static['mac']) && empty($static['cid'])) {
1327
				continue;
1328
			}
1329

    
1330
			$slease = array();
1331
			$slease['ip'] = $static['ipaddr'];
1332
			$slease['type'] = $static_string;
1333
			if (!empty($static['cid'])) {
1334
				$slease['cid'] = $static['cid'];
1335
			}
1336
			$slease['mac'] = $static['mac'];
1337
			$slease['if'] = $ifname;
1338
			$slease['starts'] = "";
1339
			$slease['ends'] = "";
1340
			$slease['hostname'] = $static['hostname'];
1341
			$slease['descr'] = $static['descr'];
1342
			$slease['act'] = $static_string;
1343
			$slease['online'] = in_array(strtolower($slease['mac']),
1344
			    $arpdata_mac) ? $online_string : $offline_string;
1345
			$slease['staticmap_array_index'] = $idx;
1346
			$leases['lease'][] = $slease;
1347
			$dedup_lease = true;
1348
		}
1349
	}
1350

    
1351
	if ($dedup_lease) {
1352
		$leases['lease'] = array_remove_duplicate($leases['lease'],
1353
		    'ip');
1354
	}
1355
	if ($dedup_failover) {
1356
		$leases['failover'] = array_remove_duplicate(
1357
		    $leases['failover'], 'name');
1358
		asort($leases['failover']);
1359
	}
1360

    
1361
	return $leases;
1362
}
1363

    
1364
function system_hostname_configure() {
1365
	if (config_path_enabled('system', 'developerspew')) {
1366
		$mt = microtime();
1367
		echo "system_hostname_configure() being called $mt\n";
1368
	}
1369

    
1370
	$syscfg = config_get_path('system');
1371

    
1372
	/* set hostname */
1373
	$status = mwexec("/bin/hostname " .
1374
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
1375

    
1376
	/* Setup host GUID ID.  This is used by ZFS. */
1377
	mwexec("/etc/rc.d/hostid start");
1378

    
1379
	return $status;
1380
}
1381

    
1382
function system_routing_configure($interface = "") {
1383
	if (config_path_enabled('system', 'developerspew')) {
1384
		$mt = microtime();
1385
		echo "system_routing_configure() being called $mt\n";
1386
	}
1387

    
1388
	$gateways_arr = get_gateways(GW_CACHE_LOCALHOST);
1389
	foreach ($gateways_arr as $gateway) {
1390
		// setup static interface routes for nonlocal gateways
1391
		if (isset($gateway["nonlocalgateway"])) {
1392
			$srgatewayip = $gateway['gateway'];
1393
			$srinterfacegw = $gateway['interface'];
1394
			if (is_ipaddr($srgatewayip) && !empty($srinterfacegw)) {
1395
				route_add_or_change($srgatewayip, '',
1396
				    $srinterfacegw);
1397
			}
1398
		}
1399
	}
1400

    
1401
	$gateways_status = return_gateways_status(true);
1402
	fixup_default_gateway("inet", $gateways_status, $gateways_arr);
1403
	fixup_default_gateway("inet6", $gateways_status, $gateways_arr);
1404

    
1405
	system_staticroutes_configure($interface, false);
1406

    
1407
	return 0;
1408
}
1409

    
1410
function system_staticroutes_configure($interface = "", $update_dns = false) {
1411
	global $g, $aliastable;
1412

    
1413
	$filterdns_list = array();
1414

    
1415
	$static_routes = get_staticroutes(false, true);
1416
	if (count($static_routes)) {
1417
		$gateways_arr = get_gateways(GW_CACHE_LOCALHOST);
1418

    
1419
		foreach ($static_routes as $rtent) {
1420
			/* Do not delete disabled routes,
1421
			 * see https://redmine.pfsense.org/issues/3709
1422
			 * and https://redmine.pfsense.org/issues/10706 */
1423
			if (isset($rtent['disabled'])) {
1424
				continue;
1425
			}
1426

    
1427
			if (empty($gateways_arr[$rtent['gateway']])) {
1428
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
1429
				continue;
1430
			}
1431
			$gateway = $gateways_arr[$rtent['gateway']];
1432
			if (!empty($interface) && $interface != $gateway['friendlyiface']) {
1433
				continue;
1434
			}
1435

    
1436
			$gatewayip = $gateway['gateway'];
1437
			$interfacegw = $gateway['interface'];
1438

    
1439
			$blackhole = "";
1440
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 4))) {
1441
				$blackhole = "-blackhole";
1442
			}
1443

    
1444
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network'])) {
1445
				continue;
1446
			}
1447

    
1448
			$dnscache = array();
1449
			if ($update_dns === true) {
1450
				if (is_subnet($rtent['network'])) {
1451
					continue;
1452
				}
1453
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
1454
				if (empty($dnscache)) {
1455
					continue;
1456
				}
1457
			}
1458

    
1459
			if (is_subnet($rtent['network'])) {
1460
				$ips = array($rtent['network']);
1461
			} else {
1462
				if (!isset($rtent['disabled'])) {
1463
					$filterdns_list[] = $rtent['network'];
1464
				}
1465
				$ips = add_hostname_to_watch($rtent['network']);
1466
			}
1467

    
1468
			foreach ($dnscache as $ip) {
1469
				if (in_array($ip, $ips)) {
1470
					continue;
1471
				}
1472
				route_del($ip);
1473
			}
1474

    
1475
			if (isset($rtent['disabled'])) {
1476
				/*
1477
				 * XXX: This can break things by deleting
1478
				 * routes that shouldn't be deleted - OpenVPN,
1479
				 * dynamic routing scenarios, etc.
1480
				 * redmine #3709
1481
				 */
1482
				foreach ($ips as $ip) {
1483
					route_del($ip);
1484
				}
1485
				continue;
1486
			}
1487

    
1488
			foreach ($ips as $ip) {
1489
				if (is_ipaddrv4($ip)) {
1490
					$ip .= "/32";
1491
				}
1492
				/*
1493
				 * do NOT do the same check here on v6,
1494
				 * is_ipaddrv6 returns true when including
1495
				 * the CIDR mask. doing so breaks v6 routes
1496
				 */
1497
				if (is_subnet($ip)) {
1498
					if (is_ipaddr($gatewayip)) {
1499
						if (is_linklocal($gatewayip) == "6" &&
1500
						    !strpos($gatewayip, '%')) {
1501
							/*
1502
							 * add interface scope
1503
							 * for link local v6
1504
							 * routes
1505
							 */
1506
							$gatewayip .= "%$interfacegw";
1507
						}
1508
						route_add_or_change($ip,
1509
						    $gatewayip, '', $blackhole);
1510
					} else if (!empty($interfacegw)) {
1511
						route_add_or_change($ip,
1512
						    '', $interfacegw, $blackhole);
1513
					}
1514
				}
1515
			}
1516
		}
1517
		unset($gateways_arr);
1518

    
1519
		/* keep static routes cache,
1520
		 * see https://redmine.pfsense.org/issues/11599 */
1521
		$id = 0;
1522
		foreach (config_get_path('staticroutes/route', []) as $sroute) {
1523
			$targets = array();
1524
			if (is_subnet($sroute['network'])) {
1525
				$targets[] = $sroute['network'];
1526
			} elseif (is_alias($sroute['network'])) {
1527
				foreach (preg_split('/\s+/', $aliastable[$sroute['network']]) as $tgt) {
1528
					if (is_ipaddrv4($tgt)) {
1529
						$tgt .= "/32";
1530
					}
1531
					if (is_ipaddrv6($tgt)) {
1532
						$tgt .= "/128";
1533
					}
1534
					if (!is_subnet($tgt)) {
1535
						continue;
1536
					}
1537
					$targets[] = $tgt;
1538
				}
1539
			}
1540
			file_put_contents("{$g['tmp_path']}/staticroute_{$id}", serialize($targets));
1541
			file_put_contents("{$g['tmp_path']}/staticroute_{$id}_gw", serialize($sroute['gateway']));
1542
			$id++;
1543
		}
1544
	}
1545
	unset($static_routes);
1546

    
1547
	if ($update_dns === false) {
1548
		if (count($filterdns_list)) {
1549
			$interval = 60;
1550
			$hostnames = "";
1551
			array_unique($filterdns_list);
1552
			foreach ($filterdns_list as $hostname) {
1553
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
1554
			}
1555
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
1556
			unset($hostnames);
1557

    
1558
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid")) {
1559
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
1560
			} else {
1561
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
1562
			}
1563
		} else {
1564
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
1565
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
1566
		}
1567
	}
1568
	unset($filterdns_list);
1569

    
1570
	return 0;
1571
}
1572

    
1573
function delete_static_route($id, $delete = false) {
1574
	global $g, $changedesc_prefix, $a_gateways;
1575

    
1576
	if (empty(config_get_path("staticroutes/route/{$id}"))) {
1577
		return;
1578
	}
1579

    
1580
	if (file_exists("{$g['tmp_path']}/.system_routes.apply")) {
1581
		$toapplylist = unserialize(file_get_contents("{$g['tmp_path']}/.system_routes.apply"));
1582
	} else {
1583
		$toapplylist = array();
1584
	}
1585

    
1586
	if (file_exists("{$g['tmp_path']}/staticroute_{$id}") &&
1587
	    file_exists("{$g['tmp_path']}/staticroute_{$id}_gw")) {
1588
		$delete_targets = unserialize(file_get_contents("{$g['tmp_path']}/staticroute_{$id}"));
1589
		$delgw = lookup_gateway_ip_by_name(unserialize(file_get_contents("{$g['tmp_path']}/staticroute_{$id}_gw")));
1590
		if (count($delete_targets)) {
1591
			foreach ($delete_targets as $dts) {
1592
				if (is_subnetv4($dts)) {
1593
					$family = "-inet";
1594
				} else {
1595
					$family = "-inet6";
1596
				}
1597
				$route = route_get($dts, '', true);
1598
				if (!count($route)) {
1599
					continue;
1600
				}
1601
				$toapplylist[] = "/sbin/route delete " .
1602
				    $family . " " . $dts . " " . $delgw;
1603
			}
1604
		}
1605
	}
1606

    
1607
	if ($delete) {
1608
		unlink_if_exists("{$g['tmp_path']}/staticroute_{$id}");
1609
		unlink_if_exists("{$g['tmp_path']}/staticroute_{$id}_gw");
1610
	}
1611

    
1612
	if (!empty($toapplylist)) {
1613
		file_put_contents("{$g['tmp_path']}/.system_routes.apply", serialize($toapplylist));
1614
	}
1615

    
1616
	unset($targets);
1617
}
1618

    
1619
function system_routing_enable() {
1620
	if (config_path_enabled('system', 'developerspew')) {
1621
		$mt = microtime();
1622
		echo "system_routing_enable() being called $mt\n";
1623
	}
1624

    
1625
	set_sysctl(array(
1626
		"net.inet.ip.forwarding" => "1",
1627
		"net.inet6.ip6.forwarding" => "1"
1628
	));
1629

    
1630
	return;
1631
}
1632

    
1633
function system_webgui_start() {
1634
	global $g;
1635

    
1636
	if (platform_booting()) {
1637
		echo gettext("Starting webConfigurator...");
1638
	}
1639

    
1640
	chdir(g_get('www_path'));
1641

    
1642
	/* defaults */
1643
	$portarg = config_get_path('system/webgui/port', '80');
1644
	$crt = "";
1645
	$key = "";
1646
	$ca = "";
1647

    
1648
	if (config_get_path('system/webgui/protocol') == "https") {
1649
		// Ensure that we have a webConfigurator CERT
1650
		$cert = lookup_cert(config_get_path('system/webgui/ssl-certref'));
1651
		if (!is_array($cert) || !$cert['crt'] || !$cert['prv'] ||
1652
		    cert_chain_has_weak_digest($cert)) {
1653
			$cert = cert_create_selfsigned();
1654
			if (is_array($cert) && !empty($cert)) {
1655
				config_set_path('system/webgui/ssl-certref', $cert['refid']);
1656
				write_config(sprintf(gettext("Generated new self-signed SSL/TLS certificate for HTTPS (%s)"), $cert['refid']));
1657
			} else {
1658
				log_error(sprintf(gettext("GUI certificate is not usable and there was an error creating a new self-signed certificate.")));
1659
			}
1660
		}
1661
		$crt = base64_decode($cert['crt']);
1662
		$key = base64_decode($cert['prv']);
1663

    
1664
		$portarg = config_get_path('system/webgui/port', '443');
1665
		$ca = ca_chain($cert);
1666
		$hsts = !config_path_enabled('system/webgui', 'disablehsts');
1667
	}
1668

    
1669
	/* generate nginx configuration */
1670
	system_generate_nginx_config("{$g['varetc_path']}/nginx-webConfigurator.conf",
1671
		$crt, $key, $ca, "nginx-webConfigurator.pid", $portarg, "/usr/local/www/",
1672
		"cert.crt", "cert.key", false, $hsts);
1673

    
1674
	/* kill any running nginx */
1675
	killbypid("{$g['varrun_path']}/nginx-webConfigurator.pid");
1676

    
1677
	sleep(1);
1678

    
1679
	@unlink("{$g['varrun_path']}/nginx-webConfigurator.pid");
1680

    
1681
	/* start nginx */
1682
	$res = mwexec("/usr/local/sbin/nginx -c {$g['varetc_path']}/nginx-webConfigurator.conf");
1683

    
1684
	if (platform_booting()) {
1685
		if ($res == 0) {
1686
			echo gettext("done.") . "\n";
1687
		} else {
1688
			echo gettext("failed!") . "\n";
1689
		}
1690
	}
1691

    
1692
	return $res;
1693
}
1694

    
1695
/****f* system.inc/get_dns_nameservers
1696
 * NAME
1697
 *   get_dns_nameservers - Get system DNS servers
1698
 * INPUTS
1699
 *   $add_v6_brackets: (boolean, false)
1700
 *                     Add brackets around IPv6 DNS servers, as expected by some
1701
 *                     daemons such as nginx.
1702
 *   $hostns         : (boolean, true)
1703
 *                     true : Return only DNS servers used by the firewall
1704
 *                            itself as upstream forwarding servers
1705
 *                     false: Return all DNS servers from the configuration and
1706
 *                            overrides (if allowed).
1707
 * RESULT
1708
 *   $dns_nameservers - An array of the requested DNS servers
1709
 ******/
1710
function get_dns_nameservers($add_v6_brackets = false, $hostns=true) {
1711
	$dns_nameservers = array();
1712

    
1713
	if (config_path_enabled('system', 'developerspew')) {
1714
		$mt = microtime();
1715
		echo "get_dns_nameservers() being called $mt\n";
1716
	}
1717

    
1718
	if ((((config_path_enabled('dnsmasq')) &&
1719
		  (config_get_path('dnsmasq/port', '53') == '53') &&
1720
		  in_array("lo0", explode(",", config_get_path('dnsmasq/interface', 'lo0'))))) ||
1721
	    (config_path_enabled('unbound') &&
1722
		 (config_get_path('unbound/port', '53') == '53') &&
1723
		 (in_array("lo0", explode(",", config_get_path('unbound/active_interface', 'lo0'))) ||
1724
		  in_array("all", explode(",", config_get_path('unbound/active_interface', 'all')), true))) &&
1725
	    (config_get_path('system/dnslocalhost') != 'remote')) {
1726
		$dns_nameservers[] = "127.0.0.1";
1727
	}
1728

    
1729
	if ($hostns || (config_get_path('system/dnslocalhost') != 'local')) {
1730
		if (config_path_enabled('system', 'dnsallowoverride')) {
1731
			/* get dynamically assigned DNS servers (if any) */
1732
			foreach (array_unique(get_dynamic_nameservers()) as $nameserver) {
1733
				if ($nameserver) {
1734
					if ($add_v6_brackets && is_ipaddrv6($nameserver)) {
1735
						$nameserver = "[{$nameserver}]";
1736
					}
1737
					$dns_nameservers[] = $nameserver;
1738
				}
1739
			}
1740
		}
1741
		foreach (config_get_path('system/dnsserver', []) as $sys_dnsserver) {
1742
			if ($sys_dnsserver && (!in_array($sys_dnsserver, $dns_nameservers))) {
1743
				if ($add_v6_brackets && is_ipaddrv6($sys_dnsserver)) {
1744
					$sys_dnsserver = "[{$sys_dnsserver}]";
1745
				}
1746
				$dns_nameservers[] = $sys_dnsserver;
1747
			}
1748
		}
1749
	}
1750
	return array_unique($dns_nameservers);
1751
}
1752

    
1753
function system_generate_nginx_config($filename,
1754
	$cert,
1755
	$key,
1756
	$ca,
1757
	$pid_file,
1758
	$port = 80,
1759
	$document_root = "/usr/local/www/",
1760
	$cert_location = "cert.crt",
1761
	$key_location = "cert.key",
1762
	$captive_portal = false,
1763
	$hsts = true) {
1764

    
1765
	global $g;
1766

    
1767
	if (config_path_enabled('system', 'developerspew')) {
1768
		$mt = microtime();
1769
		echo "system_generate_nginx_config() being called $mt\n";
1770
	}
1771

    
1772
	if ($captive_portal !== false) {
1773
		$cp_interfaces = explode(",", config_get_path("captiveportal/{$captive_portal}/interface"));
1774
		$cp_hostcheck = "";
1775
		foreach ($cp_interfaces as $cpint) {
1776
			$cpint_ip = get_interface_ip($cpint);
1777
			if (is_ipaddr($cpint_ip)) {
1778
				$cp_hostcheck .= "\t\tif (\$http_host ~* $cpint_ip) {\n";
1779
				$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1780
				$cp_hostcheck .= "\t\t}\n";
1781
			}
1782
		}
1783
		$httpsname = config_get_path("captiveportal/{$captive_portal}/httpsname");
1784
		if (!empty($httpsname) &&
1785
		    is_domain($httpsname)) {
1786
			$cp_hostcheck .= "\t\tif (\$http_host ~* {$httpsname}) {\n";
1787
			$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1788
			$cp_hostcheck .= "\t\t}\n";
1789
		}
1790
		$cp_rewrite = "\t\tif (\$cp_redirect = '') {\n";
1791
		$cp_rewrite .= "\t\t\trewrite	^ /index.php?zone=$captive_portal&redirurl=\$request_uri break;\n";
1792
		$cp_rewrite .= "\t\t}\n";
1793

    
1794
		$maxprocperip = config_get_path("captiveportal/{$captive_portal}/maxprocperip");
1795
		if (empty($maxprocperip)) {
1796
			$maxprocperip = 10;
1797
		}
1798
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1799
	}
1800

    
1801
	if (empty($port)) {
1802
		$nginx_port = "80";
1803
	} else {
1804
		$nginx_port = $port;
1805
	}
1806

    
1807
	$memory = get_memory();
1808
	$realmem = $memory[1];
1809

    
1810
	// Determine web GUI process settings and take into account low memory systems
1811
	if ($realmem < 255) {
1812
		$max_procs = 1;
1813
	} else {
1814
		$max_procs = config_get_path('system/webgui/max_procs', 2);
1815
	}
1816

    
1817
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM
1818
	if ($captive_portal !== false) {
1819
		if ($realmem > 135 and $realmem < 256) {
1820
			$max_procs += 1; // 2 worker processes
1821
		} else if ($realmem > 255 and $realmem < 513) {
1822
			$max_procs += 2; // 3 worker processes
1823
		} else if ($realmem > 512) {
1824
			$max_procs += 4; // 6 worker processes
1825
		}
1826
	}
1827

    
1828
	$nginx_config = <<<EOD
1829
#
1830
# nginx configuration file
1831

    
1832
pid {$g['varrun_path']}/{$pid_file};
1833

    
1834
user  root wheel;
1835
worker_processes  {$max_procs};
1836

    
1837
EOD;
1838

    
1839
	/* Disable file logging */
1840
	$nginx_config .= "error_log /dev/null;\n";
1841
	if (!config_path_enabled('syslog','nolognginx')) {
1842
		/* Send nginx error log to syslog */
1843
		$nginx_config .= "error_log  syslog:server=unix:/var/run/log,facility=local5;\n";
1844
	}
1845

    
1846
	$nginx_config .= <<<EOD
1847

    
1848
events {
1849
    worker_connections  1024;
1850
}
1851

    
1852
http {
1853
	include       /usr/local/etc/nginx/mime.types;
1854
	default_type  application/octet-stream;
1855
	add_header X-Frame-Options SAMEORIGIN;
1856
	server_tokens off;
1857

    
1858
	sendfile        off;
1859

    
1860
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1861

    
1862
EOD;
1863

    
1864
	if ($captive_portal !== false) {
1865
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1866
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1867
	} else {
1868
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1869
	}
1870

    
1871
	if ($cert <> "" and $key <> "") {
1872
		$nginx_config .= "\n";
1873
		$nginx_config .= "\tserver {\n";
1874
		$nginx_config .= "\t\tlisten {$nginx_port} ssl http2;\n";
1875
		$nginx_config .= "\t\tlisten [::]:{$nginx_port} ssl http2;\n";
1876
		$nginx_config .= "\n";
1877
		$nginx_config .= "\t\tssl_certificate         {$g['varetc_path']}/{$cert_location};\n";
1878
		$nginx_config .= "\t\tssl_certificate_key     {$g['varetc_path']}/{$key_location};\n";
1879
		$nginx_config .= "\t\tssl_session_timeout     10m;\n";
1880
		$nginx_config .= "\t\tkeepalive_timeout       70;\n";
1881
		$nginx_config .= "\t\tssl_session_cache       shared:SSL:10m;\n";
1882
		if ($captive_portal !== false) {
1883
			// leave TLSv1.1 for CP for now for compatibility
1884
			$nginx_config .= "\t\tssl_protocols   TLSv1.1 TLSv1.2 TLSv1.3;\n";
1885
		} else {
1886
			$nginx_config .= "\t\tssl_protocols   TLSv1.2 TLSv1.3;\n";
1887
		}
1888
		$nginx_config .= "\t\tssl_ciphers \"EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305\";\n";
1889
		$nginx_config .= "\t\tssl_prefer_server_ciphers       on;\n";
1890
		if ($captive_portal === false && $hsts !== false) {
1891
			$nginx_config .= "\t\tadd_header Strict-Transport-Security \"max-age=31536000\";\n";
1892
		}
1893
		$nginx_config .= "\t\tadd_header X-Content-Type-Options nosniff;\n";
1894
		$nginx_config .= "\t\tssl_session_tickets off;\n";
1895
		$nginx_config .= "\t\tssl_dhparam /etc/dh-parameters.4096;\n";
1896
		$cert_temp = lookup_cert(config_get_path('system/webgui/ssl-certref'));
1897
		if ((config_get_path('system/webgui/ocsp-staple') == true) or
1898
		    (cert_get_ocspstaple($cert_temp['crt']) == true)) {
1899
			$nginx_config .= "\t\tssl_stapling on;\n";
1900
			$nginx_config .= "\t\tssl_stapling_verify on;\n";
1901
			$nginx_config .= "\t\tresolver " . implode(" ", get_dns_nameservers(true)) . " valid=300s;\n";
1902
			$nginx_config .= "\t\tresolver_timeout 5s;\n";
1903
		}
1904
	} else {
1905
		$nginx_config .= "\n";
1906
		$nginx_config .= "\tserver {\n";
1907
		$nginx_config .= "\t\tlisten {$nginx_port};\n";
1908
		$nginx_config .= "\t\tlisten [::]:{$nginx_port};\n";
1909
	}
1910

    
1911
	$nginx_config .= <<<EOD
1912

    
1913
		client_max_body_size 200m;
1914

    
1915
		gzip on;
1916
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
1917

    
1918

    
1919
EOD;
1920

    
1921
	if ($captive_portal !== false) {
1922
		$nginx_config .= <<<EOD
1923
$captive_portal_maxprocperip
1924
$cp_hostcheck
1925
$cp_rewrite
1926
		log_not_found off;
1927

    
1928
EOD;
1929

    
1930
	}
1931

    
1932
	$plugin_locations = "";
1933
	if ($captive_portal == false) {
1934
		$pluginparams = [ 'section' => 'location' ];
1935
		foreach (pkg_call_plugins('plugin_nginx', $pluginparams) as $pkgname => $location) {
1936
			if (empty($location)) {
1937
				continue;
1938
			}
1939
			$plugin_locations .= "# Plugin Locations ({$pkgname})\n";
1940
			$plugin_locations .= "{$location}\n";
1941
		}
1942
	}
1943

    
1944
	$nginx_config .= <<<EOD
1945
		root "{$document_root}";
1946
		location / {
1947
			index  index.php index.html index.htm;
1948
		}
1949
		location ~ (\.inc$|\.orig$|\.pkgsave$) {
1950
			deny all;
1951
			return 403;
1952
		}
1953
		location ~ \.php$ {
1954
			try_files \$uri =404; #  This line closes a potential security hole
1955
			# ensuring users can't execute uploaded files
1956
			# see: https://forum.nginx.org/read.php?2,88845,page=3
1957
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1958
			fastcgi_index  index.php;
1959
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1960
			# Fix httpoxy - https://httpoxy.org/#fix-now
1961
			fastcgi_param  HTTP_PROXY  "";
1962
			fastcgi_read_timeout 180;
1963
			include        /usr/local/etc/nginx/fastcgi_params;
1964
		}
1965
		location ~ (^/status$) {
1966
			allow 127.0.0.1;
1967
			deny all;
1968
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1969
			fastcgi_index  index.php;
1970
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1971
			# Fix httpoxy - https://httpoxy.org/#fix-now
1972
			fastcgi_param  HTTP_PROXY  "";
1973
			fastcgi_read_timeout 360;
1974
			include        /usr/local/etc/nginx/fastcgi_params;
1975
		}
1976
		{$plugin_locations}
1977
	}
1978

    
1979
EOD;
1980

    
1981
	$cert = str_replace("\r", "", $cert);
1982
	$key = str_replace("\r", "", $key);
1983

    
1984
	$cert = str_replace("\n\n", "\n", $cert);
1985
	$key = str_replace("\n\n", "\n", $key);
1986

    
1987
	if ($cert <> "" and $key <> "") {
1988
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1989
		if (!$fd) {
1990
			printf(gettext("Error: cannot open certificate file in system_webgui_start().%s"), "\n");
1991
			return 1;
1992
		}
1993
		chmod("{$g['varetc_path']}/{$cert_location}", 0644);
1994
		if ($ca <> "") {
1995
			$cert_chain = $cert . "\n" . $ca;
1996
		} else {
1997
			$cert_chain = $cert;
1998
		}
1999
		fwrite($fd, $cert_chain);
2000
		fclose($fd);
2001
		$fd = fopen("{$g['varetc_path']}/{$key_location}", "w");
2002
		if (!$fd) {
2003
			printf(gettext("Error: cannot open certificate key file in system_webgui_start().%s"), "\n");
2004
			return 1;
2005
		}
2006
		chmod("{$g['varetc_path']}/{$key_location}", 0600);
2007
		fwrite($fd, $key);
2008
		fclose($fd);
2009
	}
2010

    
2011
	// Add HTTP to HTTPS redirect
2012
	if ($captive_portal === false && config_get_path('system/webgui/protocol') == "https" && !(config_path_enabled('system/webgui', 'disablehttpredirect') != null)) {
2013
		if ($nginx_port != "443") {
2014
			$redirectport = ":{$nginx_port}";
2015
		}
2016
		$nginx_config .= <<<EOD
2017
	server {
2018
		listen 80;
2019
		listen [::]:80;
2020
		return 301 https://\$http_host$redirectport\$request_uri;
2021
	}
2022

    
2023
EOD;
2024
	}
2025

    
2026
	if ($captive_portal == false) {
2027
		$pluginparams = [ 'section' => 'server' ];
2028
		foreach (pkg_call_plugins('plugin_nginx', $pluginparams) as $pkgname => $server) {
2029
			if (empty($server)) {
2030
				continue;
2031
			}
2032
			$nginx_config .= "	# Plugin Servers ({$pkgname})\n";
2033
			$nginx_config .= "{$server}\n";
2034
		}
2035
	}
2036

    
2037
	$nginx_config .= "}\n";
2038

    
2039
	$fd = fopen("{$filename}", "w");
2040
	if (!$fd) {
2041
		printf(gettext('Error: cannot open %1$s in system_generate_nginx_config().%2$s'), $filename, "\n");
2042
		return 1;
2043
	}
2044
	fwrite($fd, $nginx_config);
2045
	fclose($fd);
2046

    
2047
	/* nginx will fail to start if this directory does not exist. */
2048
	safe_mkdir("/var/tmp/nginx/");
2049

    
2050
	return 0;
2051

    
2052
}
2053

    
2054
function system_get_timezone_list() {
2055
	global $g;
2056

    
2057
	$file_list = array_merge(
2058
		glob("/usr/share/zoneinfo/[A-Z]*"),
2059
		glob("/usr/share/zoneinfo/*/*"),
2060
		glob("/usr/share/zoneinfo/*/*/*")
2061
	);
2062

    
2063
	if (empty($file_list)) {
2064
		$file_list[] = g_get('default_timezone');
2065
	} else {
2066
		/* Remove directories from list */
2067
		$file_list = array_filter($file_list, function($v) {
2068
			return !is_dir($v);
2069
		});
2070
	}
2071

    
2072
	/* Remove directory prefix */
2073
	$file_list = str_replace('/usr/share/zoneinfo/', '', $file_list);
2074

    
2075
	sort($file_list);
2076

    
2077
	return $file_list;
2078
}
2079

    
2080
function system_timezone_configure() {
2081
	global $g;
2082
	if (config_path_enabled('system', 'developerspew')) {
2083
		$mt = microtime();
2084
		echo "system_timezone_configure() being called $mt\n";
2085
	}
2086

    
2087
	$syscfg = config_get_path('system');
2088

    
2089
	if (platform_booting()) {
2090
		echo gettext("Setting timezone...");
2091
	}
2092

    
2093
	/* extract appropriate timezone file */
2094
	$timezone = (isset($syscfg['timezone']) ? $syscfg['timezone'] : g_get('default_timezone'));
2095
	/* DO NOT remove \n otherwise tzsetup will fail */
2096
	@file_put_contents("/var/db/zoneinfo", $timezone . "\n");
2097
	mwexec("/usr/sbin/tzsetup -r");
2098

    
2099
	if (platform_booting()) {
2100
		echo gettext("done.") . "\n";
2101
	}
2102
}
2103

    
2104
function check_gps_speed($device) {
2105
	usleep(1000);
2106
	// Set timeout to 5s
2107
	$timeout=microtime(true)+5;
2108
	if ($fp = fopen($device, 'r')) {
2109
		stream_set_blocking($fp, 0);
2110
		stream_set_timeout($fp, 5);
2111
		$contents = "";
2112
		$cnt = 0;
2113
		$buffersize = 256;
2114
		do {
2115
			$c = fread($fp, $buffersize - $cnt);
2116

    
2117
			// Wait for data to arive
2118
			if (($c === false) || (strlen($c) == 0)) {
2119
				usleep(500);
2120
				continue;
2121
			}
2122

    
2123
			$contents.=$c;
2124
			$cnt = $cnt + strlen($c);
2125
		} while (($cnt < $buffersize) && (microtime(true) < $timeout));
2126
		fclose($fp);
2127

    
2128
		$nmeasentences = ['RMC', 'GGA', 'GLL', 'ZDA', 'ZDG', 'PGRMF'];
2129
		foreach ($nmeasentences as $sentence) {
2130
			if (strpos($contents, $sentence) > 0) {
2131
				return true;
2132
			}
2133
		}
2134
		if (strpos($contents, '0') > 0) {
2135
			$filters = ['`', '?', '/', '~'];
2136
			foreach ($filters as $filter) {
2137
				if (strpos($contents, $filter) !== false) {
2138
					return false;
2139
				}
2140
			}
2141
			return true;
2142
		}
2143
	}
2144
	return false;
2145
}
2146

    
2147
/* Generate list of possible NTP poll values
2148
 * https://redmine.pfsense.org/issues/9439 */
2149
global $ntp_poll_min_value, $ntp_poll_max_value;
2150
global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
2151
global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
2152
global $ntp_poll_min_default, $ntp_poll_max_default;
2153
global $ntp_auth_halgos, $ntp_server_types;
2154
$ntp_poll_min_value = 3;
2155
$ntp_poll_max_value = 17;
2156
$ntp_poll_min_default_gps = 4;
2157
$ntp_poll_max_default_gps = 4;
2158
$ntp_poll_min_default_pps = 4;
2159
$ntp_poll_max_default_pps = 4;
2160
$ntp_poll_min_default = 'omit';
2161
$ntp_poll_max_default = 9;
2162
$ntp_auth_halgos = array(
2163
	'md5' => 'MD5',
2164
	'sha1' => 'SHA1',
2165
	'sha256' => 'SHA256'
2166
);
2167
$ntp_server_types = array(
2168
	'server' => 'Server',
2169
	'pool' => 'Pool',
2170
	'peer' => 'Peer'
2171
);
2172

    
2173
function system_ntp_poll_values() {
2174
	global $ntp_poll_min_value, $ntp_poll_max_value;
2175
	$poll_values = array("" => gettext('Default'));
2176

    
2177
	for ($i = $ntp_poll_min_value; $i <= $ntp_poll_max_value; $i++) {
2178
		$sec = 2 ** $i;
2179
		$poll_values[$i] = $i . ': ' . number_format($sec) . ' ' . gettext('seconds') .
2180
					' (' . convert_seconds_to_dhms($sec) . ')';
2181
	}
2182

    
2183
	$poll_values['omit'] = gettext('Omit (Do not set)');
2184
	return $poll_values;
2185
}
2186

    
2187
function system_ntp_fixup_poll_value($type, $configvalue, $default) {
2188
	$pollstring = "";
2189

    
2190
	if (empty($configvalue)) {
2191
		$configvalue = $default;
2192
	}
2193

    
2194
	if ($configvalue != 'omit') {
2195
		$pollstring = " {$type} {$configvalue}";
2196
	}
2197

    
2198
	return $pollstring;
2199
}
2200

    
2201
function system_ntp_setup_gps($serialport) {
2202
	if (config_get_path('ntpd/enable') == 'disabled') {
2203
		return false;
2204
	}
2205

    
2206
	init_config_arr(array('ntpd', 'gps'));
2207
	$serialports = get_serial_ports(true);
2208

    
2209
	if (!array_key_exists($serialport, $serialports)) {
2210
		return false;
2211
	}
2212

    
2213
	$gps_device = '/dev/gps0';
2214
	$serialport = '/dev/'.basename($serialport);
2215

    
2216
	if (!file_exists($serialport)) {
2217
		return false;
2218
	}
2219

    
2220
	// Create symlink that ntpd requires
2221
	unlink_if_exists($gps_device);
2222
	@symlink($serialport, $gps_device);
2223

    
2224
	$speeds = array(
2225
		0 => '4800',
2226
		16 => '9600',
2227
		32 => '19200',
2228
		48 => '38400',
2229
		64 => '57600',
2230
		80 => '115200'
2231
	);
2232
	// $gpsbaud defaults to '4800' if ntpd/gps/speed is unset or does not exist in $speeds
2233
	$gpsbaud = array_get_path($speeds, config_get_path('ntpd/gps/speed', 0), '4800');
2234

    
2235
	system_ntp_setup_rawspeed($serialport, $gpsbaud);
2236

    
2237
	$gpsspeed = config_get_path('ntpd/gps/speed');
2238
	$autospeed = ($gpsspeed == 'autoalways' || $gpsspeed == 'autoset');
2239
	if ($autospeed || (config_get_path('ntpd/gps/autobaudinit') && !check_gps_speed($gps_device))) {
2240
		$found = false;
2241
		foreach ($speeds as $baud) {
2242
			system_ntp_setup_rawspeed($serialport, $baud);
2243
			if ($found = check_gps_speed($gps_device)) {
2244
				if ($autospeed) {
2245
					$saveconfig = (config_get_path('ntpd/gps/speed') == 'autoset');
2246
					config_set_path('ntpd/gps/speed', array_search($baud, $speeds));
2247
					$gpsbaud = $baud;
2248
					if ($saveconfig) {
2249
						write_config(sprintf(gettext('Autoset GPS baud rate to %s'), $baud));
2250
					}
2251
				}
2252
				break;
2253
			}
2254
		}
2255
		if ($found === false) {
2256
			log_error(gettext("Could not find correct GPS baud rate."));
2257
			return false;
2258
		}
2259
	}
2260

    
2261
	/* Send the following to the GPS port to initialize the GPS */
2262
	if (!empty(config_get_path('ntpd/gps/type'))) {
2263
		$gps_init = base64_decode(config_get_path('ntpd/gps/initcmd'));
2264
	} else {
2265
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
2266
	}
2267

    
2268
	/* XXX: Why not file_put_contents to the device */
2269
	@file_put_contents('/tmp/gps.init', $gps_init);
2270
	mwexec("/bin/cat /tmp/gps.init > {$serialport}");
2271

    
2272
	if ($found && config_get_path('ntpd/gps/autobaudinit')) {
2273
		system_ntp_setup_rawspeed($serialport, $gpsbaud);
2274
	}
2275

    
2276
	/* Remove old /etc/remote entry if it exists */
2277
	if (mwexec("/usr/bin/grep -c '^gps0' /etc/remote") == 0) {
2278
		mwexec("/usr/bin/sed -i '' -n '/gps0/!p' /etc/remote");
2279
	}
2280

    
2281
	/* Add /etc/remote entry in case we need to read from the GPS with tip */
2282
	if (mwexec("/usr/bin/grep -c '^gps0' /etc/remote") != 0) {
2283
		@file_put_contents("/etc/remote", "gps0:dv={$serialport}:br#{$gpsbaud}:pa=none:\n", FILE_APPEND);
2284
	}
2285

    
2286
	return true;
2287
}
2288

    
2289
// Configure the serial port for raw IO and set the speed
2290
function system_ntp_setup_rawspeed($serialport, $baud) {
2291
	mwexec("/bin/stty -f " .  escapeshellarg($serialport) . " raw speed " . escapeshellarg($baud));
2292
	mwexec("/bin/stty -f " .  escapeshellarg($serialport) . ".init raw speed " . escapeshellarg($baud));
2293
}
2294

    
2295
function system_ntp_setup_pps($serialport) {
2296
	$serialports = get_serial_ports(true);
2297

    
2298
	if (!array_key_exists($serialport, $serialports)) {
2299
		return false;
2300
	}
2301

    
2302
	$pps_device = '/dev/pps0';
2303
	$serialport = '/dev/'.basename($serialport);
2304

    
2305
	if (!file_exists($serialport)) {
2306
		return false;
2307
	}
2308
	// If ntpd is disabled, just return
2309
	if (config_get_path('ntpd/enable') == 'disabled') {
2310
		return false;
2311
	}
2312

    
2313
	// Create symlink that ntpd requires
2314
	unlink_if_exists($pps_device);
2315
	@symlink($serialport, $pps_device);
2316

    
2317

    
2318
	return true;
2319
}
2320

    
2321
function system_ntp_configure() {
2322
	global $g;
2323
	global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
2324
	global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
2325
	global $ntp_poll_min_default, $ntp_poll_max_default;
2326

    
2327
	$driftfile = "/var/db/ntpd.drift";
2328
	$statsdir = "/var/log/ntp";
2329
	$gps_device = '/dev/gps0';
2330

    
2331
	safe_mkdir($statsdir);
2332

    
2333
	init_config_arr(array('ntpd'));
2334

    
2335
	// ntpd is disabled, just stop it and return
2336
	if (config_get_path('ntpd/enable') == 'disabled') {
2337
		while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
2338
			killbypid("{$g['varrun_path']}/ntpd.pid");
2339
		}
2340
		@unlink("{$g['varrun_path']}/ntpd.pid");
2341
		@unlink("{$g['varetc_path']}/ntpd.conf");
2342
		@unlink("{$g['varetc_path']}/ntp.keys");
2343
		log_error("NTPD is disabled.");
2344
		return;
2345
	}
2346

    
2347
	if (platform_booting()) {
2348
		echo gettext("Starting NTP Server...");
2349
	}
2350

    
2351
	/* if ntpd is running, kill it */
2352
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
2353
		killbypid("{$g['varrun_path']}/ntpd.pid");
2354
	}
2355
	@unlink("{$g['varrun_path']}/ntpd.pid");
2356

    
2357
	/* set NTP server authentication key */
2358
	if (config_get_path('ntpd/serverauth') == 'yes') {
2359
		$ntpkeyscfg = "1 " . strtoupper(config_get_path('ntpd/serverauthalgo')) . " " . base64_decode(config_get_path('ntpd/serverauthkey')) . "\n";
2360
		if (!@file_put_contents("{$g['varetc_path']}/ntp.keys", $ntpkeyscfg)) {
2361
			log_error(sprintf(gettext("Could not open %s/ntp.keys for writing"), g_get('varetc_path')));
2362
			return;
2363
		}
2364
	} else {
2365
		unlink_if_exists("{$g['varetc_path']}/ntp.keys");
2366
	}
2367

    
2368
	$ntpcfg = "# \n";
2369
	$ntpcfg .= "# pfSense ntp configuration file \n";
2370
	$ntpcfg .= "# \n\n";
2371
	$ntpcfg .= "tinker panic 0 \n\n";
2372

    
2373
	if (config_get_path('ntpd/serverauth') == 'yes') {
2374
		$ntpcfg .= "# Authentication settings \n";
2375
		$ntpcfg .= "keys /var/etc/ntp.keys \n";
2376
		$ntpcfg .= "trustedkey 1 \n";
2377
		$ntpcfg .= "requestkey 1 \n";
2378
		$ntpcfg .= "controlkey 1 \n";
2379
		$ntpcfg .= "\n";
2380
	}
2381

    
2382
	/* Add Orphan mode */
2383
	$ntpcfg .= "# Orphan mode stratum and Maximum candidate NTP peers\n";
2384
	$ntpcfg .= 'tos orphan ';
2385
	if (!empty(config_get_path('ntpd/orphan'))) {
2386
		$ntpcfg .= config_get_path('ntpd/orphan');
2387
	} else {
2388
		$ntpcfg .= '12';
2389
	}
2390
	/* Add Maximum candidate NTP peers */
2391
	$ntpcfg .= ' maxclock ';
2392
	if (!empty(config_get_path('ntpd/ntpmaxpeers'))) {
2393
		$ntpcfg .= config_get_path('ntpd/ntpmaxpeers');
2394
	} else {
2395
		$ntpcfg .= '5';
2396
	}
2397
	$ntpcfg .= "\n";
2398

    
2399
	/* Add PPS configuration */
2400
	if (!empty(config_get_path('ntpd/pps/port')) &&
2401
	    file_exists('/dev/'.config_get_path('ntpd/pps/port')) &&
2402
	    system_ntp_setup_pps(config_get_path('ntpd/pps/port'))) {
2403
		$ntpcfg .= "\n";
2404
		$ntpcfg .= "# PPS Setup\n";
2405
		$ntpcfg .= 'server 127.127.22.0';
2406
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', config_get_path('ntpd/pps/ppsminpoll'), $ntp_poll_min_default_pps);
2407
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', config_get_path('ntpd/pps/ppsmaxpoll'), $ntp_poll_max_default_pps);
2408
		if (empty(config_get_path('ntpd/pps/prefer'))) { /*note: this one works backwards */
2409
			$ntpcfg .= ' prefer';
2410
		}
2411
		if (!empty(config_get_path('ntpd/pps/noselect'))) {
2412
			$ntpcfg .= ' noselect ';
2413
		}
2414
		$ntpcfg .= "\n";
2415
		$ntpcfg .= 'fudge 127.127.22.0';
2416
		if (!empty(config_get_path('ntpd/pps/fudge1'))) {
2417
			$ntpcfg .= ' time1 ';
2418
			$ntpcfg .= config_get_path('ntpd/pps/fudge1');
2419
		}
2420
		if (!empty(config_get_path('ntpd/pps/flag2'))) {
2421
			$ntpcfg .= ' flag2 1';
2422
		}
2423
		if (!empty(config_get_path('ntpd/pps/flag3'))) {
2424
			$ntpcfg .= ' flag3 1';
2425
		} else {
2426
			$ntpcfg .= ' flag3 0';
2427
		}
2428
		if (!empty(config_get_path('ntpd/pps/flag4'))) {
2429
			$ntpcfg .= ' flag4 1';
2430
		}
2431
		if (!empty(config_get_path('ntpd/pps/refid'))) {
2432
			$ntpcfg .= ' refid ';
2433
			$ntpcfg .= config_get_path('ntpd/pps/refid');
2434
		}
2435
		$ntpcfg .= "\n";
2436
	}
2437
	/* End PPS configuration */
2438

    
2439
	/* Add GPS configuration */
2440
	if (!empty(config_get_path('ntpd/gps/port')) &&
2441
	    system_ntp_setup_gps(config_get_path('ntpd/gps/port'))) {
2442
		$ntpcfg .= "\n";
2443
		$ntpcfg .= "# GPS Setup\n";
2444
		$ntpcfg .= 'server 127.127.20.0 mode ';
2445
		if (!empty(config_get_path('ntpd/gps/nmea')) || !empty(config_get_path('ntpd/gps/speed')) || !empty(config_get_path('ntpd/gps/subsec')) || !empty(config_get_path('ntpd/gps/processpgrmf'))) {
2446
			if (!empty(config_get_path('ntpd/gps/nmea'))) {
2447
				$ntpmode = (int) config_get_path('ntpd/gps/nmea');
2448
			}
2449
			if (!empty(config_get_path('ntpd/gps/speed'))) {
2450
				$ntpmode += (int) config_get_path('ntpd/gps/speed');
2451
			}
2452
			if (!empty(config_get_path('ntpd/gps/subsec'))) {
2453
				$ntpmode += 128;
2454
			}
2455
			if (!empty(config_get_path('ntpd/gps/processpgrmf'))) {
2456
				$ntpmode += 256;
2457
			}
2458
			$ntpcfg .= (string) $ntpmode;
2459
		} else {
2460
			$ntpcfg .= '0';
2461
		}
2462
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', config_get_path('ntpd/gps/gpsminpoll'), $ntp_poll_min_default_gps);
2463
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', config_get_path('ntpd/gps/gpsmaxpoll'), $ntp_poll_max_default_gps);
2464

    
2465
		if (empty(config_get_path('ntpd/gps/prefer'))) { /*note: this one works backwards */
2466
			$ntpcfg .= ' prefer';
2467
		}
2468
		if (!empty(config_get_path('ntpd/gps/noselect'))) {
2469
			$ntpcfg .= ' noselect ';
2470
		}
2471
		$ntpcfg .= "\n";
2472
		$ntpcfg .= 'fudge 127.127.20.0';
2473
		if (!empty(config_get_path('ntpd/gps/fudge1'))) {
2474
			$ntpcfg .= ' time1 ';
2475
			$ntpcfg .= config_get_path('ntpd/gps/fudge1');
2476
		}
2477
		if (!empty(config_get_path('ntpd/gps/fudge2'))) {
2478
			$ntpcfg .= ' time2 ';
2479
			$ntpcfg .= config_get_path('ntpd/gps/fudge2');
2480
		}
2481
		if (!empty(config_get_path('ntpd/gps/flag1'))) {
2482
			$ntpcfg .= ' flag1 1';
2483
		} else {
2484
			$ntpcfg .= ' flag1 0';
2485
		}
2486
		if (!empty(config_get_path('ntpd/gps/flag2'))) {
2487
			$ntpcfg .= ' flag2 1';
2488
		}
2489
		if (!empty(config_get_path('ntpd/gps/flag3'))) {
2490
			$ntpcfg .= ' flag3 1';
2491
		} else {
2492
			$ntpcfg .= ' flag3 0';
2493
		}
2494
		if (!empty(config_get_path('ntpd/gps/flag4'))) {
2495
			$ntpcfg .= ' flag4 1';
2496
		}
2497
		if (!empty(config_get_path('ntpd/gps/refid'))) {
2498
			$ntpcfg .= ' refid ';
2499
			$ntpcfg .= config_get_path('ntpd/gps/refid');
2500
		}
2501
		if (!empty(config_get_path('ntpd/gps/stratum'))) {
2502
			$ntpcfg .= ' stratum ';
2503
			$ntpcfg .= config_get_path('ntpd/gps/stratum');
2504
		}
2505
		$ntpcfg .= "\n";
2506
	} elseif (system_ntp_setup_gps(config_get_path('ntpd/gpsport'))) {
2507
		/* This handles a 2.1 and earlier config */
2508
		$ntpcfg .= "# GPS Setup\n";
2509
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
2510
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
2511
		// Fall back to local clock if GPS is out of sync?
2512
		$ntpcfg .= "server 127.127.1.0\n";
2513
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
2514
	}
2515
	/* End GPS configuration */
2516
	$auto_pool_suffix = "pool.ntp.org";
2517
	$have_pools = false;
2518
	$ntpcfg .= "\n\n# Upstream Servers\n";
2519
	/* foreach through ntp servers and write out to ntpd.conf */
2520
	foreach (explode(' ', config_get_path('system/timeservers')) as $ts) {
2521
		if (empty($ts)) {
2522
			continue;
2523
		}
2524
		if ((substr_compare($ts, $auto_pool_suffix, strlen($ts) - strlen($auto_pool_suffix), strlen($auto_pool_suffix)) === 0)
2525
		    || substr_count(config_get_path('ntpd/ispool'), $ts)) {
2526
			$ntpcfg .= 'pool ';
2527
			$have_pools = true;
2528
		} else {
2529
			if (substr_count(config_get_path('ntpd/ispeer'), $ts)) {
2530
				$ntpcfg .= 'peer ';
2531
			} else {
2532
				$ntpcfg .= 'server ';
2533
			}
2534
			if (config_get_path('ntpd/dnsresolv') == 'inet') {
2535
				$ntpcfg .= '-4 ';
2536
			} elseif (config_get_path('ntpd/dnsresolv') == 'inet6') {
2537
				$ntpcfg .= '-6 ';
2538
			}
2539
		}
2540

    
2541
		$ntpcfg .= "{$ts}";
2542
		if (!substr_count(config_get_path('ntpd/ispeer'), $ts)) {
2543
			$ntpcfg .= " iburst";
2544
		}
2545

    
2546
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', config_get_path('ntpd/ntpminpoll'), $ntp_poll_min_default);
2547
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', config_get_path('ntpd/ntpmaxpoll'), $ntp_poll_max_default);
2548

    
2549
		if (substr_count(config_get_path('ntpd/prefer'), $ts)) {
2550
			$ntpcfg .= ' prefer';
2551
		}
2552
		if (substr_count(config_get_path('ntpd/noselect'), $ts)) {
2553
			$ntpcfg .= ' noselect';
2554
		}
2555
		$ntpcfg .= "\n";
2556
	}
2557
	unset($ts);
2558

    
2559
	$ntpcfg .= "\n\n";
2560
	if (!empty(config_get_path('ntpd/clockstats')) || !empty(config_get_path('ntpd/loopstats')) || !empty(config_get_path('ntpd/peerstats'))) {
2561
		$ntpcfg .= "enable stats\n";
2562
		$ntpcfg .= 'statistics';
2563
		if (!empty(config_get_path('ntpd/clockstats'))) {
2564
			$ntpcfg .= ' clockstats';
2565
		}
2566
		if (!empty(config_get_path('ntpd/loopstats'))) {
2567
			$ntpcfg .= ' loopstats';
2568
		}
2569
		if (!empty(config_get_path('ntpd/peerstats'))) {
2570
			$ntpcfg .= ' peerstats';
2571
		}
2572
		$ntpcfg .= "\n";
2573
	}
2574
	$ntpcfg .= "statsdir {$statsdir}\n";
2575
	$ntpcfg .= 'logconfig =syncall +clockall';
2576
	if (!empty(config_get_path('ntpd/logpeer'))) {
2577
		$ntpcfg .= ' +peerall';
2578
	}
2579
	if (!empty(config_get_path('ntpd/logsys'))) {
2580
		$ntpcfg .= ' +sysall';
2581
	}
2582
	$ntpcfg .= "\n";
2583
	$ntpcfg .= "driftfile {$driftfile}\n";
2584

    
2585
	/* Default Access restrictions */
2586
	$ntpcfg .= 'restrict default';
2587
	if (empty(config_get_path('ntpd/kod'))) { /*note: this one works backwards */
2588
		$ntpcfg .= ' kod limited';
2589
	}
2590
	if (empty(config_get_path('ntpd/nomodify'))) { /*note: this one works backwards */
2591
		$ntpcfg .= ' nomodify';
2592
	}
2593
	if (!empty(config_get_path('ntpd/noquery'))) {
2594
		$ntpcfg .= ' noquery';
2595
	}
2596
	if (empty(config_get_path('ntpd/nopeer'))) { /*note: this one works backwards */
2597
		$ntpcfg .= ' nopeer';
2598
	}
2599
	if (empty(config_get_path('ntpd/notrap'))) { /*note: this one works backwards */
2600
		$ntpcfg .= ' notrap';
2601
	}
2602
	if (!empty(config_get_path('ntpd/noserve'))) {
2603
		$ntpcfg .= ' noserve';
2604
	}
2605
	$ntpcfg .= "\nrestrict -6 default";
2606
	if (empty(config_get_path('ntpd/kod'))) { /*note: this one works backwards */
2607
		$ntpcfg .= ' kod limited';
2608
	}
2609
	if (empty(config_get_path('ntpd/nomodify'))) { /*note: this one works backwards */
2610
		$ntpcfg .= ' nomodify';
2611
	}
2612
	if (!empty(config_get_path('ntpd/noquery'))) {
2613
		$ntpcfg .= ' noquery';
2614
	}
2615
	if (empty(config_get_path('ntpd/nopeer'))) { /*note: this one works backwards */
2616
		$ntpcfg .= ' nopeer';
2617
	}
2618
	if (!empty(config_get_path('ntpd/noserve'))) {
2619
		$ntpcfg .= ' noserve';
2620
	}
2621
	if (empty(config_get_path('ntpd/notrap'))) { /*note: this one works backwards */
2622
		$ntpcfg .= ' notrap';
2623
	}
2624

    
2625
	/* Pools require "restrict source" and cannot contain "nopeer" and "noserve". */
2626
	if ($have_pools) {
2627
		$ntpcfg .= "\nrestrict source";
2628
		if (empty(config_get_path('ntpd/kod'))) { /*note: this one works backwards */
2629
			$ntpcfg .= ' kod limited';
2630
		}
2631
		if (empty(config_get_path('ntpd/nomodify'))) { /*note: this one works backwards */
2632
			$ntpcfg .= ' nomodify';
2633
		}
2634
		if (!empty(config_get_path('ntpd/noquery'))) {
2635
			$ntpcfg .= ' noquery';
2636
		}
2637
		if (empty(config_get_path('ntpd/notrap'))) { /*note: this one works backwards */
2638
			$ntpcfg .= ' notrap';
2639
		}
2640
	}
2641

    
2642
	/* Custom Access Restrictions */
2643
	if (is_array(config_get_path('ntpd/restrictions/row'))) {
2644
		$networkacl = config_get_path('ntpd/restrictions/row');
2645
		foreach ($networkacl as $acl) {
2646
			$restrict = "";
2647
			if (is_ipaddrv6($acl['acl_network'])) {
2648
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask_v6($acl['mask']) . " ";
2649
			} elseif (is_ipaddrv4($acl['acl_network'])) {
2650
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask($acl['mask']) . " ";
2651
			} else {
2652
				continue;
2653
			}
2654
			if (!empty($acl['kod'])) {
2655
				$restrict .= ' kod limited';
2656
			}
2657
			if (!empty($acl['nomodify'])) {
2658
				$restrict .= ' nomodify';
2659
			}
2660
			if (!empty($acl['noquery'])) {
2661
				$restrict .= ' noquery';
2662
			}
2663
			if (!empty($acl['nopeer'])) {
2664
				$restrict .= ' nopeer';
2665
			}
2666
			if (!empty($acl['noserve'])) {
2667
				$restrict .= ' noserve';
2668
			}
2669
			if (!empty($acl['notrap'])) {
2670
				$restrict .= ' notrap';
2671
			}
2672
			if (!empty($restrict)) {
2673
				$ntpcfg .= "\nrestrict {$restrict} ";
2674
			}
2675
		}
2676
	}
2677
	/* End Custom Access Restrictions */
2678

    
2679
	/* A leapseconds file is really only useful if this clock is stratum 1 */
2680
	$ntpcfg .= "\n";
2681
	if (!empty(config_get_path('ntpd/leapsec'))) {
2682
		$leapsec .= base64_decode(config_get_path('ntpd/leapsec'));
2683
		file_put_contents('/var/db/leap-seconds', $leapsec);
2684
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
2685
	}
2686

    
2687

    
2688
	if (empty(config_get_path('ntpd/interface'))) {
2689
		$interfaces =
2690
			explode(",",
2691
					config_get_path('installedpackages/openntpd/config/0/interface', ''));
2692
	} else {
2693
		$interfaces = explode(",", config_get_path('ntpd/interface'));
2694
	}
2695

    
2696
	if (is_array($interfaces) && count($interfaces)) {
2697
		$finterfaces = array();
2698
		foreach ($interfaces as $interface) {
2699
			$interface = get_real_interface($interface);
2700
			if (!empty($interface)) {
2701
				$finterfaces[] = $interface;
2702
			}
2703
		}
2704
		if (!empty($finterfaces)) {
2705
			$ntpcfg .= "interface ignore all\n";
2706
			$ntpcfg .= "interface ignore wildcard\n";
2707
			foreach ($finterfaces as $interface) {
2708
				$ntpcfg .= "interface listen {$interface}\n";
2709
			}
2710
		}
2711
	}
2712

    
2713
	/* open configuration for writing or bail */
2714
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
2715
		log_error(sprintf(gettext("Could not open %s/ntpd.conf for writing"), g_get('varetc_path')));
2716
		return;
2717
	}
2718

    
2719
	/* if /var/empty does not exist, create it */
2720
	if (!is_dir("/var/empty")) {
2721
		mkdir("/var/empty", 0555, true);
2722
	}
2723

    
2724
	/* start ntpd, set time now and use /var/etc/ntpd.conf */
2725
	mwexec("/usr/local/sbin/ntpd -g -c {$g['varetc_path']}/ntpd.conf -p {$g['varrun_path']}/ntpd.pid", false, true);
2726

    
2727
	// Note that we are starting up
2728
	log_error("NTPD is starting up.");
2729

    
2730
	if (platform_booting()) {
2731
		echo gettext("done.") . "\n";
2732
	}
2733

    
2734
	return;
2735
}
2736

    
2737
function system_halt() {
2738
	global $g;
2739

    
2740
	system_reboot_cleanup();
2741

    
2742
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
2743
}
2744

    
2745
function system_reboot() {
2746
	global $g;
2747

    
2748
	system_reboot_cleanup();
2749

    
2750
	mwexec("/usr/bin/nohup /etc/rc.reboot > /dev/null 2>&1 &");
2751
}
2752

    
2753
function system_reboot_sync($reroot=false) {
2754
	global $g;
2755

    
2756
	if ($reroot) {
2757
		$args = " -r ";
2758
	}
2759

    
2760
	system_reboot_cleanup();
2761

    
2762
	mwexec("/etc/rc.reboot {$args} > /dev/null 2>&1");
2763
}
2764

    
2765
function system_reboot_cleanup() {
2766
	global $g, $cpzone;
2767

    
2768
	mwexec("/usr/local/bin/beep.sh stop");
2769
	require_once("captiveportal.inc");
2770
	$cps = config_get_path('captiveportal', []);
2771
	foreach ($cps as $cpzone=>$cp) {
2772
		if (!isset($cp['preservedb'])) {
2773
			/* send Accounting-Stop packet for all clients, termination cause 'Admin-Reboot' */
2774
			captiveportal_radius_stop_all(7); // Admin-Reboot
2775
			unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
2776
			captiveportal_free_dnrules();
2777
		}
2778
		/* Send Accounting-Off packet to the RADIUS server */
2779
		captiveportal_send_server_accounting('off');
2780
	}
2781

    
2782
	if (count($cps)> 0) {
2783
		/* Remove the pipe database */
2784
		unlink_if_exists("{$g['vardb_path']}/captiveportaldn.rules");
2785
	}
2786

    
2787
	require_once("voucher.inc");
2788
	voucher_save_db_to_config();
2789
	require_once("pfsense-utils.inc");
2790
	enable_carp(false);
2791
	require_once("pkg-utils.inc");
2792
	stop_packages();
2793
}
2794

    
2795
function system_do_shell_commands($early = 0) {
2796
	if (config_path_enabled('system', 'developerspew')) {
2797
		$mt = microtime();
2798
		echo "system_do_shell_commands() being called $mt\n";
2799
	}
2800

    
2801
	if ($early) {
2802
		$cmdn = "earlyshellcmd";
2803
	} else {
2804
		$cmdn = "shellcmd";
2805
	}
2806

    
2807
	$syscmd = config_get_path("system/{$cmdn}", '');
2808
	if (is_array($syscmd)) {
2809
		/* *cmd is an array, loop through */
2810
		foreach ($syscmd as $cmd) {
2811
			exec($cmd);
2812
		}
2813

    
2814
	} elseif ($syscmd <> "") {
2815
		/* execute single item */
2816
		exec($syscmd);
2817

    
2818
	}
2819
}
2820

    
2821
function system_dmesg_save() {
2822
	global $g;
2823
	if (config_path_enabled('system', 'developerspew')) {
2824
		$mt = microtime();
2825
		echo "system_dmesg_save() being called $mt\n";
2826
	}
2827

    
2828
	$dmesg = "";
2829
	$_gb = exec("/sbin/dmesg", $dmesg);
2830

    
2831
	/* find last copyright line (output from previous boots may be present) */
2832
	$lastcpline = 0;
2833

    
2834
	for ($i = 0; $i < count($dmesg); $i++) {
2835
		if (strstr($dmesg[$i], "Copyright (c) 1992-")) {
2836
			$lastcpline = $i;
2837
		}
2838
	}
2839

    
2840
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
2841
	if (!$fd) {
2842
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
2843
		return 1;
2844
	}
2845

    
2846
	for ($i = $lastcpline; $i < count($dmesg); $i++) {
2847
		fwrite($fd, $dmesg[$i] . "\n");
2848
	}
2849

    
2850
	fclose($fd);
2851
	unset($dmesg);
2852

    
2853
	// vm-bhyve expects dmesg.boot at the standard location
2854
	@symlink("{$g['varlog_path']}/dmesg.boot", "{$g['varrun_path']}/dmesg.boot");
2855

    
2856
	return 0;
2857
}
2858

    
2859
function system_set_harddisk_standby() {
2860
	if (config_path_enabled('system', 'developerspew')) {
2861
		$mt = microtime();
2862
		echo "system_set_harddisk_standby() being called $mt\n";
2863
	}
2864

    
2865
	if (config_path_enabled('system', 'harddiskstandby')) {
2866
		if (platform_booting()) {
2867
			echo gettext('Setting hard disk standby... ');
2868
		}
2869

    
2870
		$standby = config_get_path('system/harddiskstandby');
2871
		// Check for a numeric value
2872
		if (is_numeric($standby)) {
2873
			// Get only suitable candidates for standby; using get_smart_drive_list()
2874
			// from utils.inc to get the list of drives.
2875
			$harddisks = get_smart_drive_list();
2876

    
2877
			// Since get_smart_drive_list() only matches ad|da|ada; lets put the check below
2878
			// just in case of some weird pfSense platform installs.
2879
			if (count($harddisks) > 0) {
2880
				// Iterate disks and run the camcontrol command for each
2881
				foreach ($harddisks as $harddisk) {
2882
					mwexec("/sbin/camcontrol standby {$harddisk} -t {$standby}");
2883
				}
2884
				if (platform_booting()) {
2885
					echo gettext("done.") . "\n";
2886
				}
2887
			} else if (platform_booting()) {
2888
				echo gettext("failed!") . "\n";
2889
			}
2890
		} else if (platform_booting()) {
2891
			echo gettext("failed!") . "\n";
2892
		}
2893
	}
2894
}
2895

    
2896
function system_setup_sysctl() {
2897
	if (config_path_enabled('system', 'developerspew')) {
2898
		$mt = microtime();
2899
		echo "system_setup_sysctl() being called $mt\n";
2900
	}
2901

    
2902
	activate_sysctls();
2903

    
2904
	if (config_path_enabled('system', 'sharednet')) {
2905
		system_disable_arp_wrong_if();
2906
	}
2907
}
2908

    
2909
function system_disable_arp_wrong_if() {
2910
	if (config_path_enabled('system', 'developerspew')) {
2911
		$mt = microtime();
2912
		echo "system_disable_arp_wrong_if() being called $mt\n";
2913
	}
2914
	set_sysctl(array(
2915
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
2916
		"net.link.ether.inet.log_arp_movements" => "0"
2917
	));
2918
}
2919

    
2920
function system_enable_arp_wrong_if() {
2921
	if (config_path_enabled('system', 'developerspew')) {
2922
		$mt = microtime();
2923
		echo "system_enable_arp_wrong_if() being called $mt\n";
2924
	}
2925
	set_sysctl(array(
2926
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
2927
		"net.link.ether.inet.log_arp_movements" => "1"
2928
	));
2929
}
2930

    
2931
function enable_watchdog() {
2932
	return;
2933
	$install_watchdog = false;
2934
	$supported_watchdogs = array("Geode");
2935
	$file = file_get_contents("/var/log/dmesg.boot");
2936
	foreach ($supported_watchdogs as $sd) {
2937
		if (stristr($file, "Geode")) {
2938
			$install_watchdog = true;
2939
		}
2940
	}
2941
	if ($install_watchdog == true) {
2942
		if (is_process_running("watchdogd")) {
2943
			mwexec("/usr/bin/killall watchdogd", true);
2944
		}
2945
		exec("/usr/sbin/watchdogd");
2946
	}
2947
}
2948

    
2949
function system_check_reset_button() {
2950
	global $g;
2951

    
2952
	$specplatform = system_identify_specific_platform();
2953

    
2954
	switch ($specplatform['name']) {
2955
		case 'SG-2220':
2956
			$binprefix = "RCC-DFF";
2957
			break;
2958
		case 'alix':
2959
		case 'wrap':
2960
		case 'FW7541':
2961
		case 'APU':
2962
		case 'RCC-VE':
2963
		case 'RCC':
2964
			$binprefix = $specplatform['name'];
2965
			break;
2966
		default:
2967
			return 0;
2968
	}
2969

    
2970
	$retval = mwexec("/usr/local/sbin/" . $binprefix . "resetbtn");
2971

    
2972
	if ($retval == 99) {
2973
		/* user has pressed reset button for 2 seconds -
2974
		   reset to factory defaults */
2975
		echo <<<EOD
2976

    
2977
***********************************************************************
2978
* Reset button pressed - resetting configuration to factory defaults. *
2979
* All additional packages installed will be removed                   *
2980
* The system will reboot after this completes.                        *
2981
***********************************************************************
2982

    
2983

    
2984
EOD;
2985

    
2986
		reset_factory_defaults();
2987
		system_reboot_sync();
2988
		exit(0);
2989
	}
2990

    
2991
	return 0;
2992
}
2993

    
2994
function system_get_serial() {
2995
	$platform = system_identify_specific_platform();
2996

    
2997
	unset($output);
2998
	if ($platform['name'] == 'Turbot Dual-E') {
2999
		$if_info = get_interface_addresses('igb0');
3000
		if (!empty($if_info['hwaddr'])) {
3001
			$serial = str_replace(":", "", $if_info['hwaddr']);
3002
		}
3003
	} else {
3004
		foreach (array('system', 'planar', 'chassis') as $key) {
3005
			unset($output);
3006
			$_gb = exec("/bin/kenv -q smbios.{$key}.serial",
3007
			    $output);
3008
			if (!empty($output[0]) && $output[0] != "0123456789" &&
3009
			    preg_match('/^[\w\d]{10,16}$/', $output[0]) === 1) {
3010
				$serial = $output[0];
3011
				break;
3012
			}
3013
		}
3014
	}
3015

    
3016
	$vm_guest = get_single_sysctl('kern.vm_guest');
3017

    
3018
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
3019
	    $vm_guest == 'none') {
3020
		return $serial;
3021
	}
3022

    
3023
	return "";
3024
}
3025

    
3026
function system_get_uniqueid() {
3027
	global $g;
3028

    
3029
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
3030

    
3031
	if (empty(g_get('uniqueid'))) {
3032
		if (!file_exists($uniqueid_file)) {
3033
			mwexec("/usr/sbin/gnid > {$g['vardb_path']}/uniqueid " .
3034
			    "2>/dev/null");
3035
		}
3036
		if (file_exists($uniqueid_file)) {
3037
			$g['uniqueid'] = @file_get_contents($uniqueid_file);
3038
		}
3039
	}
3040

    
3041
	return (g_get('uniqueid') ?: '');
3042
}
3043

    
3044
/*
3045
 * attempt to identify the specific platform (for embedded systems)
3046
 * Returns an array with two elements:
3047
 * name => platform string (e.g. 'wrap', 'alix' etc.)
3048
 * descr => human-readable description (e.g. "PC Engines WRAP")
3049
 */
3050
function system_identify_specific_platform() {
3051
	global $g;
3052

    
3053
	$hw_model = get_single_sysctl('hw.model');
3054
	$hw_ncpu = get_single_sysctl('hw.ncpu');
3055

    
3056
	/* Try to guess from smbios strings */
3057
	unset($product);
3058
	unset($maker);
3059
	unset($bios);
3060
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $product);
3061
	$_gb = exec('/bin/kenv -q smbios.system.maker 2>/dev/null', $maker);
3062
	$_gb = exec('/bin/kenv -q smbios.bios.version 2>/dev/null', $bios);
3063

    
3064
	$vm = get_single_sysctl('kern.vm_guest');
3065
	// Google GCP and newer AWS instances return kvm from this so we must detect them first.
3066

    
3067
	if ($maker[0] == "QEMU") {
3068
		return (array('name' => 'QEMU', 'descr' => 'QEMU Guest'));
3069
	} else  if ($maker[0] == "Google") {
3070
		return (array('name' => 'Google', 'descr' => 'Google Cloud Platform'));
3071
	} else  if ($maker[0] == "Amazon EC2") {
3072
		return (array('name' => 'AWS', 'descr' => 'Amazon Web Services'));
3073
	}
3074

    
3075
	// This switch needs to be expanded to include other virtualization systems
3076
	switch ($vm) {
3077
		case "none" :
3078
		break;
3079

    
3080
		case "kvm" :
3081
			return (array('name' => 'KVM', 'descr' => 'KVM Guest'));
3082
		break;
3083
	}
3084

    
3085
	// AWS and GCP can also be identified via the bios version
3086
	if (stripos($bios[0], "amazon") !== false) {
3087
		return (array('name' => 'AWS', 'descr' => 'Amazon Web Services'));
3088
	} else  if (stripos($bios[0], "Google") !== false) {
3089
		return (array('name' => 'Google', 'descr' => 'Google Cloud Platform'));
3090
	}
3091

    
3092
	switch ($product[0]) {
3093
		case 'FW7541':
3094
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
3095
			break;
3096
		case 'apu1':
3097
		case 'APU':
3098
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
3099
			break;
3100
		case 'RCC-VE':
3101
			$result = array();
3102
			$result['name'] = 'RCC-VE';
3103

    
3104
			/* Detect specific models */
3105
			if (!function_exists('does_interface_exist')) {
3106
				require_once("interfaces.inc");
3107
			}
3108
			if (!does_interface_exist('igb4')) {
3109
				$result['model'] = 'SG-2440';
3110
			} elseif (strpos($hw_model, "C2558") !== false) {
3111
				$result['model'] = 'SG-4860';
3112
			} elseif (strpos($hw_model, "C2758") !== false) {
3113
				$result['model'] = 'SG-8860';
3114
			} else {
3115
				$result['model'] = 'RCC-VE';
3116
			}
3117
			$result['descr'] = 'Netgate ' . $result['model'];
3118
			return $result;
3119
			break;
3120
		case 'DFFv2':
3121
			return (array('name' => 'SG-2220', 'descr' => 'Netgate SG-2220'));
3122
			break;
3123
		case 'RCC':
3124
			return (array('name' => 'RCC', 'descr' => 'Netgate XG-2758'));
3125
			break;
3126
		case 'SG-5100':
3127
			return (array('name' => '5100', 'descr' => 'Netgate 5100'));
3128
			break;
3129
		case 'Minnowboard Turbot D0 PLATFORM':
3130
		case 'Minnowboard Turbot D0/D1 PLATFORM':
3131
			$result = array();
3132
			$result['name'] = 'Turbot Dual-E';
3133
			/* Ensure the graphics driver is loaded */
3134
			system("kldload -nq i915kms");
3135
			/* Detect specific model */
3136
			switch ($hw_ncpu) {
3137
			case '4':
3138
				$result['model'] = 'MBT-4220';
3139
				break;
3140
			case '2':
3141
				$result['model'] = 'MBT-2220';
3142
				break;
3143
			default:
3144
				$result['model'] = $result['name'];
3145
				break;
3146
			}
3147
			$result['descr'] = 'Netgate ' . $result['model'];
3148
			return $result;
3149
			break;
3150
		case 'SYS-5018A-FTN4':
3151
		case 'A1SAi':
3152
			if (strpos($hw_model, "C2558") !== false) {
3153
				return (array(
3154
				    'name' => 'C2558',
3155
				    'descr' => 'Super Micro C2558'));
3156
			} elseif (strpos($hw_model, "C2758") !== false) {
3157
				return (array(
3158
				    'name' => 'C2758',
3159
				    'descr' => 'Super Micro C2758'));
3160
			}
3161
			break;
3162
		case 'SYS-5018D-FN4T':
3163
			if (strpos($hw_model, "D-1541") !== false) {
3164
				return (array('name' => '1541', 'descr' => 'Super Micro 1541'));
3165
			} else {
3166
				return (array('name' => '1540', 'descr' => 'Super Micro XG-1540'));
3167
			}
3168
			break;
3169
		case 'APU2':
3170
		case 'apu2':
3171
		case 'apu3':
3172
		case 'apu4':
3173
		case 'apu5':
3174
		case 'apu6':
3175
		case 'apu7':
3176
			return (array('name' => 'apu2', 'descr' => "PC Engines APU2 Platform (\"{$product[0]}\" model)"));
3177
			break;
3178
		case 'VirtualBox':
3179
			return (array('name' => 'VirtualBox', 'descr' => 'VirtualBox Virtual Machine'));
3180
			break;
3181
		case 'Virtual Machine':
3182
			if ($maker[0] == "Microsoft Corporation") {
3183
				if (stripos($bios[0], "Hyper") !== false) {
3184
					return (array('name' => 'Hyper-V', 'descr' => 'Hyper-V Virtual Machine'));
3185
				} else {
3186
					return (array('name' => 'Azure', 'descr' => 'Microsoft Azure'));
3187
				}
3188
			}
3189
			break;
3190
		case 'VMware Virtual Platform':
3191
			if ($maker[0] == "VMware, Inc.") {
3192
				return (array('name' => 'VMware', 'descr' => 'VMware Virtual Machine'));
3193
			}
3194
			break;
3195
	}
3196

    
3197
	$_gb = exec('/bin/kenv -q smbios.planar.product 2>/dev/null',
3198
	    $planar_product);
3199
	if (isset($planar_product[0]) &&
3200
	    $planar_product[0] == 'X10SDV-8C-TLN4F+') {
3201
		return array('name' => '1537', 'descr' => 'Super Micro 1537');
3202
	}
3203

    
3204
	if (strpos($hw_model, "PC Engines WRAP") !== false) {
3205
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
3206
	}
3207

    
3208
	if (strpos($hw_model, "PC Engines ALIX") !== false) {
3209
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
3210
	}
3211

    
3212
	if (preg_match("/Soekris net45../", $hw_model, $matches)) {
3213
		return array('name' => 'net45xx', 'descr' => $matches[0]);
3214
	}
3215

    
3216
	if (preg_match("/Soekris net48../", $hw_model, $matches)) {
3217
		return array('name' => 'net48xx', 'descr' => $matches[0]);
3218
	}
3219

    
3220
	if (preg_match("/Soekris net55../", $hw_model, $matches)) {
3221
		return array('name' => 'net55xx', 'descr' => $matches[0]);
3222
	}
3223

    
3224
	unset($hw_model);
3225

    
3226
	$dmesg_boot = system_get_dmesg_boot();
3227
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
3228
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
3229
	}
3230
	unset($dmesg_boot);
3231

    
3232
	return array('name' => g_get('product_name'), 'descr' => g_get('product_label'));
3233
}
3234

    
3235
function system_get_dmesg_boot() {
3236
	global $g;
3237

    
3238
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
3239
}
3240

    
3241
function system_get_arp_table($resolve_hostnames = false) {
3242
	$params="-a";
3243
	if (!$resolve_hostnames) {
3244
		$params .= "n";
3245
	}
3246

    
3247
	$arp_table = array();
3248
	$_gb = exec("/usr/sbin/arp --libxo json {$params}", $rawdata, $rc);
3249
	if ($rc == 0) {
3250
		$arp_table = json_decode(implode(" ", $rawdata),
3251
		    JSON_OBJECT_AS_ARRAY);
3252
		if ($rc == 0) {
3253
			$arp_table = $arp_table['arp']['arp-cache'];
3254
		}
3255
	}
3256

    
3257
	return $arp_table;
3258
}
3259

    
3260
function _getHostName($mac, $ip) {
3261
	global $dhcpmac, $dhcpip;
3262

    
3263
	if ($dhcpmac[$mac]) {
3264
		return $dhcpmac[$mac];
3265
	} else if ($dhcpip[$ip]) {
3266
		return $dhcpip[$ip];
3267
	} else {
3268
		exec("/usr/bin/host -W 1 " . escapeshellarg($ip), $output);
3269
		if (preg_match('/.*pointer ([A-Za-z_0-9.-]+)\..*/', $output[0], $matches)) {
3270
			if ($matches[1] <> $ip) {
3271
				return $matches[1];
3272
			}
3273
		}
3274
	}
3275
	return "";
3276
}
3277

    
3278
function check_dnsavailable($proto='inet') {
3279

    
3280
	if ($proto == 'inet') {
3281
		$gdns = array('8.8.8.8', '8.8.4.4');
3282
	} elseif ($proto == 'inet6') {
3283
		$gdns = array('2001:4860:4860::8888', '2001:4860:4860::8844');
3284
	} else {
3285
		$gdns = array('8.8.8.8', '8.8.4.4', '2001:4860:4860::8888', '2001:4860:4860::8844');
3286
	}
3287
	$nameservers = array_merge($gdns, get_dns_nameservers());
3288
	$test = 0;
3289

    
3290
	foreach ($gdns as $dns) {
3291
		if ($dns == '127.0.0.1') {
3292
			continue;
3293
		} else {
3294
			$dns_result = trim(_getHostName("", $dns));
3295
			if (($test == '2') && ($dns_result == "")) {
3296
				return false;
3297
			} elseif ($dns_result == "") {
3298
				$test++;
3299
				continue;
3300
			} else {
3301
				return true;
3302
			}
3303
		}
3304
	}
3305

    
3306
	return false;
3307
}
3308

    
3309
?>
(50-50/61)