Project

General

Profile

Download (78.2 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * system.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2004-2013 BSD Perimeter
7
 * Copyright (c) 2013-2016 Electric Sheep Fencing
8
 * Copyright (c) 2014-2023 Rubicon Communications, LLC (Netgate)
9
 * All rights reserved.
10
 *
11
 * originally part of m0n0wall (http://m0n0.ch/wall)
12
 * Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>.
13
 * All rights reserved.
14
 *
15
 * Licensed under the Apache License, Version 2.0 (the "License");
16
 * you may not use this file except in compliance with the License.
17
 * You may obtain a copy of the License at
18
 *
19
 * http://www.apache.org/licenses/LICENSE-2.0
20
 *
21
 * Unless required by applicable law or agreed to in writing, software
22
 * distributed under the License is distributed on an "AS IS" BASIS,
23
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24
 * See the License for the specific language governing permissions and
25
 * limitations under the License.
26
 */
27

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

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

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

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

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

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

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

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

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

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

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

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

    
116
	return $output[0];
117
}
118

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
204
	set_sysctl($sysctls);
205
}
206

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
308
	unlock($dnslock);
309

    
310
	return 0;
311
}
312

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

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

    
332
	return $master_list;
333
}
334

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

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

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

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

    
372
	return $master_list;
373
}
374

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

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

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

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

    
432
	return $hosts;
433
}
434

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

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

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

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

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

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

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

    
484
	return $hosts;
485
}
486

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

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

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

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

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

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

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

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

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

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

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

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

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

    
584
	return $hosts;
585
}
586

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

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

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

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

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

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

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

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

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

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

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

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

    
672
	return 0;
673
}
674

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

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

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

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

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

    
732
function system_get_dhcpleases($dnsavailable=null) {
733
	global $g;
734

    
735
	$leases = array();
736
	$leases['lease'] = array();
737
	$leases['failover'] = array();
738

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

    
741
	if (!file_exists($leases_file)) {
742
		return $leases;
743
	}
744

    
745
	$leases_content = file($leases_file, FILE_IGNORE_NEW_LINES |
746
	    FILE_IGNORE_NEW_LINES);
747

    
748
	if ($leases_content === FALSE) {
749
		return $leases;
750
	}
751

    
752
	$arp_table = system_get_arp_table();
753

    
754
	$arpdata_ip = array();
755
	$arpdata_mac = array();
756
	foreach ($arp_table as $arp_entry) {
757
		if (isset($arpentry['incomplete'])) {
758
			continue;
759
		}
760
		$arpdata_ip[] = $arp_entry['ip-address'];
761
		$arpdata_mac[] = $arp_entry['mac-address'];
762
	}
763
	unset($arp_table);
764

    
765
	/*
766
	 * Translate these once so we don't do it over and over in the loops
767
	 * below.
768
	 */
769
	$online_string = gettext("active");
770
	$offline_string = gettext("idle/offline");
771
	$active_string = gettext("active");
772
	$expired_string = gettext("expired");
773
	$reserved_string = gettext("reserved");
774
	$dynamic_string = gettext("dynamic");
775
	$static_string = gettext("static");
776

    
777
	$lease_regex = '/^lease\s+([^\s]+)\s+{$/';
778
	$starts_regex = '/^\s*(starts|ends)\s+\d+\s+([\d\/]+|never)\s*(|[\d:]*);$/';
779
	$binding_regex = '/^\s*binding\s+state\s+(.+);$/';
780
	$mac_regex = '/^\s*hardware\s+ethernet\s+(.+);$/';
781
	$hostname_regex = '/^\s*client-hostname\s+"(.+)";$/';
782

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

    
786
	$lease = false;
787
	$failover = false;
788
	$dedup_lease = false;
789
	$dedup_failover = false;
790

    
791
	foreach ($leases_content as $line) {
792
		/* Skip comments */
793
		if (preg_match('/^\s*(|#.*)$/', $line)) {
794
			continue;
795
		}
796

    
797
		if (preg_match('/}$/', $line)) {
798
			if ($lease) {
799
				if (empty($item['hostname'])) {
800
					if (is_null($dnsavailable)) {
801
						$dnsavailable = check_dnsavailable();
802
					}
803
					if ($dnsavailable) {
804
						$hostname = gethostbyaddr($item['ip']);
805
						if (!empty($hostname)) {
806
							$item['hostname'] = $hostname;
807
						}
808
					}
809
				}
810
				$leases['lease'][] = $item;
811
				$lease = false;
812
				$dedup_lease = true;
813
			} else if ($failover) {
814
				$leases['failover'][] = $item;
815
				$failover = false;
816
				$dedup_failover = true;
817
			}
818
			continue;
819
		}
820

    
821
		if (preg_match($lease_regex, $line, $m)) {
822
			$lease = true;
823
			$item = array();
824
			$item['ip'] = $m[1];
825
			$item['type'] = $dynamic_string;
826
			continue;
827
		}
828

    
829
		if ($lease) {
830
			if (preg_match($starts_regex, $line, $m)) {
831
				/*
832
				 * Quote from dhcpd.leases(5) man page:
833
				 * If a lease will never expire, date is never
834
				 * instead of an actual date
835
				 */
836
				if ($m[2] == "never") {
837
					$item[$m[1]] = gettext("Never");
838
				} else {
839
					$item[$m[1]] = dhcpd_date_adjust_gmt(
840
					    $m[2] . ' ' . $m[3]);
841
				}
842
				continue;
843
			}
844

    
845
			if (preg_match($binding_regex, $line, $m)) {
846
				switch ($m[1]) {
847
					case "active":
848
						$item['act'] = $active_string;
849
						break;
850
					case "free":
851
						$item['act'] = $expired_string;
852
						$item['online'] =
853
						    $offline_string;
854
						break;
855
					case "backup":
856
						$item['act'] = $reserved_string;
857
						$item['online'] =
858
						    $offline_string;
859
						break;
860
				}
861
				continue;
862
			}
863

    
864
			if (preg_match($mac_regex, $line, $m) &&
865
			    is_macaddr($m[1])) {
866
				$item['mac'] = $m[1];
867

    
868
				if (in_array($item['ip'], $arpdata_ip)) {
869
					$item['online'] = $online_string;
870
				} else {
871
					$item['online'] = $offline_string;
872
				}
873
				continue;
874
			}
875

    
876
			if (preg_match($hostname_regex, $line, $m)) {
877
				$item['hostname'] = $m[1];
878
			}
879
		}
880

    
881
		if (preg_match($failover_regex, $line, $m)) {
882
			$failover = true;
883
			$item = array();
884
			$item['name'] = $m[1] . ' (' .
885
			    convert_friendly_interface_to_friendly_descr(
886
			    substr($m[1],5)) . ')';
887
			continue;
888
		}
889

    
890
		if ($failover && preg_match($state_regex, $line, $m)) {
891
			$item[$m[1] . 'state'] = $m[2];
892
			$item[$m[1] . 'date'] = dhcpd_date_adjust_gmt($m[3] .
893
			    ' ' . $m[4]);
894
			continue;
895
		}
896
	}
897

    
898
	foreach (config_get_path('interfaces', []) as $ifname => $ifarr) {
899
		foreach (config_get_path("dhcpd/{$ifname}/staticmap", []) as $idx =>
900
		    $static) {
901
			if (empty($static['mac']) && empty($static['cid'])) {
902
				continue;
903
			}
904

    
905
			$slease = array();
906
			$slease['ip'] = $static['ipaddr'];
907
			$slease['type'] = $static_string;
908
			if (!empty($static['cid'])) {
909
				$slease['cid'] = $static['cid'];
910
			}
911
			$slease['mac'] = $static['mac'];
912
			$slease['if'] = $ifname;
913
			$slease['starts'] = "";
914
			$slease['ends'] = "";
915
			$slease['hostname'] = $static['hostname'];
916
			$slease['descr'] = $static['descr'];
917
			$slease['act'] = $static_string;
918
			$slease['online'] = in_array(strtolower($slease['mac']),
919
			    $arpdata_mac) ? $online_string : $offline_string;
920
			$slease['staticmap_array_index'] = $idx;
921
			$leases['lease'][] = $slease;
922
			$dedup_lease = true;
923
		}
924
	}
925

    
926
	if ($dedup_lease) {
927
		$leases['lease'] = array_remove_duplicate($leases['lease'],
928
		    'ip');
929
	}
930
	if ($dedup_failover) {
931
		$leases['failover'] = array_remove_duplicate(
932
		    $leases['failover'], 'name');
933
		asort($leases['failover']);
934
	}
935

    
936
	return $leases;
937
}
938

    
939
function system_hostname_configure() {
940
	if (config_path_enabled('system', 'developerspew')) {
941
		$mt = microtime();
942
		echo "system_hostname_configure() being called $mt\n";
943
	}
944

    
945
	$syscfg = config_get_path('system');
946

    
947
	/* set hostname */
948
	$status = mwexec("/bin/hostname " .
949
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
950

    
951
	/* Setup host GUID ID.  This is used by ZFS. */
952
	mwexec("/etc/rc.d/hostid start");
953

    
954
	return $status;
955
}
956

    
957
function system_routing_configure($interface = "") {
958
	if (config_path_enabled('system', 'developerspew')) {
959
		$mt = microtime();
960
		echo "system_routing_configure() being called $mt\n";
961
	}
962

    
963
	$gateways_arr = return_gateways_array(false, true);
964
	foreach ($gateways_arr as $gateway) {
965
		// setup static interface routes for nonlocal gateways
966
		if (isset($gateway["nonlocalgateway"])) {
967
			$srgatewayip = $gateway['gateway'];
968
			$srinterfacegw = $gateway['interface'];
969
			if (is_ipaddr($srgatewayip) && !empty($srinterfacegw)) {
970
				route_add_or_change($srgatewayip, '',
971
				    $srinterfacegw);
972
			}
973
		}
974
	}
975

    
976
	$gateways_status = return_gateways_status(true);
977
	fixup_default_gateway("inet", $gateways_status, $gateways_arr);
978
	fixup_default_gateway("inet6", $gateways_status, $gateways_arr);
979

    
980
	system_staticroutes_configure($interface, false);
981

    
982
	return 0;
983
}
984

    
985
function system_staticroutes_configure($interface = "", $update_dns = false) {
986
	global $g, $aliastable;
987

    
988
	$filterdns_list = array();
989

    
990
	$static_routes = get_staticroutes(false, true);
991
	if (count($static_routes)) {
992
		$gateways_arr = return_gateways_array(false, true);
993

    
994
		foreach ($static_routes as $rtent) {
995
			/* Do not delete disabled routes,
996
			 * see https://redmine.pfsense.org/issues/3709
997
			 * and https://redmine.pfsense.org/issues/10706 */
998
			if (isset($rtent['disabled'])) {
999
				continue;
1000
			}
1001

    
1002
			if (empty($gateways_arr[$rtent['gateway']])) {
1003
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
1004
				continue;
1005
			}
1006
			$gateway = $gateways_arr[$rtent['gateway']];
1007
			if (!empty($interface) && $interface != $gateway['friendlyiface']) {
1008
				continue;
1009
			}
1010

    
1011
			$gatewayip = $gateway['gateway'];
1012
			$interfacegw = $gateway['interface'];
1013

    
1014
			$blackhole = "";
1015
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 4))) {
1016
				$blackhole = "-blackhole";
1017
			}
1018

    
1019
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network'])) {
1020
				continue;
1021
			}
