Project

General

Profile

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

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

    
31
function activate_powerd() {
32
	if (is_process_running("powerd")) {
33
		exec("/usr/bin/killall powerd");
34
	}
35
	if (config_path_enabled('system', 'powerd_enable')) {
36
		$ac_mode = "hadp";
37
		if (!empty(config_get_path('system/powerd_ac_mode'))) {
38
			$ac_mode = config_get_path('system/powerd_ac_mode');
39
		}
40

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

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

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

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

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

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

    
70
	return $output[0];
71
}
72

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

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

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

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

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

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

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

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

    
111
	/*
112
	 * See https://redmine.pfsense.org/issues/13938
113
	 *
114
	 * We need to disable unmapped mbufs to work around a bug
115
	 * that can cause sendfile to crash.
116
	 */
117
	$sysctls['kern.ipc.mb_use_ext_pgs'] = '0';
118

    
119
	if (config_get_path('system/consolebell', 'enabled') == 'enabled') {
120
		$sysctls['kern.vt.enable_bell'] = '1';
121
	} else {
122
		$sysctls['kern.vt.enable_bell'] = '0';
123
	}
124

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

    
132
		$sysctls[$tunable['tunable']] = $value;
133
	}
134

    
135
	/* Set net.pf.request_maxcount via sysctl since it is no longer a loader
136
	 *   tunable. See https://redmine.pfsense.org/issues/10861
137
	 *   Set the value dynamically since its default is not static, yet this
138
	 *   still could be overridden by a user tunable. */
139
	$maximumtableentries = config_get_path('system/maximumtableentries',
140
										   pfsense_default_table_entries_size());
141

    
142
	/* Set the default when there is no tunable or when the tunable is set
143
	 * too low. */
144
	if (empty($sysctls['net.pf.request_maxcount']) ||
145
	    ($sysctls['net.pf.request_maxcount'] < $maximumtableentries)) {
146
		$sysctls['net.pf.request_maxcount'] = $maximumtableentries;
147
	}
148

    
149
	set_sysctl($sysctls);
150
}
151

    
152
function system_resolvconf_generate($dynupdate = false) {
153
	global $g;
154

    
155
	if (config_path_enabled('system', 'developerspew')) {
156
		$mt = microtime();
157
		echo "system_resolvconf_generate() being called $mt\n";
158
	}
159

    
160
	$syscfg = config_get_path('system', []);
161

    
162
	foreach(get_dns_nameservers(false, false) as $dns_ns) {
163
		$resolvconf .= "nameserver $dns_ns\n";
164
	}
165

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

    
183
	// Add EDNS support
184
	if (config_path_enabled('unbound') && (config_get_path('unbound/edns') != null)) {
185
		$resolvconf .= "options edns0\n";
186
	}
187

    
188
	$dnslock = lock('resolvconf', LOCK_EX);
189

    
190
	$fd = fopen("{$g['etc_path']}/resolv.conf", "w");
191
	if (!$fd) {
192
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
193
		unlock($dnslock);
194
		return 1;
195
	}
196

    
197
	fwrite($fd, $resolvconf);
198
	fclose($fd);
199

    
200
	// Prevent resolvconf(8) from rewriting our resolv.conf
201
	$fd = fopen("{$g['etc_path']}/resolvconf.conf", "w");
202
	if (!$fd) {
203
		printf("Error: cannot open resolvconf.conf in system_resolvconf_generate().\n");
204
		return 1;
205
	}
206
	fwrite($fd, "resolv_conf=\"/dev/null\"\n");
207
	fclose($fd);
208

    
209
	if (!platform_booting()) {
210
		/* restart dhcpd (nameservers may have changed) */
211
		if (!$dynupdate) {
212
			services_dhcpd_configure();
213
		}
214
	}
215

    
216
	// set up or tear down static routes for DNS servers
217
	$dnscounter = 1;
218
	$dnsgw = "dns{$dnscounter}gw";
219
	$exempt_addresses = array_unique(array_merge(get_interface_addresses_all('lo0'),
220
	    get_configured_ip_addresses(), get_configured_ipv6_addresses()));
221
	while (!empty(config_get_path("system/{$dnsgw}"))) {
222
		/* setup static routes for dns servers */
223
		$gwname = config_get_path("system/{$dnsgw}");		unset($gatewayip);
224
		unset($inet6);
225
		if ((!empty($gwname)) && ($gwname != "none")) {
226
			$gatewayip = lookup_gateway_ip_by_name($gwname);
227
			$inet6 = is_ipaddrv6($gatewayip) ? '-inet6 ' : '';
228
		}
229
		/* dns server array starts at 0 */
230
		$dnsserver = $syscfg['dnsserver'][$dnscounter - 1];
231

    
232
		/* Only modify routes for non-interface addresses;
233
		 * see https://redmine.pfsense.org/issues/14288 */
234
		if (!empty($dnsserver) && !in_array($dnsserver, $exempt_addresses)) {
235
			// specify IP protocol version for correct add/del
236
			if (is_ipaddrv4($dnsserver)) {
237
				$ipprotocol = 'inet';
238
			} else {
239
				$ipprotocol = 'inet6';
240
			}
241

    
242
			if (is_ipaddr($gatewayip)) {
243
				route_add_or_change($dnsserver, $gatewayip, '', '', $ipprotocol);
244
			} else {
245
				/* Remove old route when disable gw */
246
				route_del($dnsserver, $ipprotocol);
247
			}
248
		}
249
		$dnscounter++;
250
		$dnsgw = "dns{$dnscounter}gw";
251
	}
252

    
253
	unlock($dnslock);
254

    
255
	return 0;
256
}
257

    
258
function get_searchdomains() {
259
	$master_list = array();
260

    
261
	// Read in dhclient nameservers
262
	$search_list = glob("/var/etc/searchdomain_*");
263
	if (is_array($search_list)) {
264
		foreach ($search_list as $fdns) {
265
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
266
			if (!is_array($contents)) {
267
				continue;
268
			}
269
			foreach ($contents as $dns) {
270
				if (is_hostname($dns)) {
271
					$master_list[] = $dns;
272
				}
273
			}
274
		}
275
	}
276

    
277
	return $master_list;
278
}
279

    
280
/* Stub for deprecated function name
281
 * See https://redmine.pfsense.org/issues/10931 */
282
function get_nameservers() {
283
	return get_dynamic_nameservers();
284
}
285

    
286
/****f* system.inc/get_dynamic_nameservers
287
 * NAME
288
 *   get_dynamic_nameservers - Get DNS servers from dynamic sources (DHCP, PPP, etc)
289
 * INPUTS
290
 *   $iface: Interface name used to filter results.
291
 * RESULT
292
 *   $master_list - Array containing DNS servers
293
 ******/
