Project

General

Profile

Download (89.7 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-2025 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('services_dhcp.inc');
30
require_once('syslog.inc');
31

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

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

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

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

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

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

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

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

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

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

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

    
117
	return $output[0];
118
}
119

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
205
	set_sysctl($sysctls);
206
}
207

    
208
/* Search current tunables for a specific OID and either update the existing
209
 * entry or create a new one.
210
 * Does not write the config, that's up to the caller. */
211
function set_sysctl_config($oid, $value) {
212
	$tunables = config_get_path('sysctl/item', []);
213
	$updated = false;
214
	$found = false;
215
	foreach ($tunables as $idx => $tunable) {
216
		if ($tunable['tunable'] == $oid) {
217
			$found = true;
218
			$tunables[$idx]['value'] = $value;
219
		}
220
	}
221
	if (!$found) {
222
		$tunables[] = [
223
			'tunable' => $oid,
224
			'value' => $value,
225
		];
226
		$updated = true;
227
	}
228
	if ($updated) {
229
		config_set_path('sysctl/item', $tunables);
230
	}
231
}
232

    
233
function system_resolvconf_generate($dynupdate = false) {
234
	global $g;
235

    
236
	if (config_path_enabled('system', 'developerspew')) {
237
		$mt = microtime();
238
		echo "system_resolvconf_generate() being called $mt\n";
239
	}
240

    
241
	$syscfg = config_get_path('system', []);
242

    
243
	foreach(get_dns_nameservers(false, false) as $dns_ns) {
244
		$resolvconf .= "nameserver $dns_ns\n";
245
	}
246

    
247
	$ns = array();
248
	if (isset($syscfg['dnsallowoverride'])) {
249
		/* get dynamically assigned DNS servers (if any) */
250
		$ns = array_unique(get_searchdomains());
251
		foreach ($ns as $searchserver) {
252
			if ($searchserver) {
253
				$resolvconf .= "search {$searchserver}\n";
254
			}
255
		}
256
	}
257
	if (empty($ns)) {
258
		// Do not create blank search/domain lines, it can break tools like dig.
259
		if ($syscfg['domain']) {
260
			$resolvconf .= "search {$syscfg['domain']}\n";
261
		}
262
	}
263

    
264
	// Add EDNS support
265
	if (config_path_enabled('unbound') && (config_get_path('unbound/edns') != null)) {
266
		$resolvconf .= "options edns0\n";
267
	}
268

    
269
	$dnslock = lock('resolvconf', LOCK_EX);
270

    
271
	$fd = fopen("{$g['etc_path']}/resolv.conf", "w");
272
	if (!$fd) {
273
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
274
		unlock($dnslock);
275
		return 1;
276
	}
277

    
278
	fwrite($fd, $resolvconf);
279
	fclose($fd);
280

    
281
	// Prevent resolvconf(8) from rewriting our resolv.conf
282
	$fd = fopen("{$g['etc_path']}/resolvconf.conf", "w");
283
	if (!$fd) {
284
		printf("Error: cannot open resolvconf.conf in system_resolvconf_generate().\n");
285
		return 1;
286
	}
287
	fwrite($fd, "resolv_conf=\"/dev/null\"\n");
288
	fclose($fd);
289

    
290
	if (!is_platform_booting()) {
291
		/* restart dhcpd (nameservers may have changed) */
292
		if (!$dynupdate) {
293
			services_dhcpd_configure();
294
		}
295
	}
296

    
297
	// set up or tear down static routes for DNS servers
298
	$dnscounter = 1;
299
	$dnsgw = "dns{$dnscounter}gw";
300
	$exempt_addresses = array_unique(array_merge(get_interface_addresses_all('lo0'),
301
	    get_configured_ip_addresses(), get_configured_ipv6_addresses()));
302
	while (!empty(config_get_path("system/{$dnsgw}"))) {
303
		/* setup static routes for dns servers */
304
		$gwname = config_get_path("system/{$dnsgw}");		unset($gatewayip);
305
		unset($inet6);
306
		if ((!empty($gwname)) && ($gwname != "none")) {
307
			$gatewayip = lookup_gateway_ip_by_name($gwname);
308
			$inet6 = is_ipaddrv6($gatewayip) ? '-inet6 ' : '';
309
		}
310
		/* dns server array starts at 0 */
311
		$dnsserver = $syscfg['dnsserver'][$dnscounter - 1];
312

    
313
		/* Only modify routes for non-interface addresses;
314
		 * see https://redmine.pfsense.org/issues/14288 */
315
		if (!empty($dnsserver) && !in_array($dnsserver, $exempt_addresses)) {
316
			// specify IP protocol version for correct add/del
317
			if (is_ipaddrv4($dnsserver)) {
318
				$ipprotocol = 'inet';
319
			} else {
320
				$ipprotocol = 'inet6';
321
			}
322

    
323
			if (is_ipaddr($gatewayip)) {
324
				route_add_or_change($dnsserver, $gatewayip, '', '', $ipprotocol);
325
			} else {
326
				/* Remove old route when disable gw */
327
				route_del($dnsserver, $ipprotocol);
328
			}
329
		}
330
		$dnscounter++;
331
		$dnsgw = "dns{$dnscounter}gw";
332
	}
333

    
334
	unlock($dnslock);
335

    
336
	return 0;
337
}
338

    
339
function get_searchdomains() {
340
	$master_list = array();
341

    
342
	// Read in dhclient nameservers
343
	$search_list = glob("/var/etc/searchdomain_*");
344
	if (is_array($search_list)) {
345
		foreach ($search_list as $fdns) {
346
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
347
			if (!is_array($contents)) {
348
				continue;
349
			}
350
			foreach ($contents as $dns) {
351
				if (is_hostname($dns)) {
352
					$master_list[] = $dns;
353
				}
354
			}
355
		}
356
	}
357

    
358
	return $master_list;
359
}
360

    
361
/* Stub for deprecated function name
362
 * See https://redmine.pfsense.org/issues/10931 */
363
function get_nameservers() {
364
	return get_dynamic_nameservers();
365
}
366

    
367
/****f* system.inc/get_dynamic_nameservers
368
 * NAME
369
 *   get_dynamic_nameservers - Get DNS servers from dynamic sources (DHCP, PPP, etc)
370
 * INPUTS
371
 *   $iface: Interface name used to filter results.
372
 * RESULT
373
 *   $master_list - Array containing DNS servers
374
 ******/
375
function get_dynamic_nameservers($iface = '') {
376
	$master_list = array();
377

    
378
	if (!empty($iface)) {
379
		$realif = get_real_interface($iface);
380
	}
381

    
382
	// Read in dynamic nameservers
383
	$dns_lists = array_merge(glob("/var/etc/nameserver_{$realif}*"), glob("/var/etc/nameserver_v6{$iface}*"));
384
	if (is_array($dns_lists)) {
385
		foreach ($dns_lists as $fdns) {
386
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
387
			if (!is_array($contents)) {
388
				continue;
389
			}
390
			foreach ($contents as $dns) {
391
				if (is_ipaddr($dns)) {
392
					$master_list[] = $dns;
393
				}
394
			}
395
		}
396
	}
397

    
398
	return $master_list;
399
}
400

    
401
/* Create localhost + local interfaces entries for /etc/hosts */
402
function system_hosts_local_entries() {
403
	$syscfg = config_get_path('system', []);
404

    
405
	$hosts = array();
406
	$hosts[] = array(
407
	    'ipaddr' => '127.0.0.1',
408
	    'fqdn' => 'localhost.' . $syscfg['domain'],
409
	    'name' => 'localhost',
410
	    'domain' => $syscfg['domain']
411
	);
412
	$hosts[] = array(
413
	    'ipaddr' => '::1',
414
	    'fqdn' => 'localhost.' . $syscfg['domain'],
415
	    'name' => 'localhost',
416
	    'domain' => $syscfg['domain']
417
	);
418

    
419
	if (config_get_path('interfaces/lan')) {
420
		$sysiflist = array('lan' => "lan");
421
	} else {
422
		$sysiflist = get_configured_interface_list();
423
	}
424

    
425
	$hosts_if_found = false;
426
	$local_fqdn = "{$syscfg['hostname']}.{$syscfg['domain']}";
427
	foreach ($sysiflist as $sysif) {
428
		if ($sysif != 'lan' && interface_has_gateway($sysif)) {
429
			continue;
430
		}
431
		$cfgip = get_interface_ip($sysif);
432
		if (is_ipaddrv4($cfgip)) {
433
			$hosts[] = array(
434
			    'ipaddr' => $cfgip,
435
			    'fqdn' => $local_fqdn,
436
			    'name' => $syscfg['hostname'],
437
			    'domain' => $syscfg['domain']
438
			);
439
			$hosts_if_found = true;
440
		}
441
		if (!isset($syscfg['ipv6dontcreatelocaldns'])) {
442
			$cfgipv6 = get_interface_ipv6($sysif);
443
			if (is_ipaddrv6($cfgipv6)) {
444
				$hosts[] = array(
445
					'ipaddr' => $cfgipv6,
446
					'fqdn' => $local_fqdn,
447
					'name' => $syscfg['hostname'],
448
					'domain' => $syscfg['domain']
449
				);
450
				$hosts_if_found = true;
451
			}
452
		}
453
		if ($hosts_if_found == true) {
454
			break;
455
		}
456
	}
457

    
458
	return $hosts;
459
}
460

    
461
/* Read host override entries from dnsmasq or unbound */
462
function system_hosts_override_entries($dnscfg) {
463
	$hosts = array();
464

    
465
	if (!is_array($dnscfg) ||
466
	    !is_array($dnscfg['hosts']) ||
467
	    !isset($dnscfg['enable'])) {
468
		return $hosts;
469
	}
470

    
471
	foreach ($dnscfg['hosts'] as $host) {
472
		$fqdn = '';
473
		if ($host['host'] || $host['host'] == "0") {
474
			$fqdn .= "{$host['host']}.";
475
		}
476
		$fqdn .= $host['domain'];
477

    
478
		foreach (explode(',', $host['ip']) as $ip) {
479
			$hosts[] = array(
480
			    'ipaddr' => $ip,
481
			    'fqdn' => $fqdn,
482
			    'name' => $host['host'],
483
			    'domain' => $host['domain']
484
			);
485
		}
486

    
487
		if (!is_array($host['aliases']) ||
488
		    !is_array($host['aliases']['item'])) {
489
			continue;
490
		}
491

    
492
		foreach ($host['aliases']['item'] as $alias) {
493
			$fqdn = '';
494
			if ($alias['host'] || $alias['host'] == "0") {
495
				$fqdn .= "{$alias['host']}.";
496
			}
497
			$fqdn .= $alias['domain'];
498

    
499
			foreach (explode(',', $host['ip']) as $ip) {
500
				$hosts[] = array(
501
				    'ipaddr' => $ip,
502
				    'fqdn' => $fqdn,
503
				    'name' => $alias['host'],
504
				    'domain' => $alias['domain']
505
				);
506
			}
507
		}
508
	}
509

    
510
	return $hosts;
511
}
512

    
513
/* Read all dhcpd/dhcpdv6 staticmap entries */
514
function system_hosts_dhcpd_entries() {
515
	$hosts = array();
516
	$syscfg = config_get_path('system');
517

    
518
	$conf_dhcpd = config_get_path('dhcpd', []);
519

    
520
	foreach ($conf_dhcpd as $dhcpif => $dhcpifconf) {
521
		if (empty($dhcpifconf)) {
522
			continue;
523
		}
524
		if (!is_array($dhcpifconf['staticmap']) ||
525
		    !isset($dhcpifconf['enable'])) {
526
			continue;
527
		}
528
		foreach ($dhcpifconf['staticmap'] as $host) {
529
			if (!$host['ipaddr'] ||
530
			    !$host['hostname']) {
531
				continue;
532
			}
533

    
534
			$fqdn = $host['hostname'] . ".";
535
			$domain = "";
536
			if ($host['domain']) {
537
				$domain = $host['domain'];
538
			} elseif ($dhcpifconf['domain']) {
539
				$domain = $dhcpifconf['domain'];
540
			} else {
541
				$domain = $syscfg['domain'];
542
			}
543

    
544
			$hosts[] = array(
545
			    'ipaddr' => $host['ipaddr'],
546
			    'fqdn' => $fqdn . $domain,
547
			    'name' => $host['hostname'],
548
			    'domain' => $domain
549
			);
550
		}
551
	}
552
	unset($conf_dhcpd);
553

    
554
	$conf_dhcpdv6 = config_get_path('dhcpdv6', []);
555

    
556
	foreach ($conf_dhcpdv6 as $dhcpif => $dhcpifconf) {
557
		if (empty($dhcpifconf)) {
558
			continue;
559
		}
560
		if (!is_array($dhcpifconf['staticmap']) ||
561
		    !isset($dhcpifconf['enable'])) {
562
			continue;
563
		}
564

    
565
		if (config_get_path("interfaces/{$dhcpif}/ipaddrv6") ==
566
		    'track6') {
567
			$isdelegated = true;
568
		} else {
569
			$isdelegated = false;
570
		}
571

    
572
		foreach ($dhcpifconf['staticmap'] as $host) {
573
			$ipaddrv6 = $host['ipaddrv6'];
574

    
575
			if (!$ipaddrv6 || !$host['hostname']) {
576
				continue;
577
			}
578

    
579
			if ($isdelegated) {
580
				/*
581
				 * We are always in an "end-user" subnet
582
				 * here, which all are /64 for IPv6.
583
				 */
584
				$prefix6 = 64;
585
			} else {
586
				$prefix6 = get_interface_subnetv6($dhcpif);
587
			}
588
			$ipaddrv6 = merge_ipv6_delegated_prefix(get_interface_ipv6($dhcpif), $ipaddrv6, $prefix6);
589

    
590
			$fqdn = $host['hostname'] . ".";
591
			$domain = "";
592
			if ($host['domain']) {
593
				$domain = $host['domain'];
594
			} elseif ($dhcpifconf['domain']) {
595
				$domain = $dhcpifconf['domain'];
596
			} else {
597
				$domain = $syscfg['domain'];
598
			}
599

    
600
			$hosts[] = array(
601
			    'ipaddr' => $ipaddrv6,
602
			    'fqdn' => $fqdn . $domain,
603
			    'name' => $host['hostname'],
604
			    'domain' => $domain
605
			);
606
		}
607
	}
608
	unset($conf_dhcpdv6);
609

    
610
	return $hosts;
611
}
612

    
613
/* Concatenate local, dnsmasq/unbound and dhcpd/dhcpdv6 hosts entries */
614
function system_hosts_entries($dnscfg) {
615
	$local = array();
616
	if (!isset($dnscfg['disable_auto_added_host_entries'])) {
617
		$local = system_hosts_local_entries();
618
	}
619

    
620
	$dns = array();
621
	$dhcpd = array();
622
	if (isset($dnscfg['enable'])) {
623
		$dns = system_hosts_override_entries($dnscfg);
624
		if (isset($dnscfg['regdhcpstatic'])) {
625
			$dhcpd = system_hosts_dhcpd_entries();
626
		}
627
	}
628

    
629
	if (isset($dnscfg['dhcpfirst'])) {
630
		return array_merge($local, $dns, $dhcpd);
631
	} else {
632
		return array_merge($local, $dhcpd, $dns);
633
	}
634
}
635

    
636
function system_hosts_generate() {
637
	global $g;
638
	if (config_path_enabled('system', 'developerspew')) {
639
		$mt = microtime();
640
		echo "system_hosts_generate() being called $mt\n";
641
	}
642

    
643
	// prefer dnsmasq for hosts generation where it's enabled. It relies
644
	// on hosts for name resolution of its overrides, unbound does not.
645
	if (config_path_enabled('dnsmasq')) {
646
		$dnsmasqcfg = config_get_path('dnsmasq', []);
647
	} else {
648
		$dnsmasqcfg = config_get_path('unbound', []);
649
	}
650

    
651
	$syscfg = config_get_path('system');
652
	$hosts = "";
653
	$lhosts = "";
654
	$dhosts = "";
655

    
656
	$hosts_array = system_hosts_entries($dnsmasqcfg);
657
	foreach ($hosts_array as $host) {
658
		$hosts .= "{$host['ipaddr']}\t";
659
		if ($host['name'] == "localhost") {
660
			$hosts .= "{$host['name']} {$host['fqdn']}";
661
		} else {
662
			$hosts .= "{$host['fqdn']} {$host['name']}";
663
		}
664
		$hosts .= "\n";
665
	}
666
	unset($hosts_array);
667

    
668
	/*
669
	 * Do not remove this because dhcpleases monitors with kqueue it needs
670
	 * to be killed before writing to hosts files.
671
	 */
672
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
673
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
674
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
675
	}