1022

    
1023
			$dnscache = array();
1024
			if ($update_dns === true) {
1025
				if (is_subnet($rtent['network'])) {
1026
					continue;
1027
				}
1028
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
1029
				if (empty($dnscache)) {
1030
					continue;
1031
				}
1032
			}
1033

    
1034
			if (is_subnet($rtent['network'])) {
1035
				$ips = array($rtent['network']);
1036
			} else {
1037
				if (!isset($rtent['disabled'])) {
1038
					$filterdns_list[] = $rtent['network'];
1039
				}
1040
				$ips = add_hostname_to_watch($rtent['network']);
1041
			}
1042

    
1043
			foreach ($dnscache as $ip) {
1044
				if (in_array($ip, $ips)) {
1045
					continue;
1046
				}
1047
				route_del($ip);
1048
			}
1049

    
1050
			if (isset($rtent['disabled'])) {
1051
				/*
1052
				 * XXX: This can break things by deleting
1053
				 * routes that shouldn't be deleted - OpenVPN,
1054
				 * dynamic routing scenarios, etc.
1055
				 * redmine #3709
1056
				 */
1057
				foreach ($ips as $ip) {
1058
					route_del($ip);
1059
				}
1060
				continue;
1061
			}
1062

    
1063
			foreach ($ips as $ip) {
1064
				if (is_ipaddrv4($ip)) {
1065
					$ip .= "/32";
1066
				}
1067
				/*
1068
				 * do NOT do the same check here on v6,
1069
				 * is_ipaddrv6 returns true when including
1070
				 * the CIDR mask. doing so breaks v6 routes
1071
				 */
1072
				if (is_subnet($ip)) {
1073
					if (is_ipaddr($gatewayip)) {
1074
						if (is_linklocal($gatewayip) == "6" &&
1075
						    !strpos($gatewayip, '%')) {
1076
							/*
1077
							 * add interface scope
1078
							 * for link local v6
1079
							 * routes
1080
							 */
1081
							$gatewayip .= "%$interfacegw";
1082
						}
1083
						route_add_or_change($ip,
1084
						    $gatewayip, '', $blackhole);
1085
					} else if (!empty($interfacegw)) {
1086
						route_add_or_change($ip,
1087
						    '', $interfacegw, $blackhole);
1088
					}
1089
				}
1090
			}
1091
		}
1092
		unset($gateways_arr);
1093

    
1094
		/* keep static routes cache,
1095
		 * see https://redmine.pfsense.org/issues/11599 */
1096
		$id = 0;
1097
		foreach (config_get_path('staticroutes/route', []) as $sroute) {
1098
			$targets = array();
1099
			if (is_subnet($sroute['network'])) {
1100
				$targets[] = $sroute['network'];
1101
			} elseif (is_alias($sroute['network'])) {
1102
				foreach (preg_split('/\s+/', $aliastable[$sroute['network']]) as $tgt) {
1103
					if (is_ipaddrv4($tgt)) {
1104
						$tgt .= "/32";
1105
					}
1106
					if (is_ipaddrv6($tgt)) {
1107
						$tgt .= "/128";
1108
					}
1109
					if (!is_subnet($tgt)) {
1110
						continue;
1111
					}
1112
					$targets[] = $tgt;
1113
				}
1114
			}
1115
			file_put_contents("{$g['tmp_path']}/staticroute_{$id}", serialize($targets));
1116
			file_put_contents("{$g['tmp_path']}/staticroute_{$id}_gw", serialize($sroute['gateway']));
1117
			$id++;
1118
		}
1119
	}
1120
	unset($static_routes);
1121

    
1122
	if ($update_dns === false) {
1123
		if (count($filterdns_list)) {
1124
			$interval = 60;
1125
			$hostnames = "";
1126
			array_unique($filterdns_list);
1127
			foreach ($filterdns_list as $hostname) {
1128
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
1129
			}
1130
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
1131
			unset($hostnames);
1132

    
1133
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid")) {
1134
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
1135
			} else {
1136
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
1137
			}
1138
		} else {
1139
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
1140
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
1141
		}
1142
	}
1143
	unset($filterdns_list);
1144

    
1145
	return 0;
1146
}
1147

    
1148
function delete_static_route($id, $delete = false) {
1149
	global $g, $changedesc_prefix, $a_gateways;
1150

    
1151
	if (empty(config_get_path("staticroutes/route/{$id}"))) {
1152
		return;
1153
	}
1154

    
1155
	if (file_exists("{$g['tmp_path']}/.system_routes.apply")) {
1156
		$toapplylist = unserialize(file_get_contents("{$g['tmp_path']}/.system_routes.apply"));
1157
	} else {
1158
		$toapplylist = array();
1159
	}
1160

    
1161
	if (file_exists("{$g['tmp_path']}/staticroute_{$id}") &&
1162
	    file_exists("{$g['tmp_path']}/staticroute_{$id}_gw")) {
1163
		$delete_targets = unserialize(file_get_contents("{$g['tmp_path']}/staticroute_{$id}"));
1164
		$delgw = lookup_gateway_ip_by_name(unserialize(file_get_contents("{$g['tmp_path']}/staticroute_{$id}_gw")));
1165
		if (count($delete_targets)) {
1166
			foreach ($delete_targets as $dts) {
1167
				if (is_subnetv4($dts)) {
1168
					$family = "-inet";
1169
				} else {
1170
					$family = "-inet6";
1171
				}
1172
				$route = route_get($dts, '', true);
1173
				if (!count($route)) {
1174
					continue;
1175
				}
1176
				$toapplylist[] = "/sbin/route delete " .
1177
				    $family . " " . $dts . " " . $delgw;
1178
			}
1179
		}
1180
	}
1181

    
1182
	if ($delete) {
1183
		unlink_if_exists("{$g['tmp_path']}/staticroute_{$id}");
1184
		unlink_if_exists("{$g['tmp_path']}/staticroute_{$id}_gw");
1185
	}
1186

    
1187
	if (!empty($toapplylist)) {
1188
		file_put_contents("{$g['tmp_path']}/.system_routes.apply", serialize($toapplylist));
1189
	}
1190

    
1191
	unset($targets);
1192
}
1193

    
1194
function system_routing_enable() {
1195
	if (config_path_enabled('system', 'developerspew')) {
1196
		$mt = microtime();
1197
		echo "system_routing_enable() being called $mt\n";
1198
	}
1199

    
1200
	set_sysctl(array(
1201
		"net.inet.ip.forwarding" => "1",
1202
		"net.inet6.ip6.forwarding" => "1"
1203
	));
1204

    
1205
	return;
1206
}
1207

    
1208
function system_webgui_start() {
1209
	global $g;
1210

    
1211
	if (platform_booting()) {
1212
		echo gettext("Starting webConfigurator...");
1213
	}
1214

    
1215
	chdir(g_get('www_path'));
1216

    
1217
	/* defaults */
1218
	$portarg = config_get_path('system/webgui/port', '80');
1219
	$crt = "";
1220
	$key = "";
1221
	$ca = "";
1222

    
1223
	if (config_get_path('system/webgui/protocol') == "https") {
1224
		// Ensure that we have a webConfigurator CERT
1225
		$cert = lookup_cert(config_get_path('system/webgui/ssl-certref'));
1226
		if (!is_array($cert) || !$cert['crt'] || !$cert['prv'] ||
1227
		    cert_chain_has_weak_digest($cert)) {
1228
			$cert = cert_create_selfsigned();
1229
			if (is_array($cert) && !empty($cert)) {
1230
				config_set_path('system/webgui/ssl-certref', $cert['refid']);
1231
				write_config(sprintf(gettext("Generated new self-signed SSL/TLS certificate for HTTPS (%s)"), $cert['refid']));
1232
			} else {
1233
				log_error(sprintf(gettext("GUI certificate is not usable and there was an error creating a new self-signed certificate.")));
1234
			}
1235
		}
1236
		$crt = base64_decode($cert['crt']);
1237
		$key = base64_decode($cert['prv']);
1238

    
1239
		$portarg = config_get_path('system/webgui/port', '443');
1240
		$ca = ca_chain($cert);
1241
		$hsts = !config_path_enabled('system/webgui', 'disablehsts');
1242
	}
1243

    
1244
	/* generate nginx configuration */
1245
	system_generate_nginx_config("{$g['varetc_path']}/nginx-webConfigurator.conf",
1246
		$crt, $key, $ca, "nginx-webConfigurator.pid", $portarg, "/usr/local/www/",
1247
		"cert.crt", "cert.key", false, $hsts);
1248

    
1249
	/* kill any running nginx */
1250
	killbypid("{$g['varrun_path']}/nginx-webConfigurator.pid");
1251

    
1252
	sleep(1);
1253

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

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

    
1259
	if (platform_booting()) {
1260
		if ($res == 0) {
1261
			echo gettext("done.") . "\n";
1262
		} else {
1263
			echo gettext("failed!") . "\n";
1264
		}
1265
	}
1266

    
1267
	return $res;
1268
}
1269

    
1270
/****f* system.inc/get_dns_nameservers
1271
 * NAME
1272
 *   get_dns_nameservers - Get system DNS servers
1273
 * INPUTS
1274
 *   $add_v6_brackets: (boolean, false)
1275
 *                     Add brackets around IPv6 DNS servers, as expected by some
1276
 *                     daemons such as nginx.
1277
 *   $hostns         : (boolean, true)
1278
 *                     true : Return only DNS servers used by the firewall
1279
 *                            itself as upstream forwarding servers
1280
 *                     false: Return all DNS servers from the configuration and
1281
 *                            overrides (if allowed).
1282
 * RESULT
1283
 *   $dns_nameservers - An array of the requested DNS servers
1284
 ******/