294
function get_dynamic_nameservers($iface = '') {
295
	$master_list = array();
296

    
297
	if (!empty($iface)) {
298
		$realif = get_real_interface($iface);
299
	}
300

    
301
	// Read in dynamic nameservers
302
	$dns_lists = array_merge(glob("/var/etc/nameserver_{$realif}*"), glob("/var/etc/nameserver_v6{$iface}*"));
303
	if (is_array($dns_lists)) {
304
		foreach ($dns_lists as $fdns) {
305
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
306
			if (!is_array($contents)) {
307
				continue;
308
			}
309
			foreach ($contents as $dns) {
310
				if (is_ipaddr($dns)) {
311
					$master_list[] = $dns;
312
				}
313
			}
314
		}
315
	}
316

    
317
	return $master_list;
318
}
319

    
320
/* Create localhost + local interfaces entries for /etc/hosts */
321
function system_hosts_local_entries() {
322
	$syscfg = config_get_path('system', []);
323

    
324
	$hosts = array();
325
	$hosts[] = array(
326
	    'ipaddr' => '127.0.0.1',
327
	    'fqdn' => 'localhost.' . $syscfg['domain'],
328
	    'name' => 'localhost',
329
	    'domain' => $syscfg['domain']
330
	);
331
	$hosts[] = array(
332
	    'ipaddr' => '::1',
333
	    'fqdn' => 'localhost.' . $syscfg['domain'],
334
	    'name' => 'localhost',
335
	    'domain' => $syscfg['domain']
336
	);
337

    
338
	if (config_get_path('interfaces/lan')) {
339
		$sysiflist = array('lan' => "lan");
340
	} else {
341
		$sysiflist = get_configured_interface_list();
342
	}
343

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

    
377
	return $hosts;
378
}
379

    
380
/* Read host override entries from dnsmasq or unbound */
381
function system_hosts_override_entries($dnscfg) {
382
	$hosts = array();
383

    
384
	if (!is_array($dnscfg) ||
385
	    !is_array($dnscfg['hosts']) ||
386
	    !isset($dnscfg['enable'])) {
387
		return $hosts;
388
	}
389

    
390
	foreach ($dnscfg['hosts'] as $host) {
391
		$fqdn = '';
392
		if ($host['host'] || $host['host'] == "0") {
393
			$fqdn .= "{$host['host']}.";
394
		}
395
		$fqdn .= $host['domain'];
396

    
397
		foreach (explode(',', $host['ip']) as $ip) {
398
			$hosts[] = array(
399
			    'ipaddr' => $ip,
400
			    'fqdn' => $fqdn,
401
			    'name' => $host['host'],
402
			    'domain' => $host['domain']
403
			);
404
		}
405

    
406
		if (!is_array($host['aliases']) ||
407
		    !is_array($host['aliases']['item'])) {
408
			continue;
409
		}
410

    
411
		foreach ($host['aliases']['item'] as $alias) {
412
			$fqdn = '';
413
			if ($alias['host'] || $alias['host'] == "0") {
414
				$fqdn .= "{$alias['host']}.";
415
			}
416
			$fqdn .= $alias['domain'];
417

    
418
			foreach (explode(',', $host['ip']) as $ip) {
419
				$hosts[] = array(
420
				    'ipaddr' => $ip,
421
				    'fqdn' => $fqdn,
422
				    'name' => $alias['host'],
423
				    'domain' => $alias['domain']
424
				);
425
			}
426
		}
427
	}
428

    
429
	return $hosts;
430
}
431

    
432
/* Read all dhcpd/dhcpdv6 staticmap entries */
433
function system_hosts_dhcpd_entries() {
434
	$hosts = array();
435
	$syscfg = config_get_path('system');
436

    
437
	$conf_dhcpd = config_get_path('dhcpd', []);
438

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

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

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

    
473
	$conf_dhcpdv6 = config_get_path('dhcpdv6', []);
474

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

    
484
		if (config_get_path("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 $g;
557
	if (config_path_enabled('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 (config_path_enabled('dnsmasq')) {
565
		$dnsmasqcfg = config_get_path('dnsmasq');
566
	} else {
567
		$dnsmasqcfg = config_get_path('unbound');
568
	}
569

    
570
	$syscfg = config_get_path('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 (config_path_enabled('unbound')) {
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 $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 (((config_path_enabled('dnsmasq') && (config_get_path('dnsmasq/regdhcp') !== null)) ||
629
	    (config_path_enabled('unbound') && (config_get_path('unbound/regdhcp') !== null))) &&
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 (config_path_enabled('unbound')) {
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 " .
662
			   config_get_path('system/domain', '') .
663
			   " -p {$g['varrun_path']}/{$dns_pid} {$unbound_conf} -h {$g['etc_path']}/hosts");
664
	} else {
665
		if (isvalidpid($pidfile)) {
666
			sigkillbypid($pidfile, "TERM");
667
			@unlink($pidfile);
668
		}
669
		if (file_exists("{$g['unbound_chroot_path']}/dhcpleases_entries.conf")) {
670
			$dhcpleases = fopen("{$g['unbound_chroot_path']}/dhcpleases_entries.conf", "w");
671
			ftruncate($dhcpleases, 0);
672
			fclose($dhcpleases);
673
		}
674
	}
675
}
676

    
677
function system_get_dhcpleases($dnsavailable=null) {
678
	global $g;
679

    
680
	$leases = array();
681
	$leases['lease'] = array();
682
	$leases['failover'] = array();
683

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

    
686
	if (!file_exists($leases_file)) {
687
		return $leases;
688
	}
689

    
690
	$leases_content = file($leases_file, FILE_IGNORE_NEW_LINES |
691
	    FILE_IGNORE_NEW_LINES);
692

    
693
	if ($leases_content === FALSE) {
694
		return $leases;
695
	}
696

    
697
	$arp_table = system_get_arp_table();
698

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

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

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

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

    
731
	$lease = false;
732
	$failover = false;
733
	$dedup_lease = false;
734
	$dedup_failover = false;
735

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

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

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

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

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

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

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

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

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

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

    
843
	foreach (config_get_path('interfaces', []) as $ifname => $ifarr) {
844
		foreach (config_get_path("dhcpd/{$ifname}/staticmap", []) as $idx =>
845
		    $static) {
846
			if (empty($static['mac']) && empty($static['cid'])) {
847
				continue;
848
			}
849

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

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

    
881
	return $leases;
882
}
883

    
884
function system_hostname_configure() {
885
	if (config_path_enabled('system', 'developerspew')) {
886
		$mt = microtime();
887
		echo "system_hostname_configure() being called $mt\n";
888
	}
889

    
890
	$syscfg = config_get_path('system');
891

    
892
	/* set hostname */
893
	$status = mwexec("/bin/hostname " .
894
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
895

    
896
	/* Setup host GUID ID.  This is used by ZFS. */
897
	mwexec("/etc/rc.d/hostid start");
898

    
899
	return $status;
900
}
901

    
902
function system_routing_configure($interface = "") {
903
	if (config_path_enabled('system', 'developerspew')) {
904
		$mt = microtime();
905
		echo "system_routing_configure() being called $mt\n";
906
	}
907

    
908
	$gateways_arr = return_gateways_array(false, true);
909
	foreach ($gateways_arr as $gateway) {
910
		// setup static interface routes for nonlocal gateways
911
		if (isset($gateway["nonlocalgateway"])) {
912
			$srgatewayip = $gateway['gateway'];
913
			$srinterfacegw = $gateway['interface'];
914
			if (is_ipaddr($srgatewayip) && !empty($srinterfacegw)) {
915
				route_add_or_change($srgatewayip, '',
916
				    $srinterfacegw);
917
			}
918
		}
919
	}
920

    
921
	$gateways_status = return_gateways_status(true);
922
	fixup_default_gateway("inet", $gateways_status, $gateways_arr);
923
	fixup_default_gateway("inet6", $gateways_status, $gateways_arr);
924

    
925
	system_staticroutes_configure($interface, false);
926

    
927
	return 0;
928
}
929

    
930
function system_staticroutes_configure($interface = "", $update_dns = false) {
931
	global $g, $aliastable;
932

    
933
	$filterdns_list = array();
934

    
935
	$static_routes = get_staticroutes(false, true);
936
	if (count($static_routes)) {
937
		$gateways_arr = return_gateways_array(false, true);
938

    
939
		foreach ($static_routes as $rtent) {
940
			/* Do not delete disabled routes,
941
			 * see https://redmine.pfsense.org/issues/3709
942
			 * and https://redmine.pfsense.org/issues/10706 */
943
			if (isset($rtent['disabled'])) {
944
				continue;
945
			}
946

    
947
			if (empty($gateways_arr[$rtent['gateway']])) {
948
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
949
				continue;
950
			}
951
			$gateway = $gateways_arr[$rtent['gateway']];
952
			if (!empty($interface) && $interface != $gateway['friendlyiface']) {
953
				continue;
954
			}
955

    
956
			$gatewayip = $gateway['gateway'];
957
			$interfacegw = $gateway['interface'];
958

    
959
			$blackhole = "";
960
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 4))) {
961
				$blackhole = "-blackhole";
962
			}
963

    
964
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network'])) {
965
				continue;
966
			}
967

    
968
			$dnscache = array();
969
			if ($update_dns === true) {
970
				if (is_subnet($rtent['network'])) {
971
					continue;
972
				}
973
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
974
				if (empty($dnscache)) {
975
					continue;
976
				}
977
			}
978

    
979
			if (is_subnet($rtent['network'])) {
980
				$ips = array($rtent['network']);
981
			} else {
982
				if (!isset($rtent['disabled'])) {
983
					$filterdns_list[] = $rtent['network'];
984
				}
985
				$ips = add_hostname_to_watch($rtent['network']);
986
			}
987

    
988
			foreach ($dnscache as $ip) {
989
				if (in_array($ip, $ips)) {
990
					continue;
991
				}
992
				route_del($ip);
993
			}
994

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

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

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

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

    
1078
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid")) {
1079
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
1080
			} else {
1081
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
1082
			}
1083
		} else {
1084
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
1085
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
1086
		}
1087
	}
1088
	unset($filterdns_list);
1089

    
1090
	return 0;
1091
}
1092

    
1093
function delete_static_route($id, $delete = false) {
1094
	global $g, $changedesc_prefix, $a_gateways;
1095

    
1096
	if (empty(config_get_path("staticroutes/route/{$id}"))) {
1097
		return;
1098
	}
1099

    
1100
	if (file_exists("{$g['tmp_path']}/.system_routes.apply")) {
1101
		$toapplylist = unserialize(file_get_contents("{$g['tmp_path']}/.system_routes.apply"));
1102
	} else {
1103
		$toapplylist = array();
1104
	}
1105

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

    
1127
	if ($delete) {
1128
		unlink_if_exists("{$g['tmp_path']}/staticroute_{$id}");
1129
		unlink_if_exists("{$g['tmp_path']}/staticroute_{$id}_gw");
1130
	}
1131

    
1132
	if (!empty($toapplylist)) {
1133
		file_put_contents("{$g['tmp_path']}/.system_routes.apply", serialize($toapplylist));
1134
	}
1135

    
1136
	unset($targets);
1137
}
1138

    
1139
function system_routing_enable() {
1140
	if (config_path_enabled('system', 'developerspew')) {
1141
		$mt = microtime();
1142
		echo "system_routing_enable() being called $mt\n";
1143
	}
1144

    
1145
	set_sysctl(array(
1146
		"net.inet.ip.forwarding" => "1",
1147
		"net.inet6.ip6.forwarding" => "1"
1148
	));
1149

    
1150
	return;
1151
}
1152

    
1153
function system_webgui_start() {
1154
	global $g;
1155

    
1156
	if (platform_booting()) {
1157
		echo gettext("Starting webConfigurator...");
1158
	}
1159

    
1160
	chdir(g_get('www_path'));
1161

    
1162
	/* defaults */
1163
	$portarg = config_get_path('system/webgui/port', '80');
1164
	$crt = "";
1165
	$key = "";
1166
	$ca = "";
1167

    
1168
	if (config_get_path('system/webgui/protocol') == "https") {
1169
		// Ensure that we have a webConfigurator CERT
1170
		$cert = lookup_cert(config_get_path('system/webgui/ssl-certref'));
1171
		if (!is_array($cert) || !$cert['crt'] || !$cert['prv'] ||
1172
		    cert_chain_has_weak_digest($cert)) {
1173
			$cert = cert_create_selfsigned();
1174
			if (is_array($cert) && !empty($cert)) {
1175
				config_set_path('system/webgui/ssl-certref', $cert['refid']);
1176
				write_config(sprintf(gettext("Generated new self-signed SSL/TLS certificate for HTTPS (%s)"), $cert['refid']));
1177
			} else {
1178
				log_error(sprintf(gettext("GUI certificate is not usable and there was an error creating a new self-signed certificate.")));
1179
			}
1180
		}
1181
		$crt = base64_decode($cert['crt']);
1182
		$key = base64_decode($cert['prv']);
1183

    
1184
		$portarg = config_get_path('system/webgui/port', '443');
1185
		$ca = ca_chain($cert);
1186
		$hsts = !config_path_enabled('system/webgui', 'disablehsts');
1187
	}
1188

    
1189
	/* generate nginx configuration */
1190
	system_generate_nginx_config("{$g['varetc_path']}/nginx-webConfigurator.conf",
1191
		$crt, $key, $ca, "nginx-webConfigurator.pid", $portarg, "/usr/local/www/",
1192
		"cert.crt", "cert.key", false, $hsts);
1193

    
1194
	/* kill any running nginx */
1195
	killbypid("{$g['varrun_path']}/nginx-webConfigurator.pid");
1196

    
1197
	sleep(1);
1198

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

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

    
1204
	if (platform_booting()) {
1205
		if ($res == 0) {
1206
			echo gettext("done.") . "\n";
1207
		} else {
1208
			echo gettext("failed!") . "\n";
1209
		}
1210
	}
1211

    
1212
	return $res;
1213
}
1214

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

    
1233
	if (config_path_enabled('system', 'developerspew')) {
1234
		$mt = microtime();
1235
		echo "get_dns_nameservers() being called $mt\n";
1236
	}
1237

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

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

    
1273
function system_generate_nginx_config($filename,
1274
	$cert,
1275
	$key,
1276
	$ca,
1277
	$pid_file,
1278
	$port = 80,
1279
	$document_root = "/usr/local/www/",
1280
	$cert_location = "cert.crt",
1281
	$key_location = "cert.key",
1282
	$captive_portal = false,
1283
	$hsts = true) {
1284

    
1285
	global $g;
1286

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

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

    
1314
		$maxprocperip = config_get_path("captiveportal/{$captive_portal}/maxprocperip");
1315
		if (empty($maxprocperip)) {
1316
			$maxprocperip = 10;
1317
		}
1318
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1319
	}
1320

    
1321
	if (empty($port)) {
1322
		$nginx_port = "80";
1323
	} else {
1324
		$nginx_port = $port;
1325
	}
1326

    
1327
	$memory = get_memory();
1328
	$realmem = $memory[1];
1329

    
1330
	// Determine web GUI process settings and take into account low memory systems
1331
	if ($realmem < 255) {
1332
		$max_procs = 1;
1333
	} else {
1334
		$max_procs = config_get_path('system/webgui/max_procs', 2);
1335
	}
1336

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

    
1348
	$nginx_config = <<<EOD
1349
#
1350
# nginx configuration file
1351

    
1352
pid {$g['varrun_path']}/{$pid_file};
1353

    
1354
user  root wheel;
1355
worker_processes  {$max_procs};
1356

    
1357
EOD;
1358

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

    
1366
	$nginx_config .= <<<EOD
1367

    
1368
events {
1369
    worker_connections  1024;
1370
}
1371

    
1372
http {
1373
	include       /usr/local/etc/nginx/mime.types;
1374
	default_type  application/octet-stream;
1375
	add_header X-Frame-Options SAMEORIGIN;
1376
	server_tokens off;
1377

    
1378
	sendfile        off;
1379

    
1380
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1381

    
1382
EOD;
1383

    
1384
	if ($captive_portal !== false) {
1385
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1386
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1387
	} else {
1388
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1389
	}
1390

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

    
1431
	$nginx_config .= <<<EOD
1432

    
1433
		client_max_body_size 200m;
1434

    
1435
		gzip on;
1436
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
1437

    
1438

    
1439
EOD;
1440

    
1441
	if ($captive_portal !== false) {
1442
		$nginx_config .= <<<EOD
1443
$captive_portal_maxprocperip
1444
$cp_hostcheck
1445
$cp_rewrite
1446
		log_not_found off;
1447

    
1448
EOD;
1449

    
1450
	}
1451

    
1452
	$plugin_locations = "";
1453
	if ($captive_portal == false) {
1454
		$pluginparams = [ 'section' => 'location' ];
1455
		foreach (pkg_call_plugins('plugin_nginx', $pluginparams) as $pkgname => $location) {
1456
			if (empty($location)) {
1457
				continue;
1458
			}
1459
			$plugin_locations .= "# Plugin Locations ({$pkgname})\n";
1460
			$plugin_locations .= "{$location}\n";
1461
		}
1462
	}
1463

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

    
1499
EOD;
1500

    
1501
	$cert = str_replace("\r", "", $cert);
1502
	$key = str_replace("\r", "", $key);
1503

    
1504
	$cert = str_replace("\n\n", "\n", $cert);
1505
	$key = str_replace("\n\n", "\n", $key);
1506

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

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

    
1543
EOD;
1544
	}
1545

    
1546
	if ($captive_portal == false) {
1547
		$pluginparams = [ 'section' => 'server' ];
1548
		foreach (pkg_call_plugins('plugin_nginx', $pluginparams) as $pkgname => $server) {
1549
			if (empty($server)) {
1550
				continue;
1551
			}
1552
			$nginx_config .= "	# Plugin Servers ({$pkgname})\n";
1553
			$nginx_config .= "{$server}\n";
1554
		}
1555
	}
1556

    
1557
	$nginx_config .= "}\n";
1558

    
1559
	$fd = fopen("{$filename}", "w");
1560
	if (!$fd) {
1561
		printf(gettext('Error: cannot open %1$s in system_generate_nginx_config().%2$s'), $filename, "\n");
1562
		return 1;
1563
	}
1564
	fwrite($fd, $nginx_config);
1565
	fclose($fd);
1566

    
1567
	/* nginx will fail to start if this directory does not exist. */
1568
	safe_mkdir("/var/tmp/nginx/");
1569

    
1570
	return 0;
1571

    
1572
}
1573

    
1574
function system_get_timezone_list() {
1575
	global $g;
1576

    
1577
	$file_list = array_merge(
1578
		glob("/usr/share/zoneinfo/[A-Z]*"),
1579
		glob("/usr/share/zoneinfo/*/*"),
1580
		glob("/usr/share/zoneinfo/*/*/*")
1581
	);
1582

    
1583
	if (empty($file_list)) {
1584
		$file_list[] = g_get('default_timezone');
1585
	} else {
1586
		/* Remove directories from list */
1587
		$file_list = array_filter($file_list, function($v) {
1588
			return !is_dir($v);
1589
		});
1590
	}
1591

    
1592
	/* Remove directory prefix */
1593
	$file_list = str_replace('/usr/share/zoneinfo/', '', $file_list);
1594

    
1595
	sort($file_list);
1596

    
1597
	return $file_list;
1598
}
1599

    
1600
function system_timezone_configure() {
1601
	global $g;
1602
	if (config_path_enabled('system', 'developerspew')) {
1603
		$mt = microtime();
1604
		echo "system_timezone_configure() being called $mt\n";
1605
	}
1606

    
1607
	$syscfg = config_get_path('system');
1608

    
1609
	if (platform_booting()) {
1610
		echo gettext("Setting timezone...");
1611
	}
1612

    
1613
	/* extract appropriate timezone file */
1614
	$timezone = (isset($syscfg['timezone']) ? $syscfg['timezone'] : g_get('default_timezone'));
1615
	/* DO NOT remove \n otherwise tzsetup will fail */
1616
	@file_put_contents("/var/db/zoneinfo", $timezone . "\n");
1617
	mwexec("/usr/sbin/tzsetup -r");
1618

    
1619
	if (platform_booting()) {
1620
		echo gettext("done.") . "\n";
1621
	}
1622
}
1623

    
1624
function check_gps_speed($device) {
1625
	usleep(1000);
1626
	// Set timeout to 5s
1627
	$timeout=microtime(true)+5;
1628
	if ($fp = fopen($device, 'r')) {
1629
		stream_set_blocking($fp, 0);
1630
		stream_set_timeout($fp, 5);
1631
		$contents = "";
1632
		$cnt = 0;
1633
		$buffersize = 256;
1634
		do {
1635
			$c = fread($fp, $buffersize - $cnt);
1636

    
1637
			// Wait for data to arive
1638
			if (($c === false) || (strlen($c) == 0)) {
1639
				usleep(500);
1640
				continue;
1641
			}
1642

    
1643
			$contents.=$c;
1644
			$cnt = $cnt + strlen($c);
1645
		} while (($cnt < $buffersize) && (microtime(true) < $timeout));
1646
		fclose($fp);
1647

    
1648
		$nmeasentences = ['RMC', 'GGA', 'GLL', 'ZDA', 'ZDG', 'PGRMF'];
1649
		foreach ($nmeasentences as $sentence) {
1650
			if (strpos($contents, $sentence) > 0) {
1651
				return true;
1652
			}
1653
		}
1654
		if (strpos($contents, '0') > 0) {
1655
			$filters = ['`', '?', '/', '~'];
1656
			foreach ($filters as $filter) {
1657
				if (strpos($contents, $filter) !== false) {
1658
					return false;
1659
				}
1660
			}
1661
			return true;
1662
		}
1663
	}
1664
	return false;
1665
}
1666

    
1667
/* Generate list of possible NTP poll values
1668
 * https://redmine.pfsense.org/issues/9439 */
1669
global $ntp_poll_min_value, $ntp_poll_max_value;
1670
global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
1671
global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
1672
global $ntp_poll_min_default, $ntp_poll_max_default;
1673
global $ntp_auth_halgos, $ntp_server_types;
1674
$ntp_poll_min_value = 3;
1675
$ntp_poll_max_value = 17;
1676
$ntp_poll_min_default_gps = 4;
1677
$ntp_poll_max_default_gps = 4;
1678
$ntp_poll_min_default_pps = 4;
1679
$ntp_poll_max_default_pps = 4;
1680
$ntp_poll_min_default = 'omit';
1681
$ntp_poll_max_default = 9;
1682
$ntp_auth_halgos = array(
1683
	'md5' => 'MD5',
1684
	'sha1' => 'SHA1',
1685
	'sha256' => 'SHA256'
1686
);
1687
$ntp_server_types = array(
1688
	'server' => 'Server',
1689
	'pool' => 'Pool',
1690
	'peer' => 'Peer'
1691
);
1692

    
1693
function system_ntp_poll_values() {
1694
	global $ntp_poll_min_value, $ntp_poll_max_value;
1695
	$poll_values = array("" => gettext('Default'));
1696

    
1697
	for ($i = $ntp_poll_min_value; $i <= $ntp_poll_max_value; $i++) {
1698
		$sec = 2 ** $i;
1699
		$poll_values[$i] = $i . ': ' . number_format($sec) . ' ' . gettext('seconds') .
1700
					' (' . convert_seconds_to_dhms($sec) . ')';
1701
	}
1702

    
1703
	$poll_values['omit'] = gettext('Omit (Do not set)');
1704
	return $poll_values;
1705
}
1706

    
1707
function system_ntp_fixup_poll_value($type, $configvalue, $default) {
1708
	$pollstring = "";
1709

    
1710
	if (empty($configvalue)) {
1711
		$configvalue = $default;
1712
	}
1713

    
1714
	if ($configvalue != 'omit') {
1715
		$pollstring = " {$type} {$configvalue}";
1716
	}
1717

    
1718
	return $pollstring;
1719
}
1720

    
1721
function system_ntp_setup_gps($serialport) {
1722
	if (config_get_path('ntpd/enable') == 'disabled') {
1723
		return false;
1724
	}
1725

    
1726
	init_config_arr(array('ntpd', 'gps'));
1727
	$serialports = get_serial_ports(true);
1728

    
1729
	if (!array_key_exists($serialport, $serialports)) {
1730
		return false;
1731
	}
1732

    
1733
	$gps_device = '/dev/gps0';
1734
	$serialport = '/dev/'.basename($serialport);
1735

    
1736
	if (!file_exists($serialport)) {
1737
		return false;
1738
	}
1739

    
1740
	// Create symlink that ntpd requires
1741
	unlink_if_exists($gps_device);
1742
	@symlink($serialport, $gps_device);
1743

    
1744
	$speeds = array(
1745
		0 => '4800',
1746
		16 => '9600',
1747
		32 => '19200',
1748
		48 => '38400',
1749
		64 => '57600',
1750
		80 => '115200'
1751
	);
1752
	// $gpsbaud defaults to '4800' if ntpd/gps/speed is unset or does not exist in $speeds
1753
	$gpsbaud = array_get_path($speeds, config_get_path('ntpd/gps/speed', 0), '4800');
1754

    
1755
	system_ntp_setup_rawspeed($serialport, $gpsbaud);
1756

    
1757
	$gpsspeed = config_get_path('ntpd/gps/speed');
1758
	$autospeed = ($gpsspeed == 'autoalways' || $gpsspeed == 'autoset');
1759
	if ($autospeed || (config_get_path('ntpd/gps/autobaudinit') && !check_gps_speed($gps_device))) {
1760
		$found = false;
1761
		foreach ($speeds as $baud) {
1762
			system_ntp_setup_rawspeed($serialport, $baud);
1763
			if ($found = check_gps_speed($gps_device)) {
1764
				if ($autospeed) {
1765
					$saveconfig = (config_get_path('ntpd/gps/speed') == 'autoset');
1766
					config_set_path('ntpd/gps/speed', array_search($baud, $speeds));
1767
					$gpsbaud = $baud;
1768
					if ($saveconfig) {
1769
						write_config(sprintf(gettext('Autoset GPS baud rate to %s'), $baud));
1770
					}
1771
				}
1772
				break;
1773
			}
1774
		}
1775
		if ($found === false) {
1776
			log_error(gettext("Could not find correct GPS baud rate."));
1777
			return false;
1778
		}
1779
	}
1780

    
1781
	/* Send the following to the GPS port to initialize the GPS */
1782
	if (!empty(config_get_path('ntpd/gps/type'))) {
1783
		$gps_init = base64_decode(config_get_path('ntpd/gps/initcmd'));
1784
	} else {
1785
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1786
	}
1787

    
1788
	/* XXX: Why not file_put_contents to the device */
1789
	@file_put_contents('/tmp/gps.init', $gps_init);
1790
	mwexec("/bin/cat /tmp/gps.init > {$serialport}");
1791

    
1792
	if ($found && config_get_path('ntpd/gps/autobaudinit')) {
1793
		system_ntp_setup_rawspeed($serialport, $gpsbaud);
1794
	}
1795

    
1796
	/* Remove old /etc/remote entry if it exists */
1797
	if (mwexec("/usr/bin/grep -c '^gps0' /etc/remote") == 0) {
1798
		mwexec("/usr/bin/sed -i '' -n '/gps0/!p' /etc/remote");
1799
	}
1800

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

    
1806
	return true;
1807
}
1808

    
1809
// Configure the serial port for raw IO and set the speed
1810
function system_ntp_setup_rawspeed($serialport, $baud) {
1811
	mwexec("/bin/stty -f " .  escapeshellarg($serialport) . " raw speed " . escapeshellarg($baud));
1812
	mwexec("/bin/stty -f " .  escapeshellarg($serialport) . ".init raw speed " . escapeshellarg($baud));
1813
}
1814

    
1815
function system_ntp_setup_pps($serialport) {
1816
	$serialports = get_serial_ports(true);
1817

    
1818
	if (!array_key_exists($serialport, $serialports)) {
1819
		return false;
1820
	}
1821

    
1822
	$pps_device = '/dev/pps0';
1823
	$serialport = '/dev/'.basename($serialport);
1824

    
1825
	if (!file_exists($serialport)) {
1826
		return false;
1827
	}
1828
	// If ntpd is disabled, just return
1829
	if (config_get_path('ntpd/enable') == 'disabled') {
1830
		return false;
1831
	}
1832

    
1833
	// Create symlink that ntpd requires
1834
	unlink_if_exists($pps_device);
1835
	@symlink($serialport, $pps_device);
1836

    
1837

    
1838
	return true;
1839
}
1840

    
1841
function system_ntp_configure() {
1842
	global $g;
1843
	global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
1844
	global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
1845
	global $ntp_poll_min_default, $ntp_poll_max_default;
1846

    
1847
	$driftfile = "/var/db/ntpd.drift";
1848
	$statsdir = "/var/log/ntp";
1849
	$gps_device = '/dev/gps0';
1850

    
1851
	safe_mkdir($statsdir);
1852

    
1853
	init_config_arr(array('ntpd'));
1854

    
1855
	// ntpd is disabled, just stop it and return
1856
	if (config_get_path('ntpd/enable') == 'disabled') {
1857
		while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1858
			killbypid("{$g['varrun_path']}/ntpd.pid");
1859
		}
1860
		@unlink("{$g['varrun_path']}/ntpd.pid");
1861
		@unlink("{$g['varetc_path']}/ntpd.conf");
1862
		@unlink("{$g['varetc_path']}/ntp.keys");
1863
		log_error("NTPD is disabled.");
1864
		return;
1865
	}
1866

    
1867
	if (platform_booting()) {
1868
		echo gettext("Starting NTP Server...");
1869
	}
1870

    
1871
	/* if ntpd is running, kill it */
1872
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1873
		killbypid("{$g['varrun_path']}/ntpd.pid");
1874
	}
