Project

General

Profile

Download (87.1 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-2024 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
	if ($dnsavailable === null) {
1217
		$dnsavailable = get_dnsavailable();
1218
	}
1219
	foreach ($leases_content as $line) {
1220
		/* Skip comments */
1221
		if (preg_match('/^\s*(|#.*)$/', $line)) {
1222
			continue;
1223
		}
1224

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

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

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

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

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

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

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

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

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

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

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

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

    
1359
	return $leases;
1360
}
1361

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

    
1368
	$syscfg = config_get_path('system');
1369

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

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

    
1377
	return $status;
1378
}
1379

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

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

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

    
1403
	system_staticroutes_configure($interface, false);
1404

    
1405
	return 0;
1406
}
1407

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

    
1411
	$filterdns_list = array();
1412

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

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

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

    
1434
			$gatewayip = $gateway['gateway'];
1435
			$interfacegw = $gateway['interface'];
1436

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

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

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

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

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

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

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

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

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

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

    
1568
	return 0;
1569
}
1570

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

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

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

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

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

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

    
1614
	unset($targets);
1615
}
1616

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

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

    
1628
	return;
1629
}
1630

    
1631
function system_webgui_start() {
1632
	global $g;
1633

    
1634
	if (platform_booting()) {
1635
		echo gettext("Starting webConfigurator...");
1636
	}
1637

    
1638
	chdir(g_get('www_path'));
1639

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

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

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

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

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

    
1675
	sleep(1);
1676

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

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

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

    
1690
	return $res;
1691
}
1692

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

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

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

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

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

    
1764
	global $g;
1765

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

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

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

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

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

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

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

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

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

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

    
1836
EOD;
1837

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

    
1845
	$nginx_config .= <<<EOD
1846

    
1847
events {
1848
    worker_connections  1024;
1849
}
1850

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

    
1857
	sendfile        off;
1858

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

    
1861
EOD;
1862

    
1863
	if ($captive_portal !== false) {
1864
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1865
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1866
		$intercept_errors = "";
1867
	} else {
1868
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1869
		$nginx_config .= "\terror_page 404 /404.html;\n";
1870
		$nginx_config .= "\terror_page 500 502 503 504 /50x.html;\n";
1871
		$intercept_errors = "\t\t\tfastcgi_intercept_errors on;\n";
1872
	}
1873
	$nginx_config .= "\tclient_header_timeout 10;\n";
1874

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

    
1915
	$nginx_config .= <<<EOD
1916

    
1917
		client_max_body_size 200m;
1918

    
1919
		gzip on;
1920
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
1921

    
1922

    
1923
EOD;
1924

    
1925
	if ($captive_portal !== false) {
1926
		$nginx_config .= <<<EOD
1927
$captive_portal_maxprocperip
1928
$cp_hostcheck
1929
$cp_rewrite
1930
		log_not_found off;
1931

    
1932
EOD;
1933

    
1934
	}
1935

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

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

    
1984
EOD;
1985

    
1986
	$cert = str_replace("\r", "", $cert);
1987
	$key = str_replace("\r", "", $key);
1988

    
1989
	$cert = str_replace("\n\n", "\n", $cert);
1990
	$key = str_replace("\n\n", "\n", $key);
1991

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

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

    
2028
EOD;
2029
	}
2030

    
2031
	if ($captive_portal == false) {
2032
		$pluginparams = [ 'section' => 'server' ];
2033
		foreach (pkg_call_plugins('plugin_nginx', $pluginparams) as $pkgname => $server) {
2034
			if (empty($server)) {
2035
				continue;
2036
			}
2037
			$nginx_config .= "	# Plugin Servers ({$pkgname})\n";
2038
			$nginx_config .= "{$server}\n";
2039
		}
2040
	}
2041

    
2042
	$nginx_config .= "}\n";
2043

    
2044
	$fd = fopen("{$filename}", "w");
2045
	if (!$fd) {
2046
		printf(gettext('Error: cannot open %1$s in system_generate_nginx_config().%2$s'), $filename, "\n");
2047
		return 1;
2048
	}
2049
	fwrite($fd, $nginx_config);
2050
	fclose($fd);
2051

    
2052
	/* nginx will fail to start if this directory does not exist. */