1285
function get_dns_nameservers($add_v6_brackets = false, $hostns=true) {
1286
	$dns_nameservers = array();
1287

    
1288
	if (config_path_enabled('system', 'developerspew')) {
1289
		$mt = microtime();
1290
		echo "get_dns_nameservers() being called $mt\n";
1291
	}
1292

    
1293
	if ((((config_path_enabled('dnsmasq')) &&
1294
		  (config_get_path('dnsmasq/port', '53') == '53') &&
1295
		  in_array("lo0", explode(",", config_get_path('dnsmasq/interface', 'lo0'))))) ||
1296
	    (config_path_enabled('unbound') &&
1297
		 (config_get_path('unbound/port', '53') == '53') &&
1298
		 (in_array("lo0", explode(",", config_get_path('unbound/active_interface', 'lo0'))) ||
1299
		  in_array("all", explode(",", config_get_path('unbound/active_interface', 'all')), true))) &&
1300
	    (config_get_path('system/dnslocalhost') != 'remote')) {
1301
		$dns_nameservers[] = "127.0.0.1";
1302
	}
1303

    
1304
	if ($hostns || (config_get_path('system/dnslocalhost') != 'local')) {
1305
		if (config_path_enabled('system', 'dnsallowoverride')) {
1306
			/* get dynamically assigned DNS servers (if any) */
1307
			foreach (array_unique(get_dynamic_nameservers()) as $nameserver) {
1308
				if ($nameserver) {
1309
					if ($add_v6_brackets && is_ipaddrv6($nameserver)) {
1310
						$nameserver = "[{$nameserver}]";
1311
					}
1312
					$dns_nameservers[] = $nameserver;
1313
				}
1314
			}
1315
		}
1316
		foreach (config_get_path('system/dnsserver', []) as $sys_dnsserver) {
1317
			if ($sys_dnsserver && (!in_array($sys_dnsserver, $dns_nameservers))) {
1318
				if ($add_v6_brackets && is_ipaddrv6($sys_dnsserver)) {
1319
					$sys_dnsserver = "[{$sys_dnsserver}]";
1320
				}
1321
				$dns_nameservers[] = $sys_dnsserver;
1322
			}
1323
		}
1324
	}
1325
	return array_unique($dns_nameservers);
1326
}
1327

    
1328
function system_generate_nginx_config($filename,
1329
	$cert,
1330
	$key,
1331
	$ca,
1332
	$pid_file,
1333
	$port = 80,
1334
	$document_root = "/usr/local/www/",
1335
	$cert_location = "cert.crt",
1336
	$key_location = "cert.key",
1337
	$captive_portal = false,
1338
	$hsts = true) {
1339

    
1340
	global $g;
1341

    
1342
	if (config_path_enabled('system', 'developerspew')) {
1343
		$mt = microtime();
1344
		echo "system_generate_nginx_config() being called $mt\n";
1345
	}
1346

    
1347
	if ($captive_portal !== false) {
1348
		$cp_interfaces = explode(",", config_get_path("captiveportal/{$captive_portal}/interface"));
1349
		$cp_hostcheck = "";
1350
		foreach ($cp_interfaces as $cpint) {
1351
			$cpint_ip = get_interface_ip($cpint);
1352
			if (is_ipaddr($cpint_ip)) {
1353
				$cp_hostcheck .= "\t\tif (\$http_host ~* $cpint_ip) {\n";
1354
				$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1355
				$cp_hostcheck .= "\t\t}\n";
1356
			}
1357
		}
1358
		$httpsname = config_get_path("captiveportal/{$captive_portal}/httpsname");
1359
		if (!empty($httpsname) &&
1360
		    is_domain($httpsname)) {
1361
			$cp_hostcheck .= "\t\tif (\$http_host ~* {$httpsname}) {\n";
1362
			$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1363
			$cp_hostcheck .= "\t\t}\n";
1364
		}
1365
		$cp_rewrite = "\t\tif (\$cp_redirect = '') {\n";
1366
		$cp_rewrite .= "\t\t\trewrite	^ /index.php?zone=$captive_portal&redirurl=\$request_uri break;\n";
1367
		$cp_rewrite .= "\t\t}\n";
1368

    
1369
		$maxprocperip = config_get_path("captiveportal/{$captive_portal}/maxprocperip");
1370
		if (empty($maxprocperip)) {
1371
			$maxprocperip = 10;
1372
		}
1373
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1374
	}
1375

    
1376
	if (empty($port)) {
1377
		$nginx_port = "80";
1378
	} else {
1379
		$nginx_port = $port;
1380
	}
1381

    
1382
	$memory = get_memory();
1383
	$realmem = $memory[1];
1384

    
1385
	// Determine web GUI process settings and take into account low memory systems
1386
	if ($realmem < 255) {
1387
		$max_procs = 1;
1388
	} else {
1389
		$max_procs = config_get_path('system/webgui/max_procs', 2);
1390
	}
1391

    
1392
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM
1393
	if ($captive_portal !== false) {
1394
		if ($realmem > 135 and $realmem < 256) {
1395
			$max_procs += 1; // 2 worker processes
1396
		} else if ($realmem > 255 and $realmem < 513) {
1397
			$max_procs += 2; // 3 worker processes
1398
		} else if ($realmem > 512) {
1399
			$max_procs += 4; // 6 worker processes
1400
		}
1401
	}
1402

    
1403
	$nginx_config = <<<EOD
1404
#
1405
# nginx configuration file
1406

    
1407
pid {$g['varrun_path']}/{$pid_file};
1408

    
1409
user  root wheel;
1410
worker_processes  {$max_procs};
1411

    
1412
EOD;
1413

    
1414
	/* Disable file logging */
1415
	$nginx_config .= "error_log /dev/null;\n";
1416
	if (!config_path_enabled('syslog','nolognginx')) {
1417
		/* Send nginx error log to syslog */
1418
		$nginx_config .= "error_log  syslog:server=unix:/var/run/log,facility=local5;\n";
1419
	}
1420

    
1421
	$nginx_config .= <<<EOD
1422

    
1423
events {
1424
    worker_connections  1024;
1425
}
1426

    
1427
http {
1428
	include       /usr/local/etc/nginx/mime.types;
1429
	default_type  application/octet-stream;
1430
	add_header X-Frame-Options SAMEORIGIN;
1431
	server_tokens off;
1432

    
1433
	sendfile        off;
1434

    
1435
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1436

    
1437
EOD;
1438

    
1439
	if ($captive_portal !== false) {
1440
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1441
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1442
	} else {
1443
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1444
	}
1445

    
1446
	if ($cert <> "" and $key <> "") {
1447
		$nginx_config .= "\n";
1448
		$nginx_config .= "\tserver {\n";
1449
		$nginx_config .= "\t\tlisten {$nginx_port} ssl http2;\n";
1450
		$nginx_config .= "\t\tlisten [::]:{$nginx_port} ssl http2;\n";
1451
		$nginx_config .= "\n";
1452
		$nginx_config .= "\t\tssl_certificate         {$g['varetc_path']}/{$cert_location};\n";
1453
		$nginx_config .= "\t\tssl_certificate_key     {$g['varetc_path']}/{$key_location};\n";
1454
		$nginx_config .= "\t\tssl_session_timeout     10m;\n";
1455
		$nginx_config .= "\t\tkeepalive_timeout       70;\n";
1456
		$nginx_config .= "\t\tssl_session_cache       shared:SSL:10m;\n";
1457
		if ($captive_portal !== false) {
1458
			// leave TLSv1.1 for CP for now for compatibility
1459
			$nginx_config .= "\t\tssl_protocols   TLSv1.1 TLSv1.2 TLSv1.3;\n";
1460
		} else {
1461
			$nginx_config .= "\t\tssl_protocols   TLSv1.2 TLSv1.3;\n";
1462
		}
1463
		$nginx_config .= "\t\tssl_ciphers \"EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305\";\n";
1464
		$nginx_config .= "\t\tssl_prefer_server_ciphers       on;\n";
1465
		if ($captive_portal === false && $hsts !== false) {
1466
			$nginx_config .= "\t\tadd_header Strict-Transport-Security \"max-age=31536000\";\n";
1467
		}
1468
		$nginx_config .= "\t\tadd_header X-Content-Type-Options nosniff;\n";
1469
		$nginx_config .= "\t\tssl_session_tickets off;\n";
1470
		$nginx_config .= "\t\tssl_dhparam /etc/dh-parameters.4096;\n";
1471
		$cert_temp = lookup_cert(config_get_path('system/webgui/ssl-certref'));
1472
		if ((config_get_path('system/webgui/ocsp-staple') == true) or
1473
		    (cert_get_ocspstaple($cert_temp['crt']) == true)) {
1474
			$nginx_config .= "\t\tssl_stapling on;\n";
1475
			$nginx_config .= "\t\tssl_stapling_verify on;\n";
1476
			$nginx_config .= "\t\tresolver " . implode(" ", get_dns_nameservers(true)) . " valid=300s;\n";
1477
			$nginx_config .= "\t\tresolver_timeout 5s;\n";
1478
		}
1479
	} else {
1480
		$nginx_config .= "\n";
1481
		$nginx_config .= "\tserver {\n";
1482
		$nginx_config .= "\t\tlisten {$nginx_port};\n";
1483
		$nginx_config .= "\t\tlisten [::]:{$nginx_port};\n";
1484
	}
1485

    
1486
	$nginx_config .= <<<EOD
1487

    
1488
		client_max_body_size 200m;
1489

    
1490
		gzip on;
1491
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
1492

    
1493

    
1494
EOD;
1495

    
1496
	if ($captive_portal !== false) {
1497
		$nginx_config .= <<<EOD
1498
$captive_portal_maxprocperip
1499
$cp_hostcheck
1500
$cp_rewrite
1501
		log_not_found off;
1502

    
1503
EOD;
1504

    
1505
	}
1506

    
1507
	$plugin_locations = "";
1508
	if ($captive_portal == false) {
1509
		$pluginparams = [ 'section' => 'location' ];
1510
		foreach (pkg_call_plugins('plugin_nginx', $pluginparams) as $pkgname => $location) {
1511
			if (empty($location)) {
1512
				continue;
1513
			}
1514
			$plugin_locations .= "# Plugin Locations ({$pkgname})\n";
1515
			$plugin_locations .= "{$location}\n";
1516
		}
1517
	}
1518

    
1519
	$nginx_config .= <<<EOD
1520
		root "{$document_root}";
1521
		location / {
1522
			index  index.php index.html index.htm;
1523
		}
1524
		location ~ \.inc$ {
1525
			deny all;
1526
			return 403;
1527
		}
1528
		location ~ \.php$ {
1529
			try_files \$uri =404; #  This line closes a potential security hole
1530
			# ensuring users can't execute uploaded files
1531
			# see: https://forum.nginx.org/read.php?2,88845,page=3
1532
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1533
			fastcgi_index  index.php;
1534
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1535
			# Fix httpoxy - https://httpoxy.org/#fix-now
1536
			fastcgi_param  HTTP_PROXY  "";
1537
			fastcgi_read_timeout 180;
1538
			include        /usr/local/etc/nginx/fastcgi_params;
1539
		}
1540
		location ~ (^/status$) {
1541
			allow 127.0.0.1;
1542
			deny all;
1543
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1544
			fastcgi_index  index.php;
1545
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1546
			# Fix httpoxy - https://httpoxy.org/#fix-now
1547
			fastcgi_param  HTTP_PROXY  "";
1548
			fastcgi_read_timeout 360;
1549
			include        /usr/local/etc/nginx/fastcgi_params;
1550
		}
1551
		{$plugin_locations}
1552
	}
1553

    
1554
EOD;
1555

    
1556
	$cert = str_replace("\r", "", $cert);
1557
	$key = str_replace("\r", "", $key);
1558

    
1559
	$cert = str_replace("\n\n", "\n", $cert);
1560
	$key = str_replace("\n\n", "\n", $key);
1561

    
1562
	if ($cert <> "" and $key <> "") {
1563
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1564
		if (!$fd) {
1565
			printf(gettext("Error: cannot open certificate file in system_webgui_start().%s"), "\n");
1566
			return 1;
1567
		}
1568
		chmod("{$g['varetc_path']}/{$cert_location}", 0644);
1569
		if ($ca <> "") {
1570
			$cert_chain = $cert . "\n" . $ca;
1571
		} else {
1572
			$cert_chain = $cert;
1573
		}
1574
		fwrite($fd, $cert_chain);
1575
		fclose($fd);
1576
		$fd = fopen("{$g['varetc_path']}/{$key_location}", "w");
1577
		if (!$fd) {
1578
			printf(gettext("Error: cannot open certificate key file in system_webgui_start().%s"), "\n");
1579
			return 1;
1580
		}
1581
		chmod("{$g['varetc_path']}/{$key_location}", 0600);
1582
		fwrite($fd, $key);
1583
		fclose($fd);
1584
	}
1585

    
1586
	// Add HTTP to HTTPS redirect
1587
	if ($captive_portal === false && config_get_path('system/webgui/protocol') == "https" && !(config_path_enabled('system/webgui', 'disablehttpredirect') != null)) {
1588
		if ($nginx_port != "443") {
1589
			$redirectport = ":{$nginx_port}";
1590
		}
1591
		$nginx_config .= <<<EOD
1592
	server {
1593
		listen 80;
1594
		listen [::]:80;
1595
		return 301 https://\$http_host$redirectport\$request_uri;
1596
	}
1597

    
1598
EOD;
1599
	}
1600

    
1601
	if ($captive_portal == false) {
1602
		$pluginparams = [ 'section' => 'server' ];
1603
		foreach (pkg_call_plugins('plugin_nginx', $pluginparams) as $pkgname => $server) {
1604
			if (empty($server)) {
1605
				continue;
1606
			}
1607
			$nginx_config .= "	# Plugin Servers ({$pkgname})\n";
1608
			$nginx_config .= "{$server}\n";
1609
		}
1610
	}
1611

    
1612
	$nginx_config .= "}\n";
1613

    
1614
	$fd = fopen("{$filename}", "w");
1615
	if (!$fd) {
1616
		printf(gettext('Error: cannot open %1$s in system_generate_nginx_config().%2$s'), $filename, "\n");
1617
		return 1;
1618
	}
1619
	fwrite($fd, $nginx_config);
1620
	fclose($fd);
1621

    
1622
	/* nginx will fail to start if this directory does not exist. */
1623
	safe_mkdir("/var/tmp/nginx/");
1624

    
1625
	return 0;
1626

    
1627
}
1628

    
1629
function system_get_timezone_list() {
1630
	global $g;
1631

    
1632
	$file_list = array_merge(
1633
		glob("/usr/share/zoneinfo/[A-Z]*"),
1634
		glob("/usr/share/zoneinfo/*/*"),
1635
		glob("/usr/share/zoneinfo/*/*/*")
1636
	);
1637

    
1638
	if (empty($file_list)) {
1639
		$file_list[] = g_get('default_timezone');
1640
	} else {
1641
		/* Remove directories from list */
1642
		$file_list = array_filter($file_list, function($v) {
1643
			return !is_dir($v);
1644
		});
1645
	}
1646

    
1647
	/* Remove directory prefix */
1648
	$file_list = str_replace('/usr/share/zoneinfo/', '', $file_list);
1649

    
1650
	sort($file_list);
1651

    
1652
	return $file_list;
1653
}
1654

    
1655
function system_timezone_configure() {
1656
	global $g;
1657
	if (config_path_enabled('system', 'developerspew')) {
1658
		$mt = microtime();
1659
		echo "system_timezone_configure() being called $mt\n";
1660
	}
1661

    
1662
	$syscfg = config_get_path('system');
1663

    
1664
	if (platform_booting()) {
1665
		echo gettext("Setting timezone...");
1666
	}
1667

    
1668
	/* extract appropriate timezone file */
1669
	$timezone = (isset($syscfg['timezone']) ? $syscfg['timezone'] : g_get('default_timezone'));
1670
	/* DO NOT remove \n otherwise tzsetup will fail */
1671
	@file_put_contents("/var/db/zoneinfo", $timezone . "\n");
1672
	mwexec("/usr/sbin/tzsetup -r");
1673

    
1674
	if (platform_booting()) {
1675
		echo gettext("done.") . "\n";
1676
	}
1677
}
1678

    
1679
function check_gps_speed($device) {
1680
	usleep(1000);
1681
	// Set timeout to 5s
1682
	$timeout=microtime(true)+5;
1683
	if ($fp = fopen($device, 'r')) {
1684
		stream_set_blocking($fp, 0);
1685
		stream_set_timeout($fp, 5);
1686
		$contents = "";
1687
		$cnt = 0;
1688
		$buffersize = 256;
1689
		do {
1690
			$c = fread($fp, $buffersize - $cnt);
1691

    
1692
			// Wait for data to arive
1693
			if (($c === false) || (strlen($c) == 0)) {
1694
				usleep(500);
1695
				continue;
1696
			}
1697

    
1698
			$contents.=$c;
1699
			$cnt = $cnt + strlen($c);
1700
		} while (($cnt < $buffersize) && (microtime(true) < $timeout));
1701
		fclose($fp);
1702

    
1703
		$nmeasentences = ['RMC', 'GGA', 'GLL', 'ZDA', 'ZDG', 'PGRMF'];
1704
		foreach ($nmeasentences as $sentence) {
1705
			if (strpos($contents, $sentence) > 0) {
1706
				return true;
1707
			}
1708
		}
1709
		if (strpos($contents, '0') > 0) {
1710
			$filters = ['`', '?', '/', '~'];
1711
			foreach ($filters as $filter) {
1712
				if (strpos($contents, $filter) !== false) {
1713
					return false;
1714
				}
1715
			}
1716
			return true;
1717
		}
1718
	}
1719
	return false;
1720
}
1721

    
1722
/* Generate list of possible NTP poll values
1723
 * https://redmine.pfsense.org/issues/9439 */