676

    
677
	$fd = fopen("{$g['etc_path']}/hosts", "w");
678
	if (!$fd) {
679
		log_error(gettext(
680
		    "Error: cannot open hosts file in system_hosts_generate()."
681
		    ));
682
		return 1;
683
	}
684

    
685
	fwrite($fd, $hosts);
686
	fclose($fd);
687

    
688
	if (config_path_enabled('unbound')) {
689
		require_once("unbound.inc");
690
		unbound_hosts_generate();
691
	}
692

    
693
	/* restart dhcpleases */
694
	if (!is_platform_booting()) {
695
		system_dhcpleases_configure();
696
	}
697

    
698
	return 0;
699
}
700

    
701
function system_dhcpleases_configure() {
702
	global $g;
703
	if (!function_exists('is_dhcp_server_enabled')) {
704
		require_once('pfsense-utils.inc');
705
	}
706
	$pidfile = "{$g['varrun_path']}/dhcpleases.pid";
707

    
708
	/* Start the monitoring process for dynamic dhcpclients. */
709
	if (((config_path_enabled('dnsmasq') && (config_get_path('dnsmasq/regdhcp') !== null)) ||
710
	    (config_path_enabled('unbound') && (config_get_path('unbound/regdhcp') !== null))) &&
711
	    (is_dhcp_server_enabled())) {
712
		/* Make sure we do not error out */
713
		mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db");
714
		if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
715
			@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
716
		}
717

    
718
		if (config_path_enabled('unbound')) {
719
			$dns_pid = "unbound.pid";
720
			$unbound_conf = "-u {$g['unbound_chroot_path']}/dhcpleases_entries.conf";
721
		} else {
722
			$dns_pid = "dnsmasq.pid";
723
			$unbound_conf = "";
724
		}
725

    
726
		if (isvalidpid($pidfile)) {
727
			/* Make sure dhcpleases is using correct unbound or dnsmasq */
728
			$_gb = exec("/bin/pgrep -F {$pidfile} -f {$dns_pid}", $output, $retval);
729
			if (intval($retval) == 0) {
730
				sigkillbypid($pidfile, "HUP");
731
				return;
732
			} else {
733
				sigkillbypid($pidfile, "TERM");
734
			}
735
		}
736

    
737
		/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
738
		if (is_process_running("dhcpleases")) {
739
			sigkillbyname('dhcpleases', "TERM");
740
		}
741
		@unlink($pidfile);
742
		mwexec("/usr/local/sbin/dhcpleases -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases -d " .
743
			   config_get_path('system/domain', '') .
744
			   " -p {$g['varrun_path']}/{$dns_pid} {$unbound_conf} -h {$g['etc_path']}/hosts");
745
	} else {
746
		if (isvalidpid($pidfile)) {
747
			sigkillbypid($pidfile, "TERM");
748
			@unlink($pidfile);
749
		}
750
		if (file_exists("{$g['unbound_chroot_path']}/dhcpleases_entries.conf")) {
751
			$dhcpleases = fopen("{$g['unbound_chroot_path']}/dhcpleases_entries.conf", "w");
752
			ftruncate($dhcpleases, 0);
753
			fclose($dhcpleases);
754
		}
755
	}
