Project

General

Profile

Download (75.9 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-2022 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 activate_powerd() {
32
	if (is_process_running("powerd")) {
33
		exec("/usr/bin/killall powerd");
34
	}
35
	if (config_path_enabled('system', 'powerd_enable')) {
36
		$ac_mode = "hadp";
37
		if (!empty(config_get_path('system/powerd_ac_mode'))) {
38
			$ac_mode = config_get_path('system/powerd_ac_mode');
39
		}
40

    
41
		$battery_mode = "hadp";
42
		if (!empty(config_get_path('system/powerd_battery_mode'))) {
43
			$battery_mode = config_get_path('system/powerd_battery_mode');
44
		}
45

    
46
		$normal_mode = "hadp";
47
		if (!empty(config_get_path('system/powerd_normal_mode'))) {
48
			$normal_mode = config_get_path('system/powerd_normal_mode');
49
		}
50

    
51
		mwexec("/usr/sbin/powerd" .
52
			" -b " . escapeshellarg($battery_mode) .
53
			" -a " . escapeshellarg($ac_mode) .
54
			" -n " . escapeshellarg($normal_mode));
55
	}
56
}
57

    
58
function get_default_sysctl_value($id) {
59
	global $sysctls;
60

    
61
	if (isset($sysctls[$id])) {
62
		return $sysctls[$id];
63
	}
64
}
65

    
66
function get_sysctl_descr($sysctl) {
67
	unset($output);
68
	$_gb = exec("/sbin/sysctl -qnd {$sysctl}", $output);
69

    
70
	return $output[0];
71
}
72

    
73
function system_get_sysctls() {
74
	global $sysctls;
75

    
76
	$disp_sysctl = array();
77
	$disp_cache = array();
78
	foreach (config_get_path('sysctl/item', []) as $id => $tunable) {
79
		if ($tunable['value'] == "default") {
80
			$value = get_default_sysctl_value($tunable['tunable']);
81
		} else {
82
			$value = $tunable['value'];
83
		}
84

    
85
		$disp_sysctl[$id] = $tunable;
86
		$disp_sysctl[$id]['modified'] = true;
87
		$disp_cache[$tunable['tunable']] = 'set';
88
	}
89

    
90
	foreach ($sysctls as $sysctl => $value) {
91
		if (isset($disp_cache[$sysctl])) {
92
			continue;
93
		}
94

    
95
		$disp_sysctl[$sysctl] = array('tunable' => $sysctl, 'value' => $value, 'descr' => get_sysctl_descr($sysctl));
96
	}
97
	unset($disp_cache);
98
	return $disp_sysctl;
99
}
100

    
101
function activate_sysctls() {
102
	global $sysctls, $ipsec_filter_sysctl;
103

    
104
	if (!is_array($sysctls)) {
105
		$sysctls = array();
106
	}
107

    
108
	$ipsec_filtermode = config_get_path('ipsec/filtermode', 'enc');
109
	$sysctls = array_merge($sysctls, $ipsec_filter_sysctl[$ipsec_filtermode]);
110

    
111
	foreach (config_get_path('sysctl/item', []) as $tunable) {
112
		if ($tunable['value'] == "default") {
113
			$value = get_default_sysctl_value($tunable['tunable']);
114
		} else {
115
			$value = $tunable['value'];
116
		}
117

    
118
		$sysctls[$tunable['tunable']] = $value;
119
	}
120

    
121
	/* Set net.pf.request_maxcount via sysctl since it is no longer a loader
122
	 *   tunable. See https://redmine.pfsense.org/issues/10861
123
	 *   Set the value dynamically since its default is not static, yet this
124
	 *   still could be overridden by a user tunable. */
125
	$maximumtableentries = config_get_path('system/maximumtableentries',
126
										   pfsense_default_table_entries_size());
127

    
128
	/* Set the default when there is no tunable or when the tunable is set
129
	 * too low. */
130
	if (empty($sysctls['net.pf.request_maxcount']) ||
131
	    ($sysctls['net.pf.request_maxcount'] < $maximumtableentries)) {
132
		$sysctls['net.pf.request_maxcount'] = $maximumtableentries;
133
	}
134

    
135
	set_sysctl($sysctls);
136
}
137

    
138
function system_resolvconf_generate($dynupdate = false) {
139
	global $g;
140

    
141
	if (config_path_enabled('system', 'developerspew')) {
142
		$mt = microtime();
143
		echo "system_resolvconf_generate() being called $mt\n";
144
	}
145

    
146
	$syscfg = config_get_path('system', []);
147

    
148
	foreach(get_dns_nameservers(false, false) as $dns_ns) {
149
		$resolvconf .= "nameserver $dns_ns\n";
150
	}
151

    
152
	$ns = array();
153
	if (isset($syscfg['dnsallowoverride'])) {
154
		/* get dynamically assigned DNS servers (if any) */
155
		$ns = array_unique(get_searchdomains());
156
		foreach ($ns as $searchserver) {
157
			if ($searchserver) {
158
				$resolvconf .= "search {$searchserver}\n";
159
			}
160
		}
161
	}
162
	if (empty($ns)) {
163
		// Do not create blank search/domain lines, it can break tools like dig.
164
		if ($syscfg['domain']) {
165
			$resolvconf .= "search {$syscfg['domain']}\n";
166
		}
167
	}
168

    
169
	// Add EDNS support
170
	if (config_path_enabled('unbound') && (config_get_path('unbound/edns') != null)) {
171
		$resolvconf .= "options edns0\n";
172
	}
173

    
174
	$dnslock = lock('resolvconf', LOCK_EX);
175

    
176
	$fd = fopen("{$g['etc_path']}/resolv.conf", "w");
177
	if (!$fd) {
178
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
179
		unlock($dnslock);
180
		return 1;
181
	}
182

    
183
	fwrite($fd, $resolvconf);
184
	fclose($fd);
185

    
186
	// Prevent resolvconf(8) from rewriting our resolv.conf
187
	$fd = fopen("{$g['etc_path']}/resolvconf.conf", "w");
188
	if (!$fd) {
189
		printf("Error: cannot open resolvconf.conf in system_resolvconf_generate().\n");
190
		return 1;
191
	}
192
	fwrite($fd, "resolv_conf=\"/dev/null\"\n");
193
	fclose($fd);
194

    
195
	if (!platform_booting()) {
196
		/* restart dhcpd (nameservers may have changed) */
197
		if (!$dynupdate) {
198
			services_dhcpd_configure();
199
		}
200
	}
201

    
202
	// set up or tear down static routes for DNS servers
203
	$dnscounter = 1;
204
	$dnsgw = "dns{$dnscounter}gw";
205
	while (!empty(config_get_path("system/{$dnsgw}"))) {
206
		/* setup static routes for dns servers */
207
		$gwname = config_get_path("system/{$dnsgw}");		unset($gatewayip);
208
		unset($inet6);
209
		if ((!empty($gwname)) && ($gwname != "none")) {
210
			$gatewayip = lookup_gateway_ip_by_name($gwname);
211
			$inet6 = is_ipaddrv6($gatewayip) ? '-inet6 ' : '';
212
		}
213
		/* dns server array starts at 0 */
214
		$dnsserver = $syscfg['dnsserver'][$dnscounter - 1];
215

    
216
		/* specify IP protocol version for correct add/del,
217
		 * see https://redmine.pfsense.org/issues/11578 */
218
		if (is_ipaddrv4($dnsserver)) {
219
			$ipprotocol = 'inet';
220
		} else {
221
			$ipprotocol = 'inet6';
222
		}
223
		if (!empty($dnsserver)) {
224
			if (is_ipaddr($gatewayip)) {
225
				route_add_or_change($dnsserver, $gatewayip, '', '', $ipprotocol);
226
			} else {
227
				/* Remove old route when disable gw */
228
				route_del($dnsserver, $ipprotocol);
229
			}
230
		}
231
		$dnscounter++;
232
		$dnsgw = "dns{$dnscounter}gw";
233
	}
234

    
235
	unlock($dnslock);
236

    
237
	return 0;
238
}
239

    
240
function get_searchdomains() {
241
	$master_list = array();
242

    
243
	// Read in dhclient nameservers
244
	$search_list = glob("/var/etc/searchdomain_*");
245
	if (is_array($search_list)) {
246
		foreach ($search_list as $fdns) {
247
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
248
			if (!is_array($contents)) {
249
				continue;
250
			}
251
			foreach ($contents as $dns) {
252
				if (is_hostname($dns)) {
253
					$master_list[] = $dns;
254
				}
255
			}
256
		}
257
	}
258

    
259
	return $master_list;
260
}
261

    
262
/* Stub for deprecated function name
263
 * See https://redmine.pfsense.org/issues/10931 */
264
function get_nameservers() {
265
	return get_dynamic_nameservers();
266
}
267

    
268
/****f* system.inc/get_dynamic_nameservers
269
 * NAME
270
 *   get_dynamic_nameservers - Get DNS servers from dynamic sources (DHCP, PPP, etc)
271
 * INPUTS
272
 *   $iface: Interface name used to filter results.
273
 * RESULT
274
 *   $master_list - Array containing DNS servers
275
 ******/
276
function get_dynamic_nameservers($iface = '') {
277
	$master_list = array();
278

    
279
	if (!empty($iface)) {
280
		$realif = get_real_interface($iface);
281
	}
282

    
283
	// Read in dynamic nameservers
284
	$dns_lists = array_merge(glob("/var/etc/nameserver_{$realif}*"), glob("/var/etc/nameserver_v6{$iface}*"));
285
	if (is_array($dns_lists)) {
286
		foreach ($dns_lists as $fdns) {
287
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
288
			if (!is_array($contents)) {
289
				continue;
290
			}
291
			foreach ($contents as $dns) {
292
				if (is_ipaddr($dns)) {
293
					$master_list[] = $dns;
294
				}
295
			}
296
		}
297
	}
298

    
299
	return $master_list;
300
}
301

    
302
/* Create localhost + local interfaces entries for /etc/hosts */
303
function system_hosts_local_entries() {
304
	$syscfg = config_get_path('system', []);
305

    
306
	$hosts = array();
307
	$hosts[] = array(
308
	    'ipaddr' => '127.0.0.1',
309
	    'fqdn' => 'localhost.' . $syscfg['domain'],
310
	    'name' => 'localhost',
311
	    'domain' => $syscfg['domain']
312
	);
313
	$hosts[] = array(
314
	    'ipaddr' => '::1',
315
	    'fqdn' => 'localhost.' . $syscfg['domain'],
316
	    'name' => 'localhost',
317
	    'domain' => $syscfg['domain']
318
	);
319

    
320
	if (config_get_path('interfaces/lan')) {
321
		$sysiflist = array('lan' => "lan");
322
	} else {
323
		$sysiflist = get_configured_interface_list();
324
	}
325

    
326
	$hosts_if_found = false;
327
	$local_fqdn = "{$syscfg['hostname']}.{$syscfg['domain']}";
328
	foreach ($sysiflist as $sysif) {
329
		if ($sysif != 'lan' && interface_has_gateway($sysif)) {
330
			continue;
331
		}
332
		$cfgip = get_interface_ip($sysif);
333
		if (is_ipaddrv4($cfgip)) {
334
			$hosts[] = array(
335
			    'ipaddr' => $cfgip,
336
			    'fqdn' => $local_fqdn,
337
			    'name' => $syscfg['hostname'],
338
			    'domain' => $syscfg['domain']
339
			);
340
			$hosts_if_found = true;
341
		}
342
		if (!isset($syscfg['ipv6dontcreatelocaldns'])) {
343
			$cfgipv6 = get_interface_ipv6($sysif);
344
			if (is_ipaddrv6($cfgipv6)) {
345
				$hosts[] = array(
346
					'ipaddr' => $cfgipv6,
347
					'fqdn' => $local_fqdn,
348
					'name' => $syscfg['hostname'],
349
					'domain' => $syscfg['domain']
350
				);
351
				$hosts_if_found = true;
352
			}
353
		}
354
		if ($hosts_if_found == true) {
355
			break;
356
		}
357
	}
358

    
359
	return $hosts;
360
}
361

    
362
/* Read host override entries from dnsmasq or unbound */
363
function system_hosts_override_entries($dnscfg) {
364
	$hosts = array();
365

    
366
	if (!is_array($dnscfg) ||
367
	    !is_array($dnscfg['hosts']) ||
368
	    !isset($dnscfg['enable'])) {
369
		return $hosts;
370
	}
371

    
372
	foreach ($dnscfg['hosts'] as $host) {
373
		$fqdn = '';
374
		if ($host['host'] || $host['host'] == "0") {
375
			$fqdn .= "{$host['host']}.";
376
		}
377
		$fqdn .= $host['domain'];
378

    
379
		foreach (explode(',', $host['ip']) as $ip) {
380
			$hosts[] = array(
381
			    'ipaddr' => $ip,
382
			    'fqdn' => $fqdn,
383
			    'name' => $host['host'],
384
			    'domain' => $host['domain']
385
			);
386
		}
387

    
388
		if (!is_array($host['aliases']) ||
389
		    !is_array($host['aliases']['item'])) {
390
			continue;
391
		}
392

    
393
		foreach ($host['aliases']['item'] as $alias) {
394
			$fqdn = '';
395
			if ($alias['host'] || $alias['host'] == "0") {
396
				$fqdn .= "{$alias['host']}.";
397
			}
398
			$fqdn .= $alias['domain'];
399

    
400
			foreach (explode(',', $host['ip']) as $ip) {
401
				$hosts[] = array(
402
				    'ipaddr' => $ip,
403
				    'fqdn' => $fqdn,
404
				    'name' => $alias['host'],
405
				    'domain' => $alias['domain']
406
				);
407
			}
408
		}
409
	}
410

    
411
	return $hosts;
412
}
413

    
414
/* Read all dhcpd/dhcpdv6 staticmap entries */
415
function system_hosts_dhcpd_entries() {
416
	$hosts = array();
417
	$syscfg = config_get_path('system');
418

    
419
	$conf_dhcpd = config_get_path('dhcpd', []);
420

    
421
	foreach ($conf_dhcpd as $dhcpif => $dhcpifconf) {
422
		if (!is_array($dhcpifconf['staticmap']) ||
423
		    !isset($dhcpifconf['enable'])) {
424
			continue;
425
		}
426
		foreach ($dhcpifconf['staticmap'] as $host) {
427
			if (!$host['ipaddr'] ||
428
			    !$host['hostname']) {
429
				continue;
430
			}
431

    
432
			$fqdn = $host['hostname'] . ".";
433
			$domain = "";
434
			if ($host['domain']) {
435
				$domain = $host['domain'];
436
			} elseif ($dhcpifconf['domain']) {
437
				$domain = $dhcpifconf['domain'];
438
			} else {
439
				$domain = $syscfg['domain'];
440
			}
441

    
442
			$hosts[] = array(
443
			    'ipaddr' => $host['ipaddr'],
444
			    'fqdn' => $fqdn . $domain,
445
			    'name' => $host['hostname'],
446
			    'domain' => $domain
447
			);
448
		}
449
	}
450
	unset($conf_dhcpd);
451

    
452
	$conf_dhcpdv6 = config_get_path('dhcpdv6', []);
453

    
454
	foreach ($conf_dhcpdv6 as $dhcpif => $dhcpifconf) {
455
		if (!is_array($dhcpifconf['staticmap']) ||
456
		    !isset($dhcpifconf['enable'])) {
457
			continue;
458
		}
459

    
460
		if (config_get_path("interfaces/{$dhcpif}/ipaddrv6") ==
461
		    'track6') {
462
			$isdelegated = true;
463
		} else {
464
			$isdelegated = false;
465
		}
466

    
467
		foreach ($dhcpifconf['staticmap'] as $host) {
468
			$ipaddrv6 = $host['ipaddrv6'];
469

    
470
			if (!$ipaddrv6 || !$host['hostname']) {
471
				continue;
472
			}
473

    
474
			if ($isdelegated) {
475
				/*
476
				 * We are always in an "end-user" subnet
477
				 * here, which all are /64 for IPv6.
478
				 */
479
				$prefix6 = 64;
480
			} else {
481
				$prefix6 = get_interface_subnetv6($dhcpif);
482
			}
483
			$ipaddrv6 = merge_ipv6_delegated_prefix(get_interface_ipv6($dhcpif), $ipaddrv6, $prefix6);
484

    
485
			$fqdn = $host['hostname'] . ".";
486
			$domain = "";
487
			if ($host['domain']) {
488
				$domain = $host['domain'];
489
			} elseif ($dhcpifconf['domain']) {
490
				$domain = $dhcpifconf['domain'];
491
			} else {
492
				$domain = $syscfg['domain'];
493
			}
494

    
495
			$hosts[] = array(
496
			    'ipaddr' => $ipaddrv6,
497
			    'fqdn' => $fqdn . $domain,
498
			    'name' => $host['hostname'],
499
			    'domain' => $domain
500
			);
501
		}
502
	}
503
	unset($conf_dhcpdv6);
504

    
505
	return $hosts;
506
}
507

    
508
/* Concatenate local, dnsmasq/unbound and dhcpd/dhcpdv6 hosts entries */
509
function system_hosts_entries($dnscfg) {
510
	$local = array();
511
	if (!isset($dnscfg['disable_auto_added_host_entries'])) {
512
		$local = system_hosts_local_entries();
513
	}
514

    
515
	$dns = array();
516
	$dhcpd = array();
517
	if (isset($dnscfg['enable'])) {
518
		$dns = system_hosts_override_entries($dnscfg);
519
		if (isset($dnscfg['regdhcpstatic'])) {
520
			$dhcpd = system_hosts_dhcpd_entries();
521
		}
522
	}
523

    
524
	if (isset($dnscfg['dhcpfirst'])) {
525
		return array_merge($local, $dns, $dhcpd);
526
	} else {
527
		return array_merge($local, $dhcpd, $dns);
528
	}
529
}
530

    
531
function system_hosts_generate() {
532
	global $g;
533
	if (config_path_enabled('system', 'developerspew')) {
534
		$mt = microtime();
535
		echo "system_hosts_generate() being called $mt\n";
536
	}
537

    
538
	// prefer dnsmasq for hosts generation where it's enabled. It relies
539
	// on hosts for name resolution of its overrides, unbound does not.
540
	if (config_path_enabled('dnsmasq')) {
541
		$dnsmasqcfg = config_get_path('dnsmasq');
542
	} else {
543
		$dnsmasqcfg = config_get_path('unbound');
544
	}
545

    
546
	$syscfg = config_get_path('system');
547
	$hosts = "";
548
	$lhosts = "";
549
	$dhosts = "";
550

    
551
	$hosts_array = system_hosts_entries($dnsmasqcfg);
552
	foreach ($hosts_array as $host) {
553
		$hosts .= "{$host['ipaddr']}\t";
554
		if ($host['name'] == "localhost") {
555
			$hosts .= "{$host['name']} {$host['fqdn']}";
556
		} else {
557
			$hosts .= "{$host['fqdn']} {$host['name']}";
558
		}
559
		$hosts .= "\n";
560
	}
561
	unset($hosts_array);
562

    
563
	/*
564
	 * Do not remove this because dhcpleases monitors with kqueue it needs
565
	 * to be killed before writing to hosts files.
566
	 */
567
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
568
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
569
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
570
	}
571

    
572
	$fd = fopen("{$g['etc_path']}/hosts", "w");
573
	if (!$fd) {
574
		log_error(gettext(
575
		    "Error: cannot open hosts file in system_hosts_generate()."
576
		    ));
577
		return 1;
578
	}
579

    
580
	fwrite($fd, $hosts);
581
	fclose($fd);
582

    
583
	if (config_path_enabled('unbound')) {
584
		require_once("unbound.inc");
585
		unbound_hosts_generate();
586
	}
587

    
588
	/* restart dhcpleases */
589
	if (!platform_booting()) {
590
		system_dhcpleases_configure();
591
	}
592

    
593
	return 0;
594
}
595

    
596
function system_dhcpleases_configure() {
597
	global $g;
598
	if (!function_exists('is_dhcp_server_enabled')) {
599
		require_once('pfsense-utils.inc');
600
	}
601
	$pidfile = "{$g['varrun_path']}/dhcpleases.pid";
602

    
603
	/* Start the monitoring process for dynamic dhcpclients. */
604
	if (((config_path_enabled('dnsmasq') && (config_get_path('dnsmasq/regdhcp') !== null)) ||
605
	    (config_path_enabled('unbound') && (config_get_path('unbound/regdhcp') !== null))) &&
606
	    (is_dhcp_server_enabled())) {
607
		/* Make sure we do not error out */
608
		mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db");
609
		if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
610
			@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
611
		}
612

    
613
		if (config_path_enabled('unbound')) {
614
			$dns_pid = "unbound.pid";
615
			$unbound_conf = "-u {$g['unbound_chroot_path']}/dhcpleases_entries.conf";
616
		} else {
617
			$dns_pid = "dnsmasq.pid";
618
			$unbound_conf = "";
619
		}
620

    
621
		if (isvalidpid($pidfile)) {
622
			/* Make sure dhcpleases is using correct unbound or dnsmasq */
623
			$_gb = exec("/bin/pgrep -F {$pidfile} -f {$dns_pid}", $output, $retval);
624
			if (intval($retval) == 0) {
625
				sigkillbypid($pidfile, "HUP");
626
				return;
627
			} else {
628
				sigkillbypid($pidfile, "TERM");
629
			}
630
		}
631

    
632
		/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
633
		if (is_process_running("dhcpleases")) {
634
			sigkillbyname('dhcpleases', "TERM");
635
		}
636
		@unlink($pidfile);
637
		mwexec("/usr/local/sbin/dhcpleases -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases -d " .
638
			   config_get_path('system/domain', '') .
639
			   " -p {$g['varrun_path']}/{$dns_pid} {$unbound_conf} -h {$g['etc_path']}/hosts");
640
	} else {
641
		if (isvalidpid($pidfile)) {
642
			sigkillbypid($pidfile, "TERM");
643
			@unlink($pidfile);
644
		}
645
		if (file_exists("{$g['unbound_chroot_path']}/dhcpleases_entries.conf")) {
646
			$dhcpleases = fopen("{$g['unbound_chroot_path']}/dhcpleases_entries.conf", "w");
647
			ftruncate($dhcpleases, 0);
648
			fclose($dhcpleases);
649
		}
650
	}