1724
global $ntp_poll_min_value, $ntp_poll_max_value;
1725
global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
1726
global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
1727
global $ntp_poll_min_default, $ntp_poll_max_default;
1728
global $ntp_auth_halgos, $ntp_server_types;
1729
$ntp_poll_min_value = 3;
1730
$ntp_poll_max_value = 17;
1731
$ntp_poll_min_default_gps = 4;
1732
$ntp_poll_max_default_gps = 4;
1733
$ntp_poll_min_default_pps = 4;
1734
$ntp_poll_max_default_pps = 4;
1735
$ntp_poll_min_default = 'omit';
1736
$ntp_poll_max_default = 9;
1737
$ntp_auth_halgos = array(
1738
	'md5' => 'MD5',
1739
	'sha1' => 'SHA1',
1740
	'sha256' => 'SHA256'
1741
);
1742
$ntp_server_types = array(
1743
	'server' => 'Server',
1744
	'pool' => 'Pool',
1745
	'peer' => 'Peer'
1746
);
1747

    
1748
function system_ntp_poll_values() {
1749
	global $ntp_poll_min_value, $ntp_poll_max_value;
1750
	$poll_values = array("" => gettext('Default'));
1751

    
1752
	for ($i = $ntp_poll_min_value; $i <= $ntp_poll_max_value; $i++) {
1753
		$sec = 2 ** $i;
1754
		$poll_values[$i] = $i . ': ' . number_format($sec) . ' ' . gettext('seconds') .
1755
					' (' . convert_seconds_to_dhms($sec) . ')';
1756
	}
1757

    
1758
	$poll_values['omit'] = gettext('Omit (Do not set)');
1759
	return $poll_values;
1760
}
1761

    
1762
function system_ntp_fixup_poll_value($type, $configvalue, $default) {
1763
	$pollstring = "";
1764

    
1765
	if (empty($configvalue)) {
1766
		$configvalue = $default;
1767
	}
1768

    
1769
	if ($configvalue != 'omit') {
1770
		$pollstring = " {$type} {$configvalue}";
1771
	}
1772

    
1773
	return $pollstring;
1774
}
1775

    
1776
function system_ntp_setup_gps($serialport) {
1777
	if (config_get_path('ntpd/enable') == 'disabled') {
1778
		return false;
1779
	}
1780

    
1781
	init_config_arr(array('ntpd', 'gps'));
1782
	$serialports = get_serial_ports(true);
1783

    
1784
	if (!array_key_exists($serialport, $serialports)) {
1785
		return false;
1786
	}
1787

    
1788
	$gps_device = '/dev/gps0';
1789
	$serialport = '/dev/'.basename($serialport);
1790

    
1791
	if (!file_exists($serialport)) {
1792
		return false;
1793
	}
1794

    
1795
	// Create symlink that ntpd requires
1796
	unlink_if_exists($gps_device);
1797
	@symlink($serialport, $gps_device);
1798

    
1799
	$speeds = array(
1800
		0 => '4800',
1801
		16 => '9600',
1802
		32 => '19200',
1803
		48 => '38400',
1804
		64 => '57600',
1805
		80 => '115200'
1806
	);
1807
	// $gpsbaud defaults to '4800' if ntpd/gps/speed is unset or does not exist in $speeds
1808
	$gpsbaud = array_get_path($speeds, config_get_path('ntpd/gps/speed', 0), '4800');
1809

    
1810
	system_ntp_setup_rawspeed($serialport, $gpsbaud);
1811

    
1812
	$gpsspeed = config_get_path('ntpd/gps/speed');
1813
	$autospeed = ($gpsspeed == 'autoalways' || $gpsspeed == 'autoset');
1814
	if ($autospeed || (config_get_path('ntpd/gps/autobaudinit') && !check_gps_speed($gps_device))) {
1815
		$found = false;
1816
		foreach ($speeds as $baud) {
1817
			system_ntp_setup_rawspeed($serialport, $baud);
1818
			if ($found = check_gps_speed($gps_device)) {
1819
				if ($autospeed) {
1820
					$saveconfig = (config_get_path('ntpd/gps/speed') == 'autoset');
1821
					config_set_path('ntpd/gps/speed', array_search($baud, $speeds));
1822
					$gpsbaud = $baud;
1823
					if ($saveconfig) {
1824
						write_config(sprintf(gettext('Autoset GPS baud rate to %s'), $baud));
1825
					}
1826
				}
1827
				break;
1828
			}
1829
		}
1830
		if ($found === false) {
1831
			log_error(gettext("Could not find correct GPS baud rate."));
1832
			return false;
1833
		}
1834
	}
1835

    
1836
	/* Send the following to the GPS port to initialize the GPS */
1837
	if (!empty(config_get_path('ntpd/gps/type'))) {
1838
		$gps_init = base64_decode(config_get_path('ntpd/gps/initcmd'));
1839
	} else {
1840
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1841
	}
1842

    
1843
	/* XXX: Why not file_put_contents to the device */
1844
	@file_put_contents('/tmp/gps.init', $gps_init);
1845
	mwexec("/bin/cat /tmp/gps.init > {$serialport}");
1846

    
1847
	if ($found && config_get_path('ntpd/gps/autobaudinit')) {
1848
		system_ntp_setup_rawspeed($serialport, $gpsbaud);
1849
	}
1850

    
1851
	/* Remove old /etc/remote entry if it exists */
1852
	if (mwexec("/usr/bin/grep -c '^gps0' /etc/remote") == 0) {
1853
		mwexec("/usr/bin/sed -i '' -n '/gps0/!p' /etc/remote");
1854
	}
1855

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

    
1861
	return true;
1862
}
1863

    
1864
// Configure the serial port for raw IO and set the speed
1865
function system_ntp_setup_rawspeed($serialport, $baud) {
1866
	mwexec("/bin/stty -f " .  escapeshellarg($serialport) . " raw speed " . escapeshellarg($baud));
1867
	mwexec("/bin/stty -f " .  escapeshellarg($serialport) . ".init raw speed " . escapeshellarg($baud));
1868
}
1869

    
1870
function system_ntp_setup_pps($serialport) {
1871
	$serialports = get_serial_ports(true);
1872

    
1873
	if (!array_key_exists($serialport, $serialports)) {
1874
		return false;
1875
	}
1876

    
1877
	$pps_device = '/dev/pps0';
1878
	$serialport = '/dev/'.basename($serialport);
1879

    
1880
	if (!file_exists($serialport)) {
1881
		return false;
1882
	}
1883
	// If ntpd is disabled, just return
1884
	if (config_get_path('ntpd/enable') == 'disabled') {
1885
		return false;
1886
	}
1887

    
1888
	// Create symlink that ntpd requires
1889
	unlink_if_exists($pps_device);
1890
	@symlink($serialport, $pps_device);
1891

    
1892

    
1893
	return true;
1894
}
1895

    
1896
function system_ntp_configure() {
1897
	global $g;
1898
	global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
1899
	global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
1900
	global $ntp_poll_min_default, $ntp_poll_max_default;
1901

    
1902
	$driftfile = "/var/db/ntpd.drift";
1903
	$statsdir = "/var/log/ntp";
1904
	$gps_device = '/dev/gps0';
1905

    
1906
	safe_mkdir($statsdir);
1907

    
1908
	init_config_arr(array('ntpd'));
1909

    
1910
	// ntpd is disabled, just stop it and return
1911
	if (config_get_path('ntpd/enable') == 'disabled') {
1912
		while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1913
			killbypid("{$g['varrun_path']}/ntpd.pid");
1914
		}
1915
		@unlink("{$g['varrun_path']}/ntpd.pid");
1916
		@unlink("{$g['varetc_path']}/ntpd.conf");
1917
		@unlink("{$g['varetc_path']}/ntp.keys");
1918
		log_error("NTPD is disabled.");
1919
		return;
1920
	}