756
}
757

    
758
function system_get_kea6status() {
759
	$socket_path = g_get('varrun_path') . '/kea6-ctrl-socket';
760
	$rbuf = NULL;
761

    
762
	if (!file_exists($socket_path)) {
763
		goto out;
764
	}
765

    
766
	$fd = socket_create(AF_UNIX, SOCK_STREAM, 0);
767
	if (!$fd) {
768
		goto out;
769
	}
770

    
771
	if (!socket_connect($fd, $socket_path, 0)) {
772
		goto cleanup;
773
	}
774

    
775
	$cmdjson = json_encode(['command' => 'status-get']);
776

    
777
	if (socket_send($fd, $cmdjson, strlen($cmdjson), 0) === false) {
778
		goto cleanup;
779
	}
780

    
781
	$retjson = NULL;
782
	for (;;) {
783
		$bytes = socket_recv($fd, $rbuf, 8192, MSG_WAITALL);
784

    
785
		/* error occured, just bail out */
786
		if ($bytes === false) {
787
			goto cleanup;
788
		/* we got some data, append it to the json buffer */
789
		} elseif ($bytes > 0) {
790
			$retjson .= $rbuf;
791
		} else {
792
			break;
793
		}
794
	}
795

    
796
cleanup:
797
	socket_close($fd);
798
out:
799
	return (json_decode($retjson, true));
800
}
801

    
802
function system_get_kea4status() {
803
	$socket_path = g_get('varrun_path') . '/kea4-ctrl-socket';
804
	$rbuf = NULL;
805

    
806
	if (!file_exists($socket_path)) {
807
		goto out;
808
	}
809

    
810
	$fd = socket_create(AF_UNIX, SOCK_STREAM, 0);
811
	if (!$fd) {
812
		goto out;
813
	}
814

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

    
819
	$cmdjson = json_encode(['command' => 'status-get']);
820

    
821
	if (socket_send($fd, $cmdjson, strlen($cmdjson), 0) === false) {
822
		goto cleanup;
823
	}
824

    
825
	$retjson = NULL;
826
	for (;;) {
827
		$bytes = socket_recv($fd, $rbuf, 8192, MSG_WAITALL);
828

    
829
		/* error occured, just bail out */
830
		if ($bytes === false) {
831
			goto cleanup;
832
		/* we got some data, append it to the json buffer */
833
		} elseif ($bytes > 0) {
834
			$retjson .= $rbuf;
835
		} else {
836
			break;
837
		}
838
	}
839

    
840
cleanup:
841
	socket_close($fd);
842
out:
843
	return (json_decode($retjson, true));
844
}
845

    
846
function system_clear_all_kea4leases() {
847
	$socket_path = g_get('varrun_path') . '/kea4-ctrl-socket';
848
	$rbuf = NULL;
849

    
850
	if (!file_exists($socket_path)) {
851
		return;
852
	}
853

    
854
	$fd = socket_create(AF_UNIX, SOCK_STREAM, 0);
855
	if (!$fd) {
856
		return;
857
	}
858

    
859
	if (!socket_connect($fd, $socket_path, 0)) {
860
		socket_close($fd);
861
		return;
862
	}
863

    
864
	$cmdjson = json_encode(['command' => 'lease4-wipe']);
865

    
866
	socket_send($fd, $cmdjson, strlen($cmdjson), 0);
867

    
868
	/* Kea sends status that we are not really interested in, so just eat it */
869
	while (socket_recv($fd, $rbuf, 8192, MSG_WAITALL) > 0);
870

    
871
	socket_close($fd);
872
}
873

    
874
function system_del_kea4lease(string $ip) {
875
	$socket_path = g_get('varrun_path') . '/kea4-ctrl-socket';
876
	$rbuf = NULL;
877

    
878
	if (!file_exists($socket_path)) {
879
		return;
880
	}
881

    
882
	$fd = socket_create(AF_UNIX, SOCK_STREAM, 0);
883
	if (!$fd) {
884
		return;
885
	}
886

    
887
	if (!socket_connect($fd, $socket_path, 0)) {
888
		socket_close($fd);
889
		return;
890
	}
891

    
892
	$cmdjson = json_encode([
893
		'command' => 'lease4-del',
894
		'arguments' => [
895
			'ip-address' => $ip
896
		]
897
	]);
898

    
899
	socket_send($fd, $cmdjson, strlen($cmdjson), 0);
900

    
901
	/* Kea sends status that we are not really interested in, so just eat it */
902
	while (socket_recv($fd, $rbuf, 8192, MSG_WAITALL) > 0);
903

    
904
	socket_close($fd);
905
}
906

    
907
function system_clear_all_kea6leases() {
908
	$socket_path = g_get('varrun_path') . '/kea6-ctrl-socket';
909
	$rbuf = NULL;
910

    
911
	if (!file_exists($socket_path)) {
912
		return;
913
	}
914

    
915
	$fd = socket_create(AF_UNIX, SOCK_STREAM, 0);
916
	if (!$fd) {
917
		return;
918
	}
919

    
920
	if (!socket_connect($fd, $socket_path, 0)) {
921
		socket_close($fd);
922
		return;
923
	}
924

    
925
	$cmdjson = json_encode(['command' => 'lease6-wipe']);
926

    
927
	socket_send($fd, $cmdjson, strlen($cmdjson), 0);
928

    
929
	/* Kea sends status that we are not really interested in, so just eat it */
930
	while (socket_recv($fd, $rbuf, 8192, MSG_WAITALL) > 0);
931

    
932
	socket_close($fd);
933
}
934

    
935
function system_del_kea6lease(string $ip) {
936
	$socket_path = g_get('varrun_path') . '/kea6-ctrl-socket';
937
	$rbuf = NULL;
938

    
939
	if (!file_exists($socket_path)) {
940
		return;
941
	}
942

    
943
	$fd = socket_create(AF_UNIX, SOCK_STREAM, 0);
944
	if (!$fd) {
945
		return;
946
	}
947

    
948
	if (!socket_connect($fd, $socket_path, 0)) {
949
		socket_close($fd);
950
		return;
951
	}
952

    
953
	$cmdjson = json_encode([
954
		'command' => 'lease6-del',
955
		'arguments' => [
956
			'ip-address' => $ip
957
		]
958
	]);
959

    
960
	socket_send($fd, $cmdjson, strlen($cmdjson), 0);
961

    
962
	/* Kea sends status that we are not really interested in, so just eat it */
963
	while (socket_recv($fd, $rbuf, 8192, MSG_WAITALL) > 0);
964

    
965
	socket_close($fd);
966
}
967

    
968
function system_get_kea6leases() {
969
	$leases = [];
970
	$leases['lease'] = [];
971
	$leases['failover'] = [];
972

    
973
	$socket_path = g_get('varrun_path') . '/kea6-ctrl-socket';
974
	$rbuf = NULL;
975

    
976
	if (!file_exists($socket_path)) {
977
		goto out;
978
	}
979

    
980
	$fd = socket_create(AF_UNIX, SOCK_STREAM, 0);
981
	if (!$fd) {
982
		goto out;
983
	}
984

    
985
	if (!socket_connect($fd, $socket_path, 0)) {
986
		goto cleanup;
987
	}
988

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

    
991
	if (socket_send($fd, $cmdjson, strlen($cmdjson), 0) === false) {
992
		goto cleanup;
993
	}
994

    
995
	$retjson = NULL;
996
	for (;;) {
997
		$bytes = socket_recv($fd, $rbuf, 8192, MSG_WAITALL);
998

    
999
		/* error occured, just bail out */
1000
		if ($bytes === false) {
1001
			goto cleanup;
1002
		/* we got some data, append it to the json buffer */
1003
		} elseif ($bytes > 0) {
1004
			$retjson .= $rbuf;
1005
		} else {
1006
			break;
1007
		}
1008
	}
1009

    
1010
	/* sanity check in case we received malformed json */
1011
	if (($ret = json_decode($retjson, true)) === false) {
1012
		goto cleanup;
1013
	}
1014

    
1015
	$ndpdata = get_ndpdata();
1016

    
1017
	$online_string = gettext("active/online");
1018
	$offline_string = gettext("idle/offline");
1019
	$active_string = gettext("active");
1020
	$expired_string = gettext("expired");
1021
	$reserved_string = gettext("reserved");
1022
	$released_string = gettext("released");
1023
	$dynamic_string = gettext("dynamic");
1024
	$static_string = gettext("static");
1025

    
1026
	$leasem = [];
1027

    
1028
	foreach ($ret['arguments']['leases'] as $lease) {
1029
		$startsts = (int)$lease['cltt'];
1030
		$endsts = $startsts + (int)$lease['valid-lft'];
1031

    
1032
		$item = [];
1033
		$item['act'] = $active_string;
1034
		if (time() > $endsts) {
1035
			$item['act'] = $expired_string;
1036
		}
1037

    
1038
		$item['type'] = $dynamic_string;
1039
		$item['ip'] = $lease['ip-address'];
1040
		$item['duid'] = $lease['duid'];
1041
		$item['iaid'] = $lease['iaid'];
1042

    
1043
		if (in_array($item['ip'], array_keys($ndpdata))) {
1044
			$item['online'] = $online_string;
1045
		} else {
1046
			$item['online'] = $offline_string;
1047
		}
1048

    
1049
		$item['hostname'] = rtrim($lease['hostname'], '.');
1050

    
1051
		$format = 'Y/m/d H:i:s';
1052
		$item['starts'] = date($format, $startsts);
1053
		$item['ends'] = date($format, $endsts);
1054

    
1055
		$leasem[$item['ip']] = $item;
1056
	}
1057

    
1058
	foreach (config_get_path('interfaces', []) as $ifname => $ifarr) {
1059
		foreach (config_get_path("dhcpdv6/{$ifname}/staticmap", []) as $idx => $static) {
1060
			$slease = array();
1061
			$slease['ip'] = merge_ipv6_delegated_prefix(get_interface_ipv6($ifname), $static['ipaddrv6'], get_interface_subnetv6($ifname));
1062

    
1063
			/* we've seen this entry before, so just modify it */
1064
			if (array_key_exists($slease['ip'], $leasem)) {
1065
				$leasem[$slease['ip']]['if'] = $ifname;
1066
				$leasem[$slease['ip']]['type'] = $static_string;
1067
				$leasem[$slease['ip']]['act'] = $static_string;
1068
				$leasem[$slease['ip']]['descr'] = $static['descr'];
1069
				$leasem[$slease['ip']]['staticmap_array_index'] = $idx;
1070
				continue;
1071
			}
1072

    
1073
			/* we still want to show static leases even if Kea doesn't see them */
1074
			$slease['if'] = $ifname;
1075
			$slease['type'] = $static_string;
1076
			$slease['duid'] = $static['duid'];
1077
			$slease['start'] = "";
1078
			$slease['end'] = "";
1079
			$slease['descr'] = $static['descr'];
1080
			$slease['hostname'] = $static['hostname'];
1081
			$slease['act'] = $static_string;
1082
			if (in_array($slease['ip'], array_keys($ndpdata))) {
1083
				$slease['online'] = $online_string;
1084
			} else {
1085
				$slease['online'] = $offline_string;
1086
			}
1087
			$slease['staticmap_array_index'] = $idx;
1088

    
1089
			$leasem[$slease['ip']] = $slease;
1090
		}
1091
	}
1092

    
1093
	$leases['lease'] = $leasem;
1094

    
1095
cleanup:
1096
	socket_close($fd);
1097
out:
1098
	return $leases;
1099
}
1100

    
1101
function system_get_kea4leases() {
1102
	$leases = [];
1103
	$leases['lease'] = [];
1104
	$leases['failover'] = [];
1105

    
1106
	$socket_path = '/var/run/kea4-ctrl-socket';
1107
	$rbuf = NULL;
1108

    
1109
	if (!file_exists($socket_path)) {
1110
		goto out;
1111
	}
1112

    
1113
	$fd = socket_create(AF_UNIX, SOCK_STREAM, 0);
1114
	if (!$fd) {
1115
		goto out;
1116
	}
1117

    
1118
	if (!socket_connect($fd, $socket_path, 0)) {
1119
		goto cleanup;
1120
	}
1121

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

    
1124
	if (socket_send($fd, $cmdjson, strlen($cmdjson), 0) === false) {
1125
		goto cleanup;
1126
	}
1127

    
1128
	$retjson = NULL;
1129
	for (;;) {
1130
		$bytes = socket_recv($fd, $rbuf, 8192, MSG_WAITALL);
1131

    
1132
		/* error occured, just bail out */
1133
		if ($bytes === false) {
1134
			goto cleanup;
1135
		/* we got some data, append it to the json buffer */
1136
		} elseif ($bytes > 0) {
1137
			$retjson .= $rbuf;
1138
		/* we must be done reading */
1139
		} else {
1140
			break;
1141
		}
1142
	}
1143

    
1144
	/* sanity check in case we received malformed json */
1145
	if (($ret = json_decode($retjson, true)) === false) {
1146
		goto cleanup;
1147
	}
1148

    
1149
	$arp_table = system_get_arp_table();
1150

    
1151
	$arpdata_ip = array();
1152
	$arpdata_mac = array();
1153
	foreach ($arp_table as $arp_entry) {
1154
		if (isset($arpentry['incomplete'])) {
1155
			continue;
1156
		}
1157
		$arpdata_ip[] = $arp_entry['ip-address'];
1158
		$arpdata_mac[] = $arp_entry['mac-address'];
1159
	}
1160

    
1161
	$online_string = gettext("active/online");
1162
	$offline_string = gettext("idle/offline");
1163
	$active_string = gettext("active");
1164
	$expired_string = gettext("expired");
1165
	$reserved_string = gettext("reserved");
1166
	$dynamic_string = gettext("dynamic");
1167
	$static_string = gettext("static");
1168

    
1169
	foreach ($ret['arguments']['leases'] as $lease) {
1170
		if (empty($lease['hw-address'])) {
1171
			continue;
1172
		}
1173

    
1174
		$startsts = (int)$lease['cltt'];
1175
		$endsts = $startsts + (int)$lease['valid-lft'];
1176

    
1177
		$item = [];
1178
		$item['act'] = $active_string;
1179
		if (time() > $endsts) {
1180
			$item['act'] = $expired_string;
1181
		}
1182

    
1183
		$item['type'] = $dynamic_string;
1184
		$item['ip'] = $lease['ip-address'];
1185
		$item['mac'] = $lease['hw-address'];
1186
		$item['cid'] = $lease['client-id'];
1187

    
1188
		if (in_array($item['ip'], $arpdata_ip) &&
1189
		    in_array(strtolower($item['mac']), $arpdata_mac)) {
1190
			$item['online'] = $online_string;
1191
		} else {
1192
			$item['online'] = $offline_string;
1193
		}
1194

    
1195
		$item['hostname'] = $lease['hostname'];
1196

    
1197
		$format = 'Y/m/d H:i:s';
1198
		$item['starts'] = date($format, $startsts);
1199
		$item['ends'] = date($format, $endsts);
1200

    
1201
		$leases['lease'][] = $item;
1202
	}
1203

    
1204
	$dedup_lease = false;
1205
	foreach (config_get_path('interfaces', []) as $ifname => $ifarr) {
1206
		foreach (config_get_path("dhcpd/{$ifname}/staticmap", []) as $idx => $static) {
1207
			if (empty($static['mac']) && empty($static['cid'])) {
1208
				continue;
1209
			}
1210

    
1211
			$slease = array();
1212
			$slease['ip'] = $static['ipaddr'];
1213
			$slease['type'] = $static_string;
1214
			if (!empty($static['cid'])) {
1215
				$slease['cid'] = $static['cid'];
1216
			}
1217
			$slease['mac'] = $static['mac'];
1218
			$slease['if'] = $ifname;
1219
			$slease['starts'] = "";
1220
			$slease['ends'] = "";
1221
			$slease['hostname'] = $static['hostname'];
1222
			$slease['descr'] = $static['descr'];
1223
			$slease['act'] = $static_string;
1224
			$slease['online'] = in_array(strtolower($slease['mac']),
1225
			    $arpdata_mac) ? $online_string : $offline_string;
1226
			$slease['staticmap_array_index'] = $idx;
1227
			$leases['lease'][] = $slease;
1228
			$dedup_lease = true;
1229
		}
1230
	}
1231

    
1232
	if ($dedup_lease) {
1233
		$leases['lease'] = array_remove_duplicate($leases['lease'],
1234
		    'ip');
1235
	}
1236

    
1237
cleanup:
1238
	socket_close($fd);
1239
out:
1240
	return $leases;
1241
}
1242

    
1243
function system_get_dhcpleases($dnsavailable=null) {
1244
	global $g;
1245

    
1246
	if (dhcp_is_backend('kea')) {
1247
		return system_get_kea4leases();
1248
	}
1249

    
1250
	$leases = array();
1251
	$leases['lease'] = array();
1252
	$leases['failover'] = array();
1253

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

    
1256
	if (!file_exists($leases_file)) {
1257
		return $leases;
1258
	}
1259

    
1260
	$leases_content = file($leases_file, FILE_IGNORE_NEW_LINES |
1261
	    FILE_IGNORE_NEW_LINES);
1262

    
1263
	if ($leases_content === FALSE) {
1264
		return $leases;
1265
	}
1266

    
1267
	$arp_table = system_get_arp_table();
1268

    
1269
	$arpdata_ip = array();
1270
	$arpdata_mac = array();
1271
	foreach ($arp_table as $arp_entry) {
1272
		if (isset($arpentry['incomplete'])) {
1273
			continue;
1274
		}
1275
		$arpdata_ip[] = $arp_entry['ip-address'];
1276
		$arpdata_mac[] = $arp_entry['mac-address'];
1277
	}
1278
	unset($arp_table);
1279

    
1280
	/*
1281
	 * Translate these once so we don't do it over and over in the loops
1282
	 * below.
1283
	 */
1284
	$online_string = gettext("active/online");
1285
	$offline_string = gettext("idle/offline");
1286
	$active_string = gettext("active");
1287
	$expired_string = gettext("expired");
1288
	$reserved_string = gettext("reserved");
1289
	$dynamic_string = gettext("dynamic");
1290
	$static_string = gettext("static");
1291

    
1292
	$lease_regex = '/^lease\s+([^\s]+)\s+{$/';
1293
	$starts_regex = '/^\s*(starts|ends)\s+\d+\s+([\d\/]+|never)\s*(|[\d:]*);$/';
1294
	$binding_regex = '/^\s*binding\s+state\s+(.+);$/';
1295
	$mac_regex = '/^\s*hardware\s+ethernet\s+(.+);$/';
1296
	$hostname_regex = '/^\s*client-hostname\s+"(.+)";$/';
1297

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

    
1301
	$lease = false;
1302
	$failover = false;
1303
	$dedup_lease = false;
1304
	$dedup_failover = false;
1305

    
1306
	if ($dnsavailable === null) {
1307
		$dnsavailable = get_dnsavailable();
1308
	}
1309
	foreach ($leases_content as $line) {
1310
		/* Skip comments */
1311
		if (preg_match('/^\s*(|#.*)$/', $line)) {
1312
			continue;
1313
		}
1314

    
1315
		if (preg_match('/}$/', $line)) {
1316
			if ($lease) {
1317
				if ($dnsavailable && empty($item['hostname'])) {
1318
					$hostname = resolve_address($item['ip']);
1319
					if (!empty($hostname)) {
1320
						$item['hostname'] = $hostname;
1321
					}
1322
				}
1323
				$leases['lease'][] = $item;
1324
				$lease = false;
1325
				$dedup_lease = true;
1326
			} else if ($failover) {
1327
				$leases['failover'][] = $item;
1328
				$failover = false;
1329
				$dedup_failover = true;
1330
			}
1331
			continue;
1332
		}
1333

    
1334
		if (preg_match($lease_regex, $line, $m)) {
1335
			$lease = true;
1336
			$item = array();
1337
			$item['ip'] = $m[1];
1338
			$item['type'] = $dynamic_string;
1339
			continue;
1340
		}
1341

    
1342
		if ($lease) {
1343
			if (preg_match($starts_regex, $line, $m)) {
1344
				/*
1345
				 * Quote from dhcpd.leases(5) man page:
1346
				 * If a lease will never expire, date is never
1347
				 * instead of an actual date
1348
				 */
1349
				if ($m[2] == "never") {
1350
					$item[$m[1]] = gettext("Never");
1351
				} else {
1352
					$item[$m[1]] = dhcpd_date_adjust_gmt(
1353
					    $m[2] . ' ' . $m[3]);
1354
				}
1355
				continue;
1356
			}
1357

    
1358
			if (preg_match($binding_regex, $line, $m)) {
1359
				switch ($m[1]) {
1360
					case "active":
1361
						$item['act'] = $active_string;
1362
						break;
1363
					case "free":
1364
						$item['act'] = $expired_string;
1365
						$item['online'] =
1366
						    $offline_string;
1367
						break;
1368
					case "backup":
1369
						$item['act'] = $reserved_string;
1370
						$item['online'] =
1371
						    $offline_string;
1372
						break;
1373
				}
1374
				continue;
1375
			}
1376

    
1377
			if (preg_match($mac_regex, $line, $m) &&
1378
			    is_macaddr($m[1])) {
1379
				$item['mac'] = $m[1];
1380

    
1381
				if (in_array($item['ip'], $arpdata_ip)) {
1382
					$item['online'] = $online_string;
1383
				} else {
1384
					$item['online'] = $offline_string;
1385
				}
1386
				continue;
1387
			}
1388

    
1389
			if (preg_match($hostname_regex, $line, $m)) {
1390
				$item['hostname'] = $m[1];
1391
			}
1392
		}
1393

    
1394
		if (preg_match($failover_regex, $line, $m)) {
1395
			$failover = true;
1396
			$item = array();
1397
			$item['name'] = $m[1] . ' (' .
1398
			    convert_friendly_interface_to_friendly_descr(
1399
			    substr($m[1],5)) . ')';
1400
			continue;
1401
		}
1402

    
1403
		if ($failover && preg_match($state_regex, $line, $m)) {
1404
			$item[$m[1] . 'state'] = $m[2];
1405
			$item[$m[1] . 'date'] = dhcpd_date_adjust_gmt($m[3] .
1406
			    ' ' . $m[4]);
1407
			continue;
1408
		}
1409
	}
1410

    
1411
	foreach (config_get_path('interfaces', []) as $ifname => $ifarr) {
1412
		foreach (config_get_path("dhcpd/{$ifname}/staticmap", []) as $idx =>
1413
		    $static) {
1414
			if (empty($static['mac']) && empty($static['cid'])) {
1415
				continue;
1416
			}
1417

    
1418
			$slease = array();
1419
			$slease['ip'] = $static['ipaddr'];
1420
			$slease['type'] = $static_string;
1421
			if (!empty($static['cid'])) {
1422
				$slease['cid'] = $static['cid'];
1423
			}
1424
			$slease['mac'] = $static['mac'];
1425
			$slease['if'] = $ifname;
1426
			$slease['starts'] = "";
1427
			$slease['ends'] = "";
1428
			$slease['hostname'] = $static['hostname'];
1429
			$slease['descr'] = $static['descr'];
1430
			$slease['act'] = $static_string;
1431
			$slease['online'] = in_array(strtolower($slease['mac']),
1432
			    $arpdata_mac) ? $online_string : $offline_string;
1433
			$slease['staticmap_array_index'] = $idx;
1434
			$leases['lease'][] = $slease;
1435
			$dedup_lease = true;
1436
		}
1437
	}
1438

    
1439
	if ($dedup_lease) {
1440
		$leases['lease'] = array_remove_duplicate($leases['lease'],
1441
		    'ip');
1442
	}
1443
	if ($dedup_failover) {
1444
		$leases['failover'] = array_remove_duplicate(
1445
		    $leases['failover'], 'name');
1446
		asort($leases['failover']);
1447
	}
1448

    
1449
	return $leases;
1450
}
1451

    
1452
function system_hostname_configure() {
1453
	if (config_path_enabled('system', 'developerspew')) {
1454
		$mt = microtime();
1455
		echo "system_hostname_configure() being called $mt\n";
1456
	}
1457

    
1458
	$syscfg = config_get_path('system');
1459

    
1460
	/* set hostname */
1461
	$status = mwexec("/bin/hostname " .
1462
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
1463

    
1464
	/* Setup host GUID ID.  This is used by ZFS. */
1465
	mwexec("/etc/rc.d/hostid start");
1466

    
1467
	return $status;
1468
}
1469

    
1470
function system_routing_configure($interface = "") {
1471
	if (config_path_enabled('system', 'developerspew')) {
1472
		$mt = microtime();
1473
		echo "system_routing_configure() being called $mt\n";
1474
	}
1475

    
1476
	$gateways_arr = get_gateways(GW_CACHE_LOCALHOST);
1477
	foreach ($gateways_arr as $gateway) {
1478
		// setup static interface routes for nonlocal gateways
1479
		if (isset($gateway["nonlocalgateway"])) {
1480
			$srgatewayip = $gateway['gateway'];
1481
			$srinterfacegw = $gateway['interface'];
1482
			if (is_ipaddr($srgatewayip) && !empty($srinterfacegw)) {
1483
				route_add_or_change($srgatewayip, '',
1484
				    $srinterfacegw);
1485
			}
1486
		}
1487
	}
1488

    
1489
	$gateways_status = return_gateways_status(true);
1490
	fixup_default_gateway("inet", $gateways_status, $gateways_arr);
1491
	fixup_default_gateway("inet6", $gateways_status, $gateways_arr);
1492

    
1493
	system_staticroutes_configure($interface, false);
1494

    
1495
	return 0;
1496
}
1497

    
1498
function system_staticroutes_configure($interface = "", $update_dns = false) {
1499
	global $g, $aliastable;
1500

    
1501
	$filterdns_list = array();
1502

    
1503
	$static_routes = get_staticroutes(false, true);
1504
	if (count($static_routes)) {
1505
		$gateways_arr = get_gateways(GW_CACHE_LOCALHOST);
1506

    
1507
		foreach ($static_routes as $rtent) {
1508
			/* Do not delete disabled routes,
1509
			 * see https://redmine.pfsense.org/issues/3709
1510
			 * and https://redmine.pfsense.org/issues/10706 */
1511
			if (isset($rtent['disabled'])) {
1512
				continue;
1513
			}
1514

    
1515
			if (empty($gateways_arr[$rtent['gateway']])) {
1516
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
1517
				continue;
1518
			}
1519
			$gateway = $gateways_arr[$rtent['gateway']];
1520
			if (!empty($interface) && $interface != $gateway['friendlyiface']) {
1521
				continue;
1522
			}
1523

    
1524
			$gatewayip = $gateway['gateway'];
1525
			$interfacegw = $gateway['interface'];
1526

    
1527
			$blackhole = "";
1528
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 4))) {
1529
				$blackhole = "-blackhole";
1530
			}
1531

    
1532
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network'])) {
1533
				continue;
1534
			}