651
}
652

    
653
function system_get_dhcpleases($dnsavailable=null) {
654
	global $g;
655

    
656
	$leases = array();
657
	$leases['lease'] = array();
658
	$leases['failover'] = array();
659

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

    
662
	if (!file_exists($leases_file)) {
663
		return $leases;
664
	}
665

    
666
	$leases_content = file($leases_file, FILE_IGNORE_NEW_LINES |
667
	    FILE_IGNORE_NEW_LINES);
668

    
669
	if ($leases_content === FALSE) {
670
		return $leases;
671
	}
672

    
673
	$arp_table = system_get_arp_table();
674

    
675
	$arpdata_ip = array();
676
	$arpdata_mac = array();
677
	foreach ($arp_table as $arp_entry) {
678
		if (isset($arpentry['incomplete'])) {
679
			continue;
680
		}
681
		$arpdata_ip[] = $arp_entry['ip-address'];
682
		$arpdata_mac[] = $arp_entry['mac-address'];
683
	}
684
	unset($arp_table);
685

    
686
	/*
687
	 * Translate these once so we don't do it over and over in the loops
688
	 * below.
689
	 */
690
	$online_string = gettext("active");
691
	$offline_string = gettext("idle/offline");
692
	$active_string = gettext("active");
693
	$expired_string = gettext("expired");
694
	$reserved_string = gettext("reserved");
695
	$dynamic_string = gettext("dynamic");
696
	$static_string = gettext("static");
697

    
698
	$lease_regex = '/^lease\s+([^\s]+)\s+{$/';
699
	$starts_regex = '/^\s*(starts|ends)\s+\d+\s+([\d\/]+|never)\s*(|[\d:]*);$/';
700
	$binding_regex = '/^\s*binding\s+state\s+(.+);$/';
701
	$mac_regex = '/^\s*hardware\s+ethernet\s+(.+);$/';
702
	$hostname_regex = '/^\s*client-hostname\s+"(.+)";$/';
703

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

    
707
	$lease = false;
708
	$failover = false;
709
	$dedup_lease = false;
710
	$dedup_failover = false;
711

    
712
	foreach ($leases_content as $line) {
713
		/* Skip comments */
714
		if (preg_match('/^\s*(|#.*)$/', $line)) {
715
			continue;
716
		}
717

    
718
		if (preg_match('/}$/', $line)) {
719
			if ($lease) {
720
				if (empty($item['hostname'])) {
721
					if (is_null($dnsavailable)) {
722
						$dnsavailable = check_dnsavailable();
723
					}
724
					if ($dnsavailable) {
725
						$hostname = gethostbyaddr($item['ip']);
726
						if (!empty($hostname)) {
727
							$item['hostname'] = $hostname;
728
						}
729
					}
730
				}
731
				$leases['lease'][] = $item;
732
				$lease = false;
733
				$dedup_lease = true;
734
			} else if ($failover) {
735
				$leases['failover'][] = $item;
736
				$failover = false;
737
				$dedup_failover = true;
738
			}
739
			continue;
740
		}
741

    
742
		if (preg_match($lease_regex, $line, $m)) {
743
			$lease = true;
744
			$item = array();
745
			$item['ip'] = $m[1];
746
			$item['type'] = $dynamic_string;
747
			continue;
748
		}
749

    
750
		if ($lease) {
751
			if (preg_match($starts_regex, $line, $m)) {
752
				/*
753
				 * Quote from dhcpd.leases(5) man page:
754
				 * If a lease will never expire, date is never
755
				 * instead of an actual date
756
				 */
757
				if ($m[2] == "never") {
758
					$item[$m[1]] = gettext("Never");
759
				} else {
760
					$item[$m[1]] = dhcpd_date_adjust_gmt(
761
					    $m[2] . ' ' . $m[3]);
762
				}
763
				continue;
764
			}
765

    
766
			if (preg_match($binding_regex, $line, $m)) {
767
				switch ($m[1]) {
768
					case "active":
769
						$item['act'] = $active_string;
770
						break;
771
					case "free":
772
						$item['act'] = $expired_string;
773
						$item['online'] =
774
						    $offline_string;
775
						break;
776
					case "backup":
777
						$item['act'] = $reserved_string;
778
						$item['online'] =
779
						    $offline_string;
780
						break;
781
				}
782
				continue;
783
			}
784

    
785
			if (preg_match($mac_regex, $line, $m) &&
786
			    is_macaddr($m[1])) {
787
				$item['mac'] = $m[1];
788

    
789
				if (in_array($item['ip'], $arpdata_ip)) {
790
					$item['online'] = $online_string;
791
				} else {
792
					$item['online'] = $offline_string;
793
				}
794
				continue;
795
			}
796

    
797
			if (preg_match($hostname_regex, $line, $m)) {
798
				$item['hostname'] = $m[1];
799
			}
800
		}
801

    
802
		if (preg_match($failover_regex, $line, $m)) {
803
			$failover = true;
804
			$item = array();
805
			$item['name'] = $m[1] . ' (' .
806
			    convert_friendly_interface_to_friendly_descr(
807
			    substr($m[1],5)) . ')';
808
			continue;
809
		}
810

    
811
		if ($failover && preg_match($state_regex, $line, $m)) {
812
			$item[$m[1] . 'state'] = $m[2];
813
			$item[$m[1] . 'date'] = dhcpd_date_adjust_gmt($m[3] .
814
			    ' ' . $m[4]);
815
			continue;
816
		}
817
	}
818

    
819
	foreach (config_get_path('interfaces', []) as $ifname => $ifarr) {
820
		foreach (config_get_path("dhcpd/{$ifname}/staticmap", []) as $idx =>
821
		    $static) {
822
			if (empty($static['mac']) && empty($static['cid'])) {
823
				continue;
824
			}
825

    
826
			$slease = array();
827
			$slease['ip'] = $static['ipaddr'];
828
			$slease['type'] = $static_string;
829
			if (!empty($static['cid'])) {
830
				$slease['cid'] = $static['cid'];
831
			}
832
			$slease['mac'] = $static['mac'];
833
			$slease['if'] = $ifname;
834
			$slease['starts'] = "";
835
			$slease['ends'] = "";
836
			$slease['hostname'] = $static['hostname'];
837
			$slease['descr'] = $static['descr'];
838
			$slease['act'] = $static_string;
839
			$slease['online'] = in_array(strtolower($slease['mac']),
840
			    $arpdata_mac) ? $online_string : $offline_string;
841
			$slease['staticmap_array_index'] = $idx;
842
			$leases['lease'][] = $slease;
843
			$dedup_lease = true;
844
		}
845
	}
846

    
847
	if ($dedup_lease) {
848
		$leases['lease'] = array_remove_duplicate($leases['lease'],
849
		    'ip');
850
	}
851
	if ($dedup_failover) {
852
		$leases['failover'] = array_remove_duplicate(
853
		    $leases['failover'], 'name');
854
		asort($leases['failover']);
855
	}
856

    
857
	return $leases;
858
}
859

    
860
function system_hostname_configure() {
861
	if (config_path_enabled('system', 'developerspew')) {
862
		$mt = microtime();
863
		echo "system_hostname_configure() being called $mt\n";
864
	}
865

    
866
	$syscfg = config_get_path('system');
867

    
868
	/* set hostname */
869
	$status = mwexec("/bin/hostname " .
870
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
871

    
872
	/* Setup host GUID ID.  This is used by ZFS. */
873
	mwexec("/etc/rc.d/hostid start");
874

    
875
	return $status;
876
}
877

    
878
function system_routing_configure($interface = "") {
879
	if (config_path_enabled('system', 'developerspew')) {
880
		$mt = microtime();
881
		echo "system_routing_configure() being called $mt\n";
882
	}
883

    
884
	$gateways_arr = return_gateways_array(false, true);
885
	foreach ($gateways_arr as $gateway) {
886
		// setup static interface routes for nonlocal gateways
887
		if (isset($gateway["nonlocalgateway"])) {
888
			$srgatewayip = $gateway['gateway'];
889
			$srinterfacegw = $gateway['interface'];
890
			if (is_ipaddr($srgatewayip) && !empty($srinterfacegw)) {
891
				route_add_or_change($srgatewayip, '',
892
				    $srinterfacegw);
893
			}
894
		}
895
	}
896

    
897
	$gateways_status = return_gateways_status(true);
898
	fixup_default_gateway("inet", $gateways_status, $gateways_arr);
899
	fixup_default_gateway("inet6", $gateways_status, $gateways_arr);
900

    
901
	system_staticroutes_configure($interface, false);
902

    
903
	return 0;
904
}
905

    
906
function system_staticroutes_configure($interface = "", $update_dns = false) {
907
	global $g, $aliastable;
908

    
909
	$filterdns_list = array();
910

    
911
	$static_routes = get_staticroutes(false, true);
912
	if (count($static_routes)) {
913
		$gateways_arr = return_gateways_array(false, true);
914

    
915
		foreach ($static_routes as $rtent) {
916
			/* Do not delete disabled routes,
917
			 * see https://redmine.pfsense.org/issues/3709
918
			 * and https://redmine.pfsense.org/issues/10706 */
919
			if (isset($rtent['disabled'])) {
920
				continue;
921
			}
922

    
923
			if (empty($gateways_arr[$rtent['gateway']])) {
924
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
925
				continue;
926
			}
927
			$gateway = $gateways_arr[$rtent['gateway']];
928
			if (!empty($interface) && $interface != $gateway['friendlyiface']) {
929
				continue;
930
			}
931

    
932
			$gatewayip = $gateway['gateway'];
933
			$interfacegw = $gateway['interface'];
934

    
935
			$blackhole = "";
936
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 4))) {
937
				$blackhole = "-blackhole";
938
			}
939

    
940
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network'])) {
941
				continue;
942
			}