1875
	@unlink("{$g['varrun_path']}/ntpd.pid");
1876

    
1877
	/* set NTP server authentication key */
1878
	if (config_get_path('ntpd/serverauth') == 'yes') {
1879
		$ntpkeyscfg = "1 " . strtoupper(config_get_path('ntpd/serverauthalgo')) . " " . base64_decode(config_get_path('ntpd/serverauthkey')) . "\n";
1880
		if (!@file_put_contents("{$g['varetc_path']}/ntp.keys", $ntpkeyscfg)) {
1881
			log_error(sprintf(gettext("Could not open %s/ntp.keys for writing"), g_get('varetc_path')));
1882
			return;
1883
		}
1884
	} else {
1885
		unlink_if_exists("{$g['varetc_path']}/ntp.keys");
1886
	}
1887

    
1888
	$ntpcfg = "# \n";
1889
	$ntpcfg .= "# pfSense ntp configuration file \n";
1890
	$ntpcfg .= "# \n\n";
1891
	$ntpcfg .= "tinker panic 0 \n\n";
1892

    
1893
	if (config_get_path('ntpd/serverauth') == 'yes') {
1894
		$ntpcfg .= "# Authentication settings \n";
1895
		$ntpcfg .= "keys /var/etc/ntp.keys \n";
1896
		$ntpcfg .= "trustedkey 1 \n";
1897
		$ntpcfg .= "requestkey 1 \n";
1898
		$ntpcfg .= "controlkey 1 \n";
1899
		$ntpcfg .= "\n";
1900
	}
