Project

General

Profile

Download (76.8 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('syslog.inc');
29

    
30
function activate_powerd() {
31
	global $config, $g;
32

    
33
	if (is_process_running("powerd")) {
34
		exec("/usr/bin/killall powerd");
35
	}
36
	if (isset($config['system']['powerd_enable'])) {
37
		$ac_mode = "hadp";
38
		if (!empty($config['system']['powerd_ac_mode'])) {
39
			$ac_mode = $config['system']['powerd_ac_mode'];
40
		}
41

    
42
		$battery_mode = "hadp";
43
		if (!empty($config['system']['powerd_battery_mode'])) {
44
			$battery_mode = $config['system']['powerd_battery_mode'];
45
		}
46

    
47
		$normal_mode = "hadp";
48
		if (!empty($config['system']['powerd_normal_mode'])) {
49
			$normal_mode = $config['system']['powerd_normal_mode'];
50
		}
51

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

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

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

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

    
71
	return $output[0];
72
}
73

    
74
function system_get_sysctls() {
75
	global $config, $sysctls;
76

    
77
	$disp_sysctl = array();
78
	$disp_cache = array();
79
	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
80
		foreach ($config['sysctl']['item'] as $id => $tunable) {
81
			if ($tunable['value'] == "default") {
82
				$value = get_default_sysctl_value($tunable['tunable']);
83
			} else {
84
				$value = $tunable['value'];
85
			}
86

    
87
			$disp_sysctl[$id] = $tunable;
88
			$disp_sysctl[$id]['modified'] = true;
89
			$disp_cache[$tunable['tunable']] = 'set';
90
		}
91
	}
92

    
93
	foreach ($sysctls as $sysctl => $value) {
94
		if (isset($disp_cache[$sysctl])) {
95
			continue;
96
		}
97

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

    
104
function activate_sysctls() {
105
	global $config, $g, $sysctls, $ipsec_filter_sysctl;
106

    
107
	if (!is_array($sysctls)) {
108
		$sysctls = array();
109
	}
110

    
111
	$ipsec_filtermode = empty($config['ipsec']['filtermode']) ? 'enc' : $config['ipsec']['filtermode'];
112
	$sysctls = array_merge($sysctls, $ipsec_filter_sysctl[$ipsec_filtermode]);
113

    
114
	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
115
		foreach ($config['sysctl']['item'] as $tunable) {
116
			if ($tunable['value'] == "default") {
117
				$value = get_default_sysctl_value($tunable['tunable']);
118
			} else {
119
				$value = $tunable['value'];
120
			}
121

    
122
			$sysctls[$tunable['tunable']] = $value;
123
		}
124
	}
125

    
126
	/* Set net.pf.request_maxcount via sysctl since it is no longer a loader
127
	 *   tunable. See https://redmine.pfsense.org/issues/10861
128
	 *   Set the value dynamically since its default is not static, yet this
129
	 *   still could be overridden by a user tunable. */
130
	if (isset($config['system']['maximumtableentries'])) {
131
		$maximumtableentries = $config['system']['maximumtableentries'];
132
	} else {
133
		$maximumtableentries = pfsense_default_table_entries_size();
134
	}
135
	/* Set the default when there is no tunable or when the tunable is set
136
	 * too low. */
137
	if (empty($sysctls['net.pf.request_maxcount']) ||
138
	    ($sysctls['net.pf.request_maxcount'] < $maximumtableentries)) {
139
		$sysctls['net.pf.request_maxcount'] = $maximumtableentries;
140
	}
141

    
142
	set_sysctl($sysctls);
143
}
144

    
145
function system_resolvconf_generate($dynupdate = false) {
146
	global $config, $g;
147

    
148
	if (isset($config['system']['developerspew'])) {
149
		$mt = microtime();
150
		echo "system_resolvconf_generate() being called $mt\n";
151
	}
152

    
153
	$syscfg = $config['system'];
154

    
155
	foreach(get_dns_nameservers(false, false) as $dns_ns) {
156
		$resolvconf .= "nameserver $dns_ns\n";
157
	}
158

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

    
176
	// Add EDNS support
177
	if (isset($config['unbound']['enable']) && isset($config['unbound']['edns'])) {
178
		$resolvconf .= "options edns0\n";
179
	}
180

    
181
	$dnslock = lock('resolvconf', LOCK_EX);
182

    
183
	$fd = fopen("{$g['etc_path']}/resolv.conf", "w");
184
	if (!$fd) {
185
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
186
		unlock($dnslock);
187
		return 1;
188
	}
189

    
190
	fwrite($fd, $resolvconf);
191
	fclose($fd);
192

    
193
	// Prevent resolvconf(8) from rewriting our resolv.conf
194
	$fd = fopen("{$g['etc_path']}/resolvconf.conf", "w");
195
	if (!$fd) {
196
		printf("Error: cannot open resolvconf.conf in system_resolvconf_generate().\n");
197
		return 1;
198
	}
199
	fwrite($fd, "resolv_conf=\"/dev/null\"\n");
200
	fclose($fd);
201

    
202
	if (!platform_booting()) {
203
		/* restart dhcpd (nameservers may have changed) */
204
		if (!$dynupdate) {
205
			services_dhcpd_configure();
206
		}
207
	}
208

    
209
	// set up or tear down static routes for DNS servers
210
	$dnscounter = 1;
211
	$dnsgw = "dns{$dnscounter}gw";
212
	while (isset($config['system'][$dnsgw])) {
213
		/* setup static routes for dns servers */
214
		$gwname = $config['system'][$dnsgw];
215
		unset($gatewayip);
216
		unset($inet6);
217
		if ((!empty($gwname)) && ($gwname != "none")) {
218
			$gatewayip = lookup_gateway_ip_by_name($gwname);
219
			$inet6 = is_ipaddrv6($gatewayip) ? '-inet6 ' : '';
220
		}
221
		/* dns server array starts at 0 */
222
		$dnsserver = $syscfg['dnsserver'][$dnscounter - 1];
223

    
224
		/* specify IP protocol version for correct add/del,
225
		 * see https://redmine.pfsense.org/issues/11578 */
226
		if (is_ipaddrv4($dnsserver)) {
227
			$ipprotocol = 'inet';
228
		} else {
229
			$ipprotocol = 'inet6';
230
		}
231
		if (!empty($dnsserver)) {
232
			if (is_ipaddr($gatewayip)) {
233
				route_add_or_change($dnsserver, $gatewayip, '', '', $ipprotocol);
234
			} else {
235
				/* Remove old route when disable gw */
236
				route_del($dnsserver, $ipprotocol);
237
			}
238
		}
239
		$dnscounter++;
240
		$dnsgw = "dns{$dnscounter}gw";
241
	}
242

    
243
	unlock($dnslock);
244

    
245
	return 0;
246
}
247

    
248
function get_searchdomains() {
249
	global $config, $g;
250

    
251
	$master_list = array();
252

    
253
	// Read in dhclient nameservers
254
	$search_list = glob("/var/etc/searchdomain_*");
255
	if (is_array($search_list)) {
256
		foreach ($search_list as $fdns) {
257
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
258
			if (!is_array($contents)) {
259
				continue;
260
			}
261
			foreach ($contents as $dns) {
262
				if (is_hostname($dns)) {
263
					$master_list[] = $dns;
264
				}
265
			}
266
		}
267
	}
268

    
269
	return $master_list;
270
}
271

    
272
/* Stub for deprecated function name
273
 * See https://redmine.pfsense.org/issues/10931 */
274
function get_nameservers() {
275
	return get_dynamic_nameservers();
276
}
277

    
278
/****f* system.inc/get_dynamic_nameservers
279
 * NAME
280
 *   get_dynamic_nameservers - Get DNS servers from dynamic sources (DHCP, PPP, etc)
281
 * INPUTS
282
 *   $iface: Interface name used to filter results.
283
 * RESULT
284
 *   $master_list - Array containing DNS servers
285
 ******/
286
function get_dynamic_nameservers($iface = '') {
287
	global $config, $g;
288
	$master_list = array();
289

    
290
	if (!empty($iface)) {
291
		$realif = get_real_interface($iface);
292
	}
293

    
294
	// Read in dynamic nameservers
295
	$dns_lists = array_merge(glob("/var/etc/nameserver_{$realif}*"), glob("/var/etc/nameserver_v6{$iface}*"));
296
	if (is_array($dns_lists)) {
297
		foreach ($dns_lists as $fdns) {
298
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
299
			if (!is_array($contents)) {
300
				continue;
301
			}
302
			foreach ($contents as $dns) {
303
				if (is_ipaddr($dns)) {
304
					$master_list[] = $dns;
305
				}
306
			}
307
		}
308
	}
309

    
310
	return $master_list;
311
}
312

    
313
/* Create localhost + local interfaces entries for /etc/hosts */
314
function system_hosts_local_entries() {
315
	global $config;
316

    
317
	$syscfg = $config['system'];
318

    
319
	$hosts = array();
320
	$hosts[] = array(
321
	    'ipaddr' => '127.0.0.1',
322
	    'fqdn' => 'localhost.' . $syscfg['domain'],
323
	    'name' => 'localhost',
324
	    'domain' => $syscfg['domain']
325
	);
326
	$hosts[] = array(
327
	    'ipaddr' => '::1',
328
	    'fqdn' => 'localhost.' . $syscfg['domain'],
329
	    'name' => 'localhost',
330
	    'domain' => $syscfg['domain']
331
	);
332

    
333
	if ($config['interfaces']['lan']) {
334
		$sysiflist = array('lan' => "lan");
335
	} else {
336
		$sysiflist = get_configured_interface_list();
337
	}
338

    
339
	$hosts_if_found = false;
340
	$local_fqdn = "{$syscfg['hostname']}.{$syscfg['domain']}";
341
	foreach ($sysiflist as $sysif) {
342
		if ($sysif != 'lan' && interface_has_gateway($sysif)) {
343
			continue;
344
		}
345
		$cfgip = get_interface_ip($sysif);
346
		if (is_ipaddrv4($cfgip)) {
347
			$hosts[] = array(
348
			    'ipaddr' => $cfgip,
349
			    'fqdn' => $local_fqdn,
350
			    'name' => $syscfg['hostname'],
351
			    'domain' => $syscfg['domain']
352
			);
353
			$hosts_if_found = true;
354
		}
355
		if (!isset($syscfg['ipv6dontcreatelocaldns'])) {
356
			$cfgipv6 = get_interface_ipv6($sysif);
357
			if (is_ipaddrv6($cfgipv6)) {
358
				$hosts[] = array(
359
					'ipaddr' => $cfgipv6,
360
					'fqdn' => $local_fqdn,
361
					'name' => $syscfg['hostname'],
362
					'domain' => $syscfg['domain']
363
				);
364
				$hosts_if_found = true;
365
			}
366
		}
367
		if ($hosts_if_found == true) {
368
			break;
369
		}
370
	}
371

    
372
	return $hosts;
373
}
374

    
375
/* Read host override entries from dnsmasq or unbound */
376
function system_hosts_override_entries($dnscfg) {
377
	$hosts = array();
378

    
379
	if (!is_array($dnscfg) ||
380
	    !is_array($dnscfg['hosts']) ||
381
	    !isset($dnscfg['enable'])) {
382
		return $hosts;
383
	}
384

    
385
	foreach ($dnscfg['hosts'] as $host) {
386
		$fqdn = '';
387
		if ($host['host'] || $host['host'] == "0") {
388
			$fqdn .= "{$host['host']}.";
389
		}
390
		$fqdn .= $host['domain'];
391

    
392
		foreach (explode(',', $host['ip']) as $ip) {
393
			$hosts[] = array(
394
			    'ipaddr' => $ip,
395
			    'fqdn' => $fqdn,
396
			    'name' => $host['host'],
397
			    'domain' => $host['domain']
398
			);
399
		}
400

    
401
		if (!is_array($host['aliases']) ||
402
		    !is_array($host['aliases']['item'])) {
403
			continue;
404
		}
405

    
406
		foreach ($host['aliases']['item'] as $alias) {
407
			$fqdn = '';
408
			if ($alias['host'] || $alias['host'] == "0") {
409
				$fqdn .= "{$alias['host']}.";
410
			}
411
			$fqdn .= $alias['domain'];
412

    
413
			foreach (explode(',', $host['ip']) as $ip) {
414
				$hosts[] = array(
415
				    'ipaddr' => $ip,
416
				    'fqdn' => $fqdn,
417
				    'name' => $alias['host'],
418
				    'domain' => $alias['domain']
419
				);
420
			}
421
		}
422
	}
423

    
424
	return $hosts;
425
}
426

    
427
/* Read all dhcpd/dhcpdv6 staticmap entries */
428
function system_hosts_dhcpd_entries() {
429
	global $config;
430

    
431
	$hosts = array();
432
	$syscfg = $config['system'];
433

    
434
	if (is_array($config['dhcpd'])) {
435
		$conf_dhcpd = $config['dhcpd'];
436
	} else {
437
		$conf_dhcpd = array();
438
	}
439

    
440
	foreach ($conf_dhcpd as $dhcpif => $dhcpifconf) {
441
		if (!is_array($dhcpifconf['staticmap']) ||
442
		    !isset($dhcpifconf['enable'])) {
443
			continue;
444
		}
445
		foreach ($dhcpifconf['staticmap'] as $host) {
446
			if (!$host['ipaddr'] ||
447
			    !$host['hostname']) {
448
				continue;
449
			}
450

    
451
			$fqdn = $host['hostname'] . ".";
452
			$domain = "";
453
			if ($host['domain']) {
454
				$domain = $host['domain'];
455
			} elseif ($dhcpifconf['domain']) {
456
				$domain = $dhcpifconf['domain'];
457
			} else {
458
				$domain = $syscfg['domain'];
459
			}
460

    
461
			$hosts[] = array(
462
			    'ipaddr' => $host['ipaddr'],
463
			    'fqdn' => $fqdn . $domain,
464
			    'name' => $host['hostname'],
465
			    'domain' => $domain
466
			);
467
		}
468
	}
469
	unset($conf_dhcpd);
470

    
471
	if (is_array($config['dhcpdv6'])) {
472
		$conf_dhcpdv6 = $config['dhcpdv6'];
473
	} else {
474
		$conf_dhcpdv6 = array();
475
	}
476

    
477
	foreach ($conf_dhcpdv6 as $dhcpif => $dhcpifconf) {
478
		if (!is_array($dhcpifconf['staticmap']) ||
479
		    !isset($dhcpifconf['enable'])) {
480
			continue;
481
		}
482

    
483
		if (isset($config['interfaces'][$dhcpif]['ipaddrv6']) &&
484
		    $config['interfaces'][$dhcpif]['ipaddrv6'] ==
485
		    'track6') {
486
			$isdelegated = true;
487
		} else {
488
			$isdelegated = false;
489
		}
490

    
491
		foreach ($dhcpifconf['staticmap'] as $host) {
492
			$ipaddrv6 = $host['ipaddrv6'];
493

    
494
			if (!$ipaddrv6 || !$host['hostname']) {
495
				continue;
496
			}
497

    
498
			if ($isdelegated) {
499
				/*
500
				 * We are always in an "end-user" subnet
501
				 * here, which all are /64 for IPv6.
502
				 */
503
				$prefix6 = 64;
504
			} else {
505
				$prefix6 = get_interface_subnetv6($dhcpif);
506
			}
507
			$ipaddrv6 = merge_ipv6_delegated_prefix(get_interface_ipv6($dhcpif), $ipaddrv6, $prefix6);
508

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

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

    
529
	return $hosts;
530
}
531

    
532
/* Concatenate local, dnsmasq/unbound and dhcpd/dhcpdv6 hosts entries */
533
function system_hosts_entries($dnscfg) {
534
	$local = array();
535
	if (!isset($dnscfg['disable_auto_added_host_entries'])) {
536
		$local = system_hosts_local_entries();
537
	}
538

    
539
	$dns = array();
540
	$dhcpd = array();
541
	if (isset($dnscfg['enable'])) {
542
		$dns = system_hosts_override_entries($dnscfg);
543
		if (isset($dnscfg['regdhcpstatic'])) {
544
			$dhcpd = system_hosts_dhcpd_entries();
545
		}
546
	}
547

    
548
	if (isset($dnscfg['dhcpfirst'])) {
549
		return array_merge($local, $dns, $dhcpd);
550
	} else {
551
		return array_merge($local, $dhcpd, $dns);
552
	}
553
}
554

    
555
function system_hosts_generate() {
556
	global $config, $g;
557
	if (isset($config['system']['developerspew'])) {
558
		$mt = microtime();
559
		echo "system_hosts_generate() being called $mt\n";
560
	}
561

    
562
	// prefer dnsmasq for hosts generation where it's enabled. It relies
563
	// on hosts for name resolution of its overrides, unbound does not.
564
	if (isset($config['dnsmasq']) && isset($config['dnsmasq']['enable'])) {
565
		$dnsmasqcfg = $config['dnsmasq'];
566
	} else {
567
		$dnsmasqcfg = $config['unbound'];
568
	}
569

    
570
	$syscfg = $config['system'];
571
	$hosts = "";
572
	$lhosts = "";
573
	$dhosts = "";
574

    
575
	$hosts_array = system_hosts_entries($dnsmasqcfg);
576
	foreach ($hosts_array as $host) {
577
		$hosts .= "{$host['ipaddr']}\t";
578
		if ($host['name'] == "localhost") {
579
			$hosts .= "{$host['name']} {$host['fqdn']}";
580
		} else {
581
			$hosts .= "{$host['fqdn']} {$host['name']}";
582
		}
583
		$hosts .= "\n";
584
	}
585
	unset($hosts_array);
586

    
587
	/*
588
	 * Do not remove this because dhcpleases monitors with kqueue it needs
589
	 * to be killed before writing to hosts files.
590
	 */
591
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
592
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
593
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
594
	}
595

    
596
	$fd = fopen("{$g['etc_path']}/hosts", "w");
597
	if (!$fd) {
598
		log_error(gettext(
599
		    "Error: cannot open hosts file in system_hosts_generate()."
600
		    ));
601
		return 1;
602
	}
603

    
604
	fwrite($fd, $hosts);
605
	fclose($fd);
606

    
607
	if (isset($config['unbound']['enable'])) {
608
		require_once("unbound.inc");
609
		unbound_hosts_generate();
610
	}
611

    
612
	/* restart dhcpleases */
613
	if (!platform_booting()) {
614
		system_dhcpleases_configure();
615
	}
616

    
617
	return 0;
618
}
619

    
620
function system_dhcpleases_configure() {
621
	global $config, $g;
622
	if (!function_exists('is_dhcp_server_enabled')) {
623
		require_once('pfsense-utils.inc');
624
	}
625
	$pidfile = "{$g['varrun_path']}/dhcpleases.pid";
626

    
627
	/* Start the monitoring process for dynamic dhcpclients. */
628
	if (((isset($config['dnsmasq']['enable']) && isset($config['dnsmasq']['regdhcp'])) ||
629
	    (isset($config['unbound']['enable']) && isset($config['unbound']['regdhcp']))) &&
630
	    (is_dhcp_server_enabled())) {
631
		/* Make sure we do not error out */
632
		mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db");
633
		if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
634
			@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
635
		}
636

    
637
		if (isset($config['unbound']['enable'])) {
638
			$dns_pid = "unbound.pid";
639
			$unbound_conf = "-u {$g['unbound_chroot_path']}/dhcpleases_entries.conf";
640
		} else {
641
			$dns_pid = "dnsmasq.pid";
642
			$unbound_conf = "";
643
		}
644

    
645
		if (isvalidpid($pidfile)) {
646
			/* Make sure dhcpleases is using correct unbound or dnsmasq */
647
			$_gb = exec("/bin/pgrep -F {$pidfile} -f {$dns_pid}", $output, $retval);
648
			if (intval($retval) == 0) {
649
				sigkillbypid($pidfile, "HUP");
650
				return;
651
			} else {
652
				sigkillbypid($pidfile, "TERM");
653
			}
654
		}
655

    
656
		/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
657
		if (is_process_running("dhcpleases")) {
658
			sigkillbyname('dhcpleases', "TERM");
659
		}
660
		@unlink($pidfile);
661
		mwexec("/usr/local/sbin/dhcpleases -l {$g['dhcpd_chroot_path']}/var/db/dhcpd.leases -d {$config['system']['domain']} -p {$g['varrun_path']}/{$dns_pid} {$unbound_conf} -h {$g['etc_path']}/hosts");
662
	} else {
663
		if (isvalidpid($pidfile)) {
664
			sigkillbypid($pidfile, "TERM");
665
			@unlink($pidfile);
666
		}
667
		if (file_exists("{$g['unbound_chroot_path']}/dhcpleases_entries.conf")) {
668
			$dhcpleases = fopen("{$g['unbound_chroot_path']}/dhcpleases_entries.conf", "w");
669
			ftruncate($dhcpleases, 0);
670
			fclose($dhcpleases);
671
		}
672
	}
673
}
674

    
675
function system_get_dhcpleases($dnsavailable=null) {
676
	global $config, $g;
677

    
678
	$leases = array();
679
	$leases['lease'] = array();
680
	$leases['failover'] = array();
681

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

    
684
	if (!file_exists($leases_file)) {
685
		return $leases;
686
	}
687

    
688
	$leases_content = file($leases_file, FILE_IGNORE_NEW_LINES |
689
	    FILE_IGNORE_NEW_LINES);
690

    
691
	if ($leases_content === FALSE) {
692
		return $leases;
693
	}
694

    
695
	$arp_table = system_get_arp_table();
696

    
697
	$arpdata_ip = array();
698
	$arpdata_mac = array();
699
	foreach ($arp_table as $arp_entry) {
700
		if (isset($arpentry['incomplete'])) {
701
			continue;
702
		}
703
		$arpdata_ip[] = $arp_entry['ip-address'];
704
		$arpdata_mac[] = $arp_entry['mac-address'];
705
	}
706
	unset($arp_table);
707

    
708
	/*
709
	 * Translate these once so we don't do it over and over in the loops
710
	 * below.
711
	 */
712
	$online_string = gettext("online");
713
	$offline_string = gettext("offline");
714
	$active_string = gettext("active");
715
	$expired_string = gettext("expired");
716
	$reserved_string = gettext("reserved");
717
	$dynamic_string = gettext("dynamic");
718
	$static_string = gettext("static");
719

    
720
	$lease_regex = '/^lease\s+([^\s]+)\s+{$/';
721
	$starts_regex = '/^\s*(starts|ends)\s+\d+\s+([\d\/]+|never)\s*(|[\d:]*);$/';
722
	$binding_regex = '/^\s*binding\s+state\s+(.+);$/';
723
	$mac_regex = '/^\s*hardware\s+ethernet\s+(.+);$/';
724
	$hostname_regex = '/^\s*client-hostname\s+"(.+)";$/';
725

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

    
729
	$lease = false;
730
	$failover = false;
731
	$dedup_lease = false;
732
	$dedup_failover = false;
733

    
734
	foreach ($leases_content as $line) {
735
		/* Skip comments */
736
		if (preg_match('/^\s*(|#.*)$/', $line)) {
737
			continue;
738
		}
739

    
740
		if (preg_match('/}$/', $line)) {
741
			if ($lease) {
742
				if (empty($item['hostname'])) {
743
					if (is_null($dnsavailable)) {
744
						$dnsavailable = check_dnsavailable();
745
					}
746
					if ($dnsavailable) {
747
						$hostname = gethostbyaddr($item['ip']);
748
						if (!empty($hostname)) {
749
							$item['hostname'] = $hostname;
750
						}
751
					}
752
				}
753
				$leases['lease'][] = $item;
754
				$lease = false;
755
				$dedup_lease = true;
756
			} else if ($failover) {
757
				$leases['failover'][] = $item;
758
				$failover = false;
759
				$dedup_failover = true;
760
			}
761
			continue;
762
		}
763

    
764
		if (preg_match($lease_regex, $line, $m)) {
765
			$lease = true;
766
			$item = array();
767
			$item['ip'] = $m[1];
768
			$item['type'] = $dynamic_string;
769
			continue;
770
		}
771

    
772
		if ($lease) {
773
			if (preg_match($starts_regex, $line, $m)) {
774
				/*
775
				 * Quote from dhcpd.leases(5) man page:
776
				 * If a lease will never expire, date is never
777
				 * instead of an actual date
778
				 */
779
				if ($m[2] == "never") {
780
					$item[$m[1]] = gettext("Never");
781
				} else {
782
					$item[$m[1]] = dhcpd_date_adjust_gmt(
783
					    $m[2] . ' ' . $m[3]);
784
				}
785
				continue;
786
			}
787

    
788
			if (preg_match($binding_regex, $line, $m)) {
789
				switch ($m[1]) {
790
					case "active":
791
						$item['act'] = $active_string;
792
						break;
793
					case "free":
794
						$item['act'] = $expired_string;
795
						$item['online'] =
796
						    $offline_string;
797
						break;
798
					case "backup":
799
						$item['act'] = $reserved_string;
800
						$item['online'] =
801
						    $offline_string;
802
						break;
803
				}
804
				continue;
805
			}
806

    
807
			if (preg_match($mac_regex, $line, $m) &&
808
			    is_macaddr($m[1])) {
809
				$item['mac'] = $m[1];
810

    
811
				if (in_array($item['ip'], $arpdata_ip)) {
812
					$item['online'] = $online_string;
813
				} else {
814
					$item['online'] = $offline_string;
815
				}
816
				continue;
817
			}
818

    
819
			if (preg_match($hostname_regex, $line, $m)) {
820
				$item['hostname'] = $m[1];
821
			}
822
		}
823

    
824
		if (preg_match($failover_regex, $line, $m)) {
825
			$failover = true;
826
			$item = array();
827
			$item['name'] = $m[1] . ' (' .
828
			    convert_friendly_interface_to_friendly_descr(
829
			    substr($m[1],5)) . ')';
830
			continue;
831
		}
832

    
833
		if ($failover && preg_match($state_regex, $line, $m)) {
834
			$item[$m[1] . 'state'] = $m[2];
835
			$item[$m[1] . 'date'] = dhcpd_date_adjust_gmt($m[3] .
836
			    ' ' . $m[4]);
837
			continue;
838
		}
839
	}
840

    
841
	foreach ($config['interfaces'] as $ifname => $ifarr) {
842
		if (!is_array($config['dhcpd'][$ifname]) ||
843
		    !is_array($config['dhcpd'][$ifname]['staticmap'])) {
844
			continue;
845
		}
846

    
847
		foreach ($config['dhcpd'][$ifname]['staticmap'] as $idx =>
848
		    $static) {
849
			if (empty($static['mac']) && empty($static['cid'])) {
850
				continue;
851
			}
852

    
853
			$slease = array();
854
			$slease['ip'] = $static['ipaddr'];
855
			$slease['type'] = $static_string;
856
			if (!empty($static['cid'])) {
857
				$slease['cid'] = $static['cid'];
858
			}
859
			$slease['mac'] = $static['mac'];
860
			$slease['if'] = $ifname;
861
			$slease['starts'] = "";
862
			$slease['ends'] = "";
863
			$slease['hostname'] = $static['hostname'];
864
			$slease['descr'] = $static['descr'];
865
			$slease['act'] = $static_string;
866
			$slease['online'] = in_array(strtolower($slease['mac']),
867
			    $arpdata_mac) ? $online_string : $offline_string;
868
			$slease['staticmap_array_index'] = $idx;
869
			$leases['lease'][] = $slease;
870
			$dedup_lease = true;
871
		}
872
	}
873

    
874
	if ($dedup_lease) {
875
		$leases['lease'] = array_remove_duplicate($leases['lease'],
876
		    'ip');
877
	}
878
	if ($dedup_failover) {
879
		$leases['failover'] = array_remove_duplicate(
880
		    $leases['failover'], 'name');
881
		asort($leases['failover']);
882
	}
883

    
884
	return $leases;
885
}
886

    
887
function system_hostname_configure() {
888
	global $config, $g;
889
	if (isset($config['system']['developerspew'])) {
890
		$mt = microtime();
891
		echo "system_hostname_configure() being called $mt\n";
892
	}
893

    
894
	$syscfg = $config['system'];
895

    
896
	/* set hostname */
897
	$status = mwexec("/bin/hostname " .
898
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
899

    
900
	/* Setup host GUID ID.  This is used by ZFS. */
901
	mwexec("/etc/rc.d/hostid start");
902

    
903
	return $status;
904
}
905

    
906
function system_routing_configure($interface = "") {
907
	global $config, $g;
908

    
909
	if (isset($config['system']['developerspew'])) {
910
		$mt = microtime();
911
		echo "system_routing_configure() being called $mt\n";
912
	}
913

    
914
	$gateways_arr = return_gateways_array(false, true);
915
	foreach ($gateways_arr as $gateway) {
916
		// setup static interface routes for nonlocal gateways
917
		if (isset($gateway["nonlocalgateway"])) {
918
			$srgatewayip = $gateway['gateway'];
919
			$srinterfacegw = $gateway['interface'];
920
			if (is_ipaddr($srgatewayip) && !empty($srinterfacegw)) {
921
				route_add_or_change($srgatewayip, '',
922
				    $srinterfacegw);
923
			}
924
		}
925
	}
926

    
927
	$gateways_status = return_gateways_status(true);
928
	fixup_default_gateway("inet", $gateways_status, $gateways_arr);
929
	fixup_default_gateway("inet6", $gateways_status, $gateways_arr);
930

    
931
	system_staticroutes_configure($interface, false);
932

    
933
	return 0;
934
}
935

    
936
function system_staticroutes_configure($interface = "", $update_dns = false) {
937
	global $config, $g, $aliastable;
938

    
939
	$filterdns_list = array();
940

    
941
	$static_routes = get_staticroutes(false, true);
942
	if (count($static_routes)) {
943
		$gateways_arr = return_gateways_array(false, true);
944

    
945
		foreach ($static_routes as $rtent) {
946
			/* Do not delete disabled routes,
947
			 * see https://redmine.pfsense.org/issues/3709 
948
			 * and https://redmine.pfsense.org/issues/10706 */
949
			if (isset($rtent['disabled'])) {
950
				continue;
951
			}
952

    
953
			if (empty($gateways_arr[$rtent['gateway']])) {
954
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
955
				continue;
956
			}
957
			$gateway = $gateways_arr[$rtent['gateway']];
958
			if (!empty($interface) && $interface != $gateway['friendlyiface']) {
959
				continue;
960
			}
961

    
962
			$gatewayip = $gateway['gateway'];
963
			$interfacegw = $gateway['interface'];
964

    
965
			$blackhole = "";
966
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 4))) {
967
				$blackhole = "-blackhole";
968
			}
969

    
970
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network'])) {
971
				continue;
972
			}
973

    
974
			$dnscache = array();
975
			if ($update_dns === true) {
976
				if (is_subnet($rtent['network'])) {
977
					continue;
978
				}
979
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
980
				if (empty($dnscache)) {
981
					continue;
982
				}
983
			}
984

    
985
			if (is_subnet($rtent['network'])) {
986
				$ips = array($rtent['network']);
987
			} else {
988
				if (!isset($rtent['disabled'])) {
989
					$filterdns_list[] = $rtent['network'];
990
				}
991
				$ips = add_hostname_to_watch($rtent['network']);
992
			}
993

    
994
			foreach ($dnscache as $ip) {
995
				if (in_array($ip, $ips)) {
996
					continue;
997
				}
998
				route_del($ip);
999
			}
1000

    
1001
			if (isset($rtent['disabled'])) {
1002
				/*
1003
				 * XXX: This can break things by deleting
1004
				 * routes that shouldn't be deleted - OpenVPN,
1005
				 * dynamic routing scenarios, etc.
1006
				 * redmine #3709
1007
				 */
1008
				foreach ($ips as $ip) {
1009
					route_del($ip);
1010
				}
1011
				continue;
1012
			}
1013

    
1014
			foreach ($ips as $ip) {
1015
				if (is_ipaddrv4($ip)) {
1016
					$ip .= "/32";
1017
				}
1018
				/*
1019
				 * do NOT do the same check here on v6,
1020
				 * is_ipaddrv6 returns true when including
1021
				 * the CIDR mask. doing so breaks v6 routes
1022
				 */
1023
				if (is_subnet($ip)) {
1024
					if (is_ipaddr($gatewayip)) {
1025
						if (is_linklocal($gatewayip) == "6" &&
1026
						    !strpos($gatewayip, '%')) {
1027
							/*
1028
							 * add interface scope
1029
							 * for link local v6
1030
							 * routes
1031
							 */
1032
							$gatewayip .= "%$interfacegw";
1033
						}
1034
						route_add_or_change($ip,
1035
						    $gatewayip, '', $blackhole);
1036
					} else if (!empty($interfacegw)) {
1037
						route_add_or_change($ip,
1038
						    '', $interfacegw, $blackhole);
1039
					}
1040
				}
1041
			}
1042
		}
1043
		unset($gateways_arr);
1044

    
1045
		/* keep static routes cache,
1046
		 * see https://redmine.pfsense.org/issues/11599 */
1047
		$id = 0;
1048
		foreach ($config['staticroutes']['route'] as $sroute) {
1049
			$targets = array();
1050
			if (is_subnet($sroute['network'])) {
1051
				$targets[] = $sroute['network'];
1052
			} elseif (is_alias($sroute['network'])) {
1053
				foreach (preg_split('/\s+/', $aliastable[$sroute['network']]) as $tgt) {
1054
					if (is_ipaddrv4($tgt)) {
1055
						$tgt .= "/32";
1056
					}
1057
					if (is_ipaddrv6($tgt)) {
1058
						$tgt .= "/128";
1059
					}
1060
					if (!is_subnet($tgt)) {
1061
						continue;
1062
					}
1063
					$targets[] = $tgt;
1064
				}
1065
			}
1066
			file_put_contents("{$g['tmp_path']}/staticroute_{$id}", serialize($targets));
1067
			file_put_contents("{$g['tmp_path']}/staticroute_{$id}_gw", serialize($sroute['gateway']));
1068
			$id++;
1069
		}
1070
	}