1535

    
1536
			$dnscache = array();
1537
			if ($update_dns === true) {
1538
				if (is_subnet($rtent['network'])) {
1539
					continue;
1540
				}
1541
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
1542
				if (empty($dnscache)) {
1543
					continue;
1544
				}
1545
			}
1546

    
1547
			if (is_subnet($rtent['network'])) {
1548
				$ips = array($rtent['network']);
1549
			} else {
1550
				if (!isset($rtent['disabled'])) {
1551
					$filterdns_list[] = $rtent['network'];
1552
				}
1553
				$ips = add_hostname_to_watch($rtent['network']);
1554
			}
1555

    
1556
			foreach ($dnscache as $ip) {
1557
				if (in_array($ip, $ips)) {
1558
					continue;
1559
				}
1560
				route_del($ip);
1561
			}
1562

    
1563
			if (isset($rtent['disabled'])) {
1564
				/*
1565
				 * XXX: This can break things by deleting
1566
				 * routes that shouldn't be deleted - OpenVPN,
1567
				 * dynamic routing scenarios, etc.
1568
				 * redmine #3709
1569
				 */
1570
				foreach ($ips as $ip) {
1571
					route_del($ip);
1572
				}
1573
				continue;
1574
			}
1575

    
1576
			foreach ($ips as $ip) {
1577
				if (is_ipaddrv4($ip)) {
1578
					$ip .= "/32";
1579
				}
1580
				/*
1581
				 * do NOT do the same check here on v6,
1582
				 * is_ipaddrv6 returns true when including
1583
				 * the CIDR mask. doing so breaks v6 routes
1584
				 */
1585
				if (is_subnet($ip)) {
1586
					if (is_ipaddr($gatewayip)) {
1587
						if (is_linklocal($gatewayip) == "6" &&
1588
						    !strpos($gatewayip, '%')) {
1589
							/*
1590
							 * add interface scope
1591
							 * for link local v6
1592
							 * routes
1593
							 */
1594
							$gatewayip .= "%$interfacegw";
1595
						}
1596
						route_add_or_change($ip,
1597
						    $gatewayip, '', $blackhole);
1598
					} else if (!empty($interfacegw)) {
1599
						route_add_or_change($ip,
1600
						    '', $interfacegw, $blackhole);
1601
					}
1602
				}
1603
			}
1604
		}
1605
		unset($gateways_arr);
1606

    
1607
		/* keep static routes cache,
1608
		 * see https://redmine.pfsense.org/issues/11599 */
1609
		$id = 0;
1610
		foreach (config_get_path('staticroutes/route', []) as $sroute) {
1611
			$targets = array();
1612
			if (is_subnet($sroute['network'])) {
1613
				$targets[] = $sroute['network'];
1614
			} elseif (is_alias($sroute['network'])) {
1615
				foreach (preg_split('/\s+/', $aliastable[$sroute['network']]) as $tgt) {
1616
					if (is_ipaddrv4($tgt)) {
1617
						$tgt .= "/32";
1618
					}
1619
					if (is_ipaddrv6($tgt)) {
1620
						$tgt .= "/128";
1621
					}
1622
					if (!is_subnet($tgt)) {
1623
						continue;
1624
					}
1625
					$targets[] = $tgt;
1626
				}
1627
			}
1628
			file_put_contents("{$g['tmp_path']}/staticroute_{$id}", serialize($targets));
1629
			file_put_contents("{$g['tmp_path']}/staticroute_{$id}_gw", serialize($sroute['gateway']));
1630
			$id++;
1631
		}
1632
	}
1633
	unset($static_routes);
1634

    
1635
	if ($update_dns === false) {
1636
		if (count($filterdns_list)) {
1637
			$interval = 60;
1638
			$hostnames = "";
1639
			array_unique($filterdns_list);
1640
			foreach ($filterdns_list as $hostname) {
1641
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
1642
			}
1643
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
1644
			unset($hostnames);
1645

    
1646
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid")) {
1647
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
1648
			} else {
1649
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
1650
			}
1651
		} else {
1652
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
1653
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
1654
		}
1655
	}
1656
	unset($filterdns_list);
1657

    
1658
	return 0;
1659
}
1660

    
1661
function delete_static_route($id, $delete = false) {
1662
	global $g, $changedesc_prefix, $a_gateways;
1663

    
1664
	if (empty(config_get_path("staticroutes/route/{$id}"))) {
1665
		return;
1666
	}
1667

    
1668
	if (file_exists("{$g['tmp_path']}/.system_routes.apply")) {
1669
		$toapplylist = unserialize_data(file_get_contents("{$g['tmp_path']}/.system_routes.apply"), []);
1670
	} else {
1671
		$toapplylist = array();
1672
	}
1673

    
1674
	if (file_exists("{$g['tmp_path']}/staticroute_{$id}") &&
1675
	    file_exists("{$g['tmp_path']}/staticroute_{$id}_gw")) {
1676
		$delete_targets = unserialize_data(file_get_contents("{$g['tmp_path']}/staticroute_{$id}"), []);
1677
		$delgw = lookup_gateway_ip_by_name(unserialize_data(file_get_contents("{$g['tmp_path']}/staticroute_{$id}_gw")));
1678
		if (count($delete_targets)) {
1679
			foreach ($delete_targets as $dts) {
1680
				if (is_subnetv4($dts)) {
1681
					$family = "-inet";
1682
				} else {
1683
					$family = "-inet6";
1684
				}
1685
				$route = route_get($dts, '', true);
1686
				if (!count($route)) {
1687
					continue;
1688
				}
1689
				$toapplylist[] = "/sbin/route delete " .
1690
				    $family . " " . $dts . " " . $delgw;
1691
			}
1692
		}
1693
	}
1694

    
1695
	if ($delete) {
1696
		unlink_if_exists("{$g['tmp_path']}/staticroute_{$id}");
1697
		unlink_if_exists("{$g['tmp_path']}/staticroute_{$id}_gw");
1698
	}
1699

    
1700
	if (!empty($toapplylist)) {
1701
		file_put_contents("{$g['tmp_path']}/.system_routes.apply", serialize($toapplylist));
1702
	}
1703

    
1704
	unset($targets);
1705
}
1706

    
1707
function system_routing_enable() {
1708
	if (config_path_enabled('system', 'developerspew')) {
1709
		$mt = microtime();
1710
		echo "system_routing_enable() being called $mt\n";
1711
	}
1712

    
1713
	set_sysctl(array(
1714
		"net.inet.ip.forwarding" => "1",
1715
		"net.inet6.ip6.forwarding" => "1"
1716
	));
1717

    
1718
	return;
1719
}
1720

    
1721
function system_webgui_start() {
1722
	global $g;
1723

    
1724
	if (is_platform_booting()) {
1725
		echo gettext("Starting webConfigurator...");
1726
	}
1727

    
1728
	chdir(g_get('www_path'));
1729

    
1730
	/* defaults */
1731
	$portarg = config_get_path('system/webgui/port', '80');
1732
	$crt = "";
1733
	$key = "";
1734
	$ca = "";
1735

    
1736
	if (config_get_path('system/webgui/protocol') == "https") {
1737
		// Ensure that we have a webConfigurator CERT
1738
		$cert = lookup_cert(config_get_path('system/webgui/ssl-certref'));
1739
		$cert = $cert['item'];
1740
		if (!is_array($cert) || !$cert['crt'] || !$cert['prv'] ||
1741
		    cert_chain_has_weak_digest($cert)) {
1742
			$cert = cert_create_selfsigned();
1743
			if (is_array($cert) && !empty($cert)) {
1744
				config_set_path('system/webgui/ssl-certref', $cert['refid']);
1745
				write_config(sprintf(gettext("Generated new self-signed SSL/TLS certificate for HTTPS (%s)"), $cert['refid']));
1746
			} else {
1747
				log_error(sprintf(gettext("GUI certificate is not usable and there was an error creating a new self-signed certificate.")));
1748
			}
1749
		}
1750
		$crt = base64_decode($cert['crt']);
1751
		$key = base64_decode($cert['prv']);
1752

    
1753
		$portarg = config_get_path('system/webgui/port', '443');
1754
		$ca = ca_chain($cert);
1755
		$hsts = !config_path_enabled('system/webgui', 'disablehsts');
1756
	}
1757

    
1758
	/* generate nginx configuration */
1759
	system_generate_nginx_config("{$g['varetc_path']}/nginx-webConfigurator.conf",
1760
		$crt, $key, $ca, "nginx-webConfigurator.pid", $portarg, "/usr/local/www/",
1761
		"cert.crt", "cert.key", false, $hsts);
1762

    
1763
	/* kill any running nginx */
1764
	killbypid("{$g['varrun_path']}/nginx-webConfigurator.pid");
1765

    
1766
	sleep(1);
1767

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

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

    
1773
	if (is_platform_booting()) {
1774
		if ($res == 0) {
1775
			echo gettext("done.") . "\n";
1776
		} else {
1777
			echo gettext("failed!") . "\n";
1778
		}
1779
	}
1780

    
1781
	return $res;
1782
}
1783

    
1784
/****f* system.inc/get_dns_nameservers
1785
 * NAME
1786
 *   get_dns_nameservers - Get system DNS servers
1787
 * INPUTS
1788
 *   $add_v6_brackets: (boolean, false)
1789
 *                     Add brackets around IPv6 DNS servers, as expected by some
1790
 *                     daemons such as nginx.
1791
 *   $hostns         : (boolean, true)
1792
 *                     true : Return only DNS servers used by the firewall
1793
 *                            itself as upstream forwarding servers
1794
 *                     false: Return all DNS servers from the configuration and
1795
 *                            overrides (if allowed).
1796
 * RESULT
1797
 *   $dns_nameservers - An array of the requested DNS servers
1798
 ******/