1901

    
1902
	/* Add Orphan mode */
1903
	$ntpcfg .= "# Orphan mode stratum and Maximum candidate NTP peers\n";
1904
	$ntpcfg .= 'tos orphan ';
1905
	if (!empty(config_get_path('ntpd/orphan'))) {
1906
		$ntpcfg .= config_get_path('ntpd/orphan');
1907
	} else {
1908
		$ntpcfg .= '12';
1909
	}
1910
	/* Add Maximum candidate NTP peers */
1911
	$ntpcfg .= ' maxclock ';
1912
	if (!empty(config_get_path('ntpd/ntpmaxpeers'))) {
1913
		$ntpcfg .= config_get_path('ntpd/ntpmaxpeers');
1914
	} else {
1915
		$ntpcfg .= '5';
1916
	}
1917
	$ntpcfg .= "\n";
1918

    
1919
	/* Add PPS configuration */
1920
	if (!empty(config_get_path('ntpd/pps/port')) &&
1921
	    file_exists('/dev/'.config_get_path('ntpd/pps/port')) &&
1922
	    system_ntp_setup_pps(config_get_path('ntpd/pps/port'))) {
1923
		$ntpcfg .= "\n";
1924
		$ntpcfg .= "# PPS Setup\n";
1925
		$ntpcfg .= 'server 127.127.22.0';
1926
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', config_get_path('ntpd/pps/ppsminpoll'), $ntp_poll_min_default_pps);
1927
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', config_get_path('ntpd/pps/ppsmaxpoll'), $ntp_poll_max_default_pps);
1928
		if (empty(config_get_path('ntpd/pps/prefer'))) { /*note: this one works backwards */
1929
			$ntpcfg .= ' prefer';
1930
		}
1931
		if (!empty(config_get_path('ntpd/pps/noselect'))) {
1932
			$ntpcfg .= ' noselect ';
1933
		}
1934
		$ntpcfg .= "\n";
1935
		$ntpcfg .= 'fudge 127.127.22.0';
1936
		if (!empty(config_get_path('ntpd/pps/fudge1'))) {
1937
			$ntpcfg .= ' time1 ';
1938
			$ntpcfg .= config_get_path('ntpd/pps/fudge1');
1939
		}
1940
		if (!empty(config_get_path('ntpd/pps/flag2'))) {
1941
			$ntpcfg .= ' flag2 1';
1942
		}
1943
		if (!empty(config_get_path('ntpd/pps/flag3'))) {
1944
			$ntpcfg .= ' flag3 1';
1945
		} else {
1946
			$ntpcfg .= ' flag3 0';
1947
		}
1948
		if (!empty(config_get_path('ntpd/pps/flag4'))) {
1949
			$ntpcfg .= ' flag4 1';
1950
		}
1951
		if (!empty(config_get_path('ntpd/pps/refid'))) {
1952
			$ntpcfg .= ' refid ';
1953
			$ntpcfg .= config_get_path('ntpd/pps/refid');
1954
		}
1955
		$ntpcfg .= "\n";
1956
	}
