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

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

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

    
1293
	global $g;
1294

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

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

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

    
1329
	if (empty($port)) {
1330
		$nginx_port = "80";
1331
	} else {
1332
		$nginx_port = $port;
1333
	}
1334

    
1335
	$memory = get_memory();
1336
	$realmem = $memory[1];
1337

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

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

    
1356
	$nginx_config = <<<EOD
1357
#
1358
# nginx configuration file
1359

    
1360
pid {$g['varrun_path']}/{$pid_file};
1361

    
1362
user  root wheel;
1363
worker_processes  {$max_procs};
1364

    
1365
EOD;
1366

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

    
1374
	$nginx_config .= <<<EOD
1375

    
1376
events {
1377
    worker_connections  1024;
1378
}
1379

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

    
1386
	sendfile        on;
1387

    
1388
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1389

    
1390
EOD;
1391

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

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

    
1439
	$nginx_config .= <<<EOD
1440

    
1441
		client_max_body_size 200m;
1442

    
1443
		gzip on;
1444
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
1445

    
1446

    
1447
EOD;
1448

    
1449
	if ($captive_portal !== false) {
1450
		$nginx_config .= <<<EOD
1451
$captive_portal_maxprocperip
1452
$cp_hostcheck
1453
$cp_rewrite
1454
		log_not_found off;
1455

    
1456
EOD;
1457

    
1458
	}
1459

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

    
1494
EOD;
1495

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

    
1499
	$cert = str_replace("\n\n", "\n", $cert);
1500
	$key = str_replace("\n\n", "\n", $key);
1501

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

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

    
1538
EOD;
1539
	}
1540

    
1541
	$nginx_config .= "}\n";
1542

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

    
1551
	/* nginx will fail to start if this directory does not exist. */
1552
	safe_mkdir("/var/tmp/nginx/");
1553

    
1554
	return 0;
1555

    
1556
}
1557

    
1558
function system_get_timezone_list() {
1559
	global $g;
1560

    
1561
	$file_list = array_merge(
1562
		glob("/usr/share/zoneinfo/[A-Z]*"),
1563
		glob("/usr/share/zoneinfo/*/*"),
1564
		glob("/usr/share/zoneinfo/*/*/*")
1565
	);
1566

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

    
1576
	/* Remove directory prefix */
1577
	$file_list = str_replace('/usr/share/zoneinfo/', '', $file_list);
1578

    
1579
	sort($file_list);
1580

    
1581
	return $file_list;
1582
}
1583

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

    
1591
	$syscfg = config_get_path('system');
1592

    
1593
	if (platform_booting()) {
1594
		echo gettext("Setting timezone...");
1595
	}
1596

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

    
1603
	if (platform_booting()) {
1604
		echo gettext("done.") . "\n";
1605
	}
1606
}
1607

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

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

    
1627
			$contents.=$c;
1628
			$cnt = $cnt + strlen($c);
1629
		} while (($cnt < $buffersize) && (microtime(true) < $timeout));
1630
		fclose($fp);
1631

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

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

    
1677
function system_ntp_poll_values() {
1678
	global $ntp_poll_min_value, $ntp_poll_max_value;
1679
	$poll_values = array("" => gettext('Default'));
1680

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

    
1687
	$poll_values['omit'] = gettext('Omit (Do not set)');
1688
	return $poll_values;
1689
}
1690

    
1691
function system_ntp_fixup_poll_value($type, $configvalue, $default) {
1692
	$pollstring = "";
1693

    
1694
	if (empty($configvalue)) {
1695
		$configvalue = $default;
1696
	}
1697

    
1698
	if ($configvalue != 'omit') {
1699
		$pollstring = " {$type} {$configvalue}";
1700
	}
1701

    
1702
	return $pollstring;
1703
}
1704

    
1705
function system_ntp_setup_gps($serialport) {
1706
	if (config_get_path('ntpd/enable') == 'disabled') {
1707
		return false;
1708
	}
1709

    
1710
	init_config_arr(array('ntpd', 'gps'));
1711
	$serialports = get_serial_ports(true);
1712

    
1713
	if (!array_key_exists($serialport, $serialports)) {
1714
		return false;
1715
	}
1716

    
1717
	$gps_device = '/dev/gps0';
1718
	$serialport = '/dev/'.basename($serialport);
1719

    
1720
	if (!file_exists($serialport)) {
1721
		return false;
1722
	}
1723

    
1724
	// Create symlink that ntpd requires
1725
	unlink_if_exists($gps_device);
1726
	@symlink($serialport, $gps_device);
1727

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

    
1739
	system_ntp_setup_rawspeed($serialport, $gpsbaud);
1740

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

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

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

    
1776
	if ($found && config_get_path('ntpd/gps/autobaudinit')) {
1777
		system_ntp_setup_rawspeed($serialport, $gpsbaud);
1778
	}
1779

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

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

    
1790
	return true;
1791
}
1792

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

    
1799
function system_ntp_setup_pps($serialport) {
1800
	$serialports = get_serial_ports(true);
1801

    
1802
	if (!array_key_exists($serialport, $serialports)) {
1803
		return false;
1804
	}
1805

    
1806
	$pps_device = '/dev/pps0';
1807
	$serialport = '/dev/'.basename($serialport);
1808

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

    
1817
	// Create symlink that ntpd requires
1818
	unlink_if_exists($pps_device);
1819
	@symlink($serialport, $pps_device);
1820

    
1821

    
1822
	return true;
1823
}
1824

    
1825
function system_ntp_configure() {
1826
	global $g;
1827
	global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
1828
	global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
1829
	global $ntp_poll_min_default, $ntp_poll_max_default;
1830

    
1831
	$driftfile = "/var/db/ntpd.drift";
1832
	$statsdir = "/var/log/ntp";
1833
	$gps_device = '/dev/gps0';
1834

    
1835
	safe_mkdir($statsdir);
1836

    
1837
	init_config_arr(array('ntpd'));
1838

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

    
1851
	if (platform_booting()) {
1852
		echo gettext("Starting NTP Server...");
1853
	}
1854

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

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

    
1872
	$ntpcfg = "# \n";
1873
	$ntpcfg .= "# pfSense ntp configuration file \n";
1874
	$ntpcfg .= "# \n\n";
1875
	$ntpcfg .= "tinker panic 0 \n\n";
1876

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

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

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

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

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

    
2042
		$ntpcfg .= "{$ts}";
2043
		if (!substr_count(config_get_path('ntpd/ispeer'), $ts)) {
2044
			$ntpcfg .= " iburst";
2045
		}
2046

    
2047
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', config_get_path('ntpd/ntpminpoll'), $ntp_poll_min_default);
2048
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', config_get_path('ntpd/ntpmaxpoll'), $ntp_poll_max_default);
2049

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

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

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

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

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

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

    
2188

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

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

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

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

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

    
2228
	// Note that we are starting up
2229
	log_error("NTPD is starting up.");
2230

    
2231
	if (platform_booting()) {
2232
		echo gettext("done.") . "\n";
2233
	}
2234

    
2235
	return;
2236
}
2237

    
2238
function system_halt() {
2239
	global $g;
2240

    
2241
	system_reboot_cleanup();
2242

    
2243
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
2244
}
2245

    
2246
function system_reboot() {
2247
	global $g;
2248

    
2249
	system_reboot_cleanup();
2250

    
2251
	mwexec("/usr/bin/nohup /etc/rc.reboot > /dev/null 2>&1 &");
2252
}
2253

    
2254
function system_reboot_sync($reroot=false) {
2255
	global $g;
2256

    
2257
	if ($reroot) {
2258
		$args = " -r ";
2259
	}
2260

    
2261
	system_reboot_cleanup();
2262

    
2263
	mwexec("/etc/rc.reboot {$args} > /dev/null 2>&1");
2264
}
2265

    
2266
function system_reboot_cleanup() {
2267
	global $g, $cpzone;
2268

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

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

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

    
2300
	if ($early) {
2301
		$cmdn = "earlyshellcmd";
2302
	} else {
2303
		$cmdn = "shellcmd";
2304
	}
2305

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

    
2313
	} elseif ($syscmd <> "") {
2314
		/* execute single item */
2315
		exec($syscmd);
2316

    
2317
	}