1921

    
1922
	if (platform_booting()) {
1923
		echo gettext("Starting NTP Server...");
1924
	}
1925

    
1926
	/* if ntpd is running, kill it */
1927
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1928
		killbypid("{$g['varrun_path']}/ntpd.pid");
1929
	}
1930
	@unlink("{$g['varrun_path']}/ntpd.pid");
1931

    
1932
	/* set NTP server authentication key */
1933
	if (config_get_path('ntpd/serverauth') == 'yes') {
1934
		$ntpkeyscfg = "1 " . strtoupper(config_get_path('ntpd/serverauthalgo')) . " " . base64_decode(config_get_path('ntpd/serverauthkey')) . "\n";
1935
		if (!@file_put_contents("{$g['varetc_path']}/ntp.keys", $ntpkeyscfg)) {
1936
			log_error(sprintf(gettext("Could not open %s/ntp.keys for writing"), g_get('varetc_path')));
1937
			return;
1938
		}
1939
	} else {
1940
		unlink_if_exists("{$g['varetc_path']}/ntp.keys");
1941
	}
1942

    
1943
	$ntpcfg = "# \n";
1944
	$ntpcfg .= "# pfSense ntp configuration file \n";
1945
	$ntpcfg .= "# \n\n";
1946
	$ntpcfg .= "tinker panic 0 \n\n";
1947

    
1948
	if (config_get_path('ntpd/serverauth') == 'yes') {
1949
		$ntpcfg .= "# Authentication settings \n";
1950
		$ntpcfg .= "keys /var/etc/ntp.keys \n";
1951
		$ntpcfg .= "trustedkey 1 \n";
1952
		$ntpcfg .= "requestkey 1 \n";
1953
		$ntpcfg .= "controlkey 1 \n";
1954
		$ntpcfg .= "\n";
1955
	}
1956

    
1957
	/* Add Orphan mode */
1958
	$ntpcfg .= "# Orphan mode stratum and Maximum candidate NTP peers\n";
1959
	$ntpcfg .= 'tos orphan ';
1960
	if (!empty(config_get_path('ntpd/orphan'))) {
1961
		$ntpcfg .= config_get_path('ntpd/orphan');
1962
	} else {
1963
		$ntpcfg .= '12';
1964
	}
1965
	/* Add Maximum candidate NTP peers */
1966
	$ntpcfg .= ' maxclock ';
1967
	if (!empty(config_get_path('ntpd/ntpmaxpeers'))) {
1968
		$ntpcfg .= config_get_path('ntpd/ntpmaxpeers');
1969
	} else {
1970
		$ntpcfg .= '5';
1971
	}
1972
	$ntpcfg .= "\n";
1973

    
1974
	/* Add PPS configuration */
1975
	if (!empty(config_get_path('ntpd/pps/port')) &&
1976
	    file_exists('/dev/'.config_get_path('ntpd/pps/port')) &&
1977
	    system_ntp_setup_pps(config_get_path('ntpd/pps/port'))) {
1978
		$ntpcfg .= "\n";
1979
		$ntpcfg .= "# PPS Setup\n";
1980
		$ntpcfg .= 'server 127.127.22.0';
1981
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', config_get_path('ntpd/pps/ppsminpoll'), $ntp_poll_min_default_pps);
1982
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', config_get_path('ntpd/pps/ppsmaxpoll'), $ntp_poll_max_default_pps);
1983
		if (empty(config_get_path('ntpd/pps/prefer'))) { /*note: this one works backwards */
1984
			$ntpcfg .= ' prefer';
1985
		}
1986
		if (!empty(config_get_path('ntpd/pps/noselect'))) {
1987
			$ntpcfg .= ' noselect ';
1988
		}
1989
		$ntpcfg .= "\n";
1990
		$ntpcfg .= 'fudge 127.127.22.0';
1991
		if (!empty(config_get_path('ntpd/pps/fudge1'))) {
1992
			$ntpcfg .= ' time1 ';
1993
			$ntpcfg .= config_get_path('ntpd/pps/fudge1');
1994
		}
1995
		if (!empty(config_get_path('ntpd/pps/flag2'))) {
1996
			$ntpcfg .= ' flag2 1';
1997
		}
1998
		if (!empty(config_get_path('ntpd/pps/flag3'))) {
1999
			$ntpcfg .= ' flag3 1';
2000
		} else {
2001
			$ntpcfg .= ' flag3 0';
2002
		}
2003
		if (!empty(config_get_path('ntpd/pps/flag4'))) {
2004
			$ntpcfg .= ' flag4 1';
2005
		}
2006
		if (!empty(config_get_path('ntpd/pps/refid'))) {
2007
			$ntpcfg .= ' refid ';
2008
			$ntpcfg .= config_get_path('ntpd/pps/refid');
2009
		}
2010
		$ntpcfg .= "\n";
2011
	}
2012
	/* End PPS configuration */
2013

    
2014
	/* Add GPS configuration */
2015
	if (!empty(config_get_path('ntpd/gps/port')) &&
2016
	    system_ntp_setup_gps(config_get_path('ntpd/gps/port'))) {
2017
		$ntpcfg .= "\n";
2018
		$ntpcfg .= "# GPS Setup\n";
2019
		$ntpcfg .= 'server 127.127.20.0 mode ';
2020
		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'))) {
2021
			if (!empty(config_get_path('ntpd/gps/nmea'))) {
2022
				$ntpmode = (int) config_get_path('ntpd/gps/nmea');
2023
			}
2024
			if (!empty(config_get_path('ntpd/gps/speed'))) {
2025
				$ntpmode += (int) config_get_path('ntpd/gps/speed');
2026
			}
2027
			if (!empty(config_get_path('ntpd/gps/subsec'))) {
2028
				$ntpmode += 128;
2029
			}
2030
			if (!empty(config_get_path('ntpd/gps/processpgrmf'))) {
2031
				$ntpmode += 256;
2032
			}
2033
			$ntpcfg .= (string) $ntpmode;
2034
		} else {
2035
			$ntpcfg .= '0';
2036
		}
2037
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', config_get_path('ntpd/gps/gpsminpoll'), $ntp_poll_min_default_gps);
2038
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', config_get_path('ntpd/gps/gpsmaxpoll'), $ntp_poll_max_default_gps);
2039

    
2040
		if (empty(config_get_path('ntpd/gps/prefer'))) { /*note: this one works backwards */
2041
			$ntpcfg .= ' prefer';
2042
		}
2043
		if (!empty(config_get_path('ntpd/gps/noselect'))) {
2044
			$ntpcfg .= ' noselect ';
2045
		}
2046
		$ntpcfg .= "\n";
2047
		$ntpcfg .= 'fudge 127.127.20.0';
2048
		if (!empty(config_get_path('ntpd/gps/fudge1'))) {
2049
			$ntpcfg .= ' time1 ';
2050
			$ntpcfg .= config_get_path('ntpd/gps/fudge1');
2051
		}