1957
	/* End PPS configuration */
1958

    
1959
	/* Add GPS configuration */
1960
	if (!empty(config_get_path('ntpd/gps/port')) &&
1961
	    system_ntp_setup_gps(config_get_path('ntpd/gps/port'))) {
1962
		$ntpcfg .= "\n";
1963
		$ntpcfg .= "# GPS Setup\n";
1964
		$ntpcfg .= 'server 127.127.20.0 mode ';
1965
		if (!empty(config_get_path('ntpd/gps/nmea')) || !empty(config_get_path('ntpd/gps/speed')) || !empty(config_get_path('ntpd/gps/subsec')) || !empty(config_get_path('ntpd/gps/processpgrmf'))) {
1966
			if (!empty(config_get_path('ntpd/gps/nmea'))) {
1967
				$ntpmode = (int) config_get_path('ntpd/gps/nmea');
1968
			}
1969
			if (!empty(config_get_path('ntpd/gps/speed'))) {
1970
				$ntpmode += (int) config_get_path('ntpd/gps/speed');
1971
			}
1972
			if (!empty(config_get_path('ntpd/gps/subsec'))) {
1973
				$ntpmode += 128;
1974
			}
1975
			if (!empty(config_get_path('ntpd/gps/processpgrmf'))) {
1976
				$ntpmode += 256;
1977
			}
1978
			$ntpcfg .= (string) $ntpmode;
1979
		} else {
1980
			$ntpcfg .= '0';
1981
		}
1982
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', config_get_path('ntpd/gps/gpsminpoll'), $ntp_poll_min_default_gps);
1983
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', config_get_path('ntpd/gps/gpsmaxpoll'), $ntp_poll_max_default_gps);
1984

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

    
2061
		$ntpcfg .= "{$ts}";
2062
		if (!substr_count(config_get_path('ntpd/ispeer'), $ts)) {
2063
			$ntpcfg .= " iburst";
2064
		}
2065

    
2066
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', config_get_path('ntpd/ntpminpoll'), $ntp_poll_min_default);
2067
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', config_get_path('ntpd/ntpmaxpoll'), $ntp_poll_max_default);
2068

    
2069
		if (substr_count(config_get_path('ntpd/prefer'), $ts)) {
2070
			$ntpcfg .= ' prefer';
2071
		}
2072
		if (substr_count(config_get_path('ntpd/noselect'), $ts)) {
2073
			$ntpcfg .= ' noselect';
2074
		}
2075
		$ntpcfg .= "\n";
2076
	}
2077
	unset($ts);
2078

    
2079
	$ntpcfg .= "\n\n";
2080
	if (!empty(config_get_path('ntpd/clockstats')) || !empty(config_get_path('ntpd/loopstats')) || !empty(config_get_path('ntpd/peerstats'))) {
2081
		$ntpcfg .= "enable stats\n";
2082
		$ntpcfg .= 'statistics';
2083
		if (!empty(config_get_path('ntpd/clockstats'))) {
2084
			$ntpcfg .= ' clockstats';
2085
		}
2086
		if (!empty(config_get_path('ntpd/loopstats'))) {
2087
			$ntpcfg .= ' loopstats';
2088
		}
2089
		if (!empty(config_get_path('ntpd/peerstats'))) {
2090
			$ntpcfg .= ' peerstats';
2091
		}
2092
		$ntpcfg .= "\n";
2093
	}
2094
	$ntpcfg .= "statsdir {$statsdir}\n";
2095
	$ntpcfg .= 'logconfig =syncall +clockall';
2096
	if (!empty(config_get_path('ntpd/logpeer'))) {
2097
		$ntpcfg .= ' +peerall';
2098
	}
2099
	if (!empty(config_get_path('ntpd/logsys'))) {
2100
		$ntpcfg .= ' +sysall';
2101
	}