943

    
944
			$dnscache = array();
945
			if ($update_dns === true) {
946
				if (is_subnet($rtent['network'])) {
947
					continue;
948
				}
949
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
950
				if (empty($dnscache)) {
951
					continue;
952
				}
953
			}
954

    
955
			if (is_subnet($rtent['network'])) {
956
				$ips = array($rtent['network']);
957
			} else {
958
				if (!isset($rtent['disabled'])) {
959
					$filterdns_list[] = $rtent['network'];
960
				}
961
				$ips = add_hostname_to_watch($rtent['network']);
962
			}
963

    
964
			foreach ($dnscache as $ip) {
965
				if (in_array($ip, $ips)) {
966
					continue;
967
				}
968
				route_del($ip);
969
			}
970

    
971
			if (isset($rtent['disabled'])) {
972
				/*
973
				 * XXX: This can break things by deleting
974
				 * routes that shouldn't be deleted - OpenVPN,
975
				 * dynamic routing scenarios, etc.
976
				 * redmine #3709
977
				 */
978
				foreach ($ips as $ip) {
979
					route_del($ip);
980
				}
981
				continue;
982
			}
983

    
984
			foreach ($ips as $ip) {
985
				if (is_ipaddrv4($ip)) {
986
					$ip .= "/32";
987
				}
988
				/*
989
				 * do NOT do the same check here on v6,
990
				 * is_ipaddrv6 returns true when including
991
				 * the CIDR mask. doing so breaks v6 routes
992
				 */
993
				if (is_subnet($ip)) {
994
					if (is_ipaddr($gatewayip)) {
995
						if (is_linklocal($gatewayip) == "6" &&
996
						    !strpos($gatewayip, '%')) {
997
							/*
998
							 * add interface scope
999
							 * for link local v6
1000
							 * routes
1001
							 */
1002
							$gatewayip .= "%$interfacegw";
1003
						}
1004
						route_add_or_change($ip,
1005
						    $gatewayip, '', $blackhole);
1006
					} else if (!empty($interfacegw)) {
1007
						route_add_or_change($ip,
1008
						    '', $interfacegw, $blackhole);
1009
					}
1010
				}
1011
			}
1012
		}
1013
		unset($gateways_arr);
1014

    
1015
		/* keep static routes cache,
1016
		 * see https://redmine.pfsense.org/issues/11599 */
1017
		$id = 0;
1018
		foreach (config_get_path('staticroutes/route', []) as $sroute) {
1019
			$targets = array();
1020
			if (is_subnet($sroute['network'])) {
1021
				$targets[] = $sroute['network'];
1022
			} elseif (is_alias($sroute['network'])) {
1023
				foreach (preg_split('/\s+/', $aliastable[$sroute['network']]) as $tgt) {
1024
					if (is_ipaddrv4($tgt)) {
1025
						$tgt .= "/32";
1026
					}
1027
					if (is_ipaddrv6($tgt)) {
1028
						$tgt .= "/128";
1029
					}
1030
					if (!is_subnet($tgt)) {
1031
						continue;
1032
					}
1033
					$targets[] = $tgt;
1034
				}
1035
			}
1036
			file_put_contents("{$g['tmp_path']}/staticroute_{$id}", serialize($targets));
1037
			file_put_contents("{$g['tmp_path']}/staticroute_{$id}_gw", serialize($sroute['gateway']));
1038
			$id++;
1039
		}
1040
	}
1041
	unset($static_routes);
1042

    
1043
	if ($update_dns === false) {
1044
		if (count($filterdns_list)) {
1045
			$interval = 60;
1046
			$hostnames = "";
1047
			array_unique($filterdns_list);
1048
			foreach ($filterdns_list as $hostname) {
1049
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
1050
			}
1051
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
1052
			unset($hostnames);
1053

    
1054
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid")) {
1055
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
1056
			} else {
1057
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
1058
			}
1059
		} else {
1060
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
1061
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
1062
		}
1063
	}
1064
	unset($filterdns_list);
1065

    
1066
	return 0;
1067
}
1068

    
1069
function delete_static_route($id, $delete = false) {
1070
	global $g, $changedesc_prefix, $a_gateways;
1071

    
1072
	if (empty(config_get_path("staticroutes/route/{$id}"))) {
1073
		return;
1074
	}
1075

    
1076
	if (file_exists("{$g['tmp_path']}/.system_routes.apply")) {
1077
		$toapplylist = unserialize(file_get_contents("{$g['tmp_path']}/.system_routes.apply"));
1078
	} else {
1079
		$toapplylist = array();
1080
	}
1081

    
1082
	if (file_exists("{$g['tmp_path']}/staticroute_{$id}") &&
1083
	    file_exists("{$g['tmp_path']}/staticroute_{$id}_gw")) {
1084
		$delete_targets = unserialize(file_get_contents("{$g['tmp_path']}/staticroute_{$id}"));
1085
		$delgw = lookup_gateway_ip_by_name(unserialize(file_get_contents("{$g['tmp_path']}/staticroute_{$id}_gw")));
1086
		if (count($delete_targets)) {
1087
			foreach ($delete_targets as $dts) {
1088
				if (is_subnetv4($dts)) {
1089
					$family = "-inet";
1090
				} else {
1091
					$family = "-inet6";
1092
				}
1093
				$route = route_get($dts, '', true);
1094
				if (!count($route)) {
1095
					continue;
1096
				}
1097
				$toapplylist[] = "/sbin/route delete " .
1098
				    $family . " " . $dts . " " . $delgw;
1099
			}
1100
		}
1101
	}
1102

    
1103
	if ($delete) {
1104
		unlink_if_exists("{$g['tmp_path']}/staticroute_{$id}");
1105
		unlink_if_exists("{$g['tmp_path']}/staticroute_{$id}_gw");
1106
	}
1107

    
1108
	if (!empty($toapplylist)) {
1109
		file_put_contents("{$g['tmp_path']}/.system_routes.apply", serialize($toapplylist));
1110
	}
1111

    
1112
	unset($targets);
1113
}
1114

    
1115
function system_routing_enable() {
1116
	if (config_path_enabled('system', 'developerspew')) {
1117
		$mt = microtime();
1118
		echo "system_routing_enable() being called $mt\n";
1119
	}
1120

    
1121
	set_sysctl(array(
1122
		"net.inet.ip.forwarding" => "1",
1123
		"net.inet6.ip6.forwarding" => "1"
1124
	));
1125

    
1126
	return;
1127
}
1128

    
1129
function system_webgui_create_certificate() {
1130
	global $g, $cert_strict_values;
1131

    
1132
	init_config_arr(array('ca'));
1133
	$a_ca = config_get_path('ca');
1134
	init_config_arr(array('cert'));
1135
	$a_cert = config_get_path('cert');
1136
	log_error(gettext("Creating SSL/TLS Certificate for this host"));
1137

    
1138
	$cert = array();
1139
	$cert['refid'] = uniqid();
1140
	$cert['descr'] = sprintf(gettext("webConfigurator default (%s)"), $cert['refid']);
1141
	$hostname = config_get_path('system/hostname');
1142
	$cert_hostname = "{$hostname}-{$cert['refid']}";
1143

    
1144
	$dn = array(
1145
		'organizationName' => "{$g['product_label']} webConfigurator Self-Signed Certificate",
1146
		'commonName' => $cert_hostname,
1147
		'subjectAltName' => "DNS:{$cert_hostname}");
1148
	$old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warnings directly to a page screwing menu tab */
1149
	if (!cert_create($cert, null, 2048, $cert_strict_values['max_server_cert_lifetime'], $dn, "self-signed", "sha256")) {
1150
		while ($ssl_err = openssl_error_string()) {
1151
			log_error(sprintf(gettext("Error creating WebGUI Certificate: openssl library returns: %s"), $ssl_err));
1152
		}
1153
		error_reporting($old_err_level);
1154
		return null;
1155
	}
1156
	error_reporting($old_err_level);
1157

    
1158
	$a_cert[] = $cert;
1159
	config_set_path('cert', $a_cert);
1160
	config_set_path('system/webgui/ssl-certref', $cert['refid']);
1161
	write_config(sprintf(gettext("Generated new self-signed SSL/TLS certificate for HTTPS (%s)"), $cert['refid']));
1162
	return $cert;
1163
}
1164

    
1165
function system_webgui_start() {
1166
	global $g;
1167

    
1168
	if (platform_booting()) {
1169
		echo gettext("Starting webConfigurator...");
1170
	}
1171

    
1172
	chdir(g_get('www_path'));
1173

    
1174
	/* defaults */
1175
	$portarg = config_get_path('system/webgui/port', '80');
1176
	$crt = "";
1177
	$key = "";
1178
	$ca = "";
1179

    
1180
	if (config_get_path('system/webgui/protocol') == "https") {
1181
		// Ensure that we have a webConfigurator CERT
1182
		$cert =& lookup_cert(config_get_path('system/webgui/ssl-certref'));
1183
		if (!is_array($cert) || !$cert['crt'] || !$cert['prv']) {
1184
			$cert = system_webgui_create_certificate();
1185
		}
1186
		$crt = base64_decode($cert['crt']);
1187
		$key = base64_decode($cert['prv']);
1188

    
1189
		$portarg = config_get_path('system/webgui/port', '443');
1190
		$ca = ca_chain($cert);
1191
		$hsts = !config_path_enabled('system/webgui', 'disablehsts');
1192
	}
1193

    
1194
	/* generate nginx configuration */
1195
	system_generate_nginx_config("{$g['varetc_path']}/nginx-webConfigurator.conf",
1196
		$crt, $key, $ca, "nginx-webConfigurator.pid", $portarg, "/usr/local/www/",
1197
		"cert.crt", "cert.key", false, $hsts);
1198

    
1199
	/* kill any running nginx */
1200
	killbypid("{$g['varrun_path']}/nginx-webConfigurator.pid");
1201

    
1202
	sleep(1);
1203

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

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

    
1209
	if (platform_booting()) {
1210
		if ($res == 0) {
1211
			echo gettext("done.") . "\n";
1212
		} else {
1213
			echo gettext("failed!") . "\n";
1214
		}
1215
	}
1216

    
1217
	return $res;
1218
}
1219

    
1220
/****f* system.inc/get_dns_nameservers
1221
 * NAME
1222
 *   get_dns_nameservers - Get system DNS servers
1223
 * INPUTS
1224
 *   $add_v6_brackets: (boolean, false)
1225
 *                     Add brackets around IPv6 DNS servers, as expected by some
1226
 *                     daemons such as nginx.
1227
 *   $hostns         : (boolean, true)
1228
 *                     true : Return only DNS servers used by the firewall
1229
 *                            itself as upstream forwarding servers
1230
 *                     false: Return all DNS servers from the configuration and
1231
 *                            overrides (if allowed).
1232
 * RESULT
1233
 *   $dns_nameservers - An array of the requested DNS servers
1234
 ******/