2052
		if (!empty(config_get_path('ntpd/gps/fudge2'))) {
2053
			$ntpcfg .= ' time2 ';
2054
			$ntpcfg .= config_get_path('ntpd/gps/fudge2');
2055
		}
2056
		if (!empty(config_get_path('ntpd/gps/flag1'))) {
2057
			$ntpcfg .= ' flag1 1';
2058
		} else {
2059
			$ntpcfg .= ' flag1 0';
2060
		}
2061
		if (!empty(config_get_path('ntpd/gps/flag2'))) {
2062
			$ntpcfg .= ' flag2 1';
2063
		}
2064
		if (!empty(config_get_path('ntpd/gps/flag3'))) {
2065
			$ntpcfg .= ' flag3 1';
2066
		} else {
2067
			$ntpcfg .= ' flag3 0';
2068
		}
2069
		if (!empty(config_get_path('ntpd/gps/flag4'))) {
2070
			$ntpcfg .= ' flag4 1';
2071
		}
2072
		if (!empty(config_get_path('ntpd/gps/refid'))) {
2073
			$ntpcfg .= ' refid ';
2074
			$ntpcfg .= config_get_path('ntpd/gps/refid');
2075
		}
2076
		if (!empty(config_get_path('ntpd/gps/stratum'))) {
2077
			$ntpcfg .= ' stratum ';
2078
			$ntpcfg .= config_get_path('ntpd/gps/stratum');
2079
		}
2080
		$ntpcfg .= "\n";
2081
	} elseif (system_ntp_setup_gps(config_get_path('ntpd/gpsport'))) {
2082
		/* This handles a 2.1 and earlier config */
2083
		$ntpcfg .= "# GPS Setup\n";
2084
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
2085
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
2086
		// Fall back to local clock if GPS is out of sync?
2087
		$ntpcfg .= "server 127.127.1.0\n";
2088
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
2089
	}
2090
	/* End GPS configuration */
2091
	$auto_pool_suffix = "pool.ntp.org";
2092
	$have_pools = false;
2093
	$ntpcfg .= "\n\n# Upstream Servers\n";
2094
	/* foreach through ntp servers and write out to ntpd.conf */
2095
	foreach (explode(' ', config_get_path('system/timeservers')) as $ts) {
2096
		if (empty($ts)) {
2097
			continue;
2098
		}
2099
		if ((substr_compare($ts, $auto_pool_suffix, strlen($ts) - strlen($auto_pool_suffix), strlen($auto_pool_suffix)) === 0)
2100
		    || substr_count(config_get_path('ntpd/ispool'), $ts)) {
2101
			$ntpcfg .= 'pool ';
2102
			$have_pools = true;
2103
		} else {
2104
			if (substr_count(config_get_path('ntpd/ispeer'), $ts)) {
2105
				$ntpcfg .= 'peer ';
2106
			} else {
2107
				$ntpcfg .= 'server ';
2108
			}
2109
			if (config_get_path('ntpd/dnsresolv') == 'inet') {
2110
				$ntpcfg .= '-4 ';
2111
			} elseif (config_get_path('ntpd/dnsresolv') == 'inet6') {
2112
				$ntpcfg .= '-6 ';
2113
			}
2114
		}
2115

    
2116
		$ntpcfg .= "{$ts}";
2117
		if (!substr_count(config_get_path('ntpd/ispeer'), $ts)) {
2118
			$ntpcfg .= " iburst";
2119
		}
2120

    
2121
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', config_get_path('ntpd/ntpminpoll'), $ntp_poll_min_default);
2122
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', config_get_path('ntpd/ntpmaxpoll'), $ntp_poll_max_default);
2123

    
2124
		if (substr_count(config_get_path('ntpd/prefer'), $ts)) {
2125
			$ntpcfg .= ' prefer';
2126
		}
2127
		if (substr_count(config_get_path('ntpd/noselect'), $ts)) {
2128
			$ntpcfg .= ' noselect';
2129
		}
2130
		$ntpcfg .= "\n";
2131
	}
2132
	unset($ts);
2133

    
2134
	$ntpcfg .= "\n\n";
2135
	if (!empty(config_get_path('ntpd/clockstats')) || !empty(config_get_path('ntpd/loopstats')) || !empty(config_get_path('ntpd/peerstats'))) {
2136
		$ntpcfg .= "enable stats\n";
2137
		$ntpcfg .= 'statistics';
2138
		if (!empty(config_get_path('ntpd/clockstats'))) {
2139
			$ntpcfg .= ' clockstats';
2140
		}
2141
		if (!empty(config_get_path('ntpd/loopstats'))) {
2142
			$ntpcfg .= ' loopstats';
2143
		}
2144
		if (!empty(config_get_path('ntpd/peerstats'))) {
2145
			$ntpcfg .= ' peerstats';
2146
		}
2147
		$ntpcfg .= "\n";
2148
	}
2149
	$ntpcfg .= "statsdir {$statsdir}\n";
2150
	$ntpcfg .= 'logconfig =syncall +clockall';
2151
	if (!empty(config_get_path('ntpd/logpeer'))) {
2152
		$ntpcfg .= ' +peerall';
2153
	}
2154
	if (!empty(config_get_path('ntpd/logsys'))) {
2155
		$ntpcfg .= ' +sysall';
2156
	}
2157
	$ntpcfg .= "\n";
2158
	$ntpcfg .= "driftfile {$driftfile}\n";
2159

    
2160
	/* Default Access restrictions */
2161
	$ntpcfg .= 'restrict default';
2162
	if (empty(config_get_path('ntpd/kod'))) { /*note: this one works backwards */
2163
		$ntpcfg .= ' kod limited';
2164
	}
2165
	if (empty(config_get_path('ntpd/nomodify'))) { /*note: this one works backwards */
2166
		$ntpcfg .= ' nomodify';
2167
	}
2168
	if (!empty(config_get_path('ntpd/noquery'))) {
2169
		$ntpcfg .= ' noquery';
2170
	}
2171
	if (empty(config_get_path('ntpd/nopeer'))) { /*note: this one works backwards */
2172
		$ntpcfg .= ' nopeer';
2173
	}
2174
	if (empty(config_get_path('ntpd/notrap'))) { /*note: this one works backwards */
2175
		$ntpcfg .= ' notrap';
2176
	}
2177
	if (!empty(config_get_path('ntpd/noserve'))) {
2178
		$ntpcfg .= ' noserve';
2179
	}
2180
	$ntpcfg .= "\nrestrict -6 default";
2181
	if (empty(config_get_path('ntpd/kod'))) { /*note: this one works backwards */
2182
		$ntpcfg .= ' kod limited';
2183
	}
2184
	if (empty(config_get_path('ntpd/nomodify'))) { /*note: this one works backwards */
2185
		$ntpcfg .= ' nomodify';
2186
	}
2187
	if (!empty(config_get_path('ntpd/noquery'))) {
2188
		$ntpcfg .= ' noquery';
2189
	}
2190
	if (empty(config_get_path('ntpd/nopeer'))) { /*note: this one works backwards */
2191
		$ntpcfg .= ' nopeer';
2192
	}
2193
	if (!empty(config_get_path('ntpd/noserve'))) {
2194
		$ntpcfg .= ' noserve';
2195
	}
2196
	if (empty(config_get_path('ntpd/notrap'))) { /*note: this one works backwards */
2197
		$ntpcfg .= ' notrap';
2198
	}
2199

    
2200
	/* Pools require "restrict source" and cannot contain "nopeer" and "noserve". */
2201
	if ($have_pools) {
2202
		$ntpcfg .= "\nrestrict source";
2203
		if (empty(config_get_path('ntpd/kod'))) { /*note: this one works backwards */
2204
			$ntpcfg .= ' kod limited';
2205
		}
2206
		if (empty(config_get_path('ntpd/nomodify'))) { /*note: this one works backwards */
2207
			$ntpcfg .= ' nomodify';
2208
		}
2209
		if (!empty(config_get_path('ntpd/noquery'))) {
2210
			$ntpcfg .= ' noquery';
2211
		}
2212
		if (empty(config_get_path('ntpd/notrap'))) { /*note: this one works backwards */
2213
			$ntpcfg .= ' notrap';
2214
		}
2215
	}
2216

    
2217
	/* Custom Access Restrictions */
2218
	if (is_array(config_get_path('ntpd/restrictions/row'))) {
2219
		$networkacl = config_get_path('ntpd/restrictions/row');
2220
		foreach ($networkacl as $acl) {
2221
			$restrict = "";
2222
			if (is_ipaddrv6($acl['acl_network'])) {
2223
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask_v6($acl['mask']) . " ";
2224
			} elseif (is_ipaddrv4($acl['acl_network'])) {
2225
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask($acl['mask']) . " ";
2226
			} else {
2227
				continue;
2228
			}
2229
			if (!empty($acl['kod'])) {
2230
				$restrict .= ' kod limited';
2231
			}
2232
			if (!empty($acl['nomodify'])) {
2233
				$restrict .= ' nomodify';
2234
			}
2235
			if (!empty($acl['noquery'])) {
2236
				$restrict .= ' noquery';
2237
			}
2238
			if (!empty($acl['nopeer'])) {
2239
				$restrict .= ' nopeer';
2240
			}
2241
			if (!empty($acl['noserve'])) {
2242
				$restrict .= ' noserve';
2243
			}
2244
			if (!empty($acl['notrap'])) {
2245
				$restrict .= ' notrap';
2246
			}
2247
			if (!empty($restrict)) {
2248
				$ntpcfg .= "\nrestrict {$restrict} ";
2249
			}
2250
		}
2251
	}
2252
	/* End Custom Access Restrictions */
2253

    
2254
	/* A leapseconds file is really only useful if this clock is stratum 1 */
2255
	$ntpcfg .= "\n";
2256
	if (!empty(config_get_path('ntpd/leapsec'))) {
2257
		$leapsec .= base64_decode(config_get_path('ntpd/leapsec'));
2258
		file_put_contents('/var/db/leap-seconds', $leapsec);
2259
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
2260
	}
2261

    
2262

    
2263
	if (empty(config_get_path('ntpd/interface'))) {
2264
		$interfaces =
2265
			explode(",",
2266
					config_get_path('installedpackages/openntpd/config/0/interface', ''));
2267
	} else {
2268
		$interfaces = explode(",", config_get_path('ntpd/interface'));
2269
	}
2270

    
2271
	if (is_array($interfaces) && count($interfaces)) {
2272
		$finterfaces = array();
2273
		foreach ($interfaces as $interface) {
2274
			$interface = get_real_interface($interface);
2275
			if (!empty($interface)) {
2276
				$finterfaces[] = $interface;
2277
			}
2278
		}
2279
		if (!empty($finterfaces)) {
2280
			$ntpcfg .= "interface ignore all\n";
2281
			$ntpcfg .= "interface ignore wildcard\n";
2282
			foreach ($finterfaces as $interface) {
2283
				$ntpcfg .= "interface listen {$interface}\n";
2284
			}
2285
		}
2286
	}