2102
	$ntpcfg .= "\n";
2103
	$ntpcfg .= "driftfile {$driftfile}\n";
2104

    
2105
	/* Default Access restrictions */
2106
	$ntpcfg .= 'restrict default';
2107
	if (empty(config_get_path('ntpd/kod'))) { /*note: this one works backwards */
2108
		$ntpcfg .= ' kod limited';
2109
	}
2110
	if (empty(config_get_path('ntpd/nomodify'))) { /*note: this one works backwards */
2111
		$ntpcfg .= ' nomodify';
2112
	}
2113
	if (!empty(config_get_path('ntpd/noquery'))) {
2114
		$ntpcfg .= ' noquery';
2115
	}
2116
	if (empty(config_get_path('ntpd/nopeer'))) { /*note: this one works backwards */
2117
		$ntpcfg .= ' nopeer';
2118
	}
2119
	if (empty(config_get_path('ntpd/notrap'))) { /*note: this one works backwards */
2120
		$ntpcfg .= ' notrap';
2121
	}
2122
	if (!empty(config_get_path('ntpd/noserve'))) {
2123
		$ntpcfg .= ' noserve';
2124
	}
2125
	$ntpcfg .= "\nrestrict -6 default";
2126
	if (empty(config_get_path('ntpd/kod'))) { /*note: this one works backwards */
2127
		$ntpcfg .= ' kod limited';
2128
	}
2129
	if (empty(config_get_path('ntpd/nomodify'))) { /*note: this one works backwards */
2130
		$ntpcfg .= ' nomodify';
2131
	}
2132
	if (!empty(config_get_path('ntpd/noquery'))) {
2133
		$ntpcfg .= ' noquery';
2134
	}
2135
	if (empty(config_get_path('ntpd/nopeer'))) { /*note: this one works backwards */
2136
		$ntpcfg .= ' nopeer';
2137
	}
2138
	if (!empty(config_get_path('ntpd/noserve'))) {
2139
		$ntpcfg .= ' noserve';
2140
	}
2141
	if (empty(config_get_path('ntpd/notrap'))) { /*note: this one works backwards */
2142
		$ntpcfg .= ' notrap';
2143
	}
2144

    
2145
	/* Pools require "restrict source" and cannot contain "nopeer" and "noserve". */
2146
	if ($have_pools) {
2147
		$ntpcfg .= "\nrestrict source";
2148
		if (empty(config_get_path('ntpd/kod'))) { /*note: this one works backwards */
2149
			$ntpcfg .= ' kod limited';
2150
		}
2151
		if (empty(config_get_path('ntpd/nomodify'))) { /*note: this one works backwards */
2152
			$ntpcfg .= ' nomodify';
2153
		}
2154
		if (!empty(config_get_path('ntpd/noquery'))) {
2155
			$ntpcfg .= ' noquery';
2156
		}
2157
		if (empty(config_get_path('ntpd/notrap'))) { /*note: this one works backwards */
2158
			$ntpcfg .= ' notrap';
2159
		}
2160
	}
2161

    
2162
	/* Custom Access Restrictions */
2163
	if (is_array(config_get_path('ntpd/restrictions/row'))) {
2164
		$networkacl = config_get_path('ntpd/restrictions/row');
2165
		foreach ($networkacl as $acl) {
2166
			$restrict = "";
2167
			if (is_ipaddrv6($acl['acl_network'])) {
2168
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask_v6($acl['mask']) . " ";
2169
			} elseif (is_ipaddrv4($acl['acl_network'])) {
2170
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask($acl['mask']) . " ";
2171
			} else {
2172
				continue;
2173
			}
2174
			if (!empty($acl['kod'])) {
2175
				$restrict .= ' kod limited';
2176
			}
2177
			if (!empty($acl['nomodify'])) {
2178
				$restrict .= ' nomodify';
2179
			}
2180
			if (!empty($acl['noquery'])) {
2181
				$restrict .= ' noquery';
2182
			}
2183
			if (!empty($acl['nopeer'])) {
2184
				$restrict .= ' nopeer';
2185
			}
2186
			if (!empty($acl['noserve'])) {
2187
				$restrict .= ' noserve';
2188
			}
2189
			if (!empty($acl['notrap'])) {
2190
				$restrict .= ' notrap';
2191
			}
2192
			if (!empty($restrict)) {
2193
				$ntpcfg .= "\nrestrict {$restrict} ";
2194
			}
2195
		}
2196
	}
2197
	/* End Custom Access Restrictions */
2198

    
2199
	/* A leapseconds file is really only useful if this clock is stratum 1 */
2200
	$ntpcfg .= "\n";
2201
	if (!empty(config_get_path('ntpd/leapsec'))) {
2202
		$leapsec .= base64_decode(config_get_path('ntpd/leapsec'));
2203
		file_put_contents('/var/db/leap-seconds', $leapsec);
2204
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
2205
	}
2206

    
2207

    
2208
	if (empty(config_get_path('ntpd/interface'))) {
2209
		$interfaces =
2210
			explode(",",
2211
					config_get_path('installedpackages/openntpd/config/0/interface', ''));
2212
	} else {
2213
		$interfaces = explode(",", config_get_path('ntpd/interface'));
2214
	}
2215

    
2216
	if (is_array($interfaces) && count($interfaces)) {
2217
		$finterfaces = array();
2218
		foreach ($interfaces as $interface) {
2219
			$interface = get_real_interface($interface);
2220
			if (!empty($interface)) {
2221
				$finterfaces[] = $interface;
2222
			}
2223
		}
2224
		if (!empty($finterfaces)) {
2225
			$ntpcfg .= "interface ignore all\n";
2226
			$ntpcfg .= "interface ignore wildcard\n";
2227
			foreach ($finterfaces as $interface) {
2228
				$ntpcfg .= "interface listen {$interface}\n";
2229
			}
2230
		}
2231
	}
2232

    
2233
	/* open configuration for writing or bail */
2234
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
2235
		log_error(sprintf(gettext("Could not open %s/ntpd.conf for writing"), g_get('varetc_path')));
2236
		return;
2237
	}
2238

    
2239
	/* if /var/empty does not exist, create it */
2240
	if (!is_dir("/var/empty")) {
2241
		mkdir("/var/empty", 0555, true);
2242
	}
2243

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

    
2247
	// Note that we are starting up
2248
	log_error("NTPD is starting up.");
2249

    
2250
	if (platform_booting()) {
2251
		echo gettext("done.") . "\n";
2252
	}
2253

    
2254
	return;