2053
	safe_mkdir("/var/tmp/nginx/");
2054

    
2055
	return 0;
2056

    
2057
}
2058

    
2059
function system_get_timezone_list() {
2060
	global $g;
2061

    
2062
	$file_list = array_merge(
2063
		glob("/usr/share/zoneinfo/[A-Z]*"),
2064
		glob("/usr/share/zoneinfo/*/*"),
2065
		glob("/usr/share/zoneinfo/*/*/*")
2066
	);
2067

    
2068
	if (empty($file_list)) {
2069
		$file_list[] = g_get('default_timezone');
2070
	} else {
2071
		/* Remove directories from list */
2072
		$file_list = array_filter($file_list, function($v) {
2073
			return !is_dir($v);
2074
		});
2075
	}
2076

    
2077
	/* Remove directory prefix */
2078
	$file_list = str_replace('/usr/share/zoneinfo/', '', $file_list);
2079

    
2080
	sort($file_list);
2081

    
2082
	return $file_list;
2083
}
2084

    
2085
function system_timezone_configure() {
2086
	global $g;
2087
	if (config_path_enabled('system', 'developerspew')) {
2088
		$mt = microtime();
2089
		echo "system_timezone_configure() being called $mt\n";
2090
	}
2091

    
2092
	$syscfg = config_get_path('system');
2093

    
2094
	if (platform_booting()) {
2095
		echo gettext("Setting timezone...");
2096
	}
2097

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

    
2104
	if (platform_booting()) {
2105
		echo gettext("done.") . "\n";
2106
	}
2107
}
2108

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

    
2122
			// Wait for data to arive
2123
			if (($c === false) || (strlen($c) == 0)) {
2124
				usleep(500);
2125
				continue;
2126
			}
2127

    
2128
			$contents.=$c;
2129
			$cnt = $cnt + strlen($c);
2130
		} while (($cnt < $buffersize) && (microtime(true) < $timeout));
2131
		fclose($fp);