2287

    
2288
	/* open configuration for writing or bail */
2289
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
2290
		log_error(sprintf(gettext("Could not open %s/ntpd.conf for writing"), g_get('varetc_path')));
2291
		return;
2292
	}
2293

    
2294
	/* if /var/empty does not exist, create it */
2295
	if (!is_dir("/var/empty")) {
2296
		mkdir("/var/empty", 0555, true);
2297
	}
2298

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

    
2302
	// Note that we are starting up
2303
	log_error("NTPD is starting up.");
2304

    
2305
	if (platform_booting()) {
2306
		echo gettext("done.") . "\n";
2307
	}
2308

    
2309
	return;
2310
}
2311

    
2312
function system_halt() {
2313
	global $g;
2314

    
2315
	system_reboot_cleanup();
2316

    
2317
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
2318
}
2319

    
2320
function system_reboot() {
2321
	global $g;
2322

    
2323
	system_reboot_cleanup();
2324

    
2325
	mwexec("/usr/bin/nohup /etc/rc.reboot > /dev/null 2>&1 &");
2326
}
2327

    
2328
function system_reboot_sync($reroot=false) {
2329
	global $g;
2330

    
2331
	if ($reroot) {
2332
		$args = " -r ";
2333
	}
2334

    
2335
	system_reboot_cleanup();
2336

    
2337
	mwexec("/etc/rc.reboot {$args} > /dev/null 2>&1");
2338
}
2339

    
2340
function system_reboot_cleanup() {
2341
	global $g, $cpzone;
2342

    
2343
	mwexec("/usr/local/bin/beep.sh stop");
2344
	require_once("captiveportal.inc");
2345
	$cps = config_get_path('captiveportal', []);
2346
	foreach ($cps as $cpzone=>$cp) {
2347
		if (!isset($cp['preservedb'])) {
2348
			/* send Accounting-Stop packet for all clients, termination cause 'Admin-Reboot' */
2349
			captiveportal_radius_stop_all(7); // Admin-Reboot
2350
			unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
2351
			captiveportal_free_dnrules();
2352
		}
2353
		/* Send Accounting-Off packet to the RADIUS server */
2354
		captiveportal_send_server_accounting('off');
2355
	}
2356

    
2357
	if (count($cps)> 0) {
2358
		/* Remove the pipe database */
2359
		unlink_if_exists("{$g['vardb_path']}/captiveportaldn.rules");
2360
	}
2361

    
2362
	require_once("voucher.inc");
2363
	voucher_save_db_to_config();
2364
	require_once("pfsense-utils.inc");
2365
	enable_carp(false);
2366
	require_once("pkg-utils.inc");
2367
	stop_packages();
2368
}
2369

    
2370
function system_do_shell_commands($early = 0) {
2371
	if (config_path_enabled('system', 'developerspew')) {
2372
		$mt = microtime();
2373
		echo "system_do_shell_commands() being called $mt\n";
2374
	}
2375

    
2376
	if ($early) {
2377
		$cmdn = "earlyshellcmd";
2378
	} else {
2379
		$cmdn = "shellcmd";
2380
	}
2381

    
2382
	$syscmd = config_get_path("system/{$cmdn}", '');
2383
	if (is_array($syscmd)) {
2384
		/* *cmd is an array, loop through */
2385
		foreach ($syscmd as $cmd) {
2386
			exec($cmd);
2387
		}
2388

    
2389
	} elseif ($syscmd <> "") {
2390
		/* execute single item */
2391
		exec($syscmd);
2392

    
2393
	}
2394
}
2395

    
2396
function system_dmesg_save() {
2397
	global $g;
2398
	if (config_path_enabled('system', 'developerspew')) {
2399
		$mt = microtime();
2400
		echo "system_dmesg_save() being called $mt\n";
2401
	}
2402

    
2403
	$dmesg = "";
2404
	$_gb = exec("/sbin/dmesg", $dmesg);
2405

    
2406
	/* find last copyright line (output from previous boots may be present) */
2407
	$lastcpline = 0;
2408

    
2409
	for ($i = 0; $i < count($dmesg); $i++) {
2410
		if (strstr($dmesg[$i], "Copyright (c) 1992-")) {
2411
			$lastcpline = $i;
2412
		}
2413
	}
2414

    
2415
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
2416
	if (!$fd) {
2417
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
2418
		return 1;
2419
	}
2420

    
2421
	for ($i = $lastcpline; $i < count($dmesg); $i++) {
2422
		fwrite($fd, $dmesg[$i] . "\n");
2423
	}
2424

    
2425
	fclose($fd);
2426
	unset($dmesg);
2427

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

    
2431
	return 0;
2432
}
2433

    
2434
function system_set_harddisk_standby() {
2435
	if (config_path_enabled('system', 'developerspew')) {
2436
		$mt = microtime();
2437
		echo "system_set_harddisk_standby() being called $mt\n";
2438
	}
2439

    
2440
	if (config_path_enabled('system', 'harddiskstandby')) {
2441
		if (platform_booting()) {
2442
			echo gettext('Setting hard disk standby... ');
2443
		}
2444

    
2445
		$standby = config_get_path('system/harddiskstandby');
2446
		// Check for a numeric value
2447
		if (is_numeric($standby)) {
2448
			// Get only suitable candidates for standby; using get_smart_drive_list()
2449
			// from utils.inc to get the list of drives.
2450
			$harddisks = get_smart_drive_list();
2451

    
2452
			// Since get_smart_drive_list() only matches ad|da|ada; lets put the check below
2453
			// just in case of some weird pfSense platform installs.
2454
			if (count($harddisks) > 0) {
2455
				// Iterate disks and run the camcontrol command for each
2456
				foreach ($harddisks as $harddisk) {
2457
					mwexec("/sbin/camcontrol standby {$harddisk} -t {$standby}");
2458
				}
2459
				if (platform_booting()) {
2460
					echo gettext("done.") . "\n";
2461
				}
2462
			} else if (platform_booting()) {
2463
				echo gettext("failed!") . "\n";
2464
			}
2465
		} else if (platform_booting()) {
2466
			echo gettext("failed!") . "\n";
2467
		}
2468
	}
2469
}
2470

    
2471
function system_setup_sysctl() {
2472
	if (config_path_enabled('system', 'developerspew')) {
2473
		$mt = microtime();
2474
		echo "system_setup_sysctl() being called $mt\n";
2475
	}
2476

    
2477
	activate_sysctls();
2478

    
2479
	if (config_path_enabled('system', 'sharednet')) {
2480
		system_disable_arp_wrong_if();
2481
	}
2482
}
2483

    
2484
function system_disable_arp_wrong_if() {
2485
	if (config_path_enabled('system', 'developerspew')) {
2486
		$mt = microtime();
2487
		echo "system_disable_arp_wrong_if() being called $mt\n";
2488
	}
2489
	set_sysctl(array(
2490
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
2491
		"net.link.ether.inet.log_arp_movements" => "0"
2492
	));
2493
}
2494

    
2495
function system_enable_arp_wrong_if() {
2496
	if (config_path_enabled('system', 'developerspew')) {
2497
		$mt = microtime();
2498
		echo "system_enable_arp_wrong_if() being called $mt\n";
2499
	}
2500
	set_sysctl(array(
2501
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
2502
		"net.link.ether.inet.log_arp_movements" => "1"
2503
	));
2504
}
2505

    
2506
function enable_watchdog() {
2507
	return;
2508
	$install_watchdog = false;
2509
	$supported_watchdogs = array("Geode");
2510
	$file = file_get_contents("/var/log/dmesg.boot");
2511
	foreach ($supported_watchdogs as $sd) {
2512
		if (stristr($file, "Geode")) {
2513
			$install_watchdog = true;
2514
		}
2515
	}
2516
	if ($install_watchdog == true) {
2517
		if (is_process_running("watchdogd")) {
2518
			mwexec("/usr/bin/killall watchdogd", true);
2519
		}
2520
		exec("/usr/sbin/watchdogd");
2521
	}
2522
}
2523

    
2524
function system_check_reset_button() {
2525
	global $g;
2526

    
2527
	$specplatform = system_identify_specific_platform();
2528

    
2529
	switch ($specplatform['name']) {
2530
		case 'SG-2220':
2531
			$binprefix = "RCC-DFF";
2532
			break;
2533
		case 'alix':
2534
		case 'wrap':
2535
		case 'FW7541':
2536
		case 'APU':
2537
		case 'RCC-VE':
2538
		case 'RCC':
2539
			$binprefix = $specplatform['name'];
2540
			break;
2541
		default:
2542
			return 0;
2543
	}
2544

    
2545
	$retval = mwexec("/usr/local/sbin/" . $binprefix . "resetbtn");
2546

    
2547
	if ($retval == 99) {
2548
		/* user has pressed reset button for 2 seconds -
2549
		   reset to factory defaults */
2550
		echo <<<EOD
2551

    
2552
***********************************************************************
2553
* Reset button pressed - resetting configuration to factory defaults. *
2554
* All additional packages installed will be removed                   *
2555
* The system will reboot after this completes.                        *
2556
***********************************************************************
2557

    
2558

    
2559
EOD;
2560

    
2561
		reset_factory_defaults();
2562
		system_reboot_sync();
2563
		exit(0);
2564
	}
2565

    
2566
	return 0;
2567
}
2568

    
2569
function system_get_serial() {
2570
	$platform = system_identify_specific_platform();
2571

    
2572
	unset($output);
2573
	if ($platform['name'] == 'Turbot Dual-E') {
2574
		$if_info = get_interface_addresses('igb0');
2575
		if (!empty($if_info['hwaddr'])) {
2576
			$serial = str_replace(":", "", $if_info['hwaddr']);
2577
		}
2578
	} else {
2579
		foreach (array('system', 'planar', 'chassis') as $key) {
2580
			unset($output);
2581
			$_gb = exec("/bin/kenv -q smbios.{$key}.serial",
2582
			    $output);
2583
			if (!empty($output[0]) && $output[0] != "0123456789" &&
2584
			    preg_match('/^[\w\d]{10,16}$/', $output[0]) === 1) {
2585
				$serial = $output[0];
2586
				break;
2587
			}
2588
		}
2589
	}
2590

    
2591
	$vm_guest = get_single_sysctl('kern.vm_guest');
2592

    
2593
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2594
	    $vm_guest == 'none') {
2595
		return $serial;
2596
	}
2597

    
2598
	return "";