1235
function get_dns_nameservers($add_v6_brackets = false, $hostns=true) {
1236
	$dns_nameservers = array();
1237

    
1238
	if (config_path_enabled('system', 'developerspew')) {
1239
		$mt = microtime();
1240
		echo "get_dns_nameservers() being called $mt\n";
1241
	}
1242

    
1243
	if ((((config_path_enabled('dnsmasq')) &&
1244
		  (config_get_path('dnsmasq/port', '53') == '53') &&
1245
		  in_array("lo0", explode(",", config_get_path('dnsmasq/interface', 'lo0'))))) ||
1246
	    (config_path_enabled('unbound') &&
1247
		 (config_get_path('unbound/port', '53') == '53') &&
1248
		 (in_array("lo0", explode(",", config_get_path('unbound/active_interface', 'lo0'))) ||
1249
		  in_array("all", explode(",", config_get_path('unbound/active_interface', 'all')), true))) &&
1250
	    (config_get_path('system/dnslocalhost') != 'remote')) {
1251
		$dns_nameservers[] = "127.0.0.1";
1252
	}
1253

    
1254
	if ($hostns || (config_get_path('system/dnslocalhost') != 'local')) {
1255
		if (config_path_enabled('system', 'dnsallowoverride')) {
1256
			/* get dynamically assigned DNS servers (if any) */
1257
			foreach (array_unique(get_dynamic_nameservers()) as $nameserver) {
1258
				if ($nameserver) {
1259
					if ($add_v6_brackets && is_ipaddrv6($nameserver)) {
1260
						$nameserver = "[{$nameserver}]";
1261
					}
1262
					$dns_nameservers[] = $nameserver;
1263
				}
1264
			}
1265
		}
1266
		foreach (config_get_path('system/dnsserver', []) as $sys_dnsserver) {
1267
			if ($sys_dnsserver && (!in_array($sys_dnsserver, $dns_nameservers))) {
1268
				if ($add_v6_brackets && is_ipaddrv6($sys_dnsserver)) {
1269
					$sys_dnsserver = "[{$sys_dnsserver}]";
1270
				}
1271
				$dns_nameservers[] = $sys_dnsserver;
1272
			}
1273
		}
1274
	}
1275
	return array_unique($dns_nameservers);
1276
}
1277

    
1278
function system_generate_nginx_config($filename,
1279
	$cert,
1280
	$key,
1281
	$ca,
1282
	$pid_file,
1283
	$port = 80,
1284
	$document_root = "/usr/local/www/",
1285
	$cert_location = "cert.crt",
1286
	$key_location = "cert.key",
1287
	$captive_portal = false,
1288
	$hsts = true) {
1289

    
1290
	global $g;
1291

    
1292
	if (config_path_enabled('system', 'developerspew')) {
1293
		$mt = microtime();
1294
		echo "system_generate_nginx_config() being called $mt\n";
1295
	}
1296

    
1297
	if ($captive_portal !== false) {
1298
		$cp_interfaces = explode(",", config_get_path("captiveportal/{$captive_portal}/interface"));
1299
		$cp_hostcheck = "";
1300
		foreach ($cp_interfaces as $cpint) {
1301
			$cpint_ip = get_interface_ip($cpint);
1302
			if (is_ipaddr($cpint_ip)) {
1303
				$cp_hostcheck .= "\t\tif (\$http_host ~* $cpint_ip) {\n";
1304
				$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1305
				$cp_hostcheck .= "\t\t}\n";
1306
			}
1307
		}
1308
		$httpsname = config_get_path("captiveportal/{$captive_portal}/httpsname");
1309
		if (!empty($httpsname) &&
1310
		    is_domain($httpsname)) {
1311
			$cp_hostcheck .= "\t\tif (\$http_host ~* {$httpsname}) {\n";
1312
			$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1313
			$cp_hostcheck .= "\t\t}\n";
1314
		}
1315
		$cp_rewrite = "\t\tif (\$cp_redirect = '') {\n";
1316
		$cp_rewrite .= "\t\t\trewrite	^ /index.php?zone=$captive_portal&redirurl=\$request_uri break;\n";
1317
		$cp_rewrite .= "\t\t}\n";
1318

    
1319
		$maxprocperip = config_get_path("captiveportal/{$captive_portal}/maxprocperip");
1320
		if (empty($maxprocperip)) {
1321
			$maxprocperip = 10;
1322
		}
1323
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1324
	}
1325

    
1326
	if (empty($port)) {
1327
		$nginx_port = "80";
1328
	} else {
1329
		$nginx_port = $port;
1330
	}
1331

    
1332
	$memory = get_memory();
1333
	$realmem = $memory[1];
1334

    
1335
	// Determine web GUI process settings and take into account low memory systems
1336
	if ($realmem < 255) {
1337
		$max_procs = 1;
1338
	} else {
1339
		$max_procs = config_get_path('system/webgui/max_procs', 2);
1340
	}
1341

    
1342
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM
1343
	if ($captive_portal !== false) {
1344
		if ($realmem > 135 and $realmem < 256) {
1345
			$max_procs += 1; // 2 worker processes
1346
		} else if ($realmem > 255 and $realmem < 513) {
1347
			$max_procs += 2; // 3 worker processes
1348
		} else if ($realmem > 512) {
1349
			$max_procs += 4; // 6 worker processes
1350
		}
1351
	}
1352

    
1353
	$nginx_config = <<<EOD
1354
#
1355
# nginx configuration file
1356

    
1357
pid {$g['varrun_path']}/{$pid_file};
1358

    
1359
user  root wheel;
1360
worker_processes  {$max_procs};
1361

    
1362
EOD;
1363

    
1364
	/* Disable file logging */
1365
	$nginx_config .= "error_log /dev/null;\n";
1366
	if (!config_path_enabled('syslog','nolognginx')) {
1367
		/* Send nginx error log to syslog */
1368
		$nginx_config .= "error_log  syslog:server=unix:/var/run/log,facility=local5;\n";
1369
	}
1370

    
1371
	$nginx_config .= <<<EOD
1372

    
1373
events {
1374
    worker_connections  1024;
1375
}
1376

    
1377
http {
1378
	include       /usr/local/etc/nginx/mime.types;
1379
	default_type  application/octet-stream;
1380
	add_header X-Frame-Options SAMEORIGIN;
1381
	server_tokens off;
1382

    
1383
	sendfile        on;
1384

    
1385
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1386

    
1387
EOD;
1388

    
1389
	if ($captive_portal !== false) {
1390
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1391
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1392
	} else {
1393
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1394
	}
1395

    
1396
	if ($cert <> "" and $key <> "") {
1397
		$nginx_config .= "\n";
1398
		$nginx_config .= "\tserver {\n";
1399
		$nginx_config .= "\t\tlisten {$nginx_port} ssl http2;\n";
1400
		$nginx_config .= "\t\tlisten [::]:{$nginx_port} ssl http2;\n";
1401
		$nginx_config .= "\n";
1402
		$nginx_config .= "\t\tssl_certificate         {$g['varetc_path']}/{$cert_location};\n";
1403
		$nginx_config .= "\t\tssl_certificate_key     {$g['varetc_path']}/{$key_location};\n";
1404
		$nginx_config .= "\t\tssl_session_timeout     10m;\n";
1405
		$nginx_config .= "\t\tkeepalive_timeout       70;\n";
1406
		$nginx_config .= "\t\tssl_session_cache       shared:SSL:10m;\n";
1407
		if ($captive_portal !== false) {
1408
			// leave TLSv1.1 for CP for now for compatibility
1409
			$nginx_config .= "\t\tssl_protocols   TLSv1.1 TLSv1.2 TLSv1.3;\n";
1410
		} else {
1411
			$nginx_config .= "\t\tssl_protocols   TLSv1.2 TLSv1.3;\n";
1412
		}
1413
		$nginx_config .= "\t\tssl_ciphers \"EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305\";\n";
1414
		$nginx_config .= "\t\tssl_prefer_server_ciphers       on;\n";
1415
		if ($captive_portal === false && $hsts !== false) {
1416
			$nginx_config .= "\t\tadd_header Strict-Transport-Security \"max-age=31536000\";\n";
1417
		}
1418
		$nginx_config .= "\t\tadd_header X-Content-Type-Options nosniff;\n";
1419
		$nginx_config .= "\t\tssl_session_tickets off;\n";
1420
		$nginx_config .= "\t\tssl_dhparam /etc/dh-parameters.4096;\n";
1421
		$cert_temp = lookup_cert(config_get_path('system/webgui/ssl-certref'));
1422
		if ((config_get_path('system/webgui/ocsp-staple') == true) or
1423
		    (cert_get_ocspstaple($cert_temp['crt']) == true)) {
1424
			$nginx_config .= "\t\tssl_stapling on;\n";
1425
			$nginx_config .= "\t\tssl_stapling_verify on;\n";
1426
			$nginx_config .= "\t\tresolver " . implode(" ", get_dns_nameservers(true)) . " valid=300s;\n";
1427
			$nginx_config .= "\t\tresolver_timeout 5s;\n";
1428
		}
1429
	} else {
1430
		$nginx_config .= "\n";
1431
		$nginx_config .= "\tserver {\n";
1432
		$nginx_config .= "\t\tlisten {$nginx_port};\n";
1433
		$nginx_config .= "\t\tlisten [::]:{$nginx_port};\n";
1434
	}
1435

    
1436
	$nginx_config .= <<<EOD
1437

    
1438
		client_max_body_size 200m;
1439

    
1440
		gzip on;
1441
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
1442

    
1443

    
1444
EOD;
1445

    
1446
	if ($captive_portal !== false) {
1447
		$nginx_config .= <<<EOD
1448
$captive_portal_maxprocperip
1449
$cp_hostcheck
1450
$cp_rewrite
1451
		log_not_found off;
1452

    
1453
EOD;
1454

    
1455
	}
1456

    
1457
	$nginx_config .= <<<EOD
1458
		root "{$document_root}";
1459
		location / {
1460
			index  index.php index.html index.htm;
1461
		}
1462
		location ~ \.inc$ {
1463
			deny all;
1464
			return 403;
1465
		}
1466
		location ~ \.php$ {
1467
			try_files \$uri =404; #  This line closes a potential security hole
1468
			# ensuring users can't execute uploaded files
1469
			# see: https://forum.nginx.org/read.php?2,88845,page=3
1470
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1471
			fastcgi_index  index.php;
1472
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1473
			# Fix httpoxy - https://httpoxy.org/#fix-now
1474
			fastcgi_param  HTTP_PROXY  "";
1475
			fastcgi_read_timeout 180;
1476
			include        /usr/local/etc/nginx/fastcgi_params;
1477
		}
1478
		location ~ (^/status$) {
1479
			allow 127.0.0.1;
1480
			deny all;
1481
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1482
			fastcgi_index  index.php;
1483
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1484
			# Fix httpoxy - https://httpoxy.org/#fix-now
1485
			fastcgi_param  HTTP_PROXY  "";
1486
			fastcgi_read_timeout 360;
1487
			include        /usr/local/etc/nginx/fastcgi_params;
1488
		}
1489
	}
1490

    
1491
EOD;
1492

    
1493
	$cert = str_replace("\r", "", $cert);
1494
	$key = str_replace("\r", "", $key);
1495

    
1496
	$cert = str_replace("\n\n", "\n", $cert);
1497
	$key = str_replace("\n\n", "\n", $key);
1498

    
1499
	if ($cert <> "" and $key <> "") {
1500
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1501
		if (!$fd) {
1502
			printf(gettext("Error: cannot open certificate file in system_webgui_start().%s"), "\n");
1503
			return 1;
1504
		}
1505
		chmod("{$g['varetc_path']}/{$cert_location}", 0644);
1506
		if ($ca <> "") {
1507
			$cert_chain = $cert . "\n" . $ca;
1508
		} else {
1509
			$cert_chain = $cert;
1510
		}
1511
		fwrite($fd, $cert_chain);
1512
		fclose($fd);
1513
		$fd = fopen("{$g['varetc_path']}/{$key_location}", "w");
1514
		if (!$fd) {
1515
			printf(gettext("Error: cannot open certificate key file in system_webgui_start().%s"), "\n");
1516
			return 1;
1517
		}
1518
		chmod("{$g['varetc_path']}/{$key_location}", 0600);
1519
		fwrite($fd, $key);
1520
		fclose($fd);
1521
	}
1522

    
1523
	// Add HTTP to HTTPS redirect
1524
	if ($captive_portal === false && config_get_path('system/webgui/protocol') == "https" && !(config_path_enabled('system/webgui', 'disablehttpredirect') != null)) {
1525
		if ($nginx_port != "443") {
1526
			$redirectport = ":{$nginx_port}";
1527
		}
1528
		$nginx_config .= <<<EOD
1529
	server {
1530
		listen 80;
1531
		listen [::]:80;
1532
		return 301 https://\$http_host$redirectport\$request_uri;
1533
	}
1534

    
1535
EOD;
1536
	}
1537

    
1538
	$nginx_config .= "}\n";
1539

    
1540
	$fd = fopen("{$filename}", "w");
1541
	if (!$fd) {
1542
		printf(gettext('Error: cannot open %1$s in system_generate_nginx_config().%2$s'), $filename, "\n");
1543
		return 1;
1544
	}
1545
	fwrite($fd, $nginx_config);
1546
	fclose($fd);
1547

    
1548
	/* nginx will fail to start if this directory does not exist. */
1549
	safe_mkdir("/var/tmp/nginx/");
1550

    
1551
	return 0;
1552

    
1553
}
1554

    
1555
function system_get_timezone_list() {
1556
	global $g;
1557

    
1558
	$file_list = array_merge(
1559
		glob("/usr/share/zoneinfo/[A-Z]*"),
1560
		glob("/usr/share/zoneinfo/*/*"),
1561
		glob("/usr/share/zoneinfo/*/*/*")
1562
	);
1563

    
1564
	if (empty($file_list)) {
1565
		$file_list[] = g_get('default_timezone');
1566
	} else {
1567
		/* Remove directories from list */
1568
		$file_list = array_filter($file_list, function($v) {
1569
			return !is_dir($v);
1570
		});
1571
	}
1572

    
1573
	/* Remove directory prefix */
1574
	$file_list = str_replace('/usr/share/zoneinfo/', '', $file_list);
1575

    
1576
	sort($file_list);
1577

    
1578
	return $file_list;
1579
}
1580

    
1581
function system_timezone_configure() {
1582
	global $g;
1583
	if (config_path_enabled('system', 'developerspew')) {
1584
		$mt = microtime();
1585
		echo "system_timezone_configure() being called $mt\n";
1586
	}
1587

    
1588
	$syscfg = config_get_path('system');
1589

    
1590
	if (platform_booting()) {
1591
		echo gettext("Setting timezone...");
1592
	}
1593

    
1594
	/* extract appropriate timezone file */
1595
	$timezone = (isset($syscfg['timezone']) ? $syscfg['timezone'] : g_get('default_timezone'));
1596
	/* DO NOT remove \n otherwise tzsetup will fail */
1597
	@file_put_contents("/var/db/zoneinfo", $timezone . "\n");
1598
	mwexec("/usr/sbin/tzsetup -r");
1599

    
1600
	if (platform_booting()) {
1601
		echo gettext("done.") . "\n";
1602
	}
1603
}
1604

    
1605
function check_gps_speed($device) {
1606
	usleep(1000);
1607
	// Set timeout to 5s
1608
	$timeout=microtime(true)+5;
1609
	if ($fp = fopen($device, 'r')) {
1610
		stream_set_blocking($fp, 0);
1611
		stream_set_timeout($fp, 5);
1612
		$contents = "";
1613
		$cnt = 0;
1614
		$buffersize = 256;
1615
		do {
1616
			$c = fread($fp, $buffersize - $cnt);
1617

    
1618
			// Wait for data to arive
1619
			if (($c === false) || (strlen($c) == 0)) {
1620
				usleep(500);
1621
				continue;
1622
			}
1623

    
1624
			$contents.=$c;
1625
			$cnt = $cnt + strlen($c);
1626
		} while (($cnt < $buffersize) && (microtime(true) < $timeout));
1627
		fclose($fp);
1628

    
1629
		$nmeasentences = ['RMC', 'GGA', 'GLL', 'ZDA', 'ZDG', 'PGRMF'];
1630
		foreach ($nmeasentences as $sentence) {
1631
			if (strpos($contents, $sentence) > 0) {
1632
				return true;
1633
			}
1634
		}
1635
		if (strpos($contents, '0') > 0) {
1636
			$filters = ['`', '?', '/', '~'];
1637
			foreach ($filters as $filter) {
1638
				if (strpos($contents, $filter) !== false) {
1639
					return false;
1640
				}
1641
			}
1642
			return true;
1643
		}
1644
	}
1645
	return false;
1646
}
1647

    
1648
/* Generate list of possible NTP poll values
1649
 * https://redmine.pfsense.org/issues/9439 */