1799
function get_dns_nameservers($add_v6_brackets = false, $hostns=true) {
1800
	$dns_nameservers = array();
1801

    
1802
	if (config_path_enabled('system', 'developerspew')) {
1803
		$mt = microtime();
1804
		echo "get_dns_nameservers() being called $mt\n";
1805
	}
1806

    
1807
	if ((((config_path_enabled('dnsmasq') &&
1808
		  (config_get_path('dnsmasq/port', '53') == '53') &&
1809
		  in_array("lo0", explode(",", config_get_path('dnsmasq/interface', 'lo0'))))) ||
1810
	    (config_path_enabled('unbound') &&
1811
		 (config_get_path('unbound/port', '53') == '53') &&
1812
		 (in_array("lo0", explode(",", config_get_path('unbound/active_interface', 'lo0'))) ||
1813
		  in_array("all", explode(",", config_get_path('unbound/active_interface', 'all')), true)))) &&
1814
	    (config_get_path('system/dnslocalhost') != 'remote')) {
1815
		$dns_nameservers[] = "127.0.0.1";
1816
		$dns_nameservers[] = $add_v6_brackets ? '[::1]' : '::1';
1817
	}
1818

    
1819
	if ($hostns || (config_get_path('system/dnslocalhost') != 'local')) {
1820
		if (config_path_enabled('system', 'dnsallowoverride')) {
1821
			/* get dynamically assigned DNS servers (if any) */
1822
			foreach (array_unique(get_dynamic_nameservers()) as $nameserver) {
1823
				if ($nameserver) {
1824
					if ($add_v6_brackets && is_ipaddrv6($nameserver)) {
1825
						$nameserver = "[{$nameserver}]";
1826
					}
1827
					$dns_nameservers[] = $nameserver;
1828
				}
1829
			}
1830
		}
1831
		foreach (config_get_path('system/dnsserver', []) as $sys_dnsserver) {
1832
			if ($sys_dnsserver && (!in_array($sys_dnsserver, $dns_nameservers))) {
1833
				if ($add_v6_brackets && is_ipaddrv6($sys_dnsserver)) {
1834
					$sys_dnsserver = "[{$sys_dnsserver}]";
1835
				}
1836
				$dns_nameservers[] = $sys_dnsserver;
1837
			}
1838
		}
1839
	}
1840
	return array_unique($dns_nameservers);
1841
}
1842

    
1843
function system_generate_nginx_config($filename,
1844
	$cert,
1845
	$key,
1846
	$ca,
1847
	$pid_file,
1848
	$port = 80,
1849
	$document_root = "/usr/local/www/",
1850
	$cert_location = "cert.crt",
1851
	$key_location = "cert.key",
1852
	$captive_portal = false,
1853
	$hsts = true) {
1854

    
1855
	global $g;
1856

    
1857
	if (config_path_enabled('system', 'developerspew')) {
1858
		$mt = microtime();
1859
		echo "system_generate_nginx_config() being called $mt\n";
1860
	}
1861

    
1862
	if ($captive_portal !== false) {
1863
		$cp_interfaces = array_filter(explode(",", config_get_path("captiveportal/{$captive_portal}/interface")));
1864
		$cp_hostcheck = "";
1865
		foreach ($cp_interfaces as $cpint) {
1866
			$cpint_ip = get_interface_ip($cpint);
1867
			if (is_ipaddr($cpint_ip)) {
1868
				$cp_hostcheck .= "\t\tif (\$http_host ~* $cpint_ip) {\n";
1869
				$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1870
				$cp_hostcheck .= "\t\t}\n";
1871
			}
1872
		}
1873
		$httpsname = config_get_path("captiveportal/{$captive_portal}/httpsname");
1874
		if (!empty($httpsname) &&
1875
		    is_domain($httpsname)) {
1876
			$cp_hostcheck .= "\t\tif (\$http_host ~* {$httpsname}) {\n";
1877
			$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1878
			$cp_hostcheck .= "\t\t}\n";
1879
		}
1880
		$cp_rewrite = "\t\tif (\$cp_redirect = '') {\n";
1881
		$cp_rewrite .= "\t\t\trewrite	^ /index.php?zone=$captive_portal&redirurl=\$request_uri break;\n";
1882
		$cp_rewrite .= "\t\t}\n";
1883

    
1884
		$maxprocperip = config_get_path("captiveportal/{$captive_portal}/maxprocperip");
1885
		if (empty($maxprocperip)) {
1886
			$maxprocperip = 10;
1887
		}
1888
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1889
	}
1890

    
1891
	if (empty($port)) {
1892
		$nginx_port = "80";
1893
	} else {
1894
		$nginx_port = $port;
1895
	}
1896

    
1897
	$memory = get_memory();
1898
	$realmem = $memory[1];
1899

    
1900
	// Determine web GUI process settings and take into account low memory systems
1901
	if ($realmem < 255) {
1902
		$max_procs = 1;
1903
	} else {
1904
		$max_procs = config_get_path('system/webgui/max_procs', 2);
1905
	}
1906

    
1907
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM
1908
	if ($captive_portal !== false) {
1909
		if ($realmem > 135 and $realmem < 256) {
1910
			$max_procs += 1; // 2 worker processes
1911
		} else if ($realmem > 255 and $realmem < 513) {
1912
			$max_procs += 2; // 3 worker processes
1913
		} else if ($realmem > 512) {
1914
			$max_procs += 4; // 6 worker processes
1915
		}
1916
	}
1917

    
1918
	$nginx_config = <<<EOD
1919
#
1920
# nginx configuration file
1921

    
1922
pid {$g['varrun_path']}/{$pid_file};
1923

    
1924
user  root wheel;
1925
worker_processes  {$max_procs};
1926

    
1927
EOD;
1928

    
1929
	/* Disable file logging */
1930
	$nginx_config .= "error_log /dev/null;\n";
1931
	if (!config_path_enabled('syslog','nolognginx')) {
1932
		/* Send nginx error log to syslog */
1933
		$nginx_config .= "error_log  syslog:server=unix:/var/run/log,facility=local5;\n";
1934
	}
1935

    
1936
	$nginx_config .= <<<EOD
1937

    
1938
events {
1939
    worker_connections  1024;
1940
}
1941

    
1942
http {
1943
	include       /usr/local/etc/nginx/mime.types;
1944
	default_type  application/octet-stream;
1945
	add_header X-Frame-Options SAMEORIGIN;
1946
	server_tokens off;
1947

    
1948
	sendfile        off;
1949

    
1950
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1951

    
1952
EOD;
1953

    
1954
	if ($captive_portal !== false) {
1955
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1956
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1957
		$intercept_errors = "";
1958
	} else {
1959
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1960
		$nginx_config .= "\terror_page 404 /404.html;\n";
1961
		$nginx_config .= "\terror_page 500 502 503 504 /50x.html;\n";
1962
		$intercept_errors = "\t\t\tfastcgi_intercept_errors on;\n";
1963
	}
1964
	$nginx_config .= "\tclient_header_timeout 10;\n";
1965

    
1966
	if ($cert <> "" and $key <> "") {
1967
		$nginx_config .= "\n";
1968
		$nginx_config .= "\tserver {\n";
1969
		$nginx_config .= "\t\tlisten {$nginx_port} ssl;\n";
1970
		$nginx_config .= "\t\tlisten [::]:{$nginx_port} ssl;\n";
1971
		$nginx_config .= "\t\thttp2 on;\n";
1972
		$nginx_config .= "\n";
1973
		$nginx_config .= "\t\tssl_certificate         {$g['varetc_path']}/{$cert_location};\n";
1974
		$nginx_config .= "\t\tssl_certificate_key     {$g['varetc_path']}/{$key_location};\n";
1975
		$nginx_config .= "\t\tssl_session_timeout     10m;\n";
1976
		$nginx_config .= "\t\tkeepalive_timeout       70;\n";
1977
		$nginx_config .= "\t\tssl_session_cache       shared:SSL:10m;\n";
1978
		if ($captive_portal !== false) {
1979
			// leave TLSv1.1 for CP for now for compatibility
1980
			$nginx_config .= "\t\tssl_protocols   TLSv1.1 TLSv1.2 TLSv1.3;\n";
1981
		} else {
1982
			$nginx_config .= "\t\tssl_protocols   TLSv1.2 TLSv1.3;\n";
1983
		}
1984
		$nginx_config .= "\t\tssl_ciphers \"EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305\";\n";
1985
		$nginx_config .= "\t\tssl_prefer_server_ciphers       on;\n";
1986
		if ($captive_portal === false && $hsts !== false) {
1987
			$nginx_config .= "\t\tadd_header Strict-Transport-Security \"max-age=31536000\";\n";
1988
		}
1989
		$nginx_config .= "\t\tadd_header X-Content-Type-Options nosniff;\n";
1990
		$nginx_config .= "\t\tssl_session_tickets off;\n";
1991
		$nginx_config .= "\t\tssl_dhparam /etc/dh-parameters.4096;\n";
1992
		$cert_temp = lookup_cert(config_get_path('system/webgui/ssl-certref'));
1993
		$cert_temp = $cert_temp['item'];
1994
		if ((config_get_path('system/webgui/ocsp-staple') == true) or
1995
		    (cert_get_ocspstaple($cert_temp['crt']) == true)) {
1996
			$nginx_config .= "\t\tssl_stapling on;\n";
1997
			$nginx_config .= "\t\tssl_stapling_verify on;\n";
1998
			$nginx_config .= "\t\tresolver " . implode(" ", get_dns_nameservers(true)) . " valid=300s;\n";
1999
			$nginx_config .= "\t\tresolver_timeout 5s;\n";
2000
		}
2001
	} else {
2002
		$nginx_config .= "\n";
2003
		$nginx_config .= "\tserver {\n";
2004
		$nginx_config .= "\t\tlisten {$nginx_port};\n";
2005
		$nginx_config .= "\t\tlisten [::]:{$nginx_port};\n";
2006
	}
2007

    
2008
	$nginx_config .= <<<EOD
2009

    
2010
		client_max_body_size 200m;
2011

    
2012
		gzip on;
2013
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
2014

    
2015

    
2016
EOD;
2017

    
2018
	if ($captive_portal !== false) {
2019
		$nginx_config .= <<<EOD
2020
$captive_portal_maxprocperip
2021
$cp_hostcheck
2022
$cp_rewrite
2023
		log_not_found off;
2024

    
2025
EOD;
2026

    
2027
	}
2028

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

    
2041
	$nginx_config .= <<<EOD
2042
		root "{$document_root}";
2043
		location / {
2044
			index  index.php index.html index.htm;
2045
		}
2046
		location ~ (\.inc$|\.orig$|\.pkgsave$) {
2047
			deny all;
2048
			return 403;
2049
		}
2050
		location ~ \.php$ {
2051
			try_files \$uri =404; #  This line closes a potential security hole
2052
			# ensuring users can't execute uploaded files
2053
			# see: https://forum.nginx.org/read.php?2,88845,page=3
2054
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
2055
			fastcgi_index  index.php;
2056
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
2057
			# Fix httpoxy - https://httpoxy.org/#fix-now
2058
			fastcgi_param  HTTP_PROXY  "";
2059
			fastcgi_read_timeout 180;
2060
{$intercept_errors}
2061
			include        /usr/local/etc/nginx/fastcgi_params;
2062
		}
2063
		location ~ (^/status$) {
2064
			allow 127.0.0.1;
2065
			deny all;
2066
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
2067
			fastcgi_index  index.php;
2068
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
2069
			# Fix httpoxy - https://httpoxy.org/#fix-now
2070
			fastcgi_param  HTTP_PROXY  "";
2071
			fastcgi_read_timeout 360;
2072
			include        /usr/local/etc/nginx/fastcgi_params;
2073
		}
2074
		{$plugin_locations}
2075
	}
2076

    
2077
EOD;
2078

    
2079
	$cert = str_replace("\r", "", $cert);
2080
	$key = str_replace("\r", "", $key);
2081

    
2082
	$cert = str_replace("\n\n", "\n", $cert);
2083
	$key = str_replace("\n\n", "\n", $key);
2084

    
2085
	if ($cert <> "" and $key <> "") {
2086
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
2087
		if (!$fd) {
2088
			printf(gettext("Error: cannot open certificate file in system_webgui_start().%s"), "\n");
2089
			return 1;
2090
		}
2091
		chmod("{$g['varetc_path']}/{$cert_location}", 0644);
2092
		if ($ca <> "") {
2093
			$cert_chain = $cert . "\n" . $ca;
2094
		} else {
2095
			$cert_chain = $cert;
2096
		}
2097
		fwrite($fd, $cert_chain);
2098
		fclose($fd);
2099
		$fd = fopen("{$g['varetc_path']}/{$key_location}", "w");
2100
		if (!$fd) {
2101
			printf(gettext("Error: cannot open certificate key file in system_webgui_start().%s"), "\n");
2102
			return 1;
2103
		}
2104
		chmod("{$g['varetc_path']}/{$key_location}", 0600);
2105
		fwrite($fd, $key);
2106
		fclose($fd);
2107
	}
2108

    
2109
	// Add HTTP to HTTPS redirect
2110
	if ($captive_portal === false && config_get_path('system/webgui/protocol') == "https" && !(config_path_enabled('system/webgui', 'disablehttpredirect') != null)) {
2111
		if ($nginx_port != "443") {
2112
			$redirectport = ":{$nginx_port}";
2113
		}
2114
		$nginx_config .= <<<EOD
2115
	server {
2116
		listen 80;
2117
		listen [::]:80;
2118
		return 301 https://\$http_host$redirectport\$request_uri;
2119
	}
2120

    
2121
EOD;
2122
	}
2123

    
2124
	if ($captive_portal == false) {
2125
		$pluginparams = [ 'section' => 'server' ];
2126
		foreach (pkg_call_plugins('plugin_nginx', $pluginparams) as $pkgname => $server) {
2127
			if (empty($server)) {
2128
				continue;
2129
			}
2130
			$nginx_config .= "	# Plugin Servers ({$pkgname})\n";
2131
			$nginx_config .= "{$server}\n";
2132
		}
2133
	}
2134

    
2135
	$nginx_config .= "}\n";
2136

    
2137
	$fd = fopen("{$filename}", "w");
2138
	if (!$fd) {
2139
		printf(gettext('Error: cannot open %1$s in system_generate_nginx_config().%2$s'), $filename, "\n");
2140
		return 1;
2141
	}
2142
	fwrite($fd, $nginx_config);
2143
	fclose($fd);
2144

    
2145
	/* nginx will fail to start if this directory does not exist. */
2146
	safe_mkdir("/var/tmp/nginx/");
2147

    
2148
	return 0;
2149

    
2150
}
2151

    
2152
function system_get_timezone_list() {
2153
	global $g;
2154

    
2155
	$file_list = array_merge(
2156
		glob("/usr/share/zoneinfo/[A-Z]*"),
2157
		glob("/usr/share/zoneinfo/*/*"),
2158
		glob("/usr/share/zoneinfo/*/*/*")
2159
	);
2160

    
2161
	if (empty($file_list)) {
2162
		$file_list[] = g_get('default_timezone');
2163
	} else {
2164
		/* Remove directories from list */
2165
		$file_list = array_filter($file_list, function($v) {
2166
			return !is_dir($v);
2167
		});
2168
	}
2169

    
2170
	/* Remove directory prefix */
2171
	$file_list = str_replace('/usr/share/zoneinfo/', '', $file_list);
2172

    
2173
	sort($file_list);
2174

    
2175
	return $file_list;
2176
}
2177

    
2178
function system_timezone_configure() {
2179
	global $g;
2180
	if (config_path_enabled('system', 'developerspew')) {
2181
		$mt = microtime();
2182
		echo "system_timezone_configure() being called $mt\n";
2183
	}
2184

    
2185
	$syscfg = config_get_path('system');
2186

    
2187
	if (is_platform_booting()) {
2188
		echo gettext("Setting timezone...");
2189
	}
2190

    
2191
	/* extract appropriate timezone file */
2192
	$timezone = (isset($syscfg['timezone']) ? $syscfg['timezone'] : g_get('default_timezone'));
2193
	/* DO NOT remove \n otherwise tzsetup will fail */
2194
	@file_put_contents("/var/db/zoneinfo", $timezone . "\n");
2195
	mwexec("/usr/sbin/tzsetup -r");
2196

    
2197
	if (is_platform_booting()) {
2198
		echo gettext("done.") . "\n";
2199
	}
2200
}
2201

    
2202
function check_gps_speed($device) {
2203
	usleep(1000);
2204
	// Set timeout to 5s
2205
	$timeout=microtime(true)+5;
2206
	if ($fp = fopen($device, 'r')) {
2207
		stream_set_blocking($fp, 0);
2208
		stream_set_timeout($fp, 5);
2209
		$contents = "";
2210
		$cnt = 0;
2211
		$buffersize = 256;
2212
		do {
2213
			$c = fread($fp, $buffersize - $cnt);
2214

    
2215
			// Wait for data to arive
2216
			if (($c === false) || (strlen($c) == 0)) {
2217
				usleep(500);
2218
				continue;
2219
			}
2220

    
2221
			$contents.=$c;
2222
			$cnt = $cnt + strlen($c);
2223
		} while (($cnt < $buffersize) && (microtime(true) < $timeout));
2224
		fclose($fp);
2225

    
2226
		$nmeasentences = ['RMC', 'GGA', 'GLL', 'ZDA', 'ZDG', 'PGRMF'];
2227
		foreach ($nmeasentences as $sentence) {
2228
			if (strpos($contents, $sentence) > 0) {
2229
				return true;
2230
			}
2231
		}
2232
		if (strpos($contents, '0') > 0) {
2233
			$filters = ['`', '?', '/', '~'];
2234
			foreach ($filters as $filter) {
2235
				if (strpos($contents, $filter) !== false) {
2236
					return false;
2237
				}
2238
			}
2239
			return true;
2240
		}
2241
	}
2242
	return false;
2243
}
2244

    
2245
/* Generate list of possible NTP poll values
2246
 * https://redmine.pfsense.org/issues/9439 */