2255
}
2256

    
2257
function system_halt() {
2258
	global $g;
2259

    
2260
	system_reboot_cleanup();
2261

    
2262
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
2263
}
2264

    
2265
function system_reboot() {
2266
	global $g;
2267

    
2268
	system_reboot_cleanup();
2269

    
2270
	mwexec("/usr/bin/nohup /etc/rc.reboot > /dev/null 2>&1 &");
2271
}
2272

    
2273
function system_reboot_sync($reroot=false) {
2274
	global $g;
2275

    
2276
	if ($reroot) {
2277
		$args = " -r ";
2278
	}
2279

    
2280
	system_reboot_cleanup();
2281

    
2282
	mwexec("/etc/rc.reboot {$args} > /dev/null 2>&1");
2283
}
2284

    
2285
function system_reboot_cleanup() {
2286
	global $g, $cpzone;
2287

    
2288
	mwexec("/usr/local/bin/beep.sh stop");
2289
	require_once("captiveportal.inc");
2290
	$cps = config_get_path('captiveportal', []);
2291
	foreach ($cps as $cpzone=>$cp) {
2292
		if (!isset($cp['preservedb'])) {
2293
			/* send Accounting-Stop packet for all clients, termination cause 'Admin-Reboot' */
2294
			captiveportal_radius_stop_all(7); // Admin-Reboot
2295
			unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
2296
			captiveportal_free_dnrules();
2297
		}
2298
		/* Send Accounting-Off packet to the RADIUS server */
2299
		captiveportal_send_server_accounting('off');
2300
	}
2301

    
2302
	if (count($cps)> 0) {
2303
		/* Remove the pipe database */
2304
		unlink_if_exists("{$g['vardb_path']}/captiveportaldn.rules");
2305
	}
2306

    
2307
	require_once("voucher.inc");
2308
	voucher_save_db_to_config();
2309
	require_once("pfsense-utils.inc");
2310
	enable_carp(false);
2311
	require_once("pkg-utils.inc");
2312
	stop_packages();
2313
}
2314

    
2315
function system_do_shell_commands($early = 0) {
2316
	if (config_path_enabled('system', 'developerspew')) {
2317
		$mt = microtime();
2318
		echo "system_do_shell_commands() being called $mt\n";
2319
	}
2320

    
2321
	if ($early) {
2322
		$cmdn = "earlyshellcmd";
2323
	} else {
2324
		$cmdn = "shellcmd";
2325
	}
2326

    
2327
	$syscmd = config_get_path("system/{$cmdn}", '');
2328
	if (is_array($syscmd)) {
2329
		/* *cmd is an array, loop through */
2330
		foreach ($syscmd as $cmd) {
2331
			exec($cmd);
2332
		}
2333

    
2334
	} elseif ($syscmd <> "") {
2335
		/* execute single item */
2336
		exec($syscmd);
2337

    
2338
	}
2339
}
2340

    
2341
function system_dmesg_save() {
2342
	global $g;
2343
	if (config_path_enabled('system', 'developerspew')) {
2344
		$mt = microtime();
2345
		echo "system_dmesg_save() being called $mt\n";
2346
	}
2347

    
2348
	$dmesg = "";
2349
	$_gb = exec("/sbin/dmesg", $dmesg);
2350

    
2351
	/* find last copyright line (output from previous boots may be present) */
2352
	$lastcpline = 0;
2353

    
2354
	for ($i = 0; $i < count($dmesg); $i++) {
2355
		if (strstr($dmesg[$i], "Copyright (c) 1992-")) {
2356
			$lastcpline = $i;
2357
		}
2358
	}
2359

    
2360
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
2361
	if (!$fd) {
2362
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
2363
		return 1;
2364
	}
2365

    
2366
	for ($i = $lastcpline; $i < count($dmesg); $i++) {
2367
		fwrite($fd, $dmesg[$i] . "\n");
2368
	}
2369

    
2370
	fclose($fd);
2371
	unset($dmesg);
2372

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

    
2376
	return 0;
2377
}
2378

    
2379
function system_set_harddisk_standby() {
2380
	if (config_path_enabled('system', 'developerspew')) {
2381
		$mt = microtime();
2382
		echo "system_set_harddisk_standby() being called $mt\n";
2383
	}
2384

    
2385
	if (config_path_enabled('system', 'harddiskstandby')) {
2386
		if (platform_booting()) {
2387
			echo gettext('Setting hard disk standby... ');
2388
		}
2389

    
2390
		$standby = config_get_path('system/harddiskstandby');
2391
		// Check for a numeric value
2392
		if (is_numeric($standby)) {
2393
			// Get only suitable candidates for standby; using get_smart_drive_list()
2394
			// from utils.inc to get the list of drives.
2395
			$harddisks = get_smart_drive_list();
2396

    
2397
			// Since get_smart_drive_list() only matches ad|da|ada; lets put the check below
2398
			// just in case of some weird pfSense platform installs.
2399
			if (count($harddisks) > 0) {
2400
				// Iterate disks and run the camcontrol command for each
2401
				foreach ($harddisks as $harddisk) {
2402
					mwexec("/sbin/camcontrol standby {$harddisk} -t {$standby}");
2403
				}
2404
				if (platform_booting()) {
2405
					echo gettext("done.") . "\n";
2406
				}
2407
			} else if (platform_booting()) {
2408
				echo gettext("failed!") . "\n";
2409
			}
2410
		} else if (platform_booting()) {
2411
			echo gettext("failed!") . "\n";
2412
		}
2413
	}
2414
}
2415

    
2416
function system_setup_sysctl() {
2417
	if (config_path_enabled('system', 'developerspew')) {
2418
		$mt = microtime();
2419
		echo "system_setup_sysctl() being called $mt\n";
2420
	}
2421

    
2422
	activate_sysctls();
2423

    
2424
	if (config_path_enabled('system', 'sharednet')) {
2425
		system_disable_arp_wrong_if();
2426
	}
2427
}
2428

    
2429
function system_disable_arp_wrong_if() {
2430
	if (config_path_enabled('system', 'developerspew')) {
2431
		$mt = microtime();
2432
		echo "system_disable_arp_wrong_if() being called $mt\n";
2433
	}
2434
	set_sysctl(array(
2435
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
2436
		"net.link.ether.inet.log_arp_movements" => "0"
2437
	));
2438
}
2439

    
2440
function system_enable_arp_wrong_if() {
2441
	if (config_path_enabled('system', 'developerspew')) {
2442
		$mt = microtime();
2443
		echo "system_enable_arp_wrong_if() being called $mt\n";
2444
	}
2445
	set_sysctl(array(
2446
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
2447
		"net.link.ether.inet.log_arp_movements" => "1"
2448
	));
2449
}
2450

    
2451
function enable_watchdog() {
2452
	return;
2453
	$install_watchdog = false;
2454
	$supported_watchdogs = array("Geode");
2455
	$file = file_get_contents("/var/log/dmesg.boot");
2456
	foreach ($supported_watchdogs as $sd) {
2457
		if (stristr($file, "Geode")) {
2458
			$install_watchdog = true;
2459
		}
2460
	}
2461
	if ($install_watchdog == true) {
2462
		if (is_process_running("watchdogd")) {
2463
			mwexec("/usr/bin/killall watchdogd", true);
2464
		}
2465
		exec("/usr/sbin/watchdogd");
2466
	}
2467
}
2468

    
2469
function system_check_reset_button() {
2470
	global $g;
2471

    
2472
	$specplatform = system_identify_specific_platform();
2473

    
2474
	switch ($specplatform['name']) {
2475
		case 'SG-2220':
2476
			$binprefix = "RCC-DFF";
2477
			break;
2478
		case 'alix':
2479
		case 'wrap':
2480
		case 'FW7541':
2481
		case 'APU':
2482
		case 'RCC-VE':
2483
		case 'RCC':
2484
			$binprefix = $specplatform['name'];
2485
			break;
2486
		default:
2487
			return 0;
2488
	}
2489

    
2490
	$retval = mwexec("/usr/local/sbin/" . $binprefix . "resetbtn");
2491

    
2492
	if ($retval == 99) {
2493
		/* user has pressed reset button for 2 seconds -
2494
		   reset to factory defaults */
2495
		echo <<<EOD
2496

    
2497
***********************************************************************
2498
* Reset button pressed - resetting configuration to factory defaults. *
2499
* All additional packages installed will be removed                   *
2500
* The system will reboot after this completes.                        *
2501
***********************************************************************
2502

    
2503

    
2504
EOD;
2505

    
2506
		reset_factory_defaults();
2507
		system_reboot_sync();
2508
		exit(0);
2509
	}
2510

    
2511
	return 0;
2512
}
2513

    
2514
function system_get_serial() {
2515
	$platform = system_identify_specific_platform();
2516

    
2517
	unset($output);
2518
	if ($platform['name'] == 'Turbot Dual-E') {
2519
		$if_info = get_interface_addresses('igb0');
2520
		if (!empty($if_info['hwaddr'])) {
2521
			$serial = str_replace(":", "", $if_info['hwaddr']);
2522
		}
2523
	} else {
2524
		foreach (array('system', 'planar', 'chassis') as $key) {
2525
			unset($output);
2526
			$_gb = exec("/bin/kenv -q smbios.{$key}.serial",
2527
			    $output);
2528
			if (!empty($output[0]) && $output[0] != "0123456789" &&
2529
			    preg_match('/^[\w\d]{10,16}$/', $output[0]) === 1) {
2530
				$serial = $output[0];
2531
				break;
2532
			}
2533
		}
2534
	}
2535

    
2536
	$vm_guest = get_single_sysctl('kern.vm_guest');
2537

    
2538
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2539
	    $vm_guest == 'none') {
2540
		return $serial;
2541
	}
2542

    
2543
	return "";
2544
}
2545

    
2546
function system_get_uniqueid() {
2547
	global $g;
2548

    
2549
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2550

    
2551
	if (empty(g_get('uniqueid'))) {
2552
		if (!file_exists($uniqueid_file)) {
2553
			mwexec("/usr/sbin/gnid > {$g['vardb_path']}/uniqueid " .
2554
			    "2>/dev/null");
2555
		}
2556
		if (file_exists($uniqueid_file)) {
2557
			$g['uniqueid'] = @file_get_contents($uniqueid_file);
2558
		}
2559
	}
2560

    
2561
	return (g_get('uniqueid') ?: '');
2562
}
2563

    
2564
/*
2565
 * attempt to identify the specific platform (for embedded systems)
2566
 * Returns an array with two elements:
2567
 * name => platform string (e.g. 'wrap', 'alix' etc.)
2568
 * descr => human-readable description (e.g. "PC Engines WRAP")
2569
 */
2570
function system_identify_specific_platform() {
2571
	global $g;
2572

    
2573
	$hw_model = get_single_sysctl('hw.model');
2574
	$hw_ncpu = get_single_sysctl('hw.ncpu');
2575

    
2576
	/* Try to guess from smbios strings */
2577
	unset($product);
2578
	unset($maker);
2579
	unset($bios);
2580
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $product);
2581
	$_gb = exec('/bin/kenv -q smbios.system.maker 2>/dev/null', $maker);
2582
	$_gb = exec('/bin/kenv -q smbios.bios.version 2>/dev/null', $bios);
2583

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

    
2587
	if ($maker[0] == "QEMU") {
2588
		return (array('name' => 'QEMU', 'descr' => 'QEMU Guest'));
2589
	} else  if ($maker[0] == "Google") {
2590
		return (array('name' => 'Google', 'descr' => 'Google Cloud Platform'));
2591
	} else  if ($maker[0] == "Amazon EC2") {
2592
		return (array('name' => 'AWS', 'descr' => 'Amazon Web Services'));
2593
	}