1071
	unset($static_routes);
1072

    
1073
	if ($update_dns === false) {
1074
		if (count($filterdns_list)) {
1075
			$interval = 60;
1076
			$hostnames = "";
1077
			array_unique($filterdns_list);
1078
			foreach ($filterdns_list as $hostname) {
1079
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
1080
			}
1081
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
1082
			unset($hostnames);
1083

    
1084
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid")) {
1085
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
1086
			} else {
1087
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
1088
			}
1089
		} else {
1090
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
1091
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
1092
		}
1093
	}
1094
	unset($filterdns_list);
1095

    
1096
	return 0;
1097
}
1098

    
1099
function delete_static_route($id, $delete = false) {
1100
	global $g, $config, $changedesc_prefix, $a_gateways;
1101

    
1102
	if (!isset($config['staticroutes']['route'][$id])) {
1103
		return;
1104
	}
1105

    
1106
	if (file_exists("{$g['tmp_path']}/.system_routes.apply")) {
1107
		$toapplylist = unserialize(file_get_contents("{$g['tmp_path']}/.system_routes.apply"));
1108
	} else {
1109
		$toapplylist = array();
1110
	}
1111

    
1112
	if (file_exists("{$g['tmp_path']}/staticroute_{$id}") &&
1113
	    file_exists("{$g['tmp_path']}/staticroute_{$id}_gw")) {
1114
		$delete_targets = unserialize(file_get_contents("{$g['tmp_path']}/staticroute_{$id}"));
1115
		$delgw = lookup_gateway_ip_by_name(unserialize(file_get_contents("{$g['tmp_path']}/staticroute_{$id}_gw")));
1116
		if (count($delete_targets)) {
1117
			foreach ($delete_targets as $dts) {
1118
				if (is_subnetv4($dts)) {
1119
					$family = "-inet";
1120
				} else {
1121
					$family = "-inet6";
1122
				}
1123
				$route = route_get($dts, '', true);
1124
				if (!count($route)) {
1125
					continue;
1126
				}
1127
				$toapplylist[] = "/sbin/route delete " .
1128
				    $family . " " . $dts . " " . $delgw;
1129
			}
1130
		}
1131
	}
1132

    
1133
	if ($delete) {
1134
		unlink_if_exists("{$g['tmp_path']}/staticroute_{$id}");
1135
		unlink_if_exists("{$g['tmp_path']}/staticroute_{$id}_gw");
1136
	}
1137

    
1138
	if (!empty($toapplylist)) {
1139
		file_put_contents("{$g['tmp_path']}/.system_routes.apply", serialize($toapplylist));
1140
	}
1141

    
1142
	unset($targets);
1143
}
1144

    
1145
function system_routing_enable() {
1146
	global $config, $g;
1147
	if (isset($config['system']['developerspew'])) {
1148
		$mt = microtime();
1149
		echo "system_routing_enable() being called $mt\n";
1150
	}
1151

    
1152
	set_sysctl(array(
1153
		"net.inet.ip.forwarding" => "1",
1154
		"net.inet6.ip6.forwarding" => "1"
1155
	));
1156

    
1157
	return;
1158
}
1159

    
1160
function system_webgui_create_certificate() {
1161
	global $config, $g, $cert_strict_values;
1162

    
1163
	init_config_arr(array('ca'));
1164
	$a_ca = &$config['ca'];
1165
	init_config_arr(array('cert'));
1166
	$a_cert = &$config['cert'];
1167
	log_error(gettext("Creating SSL/TLS Certificate for this host"));
1168

    
1169
	$cert = array();
1170
	$cert['refid'] = uniqid();
1171
	$cert['descr'] = sprintf(gettext("webConfigurator default (%s)"), $cert['refid']);
1172
	$cert_hostname = "{$config['system']['hostname']}-{$cert['refid']}";
1173

    
1174
	$dn = array(
1175
		'organizationName' => "{$g['product_label']} webConfigurator Self-Signed Certificate",
1176
		'commonName' => $cert_hostname,
1177
		'subjectAltName' => "DNS:{$cert_hostname}");
1178
	$old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warnings directly to a page screwing menu tab */
1179
	if (!cert_create($cert, null, 2048, $cert_strict_values['max_server_cert_lifetime'], $dn, "self-signed", "sha256")) {
1180
		while ($ssl_err = openssl_error_string()) {
1181
			log_error(sprintf(gettext("Error creating WebGUI Certificate: openssl library returns: %s"), $ssl_err));
1182
		}
1183
		error_reporting($old_err_level);
1184
		return null;
1185
	}
1186
	error_reporting($old_err_level);
1187

    
1188
	$a_cert[] = $cert;
1189
	$config['system']['webgui']['ssl-certref'] = $cert['refid'];
1190
	write_config(sprintf(gettext("Generated new self-signed SSL/TLS certificate for HTTPS (%s)"), $cert['refid']));
1191
	return $cert;
1192
}
1193

    
1194
function system_webgui_start() {
1195
	global $config, $g;
1196

    
1197
	if (platform_booting()) {
1198
		echo gettext("Starting webConfigurator...");
1199
	}
1200

    
1201
	chdir($g['www_path']);
1202

    
1203
	/* defaults */
1204
	$portarg = "80";
1205
	$crt = "";
1206
	$key = "";
1207
	$ca = "";
1208

    
1209
	/* non-standard port? */
1210
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "") {
1211
		$portarg = "{$config['system']['webgui']['port']}";
1212
	}