2247
global $ntp_poll_min_value, $ntp_poll_max_value;
2248
global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
2249
global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
2250
global $ntp_poll_min_default, $ntp_poll_max_default;
2251
global $ntp_auth_halgos, $ntp_server_types;
2252
$ntp_poll_min_value = 3;
2253
$ntp_poll_max_value = 17;
2254
$ntp_poll_min_default_gps = 4;
2255
$ntp_poll_max_default_gps = 4;
2256
$ntp_poll_min_default_pps = 4;
2257
$ntp_poll_max_default_pps = 4;
2258
$ntp_poll_min_default = 'omit';
2259
$ntp_poll_max_default = 9;
2260
$ntp_auth_halgos = array(
2261
	'md5' => 'MD5',
2262
	'sha1' => 'SHA1',
2263
	'sha256' => 'SHA256'
2264
);
2265
$ntp_server_types = array(
2266
	'server' => 'Server',
2267
	'pool' => 'Pool',
2268
	'peer' => 'Peer'
2269
);
2270

    
2271
function system_ntp_poll_values() {
2272
	global $ntp_poll_min_value, $ntp_poll_max_value;
2273
	$poll_values = array("" => gettext('Default'));
2274

    
2275
	for ($i = $ntp_poll_min_value; $i <= $ntp_poll_max_value; $i++) {
2276
		$sec = 2 ** $i;
2277
		$poll_values[$i] = $i . ': ' . number_format($sec) . ' ' . gettext('seconds') .
2278
					' (' . convert_seconds_to_dhms($sec) . ')';
2279
	}
2280

    
2281
	$poll_values['omit'] = gettext('Omit (Do not set)');
2282
	return $poll_values;
2283
}
2284

    
2285
function system_ntp_fixup_poll_value($type, $configvalue, $default) {
2286
	$pollstring = "";
2287

    
2288
	if (empty($configvalue)) {
2289
		$configvalue = $default;
2290
	}
2291

    
2292
	if ($configvalue != 'omit') {
2293
		$pollstring = " {$type} {$configvalue}";
2294
	}
2295

    
2296
	return $pollstring;
2297
}
2298

    
2299
function system_ntp_setup_gps($serialport) {
2300
	if (config_get_path('ntpd/enable') == 'disabled') {
2301
		return false;
2302
	}
2303

    
2304
	$serialports = get_serial_ports(true);
2305

    
2306
	if (!array_key_exists($serialport, $serialports)) {
2307
		return false;
2308
	}
2309

    
2310
	$gps_device = '/dev/gps0';
2311
	$serialport = '/dev/'.basename($serialport);
2312

    
2313
	if (!file_exists($serialport)) {
2314
		return false;
2315
	}
2316

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

    
2321
	$speeds = array(
2322
		0 => '4800',
2323
		16 => '9600',
2324
		32 => '19200',
2325
		48 => '38400',
2326
		64 => '57600',
2327
		80 => '115200'
2328
	);
2329
	// $gpsbaud defaults to '4800' if ntpd/gps/speed is unset or does not exist in $speeds
2330
	$gpsbaud = array_get_path($speeds, config_get_path('ntpd/gps/speed', 0), '4800');
2331

    
2332
	system_ntp_setup_rawspeed($serialport, $gpsbaud);
2333

    
2334
	$gpsspeed = config_get_path('ntpd/gps/speed');
2335
	$autospeed = ($gpsspeed == 'autoalways' || $gpsspeed == 'autoset');
2336
	if ($autospeed || (config_get_path('ntpd/gps/autobaudinit') && !check_gps_speed($gps_device))) {
2337
		$found = false;
2338
		foreach ($speeds as $baud) {
2339
			system_ntp_setup_rawspeed($serialport, $baud);
2340
			if ($found = check_gps_speed($gps_device)) {
2341
				if ($autospeed) {
2342
					$saveconfig = (config_get_path('ntpd/gps/speed') == 'autoset');
2343
					config_set_path('ntpd/gps/speed', array_search($baud, $speeds));
2344
					$gpsbaud = $baud;
2345
					if ($saveconfig) {
2346
						write_config(sprintf(gettext('Autoset GPS baud rate to %s'), $baud));
2347
					}
2348
				}
2349
				break;
2350
			}
2351
		}
2352
		if ($found === false) {
2353
			log_error(gettext("Could not find correct GPS baud rate."));
2354
			return false;
2355
		}
2356
	}
2357

    
2358
	/* Send the following to the GPS port to initialize the GPS */
2359
	if (!empty(config_get_path('ntpd/gps/type'))) {
2360
		$gps_init = base64_decode(config_get_path('ntpd/gps/initcmd'));
2361
	} else {
2362
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
2363
	}
2364

    
2365
	/* XXX: Why not file_put_contents to the device */
2366
	@file_put_contents('/tmp/gps.init', $gps_init);
2367
	mwexec("/bin/cat /tmp/gps.init > {$serialport}");
2368

    
2369
	if ($found && config_get_path('ntpd/gps/autobaudinit')) {
2370
		system_ntp_setup_rawspeed($serialport, $gpsbaud);
2371
	}
2372

    
2373
	/* Remove old /etc/remote entry if it exists */
2374
	if (mwexec("/usr/bin/grep -c '^gps0' /etc/remote") == 0) {
2375
		mwexec("/usr/bin/sed -i '' -n '/gps0/!p' /etc/remote");
2376
	}
2377

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

    
2383
	return true;
2384
}
2385

    
2386
// Configure the serial port for raw IO and set the speed
2387
function system_ntp_setup_rawspeed($serialport, $baud) {
2388
	mwexec("/bin/stty -f " .  escapeshellarg($serialport) . " raw speed " . escapeshellarg($baud));
2389
	mwexec("/bin/stty -f " .  escapeshellarg($serialport) . ".init raw speed " . escapeshellarg($baud));
2390
}
2391

    
2392
function system_ntp_setup_pps($serialport) {
2393
	$serialports = get_serial_ports(true);
2394

    
2395
	if (!array_key_exists($serialport, $serialports)) {
2396
		return false;
2397
	}
2398

    
2399
	$pps_device = '/dev/pps0';
2400
	$serialport = '/dev/'.basename($serialport);
2401

    
2402
	if (!file_exists($serialport)) {
2403
		return false;
2404
	}
2405
	// If ntpd is disabled, just return
2406
	if (config_get_path('ntpd/enable') == 'disabled') {
2407
		return false;
2408
	}
2409

    
2410
	// Create symlink that ntpd requires
2411
	unlink_if_exists($pps_device);
2412
	@symlink($serialport, $pps_device);
2413

    
2414

    
2415
	return true;
2416
}
2417

    
2418
function system_ntp_configure() {
2419
	global $g;
2420
	global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
2421
	global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
2422
	global $ntp_poll_min_default, $ntp_poll_max_default;
2423

    
2424
	$driftfile = "/var/db/ntpd.drift";
2425
	$statsdir = "/var/log/ntp";
2426
	$gps_device = '/dev/gps0';
2427
	$ntp_keyid = config_get_path('ntpd/serverauthkeyid', '1');
2428

    
2429
	safe_mkdir($statsdir);
2430

    
2431
	// ntpd is disabled, just stop it and return
2432
	if (config_get_path('ntpd/enable') == 'disabled') {
2433
		while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
2434
			killbypid("{$g['varrun_path']}/ntpd.pid");
2435
		}
2436
		@unlink("{$g['varrun_path']}/ntpd.pid");
2437
		@unlink("{$g['varetc_path']}/ntpd.conf");
2438
		@unlink("{$g['varetc_path']}/ntp.keys");
2439
		log_error("NTPD is disabled.");
2440
		return;
2441
	}
2442

    
2443
	if (is_platform_booting()) {
2444
		echo gettext("Starting NTP Server...");
2445
	}
2446

    
2447
	/* if ntpd is running, kill it */
2448
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
2449
		killbypid("{$g['varrun_path']}/ntpd.pid");
2450
	}
2451
	@unlink("{$g['varrun_path']}/ntpd.pid");
2452

    
2453
	/* set NTP server authentication key */
2454
	if (config_get_path('ntpd/serverauth') == 'yes') {
2455
		$ntpkeyscfg = "{$ntp_keyid} " . strtoupper(config_get_path('ntpd/serverauthalgo')) . " " . base64_decode(config_get_path('ntpd/serverauthkey')) . "\n";
2456
		if (!@file_put_contents("{$g['varetc_path']}/ntp.keys", $ntpkeyscfg)) {
2457
			log_error(sprintf(gettext("Could not open %s/ntp.keys for writing"), g_get('varetc_path')));
2458
			return;
2459
		}
2460
	} else {
2461
		unlink_if_exists("{$g['varetc_path']}/ntp.keys");
2462
	}
2463

    
2464
	$ntpcfg = "# \n";
2465
	$ntpcfg .= "# pfSense ntp configuration file \n";
2466
	$ntpcfg .= "# \n\n";
2467
	$ntpcfg .= "tinker panic 0 \n\n";
2468

    
2469
	if (config_get_path('ntpd/serverauth') == 'yes') {
2470
		$ntpcfg .= "# Authentication settings \n";
2471
		$ntpcfg .= "keys /var/etc/ntp.keys \n";
2472
		$ntpcfg .= "trustedkey {$ntp_keyid} \n";
2473
		$ntpcfg .= "requestkey {$ntp_keyid} \n";
2474
		$ntpcfg .= "controlkey {$ntp_keyid} \n";
2475
		$ntpcfg .= "\n";
2476
	}
2477

    
2478
	/* Add Orphan mode */
2479
	$ntpcfg .= "# Orphan mode stratum and Maximum candidate NTP peers\n";
2480
	$ntpcfg .= 'tos orphan ';
2481
	if (!empty(config_get_path('ntpd/orphan'))) {
2482
		$ntpcfg .= config_get_path('ntpd/orphan');
2483
	} else {
2484
		$ntpcfg .= '12';
2485
	}
2486
	/* Add Maximum candidate NTP peers */
2487
	$ntpcfg .= ' maxclock ';
2488
	if (!empty(config_get_path('ntpd/ntpmaxpeers'))) {
2489
		$ntpcfg .= config_get_path('ntpd/ntpmaxpeers');
2490
	} else {
2491
		$ntpcfg .= '5';
2492
	}
2493
	$ntpcfg .= "\n";
2494

    
2495
	/* Add PPS configuration */
2496
	if (!empty(config_get_path('ntpd/pps/port')) &&
2497
	    file_exists('/dev/'.config_get_path('ntpd/pps/port')) &&
2498
	    system_ntp_setup_pps(config_get_path('ntpd/pps/port'))) {
2499
		$ntpcfg .= "\n";
2500
		$ntpcfg .= "# PPS Setup\n";
2501
		$ntpcfg .= 'server 127.127.22.0';
2502
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', config_get_path('ntpd/pps/ppsminpoll'), $ntp_poll_min_default_pps);
2503
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', config_get_path('ntpd/pps/ppsmaxpoll'), $ntp_poll_max_default_pps);
2504
		if (empty(config_get_path('ntpd/pps/prefer'))) { /*note: this one works backwards */
2505
			$ntpcfg .= ' prefer';
2506
		}
2507
		if (!empty(config_get_path('ntpd/pps/noselect'))) {
2508
			$ntpcfg .= ' noselect ';
2509
		}
2510
		$ntpcfg .= "\n";
2511
		$ntpcfg .= 'fudge 127.127.22.0';
2512
		if (!empty(config_get_path('ntpd/pps/fudge1'))) {
2513
			$ntpcfg .= ' time1 ';
2514
			$ntpcfg .= config_get_path('ntpd/pps/fudge1');
2515
		}
2516
		if (!empty(config_get_path('ntpd/pps/flag2'))) {
2517
			$ntpcfg .= ' flag2 1';
2518
		}
2519
		if (!empty(config_get_path('ntpd/pps/flag3'))) {
2520
			$ntpcfg .= ' flag3 1';
2521
		} else {
2522
			$ntpcfg .= ' flag3 0';
2523
		}
2524
		if (!empty(config_get_path('ntpd/pps/flag4'))) {
2525
			$ntpcfg .= ' flag4 1';
2526
		}
2527
		if (!empty(config_get_path('ntpd/pps/refid'))) {
2528
			$ntpcfg .= ' refid ';
2529
			$ntpcfg .= config_get_path('ntpd/pps/refid');
2530
		}
2531
		$ntpcfg .= "\n";
2532
	}
2533
	/* End PPS configuration */
2534

    
2535
	/* Add GPS configuration */
2536
	if (!empty(config_get_path('ntpd/gps/port')) &&
2537
	    system_ntp_setup_gps(config_get_path('ntpd/gps/port'))) {
2538
		$ntpcfg .= "\n";
2539
		$ntpcfg .= "# GPS Setup\n";
2540
		$ntpcfg .= 'server 127.127.20.0 mode ';
2541
		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'))) {
2542
			if (!empty(config_get_path('ntpd/gps/nmea'))) {
2543
				$ntpmode = (int) config_get_path('ntpd/gps/nmea');
2544
			}
2545
			if (!empty(config_get_path('ntpd/gps/speed'))) {
2546
				$ntpmode += (int) config_get_path('ntpd/gps/speed');
2547
			}
2548
			if (!empty(config_get_path('ntpd/gps/subsec'))) {
2549
				$ntpmode += 128;
2550
			}
2551
			if (!empty(config_get_path('ntpd/gps/processpgrmf'))) {
2552
				$ntpmode += 256;
2553
			}
2554
			$ntpcfg .= (string) $ntpmode;
2555
		} else {
2556
			$ntpcfg .= '0';
2557
		}
2558
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', config_get_path('ntpd/gps/gpsminpoll'), $ntp_poll_min_default_gps);
2559
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', config_get_path('ntpd/gps/gpsmaxpoll'), $ntp_poll_max_default_gps);
2560

    
2561
		if (empty(config_get_path('ntpd/gps/prefer'))) { /*note: this one works backwards */
2562
			$ntpcfg .= ' prefer';
2563
		}
2564
		if (!empty(config_get_path('ntpd/gps/noselect'))) {
2565
			$ntpcfg .= ' noselect ';
2566
		}
2567
		$ntpcfg .= "\n";
2568
		$ntpcfg .= 'fudge 127.127.20.0';
2569
		if (!empty(config_get_path('ntpd/gps/fudge1'))) {
2570
			$ntpcfg .= ' time1 ';
2571
			$ntpcfg .= config_get_path('ntpd/gps/fudge1');
2572
		}
2573
		if (!empty(config_get_path('ntpd/gps/fudge2'))) {
2574
			$ntpcfg .= ' time2 ';
2575
			$ntpcfg .= config_get_path('ntpd/gps/fudge2');
2576
		}
2577
		if (!empty(config_get_path('ntpd/gps/flag1'))) {
2578
			$ntpcfg .= ' flag1 1';
2579
		} else {
2580
			$ntpcfg .= ' flag1 0';
2581
		}
2582
		if (!empty(config_get_path('ntpd/gps/flag2'))) {
2583
			$ntpcfg .= ' flag2 1';
2584
		}
2585
		if (!empty(config_get_path('ntpd/gps/flag3'))) {
2586
			$ntpcfg .= ' flag3 1';
2587
		} else {
2588
			$ntpcfg .= ' flag3 0';
2589
		}
2590
		if (!empty(config_get_path('ntpd/gps/flag4'))) {
2591
			$ntpcfg .= ' flag4 1';
2592
		}
2593
		if (!empty(config_get_path('ntpd/gps/refid'))) {
2594
			$ntpcfg .= ' refid ';
2595
			$ntpcfg .= config_get_path('ntpd/gps/refid');
2596
		}