2132

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

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

    
2178
function system_ntp_poll_values() {
2179
	global $ntp_poll_min_value, $ntp_poll_max_value;
2180
	$poll_values = array("" => gettext('Default'));
2181

    
2182
	for ($i = $ntp_poll_min_value; $i <= $ntp_poll_max_value; $i++) {
2183
		$sec = 2 ** $i;
2184
		$poll_values[$i] = $i . ': ' . number_format($sec) . ' ' . gettext('seconds') .
2185
					' (' . convert_seconds_to_dhms($sec) . ')';
2186
	}
2187

    
2188
	$poll_values['omit'] = gettext('Omit (Do not set)');
2189
	return $poll_values;
2190
}
2191

    
2192
function system_ntp_fixup_poll_value($type, $configvalue, $default) {
2193
	$pollstring = "";
2194

    
2195
	if (empty($configvalue)) {
2196
		$configvalue = $default;
2197
	}
2198

    
2199
	if ($configvalue != 'omit') {
2200
		$pollstring = " {$type} {$configvalue}";
2201
	}
2202

    
2203
	return $pollstring;
2204
}
2205

    
2206
function system_ntp_setup_gps($serialport) {
2207
	if (config_get_path('ntpd/enable') == 'disabled') {
2208
		return false;
2209
	}
2210

    
2211
	init_config_arr(array('ntpd', 'gps'));
2212
	$serialports = get_serial_ports(true);
2213

    
2214
	if (!array_key_exists($serialport, $serialports)) {
2215
		return false;
2216
	}
2217

    
2218
	$gps_device = '/dev/gps0';
2219
	$serialport = '/dev/'.basename($serialport);
2220

    
2221
	if (!file_exists($serialport)) {
2222
		return false;
2223
	}
2224

    
2225
	// Create symlink that ntpd requires
2226
	unlink_if_exists($gps_device);
2227
	@symlink($serialport, $gps_device);
2228

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

    
2240
	system_ntp_setup_rawspeed($serialport, $gpsbaud);
2241

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

    
2266
	/* Send the following to the GPS port to initialize the GPS */
2267
	if (!empty(config_get_path('ntpd/gps/type'))) {
2268
		$gps_init = base64_decode(config_get_path('ntpd/gps/initcmd'));
2269
	} else {
2270
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
2271
	}
2272

    
2273
	/* XXX: Why not file_put_contents to the device */
2274
	@file_put_contents('/tmp/gps.init', $gps_init);
2275
	mwexec("/bin/cat /tmp/gps.init > {$serialport}");
2276

    
2277
	if ($found && config_get_path('ntpd/gps/autobaudinit')) {
2278
		system_ntp_setup_rawspeed($serialport, $gpsbaud);
2279
	}
2280

    
2281
	/* Remove old /etc/remote entry if it exists */
2282
	if (mwexec("/usr/bin/grep -c '^gps0' /etc/remote") == 0) {
2283
		mwexec("/usr/bin/sed -i '' -n '/gps0/!p' /etc/remote");
2284
	}
2285

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

    
2291
	return true;
2292
}
2293

    
2294
// Configure the serial port for raw IO and set the speed
2295
function system_ntp_setup_rawspeed($serialport, $baud) {
2296
	mwexec("/bin/stty -f " .  escapeshellarg($serialport) . " raw speed " . escapeshellarg($baud));
2297
	mwexec("/bin/stty -f " .  escapeshellarg($serialport) . ".init raw speed " . escapeshellarg($baud));
2298
}
2299

    
2300
function system_ntp_setup_pps($serialport) {
2301
	$serialports = get_serial_ports(true);
2302

    
2303
	if (!array_key_exists($serialport, $serialports)) {
2304
		return false;
2305
	}
2306

    
2307
	$pps_device = '/dev/pps0';
2308
	$serialport = '/dev/'.basename($serialport);
2309

    
2310
	if (!file_exists($serialport)) {
2311
		return false;
2312
	}
2313
	// If ntpd is disabled, just return
2314
	if (config_get_path('ntpd/enable') == 'disabled') {
2315
		return false;
2316
	}
2317

    
2318
	// Create symlink that ntpd requires
2319
	unlink_if_exists($pps_device);
2320
	@symlink($serialport, $pps_device);
2321

    
2322

    
2323
	return true;
2324
}
2325

    
2326
function system_ntp_configure() {
2327
	global $g;
2328
	global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
2329
	global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
2330
	global $ntp_poll_min_default, $ntp_poll_max_default;
2331

    
2332
	$driftfile = "/var/db/ntpd.drift";
2333
	$statsdir = "/var/log/ntp";
2334
	$gps_device = '/dev/gps0';
2335

    
2336
	safe_mkdir($statsdir);
2337

    
2338
	init_config_arr(array('ntpd'));
2339

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

    
2352
	if (platform_booting()) {
2353
		echo gettext("Starting NTP Server...");
2354
	}
2355

    
2356
	/* if ntpd is running, kill it */
2357
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
2358
		killbypid("{$g['varrun_path']}/ntpd.pid");
2359
	}
2360
	@unlink("{$g['varrun_path']}/ntpd.pid");
2361

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

    
2373
	$ntpcfg = "# \n";
2374
	$ntpcfg .= "# pfSense ntp configuration file \n";
2375
	$ntpcfg .= "# \n\n";
2376
	$ntpcfg .= "tinker panic 0 \n\n";
2377

    
2378
	if (config_get_path('ntpd/serverauth') == 'yes') {
2379
		$ntpcfg .= "# Authentication settings \n";
2380
		$ntpcfg .= "keys /var/etc/ntp.keys \n";
2381
		$ntpcfg .= "trustedkey 1 \n";
2382
		$ntpcfg .= "requestkey 1 \n";
2383
		$ntpcfg .= "controlkey 1 \n";
2384
		$ntpcfg .= "\n";
2385
	}
2386

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

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

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

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

    
2546
		$ntpcfg .= "{$ts}";
2547
		if (!substr_count(config_get_path('ntpd/ispeer'), $ts)) {
2548
			$ntpcfg .= " iburst";
2549
		}
2550

    
2551
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', config_get_path('ntpd/ntpminpoll'), $ntp_poll_min_default);
2552
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', config_get_path('ntpd/ntpmaxpoll'), $ntp_poll_max_default);
2553

    
2554
		if (substr_count(config_get_path('ntpd/prefer'), $ts)) {
2555
			$ntpcfg .= ' prefer';
2556
		}