1213

    
1214
	if ($config['system']['webgui']['protocol'] == "https") {
1215
		// Ensure that we have a webConfigurator CERT
1216
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
1217
		if (!is_array($cert) || !$cert['crt'] || !$cert['prv']) {
1218
			$cert = system_webgui_create_certificate();
1219
		}
1220
		$crt = base64_decode($cert['crt']);
1221
		$key = base64_decode($cert['prv']);
1222

    
1223
		if (!$config['system']['webgui']['port']) {
1224
			$portarg = "443";
1225
		}
1226
		$ca = ca_chain($cert);
1227
		$hsts = isset($config['system']['webgui']['disablehsts']) ? false : true;
1228
	}
1229

    
1230
	/* generate nginx configuration */
1231
	system_generate_nginx_config("{$g['varetc_path']}/nginx-webConfigurator.conf",
1232
		$crt, $key, $ca, "nginx-webConfigurator.pid", $portarg, "/usr/local/www/",
1233
		"cert.crt", "cert.key", false, $hsts);
1234

    
1235
	/* kill any running nginx */
1236
	killbypid("{$g['varrun_path']}/nginx-webConfigurator.pid");
1237

    
1238
	sleep(1);
1239

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

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

    
1245
	if (platform_booting()) {
1246
		if ($res == 0) {
1247
			echo gettext("done.") . "\n";
1248
		} else {
1249
			echo gettext("failed!") . "\n";
1250
		}
1251
	}