2318
}
2319

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

    
2327
	$dmesg = "";
2328
	$_gb = exec("/sbin/dmesg", $dmesg);
2329

    
2330
	/* find last copyright line (output from previous boots may be present) */
2331
	$lastcpline = 0;
2332

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

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

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

    
2349
	fclose($fd);
2350
	unset($dmesg);
2351

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

    
2355
	return 0;
2356
}
2357

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

    
2364
	if (config_path_enabled('system', 'harddiskstandby')) {
2365
		if (platform_booting()) {
2366
			echo gettext('Setting hard disk standby... ');
2367
		}
2368

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

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

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

    
2401
	activate_sysctls();
2402

    
2403
	if (config_path_enabled('system', 'sharednet')) {
2404
		system_disable_arp_wrong_if();
2405
	}
2406
}
2407

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

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

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

    
2448
function system_check_reset_button() {
2449
	global $g;
2450

    
2451
	$specplatform = system_identify_specific_platform();
2452

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

    
2469
	$retval = mwexec("/usr/local/sbin/" . $binprefix . "resetbtn");
2470

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

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

    
2482

    
2483
EOD;
2484

    
2485
		reset_factory_defaults();
2486
		system_reboot_sync();
2487
		exit(0);
2488
	}
2489

    
2490
	return 0;
2491
}
2492

    
2493
function system_get_serial() {
2494
	$platform = system_identify_specific_platform();
2495

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

    
2515
	$vm_guest = get_single_sysctl('kern.vm_guest');
2516

    
2517
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2518
	    $vm_guest == 'none') {
2519
		return $serial;
2520
	}
2521

    
2522
	return "";
2523
}
2524

    
2525
function system_get_uniqueid() {
2526
	global $g;
2527

    
2528
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2529

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

    
2540
	return ($g['uniqueid'] ?: '');
2541
}
2542

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

    
2552
	$hw_model = get_single_sysctl('hw.model');
2553
	$hw_ncpu = get_single_sysctl('hw.ncpu');
2554

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

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

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

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

    
2577
		case "kvm" :
2578
			return (array('name' => 'KVM', 'descr' => 'KVM Guest'));
2579
		break;
2580
	}
2581

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

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

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

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

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

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

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

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

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

    
2714
	unset($hw_model);
2715

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

    
2722
	return array('name' => $g['product_name'], 'descr' => $g['product_label']);
2723
}
2724

    
2725
function system_get_dmesg_boot() {
2726
	global $g;
2727

    
2728
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2729
}
2730

    
2731
function system_get_arp_table($resolve_hostnames = false) {
2732
	$params="-a";
2733
	if (!$resolve_hostnames) {
2734
		$params .= "n";
2735
	}
2736

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

    
2747
	return $arp_table;
2748
}
2749

    
2750
function _getHostName($mac, $ip) {
2751
	global $dhcpmac, $dhcpip;
2752

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

    
2768
function check_dnsavailable($proto='inet') {
2769

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

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

    
2796
	return false;
2797
}
2798

    
2799
?>
(50-50/62)