1650
global $ntp_poll_min_value, $ntp_poll_max_value;
1651
global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
1652
global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
1653
global $ntp_poll_min_default, $ntp_poll_max_default;
1654
global $ntp_auth_halgos, $ntp_server_types;
1655
$ntp_poll_min_value = 3;
1656
$ntp_poll_max_value = 17;
1657
$ntp_poll_min_default_gps = 4;
1658
$ntp_poll_max_default_gps = 4;
1659
$ntp_poll_min_default_pps = 4;
1660
$ntp_poll_max_default_pps = 4;
1661
$ntp_poll_min_default = 'omit';
1662
$ntp_poll_max_default = 9;
1663
$ntp_auth_halgos = array(
1664
	'md5' => 'MD5',
1665
	'sha1' => 'SHA1',
1666
	'sha256' => 'SHA256'
1667
);
1668
$ntp_server_types = array(
1669
	'server' => 'Server',
1670
	'pool' => 'Pool',
1671
	'peer' => 'Peer'
1672
);
1673

    
1674
function system_ntp_poll_values() {
1675
	global $ntp_poll_min_value, $ntp_poll_max_value;
1676
	$poll_values = array("" => gettext('Default'));
1677

    
1678
	for ($i = $ntp_poll_min_value; $i <= $ntp_poll_max_value; $i++) {
1679
		$sec = 2 ** $i;
1680
		$poll_values[$i] = $i . ': ' . number_format($sec) . ' ' . gettext('seconds') .
1681
					' (' . convert_seconds_to_dhms($sec) . ')';
1682
	}
1683

    
1684
	$poll_values['omit'] = gettext('Omit (Do not set)');
1685
	return $poll_values;
1686
}
1687

    
1688
function system_ntp_fixup_poll_value($type, $configvalue, $default) {
1689
	$pollstring = "";
1690

    
1691
	if (empty($configvalue)) {
1692
		$configvalue = $default;
1693
	}
1694

    
1695
	if ($configvalue != 'omit') {
1696
		$pollstring = " {$type} {$configvalue}";
1697
	}
1698

    
1699
	return $pollstring;
1700
}
1701

    
1702
function system_ntp_setup_gps($serialport) {
1703
	if (config_get_path('ntpd/enable') == 'disabled') {
1704
		return false;
1705
	}
1706

    
1707
	init_config_arr(array('ntpd', 'gps'));
1708
	$serialports = get_serial_ports(true);
1709

    
1710
	if (!array_key_exists($serialport, $serialports)) {
1711
		return false;
1712
	}
1713

    
1714
	$gps_device = '/dev/gps0';
1715
	$serialport = '/dev/'.basename($serialport);
1716

    
1717
	if (!file_exists($serialport)) {
1718
		return false;
1719
	}
1720

    
1721
	// Create symlink that ntpd requires
1722
	unlink_if_exists($gps_device);
1723
	@symlink($serialport, $gps_device);
1724

    
1725
	$speeds = array(
1726
		0 => '4800',
1727
		16 => '9600',
1728
		32 => '19200',
1729
		48 => '38400',
1730
		64 => '57600',
1731
		80 => '115200'
1732
	);
1733
	// $gpsbaud defaults to '4800' if ntpd/gps/speed is unset or does not exist in $speeds
1734
	$gpsbaud = array_get_path($speeds, config_get_path('ntpd/gps/speed', 0), '4800');
1735

    
1736
	system_ntp_setup_rawspeed($serialport, $gpsbaud);
1737

    
1738
	$gpsspeed = config_get_path('ntpd/gps/speed');
1739
	$autospeed = ($gpsspeed == 'autoalways' || $gpsspeed == 'autoset');
1740
	if ($autospeed || (config_get_path('ntpd/gps/autobaudinit') && !check_gps_speed($gps_device))) {
1741
		$found = false;
1742
		foreach ($speeds as $baud) {
1743
			system_ntp_setup_rawspeed($serialport, $baud);
1744
			if ($found = check_gps_speed($gps_device)) {
1745
				if ($autospeed) {
1746
					$saveconfig = (config_get_path('ntpd/gps/speed') == 'autoset');
1747
					config_set_path('ntpd/gps/speed', array_search($baud, $speeds));
1748
					$gpsbaud = $baud;
1749
					if ($saveconfig) {
1750
						write_config(sprintf(gettext('Autoset GPS baud rate to %s'), $baud));
1751
					}
1752
				}
1753
				break;
1754
			}
1755
		}
1756
		if ($found === false) {
1757
			log_error(gettext("Could not find correct GPS baud rate."));
1758
			return false;
1759
		}
1760
	}
1761

    
1762
	/* Send the following to the GPS port to initialize the GPS */
1763
	if (!empty(config_get_path('ntpd/gps/type'))) {
1764
		$gps_init = base64_decode(config_get_path('ntpd/gps/initcmd'));
1765
	} else {
1766
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1767
	}
1768

    
1769
	/* XXX: Why not file_put_contents to the device */
1770
	@file_put_contents('/tmp/gps.init', $gps_init);
1771
	mwexec("/bin/cat /tmp/gps.init > {$serialport}");
1772

    
1773
	if ($found && config_get_path('ntpd/gps/autobaudinit')) {
1774
		system_ntp_setup_rawspeed($serialport, $gpsbaud);
1775
	}
1776

    
1777
	/* Remove old /etc/remote entry if it exists */
1778
	if (mwexec("/usr/bin/grep -c '^gps0' /etc/remote") == 0) {
1779
		mwexec("/usr/bin/sed -i '' -n '/gps0/!p' /etc/remote");
1780
	}
1781

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

    
1787
	return true;
1788
}
1789

    
1790
// Configure the serial port for raw IO and set the speed
1791
function system_ntp_setup_rawspeed($serialport, $baud) {
1792
	mwexec("/bin/stty -f " .  escapeshellarg($serialport) . " raw speed " . escapeshellarg($baud));
1793
	mwexec("/bin/stty -f " .  escapeshellarg($serialport) . ".init raw speed " . escapeshellarg($baud));
1794
}
1795

    
1796
function system_ntp_setup_pps($serialport) {
1797
	$serialports = get_serial_ports(true);
1798

    
1799
	if (!array_key_exists($serialport, $serialports)) {
1800
		return false;
1801
	}
1802

    
1803
	$pps_device = '/dev/pps0';
1804
	$serialport = '/dev/'.basename($serialport);
1805

    
1806
	if (!file_exists($serialport)) {
1807
		return false;
1808
	}
1809
	// If ntpd is disabled, just return
1810
	if (config_get_path('ntpd/enable') == 'disabled') {
1811
		return false;
1812
	}
1813

    
1814
	// Create symlink that ntpd requires
1815
	unlink_if_exists($pps_device);
1816
	@symlink($serialport, $pps_device);
1817

    
1818

    
1819
	return true;
1820
}
1821

    
1822
function system_ntp_configure() {
1823
	global $g;
1824
	global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
1825
	global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
1826
	global $ntp_poll_min_default, $ntp_poll_max_default;
1827

    
1828
	$driftfile = "/var/db/ntpd.drift";
1829
	$statsdir = "/var/log/ntp";
1830
	$gps_device = '/dev/gps0';
1831

    
1832
	safe_mkdir($statsdir);
1833

    
1834
	init_config_arr(array('ntpd'));
1835

    
1836
	// ntpd is disabled, just stop it and return
1837
	if (config_get_path('ntpd/enable') == 'disabled') {
1838
		while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1839
			killbypid("{$g['varrun_path']}/ntpd.pid");
1840
		}
1841
		@unlink("{$g['varrun_path']}/ntpd.pid");
1842
		@unlink("{$g['varetc_path']}/ntpd.conf");
1843
		@unlink("{$g['varetc_path']}/ntp.keys");
1844
		log_error("NTPD is disabled.");
1845
		return;
1846
	}