1252

    
1253
	return $res;
1254
}
1255

    
1256
/****f* system.inc/get_dns_nameservers
1257
 * NAME
1258
 *   get_dns_nameservers - Get system DNS servers
1259
 * INPUTS
1260
 *   $add_v6_brackets: (boolean, false)
1261
 *                     Add brackets around IPv6 DNS servers, as expected by some
1262
 *                     daemons such as nginx.
1263
 *   $hostns         : (boolean, true)
1264
 *                     true : Return only DNS servers used by the firewall
1265
 *                            itself as upstream forwarding servers
1266
 *                     false: Return all DNS servers from the configuration and
1267
 *                            overrides (if allowed).
1268
 * RESULT
1269
 *   $dns_nameservers - An array of the requested DNS servers
1270
 ******/
1271
function get_dns_nameservers($add_v6_brackets = false, $hostns=true) {
1272
	global $config;
1273

    
1274
	$dns_nameservers = array();
1275

    
1276
	if (isset($config['system']['developerspew'])) {
1277
		$mt = microtime();
1278
		echo "get_dns_nameservers() being called $mt\n";
1279
	}
1280

    
1281
	$syscfg = $config['system'];
1282
	if ((((isset($config['dnsmasq']['enable'])) &&
1283
	    (empty($config['dnsmasq']['port']) || $config['dnsmasq']['port'] == "53") &&
1284
	    (empty($config['dnsmasq']['interface']) ||
1285
	    in_array("lo0", explode(",", $config['dnsmasq']['interface'])))) ||
1286
	    ((isset($config['unbound']['enable'])) &&
1287
	    (empty($config['unbound']['port']) || $config['unbound']['port'] == "53") &&
1288
	    (empty($config['unbound']['active_interface']) ||
1289
	    in_array("lo0", explode(",", $config['unbound']['active_interface'])) ||
1290
	    in_array("all", explode(",", $config['unbound']['active_interface']), true)))) &&
1291
	    ($config['system']['dnslocalhost'] != 'remote')) {
1292
		$dns_nameservers[] = "127.0.0.1";
1293
	}
1294

    
1295
	if ($hostns || ($config['system']['dnslocalhost'] != 'local')) {
1296
		if (isset($syscfg['dnsallowoverride'])) {
1297
			/* get dynamically assigned DNS servers (if any) */
1298
			foreach (array_unique(get_dynamic_nameservers()) as $nameserver) {
1299
				if ($nameserver) {
1300
					if ($add_v6_brackets && is_ipaddrv6($nameserver)) {
1301
						$nameserver = "[{$nameserver}]";
1302
					}
1303
					$dns_nameservers[] = $nameserver;
1304
				}
1305
			}
1306
		}
1307
		if (is_array($syscfg['dnsserver'])) {
1308
			foreach ($syscfg['dnsserver'] as $sys_dnsserver) {
1309
				if ($sys_dnsserver && (!in_array($sys_dnsserver, $dns_nameservers))) {
1310
					if ($add_v6_brackets && is_ipaddrv6($sys_dnsserver)) {
1311
						$sys_dnsserver = "[{$sys_dnsserver}]";
1312
					}
1313
					$dns_nameservers[] = $sys_dnsserver;
1314
				}
1315
			}
1316
		}
1317
	}
1318
	return array_unique($dns_nameservers);
1319
}
1320

    
1321
function system_generate_nginx_config($filename,
1322
	$cert,
1323
	$key,
1324
	$ca,
1325
	$pid_file,
1326
	$port = 80,
1327
	$document_root = "/usr/local/www/",
1328
	$cert_location = "cert.crt",
1329
	$key_location = "cert.key",
1330
	$captive_portal = false,
1331
	$hsts = true) {
1332

    
1333
	global $config, $g;
1334

    
1335
	if (isset($config['system']['developerspew'])) {
1336
		$mt = microtime();
1337
		echo "system_generate_nginx_config() being called $mt\n";
1338
	}
1339

    
1340
	if ($captive_portal !== false) {
1341
		$cp_interfaces = explode(",", $config['captiveportal'][$captive_portal]['interface']);
1342
		$cp_hostcheck = "";
1343
		foreach ($cp_interfaces as $cpint) {
1344
			$cpint_ip = get_interface_ip($cpint);
1345
			if (is_ipaddr($cpint_ip)) {
1346
				$cp_hostcheck .= "\t\tif (\$http_host ~* $cpint_ip) {\n";
1347
				$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1348
				$cp_hostcheck .= "\t\t}\n";
1349
			}
1350
		}
1351
		if (isset($config['captiveportal'][$captive_portal]['httpsname']) &&
1352
		    is_domain($config['captiveportal'][$captive_portal]['httpsname'])) {
1353
			$cp_hostcheck .= "\t\tif (\$http_host ~* {$config['captiveportal'][$captive_portal]['httpsname']}) {\n";
1354
			$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1355
			$cp_hostcheck .= "\t\t}\n";
1356
		}
1357
		$cp_rewrite = "\t\tif (\$cp_redirect = '') {\n";
1358
		$cp_rewrite .= "\t\t\trewrite	^ /index.php?zone=$captive_portal&redirurl=\$request_uri break;\n";
1359
		$cp_rewrite .= "\t\t}\n";
1360

    
1361
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1362
		if (empty($maxprocperip)) {
1363
			$maxprocperip = 10;
1364
		}
1365
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1366
	}
1367

    
1368
	if (empty($port)) {
1369
		$nginx_port = "80";
1370
	} else {
1371
		$nginx_port = $port;
1372
	}
1373

    
1374
	$memory = get_memory();
1375
	$realmem = $memory[1];
1376

    
1377
	// Determine web GUI process settings and take into account low memory systems
1378
	if ($realmem < 255) {
1379
		$max_procs = 1;
1380
	} else {
1381
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
1382
	}
1383

    
1384
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM
1385
	if ($captive_portal !== false) {
1386
		if ($realmem > 135 and $realmem < 256) {
1387
			$max_procs += 1; // 2 worker processes
1388
		} else if ($realmem > 255 and $realmem < 513) {
1389
			$max_procs += 2; // 3 worker processes
1390
		} else if ($realmem > 512) {
1391
			$max_procs += 4; // 6 worker processes
1392
		}
1393
	}
1394

    
1395
	$nginx_config = <<<EOD
1396
#
1397
# nginx configuration file
1398

    
1399
pid {$g['varrun_path']}/{$pid_file};
1400

    
1401
user  root wheel;
1402
worker_processes  {$max_procs};
1403

    
1404
EOD;
1405

    
1406
	/* Disable file logging */
1407
	$nginx_config .= "error_log /dev/null;\n";
1408
	if (!isset($config['syslog']['nolognginx'])) {
1409
		/* Send nginx error log to syslog */
1410
		$nginx_config .= "error_log  syslog:server=unix:/var/run/log,facility=local5;\n";
1411
	}
1412

    
1413
	$nginx_config .= <<<EOD
1414

    
1415
events {
1416
    worker_connections  1024;
1417
}
1418

    
1419
http {
1420
	include       /usr/local/etc/nginx/mime.types;
1421
	default_type  application/octet-stream;
1422
	add_header X-Frame-Options SAMEORIGIN;
1423
	server_tokens off;
1424

    
1425
	sendfile        on;
1426

    
1427
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1428

    
1429
EOD;
1430

    
1431
	if ($captive_portal !== false) {
1432
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1433
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1434
	} else {
1435
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1436
	}
1437

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

    
1478
	$nginx_config .= <<<EOD
1479

    
1480
		client_max_body_size 200m;
1481

    
1482
		gzip on;
1483
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
1484

    
1485

    
1486
EOD;
1487

    
1488
	if ($captive_portal !== false) {
1489
		$nginx_config .= <<<EOD
1490
$captive_portal_maxprocperip
1491
$cp_hostcheck
1492
$cp_rewrite
1493
		log_not_found off;
1494

    
1495
EOD;
1496

    
1497
	}
1498

    
1499
	$nginx_config .= <<<EOD
1500
		root "{$document_root}";
1501
		location / {
1502
			index  index.php index.html index.htm;
1503
		}
1504
		location ~ \.inc$ {
1505
			deny all;
1506
			return 403;
1507
		}
1508
		location ~ \.php$ {
1509
			try_files \$uri =404; #  This line closes a potential security hole
1510
			# ensuring users can't execute uploaded files
1511
			# see: http://forum.nginx.org/read.php?2,88845,page=3
1512
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1513
			fastcgi_index  index.php;
1514
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1515
			# Fix httpoxy - https://httpoxy.org/#fix-now
1516
			fastcgi_param  HTTP_PROXY  "";
1517
			fastcgi_read_timeout 180;
1518
			include        /usr/local/etc/nginx/fastcgi_params;
1519
		}
1520
		location ~ (^/status$) {
1521
			allow 127.0.0.1;
1522
			deny all;
1523
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1524
			fastcgi_index  index.php;
1525
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1526
			# Fix httpoxy - https://httpoxy.org/#fix-now
1527
			fastcgi_param  HTTP_PROXY  "";
1528
			fastcgi_read_timeout 360;
1529
			include        /usr/local/etc/nginx/fastcgi_params;
1530
		}
1531
	}
1532

    
1533
EOD;
1534

    
1535
	$cert = str_replace("\r", "", $cert);
1536
	$key = str_replace("\r", "", $key);
1537

    
1538
	$cert = str_replace("\n\n", "\n", $cert);
1539
	$key = str_replace("\n\n", "\n", $key);
1540

    
1541
	if ($cert <> "" and $key <> "") {
1542
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1543
		if (!$fd) {
1544
			printf(gettext("Error: cannot open certificate file in system_webgui_start().%s"), "\n");
1545
			return 1;
1546
		}
1547
		chmod("{$g['varetc_path']}/{$cert_location}", 0644);
1548
		if ($ca <> "") {
1549
			$cert_chain = $cert . "\n" . $ca;
1550
		} else {
1551
			$cert_chain = $cert;
1552
		}
1553
		fwrite($fd, $cert_chain);
1554
		fclose($fd);
1555
		$fd = fopen("{$g['varetc_path']}/{$key_location}", "w");
1556
		if (!$fd) {
1557
			printf(gettext("Error: cannot open certificate key file in system_webgui_start().%s"), "\n");
1558
			return 1;
1559
		}
1560
		chmod("{$g['varetc_path']}/{$key_location}", 0600);
1561
		fwrite($fd, $key);
1562
		fclose($fd);
1563
	}
1564

    
1565
	// Add HTTP to HTTPS redirect
1566
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1567
		if ($nginx_port != "443") {
1568
			$redirectport = ":{$nginx_port}";
1569
		}
1570
		$nginx_config .= <<<EOD
1571
	server {
1572
		listen 80;
1573
		listen [::]:80;
1574
		return 301 https://\$http_host$redirectport\$request_uri;
1575
	}
1576

    
1577
EOD;
1578
	}