2599
}
2600

    
2601
function system_get_uniqueid() {
2602
	global $g;
2603

    
2604
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2605

    
2606
	if (empty(g_get('uniqueid'))) {
2607
		if (!file_exists($uniqueid_file)) {
2608
			mwexec("/usr/sbin/gnid > {$g['vardb_path']}/uniqueid " .
2609
			    "2>/dev/null");
2610
		}
2611
		if (file_exists($uniqueid_file)) {
2612
			$g['uniqueid'] = @file_get_contents($uniqueid_file);
2613
		}
2614
	}
2615

    
2616
	return (g_get('uniqueid') ?: '');
2617
}
2618

    
2619
/*
2620
 * attempt to identify the specific platform (for embedded systems)
2621
 * Returns an array with two elements:
2622
 * name => platform string (e.g. 'wrap', 'alix' etc.)
2623
 * descr => human-readable description (e.g. "PC Engines WRAP")
2624
 */
2625
function system_identify_specific_platform() {
2626
	global $g;
2627

    
2628
	$hw_model = get_single_sysctl('hw.model');
2629
	$hw_ncpu = get_single_sysctl('hw.ncpu');
2630

    
2631
	/* Try to guess from smbios strings */
2632
	unset($product);
2633
	unset($maker);
2634
	unset($bios);
2635
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $product);
2636
	$_gb = exec('/bin/kenv -q smbios.system.maker 2>/dev/null', $maker);
2637
	$_gb = exec('/bin/kenv -q smbios.bios.version 2>/dev/null', $bios);
2638

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

    
2642
	if ($maker[0] == "QEMU") {
2643
		return (array('name' => 'QEMU', 'descr' => 'QEMU Guest'));
2644
	} else  if ($maker[0] == "Google") {
2645
		return (array('name' => 'Google', 'descr' => 'Google Cloud Platform'));
2646
	} else  if ($maker[0] == "Amazon EC2") {
2647
		return (array('name' => 'AWS', 'descr' => 'Amazon Web Services'));
2648
	}
2649

    
2650
	// This switch needs to be expanded to include other virtualization systems
2651
	switch ($vm) {
2652
		case "none" :
2653
		break;
2654

    
2655
		case "kvm" :
2656
			return (array('name' => 'KVM', 'descr' => 'KVM Guest'));
2657
		break;
2658
	}
2659

    
2660
	// AWS and GCP can also be identified via the bios version
2661
	if (stripos($bios[0], "amazon") !== false) {
2662
		return (array('name' => 'AWS', 'descr' => 'Amazon Web Services'));
2663
	} else  if (stripos($bios[0], "Google") !== false) {
2664
		return (array('name' => 'Google', 'descr' => 'Google Cloud Platform'));
2665
	}
2666

    
2667
	switch ($product[0]) {
2668
		case 'FW7541':
2669
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2670
			break;
2671
		case 'apu1':
2672
		case 'APU':
2673
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2674
			break;
2675
		case 'RCC-VE':
2676
			$result = array();
2677
			$result['name'] = 'RCC-VE';
2678

    
2679
			/* Detect specific models */
2680
			if (!function_exists('does_interface_exist')) {
2681
				require_once("interfaces.inc");
2682
			}
2683
			if (!does_interface_exist('igb4')) {
2684
				$result['model'] = 'SG-2440';
2685
			} elseif (strpos($hw_model, "C2558") !== false) {
2686
				$result['model'] = 'SG-4860';
2687
			} elseif (strpos($hw_model, "C2758") !== false) {
2688
				$result['model'] = 'SG-8860';
2689
			} else {
2690
				$result['model'] = 'RCC-VE';
2691
			}
2692
			$result['descr'] = 'Netgate ' . $result['model'];
2693
			return $result;
2694
			break;
2695
		case 'DFFv2':
2696
			return (array('name' => 'SG-2220', 'descr' => 'Netgate SG-2220'));
2697
			break;
2698
		case 'RCC':
2699
			return (array('name' => 'RCC', 'descr' => 'Netgate XG-2758'));
2700
			break;
2701
		case 'SG-5100':
2702
			return (array('name' => '5100', 'descr' => 'Netgate 5100'));
2703
			break;
2704
		case 'Minnowboard Turbot D0 PLATFORM':
2705
		case 'Minnowboard Turbot D0/D1 PLATFORM':
2706
			$result = array();
2707
			$result['name'] = 'Turbot Dual-E';
2708
			/* Ensure the graphics driver is loaded */
2709
			system("kldload -nq i915kms");
2710
			/* Detect specific model */
2711
			switch ($hw_ncpu) {
2712
			case '4':
2713
				$result['model'] = 'MBT-4220';
2714
				break;
2715
			case '2':
2716
				$result['model'] = 'MBT-2220';
2717
				break;
2718
			default:
2719
				$result['model'] = $result['name'];
2720
				break;
2721
			}
2722
			$result['descr'] = 'Netgate ' . $result['model'];
2723
			return $result;
2724
			break;
2725
		case 'SYS-5018A-FTN4':
2726
		case 'A1SAi':
2727
			if (strpos($hw_model, "C2558") !== false) {
2728
				return (array(
2729
				    'name' => 'C2558',
2730
				    'descr' => 'Super Micro C2558'));
2731
			} elseif (strpos($hw_model, "C2758") !== false) {
2732
				return (array(
2733
				    'name' => 'C2758',
2734
				    'descr' => 'Super Micro C2758'));
2735
			}
2736
			break;
2737
		case 'SYS-5018D-FN4T':
2738
			if (strpos($hw_model, "D-1541") !== false) {
2739
				return (array('name' => '1541', 'descr' => 'Super Micro 1541'));
2740
			} else {
2741
				return (array('name' => '1540', 'descr' => 'Super Micro XG-1540'));
2742
			}
2743
			break;
2744
		case 'apu2':
2745
		case 'APU2':
2746
			return (array('name' => 'apu2', 'descr' => 'PC Engines APU2'));
2747
			break;
2748
		case 'VirtualBox':
2749
			return (array('name' => 'VirtualBox', 'descr' => 'VirtualBox Virtual Machine'));
2750
			break;
2751
		case 'Virtual Machine':
2752
			if ($maker[0] == "Microsoft Corporation") {
2753
				if (stripos($bios[0], "Hyper") !== false) {
2754
					return (array('name' => 'Hyper-V', 'descr' => 'Hyper-V Virtual Machine'));
2755
				} else {
2756
					return (array('name' => 'Azure', 'descr' => 'Microsoft Azure'));
2757
				}
2758
			}
2759
			break;
2760
		case 'VMware Virtual Platform':
2761
			if ($maker[0] == "VMware, Inc.") {
2762
				return (array('name' => 'VMware', 'descr' => 'VMware Virtual Machine'));
2763
			}
2764
			break;
2765
	}
2766

    
2767
	$_gb = exec('/bin/kenv -q smbios.planar.product 2>/dev/null',
2768
	    $planar_product);
2769
	if (isset($planar_product[0]) &&
2770
	    $planar_product[0] == 'X10SDV-8C-TLN4F+') {
2771
		return array('name' => '1537', 'descr' => 'Super Micro 1537');
2772
	}
2773

    
2774
	if (strpos($hw_model, "PC Engines WRAP") !== false) {
2775
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
2776
	}
2777

    
2778
	if (strpos($hw_model, "PC Engines ALIX") !== false) {
2779
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2780
	}
2781

    
2782
	if (preg_match("/Soekris net45../", $hw_model, $matches)) {
2783
		return array('name' => 'net45xx', 'descr' => $matches[0]);
2784
	}
2785

    
2786
	if (preg_match("/Soekris net48../", $hw_model, $matches)) {
2787
		return array('name' => 'net48xx', 'descr' => $matches[0]);
2788
	}
2789

    
2790
	if (preg_match("/Soekris net55../", $hw_model, $matches)) {
2791
		return array('name' => 'net55xx', 'descr' => $matches[0]);
2792
	}
2793

    
2794
	unset($hw_model);
2795

    
2796
	$dmesg_boot = system_get_dmesg_boot();
2797
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
2798
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2799
	}
2800
	unset($dmesg_boot);
2801

    
2802
	return array('name' => g_get('product_name'), 'descr' => g_get('product_label'));
2803
}
2804

    
2805
function system_get_dmesg_boot() {
2806
	global $g;
2807

    
2808
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2809
}
2810

    
2811
function system_get_arp_table($resolve_hostnames = false) {
2812
	$params="-a";
2813
	if (!$resolve_hostnames) {
2814
		$params .= "n";
2815
	}
2816

    
2817
	$arp_table = array();
2818
	$_gb = exec("/usr/sbin/arp --libxo json {$params}", $rawdata, $rc);
2819
	if ($rc == 0) {
2820
		$arp_table = json_decode(implode(" ", $rawdata),
2821
		    JSON_OBJECT_AS_ARRAY);
2822
		if ($rc == 0) {
2823
			$arp_table = $arp_table['arp']['arp-cache'];
2824
		}
2825
	}
2826

    
2827
	return $arp_table;
2828
}
2829

    
2830
function _getHostName($mac, $ip) {
2831
	global $dhcpmac, $dhcpip;
2832

    
2833
	if ($dhcpmac[$mac]) {
2834
		return $dhcpmac[$mac];
2835
	} else if ($dhcpip[$ip]) {
2836
		return $dhcpip[$ip];
2837
	} else {
2838
		exec("/usr/bin/host -W 1 " . escapeshellarg($ip), $output);
2839
		if (preg_match('/.*pointer ([A-Za-z_0-9.-]+)\..*/', $output[0], $matches)) {
2840
			if ($matches[1] <> $ip) {
2841
				return $matches[1];
2842
			}
2843
		}
2844
	}
2845
	return "";
2846
}
2847

    
2848
function check_dnsavailable($proto='inet') {
2849

    
2850
	if ($proto == 'inet') {
2851
		$gdns = array('8.8.8.8', '8.8.4.4');
2852
	} elseif ($proto == 'inet6') {
2853
		$gdns = array('2001:4860:4860::8888', '2001:4860:4860::8844');
2854
	} else {
2855
		$gdns = array('8.8.8.8', '8.8.4.4', '2001:4860:4860::8888', '2001:4860:4860::8844');
2856
	}
2857
	$nameservers = array_merge($gdns, get_dns_nameservers());
2858
	$test = 0;
2859

    
2860
	foreach ($gdns as $dns) {
2861
		if ($dns == '127.0.0.1') {
2862
			continue;
2863
		} else {
2864
			$dns_result = trim(_getHostName("", $dns));
2865
			if (($test == '2') && ($dns_result == "")) {
2866
				return false;
2867
			} elseif ($dns_result == "") {
2868
				$test++;
2869
				continue;
2870
			} else {
2871
				return true;
2872
			}
2873
		}
2874
	}
2875

    
2876
	return false;
2877
}
2878

    
2879
?>
(50-50/61)