1847

    
1848
	if (platform_booting()) {
1849
		echo gettext("Starting NTP Server...");
1850
	}
1851

    
1852
	/* if ntpd is running, kill it */
1853
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1854
		killbypid("{$g['varrun_path']}/ntpd.pid");
1855
	}
1856
	@unlink("{$g['varrun_path']}/ntpd.pid");
1857

    
1858
	/* set NTP server authentication key */
1859
	if (config_get_path('ntpd/serverauth') == 'yes') {
1860
		$ntpkeyscfg = "1 " . strtoupper(config_get_path('ntpd/serverauthalgo')) . " " . base64_decode(config_get_path('ntpd/serverauthkey')) . "\n";
1861
		if (!@file_put_contents("{$g['varetc_path']}/ntp.keys", $ntpkeyscfg)) {
1862
			log_error(sprintf(gettext("Could not open %s/ntp.keys for writing"), g_get('varetc_path')));
1863
			return;
1864
		}
1865
	} else {
1866
		unlink_if_exists("{$g['varetc_path']}/ntp.keys");
1867
	}
1868

    
1869
	$ntpcfg = "# \n";
1870
	$ntpcfg .= "# pfSense ntp configuration file \n";
1871
	$ntpcfg .= "# \n\n";
1872
	$ntpcfg .= "tinker panic 0 \n\n";
1873

    
1874
	if (config_get_path('ntpd/serverauth') == 'yes') {
1875
		$ntpcfg .= "# Authentication settings \n";
1876
		$ntpcfg .= "keys /var/etc/ntp.keys \n";
1877
		$ntpcfg .= "trustedkey 1 \n";
1878
		$ntpcfg .= "requestkey 1 \n";
1879
		$ntpcfg .= "controlkey 1 \n";
1880
		$ntpcfg .= "\n";
1881
	}
1882

    
1883
	/* Add Orphan mode */
1884
	$ntpcfg .= "# Orphan mode stratum and Maximum candidate NTP peers\n";
1885
	$ntpcfg .= 'tos orphan ';
1886
	if (!empty(config_get_path('ntpd/orphan'))) {
1887
		$ntpcfg .= config_get_path('ntpd/orphan');
1888
	} else {
1889
		$ntpcfg .= '12';
1890
	}
1891
	/* Add Maximum candidate NTP peers */
1892
	$ntpcfg .= ' maxclock ';
1893
	if (!empty(config_get_path('ntpd/ntpmaxpeers'))) {
1894
		$ntpcfg .= config_get_path('ntpd/ntpmaxpeers');
1895
	} else {
1896
		$ntpcfg .= '5';
1897
	}
1898
	$ntpcfg .= "\n";
1899

    
1900
	/* Add PPS configuration */
1901
	if (!empty(config_get_path('ntpd/pps/port')) &&
1902
	    file_exists('/dev/'.config_get_path('ntpd/pps/port')) &&
1903
	    system_ntp_setup_pps(config_get_path('ntpd/pps/port'))) {
1904
		$ntpcfg .= "\n";
1905
		$ntpcfg .= "# PPS Setup\n";
1906
		$ntpcfg .= 'server 127.127.22.0';
1907
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', config_get_path('ntpd/pps/ppsminpoll'), $ntp_poll_min_default_pps);
1908
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', config_get_path('ntpd/pps/ppsmaxpoll'), $ntp_poll_max_default_pps);
1909
		if (empty(config_get_path('ntpd/pps/prefer'))) { /*note: this one works backwards */
1910
			$ntpcfg .= ' prefer';
1911
		}
1912
		if (!empty(config_get_path('ntpd/pps/noselect'))) {
1913
			$ntpcfg .= ' noselect ';
1914
		}
1915
		$ntpcfg .= "\n";
1916
		$ntpcfg .= 'fudge 127.127.22.0';
1917
		if (!empty(config_get_path('ntpd/pps/fudge1'))) {
1918
			$ntpcfg .= ' time1 ';
1919
			$ntpcfg .= config_get_path('ntpd/pps/fudge1');
1920
		}
1921
		if (!empty(config_get_path('ntpd/pps/flag2'))) {
1922
			$ntpcfg .= ' flag2 1';
1923
		}
1924
		if (!empty(config_get_path('ntpd/pps/flag3'))) {
1925
			$ntpcfg .= ' flag3 1';
1926
		} else {
1927
			$ntpcfg .= ' flag3 0';
1928
		}
1929
		if (!empty(config_get_path('ntpd/pps/flag4'))) {
1930
			$ntpcfg .= ' flag4 1';
1931
		}
1932
		if (!empty(config_get_path('ntpd/pps/refid'))) {
1933
			$ntpcfg .= ' refid ';
1934
			$ntpcfg .= config_get_path('ntpd/pps/refid');
1935
		}
1936
		$ntpcfg .= "\n";
1937
	}
1938
	/* End PPS configuration */
1939

    
1940
	/* Add GPS configuration */
1941
	if (!empty(config_get_path('ntpd/gps/port')) &&
1942
	    system_ntp_setup_gps(config_get_path('ntpd/gps/port'))) {
1943
		$ntpcfg .= "\n";
1944
		$ntpcfg .= "# GPS Setup\n";
1945
		$ntpcfg .= 'server 127.127.20.0 mode ';
1946
		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'))) {
1947
			if (!empty(config_get_path('ntpd/gps/nmea'))) {
1948
				$ntpmode = (int) config_get_path('ntpd/gps/nmea');
1949
			}
1950
			if (!empty(config_get_path('ntpd/gps/speed'))) {
1951
				$ntpmode += (int) config_get_path('ntpd/gps/speed');
1952
			}
1953
			if (!empty(config_get_path('ntpd/gps/subsec'))) {
1954
				$ntpmode += 128;
1955
			}
1956
			if (!empty(config_get_path('ntpd/gps/processpgrmf'))) {
1957
				$ntpmode += 256;
1958
			}
1959
			$ntpcfg .= (string) $ntpmode;
1960
		} else {
1961
			$ntpcfg .= '0';
1962
		}
1963
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', config_get_path('ntpd/gps/gpsminpoll'), $ntp_poll_min_default_gps);
1964
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', config_get_path('ntpd/gps/gpsmaxpoll'), $ntp_poll_max_default_gps);
1965

    
1966
		if (empty(config_get_path('ntpd/gps/prefer'))) { /*note: this one works backwards */
1967
			$ntpcfg .= ' prefer';
1968
		}
1969
		if (!empty(config_get_path('ntpd/gps/noselect'))) {
1970
			$ntpcfg .= ' noselect ';
1971
		}
1972
		$ntpcfg .= "\n";
1973
		$ntpcfg .= 'fudge 127.127.20.0';
1974
		if (!empty(config_get_path('ntpd/gps/fudge1'))) {
1975
			$ntpcfg .= ' time1 ';
1976
			$ntpcfg .= config_get_path('ntpd/gps/fudge1');
1977
		}
1978
		if (!empty(config_get_path('ntpd/gps/fudge2'))) {
1979
			$ntpcfg .= ' time2 ';
1980
			$ntpcfg .= config_get_path('ntpd/gps/fudge2');
1981
		}
1982
		if (!empty(config_get_path('ntpd/gps/flag1'))) {
1983
			$ntpcfg .= ' flag1 1';
1984
		} else {
1985
			$ntpcfg .= ' flag1 0';
1986
		}
1987
		if (!empty(config_get_path('ntpd/gps/flag2'))) {
1988
			$ntpcfg .= ' flag2 1';
1989
		}
1990
		if (!empty(config_get_path('ntpd/gps/flag3'))) {
1991
			$ntpcfg .= ' flag3 1';
1992
		} else {
1993
			$ntpcfg .= ' flag3 0';
1994
		}
1995
		if (!empty(config_get_path('ntpd/gps/flag4'))) {
1996
			$ntpcfg .= ' flag4 1';
1997
		}
1998
		if (!empty(config_get_path('ntpd/gps/refid'))) {
1999
			$ntpcfg .= ' refid ';
2000
			$ntpcfg .= config_get_path('ntpd/gps/refid');
2001
		}
2002
		if (!empty(config_get_path('ntpd/gps/stratum'))) {
2003
			$ntpcfg .= ' stratum ';
2004
			$ntpcfg .= config_get_path('ntpd/gps/stratum');
2005
		}
2006
		$ntpcfg .= "\n";
2007
	} elseif (system_ntp_setup_gps(config_get_path('ntpd/gpsport'))) {
2008
		/* This handles a 2.1 and earlier config */
2009
		$ntpcfg .= "# GPS Setup\n";
2010
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
2011
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
2012
		// Fall back to local clock if GPS is out of sync?
2013
		$ntpcfg .= "server 127.127.1.0\n";
2014
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
2015
	}
2016
	/* End GPS configuration */
2017
	$auto_pool_suffix = "pool.ntp.org";
2018
	$have_pools = false;
2019
	$ntpcfg .= "\n\n# Upstream Servers\n";
2020
	/* foreach through ntp servers and write out to ntpd.conf */
2021
	foreach (explode(' ', config_get_path('system/timeservers')) as $ts) {
2022
		if ((substr_compare($ts, $auto_pool_suffix, strlen($ts) - strlen($auto_pool_suffix), strlen($auto_pool_suffix)) === 0)
2023
		    || substr_count(config_get_path('ntpd/ispool'), $ts)) {
2024
			$ntpcfg .= 'pool ';
2025
			$have_pools = true;
2026
		} else {
2027
			if (substr_count(config_get_path('ntpd/ispeer'), $ts)) {
2028
				$ntpcfg .= 'peer ';
2029
			} else {
2030
				$ntpcfg .= 'server ';
2031
			}
2032
			if (config_get_path('ntpd/dnsresolv') == 'inet') {
2033
				$ntpcfg .= '-4 ';
2034
			} elseif (config_get_path('ntpd/dnsresolv') == 'inet6') {
2035
				$ntpcfg .= '-6 ';
2036
			}
2037
		}
2038

    
2039
		$ntpcfg .= "{$ts}";
2040
		if (!substr_count(config_get_path('ntpd/ispeer'), $ts)) {
2041
			$ntpcfg .= " iburst";
2042
		}
2043

    
2044
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', config_get_path('ntpd/ntpminpoll'), $ntp_poll_min_default);
2045
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', config_get_path('ntpd/ntpmaxpoll'), $ntp_poll_max_default);
2046

    
2047
		if (substr_count(config_get_path('ntpd/prefer'), $ts)) {
2048
			$ntpcfg .= ' prefer';
2049
		}
2050
		if (substr_count(config_get_path('ntpd/noselect'), $ts)) {
2051
			$ntpcfg .= ' noselect';
2052
		}
2053
		$ntpcfg .= "\n";
2054
	}
2055
	unset($ts);
2056

    
2057
	$ntpcfg .= "\n\n";
2058
	if (!empty(config_get_path('ntpd/clockstats')) || !empty(config_get_path('ntpd/loopstats')) || !empty(config_get_path('ntpd/peerstats'))) {
2059
		$ntpcfg .= "enable stats\n";
2060
		$ntpcfg .= 'statistics';
2061
		if (!empty(config_get_path('ntpd/clockstats'))) {
2062
			$ntpcfg .= ' clockstats';
2063
		}
2064
		if (!empty(config_get_path('ntpd/loopstats'))) {
2065
			$ntpcfg .= ' loopstats';
2066
		}
2067
		if (!empty(config_get_path('ntpd/peerstats'))) {
2068
			$ntpcfg .= ' peerstats';
2069
		}
2070
		$ntpcfg .= "\n";
2071
	}
2072
	$ntpcfg .= "statsdir {$statsdir}\n";
2073
	$ntpcfg .= 'logconfig =syncall +clockall';
2074
	if (!empty(config_get_path('ntpd/logpeer'))) {
2075
		$ntpcfg .= ' +peerall';
2076
	}
2077
	if (!empty(config_get_path('ntpd/logsys'))) {
2078
		$ntpcfg .= ' +sysall';
2079
	}
2080
	$ntpcfg .= "\n";
2081
	$ntpcfg .= "driftfile {$driftfile}\n";