1579

    
1580
	$nginx_config .= "}\n";
1581

    
1582
	$fd = fopen("{$filename}", "w");
1583
	if (!$fd) {
1584
		printf(gettext('Error: cannot open %1$s in system_generate_nginx_config().%2$s'), $filename, "\n");
1585
		return 1;
1586
	}
1587
	fwrite($fd, $nginx_config);
1588
	fclose($fd);
1589

    
1590
	/* nginx will fail to start if this directory does not exist. */
1591
	safe_mkdir("/var/tmp/nginx/");
1592

    
1593
	return 0;
1594

    
1595
}
1596

    
1597
function system_get_timezone_list() {
1598
	global $g;
1599

    
1600
	$file_list = array_merge(
1601
		glob("/usr/share/zoneinfo/[A-Z]*"),
1602
		glob("/usr/share/zoneinfo/*/*"),
1603
		glob("/usr/share/zoneinfo/*/*/*")
1604
	);
1605

    
1606
	if (empty($file_list)) {
1607
		$file_list[] = $g['default_timezone'];
1608
	} else {
1609
		/* Remove directories from list */
1610
		$file_list = array_filter($file_list, function($v) {
1611
			return !is_dir($v);
1612
		});
1613
	}
1614

    
1615
	/* Remove directory prefix */
1616
	$file_list = str_replace('/usr/share/zoneinfo/', '', $file_list);
1617

    
1618
	sort($file_list);
1619

    
1620
	return $file_list;
1621
}
1622

    
1623
function system_timezone_configure() {
1624
	global $config, $g;
1625
	if (isset($config['system']['developerspew'])) {
1626
		$mt = microtime();
1627
		echo "system_timezone_configure() being called $mt\n";
1628
	}
1629

    
1630
	$syscfg = $config['system'];
1631

    
1632
	if (platform_booting()) {
1633
		echo gettext("Setting timezone...");
1634
	}
1635

    
1636
	/* extract appropriate timezone file */
1637
	$timezone = (isset($syscfg['timezone']) ? $syscfg['timezone'] : $g['default_timezone']);
1638
	/* DO NOT remove \n otherwise tzsetup will fail */
1639
	@file_put_contents("/var/db/zoneinfo", $timezone . "\n");
1640
	mwexec("/usr/sbin/tzsetup -r");
1641

    
1642
	if (platform_booting()) {
1643
		echo gettext("done.") . "\n";
1644
	}
1645
}
1646

    
1647
function check_gps_speed($device) {
1648
	usleep(1000);
1649
	// Set timeout to 5s
1650
	$timeout=microtime(true)+5;
1651
	if ($fp = fopen($device, 'r')) {
1652
		stream_set_blocking($fp, 0);
1653
		stream_set_timeout($fp, 5);
1654
		$contents = "";
1655
		$cnt = 0;
1656
		$buffersize = 256;
1657
		do {
1658
			$c = fread($fp, $buffersize - $cnt);
1659

    
1660
			// Wait for data to arive
1661
			if (($c === false) || (strlen($c) == 0)) {
1662
				usleep(500);
1663
				continue;
1664
			}
1665

    
1666
			$contents.=$c;
1667
			$cnt = $cnt + strlen($c);
1668
		} while (($cnt < $buffersize) && (microtime(true) < $timeout));
1669
		fclose($fp);
1670

    
1671
		$nmeasentences = ['RMC', 'GGA', 'GLL', 'ZDA', 'ZDG', 'PGRMF'];
1672
		foreach ($nmeasentences as $sentence) {
1673
			if (strpos($contents, $sentence) > 0) {
1674
				return true;
1675
			}
1676
		}
1677
		if (strpos($contents, '0') > 0) {
1678
			$filters = ['`', '?', '/', '~'];
1679
			foreach ($filters as $filter) {
1680
				if (strpos($contents, $filter) !== false) {
1681
					return false;
1682
				}
1683
			}
1684
			return true;
1685
		}
1686
	}
1687
	return false;
1688
}
1689

    
1690
/* Generate list of possible NTP poll values
1691
 * https://redmine.pfsense.org/issues/9439 */
1692
global $ntp_poll_min_value, $ntp_poll_max_value;
1693
global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
1694
global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
1695
global $ntp_poll_min_default, $ntp_poll_max_default;
1696
global $ntp_auth_halgos, $ntp_server_types;
1697
$ntp_poll_min_value = 3;
1698
$ntp_poll_max_value = 17;
1699
$ntp_poll_min_default_gps = 4;
1700
$ntp_poll_max_default_gps = 4;
1701
$ntp_poll_min_default_pps = 4;
1702
$ntp_poll_max_default_pps = 4;
1703
$ntp_poll_min_default = 'omit';
1704
$ntp_poll_max_default = 9;
1705
$ntp_auth_halgos = array(
1706
	'md5' => 'MD5',
1707
	'sha1' => 'SHA1',
1708
	'sha256' => 'SHA256'
1709
);
1710
$ntp_server_types = array(
1711
	'server' => 'Server',
1712
	'pool' => 'Pool',
1713
	'peer' => 'Peer'
1714
);
1715

    
1716
function system_ntp_poll_values() {
1717
	global $ntp_poll_min_value, $ntp_poll_max_value;
1718
	$poll_values = array("" => gettext('Default'));
1719

    
1720
	for ($i = $ntp_poll_min_value; $i <= $ntp_poll_max_value; $i++) {
1721
		$sec = 2 ** $i;
1722
		$poll_values[$i] = $i . ': ' . number_format($sec) . ' ' . gettext('seconds') .
1723
					' (' . convert_seconds_to_dhms($sec) . ')';
1724
	}
1725

    
1726
	$poll_values['omit'] = gettext('Omit (Do not set)');
1727
	return $poll_values;
1728
}
1729

    
1730
function system_ntp_fixup_poll_value($type, $configvalue, $default) {
1731
	$pollstring = "";
1732

    
1733
	if (empty($configvalue)) {
1734
		$configvalue = $default;
1735
	}
1736

    
1737
	if ($configvalue != 'omit') {
1738
		$pollstring = " {$type} {$configvalue}";
1739
	}
1740

    
1741
	return $pollstring;
1742
}
1743

    
1744
function system_ntp_setup_gps($serialport) {
1745
	global $config, $g;
1746

    
1747
	if (is_array($config['ntpd']) && ($config['ntpd']['enable'] == 'disabled')) {
1748
		return false;
1749
	}
1750

    
1751
	init_config_arr(array('ntpd', 'gps'));
1752
	$serialports = get_serial_ports(true);
1753

    
1754
	if (!array_key_exists($serialport, $serialports)) {
1755
		return false;
1756
	}
1757

    
1758
	$gps_device = '/dev/gps0';
1759
	$serialport = '/dev/'.basename($serialport);
1760

    
1761
	if (!file_exists($serialport)) {
1762
		return false;
1763
	}
1764

    
1765
	// Create symlink that ntpd requires
1766
	unlink_if_exists($gps_device);
1767
	@symlink($serialport, $gps_device);
1768

    
1769
	$gpsbaud = '4800';
1770
	$speeds = array(
1771
		0 => '4800', 
1772
		16 => '9600', 
1773
		32 => '19200', 
1774
		48 => '38400', 
1775
		64 => '57600', 
1776
		80 => '115200'
1777
	);
1778
	if (!empty($config['ntpd']['gps']['speed']) && array_key_exists($config['ntpd']['gps']['speed'], $speeds)) {
1779
		$gpsbaud = $speeds[$config['ntpd']['gps']['speed']];
1780
	}
1781

    
1782
	system_ntp_setup_rawspeed($serialport, $gpsbaud);
1783

    
1784
	$autospeed = ($config['ntpd']['gps']['speed'] == 'autoalways' || $config['ntpd']['gps']['speed'] == 'autoset');
1785
	if ($autospeed || ($config['ntpd']['gps']['autobaudinit'] && !check_gps_speed($gps_device))) {
1786
		$found = false;
1787
		foreach ($speeds as $baud) {
1788
			system_ntp_setup_rawspeed($serialport, $baud);
1789
			if ($found = check_gps_speed($gps_device)) {
1790
				if ($autospeed) {
1791
					$saveconfig = ($config['ntpd']['gps']['speed'] == 'autoset');
1792
					$config['ntpd']['gps']['speed'] = array_search($baud, $speeds);
1793
					$gpsbaud = $baud;
1794
					if ($saveconfig) {
1795
						write_config(sprintf(gettext('Autoset GPS baud rate to %s'), $baud));
1796
					}
1797
				}
1798
				break;
1799
			}
1800
		}
1801
		if ($found === false) {
1802
			log_error(gettext("Could not find correct GPS baud rate."));
1803
			return false;
1804
		}
1805
	}
1806

    
1807
	/* Send the following to the GPS port to initialize the GPS */
1808
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
1809
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
1810
	} else {
1811
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1812
	}
1813

    
1814
	/* XXX: Why not file_put_contents to the device */
1815
	@file_put_contents('/tmp/gps.init', $gps_init);
1816
	mwexec("/bin/cat /tmp/gps.init > {$serialport}");
1817

    
1818
	if ($found && $config['ntpd']['gps']['autobaudinit']) {
1819
		system_ntp_setup_rawspeed($serialport, $gpsbaud);
1820
	}
1821

    
1822
	/* Remove old /etc/remote entry if it exists */
1823
	if (mwexec("/usr/bin/grep -c '^gps0' /etc/remote") == 0) {
1824
		mwexec("/usr/bin/sed -i '' -n '/gps0/!p' /etc/remote");
1825
	}
1826

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

    
1832
	return true;
1833
}
1834

    
1835
// Configure the serial port for raw IO and set the speed
1836
function system_ntp_setup_rawspeed($serialport, $baud) {
1837
	mwexec("/bin/stty -f " .  escapeshellarg($serialport) . " raw speed " . escapeshellarg($baud));
1838
	mwexec("/bin/stty -f " .  escapeshellarg($serialport) . ".init raw speed " . escapeshellarg($baud));
1839
}
1840

    
1841
function system_ntp_setup_pps($serialport) {
1842
	global $config, $g;
1843

    
1844
	$serialports = get_serial_ports(true);
1845

    
1846
	if (!array_key_exists($serialport, $serialports)) {
1847
		return false;
1848
	}
1849

    
1850
	$pps_device = '/dev/pps0';
1851
	$serialport = '/dev/'.basename($serialport);
1852

    
1853
	if (!file_exists($serialport)) {
1854
		return false;
1855
	}
1856
	// If ntpd is disabled, just return
1857
	if (is_array($config['ntpd']) && ($config['ntpd']['enable'] == 'disabled')) {
1858
		return false;
1859
	}
1860

    
1861
	// Create symlink that ntpd requires
1862
	unlink_if_exists($pps_device);
1863
	@symlink($serialport, $pps_device);
1864

    
1865

    
1866
	return true;
1867
}
1868

    
1869
function system_ntp_configure() {
1870
	global $config, $g;
1871
	global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
1872
	global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
1873
	global $ntp_poll_min_default, $ntp_poll_max_default;
1874

    
1875
	$driftfile = "/var/db/ntpd.drift";
1876
	$statsdir = "/var/log/ntp";
1877
	$gps_device = '/dev/gps0';
1878

    
1879
	safe_mkdir($statsdir);
1880

    
1881
	if (!is_array($config['ntpd'])) {
1882
		$config['ntpd'] = array();
1883
	}
1884
	// ntpd is disabled, just stop it and return
1885
	if ($config['ntpd']['enable'] == 'disabled') {
1886
		while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1887
			killbypid("{$g['varrun_path']}/ntpd.pid");
1888
		}
1889
		@unlink("{$g['varrun_path']}/ntpd.pid");
1890
		@unlink("{$g['varetc_path']}/ntpd.conf");
1891
		@unlink("{$g['varetc_path']}/ntp.keys");
1892
		log_error("NTPD is disabled.");
1893
		return;
1894
	}