2557
		if (substr_count(config_get_path('ntpd/noselect'), $ts)) {
2558
			$ntpcfg .= ' noselect';
2559
		}
2560
		$ntpcfg .= "\n";
2561
	}
2562
	unset($ts);
2563

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

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

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

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

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

    
2692

    
2693
	if (empty(config_get_path('ntpd/interface'))) {
2694
		$interfaces =
2695
			explode(",",
2696
					config_get_path('installedpackages/openntpd/config/0/interface', ''));
2697
	} else {
2698
		$interfaces = explode(",", config_get_path('ntpd/interface'));
2699
	}
2700

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

    
2718
	/* open configuration for writing or bail */
2719
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
2720
		log_error(sprintf(gettext("Could not open %s/ntpd.conf for writing"), g_get('varetc_path')));
2721
		return;
2722
	}
2723

    
2724
	/* if /var/empty does not exist, create it */
2725
	if (!is_dir("/var/empty")) {
2726
		mkdir("/var/empty", 0555, true);
2727
	}
2728

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

    
2732
	// Note that we are starting up
2733
	log_error("NTPD is starting up.");
2734

    
2735
	if (platform_booting()) {
2736
		echo gettext("done.") . "\n";
2737
	}
2738

    
2739
	return;
2740
}
2741

    
2742
function system_halt() {
2743
	global $g;
2744

    
2745
	system_reboot_cleanup();
2746

    
2747
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
2748
}
2749

    
2750
function system_reboot() {
2751
	global $g;
2752

    
2753
	system_reboot_cleanup();
2754

    
2755
	mwexec("/usr/bin/nohup /etc/rc.reboot > /dev/null 2>&1 &");
2756
}
2757

    
2758
function system_reboot_sync($reroot=false) {
2759
	global $g;
2760

    
2761
	if ($reroot) {
2762
		$args = " -r ";
2763
	}
2764

    
2765
	system_reboot_cleanup();
2766

    
2767
	mwexec("/etc/rc.reboot {$args} > /dev/null 2>&1");
2768
}
2769

    
2770
function system_reboot_cleanup() {
2771
	global $g, $cpzone;
2772

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

    
2787
	if (count($cps)> 0) {
2788
		/* Remove the pipe database */
2789
		unlink_if_exists("{$g['vardb_path']}/captiveportaldn.rules");
2790
	}
2791

    
2792
	require_once("voucher.inc");
2793
	voucher_save_db_to_config();
2794
	require_once("pfsense-utils.inc");
2795
	enable_carp(false);
2796
	require_once("pkg-utils.inc");
2797
	stop_packages();
2798
}
2799

    
2800
function system_do_shell_commands($early = 0) {
2801
	if (config_path_enabled('system', 'developerspew')) {
2802
		$mt = microtime();
2803
		echo "system_do_shell_commands() being called $mt\n";
2804
	}
2805

    
2806
	if ($early) {
2807
		$cmdn = "earlyshellcmd";
2808
	} else {
2809
		$cmdn = "shellcmd";
2810
	}
2811

    
2812
	$syscmd = config_get_path("system/{$cmdn}", '');
2813
	if (is_array($syscmd)) {
2814
		/* *cmd is an array, loop through */
2815
		foreach ($syscmd as $cmd) {
2816
			exec($cmd);
2817
		}
2818

    
2819
	} elseif ($syscmd <> "") {
2820
		/* execute single item */
2821
		exec($syscmd);
2822

    
2823
	}
2824
}
2825

    
2826
function system_dmesg_save() {
2827
	global $g;
2828
	if (config_path_enabled('system', 'developerspew')) {
2829
		$mt = microtime();
2830
		echo "system_dmesg_save() being called $mt\n";
2831
	}
2832

    
2833
	$dmesg = "";
2834
	$_gb = exec("/sbin/dmesg", $dmesg);
2835

    
2836
	/* find last copyright line (output from previous boots may be present) */
2837
	$lastcpline = 0;
2838

    
2839
	for ($i = 0; $i < count($dmesg); $i++) {
2840
		if (strstr($dmesg[$i], "Copyright (c) 1992-")) {
2841
			$lastcpline = $i;
2842
		}
2843
	}
2844

    
2845
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
2846
	if (!$fd) {
2847
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
2848
		return 1;
2849
	}
2850

    
2851
	for ($i = $lastcpline; $i < count($dmesg); $i++) {
2852
		fwrite($fd, $dmesg[$i] . "\n");
2853
	}
2854

    
2855
	fclose($fd);
2856
	unset($dmesg);
2857

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

    
2861
	return 0;
2862
}
2863

    
2864
function system_set_harddisk_standby() {
2865
	if (config_path_enabled('system', 'developerspew')) {
2866
		$mt = microtime();
2867
		echo "system_set_harddisk_standby() being called $mt\n";
2868
	}
2869

    
2870
	if (config_path_enabled('system', 'harddiskstandby')) {
2871
		if (platform_booting()) {
2872
			echo gettext('Setting hard disk standby... ');
2873
		}
2874

    
2875
		$standby = config_get_path('system/harddiskstandby');
2876
		// Check for a numeric value
2877
		if (is_numeric($standby)) {
2878
			// Get only suitable candidates for standby; using get_smart_drive_list()
2879
			// from utils.inc to get the list of drives.
2880
			$harddisks = get_smart_drive_list();
2881

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

    
2901
function system_setup_sysctl() {
2902
	if (config_path_enabled('system', 'developerspew')) {
2903
		$mt = microtime();
2904
		echo "system_setup_sysctl() being called $mt\n";
2905
	}
2906

    
2907
	activate_sysctls();
2908

    
2909
	if (config_path_enabled('system', 'sharednet')) {
2910
		system_disable_arp_wrong_if();
2911
	}
2912
}
2913

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

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

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

    
2954
function system_check_reset_button() {
2955
	global $g;
2956

    
2957
	$specplatform = system_identify_specific_platform();
2958

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

    
2975
	$retval = mwexec("/usr/local/sbin/" . $binprefix . "resetbtn");
2976

    
2977
	if ($retval == 99) {
2978
		/* user has pressed reset button for 2 seconds -
2979
		   reset to factory defaults */
2980
		echo <<<EOD
2981

    
2982
***********************************************************************
2983
* Reset button pressed - resetting configuration to factory defaults. *
2984
* All additional packages installed will be removed                   *
2985
* The system will reboot after this completes.                        *
2986
***********************************************************************
2987

    
2988

    
2989
EOD;
2990

    
2991
		reset_factory_defaults();
2992
		system_reboot_sync();
2993
		exit(0);
2994
	}
2995

    
2996
	return 0;
2997
}
2998

    
2999
function system_get_serial() {
3000
	$platform = system_identify_specific_platform();
3001

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

    
3021
	$vm_guest = get_single_sysctl('kern.vm_guest');
3022

    
3023
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
3024
	    $vm_guest == 'none') {
3025
		return $serial;
3026
	}
3027

    
3028
	return "";
3029
}
3030

    
3031
function system_get_uniqueid() {
3032
	global $g;
3033

    
3034
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
3035

    
3036
	if (empty(g_get('uniqueid'))) {
3037
		if (!file_exists($uniqueid_file)) {
3038
			mwexec("/usr/sbin/gnid > {$g['vardb_path']}/uniqueid " .
3039
			    "2>/dev/null");
3040
		}
3041
		if (file_exists($uniqueid_file)) {
3042
			$g['uniqueid'] = @file_get_contents($uniqueid_file);
3043
		}
3044
	}
3045

    
3046
	return (g_get('uniqueid') ?: '');
3047
}
3048

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

    
3058
	$hw_model = get_single_sysctl('hw.model');
3059
	$hw_ncpu = get_single_sysctl('hw.ncpu');
3060

    
3061
	/* Try to guess from smbios strings */
3062
	unset($product);
3063
	unset($maker);
3064
	unset($bios);
3065
	unset($chassis);
3066
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $product);
3067
	$_gb = exec('/bin/kenv -q smbios.system.maker 2>/dev/null', $maker);
3068
	$_gb = exec('/bin/kenv -q smbios.bios.version 2>/dev/null', $bios);
3069
	$_gb = exec('/bin/kenv -q smbios.chassis.tag 2>/dev/null', $chassis);
3070

    
3071
	$vm = get_single_sysctl('kern.vm_guest');
3072
	// Google GCP, newer AWS instances and OCI return kvm from this so we must detect them first.
3073

    
3074
	if ($chassis[0] == "OracleCloud.com") {
3075
		return (array('name' => 'Oracle', 'descr' => 'Oracle Cloud Infrastructure'));
3076
	}	
3077

    
3078
	if ($maker[0] == "QEMU") {
3079
		return (array('name' => 'QEMU', 'descr' => 'QEMU Guest'));
3080
	} else  if ($maker[0] == "Google") {
3081
		return (array('name' => 'Google', 'descr' => 'Google Cloud Platform'));
3082
	} else  if ($maker[0] == "Amazon EC2") {
3083
		return (array('name' => 'AWS', 'descr' => 'Amazon Web Services'));
3084
	}
3085

    
3086
	// This switch needs to be expanded to include other virtualization systems
3087
	switch ($vm) {
3088
		case "none" :
3089
		break;
3090

    
3091
		case "kvm" :
3092
			return (array('name' => 'KVM', 'descr' => 'KVM Guest'));
3093
		break;
3094
	}
3095

    
3096
	// AWS, GCP and OCI can also be identified via the bios version
3097
	if (stripos($bios[0], "amazon") !== false) {
3098
		return (array('name' => 'AWS', 'descr' => 'Amazon Web Services'));
3099
	} else  if (stripos($bios[0], "Google") !== false) {
3100
		return (array('name' => 'Google', 'descr' => 'Google Cloud Platform'));
3101
	} else  if (stripos($bios[0], "oracle") !== false) {
3102
		return (array('name' => 'Oracle', 'descr' => 'Oracle Cloud Infrastructure'));
3103
	}
3104

    
3105
	switch ($product[0]) {
3106
		case 'FW7541':
3107
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
3108
			break;
3109
		case 'apu1':
3110
		case 'APU':
3111
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
3112
			break;
3113
		case 'RCC-VE':
3114
			$result = array();
3115
			$result['name'] = 'RCC-VE';
3116

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

    
3210
	$_gb = exec('/bin/kenv -q smbios.planar.product 2>/dev/null',
3211
	    $planar_product);
3212
	if (isset($planar_product[0]) &&
3213
	    $planar_product[0] == 'X10SDV-8C-TLN4F+') {
3214
		return array('name' => '1537', 'descr' => 'Super Micro 1537');
3215
	}
3216

    
3217
	if (strpos($hw_model, "PC Engines WRAP") !== false) {
3218
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
3219
	}
3220

    
3221
	if (strpos($hw_model, "PC Engines ALIX") !== false) {
3222
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
3223
	}
3224

    
3225
	if (preg_match("/Soekris net45../", $hw_model, $matches)) {
3226
		return array('name' => 'net45xx', 'descr' => $matches[0]);
3227
	}
3228

    
3229
	if (preg_match("/Soekris net48../", $hw_model, $matches)) {
3230
		return array('name' => 'net48xx', 'descr' => $matches[0]);
3231
	}
3232

    
3233
	if (preg_match("/Soekris net55../", $hw_model, $matches)) {
3234
		return array('name' => 'net55xx', 'descr' => $matches[0]);
3235
	}
3236

    
3237
	unset($hw_model);
3238

    
3239
	$dmesg_boot = system_get_dmesg_boot();
3240
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
3241
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
3242
	}
3243
	unset($dmesg_boot);
3244

    
3245
	return array('name' => g_get('product_name'), 'descr' => g_get('product_label'));
3246
}
3247

    
3248
function system_get_dmesg_boot() {
3249
	global $g;
3250

    
3251
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
3252
}
3253

    
3254
function system_get_arp_table($resolve_hostnames = false) {
3255
	$params="-a";
3256
	if (!$resolve_hostnames) {
3257
		$params .= "n";
3258
	}
3259

    
3260
	$arp_table = array();
3261
	$_gb = exec("/usr/sbin/arp --libxo json {$params}", $rawdata, $rc);
3262
	if ($rc == 0) {
3263
		$arp_table = json_decode(implode(" ", $rawdata),
3264
		    JSON_OBJECT_AS_ARRAY);
3265
		if ($rc == 0) {
3266
			$arp_table = $arp_table['arp']['arp-cache'];
3267
		}
3268
	}
3269

    
3270
	return $arp_table;
3271
}
3272

    
3273
?>
(50-50/61)