2594

    
2595
	// This switch needs to be expanded to include other virtualization systems
2596
	switch ($vm) {
2597
		case "none" :
2598
		break;
2599

    
2600
		case "kvm" :
2601
			return (array('name' => 'KVM', 'descr' => 'KVM Guest'));
2602
		break;
2603
	}
2604

    
2605
	// AWS and GCP can also be identified via the bios version
2606
	if (stripos($bios[0], "amazon") !== false) {
2607
		return (array('name' => 'AWS', 'descr' => 'Amazon Web Services'));
2608
	} else  if (stripos($bios[0], "Google") !== false) {
2609
		return (array('name' => 'Google', 'descr' => 'Google Cloud Platform'));
2610
	}
2611

    
2612
	switch ($product[0]) {
2613
		case 'FW7541':
2614
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2615
			break;
2616
		case 'apu1':
2617
		case 'APU':
2618
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2619
			break;
2620
		case 'RCC-VE':
2621
			$result = array();
2622
			$result['name'] = 'RCC-VE';
2623

    
2624
			/* Detect specific models */
2625
			if (!function_exists('does_interface_exist')) {
2626
				require_once("interfaces.inc");
2627
			}
2628
			if (!does_interface_exist('igb4')) {
2629
				$result['model'] = 'SG-2440';
2630
			} elseif (strpos($hw_model, "C2558") !== false) {
2631
				$result['model'] = 'SG-4860';
2632
			} elseif (strpos($hw_model, "C2758") !== false) {
2633
				$result['model'] = 'SG-8860';
2634
			} else {
2635
				$result['model'] = 'RCC-VE';
2636
			}
2637
			$result['descr'] = 'Netgate ' . $result['model'];
2638
			return $result;
2639
			break;
2640
		case 'DFFv2':
2641
			return (array('name' => 'SG-2220', 'descr' => 'Netgate SG-2220'));
2642
			break;
2643
		case 'RCC':
2644
			return (array('name' => 'RCC', 'descr' => 'Netgate XG-2758'));
2645
			break;
2646
		case 'SG-5100':
2647
			return (array('name' => '5100', 'descr' => 'Netgate 5100'));
2648
			break;
2649
		case 'Minnowboard Turbot D0 PLATFORM':
2650
		case 'Minnowboard Turbot D0/D1 PLATFORM':
2651
			$result = array();
2652
			$result['name'] = 'Turbot Dual-E';
2653
			/* Ensure the graphics driver is loaded */
2654
			system("kldload -nq i915kms");
2655
			/* Detect specific model */
2656
			switch ($hw_ncpu) {
2657
			case '4':
2658
				$result['model'] = 'MBT-4220';
2659
				break;
2660
			case '2':
2661
				$result['model'] = 'MBT-2220';
2662
				break;
2663
			default:
2664
				$result['model'] = $result['name'];
2665
				break;
2666
			}
2667
			$result['descr'] = 'Netgate ' . $result['model'];
2668
			return $result;
2669
			break;
2670
		case 'SYS-5018A-FTN4':
2671
		case 'A1SAi':
2672
			if (strpos($hw_model, "C2558") !== false) {
2673
				return (array(
2674
				    'name' => 'C2558',
2675
				    'descr' => 'Super Micro C2558'));
2676
			} elseif (strpos($hw_model, "C2758") !== false) {
2677
				return (array(
2678
				    'name' => 'C2758',
2679
				    'descr' => 'Super Micro C2758'));
2680
			}
2681
			break;
2682
		case 'SYS-5018D-FN4T':
2683
			if (strpos($hw_model, "D-1541") !== false) {
2684
				return (array('name' => '1541', 'descr' => 'Super Micro 1541'));
2685
			} else {
2686
				return (array('name' => '1540', 'descr' => 'Super Micro XG-1540'));
2687
			}
2688
			break;
2689
		case 'apu2':
2690
		case 'APU2':
2691
			return (array('name' => 'apu2', 'descr' => 'PC Engines APU2'));
2692
			break;
2693
		case 'VirtualBox':
2694
			return (array('name' => 'VirtualBox', 'descr' => 'VirtualBox Virtual Machine'));
2695
			break;
2696
		case 'Virtual Machine':
2697
			if ($maker[0] == "Microsoft Corporation") {
2698
				if (stripos($bios[0], "Hyper") !== false) {
2699
					return (array('name' => 'Hyper-V', 'descr' => 'Hyper-V Virtual Machine'));
2700
				} else {
2701
					return (array('name' => 'Azure', 'descr' => 'Microsoft Azure'));
2702
				}
2703
			}
2704
			break;
2705
		case 'VMware Virtual Platform':
2706
			if ($maker[0] == "VMware, Inc.") {
2707
				return (array('name' => 'VMware', 'descr' => 'VMware Virtual Machine'));
2708
			}
2709
			break;
2710
	}
2711

    
2712
	$_gb = exec('/bin/kenv -q smbios.planar.product 2>/dev/null',
2713
	    $planar_product);
2714
	if (isset($planar_product[0]) &&
2715
	    $planar_product[0] == 'X10SDV-8C-TLN4F+') {
2716
		return array('name' => '1537', 'descr' => 'Super Micro 1537');
2717
	}
2718

    
2719
	if (strpos($hw_model, "PC Engines WRAP") !== false) {
2720
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
2721
	}
2722

    
2723
	if (strpos($hw_model, "PC Engines ALIX") !== false) {
2724
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2725
	}
2726

    
2727
	if (preg_match("/Soekris net45../", $hw_model, $matches)) {
2728
		return array('name' => 'net45xx', 'descr' => $matches[0]);
2729
	}
2730

    
2731
	if (preg_match("/Soekris net48../", $hw_model, $matches)) {
2732
		return array('name' => 'net48xx', 'descr' => $matches[0]);
2733
	}
2734

    
2735
	if (preg_match("/Soekris net55../", $hw_model, $matches)) {
2736
		return array('name' => 'net55xx', 'descr' => $matches[0]);
2737
	}
2738

    
2739
	unset($hw_model);
2740

    
2741
	$dmesg_boot = system_get_dmesg_boot();
2742
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
2743
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2744
	}
2745
	unset($dmesg_boot);
2746

    
2747
	return array('name' => g_get('product_name'), 'descr' => g_get('product_label'));
2748
}
2749

    
2750
function system_get_dmesg_boot() {
2751
	global $g;
2752

    
2753
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2754
}
2755

    
2756
function system_get_arp_table($resolve_hostnames = false) {
2757
	$params="-a";
2758
	if (!$resolve_hostnames) {
2759
		$params .= "n";
2760
	}
2761

    
2762
	$arp_table = array();
2763
	$_gb = exec("/usr/sbin/arp --libxo json {$params}", $rawdata, $rc);
2764
	if ($rc == 0) {
2765
		$arp_table = json_decode(implode(" ", $rawdata),
2766
		    JSON_OBJECT_AS_ARRAY);
2767
		if ($rc == 0) {
2768
			$arp_table = $arp_table['arp']['arp-cache'];
2769
		}
2770
	}
2771

    
2772
	return $arp_table;
2773
}
2774

    
2775
function _getHostName($mac, $ip) {
2776
	global $dhcpmac, $dhcpip;
2777

    
2778
	if ($dhcpmac[$mac]) {
2779
		return $dhcpmac[$mac];
2780
	} else if ($dhcpip[$ip]) {
2781
		return $dhcpip[$ip];
2782
	} else {
2783
		exec("/usr/bin/host -W 1 " . escapeshellarg($ip), $output);
2784
		if (preg_match('/.*pointer ([A-Za-z_0-9.-]+)\..*/', $output[0], $matches)) {
2785
			if ($matches[1] <> $ip) {
2786
				return $matches[1];
2787
			}
2788
		}
2789
	}
2790
	return "";
2791
}
2792

    
2793
function check_dnsavailable($proto='inet') {
2794

    
2795
	if ($proto == 'inet') {
2796
		$gdns = array('8.8.8.8', '8.8.4.4');
2797
	} elseif ($proto == 'inet6') {
2798
		$gdns = array('2001:4860:4860::8888', '2001:4860:4860::8844');
2799
	} else {
2800
		$gdns = array('8.8.8.8', '8.8.4.4', '2001:4860:4860::8888', '2001:4860:4860::8844');
2801
	}
2802
	$nameservers = array_merge($gdns, get_dns_nameservers());
2803
	$test = 0;
2804

    
2805
	foreach ($gdns as $dns) {
2806
		if ($dns == '127.0.0.1') {
2807
			continue;
2808
		} else {
2809
			$dns_result = trim(_getHostName("", $dns));
2810
			if (($test == '2') && ($dns_result == "")) {
2811
				return false;
2812
			} elseif ($dns_result == "") {
2813
				$test++;
2814
				continue;
2815
			} else {
2816
				return true;
2817
			}
2818
		}
2819
	}
2820

    
2821
	return false;
2822
}
2823

    
2824
?>
(50-50/61)