1895

    
1896
	if (platform_booting()) {
1897
		echo gettext("Starting NTP Server...");
1898
	}
1899

    
1900
	/* if ntpd is running, kill it */
1901
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1902
		killbypid("{$g['varrun_path']}/ntpd.pid");
1903
	}
1904
	@unlink("{$g['varrun_path']}/ntpd.pid");
1905

    
1906
	/* set NTP server authentication key */
1907
	if ($config['ntpd']['serverauth'] == 'yes') {
1908
		$ntpkeyscfg = "1 " . strtoupper($config['ntpd']['serverauthalgo']) . " " . base64_decode($config['ntpd']['serverauthkey']) . "\n";
1909
		if (!@file_put_contents("{$g['varetc_path']}/ntp.keys", $ntpkeyscfg)) {
1910
			log_error(sprintf(gettext("Could not open %s/ntp.keys for writing"), $g['varetc_path']));
1911
			return;
1912
		}
1913
	} else {
1914
		unlink_if_exists("{$g['varetc_path']}/ntp.keys");
1915
	}
1916

    
1917
	$ntpcfg = "# \n";
1918
	$ntpcfg .= "# pfSense ntp configuration file \n";
1919
	$ntpcfg .= "# \n\n";
1920
	$ntpcfg .= "tinker panic 0 \n\n";
1921

    
1922
	if ($config['ntpd']['serverauth'] == 'yes') {
1923
		$ntpcfg .= "# Authentication settings \n";
1924
		$ntpcfg .= "keys /var/etc/ntp.keys \n";
1925
		$ntpcfg .= "trustedkey 1 \n";
1926
		$ntpcfg .= "requestkey 1 \n";
1927
		$ntpcfg .= "controlkey 1 \n";
1928
		$ntpcfg .= "\n";
1929
	}
1930

    
1931
	/* Add Orphan mode */
1932
	$ntpcfg .= "# Orphan mode stratum and Maximum candidate NTP peers\n";
1933
	$ntpcfg .= 'tos orphan ';
1934
	if (!empty($config['ntpd']['orphan'])) {
1935
		$ntpcfg .= $config['ntpd']['orphan'];
1936
	} else {
1937
		$ntpcfg .= '12';
1938
	}
1939
	/* Add Maximum candidate NTP peers */
1940
	$ntpcfg .= ' maxclock ';
1941
	if (!empty($config['ntpd']['ntpmaxpeers'])) {
1942
		$ntpcfg .= $config['ntpd']['ntpmaxpeers'];
1943
	} else {
1944
		$ntpcfg .= '5';
1945
	}
1946
	$ntpcfg .= "\n";
1947

    
1948
	/* Add PPS configuration */
1949
	if (is_array($config['ntpd']['pps']) && !empty($config['ntpd']['pps']['port']) &&
1950
	    file_exists('/dev/'.$config['ntpd']['pps']['port']) &&
1951
	    system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
1952
		$ntpcfg .= "\n";
1953
		$ntpcfg .= "# PPS Setup\n";
1954
		$ntpcfg .= 'server 127.127.22.0';
1955
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', $config['ntpd']['pps']['ppsminpoll'], $ntp_poll_min_default_pps);
1956
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', $config['ntpd']['pps']['ppsmaxpoll'], $ntp_poll_max_default_pps);
1957
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
1958
			$ntpcfg .= ' prefer';
1959
		}
1960
		if (!empty($config['ntpd']['pps']['noselect'])) {
1961
			$ntpcfg .= ' noselect ';
1962
		}
1963
		$ntpcfg .= "\n";
1964
		$ntpcfg .= 'fudge 127.127.22.0';
1965
		if (!empty($config['ntpd']['pps']['fudge1'])) {
1966
			$ntpcfg .= ' time1 ';
1967
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
1968
		}
1969
		if (!empty($config['ntpd']['pps']['flag2'])) {
1970
			$ntpcfg .= ' flag2 1';
1971
		}
1972
		if (!empty($config['ntpd']['pps']['flag3'])) {
1973
			$ntpcfg .= ' flag3 1';
1974
		} else {
1975
			$ntpcfg .= ' flag3 0';
1976
		}
1977
		if (!empty($config['ntpd']['pps']['flag4'])) {
1978
			$ntpcfg .= ' flag4 1';
1979
		}
1980
		if (!empty($config['ntpd']['pps']['refid'])) {
1981
			$ntpcfg .= ' refid ';
1982
			$ntpcfg .= $config['ntpd']['pps']['refid'];
1983
		}
1984
		$ntpcfg .= "\n";
1985
	}
1986
	/* End PPS configuration */
1987

    
1988
	/* Add GPS configuration */
1989
	if (is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['port']) &&
1990
	    system_ntp_setup_gps($config['ntpd']['gps']['port'])) {
1991
		$ntpcfg .= "\n";
1992
		$ntpcfg .= "# GPS Setup\n";
1993
		$ntpcfg .= 'server 127.127.20.0 mode ';
1994
		if (!empty($config['ntpd']['gps']['nmea']) || !empty($config['ntpd']['gps']['speed']) || !empty($config['ntpd']['gps']['subsec']) || !empty($config['ntpd']['gps']['processpgrmf'])) {
1995
			if (!empty($config['ntpd']['gps']['nmea'])) {
1996
				$ntpmode = (int) $config['ntpd']['gps']['nmea'];
1997
			}
1998
			if (!empty($config['ntpd']['gps']['speed'])) {
1999
				$ntpmode += (int) $config['ntpd']['gps']['speed'];
2000
			}
2001
			if (!empty($config['ntpd']['gps']['subsec'])) {
2002
				$ntpmode += 128;
2003
			}
2004
			if (!empty($config['ntpd']['gps']['processpgrmf'])) {
2005
				$ntpmode += 256;
2006
			}
2007
			$ntpcfg .= (string) $ntpmode;
2008
		} else {
2009
			$ntpcfg .= '0';
2010
		}
2011
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', $config['ntpd']['gps']['gpsminpoll'], $ntp_poll_min_default_gps);
2012
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', $config['ntpd']['gps']['gpsmaxpoll'], $ntp_poll_max_default_gps);
2013

    
2014
		if (empty($config['ntpd']['gps']['prefer'])) { /*note: this one works backwards */
2015
			$ntpcfg .= ' prefer';
2016
		}
2017
		if (!empty($config['ntpd']['gps']['noselect'])) {
2018
			$ntpcfg .= ' noselect ';
2019
		}
2020
		$ntpcfg .= "\n";
2021
		$ntpcfg .= 'fudge 127.127.20.0';
2022
		if (!empty($config['ntpd']['gps']['fudge1'])) {
2023
			$ntpcfg .= ' time1 ';
2024
			$ntpcfg .= $config['ntpd']['gps']['fudge1'];
2025
		}
2026
		if (!empty($config['ntpd']['gps']['fudge2'])) {
2027
			$ntpcfg .= ' time2 ';
2028
			$ntpcfg .= $config['ntpd']['gps']['fudge2'];
2029
		}
2030
		if (!empty($config['ntpd']['gps']['flag1'])) {
2031
			$ntpcfg .= ' flag1 1';
2032
		} else {
2033
			$ntpcfg .= ' flag1 0';
2034
		}
2035
		if (!empty($config['ntpd']['gps']['flag2'])) {
2036
			$ntpcfg .= ' flag2 1';
2037
		}
2038
		if (!empty($config['ntpd']['gps']['flag3'])) {
2039
			$ntpcfg .= ' flag3 1';
2040
		} else {
2041
			$ntpcfg .= ' flag3 0';
2042
		}
2043
		if (!empty($config['ntpd']['gps']['flag4'])) {
2044
			$ntpcfg .= ' flag4 1';
2045
		}
2046
		if (!empty($config['ntpd']['gps']['refid'])) {
2047
			$ntpcfg .= ' refid ';
2048
			$ntpcfg .= $config['ntpd']['gps']['refid'];
2049
		}
2050
		if (!empty($config['ntpd']['gps']['stratum'])) {
2051
			$ntpcfg .= ' stratum ';
2052
			$ntpcfg .= $config['ntpd']['gps']['stratum'];
2053
		}
2054
		$ntpcfg .= "\n";
2055
	} elseif (is_array($config['ntpd']) && !empty($config['ntpd']['gpsport']) &&
2056
	    system_ntp_setup_gps($config['ntpd']['gpsport'])) {
2057
		/* This handles a 2.1 and earlier config */
2058
		$ntpcfg .= "# GPS Setup\n";
2059
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
2060
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
2061
		// Fall back to local clock if GPS is out of sync?
2062
		$ntpcfg .= "server 127.127.1.0\n";
2063
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
2064
	}
2065
	/* End GPS configuration */
2066
	$auto_pool_suffix = "pool.ntp.org";
2067
	$have_pools = false;
2068
	$ntpcfg .= "\n\n# Upstream Servers\n";
2069
	/* foreach through ntp servers and write out to ntpd.conf */
2070
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
2071
		if ((substr_compare($ts, $auto_pool_suffix, strlen($ts) - strlen($auto_pool_suffix), strlen($auto_pool_suffix)) === 0)
2072
		    || substr_count($config['ntpd']['ispool'], $ts)) {
2073
			$ntpcfg .= 'pool ';
2074
			$have_pools = true;
2075
		} else {
2076
			if (substr_count($config['ntpd']['ispeer'], $ts)) {
2077
				$ntpcfg .= 'peer ';
2078
			} else {
2079
				$ntpcfg .= 'server ';
2080
			}
2081
			if ($config['ntpd']['dnsresolv'] == 'inet') {
2082
				$ntpcfg .= '-4 ';
2083
			} elseif ($config['ntpd']['dnsresolv'] == 'inet6') {
2084
				$ntpcfg .= '-6 ';
2085
			}
2086
		}
2087

    
2088
		$ntpcfg .= "{$ts}";
2089
		if (!substr_count($config['ntpd']['ispeer'], $ts)) {
2090
			$ntpcfg .= " iburst";
2091
		}
2092

    
2093
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', $config['ntpd']['ntpminpoll'], $ntp_poll_min_default);
2094
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', $config['ntpd']['ntpmaxpoll'], $ntp_poll_max_default);
2095

    
2096
		if (substr_count($config['ntpd']['prefer'], $ts)) {
2097
			$ntpcfg .= ' prefer';
2098
		}
2099
		if (substr_count($config['ntpd']['noselect'], $ts)) {
2100
			$ntpcfg .= ' noselect';
2101
		}
2102
		$ntpcfg .= "\n";
2103
	}
2104
	unset($ts);
2105

    
2106
	$ntpcfg .= "\n\n";
2107
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
2108
		$ntpcfg .= "enable stats\n";
2109
		$ntpcfg .= 'statistics';
2110
		if (!empty($config['ntpd']['clockstats'])) {
2111
			$ntpcfg .= ' clockstats';
2112
		}
2113
		if (!empty($config['ntpd']['loopstats'])) {
2114
			$ntpcfg .= ' loopstats';
2115
		}
2116
		if (!empty($config['ntpd']['peerstats'])) {
2117
			$ntpcfg .= ' peerstats';
2118
		}
2119
		$ntpcfg .= "\n";
2120
	}
2121
	$ntpcfg .= "statsdir {$statsdir}\n";
2122
	$ntpcfg .= 'logconfig =syncall +clockall';
2123
	if (!empty($config['ntpd']['logpeer'])) {
2124
		$ntpcfg .= ' +peerall';
2125
	}
2126
	if (!empty($config['ntpd']['logsys'])) {
2127
		$ntpcfg .= ' +sysall';
2128
	}
2129
	$ntpcfg .= "\n";
2130
	$ntpcfg .= "driftfile {$driftfile}\n";
2131

    
2132
	/* Default Access restrictions */
2133
	$ntpcfg .= 'restrict default';