2082

    
2083
	/* Default Access restrictions */
2084
	$ntpcfg .= 'restrict default';
2085
	if (empty(config_get_path('ntpd/kod'))) { /*note: this one works backwards */
2086
		$ntpcfg .= ' kod limited';
2087
	}
2088
	if (empty(config_get_path('ntpd/nomodify'))) { /*note: this one works backwards */
2089
		$ntpcfg .= ' nomodify';
2090
	}
2091
	if (!empty(config_get_path('ntpd/noquery'))) {
2092
		$ntpcfg .= ' noquery';
2093
	}
2094
	if (empty(config_get_path('ntpd/nopeer'))) { /*note: this one works backwards */
2095
		$ntpcfg .= ' nopeer';
2096
	}
2097
	if (empty(config_get_path('ntpd/notrap'))) { /*note: this one works backwards */
2098
		$ntpcfg .= ' notrap';
2099
	}
2100
	if (!empty(config_get_path('ntpd/noserve'))) {
2101
		$ntpcfg .= ' noserve';
2102
	}
2103
	$ntpcfg .= "\nrestrict -6 default";
2104
	if (empty(config_get_path('ntpd/kod'))) { /*note: this one works backwards */
2105
		$ntpcfg .= ' kod limited';
2106
	}
2107
	if (empty(config_get_path('ntpd/nomodify'))) { /*note: this one works backwards */
2108
		$ntpcfg .= ' nomodify';
2109
	}
2110
	if (!empty(config_get_path('ntpd/noquery'))) {
2111
		$ntpcfg .= ' noquery';
2112
	}
2113
	if (empty(config_get_path('ntpd/nopeer'))) { /*note: this one works backwards */
2114
		$ntpcfg .= ' nopeer';
2115
	}
2116
	if (!empty(config_get_path('ntpd/noserve'))) {
2117
		$ntpcfg .= ' noserve';
2118
	}
2119
	if (empty(config_get_path('ntpd/notrap'))) { /*note: this one works backwards */
2120
		$ntpcfg .= ' notrap';
2121
	}
2122

    
2123
	/* Pools require "restrict source" and cannot contain "nopeer" and "noserve". */
2124
	if ($have_pools) {
2125
		$ntpcfg .= "\nrestrict source";
2126
		if (empty(config_get_path('ntpd/kod'))) { /*note: this one works backwards */
2127
			$ntpcfg .= ' kod limited';
2128
		}
2129
		if (empty(config_get_path('ntpd/nomodify'))) { /*note: this one works backwards */
2130
			$ntpcfg .= ' nomodify';
2131
		}
2132
		if (!empty(config_get_path('ntpd/noquery'))) {
2133
			$ntpcfg .= ' noquery';
2134
		}
2135
		if (empty(config_get_path('ntpd/notrap'))) { /*note: this one works backwards */
2136
			$ntpcfg .= ' notrap';
2137
		}
2138
	}
2139

    
2140
	/* Custom Access Restrictions */
2141
	if (is_array(config_get_path('ntpd/restrictions/row'))) {
2142
		$networkacl = config_get_path('ntpd/restrictions/row');
2143
		foreach ($networkacl as $acl) {
2144
			$restrict = "";
2145
			if (is_ipaddrv6($acl['acl_network'])) {
2146
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask_v6($acl['mask']) . " ";
2147
			} elseif (is_ipaddrv4($acl['acl_network'])) {
2148
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask($acl['mask']) . " ";
2149
			} else {
2150
				continue;
2151
			}
2152
			if (!empty($acl['kod'])) {
2153
				$restrict .= ' kod limited';
2154
			}
2155
			if (!empty($acl['nomodify'])) {
2156
				$restrict .= ' nomodify';
2157
			}
2158
			if (!empty($acl['noquery'])) {
2159
				$restrict .= ' noquery';
2160
			}
2161
			if (!empty($acl['nopeer'])) {
2162
				$restrict .= ' nopeer';
2163
			}
2164
			if (!empty($acl['noserve'])) {
2165
				$restrict .= ' noserve';
2166
			}
2167
			if (!empty($acl['notrap'])) {
2168
				$restrict .= ' notrap';
2169
			}
2170
			if (!empty($restrict)) {
2171
				$ntpcfg .= "\nrestrict {$restrict} ";
2172
			}
2173
		}
2174
	}
2175
	/* End Custom Access Restrictions */
2176

    
2177
	/* A leapseconds file is really only useful if this clock is stratum 1 */
2178
	$ntpcfg .= "\n";
2179
	if (!empty(config_get_path('ntpd/leapsec'))) {
2180
		$leapsec .= base64_decode(config_get_path('ntpd/leapsec'));
2181
		file_put_contents('/var/db/leap-seconds', $leapsec);
2182
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
2183
	}
2184

    
2185

    
2186
	if (empty(config_get_path('ntpd/interface'))) {
2187
		$interfaces =
2188
			explode(",",
2189
					config_get_path('installedpackages/openntpd/config/0/interface', ''));
2190
	} else {
2191
		$interfaces = explode(",", config_get_path('ntpd/interface'));
2192
	}
2193

    
2194
	if (is_array($interfaces) && count($interfaces)) {
2195
		$finterfaces = array();
2196
		foreach ($interfaces as $interface) {
2197
			$interface = get_real_interface($interface);
2198
			if (!empty($interface)) {
2199
				$finterfaces[] = $interface;
2200
			}
2201
		}
2202
		if (!empty($finterfaces)) {
2203
			$ntpcfg .= "interface ignore all\n";
2204
			$ntpcfg .= "interface ignore wildcard\n";
2205
			foreach ($finterfaces as $interface) {
2206
				$ntpcfg .= "interface listen {$interface}\n";
2207
			}
2208
		}
2209
	}
2210

    
2211
	/* open configuration for writing or bail */
2212
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
2213
		log_error(sprintf(gettext("Could not open %s/ntpd.conf for writing"), g_get('varetc_path')));
2214
		return;
2215
	}
2216

    
2217
	/* if /var/empty does not exist, create it */
2218
	if (!is_dir("/var/empty")) {
2219
		mkdir("/var/empty", 0555, true);
2220
	}
2221

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

    
2225
	// Note that we are starting up
2226
	log_error("NTPD is starting up.");
2227

    
2228
	if (platform_booting()) {
2229
		echo gettext("done.") . "\n";
2230
	}
2231

    
2232
	return;
2233
}
2234

    
2235
function system_halt() {
2236
	global $g;
2237

    
2238
	system_reboot_cleanup();
2239

    
2240
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
2241
}
2242

    
2243
function system_reboot() {
2244
	global $g;
2245

    
2246
	system_reboot_cleanup();
2247

    
2248
	mwexec("/usr/bin/nohup /etc/rc.reboot > /dev/null 2>&1 &");
2249
}
2250

    
2251
function system_reboot_sync($reroot=false) {
2252
	global $g;
2253

    
2254
	if ($reroot) {
2255
		$args = " -r ";
2256
	}
2257

    
2258
	system_reboot_cleanup();
2259

    
2260
	mwexec("/etc/rc.reboot {$args} > /dev/null 2>&1");
2261
}
2262

    
2263
function system_reboot_cleanup() {
2264
	global $g, $cpzone;
2265

    
2266
	mwexec("/usr/local/bin/beep.sh stop");
2267
	require_once("captiveportal.inc");
2268
	$cps = config_get_path('captiveportal', []);
2269
	foreach ($cps as $cpzone=>$cp) {
2270
		if (!isset($cp['preservedb'])) {
2271
			/* send Accounting-Stop packet for all clients, termination cause 'Admin-Reboot' */
2272
			captiveportal_radius_stop_all(7); // Admin-Reboot
2273
			unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
2274
			captiveportal_free_dnrules();
2275
		}
2276
		/* Send Accounting-Off packet to the RADIUS server */
2277
		captiveportal_send_server_accounting('off');
2278
	}
2279

    
2280
	if (count($cps)> 0) {
2281
		/* Remove the pipe database */
2282
		unlink_if_exists("{$g['vardb_path']}/captiveportaldn.rules");
2283
	}
2284
	
2285
	require_once("voucher.inc");
2286
	voucher_save_db_to_config();
2287
	require_once("pkg-utils.inc");
2288
	stop_packages();
2289
}
2290

    
2291
function system_do_shell_commands($early = 0) {
2292
	if (config_path_enabled('system', 'developerspew')) {
2293
		$mt = microtime();
2294
		echo "system_do_shell_commands() being called $mt\n";
2295
	}
2296

    
2297
	if ($early) {
2298
		$cmdn = "earlyshellcmd";
2299
	} else {
2300
		$cmdn = "shellcmd";
2301
	}
2302

    
2303
	$syscmd = config_get_path("system/{$cmdn}", '');
2304
	if (is_array($syscmd)) {
2305
		/* *cmd is an array, loop through */
2306
		foreach ($syscmd as $cmd) {
2307
			exec($cmd);
2308
		}
2309

    
2310
	} elseif ($syscmd <> "") {
2311
		/* execute single item */
2312
		exec($syscmd);
2313

    
2314
	}
2315
}
2316

    
2317
function system_dmesg_save() {
2318
	global $g;
2319
	if (config_path_enabled('system', 'developerspew')) {
2320
		$mt = microtime();
2321
		echo "system_dmesg_save() being called $mt\n";
2322
	}
2323

    
2324
	$dmesg = "";
2325
	$_gb = exec("/sbin/dmesg", $dmesg);
2326

    
2327
	/* find last copyright line (output from previous boots may be present) */
2328
	$lastcpline = 0;
2329

    
2330
	for ($i = 0; $i < count($dmesg); $i++) {
2331
		if (strstr($dmesg[$i], "Copyright (c) 1992-")) {
2332
			$lastcpline = $i;
2333
		}
2334
	}
2335

    
2336
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
2337
	if (!$fd) {
2338
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
2339
		return 1;
2340
	}
2341

    
2342
	for ($i = $lastcpline; $i < count($dmesg); $i++) {
2343
		fwrite($fd, $dmesg[$i] . "\n");
2344
	}
2345

    
2346
	fclose($fd);
2347
	unset($dmesg);
2348

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

    
2352
	return 0;
2353
}
2354

    
2355
function system_set_harddisk_standby() {
2356
	if (config_path_enabled('system', 'developerspew')) {
2357
		$mt = microtime();
2358
		echo "system_set_harddisk_standby() being called $mt\n";
2359
	}
2360

    
2361
	if (config_path_enabled('system', 'harddiskstandby')) {
2362
		if (platform_booting()) {
2363
			echo gettext('Setting hard disk standby... ');
2364
		}
2365

    
2366
		$standby = config_get_path('system/harddiskstandby');
2367
		// Check for a numeric value
2368
		if (is_numeric($standby)) {
2369
			// Get only suitable candidates for standby; using get_smart_drive_list()
2370
			// from utils.inc to get the list of drives.
2371
			$harddisks = get_smart_drive_list();
2372

    
2373
			// Since get_smart_drive_list() only matches ad|da|ada; lets put the check below
2374
			// just in case of some weird pfSense platform installs.
2375
			if (count($harddisks) > 0) {
2376
				// Iterate disks and run the camcontrol command for each
2377
				foreach ($harddisks as $harddisk) {
2378
					mwexec("/sbin/camcontrol standby {$harddisk} -t {$standby}");
2379
				}
2380
				if (platform_booting()) {
2381
					echo gettext("done.") . "\n";
2382
				}
2383
			} else if (platform_booting()) {
2384
				echo gettext("failed!") . "\n";
2385
			}
2386
		} else if (platform_booting()) {
2387
			echo gettext("failed!") . "\n";
2388
		}
2389
	}
2390
}
2391

    
2392
function system_setup_sysctl() {
2393
	if (config_path_enabled('system', 'developerspew')) {
2394
		$mt = microtime();
2395
		echo "system_setup_sysctl() being called $mt\n";
2396
	}
2397

    
2398
	activate_sysctls();
2399

    
2400
	if (config_path_enabled('system', 'sharednet')) {
2401
		system_disable_arp_wrong_if();
2402
	}
2403
}
2404

    
2405
function system_disable_arp_wrong_if() {
2406
	if (config_path_enabled('system', 'developerspew')) {
2407
		$mt = microtime();
2408
		echo "system_disable_arp_wrong_if() being called $mt\n";
2409
	}
2410
	set_sysctl(array(
2411
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
2412
		"net.link.ether.inet.log_arp_movements" => "0"
2413
	));
2414
}
2415

    
2416
function system_enable_arp_wrong_if() {
2417
	if (config_path_enabled('system', 'developerspew')) {
2418
		$mt = microtime();
2419
		echo "system_enable_arp_wrong_if() being called $mt\n";
2420
	}
2421
	set_sysctl(array(
2422
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
2423
		"net.link.ether.inet.log_arp_movements" => "1"
2424
	));
2425
}
2426

    
2427
function enable_watchdog() {
2428
	return;
2429
	$install_watchdog = false;
2430
	$supported_watchdogs = array("Geode");
2431
	$file = file_get_contents("/var/log/dmesg.boot");
2432
	foreach ($supported_watchdogs as $sd) {
2433
		if (stristr($file, "Geode")) {
2434
			$install_watchdog = true;
2435
		}
2436
	}
2437
	if ($install_watchdog == true) {
2438
		if (is_process_running("watchdogd")) {
2439
			mwexec("/usr/bin/killall watchdogd", true);
2440
		}
2441
		exec("/usr/sbin/watchdogd");
2442
	}
2443
}
2444

    
2445
function system_check_reset_button() {
2446
	global $g;
2447

    
2448
	$specplatform = system_identify_specific_platform();
2449

    
2450
	switch ($specplatform['name']) {
2451
		case 'SG-2220':
2452
			$binprefix = "RCC-DFF";
2453
			break;
2454
		case 'alix':
2455
		case 'wrap':
2456
		case 'FW7541':
2457
		case 'APU':
2458
		case 'RCC-VE':
2459
		case 'RCC':
2460
			$binprefix = $specplatform['name'];
2461
			break;
2462
		default:
2463
			return 0;
2464
	}
2465

    
2466
	$retval = mwexec("/usr/local/sbin/" . $binprefix . "resetbtn");
2467

    
2468
	if ($retval == 99) {
2469
		/* user has pressed reset button for 2 seconds -
2470
		   reset to factory defaults */
2471
		echo <<<EOD
2472

    
2473
***********************************************************************
2474
* Reset button pressed - resetting configuration to factory defaults. *
2475
* All additional packages installed will be removed                   *
2476
* The system will reboot after this completes.                        *
2477
***********************************************************************
2478

    
2479

    
2480
EOD;
2481

    
2482
		reset_factory_defaults();
2483
		system_reboot_sync();
2484
		exit(0);
2485
	}
2486

    
2487
	return 0;
2488
}
2489

    
2490
function system_get_serial() {
2491
	$platform = system_identify_specific_platform();
2492

    
2493
	unset($output);
2494
	if ($platform['name'] == 'Turbot Dual-E') {
2495
		$if_info = get_interface_addresses('igb0');
2496
		if (!empty($if_info['hwaddr'])) {
2497
			$serial = str_replace(":", "", $if_info['hwaddr']);
2498
		}
2499
	} else {
2500
		foreach (array('system', 'planar', 'chassis') as $key) {
2501
			unset($output);
2502
			$_gb = exec("/bin/kenv -q smbios.{$key}.serial",
2503
			    $output);
2504
			if (!empty($output[0]) && $output[0] != "0123456789" &&
2505
			    preg_match('/^[\w\d]{10,16}$/', $output[0]) === 1) {
2506
				$serial = $output[0];
2507
				break;
2508
			}
2509
		}
2510
	}
2511

    
2512
	$vm_guest = get_single_sysctl('kern.vm_guest');
2513

    
2514
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2515
	    $vm_guest == 'none') {
2516
		return $serial;
2517
	}