2597
		if (!empty(config_get_path('ntpd/gps/stratum'))) {
2598
			$ntpcfg .= ' stratum ';
2599
			$ntpcfg .= config_get_path('ntpd/gps/stratum');
2600
		}
2601
		$ntpcfg .= "\n";
2602
	} elseif (system_ntp_setup_gps(config_get_path('ntpd/gpsport'))) {
2603
		/* This handles a 2.1 and earlier config */
2604
		$ntpcfg .= "# GPS Setup\n";
2605
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
2606
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
2607
		// Fall back to local clock if GPS is out of sync?
2608
		$ntpcfg .= "server 127.127.1.0\n";
2609
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
2610
	}
2611
	/* End GPS configuration */
2612
	$auto_pool_suffix = "pool.ntp.org";
2613
	$have_pools = false;
2614
	$ntpcfg .= "\n\n# Upstream Servers\n";
2615
	/* foreach through ntp servers and write out to ntpd.conf */
2616
	foreach (explode(' ', config_get_path('system/timeservers')) as $ts) {
2617
		if (empty($ts)) {
2618
			continue;
2619
		}
2620
		if ((substr_compare($ts, $auto_pool_suffix, strlen($ts) - strlen($auto_pool_suffix), strlen($auto_pool_suffix)) === 0)
2621
		    || substr_count(config_get_path('ntpd/ispool'), $ts)) {
2622
			$ntpcfg .= 'pool ';
2623
			$have_pools = true;
2624
		} else {
2625
			if (substr_count(config_get_path('ntpd/ispeer'), $ts)) {
2626
				$ntpcfg .= 'peer ';
2627
			} else {
2628
				$ntpcfg .= 'server ';
2629
			}
2630
		}
2631
		if (config_get_path('ntpd/dnsresolv') == 'inet') {
2632
			$ntpcfg .= '-4 ';
2633
		} elseif (config_get_path('ntpd/dnsresolv') == 'inet6') {
2634
			$ntpcfg .= '-6 ';
2635
		}
2636

    
2637
		$ntpcfg .= "{$ts}";
2638
		if (!substr_count(config_get_path('ntpd/ispeer'), $ts)) {
2639
			$ntpcfg .= " iburst";
2640
		}
2641

    
2642
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', config_get_path('ntpd/ntpminpoll'), $ntp_poll_min_default);
2643
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', config_get_path('ntpd/ntpmaxpoll'), $ntp_poll_max_default);
2644

    
2645
		if (substr_count(config_get_path('ntpd/prefer'), $ts)) {
2646
			$ntpcfg .= ' prefer';
2647
		}
2648
		if (substr_count(config_get_path('ntpd/noselect'), $ts)) {
2649
			$ntpcfg .= ' noselect';
2650
		}
2651
		if (config_get_path('ntpd/serverauth') == 'yes' &&
2652
		    !substr_count(config_get_path('ntpd/ispool'), $ts) &&
2653
		    substr_count(config_get_path('ntpd/isauth'), $ts)) {
2654
			$ntpcfg .= " key {$ntp_keyid} ";
2655
		}
2656
		$ntpcfg .= "\n";
2657
	}
2658
	unset($ts);
2659

    
2660
	$ntpcfg .= "\n\n";
2661
	if (!empty(config_get_path('ntpd/clockstats')) || !empty(config_get_path('ntpd/loopstats')) || !empty(config_get_path('ntpd/peerstats'))) {
2662
		$ntpcfg .= "enable stats\n";
2663
		$ntpcfg .= 'statistics';
2664
		if (!empty(config_get_path('ntpd/clockstats'))) {
2665
			$ntpcfg .= ' clockstats';
2666
		}
2667
		if (!empty(config_get_path('ntpd/loopstats'))) {
2668
			$ntpcfg .= ' loopstats';
2669
		}
2670
		if (!empty(config_get_path('ntpd/peerstats'))) {
2671
			$ntpcfg .= ' peerstats';
2672
		}
2673
		$ntpcfg .= "\n";
2674
	}
2675
	$ntpcfg .= "statsdir {$statsdir}\n";
2676
	$ntpcfg .= 'logconfig =syncall +clockall';
2677
	if (!empty(config_get_path('ntpd/logpeer'))) {
2678
		$ntpcfg .= ' +peerall';
2679
	}
2680
	if (!empty(config_get_path('ntpd/logsys'))) {
2681
		$ntpcfg .= ' +sysall';
2682
	}
2683
	$ntpcfg .= "\n";
2684
	$ntpcfg .= "driftfile {$driftfile}\n";
2685

    
2686
	/* Default Access restrictions */
2687
	$ntpcfg .= 'restrict default';
2688
	if (empty(config_get_path('ntpd/kod'))) { /*note: this one works backwards */
2689
		$ntpcfg .= ' kod limited';
2690
	}
2691
	if (empty(config_get_path('ntpd/nomodify'))) { /*note: this one works backwards */
2692
		$ntpcfg .= ' nomodify';
2693
	}
2694
	if (!empty(config_get_path('ntpd/noquery'))) {
2695
		$ntpcfg .= ' noquery';
2696
	}
2697
	if (empty(config_get_path('ntpd/nopeer'))) { /*note: this one works backwards */
2698
		$ntpcfg .= ' nopeer';
2699
	}
2700
	if (empty(config_get_path('ntpd/notrap'))) { /*note: this one works backwards */
2701
		$ntpcfg .= ' notrap';
2702
	}
2703
	if (!empty(config_get_path('ntpd/noserve'))) {
2704
		$ntpcfg .= ' noserve';
2705
	}
2706
	$ntpcfg .= "\nrestrict -6 default";
2707
	if (empty(config_get_path('ntpd/kod'))) { /*note: this one works backwards */
2708
		$ntpcfg .= ' kod limited';
2709
	}
2710
	if (empty(config_get_path('ntpd/nomodify'))) { /*note: this one works backwards */
2711
		$ntpcfg .= ' nomodify';
2712
	}
2713
	if (!empty(config_get_path('ntpd/noquery'))) {
2714
		$ntpcfg .= ' noquery';
2715
	}
2716
	if (empty(config_get_path('ntpd/nopeer'))) { /*note: this one works backwards */
2717
		$ntpcfg .= ' nopeer';
2718
	}
2719
	if (!empty(config_get_path('ntpd/noserve'))) {
2720
		$ntpcfg .= ' noserve';
2721
	}
2722
	if (empty(config_get_path('ntpd/notrap'))) { /*note: this one works backwards */
2723
		$ntpcfg .= ' notrap';
2724
	}
2725

    
2726
	/* Pools require "restrict source" and cannot contain "nopeer" and "noserve". */
2727
	if ($have_pools) {
2728
		$ntpcfg .= "\nrestrict source";
2729
		if (empty(config_get_path('ntpd/kod'))) { /*note: this one works backwards */
2730
			$ntpcfg .= ' kod limited';
2731
		}
2732
		if (empty(config_get_path('ntpd/nomodify'))) { /*note: this one works backwards */
2733
			$ntpcfg .= ' nomodify';
2734
		}
2735
		if (!empty(config_get_path('ntpd/noquery'))) {
2736
			$ntpcfg .= ' noquery';
2737
		}
2738
		if (empty(config_get_path('ntpd/notrap'))) { /*note: this one works backwards */
2739
			$ntpcfg .= ' notrap';
2740
		}
2741
	}
2742

    
2743
	/* Custom Access Restrictions */
2744
	if (is_array(config_get_path('ntpd/restrictions/row'))) {
2745
		$networkacl = config_get_path('ntpd/restrictions/row');
2746
		foreach ($networkacl as $acl) {
2747
			$restrict = "";
2748
			if (is_ipaddrv6($acl['acl_network'])) {
2749
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask_v6($acl['mask']) . " ";
2750
			} elseif (is_ipaddrv4($acl['acl_network'])) {
2751
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask($acl['mask']) . " ";
2752
			} else {
2753
				continue;
2754
			}
2755
			if (!empty($acl['kod'])) {
2756
				$restrict .= ' kod limited';
2757
			}
2758
			if (!empty($acl['nomodify'])) {
2759
				$restrict .= ' nomodify';
2760
			}
2761
			if (!empty($acl['noquery'])) {
2762
				$restrict .= ' noquery';
2763
			}
2764
			if (!empty($acl['nopeer'])) {
2765
				$restrict .= ' nopeer';
2766
			}
2767
			if (!empty($acl['noserve'])) {
2768
				$restrict .= ' noserve';
2769
			}
2770
			if (!empty($acl['notrap'])) {
2771
				$restrict .= ' notrap';
2772
			}
2773
			if (!empty($restrict)) {
2774
				$ntpcfg .= "\nrestrict {$restrict} ";
2775
			}
2776
		}
2777
	}
2778
	/* End Custom Access Restrictions */
2779

    
2780
	/* A leapseconds file is really only useful if this clock is stratum 1 */
2781
	$ntpcfg .= "\n";
2782
	if (!empty(config_get_path('ntpd/leapsec'))) {
2783
		$leapsec .= base64_decode(config_get_path('ntpd/leapsec'));
2784
		file_put_contents('/var/db/leap-seconds', $leapsec);
2785
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
2786
	}
2787

    
2788

    
2789
	if (empty(config_get_path('ntpd/interface'))) {
2790
		$interfaces = config_get_path('installedpackages/openntpd/config/0/interface', '');
2791
	} else {
2792
		$interfaces = config_get_path('ntpd/interface', '');
2793
	}
2794
	// avoid an array with a single empty value
2795
	if (!empty(trim($interfaces))) {
2796
		$interfaces = array_filter(explode(",", config_get_path('ntpd/interface', '')));
2797
	}
2798

    
2799
	if (is_array($interfaces) && count($interfaces)) {
2800
		$finterfaces = array();
2801
		foreach ($interfaces as $interface) {
2802
			$interface = get_real_interface($interface);
2803
			if (!empty($interface)) {
2804
				$finterfaces[] = $interface;
2805
			}
2806
		}
2807
		if (!empty($finterfaces)) {
2808
			$ntpcfg .= "interface ignore all\n";
2809
			$ntpcfg .= "interface ignore wildcard\n";
2810
			foreach ($finterfaces as $interface) {
2811
				$ntpcfg .= "interface listen {$interface}\n";
2812
			}
2813
		}
2814
	}
2815

    
2816
	/* open configuration for writing or bail */
2817
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
2818
		log_error(sprintf(gettext("Could not open %s/ntpd.conf for writing"), g_get('varetc_path')));
2819
		return;
2820
	}
2821

    
2822
	/* if /var/empty does not exist, create it */
2823
	if (!is_dir("/var/empty")) {
2824
		mkdir("/var/empty", 0555, true);
2825
	}
2826

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

    
2830
	// Note that we are starting up
2831
	log_error("NTPD is starting up.");
2832

    
2833
	if (is_platform_booting()) {
2834
		echo gettext("done.") . "\n";
2835
	}
2836

    
2837
	return;