2134
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
2135
		$ntpcfg .= ' kod limited';
2136
	}
2137
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
2138
		$ntpcfg .= ' nomodify';
2139
	}
2140
	if (!empty($config['ntpd']['noquery'])) {
2141
		$ntpcfg .= ' noquery';
2142
	}
2143
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
2144
		$ntpcfg .= ' nopeer';
2145
	}
2146
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
2147
		$ntpcfg .= ' notrap';
2148
	}
2149
	if (!empty($config['ntpd']['noserve'])) {
2150
		$ntpcfg .= ' noserve';
2151
	}
2152
	$ntpcfg .= "\nrestrict -6 default";
2153
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
2154
		$ntpcfg .= ' kod limited';
2155
	}
2156
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
2157
		$ntpcfg .= ' nomodify';
2158
	}
2159
	if (!empty($config['ntpd']['noquery'])) {
2160
		$ntpcfg .= ' noquery';
2161
	}
2162
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
2163
		$ntpcfg .= ' nopeer';
2164
	}
2165
	if (!empty($config['ntpd']['noserve'])) {
2166
		$ntpcfg .= ' noserve';
2167
	}
2168
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
2169
		$ntpcfg .= ' notrap';
2170
	}
2171

    
2172
	/* Pools require "restrict source" and cannot contain "nopeer" and "noserve". */
2173
	if ($have_pools) {
2174
		$ntpcfg .= "\nrestrict source";
2175
		if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
2176
			$ntpcfg .= ' kod limited';
2177
		}
2178
		if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
2179
			$ntpcfg .= ' nomodify';
2180
		}
2181
		if (!empty($config['ntpd']['noquery'])) {
2182
			$ntpcfg .= ' noquery';
2183
		}
2184
		if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
2185
			$ntpcfg .= ' notrap';
2186
		}
2187
	}
2188

    
2189
	/* Custom Access Restrictions */
2190
	if (is_array($config['ntpd']['restrictions']) && is_array($config['ntpd']['restrictions']['row'])) {
2191
		$networkacl = $config['ntpd']['restrictions']['row'];
2192
		foreach ($networkacl as $acl) {
2193
			$restrict = "";
2194
			if (is_ipaddrv6($acl['acl_network'])) {
2195
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask_v6($acl['mask']) . " ";
2196
			} elseif (is_ipaddrv4($acl['acl_network'])) {
2197
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask($acl['mask']) . " ";
2198
			} else {
2199
				continue;
2200
			}
2201
			if (!empty($acl['kod'])) {
2202
				$restrict .= ' kod limited';
2203
			}
2204
			if (!empty($acl['nomodify'])) {
2205
				$restrict .= ' nomodify';
2206
			}
2207
			if (!empty($acl['noquery'])) {
2208
				$restrict .= ' noquery';
2209
			}
2210
			if (!empty($acl['nopeer'])) {
2211
				$restrict .= ' nopeer';
2212
			}
2213
			if (!empty($acl['noserve'])) {
2214
				$restrict .= ' noserve';
2215
			}
2216
			if (!empty($acl['notrap'])) {
2217
				$restrict .= ' notrap';
2218
			}
2219
			if (!empty($restrict)) {
2220
				$ntpcfg .= "\nrestrict {$restrict} ";
2221
			}
2222
		}
2223
	}
2224
	/* End Custom Access Restrictions */
2225

    
2226
	/* A leapseconds file is really only useful if this clock is stratum 1 */
2227
	$ntpcfg .= "\n";
2228
	if (!empty($config['ntpd']['leapsec'])) {
2229
		$leapsec .= base64_decode($config['ntpd']['leapsec']);
2230
		file_put_contents('/var/db/leap-seconds', $leapsec);
2231
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
2232
	}
2233

    
2234

    
2235
	if (empty($config['ntpd']['interface'])) {
2236
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface'])) {
2237
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
2238
		} else {
2239
			$interfaces = array();
2240
		}
2241
	} else {
2242
		$interfaces = explode(",", $config['ntpd']['interface']);
2243
	}
2244

    
2245
	if (is_array($interfaces) && count($interfaces)) {
2246
		$finterfaces = array();
2247
		$ntpcfg .= "interface ignore all\n";
2248
		$ntpcfg .= "interface ignore wildcard\n";
2249
		foreach ($interfaces as $interface) {
2250
			$interface = get_real_interface($interface);
2251
			if (!empty($interface)) {
2252
				$finterfaces[] = $interface;
2253
			}
2254
		}
2255
		foreach ($finterfaces as $interface) {
2256
			$ntpcfg .= "interface listen {$interface}\n";
2257
		}
2258
	}
2259

    
2260
	/* open configuration for writing or bail */
2261
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
2262
		log_error(sprintf(gettext("Could not open %s/ntpd.conf for writing"), $g['varetc_path']));
2263
		return;
2264
	}
2265

    
2266
	/* if /var/empty does not exist, create it */
2267
	if (!is_dir("/var/empty")) {
2268
		mkdir("/var/empty", 0555, true);
2269
	}
2270

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

    
2274
	// Note that we are starting up
2275
	log_error("NTPD is starting up.");
2276

    
2277
	if (platform_booting()) {
2278
		echo gettext("done.") . "\n";
2279
	}
2280

    
2281
	return;
2282
}
2283

    
2284
function system_halt() {
2285
	global $g;
2286

    
2287
	system_reboot_cleanup();
2288

    
2289
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
2290
}
2291

    
2292
function system_reboot() {
2293
	global $g;
2294

    
2295
	system_reboot_cleanup();
2296

    
2297
	mwexec("/usr/bin/nohup /etc/rc.reboot > /dev/null 2>&1 &");
2298
}
2299

    
2300
function system_reboot_sync($reroot=false) {
2301
	global $g;
2302

    
2303
	if ($reroot) {
2304
		$args = " -r ";
2305
	}
2306

    
2307
	system_reboot_cleanup();
2308

    
2309
	mwexec("/etc/rc.reboot {$args} > /dev/null 2>&1");
2310
}
2311

    
2312
function system_reboot_cleanup() {
2313
	global $config, $g, $cpzone;
2314

    
2315
	mwexec("/usr/local/bin/beep.sh stop");
2316
	require_once("captiveportal.inc");
2317
	if (is_array($config['captiveportal'])) {
2318
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
2319
			if (!isset($cp['preservedb'])) {
2320
				/* send Accounting-Stop packet for all clients, termination cause 'Admin-Reboot' */
2321
				captiveportal_radius_stop_all(7); // Admin-Reboot
2322
				unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
2323
				captiveportal_free_dnrules();
2324
			}
2325
			/* Send Accounting-Off packet to the RADIUS server */
2326
			captiveportal_send_server_accounting('off');
2327
		}
2328
		/* Remove the pipe database */
2329
		unlink_if_exists("{$g['vardb_path']}/captiveportaldn.rules");
2330
	}
2331
	require_once("voucher.inc");
2332
	voucher_save_db_to_config();
2333
	require_once("pkg-utils.inc");
2334
	stop_packages();
2335
}
2336

    
2337
function system_do_shell_commands($early = 0) {
2338
	global $config, $g;
2339
	if (isset($config['system']['developerspew'])) {
2340
		$mt = microtime();
2341
		echo "system_do_shell_commands() being called $mt\n";
2342
	}
2343

    
2344
	if ($early) {
2345
		$cmdn = "earlyshellcmd";
2346
	} else {
2347
		$cmdn = "shellcmd";
2348
	}
2349

    
2350
	if (is_array($config['system'][$cmdn])) {
2351

    
2352
		/* *cmd is an array, loop through */
2353
		foreach ($config['system'][$cmdn] as $cmd) {
2354
			exec($cmd);
2355
		}
2356

    
2357
	} elseif ($config['system'][$cmdn] <> "") {
2358

    
2359
		/* execute single item */
2360
		exec($config['system'][$cmdn]);
2361

    
2362
	}
2363
}
2364

    
2365
function system_dmesg_save() {
2366
	global $g;
2367
	if (isset($config['system']['developerspew'])) {
2368
		$mt = microtime();
2369
		echo "system_dmesg_save() being called $mt\n";
2370
	}
2371

    
2372
	$dmesg = "";
2373
	$_gb = exec("/sbin/dmesg", $dmesg);
2374

    
2375
	/* find last copyright line (output from previous boots may be present) */
2376
	$lastcpline = 0;
2377

    
2378
	for ($i = 0; $i < count($dmesg); $i++) {
2379
		if (strstr($dmesg[$i], "Copyright (c) 1992-")) {
2380
			$lastcpline = $i;
2381
		}
2382
	}
2383

    
2384
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
2385
	if (!$fd) {
2386
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
2387
		return 1;
2388
	}
2389

    
2390
	for ($i = $lastcpline; $i < count($dmesg); $i++) {
2391
		fwrite($fd, $dmesg[$i] . "\n");
2392
	}
2393

    
2394
	fclose($fd);
2395
	unset($dmesg);
2396

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

    
2400
	return 0;
2401
}
2402

    
2403
function system_set_harddisk_standby() {
2404
	global $g, $config;
2405

    
2406
	if (isset($config['system']['developerspew'])) {
2407
		$mt = microtime();
2408
		echo "system_set_harddisk_standby() being called $mt\n";
2409
	}
2410

    
2411
	if (isset($config['system']['harddiskstandby'])) {
2412
		if (platform_booting()) {
2413
			echo gettext('Setting hard disk standby... ');
2414
		}
2415

    
2416
		$standby = $config['system']['harddiskstandby'];
2417
		// Check for a numeric value
2418
		if (is_numeric($standby)) {
2419
			// Get only suitable candidates for standby; using get_smart_drive_list()
2420
			// from utils.inc to get the list of drives.
2421
			$harddisks = get_smart_drive_list();
2422

    
2423
			// Since get_smart_drive_list() only matches ad|da|ada; lets put the check below
2424
			// just in case of some weird pfSense platform installs.
2425
			if (count($harddisks) > 0) {
2426
				// Iterate disks and run the camcontrol command for each
2427
				foreach ($harddisks as $harddisk) {
2428
					mwexec("/sbin/camcontrol standby {$harddisk} -t {$standby}");
2429
				}
2430
				if (platform_booting()) {
2431
					echo gettext("done.") . "\n";
2432
				}
2433
			} else if (platform_booting()) {
2434
				echo gettext("failed!") . "\n";
2435
			}
2436
		} else if (platform_booting()) {
2437
			echo gettext("failed!") . "\n";
2438
		}
2439
	}
2440
}
2441

    
2442
function system_setup_sysctl() {
2443
	global $config;
2444
	if (isset($config['system']['developerspew'])) {
2445
		$mt = microtime();
2446
		echo "system_setup_sysctl() being called $mt\n";
2447
	}
2448

    
2449
	activate_sysctls();
2450

    
2451
	if (isset($config['system']['sharednet'])) {
2452
		system_disable_arp_wrong_if();
2453
	}
2454
}
2455

    
2456
function system_disable_arp_wrong_if() {
2457
	global $config;
2458
	if (isset($config['system']['developerspew'])) {
2459
		$mt = microtime();
2460
		echo "system_disable_arp_wrong_if() being called $mt\n";
2461
	}
2462
	set_sysctl(array(
2463
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
2464
		"net.link.ether.inet.log_arp_movements" => "0"
2465
	));
2466
}
2467

    
2468
function system_enable_arp_wrong_if() {
2469
	global $config;
2470
	if (isset($config['system']['developerspew'])) {
2471
		$mt = microtime();
2472
		echo "system_enable_arp_wrong_if() being called $mt\n";
2473
	}
2474
	set_sysctl(array(
2475
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
2476
		"net.link.ether.inet.log_arp_movements" => "1"
2477
	));
2478
}
2479

    
2480
function enable_watchdog() {
2481
	global $config;
2482
	return;
2483
	$install_watchdog = false;
2484
	$supported_watchdogs = array("Geode");
2485
	$file = file_get_contents("/var/log/dmesg.boot");
2486
	foreach ($supported_watchdogs as $sd) {
2487
		if (stristr($file, "Geode")) {
2488
			$install_watchdog = true;
2489
		}
2490
	}
2491
	if ($install_watchdog == true) {
2492
		if (is_process_running("watchdogd")) {
2493
			mwexec("/usr/bin/killall watchdogd", true);
2494
		}
2495
		exec("/usr/sbin/watchdogd");
2496
	}
2497
}
2498

    
2499
function system_check_reset_button() {
2500
	global $g;
2501

    
2502
	$specplatform = system_identify_specific_platform();
2503

    
2504
	switch ($specplatform['name']) {
2505
		case 'SG-2220':
2506
			$binprefix = "RCC-DFF";
2507
			break;
2508
		case 'alix':
2509
		case 'wrap':
2510
		case 'FW7541':
2511
		case 'APU':
2512
		case 'RCC-VE':
2513
		case 'RCC':
2514
			$binprefix = $specplatform['name'];
2515
			break;
2516
		default:
2517
			return 0;
2518
	}
2519

    
2520
	$retval = mwexec("/usr/local/sbin/" . $binprefix . "resetbtn");
2521

    
2522
	if ($retval == 99) {
2523
		/* user has pressed reset button for 2 seconds -
2524
		   reset to factory defaults */
2525
		echo <<<EOD
2526

    
2527
***********************************************************************
2528
* Reset button pressed - resetting configuration to factory defaults. *
2529
* All additional packages installed will be removed                   *
2530
* The system will reboot after this completes.                        *
2531
***********************************************************************
2532

    
2533

    
2534
EOD;
2535

    
2536
		reset_factory_defaults();
2537
		system_reboot_sync();
2538
		exit(0);
2539
	}
2540

    
2541
	return 0;
2542
}
2543

    
2544
function system_get_serial() {
2545
	$platform = system_identify_specific_platform();
2546

    
2547
	unset($output);
2548
	if ($platform['name'] == 'Turbot Dual-E') {
2549
		$if_info = pfSense_get_interface_addresses('igb0');
2550
		if (!empty($if_info['hwaddr'])) {
2551
			$serial = str_replace(":", "", $if_info['hwaddr']);
2552
		}
2553
	} else {
2554
		foreach (array('system', 'planar', 'chassis') as $key) {
2555
			unset($output);
2556
			$_gb = exec("/bin/kenv -q smbios.{$key}.serial",
2557
			    $output);
2558
			if (!empty($output[0]) && $output[0] != "0123456789" &&
2559
			    preg_match('/^[\w\d]{10,16}$/', $output[0]) === 1) {
2560
				$serial = $output[0];
2561
				break;
2562
			}
2563
		}
2564
	}
2565

    
2566
	$vm_guest = get_single_sysctl('kern.vm_guest');
2567

    
2568
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2569
	    $vm_guest == 'none') {
2570
		return $serial;
2571
	}