2518

    
2519
	return "";
2520
}
2521

    
2522
function system_get_uniqueid() {
2523
	global $g;
2524

    
2525
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2526

    
2527
	if (empty(g_get('uniqueid'))) {
2528
		if (!file_exists($uniqueid_file)) {
2529
			mwexec("/usr/sbin/gnid > {$g['vardb_path']}/uniqueid " .
2530
			    "2>/dev/null");
2531
		}
2532
		if (file_exists($uniqueid_file)) {
2533
			$g['uniqueid'] = @file_get_contents($uniqueid_file);
2534
		}
2535
	}
2536

    
2537
	return (g_get('uniqueid') ?: '');
2538
}
2539

    
2540
/*
2541
 * attempt to identify the specific platform (for embedded systems)
2542
 * Returns an array with two elements:
2543
 * name => platform string (e.g. 'wrap', 'alix' etc.)
2544
 * descr => human-readable description (e.g. "PC Engines WRAP")
2545
 */
2546
function system_identify_specific_platform() {
2547
	global $g;
2548

    
2549
	$hw_model = get_single_sysctl('hw.model');
2550
	$hw_ncpu = get_single_sysctl('hw.ncpu');
2551

    
2552
	/* Try to guess from smbios strings */
2553
	unset($product);
2554
	unset($maker);
2555
	unset($bios);
2556
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $product);
2557
	$_gb = exec('/bin/kenv -q smbios.system.maker 2>/dev/null', $maker);
2558
	$_gb = exec('/bin/kenv -q smbios.bios.version 2>/dev/null', $bios);
2559

    
2560
	$vm = get_single_sysctl('kern.vm_guest');
2561
	// Google GCP returns kvm from this so we must detect it first.
2562

    
2563
	if ($maker[0] == "QEMU") {
2564
		return (array('name' => 'QEMU', 'descr' => 'QEMU Guest'));
2565
	} else  if ($maker[0] == "Google") {
2566
		return (array('name' => 'Google', 'descr' => 'Google Cloud Platform'));
2567
	}
2568

    
2569
	// This switch needs to be expanded to include other virtualization systems
2570
	switch ($vm) {
2571
		case "none" :
2572
		break;
2573

    
2574
		case "kvm" :
2575
			return (array('name' => 'KVM', 'descr' => 'KVM Guest'));
2576
		break;
2577
	}
2578

    
2579
	// AWS can only be identified via the bios version
2580
	if (stripos($bios[0], "amazon") !== false) {
2581
		return (array('name' => 'AWS', 'descr' => 'Amazon Web Services'));
2582
	} else  if (stripos($bios[0], "Google") !== false) {
2583
		return (array('name' => 'Google', 'descr' => 'Google Cloud Platform'));
2584
	}
2585

    
2586
	switch ($product[0]) {
2587
		case 'FW7541':
2588
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2589
			break;
2590
		case 'apu1':
2591
		case 'APU':
2592
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2593
			break;
2594
		case 'RCC-VE':
2595
			$result = array();
2596
			$result['name'] = 'RCC-VE';
2597

    
2598
			/* Detect specific models */
2599
			if (!function_exists('does_interface_exist')) {
2600
				require_once("interfaces.inc");
2601
			}
2602
			if (!does_interface_exist('igb4')) {
2603
				$result['model'] = 'SG-2440';
2604
			} elseif (strpos($hw_model, "C2558") !== false) {
2605
				$result['model'] = 'SG-4860';
2606
			} elseif (strpos($hw_model, "C2758") !== false) {
2607
				$result['model'] = 'SG-8860';
2608
			} else {
2609
				$result['model'] = 'RCC-VE';
2610
			}
2611
			$result['descr'] = 'Netgate ' . $result['model'];
2612
			return $result;
2613
			break;
2614
		case 'DFFv2':
2615
			return (array('name' => 'SG-2220', 'descr' => 'Netgate SG-2220'));
2616
			break;
2617
		case 'RCC':
2618
			return (array('name' => 'RCC', 'descr' => 'Netgate XG-2758'));
2619
			break;
2620
		case 'SG-5100':
2621
			return (array('name' => '5100', 'descr' => 'Netgate 5100'));
2622
			break;
2623
		case 'Minnowboard Turbot D0 PLATFORM':
2624
		case 'Minnowboard Turbot D0/D1 PLATFORM':
2625
			$result = array();
2626
			$result['name'] = 'Turbot Dual-E';
2627
			/* Detect specific model */
2628
			switch ($hw_ncpu) {
2629
			case '4':
2630
				$result['model'] = 'MBT-4220';
2631
				break;
2632
			case '2':
2633
				$result['model'] = 'MBT-2220';
2634
				break;
2635
			default:
2636
				$result['model'] = $result['name'];
2637
				break;
2638
			}
2639
			$result['descr'] = 'Netgate ' . $result['model'];
2640
			return $result;
2641
			break;
2642
		case 'SYS-5018A-FTN4':
2643
		case 'A1SAi':
2644
			if (strpos($hw_model, "C2558") !== false) {
2645
				return (array(
2646
				    'name' => 'C2558',
2647
				    'descr' => 'Super Micro C2558'));
2648
			} elseif (strpos($hw_model, "C2758") !== false) {
2649
				return (array(
2650
				    'name' => 'C2758',
2651
				    'descr' => 'Super Micro C2758'));
2652
			}
2653
			break;
2654
		case 'SYS-5018D-FN4T':
2655
			if (strpos($hw_model, "D-1541") !== false) {
2656
				return (array('name' => '1541', 'descr' => 'Super Micro 1541'));
2657
			} else {
2658
				return (array('name' => '1540', 'descr' => 'Super Micro XG-1540'));
2659
			}
2660
			break;
2661
		case 'apu2':
2662
		case 'APU2':
2663
			return (array('name' => 'apu2', 'descr' => 'PC Engines APU2'));
2664
			break;
2665
		case 'VirtualBox':
2666
			return (array('name' => 'VirtualBox', 'descr' => 'VirtualBox Virtual Machine'));
2667
			break;
2668
		case 'Virtual Machine':
2669
			if ($maker[0] == "Microsoft Corporation") {
2670
				if (stripos($bios[0], "Hyper") !== false) {
2671
					return (array('name' => 'Hyper-V', 'descr' => 'Hyper-V Virtual Machine'));
2672
				} else {
2673
					return (array('name' => 'Azure', 'descr' => 'Microsoft Azure'));
2674
				}
2675
			}
2676
			break;
2677
		case 'VMware Virtual Platform':
2678
			if ($maker[0] == "VMware, Inc.") {
2679
				return (array('name' => 'VMware', 'descr' => 'VMware Virtual Machine'));
2680
			}
2681
			break;
2682
	}
2683

    
2684
	$_gb = exec('/bin/kenv -q smbios.planar.product 2>/dev/null',
2685
	    $planar_product);
2686
	if (isset($planar_product[0]) &&
2687
	    $planar_product[0] == 'X10SDV-8C-TLN4F+') {
2688
		return array('name' => '1537', 'descr' => 'Super Micro 1537');
2689
	}
2690

    
2691
	if (strpos($hw_model, "PC Engines WRAP") !== false) {
2692
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
2693
	}
2694

    
2695
	if (strpos($hw_model, "PC Engines ALIX") !== false) {
2696
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2697
	}
2698

    
2699
	if (preg_match("/Soekris net45../", $hw_model, $matches)) {
2700
		return array('name' => 'net45xx', 'descr' => $matches[0]);
2701
	}
2702

    
2703
	if (preg_match("/Soekris net48../", $hw_model, $matches)) {
2704
		return array('name' => 'net48xx', 'descr' => $matches[0]);
2705
	}
2706

    
2707
	if (preg_match("/Soekris net55../", $hw_model, $matches)) {
2708
		return array('name' => 'net55xx', 'descr' => $matches[0]);
2709
	}
2710

    
2711
	unset($hw_model);
2712

    
2713
	$dmesg_boot = system_get_dmesg_boot();
2714
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
2715
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2716
	}
2717
	unset($dmesg_boot);
2718

    
2719
	return array('name' => g_get('product_name'), 'descr' => g_get('product_label'));
2720
}
2721

    
2722
function system_get_dmesg_boot() {
2723
	global $g;
2724

    
2725
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2726
}
2727

    
2728
function system_get_arp_table($resolve_hostnames = false) {
2729
	$params="-a";
2730
	if (!$resolve_hostnames) {
2731
		$params .= "n";
2732
	}
2733

    
2734
	$arp_table = array();
2735
	$_gb = exec("/usr/sbin/arp --libxo json {$params}", $rawdata, $rc);
2736
	if ($rc == 0) {
2737
		$arp_table = json_decode(implode(" ", $rawdata),
2738
		    JSON_OBJECT_AS_ARRAY);
2739
		if ($rc == 0) {
2740
			$arp_table = $arp_table['arp']['arp-cache'];
2741
		}
2742
	}
2743

    
2744
	return $arp_table;
2745
}
2746

    
2747
function _getHostName($mac, $ip) {
2748
	global $dhcpmac, $dhcpip;
2749

    
2750
	if ($dhcpmac[$mac]) {
2751
		return $dhcpmac[$mac];
2752
	} else if ($dhcpip[$ip]) {
2753
		return $dhcpip[$ip];
2754
	} else {
2755
		exec("/usr/bin/host -W 1 " . escapeshellarg($ip), $output);
2756
		if (preg_match('/.*pointer ([A-Za-z_0-9.-]+)\..*/', $output[0], $matches)) {
2757
			if ($matches[1] <> $ip) {
2758
				return $matches[1];
2759
			}
2760
		}
2761
	}
2762
	return "";
2763
}
2764

    
2765
function check_dnsavailable($proto='inet') {
2766

    
2767
	if ($proto == 'inet') {
2768
		$gdns = array('8.8.8.8', '8.8.4.4');
2769
	} elseif ($proto == 'inet6') {
2770
		$gdns = array('2001:4860:4860::8888', '2001:4860:4860::8844');
2771
	} else {
2772
		$gdns = array('8.8.8.8', '8.8.4.4', '2001:4860:4860::8888', '2001:4860:4860::8844');
2773
	}
2774
	$nameservers = array_merge($gdns, get_dns_nameservers());
2775
	$test = 0;
2776

    
2777
	foreach ($gdns as $dns) {
2778
		if ($dns == '127.0.0.1') {
2779
			continue;
2780
		} else {
2781
			$dns_result = trim(_getHostName("", $dns));
2782
			if (($test == '2') && ($dns_result == "")) {
2783
				return false;
2784
			} elseif ($dns_result == "") {
2785
				$test++;
2786
				continue;
2787
			} else {
2788
				return true;
2789
			}
2790
		}
2791
	}
2792

    
2793
	return false;
2794
}
2795

    
2796
?>
(50-50/61)