2838
}
2839

    
2840
function system_halt() {
2841
	global $g;
2842

    
2843
	system_reboot_cleanup();
2844

    
2845
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
2846
}
2847

    
2848
function system_reboot() {
2849
	global $g;
2850

    
2851
	system_reboot_cleanup();
2852

    
2853
	mwexec("/usr/bin/nohup /etc/rc.reboot > /dev/null 2>&1 &");
2854
}
2855

    
2856
function system_reboot_sync($reroot=false) {
2857
	global $g;
2858

    
2859
	if ($reroot) {
2860
		$args = " -r ";
2861
	}
2862

    
2863
	system_reboot_cleanup();
2864

    
2865
	mwexec("/etc/rc.reboot {$args} > /dev/null 2>&1");
2866
}
2867

    
2868
function system_reboot_cleanup() {
2869
	global $g, $cpzone;
2870

    
2871
	mwexec("/usr/local/bin/beep.sh stop");
2872
	require_once("captiveportal.inc");
2873
	$cps = config_get_path('captiveportal', []);
2874
	foreach ($cps as $cpzone=>$cp) {
2875
		if (!isset($cp['preservedb'])) {
2876
			/* send Accounting-Stop packet for all clients, termination cause 'Admin-Reboot' */
2877
			captiveportal_radius_stop_all(7); // Admin-Reboot
2878
			unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
2879
			captiveportal_free_dnrules();
2880
		}
2881
		/* Send Accounting-Off packet to the RADIUS server */
2882
		captiveportal_send_server_accounting('off');
2883
	}
2884

    
2885
	if (count($cps)> 0) {
2886
		/* Remove the pipe database */
2887
		unlink_if_exists("{$g['vardb_path']}/captiveportaldn.rules");
2888
	}
2889

    
2890
	require_once("voucher.inc");
2891
	voucher_save_db_to_config();
2892
	require_once("pfsense-utils.inc");
2893
	enable_carp(false);
2894
	require_once("pkg-utils.inc");
2895
	stop_packages();
2896
}
2897

    
2898
function system_do_shell_commands($early = 0) {
2899
	if (config_path_enabled('system', 'developerspew')) {
2900
		$mt = microtime();
2901
		echo "system_do_shell_commands() being called $mt\n";
2902
	}
2903

    
2904
	if ($early) {
2905
		$cmdn = "earlyshellcmd";
2906
	} else {
2907
		$cmdn = "shellcmd";
2908
	}
2909

    
2910
	$syscmd = config_get_path("system/{$cmdn}", '');
2911
	if (is_array($syscmd)) {
2912
		/* *cmd is an array, loop through */
2913
		foreach ($syscmd as $cmd) {
2914
			exec($cmd);
2915
		}
2916

    
2917
	} elseif ($syscmd <> "") {
2918
		/* execute single item */
2919
		exec($syscmd);
2920

    
2921
	}
2922
}
2923

    
2924
function system_dmesg_save() {
2925
	global $g;
2926
	if (config_path_enabled('system', 'developerspew')) {
2927
		$mt = microtime();
2928
		echo "system_dmesg_save() being called $mt\n";
2929
	}
2930

    
2931
	$dmesg = "";
2932
	$_gb = exec("/sbin/dmesg", $dmesg);
2933

    
2934
	/* find last copyright line (output from previous boots may be present) */
2935
	$lastcpline = 0;
2936

    
2937
	for ($i = 0; $i < count($dmesg); $i++) {
2938
		if (strstr($dmesg[$i], "Copyright (c) 1992-")) {
2939
			$lastcpline = $i;
2940
		}
2941
	}
2942

    
2943
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
2944
	if (!$fd) {
2945
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
2946
		return 1;
2947
	}
2948

    
2949
	for ($i = $lastcpline; $i < count($dmesg); $i++) {
2950
		fwrite($fd, $dmesg[$i] . "\n");
2951
	}
2952

    
2953
	fclose($fd);
2954
	unset($dmesg);
2955

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

    
2959
	return 0;
2960
}
2961

    
2962
function system_set_harddisk_standby() {
2963
	if (config_path_enabled('system', 'developerspew')) {
2964
		$mt = microtime();
2965
		echo "system_set_harddisk_standby() being called $mt\n";
2966
	}
2967

    
2968
	if (config_path_enabled('system', 'harddiskstandby')) {
2969
		if (is_platform_booting()) {
2970
			echo gettext('Setting hard disk standby... ');
2971
		}
2972

    
2973
		$standby = config_get_path('system/harddiskstandby');
2974
		// Check for a numeric value
2975
		if (is_numeric($standby)) {
2976
			// Get only suitable candidates for standby
2977
			$harddisks = get_drive_list(false);
2978

    
2979
			if (count($harddisks) > 0) {
2980
				// Iterate disks and run the camcontrol command for each
2981
				foreach ($harddisks as $harddisk) {
2982
					mwexec("/sbin/camcontrol standby {$harddisk} -t {$standby}");
2983
				}
2984
				if (is_platform_booting()) {
2985
					echo gettext("done.") . "\n";
2986
				}
2987
			} else if (is_platform_booting()) {
2988
				echo gettext("failed!") . "\n";
2989
			}
2990
		} else if (is_platform_booting()) {
2991
			echo gettext("failed!") . "\n";
2992
		}
2993
	}
2994
}
2995

    
2996
function system_setup_sysctl() {
2997
	if (config_path_enabled('system', 'developerspew')) {
2998
		$mt = microtime();
2999
		echo "system_setup_sysctl() being called $mt\n";
3000
	}
3001

    
3002
	activate_sysctls();
3003

    
3004
	if (config_path_enabled('system', 'sharednet')) {
3005
		system_disable_arp_wrong_if();
3006
	}
3007
}
3008

    
3009
function system_disable_arp_wrong_if() {
3010
	if (config_path_enabled('system', 'developerspew')) {
3011
		$mt = microtime();
3012
		echo "system_disable_arp_wrong_if() being called $mt\n";
3013
	}
3014
	set_sysctl(array(
3015
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
3016
		"net.link.ether.inet.log_arp_movements" => "0"
3017
	));
3018
}
3019

    
3020
function system_enable_arp_wrong_if() {
3021
	if (config_path_enabled('system', 'developerspew')) {
3022
		$mt = microtime();
3023
		echo "system_enable_arp_wrong_if() being called $mt\n";
3024
	}
3025
	set_sysctl(array(
3026
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
3027
		"net.link.ether.inet.log_arp_movements" => "1"
3028
	));
3029
}
3030

    
3031
function enable_watchdog() {
3032
	return;
3033
	$install_watchdog = false;
3034
	$supported_watchdogs = array("Geode");
3035
	$file = file_get_contents("/var/log/dmesg.boot");
3036
	foreach ($supported_watchdogs as $sd) {
3037
		if (stristr($file, "Geode")) {
3038
			$install_watchdog = true;
3039
		}
3040
	}
3041
	if ($install_watchdog == true) {
3042
		if (is_process_running("watchdogd")) {
3043
			mwexec("/usr/bin/killall watchdogd", true);
3044
		}
3045
		exec("/usr/sbin/watchdogd");
3046
	}
3047
}
3048

    
3049
function system_check_reset_button() {
3050
	global $g;
3051

    
3052
	$specplatform = system_identify_specific_platform();
3053

    
3054
	switch ($specplatform['name']) {
3055
		case 'SG-2220':
3056
			$binprefix = "RCC-DFF";
3057
			break;
3058
		case 'alix':
3059
		case 'wrap':
3060
		case 'FW7541':
3061
		case 'APU':
3062
		case 'RCC-VE':
3063
		case 'RCC':
3064
			$binprefix = $specplatform['name'];
3065
			break;
3066
		default:
3067
			return 0;
3068
	}
3069

    
3070
	$retval = mwexec("/usr/local/sbin/" . $binprefix . "resetbtn");
3071

    
3072
	if ($retval == 99) {
3073
		/* user has pressed reset button for 2 seconds -
3074
		   reset to factory defaults */
3075
		echo <<<EOD
3076

    
3077
***********************************************************************
3078
* Reset button pressed - resetting configuration to factory defaults. *
3079
* All additional packages installed will be removed                   *
3080
* The system will reboot after this completes.                        *
3081
***********************************************************************
3082

    
3083

    
3084
EOD;
3085

    
3086
		reset_factory_defaults();
3087
		system_reboot_sync();
3088
		exit(0);
3089
	}
3090

    
3091
	return 0;
3092
}
3093

    
3094
function system_get_serial() {
3095
	$platform = system_identify_specific_platform();
3096

    
3097
	unset($output);
3098
	if ($platform['name'] == 'Turbot Dual-E') {
3099
		$if_info = get_interface_addresses('igb0');
3100
		if (isset($if_info) && !empty($if_info['hwaddr'])) {
3101
			$serial = str_replace(":", "", $if_info['hwaddr']);
3102
		}
3103
	} else {
3104
		foreach (array('system', 'planar', 'chassis') as $key) {
3105
			unset($output);
3106
			$_gb = exec("/bin/kenv -q smbios.{$key}.serial",
3107
			    $output);
3108
			if (!empty($output[0]) && $output[0] != "0123456789" &&
3109
			    preg_match('/^[\w\d]{10,16}$/', $output[0]) === 1) {
3110
				$serial = $output[0];
3111
				break;
3112
			}
3113
		}
3114
	}
3115

    
3116
	$vm_guest = get_single_sysctl('kern.vm_guest');
3117

    
3118
	$serial = chop($serial);
3119
	if (strlen($serial) >= 10 && strlen($serial) <= 18 &&
3120
	    $vm_guest == 'none') {
3121
		return $serial;
3122
	}
3123

    
3124
	return "";
3125
}
3126

    
3127
function system_get_uniqueid() {
3128
	global $g;
3129

    
3130
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
3131

    
3132
	if (empty(g_get('uniqueid'))) {
3133
		if (!file_exists($uniqueid_file)) {
3134
			mwexec("/usr/sbin/gnid > {$g['vardb_path']}/uniqueid " .
3135
			    "2>/dev/null");
3136
		}
3137
		if (file_exists($uniqueid_file)) {
3138
			$g['uniqueid'] = @file_get_contents($uniqueid_file);
3139
		}
3140
	}
3141

    
3142
	return (g_get('uniqueid') ?: '');
3143
}
3144

    
3145
/*
3146
 * attempt to identify the specific platform (for embedded systems)
3147
 * Returns an array with two elements:
3148
 * name => platform string (e.g. 'wrap', 'alix' etc.)
3149
 * descr => human-readable description (e.g. "PC Engines WRAP")
3150
 */
3151
function system_identify_specific_platform() {
3152
	global $g;
3153

    
3154
	$hw_model = get_single_sysctl('hw.model');
3155
	$hw_ncpu = get_single_sysctl('hw.ncpu');
3156

    
3157
	/* Try to guess from smbios strings */
3158
	unset($product);
3159
	unset($maker);
3160
	unset($bios);
3161
	unset($chassis);
3162
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $product);
3163
	$_gb = exec('/bin/kenv -q smbios.system.maker 2>/dev/null', $maker);
3164
	$_gb = exec('/bin/kenv -q smbios.bios.version 2>/dev/null', $bios);
3165
	$_gb = exec('/bin/kenv -q smbios.chassis.tag 2>/dev/null', $chassis);
3166

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

    
3170
	if ($chassis[0] == "OracleCloud.com") {
3171
		return (array('name' => 'Oracle', 'descr' => 'Oracle Cloud Infrastructure'));
3172
	}
3173

    
3174
	if ($maker[0] == "QEMU") {
3175
		return (array('name' => 'QEMU', 'descr' => 'QEMU Guest'));
3176
	} else  if ($maker[0] == "Google") {
3177
		return (array('name' => 'Google', 'descr' => 'Google Cloud Platform'));
3178
	} else  if ($maker[0] == "Amazon EC2") {
3179
		return (array('name' => 'AWS', 'descr' => 'Amazon Web Services'));
3180
	}
3181

    
3182
	// This switch needs to be expanded to include other virtualization systems
3183
	switch ($vm) {
3184
		case "none" :
3185
		break;
3186

    
3187
		case "kvm" :
3188
			return (array('name' => 'KVM', 'descr' => 'KVM Guest'));
3189
		break;
3190
	}
3191

    
3192
	// AWS, GCP and OCI can also be identified via the bios version
3193
	if (stripos($bios[0], "amazon") !== false) {
3194
		return (array('name' => 'AWS', 'descr' => 'Amazon Web Services'));
3195
	} else  if (stripos($bios[0], "Google") !== false) {
3196
		return (array('name' => 'Google', 'descr' => 'Google Cloud Platform'));
3197
	} else  if (stripos($bios[0], "oracle") !== false) {
3198
		return (array('name' => 'Oracle', 'descr' => 'Oracle Cloud Infrastructure'));
3199
	}
3200

    
3201
	switch ($product[0]) {
3202
		case 'FW7541':
3203
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
3204
			break;
3205
		case 'apu1':
3206
		case 'APU':
3207
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
3208
			break;
3209
		case 'RCC-VE':
3210
			$result = array();
3211
			$result['name'] = 'RCC-VE';
3212

    
3213
			/* Detect specific models */
3214
			if (!function_exists('does_interface_exist')) {
3215
				require_once("interfaces.inc");
3216
			}
3217
			if (!does_interface_exist('igb4')) {
3218
				$result['model'] = 'SG-2440';
3219
			} elseif (strpos($hw_model, "C2558") !== false) {
3220
				$result['model'] = 'SG-4860';
3221
			} elseif (strpos($hw_model, "C2758") !== false) {
3222
				$result['model'] = 'SG-8860';
3223
			} else {
3224
				$result['model'] = 'RCC-VE';
3225
			}
3226
			$result['descr'] = 'Netgate ' . $result['model'];
3227
			return $result;
3228
			break;
3229
		case 'DFFv2':
3230
			return (array('name' => 'SG-2220', 'descr' => 'Netgate SG-2220'));
3231
			break;
3232
		case 'RCC':
3233
			return (array('name' => 'RCC', 'descr' => 'Netgate XG-2758'));
3234
			break;
3235
		case 'SG-5100':
3236
			return (array('name' => '5100', 'descr' => 'Netgate 5100'));
3237
			break;
3238
		case 'Minnowboard Turbot D0 PLATFORM':
3239
		case 'Minnowboard Turbot D0/D1 PLATFORM':
3240
			$result = array();
3241
			$result['name'] = 'Turbot Dual-E';
3242
			/* Ensure the graphics driver is loaded */
3243
			system("kldload -nq i915kms");
3244
			/* Detect specific model */
3245
			switch ($hw_ncpu) {
3246
			case '4':
3247
				$result['model'] = 'MBT-4220';
3248
				break;
3249
			case '2':
3250
				$result['model'] = 'MBT-2220';
3251
				break;
3252
			default:
3253
				$result['model'] = $result['name'];
3254
				break;
3255
			}
3256
			$result['descr'] = 'Netgate ' . $result['model'];
3257
			return $result;
3258
			break;
3259
		case 'SYS-5018A-FTN4':
3260
		case 'A1SAi':
3261
			if (strpos($hw_model, "C2558") !== false) {
3262
				return (array(
3263
				    'name' => 'C2558',
3264
				    'descr' => 'Super Micro C2558'));
3265
			} elseif (strpos($hw_model, "C2758") !== false) {
3266
				return (array(
3267
				    'name' => 'C2758',
3268
				    'descr' => 'Super Micro C2758'));
3269
			}
3270
			break;
3271
		case 'SYS-5018D-FN4T':
3272
			if (strpos($hw_model, "D-1541") !== false) {
3273
				return (array('name' => '1541', 'descr' => 'Super Micro 1541'));
3274
			} else {
3275
				return (array('name' => '1540', 'descr' => 'Super Micro XG-1540'));
3276
			}
3277
			break;
3278
		case 'APU2':
3279
		case 'apu2':
3280
		case 'apu3':
3281
		case 'apu4':
3282
		case 'apu5':
3283
		case 'apu6':
3284
		case 'apu7':
3285
			return (array('name' => 'apu2', 'descr' => "PC Engines APU2 Platform (\"{$product[0]}\" model)"));
3286
			break;
3287
		case 'VirtualBox':
3288
			return (array('name' => 'VirtualBox', 'descr' => 'VirtualBox Virtual Machine'));
3289
			break;
3290
		case 'Virtual Machine':
3291
			if ($maker[0] == "Microsoft Corporation") {
3292
				if ((stripos($bios[0], "Hyper") !== false) &&
3293
				    ($g['default-config-flavor'] != 'azure')) {
3294
					return (array('name' => 'Hyper-V', 'descr' => 'Hyper-V Virtual Machine'));
3295
				} else {
3296
					return (array('name' => 'Azure', 'descr' => 'Microsoft Azure'));
3297
				}
3298
			}
3299
			break;
3300
		case 'VMware Virtual Platform':
3301
			if ($maker[0] == "VMware, Inc.") {
3302
				return (array('name' => 'VMware', 'descr' => 'VMware Virtual Machine'));
3303
			}
3304
			break;
3305
	}
3306

    
3307
	$_gb = exec('/bin/kenv -q smbios.planar.product 2>/dev/null',
3308
	    $planar_product);
3309
	if (isset($planar_product[0]) &&
3310
	    $planar_product[0] == 'X10SDV-8C-TLN4F+') {
3311
		return array('name' => '1537', 'descr' => 'Super Micro 1537');
3312
	}
3313

    
3314
	if (strpos($hw_model, "PC Engines WRAP") !== false) {
3315
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
3316
	}
3317

    
3318
	if (strpos($hw_model, "PC Engines ALIX") !== false) {
3319
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
3320
	}
3321

    
3322
	if (preg_match("/Soekris net45../", $hw_model, $matches)) {
3323
		return array('name' => 'net45xx', 'descr' => $matches[0]);
3324
	}
3325

    
3326
	if (preg_match("/Soekris net48../", $hw_model, $matches)) {
3327
		return array('name' => 'net48xx', 'descr' => $matches[0]);
3328
	}
3329

    
3330
	if (preg_match("/Soekris net55../", $hw_model, $matches)) {
3331
		return array('name' => 'net55xx', 'descr' => $matches[0]);
3332
	}
3333

    
3334
	unset($hw_model);
3335

    
3336
	$dmesg_boot = system_get_dmesg_boot();
3337
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
3338
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
3339
	}
3340
	unset($dmesg_boot);
3341

    
3342
	return array('name' => g_get('product_name'), 'descr' => g_get('product_label'));
3343
}
3344

    
3345
function system_get_dmesg_boot() {
3346
	global $g;
3347

    
3348
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
3349
}
3350

    
3351
function system_get_arp_table($resolve_hostnames = false) {
3352
	$params="-a";
3353
	if (!$resolve_hostnames) {
3354
		$params .= "n";
3355
	}
3356

    
3357
	$arp_table = array();
3358
	$_gb = exec("/usr/sbin/arp --libxo json {$params}", $rawdata, $rc);
3359
	if ($rc == 0) {
3360
		$arp_table = json_decode(implode(" ", $rawdata),
3361
		    JSON_OBJECT_AS_ARRAY);
3362
		if ($rc == 0) {
3363
			$arp_table = $arp_table['arp']['arp-cache'];
3364
		}
3365
	}
3366

    
3367
	return $arp_table;
3368
}
(50-50/61)