2572

    
2573
	return "";
2574
}
2575

    
2576
function system_get_uniqueid() {
2577
	global $g;
2578

    
2579
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2580

    
2581
	if (empty($g['uniqueid'])) {
2582
		if (!file_exists($uniqueid_file)) {
2583
			mwexec("/usr/sbin/gnid > {$g['vardb_path']}/uniqueid " .
2584
			    "2>/dev/null");
2585
		}
2586
		if (file_exists($uniqueid_file)) {
2587
			$g['uniqueid'] = @file_get_contents($uniqueid_file);
2588
		}
2589
	}
2590

    
2591
	return ($g['uniqueid'] ?: '');
2592
}
2593

    
2594
/*
2595
 * attempt to identify the specific platform (for embedded systems)
2596
 * Returns an array with two elements:
2597
 * name => platform string (e.g. 'wrap', 'alix' etc.)
2598
 * descr => human-readable description (e.g. "PC Engines WRAP")
2599
 */
2600
function system_identify_specific_platform() {
2601
	global $g;
2602

    
2603
	$hw_model = get_single_sysctl('hw.model');
2604
	$hw_ncpu = get_single_sysctl('hw.ncpu');
2605

    
2606
	/* Try to guess from smbios strings */
2607
	unset($product);
2608
	unset($maker);
2609
	unset($bios);
2610
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $product);
2611
	$_gb = exec('/bin/kenv -q smbios.system.maker 2>/dev/null', $maker);
2612
	$_gb = exec('/bin/kenv -q smbios.bios.version 2>/dev/null', $bios);
2613

    
2614
	$vm = get_single_sysctl('kern.vm_guest');
2615

    
2616
	// This switch needs to be expanded to include other virtualization systems
2617
	switch ($vm) {
2618
		case "none" :
2619
		break;
2620

    
2621
		case "kvm" :
2622
			return (array('name' => 'KVM', 'descr' => 'KVM Guest'));
2623
		break;
2624
	}
2625

    
2626
	if ($maker[0] == "QEMU") {
2627
		return (array('name' => 'QEMU', 'descr' => 'QEMU'));
2628
	}
2629

    
2630
	// AWS can only be identified via the bios version
2631
	if (stripos($bios[0], "amazon") !== false) {
2632
		return (array('name' => 'AWS', 'descr' => 'Amazon Web Services'));
2633
	} else  if (stripos($bios[0], "Google") !== false) {
2634
		return (array('name' => 'Google', 'descr' => 'Google Cloud Platform'));
2635
	}
2636

    
2637
	switch ($product[0]) {
2638
		case 'FW7541':
2639
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2640
			break;
2641
		case 'APU':
2642
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2643
			break;
2644
		case 'RCC-VE':
2645
			$result = array();
2646
			$result['name'] = 'RCC-VE';
2647

    
2648
			/* Detect specific models */
2649
			if (!function_exists('does_interface_exist')) {
2650
				require_once("interfaces.inc");
2651
			}
2652
			if (!does_interface_exist('igb4')) {
2653
				$result['model'] = 'SG-2440';
2654
			} elseif (strpos($hw_model, "C2558") !== false) {
2655
				$result['model'] = 'SG-4860';
2656
			} elseif (strpos($hw_model, "C2758") !== false) {
2657
				$result['model'] = 'SG-8860';
2658
			} else {
2659
				$result['model'] = 'RCC-VE';
2660
			}
2661
			$result['descr'] = 'Netgate ' . $result['model'];
2662
			return $result;
2663
			break;
2664
		case 'DFFv2':
2665
			return (array('name' => 'SG-2220', 'descr' => 'Netgate SG-2220'));
2666
			break;
2667
		case 'RCC':
2668
			return (array('name' => 'RCC', 'descr' => 'Netgate XG-2758'));
2669
			break;
2670
		case 'SG-5100':
2671
			return (array('name' => '5100', 'descr' => 'Netgate 5100'));
2672
			break;
2673
		case 'Minnowboard Turbot D0 PLATFORM':
2674
		case 'Minnowboard Turbot D0/D1 PLATFORM':
2675
			$result = array();
2676
			$result['name'] = 'Turbot Dual-E';
2677
			/* Detect specific model */
2678
			switch ($hw_ncpu) {
2679
			case '4':
2680
				$result['model'] = 'MBT-4220';
2681
				break;
2682
			case '2':
2683
				$result['model'] = 'MBT-2220';
2684
				break;
2685
			default:
2686
				$result['model'] = $result['name'];
2687
				break;
2688
			}
2689
			$result['descr'] = 'Netgate ' . $result['model'];
2690
			return $result;
2691
			break;
2692
		case 'SYS-5018A-FTN4':
2693
		case 'A1SAi':
2694
			if (strpos($hw_model, "C2558") !== false) {
2695
				return (array(
2696
				    'name' => 'C2558',
2697
				    'descr' => 'Super Micro C2558'));
2698
			} elseif (strpos($hw_model, "C2758") !== false) {
2699
				return (array(
2700
				    'name' => 'C2758',
2701
				    'descr' => 'Super Micro C2758'));
2702
			}
2703
			break;
2704
		case 'SYS-5018D-FN4T':
2705
			if (strpos($hw_model, "D-1541") !== false) {
2706
				return (array('name' => '1541', 'descr' => 'Super Micro 1541'));
2707
			} else {
2708
				return (array('name' => '1540', 'descr' => 'Super Micro XG-1540'));
2709
			}
2710
			break;
2711
		case 'apu2':
2712
		case 'APU2':
2713
			return (array('name' => 'apu2', 'descr' => 'PC Engines APU2'));
2714
			break;
2715
		case 'VirtualBox':
2716
			return (array('name' => 'VirtualBox', 'descr' => 'VirtualBox Virtual Machine'));
2717
			break;
2718
		case 'Virtual Machine':
2719
			if ($maker[0] == "Microsoft Corporation") {
2720
				if (stripos($bios[0], "Hyper") !== false) {
2721
					return (array('name' => 'Hyper-V', 'descr' => 'Hyper-V Virtual Machine'));
2722
				} else {
2723
					return (array('name' => 'Azure', 'descr' => 'Microsoft Azure'));
2724
				}
2725
			}
2726
			break;
2727
		case 'VMware Virtual Platform':
2728
			if ($maker[0] == "VMware, Inc.") {
2729
				return (array('name' => 'VMware', 'descr' => 'VMware Virtual Machine'));
2730
			}
2731
			break;
2732
	}
2733

    
2734
	$_gb = exec('/bin/kenv -q smbios.planar.product 2>/dev/null',
2735
	    $planar_product);
2736
	if (isset($planar_product[0]) &&
2737
	    $planar_product[0] == 'X10SDV-8C-TLN4F+') {
2738
		return array('name' => '1537', 'descr' => 'Super Micro 1537');
2739
	}
2740

    
2741
	if (strpos($hw_model, "PC Engines WRAP") !== false) {
2742
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
2743
	}
2744

    
2745
	if (strpos($hw_model, "PC Engines ALIX") !== false) {
2746
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2747
	}
2748

    
2749
	if (preg_match("/Soekris net45../", $hw_model, $matches)) {
2750
		return array('name' => 'net45xx', 'descr' => $matches[0]);
2751
	}
2752

    
2753
	if (preg_match("/Soekris net48../", $hw_model, $matches)) {
2754
		return array('name' => 'net48xx', 'descr' => $matches[0]);
2755
	}
2756

    
2757
	if (preg_match("/Soekris net55../", $hw_model, $matches)) {
2758
		return array('name' => 'net55xx', 'descr' => $matches[0]);
2759
	}
2760

    
2761
	unset($hw_model);
2762

    
2763
	$dmesg_boot = system_get_dmesg_boot();
2764
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
2765
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2766
	}
2767
	unset($dmesg_boot);
2768

    
2769
	return array('name' => $g['product_name'], 'descr' => $g['product_label']);
2770
}
2771

    
2772
function system_get_dmesg_boot() {
2773
	global $g;
2774

    
2775
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2776
}
2777

    
2778
function system_get_arp_table($resolve_hostnames = false) {
2779
	$params="-a";
2780
	if (!$resolve_hostnames) {
2781
		$params .= "n";
2782
	}
2783

    
2784
	$arp_table = array();
2785
	$_gb = exec("/usr/sbin/arp --libxo json {$params}", $rawdata, $rc);
2786
	if ($rc == 0) {
2787
		$arp_table = json_decode(implode(" ", $rawdata),
2788
		    JSON_OBJECT_AS_ARRAY);
2789
		if ($rc == 0) {
2790
			$arp_table = $arp_table['arp']['arp-cache'];
2791
		}
2792
	}
2793

    
2794
	return $arp_table;
2795
}
2796

    
2797
function _getHostName($mac, $ip) {
2798
	global $dhcpmac, $dhcpip;
2799

    
2800
	if ($dhcpmac[$mac]) {
2801
		return $dhcpmac[$mac];
2802
	} else if ($dhcpip[$ip]) {
2803
		return $dhcpip[$ip];
2804
	} else {
2805
		$ipproto = (is_ipaddrv4($ip)) ? '-4 ' : '-6 ';
2806
		exec("/usr/bin/host -W 1 " . $ipproto . escapeshellarg($ip), $output);
2807
		if (preg_match('/.*pointer ([A-Za-z_0-9.-]+)\..*/', $output[0], $matches)) {
2808
			if ($matches[1] <> $ip) {
2809
				return $matches[1];
2810
			}
2811
		}
2812
	}
2813
	return "";
2814
}
2815

    
2816
function check_dnsavailable($proto='inet') {
2817

    
2818
	if ($proto == 'inet') {
2819
		$gdns = array('8.8.8.8', '8.8.4.4');
2820
	} else {
2821
		$gdns = array('2001:4860:4860::8888', '2001:4860:4860::8844');
2822
	}
2823
	$nameservers = array_merge($gdns, get_dns_nameservers());
2824
	$test = 0;
2825

    
2826
	foreach ($gdns as $dns) {
2827
		if ($dns == '127.0.0.1') {
2828
			continue;
2829
		} else {
2830
			$dns_result = trim(_getHostName("", $dns));
2831
			if (($test == '2') && ($dns_result == "")) {
2832
				return false;
2833
			} elseif ($dns_result == "") {
2834
				$test++; 
2835
				continue;
2836
			} else {
2837
				return true;
2838
			}
2839
		}
2840
	}
2841

    
2842
	return false;
2843
}
2844

    
2845
?>
(49-49/61)