Project

General

Profile

Download (73.3 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-2021 Rubicon Communications, LLC (Netgate)
9
 * All rights reserved.
10
 *
11
 * originally part of m0n0wall (http://m0n0.ch/wall)
12
 * Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>.
13
 * All rights reserved.
14
 *
15
 * Licensed under the Apache License, Version 2.0 (the "License");
16
 * you may not use this file except in compliance with the License.
17
 * You may obtain a copy of the License at
18
 *
19
 * http://www.apache.org/licenses/LICENSE-2.0
20
 *
21
 * Unless required by applicable law or agreed to in writing, software
22
 * distributed under the License is distributed on an "AS IS" BASIS,
23
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24
 * See the License for the specific language governing permissions and
25
 * limitations under the License.
26
 */
27

    
28
require_once('syslog.inc');
29

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

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

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

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

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

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

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

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

    
71
	return $output[0];
72
}
73

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

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

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

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

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

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

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

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

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

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

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

    
142
	set_sysctl($sysctls);
143
}
144

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

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

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

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

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

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

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

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

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

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

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

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

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

    
243
	unlock($dnslock);
244

    
245
	return 0;
246
}
247

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

    
251
	$master_list = array();
252

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

    
269
	return $master_list;
270
}
271

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

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

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

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

    
310
	return $master_list;
311
}
312

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

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

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

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

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

    
372
	return $hosts;
373
}
374

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

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

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

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

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

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

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

    
424
	return $hosts;
425
}
426

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
529
	return $hosts;
530
}
531

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

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

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

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

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

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

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

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

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

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

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

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

    
617
	return 0;
618
}
619

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

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

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

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

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

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

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

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

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

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

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

    
695
	$arp_table = system_get_arp_table();
696

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

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

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

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

    
729
	$lease = false;
730
	$failover = false;
731
	$dedup_lease = false;
732
	$dedup_failover = false;
733
	foreach ($leases_content as $line) {
734
		/* Skip comments */
735
		if (preg_match('/^\s*(|#.*)$/', $line)) {
736
			continue;
737
		}
738

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

    
758
		if (preg_match($lease_regex, $line, $m)) {
759
			$lease = true;
760
			$item = array();
761
			$item['ip'] = $m[1];
762
			$item['type'] = $dynamic_string;
763
			continue;
764
		}
765

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

    
782
			if (preg_match($binding_regex, $line, $m)) {
783
				switch ($m[1]) {
784
					case "active":
785
						$item['act'] = $active_string;
786
						break;
787
					case "free":
788
						$item['act'] = $expired_string;
789
						$item['online'] =
790
						    $offline_string;
791
						break;
792
					case "backup":
793
						$item['act'] = $reserved_string;
794
						$item['online'] =
795
						    $offline_string;
796
						break;
797
				}
798
				continue;
799
			}
800

    
801
			if (preg_match($mac_regex, $line, $m) &&
802
			    is_macaddr($m[1])) {
803
				$item['mac'] = $m[1];
804

    
805
				if (in_array($item['ip'], $arpdata_ip)) {
806
					$item['online'] = $online_string;
807
				} else {
808
					$item['online'] = $offline_string;
809
				}
810
				continue;
811
			}
812

    
813
			if (preg_match($hostname_regex, $line, $m)) {
814
				$item['hostname'] = $m[1];
815
			}
816
		}
817

    
818
		if (preg_match($failover_regex, $line, $m)) {
819
			$failover = true;
820
			$item = array();
821
			$item['name'] = $m[1] . ' (' .
822
			    convert_friendly_interface_to_friendly_descr(
823
			    substr($m[1],5)) . ')';
824
			continue;
825
		}
826

    
827
		if ($failover && preg_match($state_regex, $line, $m)) {
828
			$item[$m[1] . 'state'] = $m[2];
829
			$item[$m[1] . 'date'] = dhcpd_date_adjust_gmt($m[3] .
830
			    ' ' . $m[4]);
831
			continue;
832
		}
833
	}
834

    
835
	foreach ($config['interfaces'] as $ifname => $ifarr) {
836
		if (!is_array($config['dhcpd'][$ifname]) ||
837
		    !is_array($config['dhcpd'][$ifname]['staticmap'])) {
838
			continue;
839
		}
840

    
841
		foreach ($config['dhcpd'][$ifname]['staticmap'] as $idx =>
842
		    $static) {
843
			if (empty($static['mac']) && empty($static['cid'])) {
844
				continue;
845
			}
846

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

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

    
878
	return $leases;
879
}
880

    
881
function system_hostname_configure() {
882
	global $config, $g;
883
	if (isset($config['system']['developerspew'])) {
884
		$mt = microtime();
885
		echo "system_hostname_configure() being called $mt\n";
886
	}
887

    
888
	$syscfg = $config['system'];
889

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

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

    
897
	return $status;
898
}
899

    
900
function system_routing_configure($interface = "") {
901
	global $config, $g;
902

    
903
	if (isset($config['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 $config, $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
		$gateways_status = return_gateways_status(true);
939

    
940
		foreach ($static_routes as $rtent) {
941
			/* Do not delete disabled routes on boot,
942
			 * see https://redmine.pfsense.org/issues/3709 */
943
			if (isset($rtent['disabled']) && platform_booting()) {
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']) || (!isset($gateway['action_disable']) &&
996
			    ($gateways_status[$gateway['name']]['status'] == 'down'))) {
997
				/*
998
				 * XXX: This can break things by deleting
999
				 * routes that shouldn't be deleted - OpenVPN,
1000
				 * dynamic routing scenarios, etc.
1001
				 * redmine #3709
1002
				 */
1003
				foreach ($ips as $ip) {
1004
					route_del($ip);
1005
				}
1006
				continue;
1007
			}
1008

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

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

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

    
1065
	return 0;
1066
}
1067

    
1068
function system_routing_enable() {
1069
	global $config, $g;
1070
	if (isset($config['system']['developerspew'])) {
1071
		$mt = microtime();
1072
		echo "system_routing_enable() being called $mt\n";
1073
	}
1074

    
1075
	set_sysctl(array(
1076
		"net.inet.ip.forwarding" => "1",
1077
		"net.inet6.ip6.forwarding" => "1"
1078
	));
1079

    
1080
	return;
1081
}
1082

    
1083
function system_webgui_create_certificate() {
1084
	global $config, $g, $cert_strict_values;
1085

    
1086
	init_config_arr(array('ca'));
1087
	$a_ca = &$config['ca'];
1088
	init_config_arr(array('cert'));
1089
	$a_cert = &$config['cert'];
1090
	log_error(gettext("Creating SSL/TLS Certificate for this host"));
1091

    
1092
	$cert = array();
1093
	$cert['refid'] = uniqid();
1094
	$cert['descr'] = sprintf(gettext("webConfigurator default (%s)"), $cert['refid']);
1095
	$cert_hostname = "{$config['system']['hostname']}-{$cert['refid']}";
1096

    
1097
	$dn = array(
1098
		'organizationName' => "{$g['product_label']} webConfigurator Self-Signed Certificate",
1099
		'commonName' => $cert_hostname,
1100
		'subjectAltName' => "DNS:{$cert_hostname}");
1101
	$old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warnings directly to a page screwing menu tab */
1102
	if (!cert_create($cert, null, 2048, $cert_strict_values['max_server_cert_lifetime'], $dn, "self-signed", "sha256")) {
1103
		while ($ssl_err = openssl_error_string()) {
1104
			log_error(sprintf(gettext("Error creating WebGUI Certificate: openssl library returns: %s"), $ssl_err));
1105
		}
1106
		error_reporting($old_err_level);
1107
		return null;
1108
	}
1109
	error_reporting($old_err_level);
1110

    
1111
	$a_cert[] = $cert;
1112
	$config['system']['webgui']['ssl-certref'] = $cert['refid'];
1113
	write_config(sprintf(gettext("Generated new self-signed SSL/TLS certificate for HTTPS (%s)"), $cert['refid']));
1114
	return $cert;
1115
}
1116

    
1117
function system_webgui_start() {
1118
	global $config, $g;
1119

    
1120
	if (platform_booting()) {
1121
		echo gettext("Starting webConfigurator...");
1122
	}
1123

    
1124
	chdir($g['www_path']);
1125

    
1126
	/* defaults */
1127
	$portarg = "80";
1128
	$crt = "";
1129
	$key = "";
1130
	$ca = "";
1131

    
1132
	/* non-standard port? */
1133
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "") {
1134
		$portarg = "{$config['system']['webgui']['port']}";
1135
	}
1136

    
1137
	if ($config['system']['webgui']['protocol'] == "https") {
1138
		// Ensure that we have a webConfigurator CERT
1139
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
1140
		if (!is_array($cert) || !$cert['crt'] || !$cert['prv']) {
1141
			$cert = system_webgui_create_certificate();
1142
		}
1143
		$crt = base64_decode($cert['crt']);
1144
		$key = base64_decode($cert['prv']);
1145

    
1146
		if (!$config['system']['webgui']['port']) {
1147
			$portarg = "443";
1148
		}
1149
		$ca = ca_chain($cert);
1150
		$hsts = isset($config['system']['webgui']['disablehsts']) ? false : true;
1151
	}
1152

    
1153
	/* generate nginx configuration */
1154
	system_generate_nginx_config("{$g['varetc_path']}/nginx-webConfigurator.conf",
1155
		$crt, $key, $ca, "nginx-webConfigurator.pid", $portarg, "/usr/local/www/",
1156
		"cert.crt", "cert.key", false, $hsts);
1157

    
1158
	/* kill any running nginx */
1159
	killbypid("{$g['varrun_path']}/nginx-webConfigurator.pid");
1160

    
1161
	sleep(1);
1162

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

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

    
1168
	if (platform_booting()) {
1169
		if ($res == 0) {
1170
			echo gettext("done.") . "\n";
1171
		} else {
1172
			echo gettext("failed!") . "\n";
1173
		}
1174
	}
1175

    
1176
	return $res;
1177
}
1178

    
1179
/****f* system.inc/get_dns_nameservers
1180
 * NAME
1181
 *   get_dns_nameservers - Get system DNS servers
1182
 * INPUTS
1183
 *   $add_v6_brackets: (boolean, false)
1184
 *                     Add brackets around IPv6 DNS servers, as expected by some
1185
 *                     daemons such as nginx.
1186
 *   $hostns         : (boolean, true)
1187
 *                     true : Return only DNS servers used by the firewall
1188
 *                            itself as upstream forwarding servers
1189
 *                     false: Return all DNS servers from the configuration and
1190
 *                            overrides (if allowed).
1191
 * RESULT
1192
 *   $dns_nameservers - An array of the requested DNS servers
1193
 ******/
1194
function get_dns_nameservers($add_v6_brackets = false, $hostns=true) {
1195
	global $config;
1196

    
1197
	$dns_nameservers = array();
1198

    
1199
	if (isset($config['system']['developerspew'])) {
1200
		$mt = microtime();
1201
		echo "get_dns_nameservers() being called $mt\n";
1202
	}
1203

    
1204
	$syscfg = $config['system'];
1205
	if ((((isset($config['dnsmasq']['enable'])) &&
1206
	    (empty($config['dnsmasq']['port']) || $config['dnsmasq']['port'] == "53") &&
1207
	    (empty($config['dnsmasq']['interface']) ||
1208
	    in_array("lo0", explode(",", $config['dnsmasq']['interface'])))) ||
1209
	    ((isset($config['unbound']['enable'])) &&
1210
	    (empty($config['unbound']['port']) || $config['unbound']['port'] == "53") &&
1211
	    (empty($config['unbound']['active_interface']) ||
1212
	    in_array("lo0", explode(",", $config['unbound']['active_interface'])) ||
1213
	    in_array("all", explode(",", $config['unbound']['active_interface']), true)))) &&
1214
	    ($config['system']['dnslocalhost'] != 'remote')) {
1215
		$dns_nameservers[] = "127.0.0.1";
1216
	}
1217

    
1218
	if ($hostns || ($config['system']['dnslocalhost'] != 'local')) {
1219
		if (isset($syscfg['dnsallowoverride'])) {
1220
			/* get dynamically assigned DNS servers (if any) */
1221
			foreach (array_unique(get_dynamic_nameservers()) as $nameserver) {
1222
				if ($nameserver) {
1223
					if ($add_v6_brackets && is_ipaddrv6($nameserver)) {
1224
						$nameserver = "[{$nameserver}]";
1225
					}
1226
					$dns_nameservers[] = $nameserver;
1227
				}
1228
			}
1229
		}
1230
		if (is_array($syscfg['dnsserver'])) {
1231
			foreach ($syscfg['dnsserver'] as $sys_dnsserver) {
1232
				if ($sys_dnsserver && (!in_array($sys_dnsserver, $dns_nameservers))) {
1233
					if ($add_v6_brackets && is_ipaddrv6($sys_dnsserver)) {
1234
						$sys_dnsserver = "[{$sys_dnsserver}]";
1235
					}
1236
					$dns_nameservers[] = $sys_dnsserver;
1237
				}
1238
			}
1239
		}
1240
	}
1241
	return array_unique($dns_nameservers);
1242
}
1243

    
1244
function system_generate_nginx_config($filename,
1245
	$cert,
1246
	$key,
1247
	$ca,
1248
	$pid_file,
1249
	$port = 80,
1250
	$document_root = "/usr/local/www/",
1251
	$cert_location = "cert.crt",
1252
	$key_location = "cert.key",
1253
	$captive_portal = false,
1254
	$hsts = true) {
1255

    
1256
	global $config, $g;
1257

    
1258
	if (isset($config['system']['developerspew'])) {
1259
		$mt = microtime();
1260
		echo "system_generate_nginx_config() being called $mt\n";
1261
	}
1262

    
1263
	if ($captive_portal !== false) {
1264
		$cp_interfaces = explode(",", $config['captiveportal'][$captive_portal]['interface']);
1265
		$cp_hostcheck = "";
1266
		foreach ($cp_interfaces as $cpint) {
1267
			$cpint_ip = get_interface_ip($cpint);
1268
			if (is_ipaddr($cpint_ip)) {
1269
				$cp_hostcheck .= "\t\tif (\$http_host ~* $cpint_ip) {\n";
1270
				$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1271
				$cp_hostcheck .= "\t\t}\n";
1272
			}
1273
		}
1274
		if (isset($config['captiveportal'][$captive_portal]['httpsname']) &&
1275
		    is_domain($config['captiveportal'][$captive_portal]['httpsname'])) {
1276
			$cp_hostcheck .= "\t\tif (\$http_host ~* {$config['captiveportal'][$captive_portal]['httpsname']}) {\n";
1277
			$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1278
			$cp_hostcheck .= "\t\t}\n";
1279
		}
1280
		$cp_rewrite = "\t\tif (\$cp_redirect = '') {\n";
1281
		$cp_rewrite .= "\t\t\trewrite	^ /index.php?zone=$captive_portal&redirurl=\$request_uri break;\n";
1282
		$cp_rewrite .= "\t\t}\n";
1283

    
1284
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1285
		if (empty($maxprocperip)) {
1286
			$maxprocperip = 10;
1287
		}
1288
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1289
	}
1290

    
1291
	if (empty($port)) {
1292
		$nginx_port = "80";
1293
	} else {
1294
		$nginx_port = $port;
1295
	}
1296

    
1297
	$memory = get_memory();
1298
	$realmem = $memory[1];
1299

    
1300
	// Determine web GUI process settings and take into account low memory systems
1301
	if ($realmem < 255) {
1302
		$max_procs = 1;
1303
	} else {
1304
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
1305
	}
1306

    
1307
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM
1308
	if ($captive_portal !== false) {
1309
		if ($realmem > 135 and $realmem < 256) {
1310
			$max_procs += 1; // 2 worker processes
1311
		} else if ($realmem > 255 and $realmem < 513) {
1312
			$max_procs += 2; // 3 worker processes
1313
		} else if ($realmem > 512) {
1314
			$max_procs += 4; // 6 worker processes
1315
		}
1316
	}
1317

    
1318
	$nginx_config = <<<EOD
1319
#
1320
# nginx configuration file
1321

    
1322
pid {$g['varrun_path']}/{$pid_file};
1323

    
1324
user  root wheel;
1325
worker_processes  {$max_procs};
1326

    
1327
EOD;
1328

    
1329
	/* Disable file logging */
1330
	$nginx_config .= "error_log /dev/null;\n";
1331
	if (!isset($config['syslog']['nolognginx'])) {
1332
		/* Send nginx error log to syslog */
1333
		$nginx_config .= "error_log  syslog:server=unix:/var/run/log,facility=local5;\n";
1334
	}
1335

    
1336
	$nginx_config .= <<<EOD
1337

    
1338
events {
1339
    worker_connections  1024;
1340
}
1341

    
1342
http {
1343
	include       /usr/local/etc/nginx/mime.types;
1344
	default_type  application/octet-stream;
1345
	add_header X-Frame-Options SAMEORIGIN;
1346
	server_tokens off;
1347

    
1348
	sendfile        on;
1349

    
1350
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1351

    
1352
EOD;
1353

    
1354
	if ($captive_portal !== false) {
1355
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1356
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1357
	} else {
1358
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1359
	}
1360

    
1361
	if ($cert <> "" and $key <> "") {
1362
		$nginx_config .= "\n";
1363
		$nginx_config .= "\tserver {\n";
1364
		$nginx_config .= "\t\tlisten {$nginx_port} ssl http2;\n";
1365
		$nginx_config .= "\t\tlisten [::]:{$nginx_port} ssl http2;\n";
1366
		$nginx_config .= "\n";
1367
		$nginx_config .= "\t\tssl_certificate         {$g['varetc_path']}/{$cert_location};\n";
1368
		$nginx_config .= "\t\tssl_certificate_key     {$g['varetc_path']}/{$key_location};\n";
1369
		$nginx_config .= "\t\tssl_session_timeout     10m;\n";
1370
		$nginx_config .= "\t\tkeepalive_timeout       70;\n";
1371
		$nginx_config .= "\t\tssl_session_cache       shared:SSL:10m;\n";
1372
		if ($captive_portal !== false) {
1373
			// leave TLSv1.1 for CP for now for compatibility
1374
			$nginx_config .= "\t\tssl_protocols   TLSv1.1 TLSv1.2 TLSv1.3;\n";
1375
		} else {
1376
			$nginx_config .= "\t\tssl_protocols   TLSv1.2 TLSv1.3;\n";
1377
		}
1378
		$nginx_config .= "\t\tssl_ciphers \"EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305\";\n";
1379
		$nginx_config .= "\t\tssl_prefer_server_ciphers       on;\n";
1380
		if ($captive_portal === false && $hsts !== false) {
1381
			$nginx_config .= "\t\tadd_header Strict-Transport-Security \"max-age=31536000\";\n";
1382
		}
1383
		$nginx_config .= "\t\tadd_header X-Content-Type-Options nosniff;\n";
1384
		$nginx_config .= "\t\tssl_session_tickets off;\n";
1385
		$nginx_config .= "\t\tssl_dhparam /etc/dh-parameters.4096;\n";
1386
		$cert_temp = lookup_cert($config['system']['webgui']['ssl-certref']);
1387
		if (($config['system']['webgui']['ocsp-staple'] == true) or
1388
		    (cert_get_ocspstaple($cert_temp['crt']) == true)) {
1389
			$nginx_config .= "\t\tssl_stapling on;\n";
1390
			$nginx_config .= "\t\tssl_stapling_verify on;\n";
1391
			$nginx_config .= "\t\tresolver " . implode(" ", get_dns_nameservers(true)) . " valid=300s;\n";
1392
			$nginx_config .= "\t\tresolver_timeout 5s;\n";
1393
		}
1394
	} else {
1395
		$nginx_config .= "\n";
1396
		$nginx_config .= "\tserver {\n";
1397
		$nginx_config .= "\t\tlisten {$nginx_port};\n";
1398
		$nginx_config .= "\t\tlisten [::]:{$nginx_port};\n";
1399
	}
1400

    
1401
	$nginx_config .= <<<EOD
1402

    
1403
		client_max_body_size 200m;
1404

    
1405
		gzip on;
1406
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
1407

    
1408

    
1409
EOD;
1410

    
1411
	if ($captive_portal !== false) {
1412
		$nginx_config .= <<<EOD
1413
$captive_portal_maxprocperip
1414
$cp_hostcheck
1415
$cp_rewrite
1416
		log_not_found off;
1417

    
1418
EOD;
1419

    
1420
	}
1421

    
1422
	$nginx_config .= <<<EOD
1423
		root "{$document_root}";
1424
		location / {
1425
			index  index.php index.html index.htm;
1426
		}
1427
		location ~ \.inc$ {
1428
			deny all;
1429
			return 403;
1430
		}
1431
		location ~ \.php$ {
1432
			try_files \$uri =404; #  This line closes a potential security hole
1433
			# ensuring users can't execute uploaded files
1434
			# see: http://forum.nginx.org/read.php?2,88845,page=3
1435
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1436
			fastcgi_index  index.php;
1437
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1438
			# Fix httpoxy - https://httpoxy.org/#fix-now
1439
			fastcgi_param  HTTP_PROXY  "";
1440
			fastcgi_read_timeout 180;
1441
			include        /usr/local/etc/nginx/fastcgi_params;
1442
		}
1443
		location ~ (^/status$) {
1444
			allow 127.0.0.1;
1445
			deny all;
1446
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1447
			fastcgi_index  index.php;
1448
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1449
			# Fix httpoxy - https://httpoxy.org/#fix-now
1450
			fastcgi_param  HTTP_PROXY  "";
1451
			fastcgi_read_timeout 360;
1452
			include        /usr/local/etc/nginx/fastcgi_params;
1453
		}
1454
	}
1455

    
1456
EOD;
1457

    
1458
	$cert = str_replace("\r", "", $cert);
1459
	$key = str_replace("\r", "", $key);
1460

    
1461
	$cert = str_replace("\n\n", "\n", $cert);
1462
	$key = str_replace("\n\n", "\n", $key);
1463

    
1464
	if ($cert <> "" and $key <> "") {
1465
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1466
		if (!$fd) {
1467
			printf(gettext("Error: cannot open certificate file in system_webgui_start().%s"), "\n");
1468
			return 1;
1469
		}
1470
		chmod("{$g['varetc_path']}/{$cert_location}", 0644);
1471
		if ($ca <> "") {
1472
			$cert_chain = $cert . "\n" . $ca;
1473
		} else {
1474
			$cert_chain = $cert;
1475
		}
1476
		fwrite($fd, $cert_chain);
1477
		fclose($fd);
1478
		$fd = fopen("{$g['varetc_path']}/{$key_location}", "w");
1479
		if (!$fd) {
1480
			printf(gettext("Error: cannot open certificate key file in system_webgui_start().%s"), "\n");
1481
			return 1;
1482
		}
1483
		chmod("{$g['varetc_path']}/{$key_location}", 0600);
1484
		fwrite($fd, $key);
1485
		fclose($fd);
1486
	}
1487

    
1488
	// Add HTTP to HTTPS redirect
1489
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1490
		if ($nginx_port != "443") {
1491
			$redirectport = ":{$nginx_port}";
1492
		}
1493
		$nginx_config .= <<<EOD
1494
	server {
1495
		listen 80;
1496
		listen [::]:80;
1497
		return 301 https://\$http_host$redirectport\$request_uri;
1498
	}
1499

    
1500
EOD;
1501
	}
1502

    
1503
	$nginx_config .= "}\n";
1504

    
1505
	$fd = fopen("{$filename}", "w");
1506
	if (!$fd) {
1507
		printf(gettext('Error: cannot open %1$s in system_generate_nginx_config().%2$s'), $filename, "\n");
1508
		return 1;
1509
	}
1510
	fwrite($fd, $nginx_config);
1511
	fclose($fd);
1512

    
1513
	/* nginx will fail to start if this directory does not exist. */
1514
	safe_mkdir("/var/tmp/nginx/");
1515

    
1516
	return 0;
1517

    
1518
}
1519

    
1520
function system_get_timezone_list() {
1521
	global $g;
1522

    
1523
	$file_list = array_merge(
1524
		glob("/usr/share/zoneinfo/[A-Z]*"),
1525
		glob("/usr/share/zoneinfo/*/*"),
1526
		glob("/usr/share/zoneinfo/*/*/*")
1527
	);
1528

    
1529
	if (empty($file_list)) {
1530
		$file_list[] = $g['default_timezone'];
1531
	} else {
1532
		/* Remove directories from list */
1533
		$file_list = array_filter($file_list, function($v) {
1534
			return !is_dir($v);
1535
		});
1536
	}
1537

    
1538
	/* Remove directory prefix */
1539
	$file_list = str_replace('/usr/share/zoneinfo/', '', $file_list);
1540

    
1541
	sort($file_list);
1542

    
1543
	return $file_list;
1544
}
1545

    
1546
function system_timezone_configure() {
1547
	global $config, $g;
1548
	if (isset($config['system']['developerspew'])) {
1549
		$mt = microtime();
1550
		echo "system_timezone_configure() being called $mt\n";
1551
	}
1552

    
1553
	$syscfg = $config['system'];
1554

    
1555
	if (platform_booting()) {
1556
		echo gettext("Setting timezone...");
1557
	}
1558

    
1559
	/* extract appropriate timezone file */
1560
	$timezone = (isset($syscfg['timezone']) ? $syscfg['timezone'] : $g['default_timezone']);
1561
	/* DO NOT remove \n otherwise tzsetup will fail */
1562
	@file_put_contents("/var/db/zoneinfo", $timezone . "\n");
1563
	mwexec("/usr/sbin/tzsetup -r");
1564

    
1565
	if (platform_booting()) {
1566
		echo gettext("done.") . "\n";
1567
	}
1568
}
1569

    
1570
function check_gps_speed($device) {
1571
	usleep(1000);
1572
	// Set timeout to 5s
1573
	$timeout=microtime(true)+5;
1574
	if ($fp = fopen($device, 'r')) {
1575
		stream_set_blocking($fp, 0);
1576
		stream_set_timeout($fp, 5);
1577
		$contents = "";
1578
		$cnt = 0;
1579
		$buffersize = 256;
1580
		do {
1581
			$c = fread($fp, $buffersize - $cnt);
1582

    
1583
			// Wait for data to arive
1584
			if (($c === false) || (strlen($c) == 0)) {
1585
				usleep(500);
1586
				continue;
1587
			}
1588

    
1589
			$contents.=$c;
1590
			$cnt = $cnt + strlen($c);
1591
		} while (($cnt < $buffersize) && (microtime(true) < $timeout));
1592
		fclose($fp);
1593

    
1594
		$nmeasentences = ['RMC', 'GGA', 'GLL', 'ZDA', 'ZDG', 'PGRMF'];
1595
		foreach ($nmeasentences as $sentence) {
1596
			if (strpos($contents, $sentence) > 0) {
1597
				return true;
1598
			}
1599
		}
1600
		if (strpos($contents, '0') > 0) {
1601
			$filters = ['`', '?', '/', '~'];
1602
			foreach ($filters as $filter) {
1603
				if (strpos($contents, $filter) !== false) {
1604
					return false;
1605
				}
1606
			}
1607
			return true;
1608
		}
1609
	}
1610
	return false;
1611
}
1612

    
1613
/* Generate list of possible NTP poll values
1614
 * https://redmine.pfsense.org/issues/9439 */
1615
global $ntp_poll_min_value, $ntp_poll_max_value;
1616
global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
1617
global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
1618
global $ntp_poll_min_default, $ntp_poll_max_default;
1619
global $ntp_auth_halgos;
1620
$ntp_poll_min_value = 4;
1621
$ntp_poll_max_value = 17;
1622
$ntp_poll_min_default_gps = 4;
1623
$ntp_poll_max_default_gps = 4;
1624
$ntp_poll_min_default_pps = 4;
1625
$ntp_poll_max_default_pps = 4;
1626
$ntp_poll_min_default = 'omit';
1627
$ntp_poll_max_default = 9;
1628
$ntp_auth_halgos = array(
1629
	'md5' => 'MD5',
1630
	'sha1' => 'SHA1'
1631
);
1632

    
1633
function system_ntp_poll_values() {
1634
	global $ntp_poll_min_value, $ntp_poll_max_value;
1635
	$poll_values = array("" => gettext('Default'));
1636

    
1637
	for ($i = $ntp_poll_min_value; $i <= $ntp_poll_max_value; $i++) {
1638
		$sec = 2 ** $i;
1639
		$poll_values[$i] = $i . ': ' . number_format($sec) . ' ' . gettext('seconds') .
1640
					' (' . convert_seconds_to_dhms($sec) . ')';
1641
	}
1642

    
1643
	$poll_values['omit'] = gettext('Omit (Do not set)');
1644
	return $poll_values;
1645
}
1646

    
1647
function system_ntp_fixup_poll_value($type, $configvalue, $default) {
1648
	$pollstring = "";
1649

    
1650
	if (empty($configvalue)) {
1651
		$configvalue = $default;
1652
	}
1653

    
1654
	if ($configvalue != 'omit') {
1655
		$pollstring = " {$type} {$configvalue}";
1656
	}
1657

    
1658
	return $pollstring;
1659
}
1660

    
1661
function system_ntp_setup_gps($serialport) {
1662
	global $config, $g;
1663

    
1664
	if (is_array($config['ntpd']) && ($config['ntpd']['enable'] == 'disabled')) {
1665
		return false;
1666
	}
1667

    
1668
	init_config_arr(array('ntpd', 'gps'));
1669

    
1670
	$gps_device = '/dev/gps0';
1671
	$serialport = '/dev/'.$serialport;
1672

    
1673
	if (!file_exists($serialport)) {
1674
		return false;
1675
	}
1676

    
1677
	// Create symlink that ntpd requires
1678
	unlink_if_exists($gps_device);
1679
	@symlink($serialport, $gps_device);
1680

    
1681
	$gpsbaud = '4800';
1682
	$speeds = array(
1683
		0 => '4800', 
1684
		16 => '9600', 
1685
		32 => '19200', 
1686
		48 => '38400', 
1687
		64 => '57600', 
1688
		80 => '115200'
1689
	);
1690
	if (!empty($config['ntpd']['gps']['speed']) && array_key_exists($config['ntpd']['gps']['speed'], $speeds)) {
1691
		$gpsbaud = $speeds[$config['ntpd']['gps']['speed']];
1692
	}
1693

    
1694
	system_ntp_setup_rawspeed($serialport, $gpsbaud);
1695

    
1696
	$autospeed = ($config['ntpd']['gps']['speed'] == 'autoalways' || $config['ntpd']['gps']['speed'] == 'autoset');
1697
	if ($autospeed || ($config['ntpd']['gps']['autobaudinit'] && !check_gps_speed($gps_device))) {
1698
		$found = false;
1699
		foreach ($speeds as $baud) {
1700
			system_ntp_setup_rawspeed($serialport, $baud);
1701
			if ($found = check_gps_speed($gps_device)) {
1702
				if ($autospeed) {
1703
					$saveconfig = ($config['ntpd']['gps']['speed'] == 'autoset');
1704
					$config['ntpd']['gps']['speed'] = array_search($baud, $speeds);
1705
					$gpsbaud = $baud;
1706
					if ($saveconfig) {
1707
						write_config(sprintf(gettext('Autoset GPS baud rate to %s'), $baud));
1708
					}
1709
				}
1710
				break;
1711
			}
1712
		}
1713
		if ($found === false) {
1714
			log_error(gettext("Could not find correct GPS baud rate."));
1715
			return false;
1716
		}
1717
	}
1718

    
1719
	/* Send the following to the GPS port to initialize the GPS */
1720
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
1721
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
1722
	} else {
1723
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1724
	}
1725

    
1726
	/* XXX: Why not file_put_contents to the device */
1727
	@file_put_contents('/tmp/gps.init', $gps_init);
1728
	mwexec("cat /tmp/gps.init > {$serialport}");
1729

    
1730
	if ($found && $config['ntpd']['gps']['autobaudinit']) {
1731
		system_ntp_setup_rawspeed($serialport, $gpsbaud);
1732
	}
1733

    
1734
	/* Remove old /etc/remote entry if it exists */
1735
	if (mwexec("/usr/bin/grep -c '^gps0' /etc/remote") == 0) {
1736
		mwexec("/usr/bin/sed -i '' -n '/gps0/!p' /etc/remote");
1737
	}
1738

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

    
1744
	return true;
1745
}
1746

    
1747
// Configure the serial port for raw IO and set the speed
1748
function system_ntp_setup_rawspeed($serialport, $baud) {
1749
	mwexec("/bin/stty -f " .  escapeshellarg($serialport) . " raw speed " . escapeshellarg($baud));
1750
	mwexec("/bin/stty -f " .  escapeshellarg($serialport) . ".init raw speed " . escapeshellarg($baud));
1751
}
1752

    
1753
function system_ntp_setup_pps($serialport) {
1754
	global $config, $g;
1755

    
1756
	$pps_device = '/dev/pps0';
1757
	$serialport = '/dev/'.$serialport;
1758

    
1759
	if (!file_exists($serialport)) {
1760
		return false;
1761
	}
1762
	// If ntpd is disabled, just return
1763
	if (is_array($config['ntpd']) && ($config['ntpd']['enable'] == 'disabled')) {
1764
		return false;
1765
	}
1766

    
1767
	// Create symlink that ntpd requires
1768
	unlink_if_exists($pps_device);
1769
	@symlink($serialport, $pps_device);
1770

    
1771

    
1772
	return true;
1773
}
1774

    
1775
function system_ntp_configure() {
1776
	global $config, $g;
1777
	global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
1778
	global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
1779
	global $ntp_poll_min_default, $ntp_poll_max_default;
1780

    
1781
	$driftfile = "/var/db/ntpd.drift";
1782
	$statsdir = "/var/log/ntp";
1783
	$gps_device = '/dev/gps0';
1784

    
1785
	safe_mkdir($statsdir);
1786

    
1787
	if (!is_array($config['ntpd'])) {
1788
		$config['ntpd'] = array();
1789
	}
1790
	// ntpd is disabled, just stop it and return
1791
	if ($config['ntpd']['enable'] == 'disabled') {
1792
		while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1793
			killbypid("{$g['varrun_path']}/ntpd.pid");
1794
		}
1795
		@unlink("{$g['varrun_path']}/ntpd.pid");
1796
		@unlink("{$g['varetc_path']}/ntpd.conf");
1797
		@unlink("{$g['varetc_path']}/ntp.keys");
1798
		log_error("NTPD is disabled.");
1799
		return;
1800
	}
1801

    
1802
	if (platform_booting()) {
1803
		echo gettext("Starting NTP Server...");
1804
	}
1805

    
1806
	/* if ntpd is running, kill it */
1807
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1808
		killbypid("{$g['varrun_path']}/ntpd.pid");
1809
	}
1810
	@unlink("{$g['varrun_path']}/ntpd.pid");
1811

    
1812
	/* set NTP server authentication key */
1813
	if ($config['ntpd']['serverauth'] == 'yes') {
1814
		$ntpkeyscfg = "1 " . strtoupper($config['ntpd']['serverauthalgo']) . " " . base64_decode($config['ntpd']['serverauthkey']) . "\n";
1815
		if (!@file_put_contents("{$g['varetc_path']}/ntp.keys", $ntpkeyscfg)) {
1816
			log_error(sprintf(gettext("Could not open %s/ntp.keys for writing"), $g['varetc_path']));
1817
			return;
1818
		}
1819
	} else {
1820
		unlink_if_exists("{$g['varetc_path']}/ntp.keys");
1821
	}
1822

    
1823
	$ntpcfg = "# \n";
1824
	$ntpcfg .= "# pfSense ntp configuration file \n";
1825
	$ntpcfg .= "# \n\n";
1826
	$ntpcfg .= "tinker panic 0 \n\n";
1827

    
1828
	if ($config['ntpd']['serverauth'] == 'yes') {
1829
		$ntpcfg .= "# Authentication settings \n";
1830
		$ntpcfg .= "keys /var/etc/ntp.keys \n";
1831
		$ntpcfg .= "trustedkey 1 \n";
1832
		$ntpcfg .= "requestkey 1 \n";
1833
		$ntpcfg .= "controlkey 1 \n";
1834
		$ntpcfg .= "\n";
1835
	}
1836

    
1837
	/* Add Orphan mode */
1838
	$ntpcfg .= "# Orphan mode stratum and Maximum candidate NTP peers\n";
1839
	$ntpcfg .= 'tos orphan ';
1840
	if (!empty($config['ntpd']['orphan'])) {
1841
		$ntpcfg .= $config['ntpd']['orphan'];
1842
	} else {
1843
		$ntpcfg .= '12';
1844
	}
1845
	/* Add Maximum candidate NTP peers */
1846
	$ntpcfg .= ' maxclock ';
1847
	if (!empty($config['ntpd']['ntpmaxpeers'])) {
1848
		$ntpcfg .= $config['ntpd']['ntpmaxpeers'];
1849
	} else {
1850
		$ntpcfg .= '5';
1851
	}
1852
	$ntpcfg .= "\n";
1853

    
1854
	/* Add PPS configuration */
1855
	if (is_array($config['ntpd']['pps']) && !empty($config['ntpd']['pps']['port']) &&
1856
	    file_exists('/dev/'.$config['ntpd']['pps']['port']) &&
1857
	    system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
1858
		$ntpcfg .= "\n";
1859
		$ntpcfg .= "# PPS Setup\n";
1860
		$ntpcfg .= 'server 127.127.22.0';
1861
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', $config['ntpd']['pps']['ppsminpoll'], $ntp_poll_min_default_pps);
1862
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', $config['ntpd']['pps']['ppsmaxpoll'], $ntp_poll_max_default_pps);
1863
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
1864
			$ntpcfg .= ' prefer';
1865
		}
1866
		if (!empty($config['ntpd']['pps']['noselect'])) {
1867
			$ntpcfg .= ' noselect ';
1868
		}
1869
		$ntpcfg .= "\n";
1870
		$ntpcfg .= 'fudge 127.127.22.0';
1871
		if (!empty($config['ntpd']['pps']['fudge1'])) {
1872
			$ntpcfg .= ' time1 ';
1873
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
1874
		}
1875
		if (!empty($config['ntpd']['pps']['flag2'])) {
1876
			$ntpcfg .= ' flag2 1';
1877
		}
1878
		if (!empty($config['ntpd']['pps']['flag3'])) {
1879
			$ntpcfg .= ' flag3 1';
1880
		} else {
1881
			$ntpcfg .= ' flag3 0';
1882
		}
1883
		if (!empty($config['ntpd']['pps']['flag4'])) {
1884
			$ntpcfg .= ' flag4 1';
1885
		}
1886
		if (!empty($config['ntpd']['pps']['refid'])) {
1887
			$ntpcfg .= ' refid ';
1888
			$ntpcfg .= $config['ntpd']['pps']['refid'];
1889
		}
1890
		$ntpcfg .= "\n";
1891
	}
1892
	/* End PPS configuration */
1893

    
1894
	/* Add GPS configuration */
1895
	if (is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['port']) &&
1896
	    system_ntp_setup_gps($config['ntpd']['gps']['port'])) {
1897
		$ntpcfg .= "\n";
1898
		$ntpcfg .= "# GPS Setup\n";
1899
		$ntpcfg .= 'server 127.127.20.0 mode ';
1900
		if (!empty($config['ntpd']['gps']['nmea']) || !empty($config['ntpd']['gps']['speed']) || !empty($config['ntpd']['gps']['subsec']) || !empty($config['ntpd']['gps']['processpgrmf'])) {
1901
			if (!empty($config['ntpd']['gps']['nmea'])) {
1902
				$ntpmode = (int) $config['ntpd']['gps']['nmea'];
1903
			}
1904
			if (!empty($config['ntpd']['gps']['speed'])) {
1905
				$ntpmode += (int) $config['ntpd']['gps']['speed'];
1906
			}
1907
			if (!empty($config['ntpd']['gps']['subsec'])) {
1908
				$ntpmode += 128;
1909
			}
1910
			if (!empty($config['ntpd']['gps']['processpgrmf'])) {
1911
				$ntpmode += 256;
1912
			}
1913
			$ntpcfg .= (string) $ntpmode;
1914
		} else {
1915
			$ntpcfg .= '0';
1916
		}
1917
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', $config['ntpd']['gps']['gpsminpoll'], $ntp_poll_min_default_gps);
1918
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', $config['ntpd']['gps']['gpsmaxpoll'], $ntp_poll_max_default_gps);
1919

    
1920
		if (empty($config['ntpd']['gps']['prefer'])) { /*note: this one works backwards */
1921
			$ntpcfg .= ' prefer';
1922
		}
1923
		if (!empty($config['ntpd']['gps']['noselect'])) {
1924
			$ntpcfg .= ' noselect ';
1925
		}
1926
		$ntpcfg .= "\n";
1927
		$ntpcfg .= 'fudge 127.127.20.0';
1928
		if (!empty($config['ntpd']['gps']['fudge1'])) {
1929
			$ntpcfg .= ' time1 ';
1930
			$ntpcfg .= $config['ntpd']['gps']['fudge1'];
1931
		}
1932
		if (!empty($config['ntpd']['gps']['fudge2'])) {
1933
			$ntpcfg .= ' time2 ';
1934
			$ntpcfg .= $config['ntpd']['gps']['fudge2'];
1935
		}
1936
		if (!empty($config['ntpd']['gps']['flag1'])) {
1937
			$ntpcfg .= ' flag1 1';
1938
		} else {
1939
			$ntpcfg .= ' flag1 0';
1940
		}
1941
		if (!empty($config['ntpd']['gps']['flag2'])) {
1942
			$ntpcfg .= ' flag2 1';
1943
		}
1944
		if (!empty($config['ntpd']['gps']['flag3'])) {
1945
			$ntpcfg .= ' flag3 1';
1946
		} else {
1947
			$ntpcfg .= ' flag3 0';
1948
		}
1949
		if (!empty($config['ntpd']['gps']['flag4'])) {
1950
			$ntpcfg .= ' flag4 1';
1951
		}
1952
		if (!empty($config['ntpd']['gps']['refid'])) {
1953
			$ntpcfg .= ' refid ';
1954
			$ntpcfg .= $config['ntpd']['gps']['refid'];
1955
		}
1956
		if (!empty($config['ntpd']['gps']['stratum'])) {
1957
			$ntpcfg .= ' stratum ';
1958
			$ntpcfg .= $config['ntpd']['gps']['stratum'];
1959
		}
1960
		$ntpcfg .= "\n";
1961
	} elseif (is_array($config['ntpd']) && !empty($config['ntpd']['gpsport']) &&
1962
	    system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1963
		/* This handles a 2.1 and earlier config */
1964
		$ntpcfg .= "# GPS Setup\n";
1965
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1966
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1967
		// Fall back to local clock if GPS is out of sync?
1968
		$ntpcfg .= "server 127.127.1.0\n";
1969
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1970
	}
1971
	/* End GPS configuration */
1972
	$auto_pool_suffix = "pool.ntp.org";
1973
	$have_pools = false;
1974
	$ntpcfg .= "\n\n# Upstream Servers\n";
1975
	/* foreach through ntp servers and write out to ntpd.conf */
1976
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1977
		if ((substr_compare($ts, $auto_pool_suffix, strlen($ts) - strlen($auto_pool_suffix), strlen($auto_pool_suffix)) === 0)
1978
		    || substr_count($config['ntpd']['ispool'], $ts)) {
1979
			$ntpcfg .= 'pool ';
1980
			$have_pools = true;
1981
		} else {
1982
			$ntpcfg .= 'server ';
1983
			if ($config['ntpd']['dnsresolv'] == 'inet') {
1984
				$ntpcfg .= '-4 ';
1985
			} elseif ($config['ntpd']['dnsresolv'] == 'inet6') {
1986
				$ntpcfg .= '-6 ';
1987
			}
1988
		}
1989

    
1990
		$ntpcfg .= "{$ts} iburst";
1991

    
1992
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', $config['ntpd']['ntpminpoll'], $ntp_poll_min_default);
1993
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', $config['ntpd']['ntpmaxpoll'], $ntp_poll_max_default);
1994

    
1995
		if (substr_count($config['ntpd']['prefer'], $ts)) {
1996
			$ntpcfg .= ' prefer';
1997
		}
1998
		if (substr_count($config['ntpd']['noselect'], $ts)) {
1999
			$ntpcfg .= ' noselect';
2000
		}
2001
		$ntpcfg .= "\n";
2002
	}
2003
	unset($ts);
2004

    
2005
	$ntpcfg .= "\n\n";
2006
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
2007
		$ntpcfg .= "enable stats\n";
2008
		$ntpcfg .= 'statistics';
2009
		if (!empty($config['ntpd']['clockstats'])) {
2010
			$ntpcfg .= ' clockstats';
2011
		}
2012
		if (!empty($config['ntpd']['loopstats'])) {
2013
			$ntpcfg .= ' loopstats';
2014
		}
2015
		if (!empty($config['ntpd']['peerstats'])) {
2016
			$ntpcfg .= ' peerstats';
2017
		}
2018
		$ntpcfg .= "\n";
2019
	}
2020
	$ntpcfg .= "statsdir {$statsdir}\n";
2021
	$ntpcfg .= 'logconfig =syncall +clockall';
2022
	if (!empty($config['ntpd']['logpeer'])) {
2023
		$ntpcfg .= ' +peerall';
2024
	}
2025
	if (!empty($config['ntpd']['logsys'])) {
2026
		$ntpcfg .= ' +sysall';
2027
	}
2028
	$ntpcfg .= "\n";
2029
	$ntpcfg .= "driftfile {$driftfile}\n";
2030

    
2031
	/* Default Access restrictions */
2032
	$ntpcfg .= 'restrict default';
2033
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
2034
		$ntpcfg .= ' kod limited';
2035
	}
2036
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
2037
		$ntpcfg .= ' nomodify';
2038
	}
2039
	if (!empty($config['ntpd']['noquery'])) {
2040
		$ntpcfg .= ' noquery';
2041
	}
2042
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
2043
		$ntpcfg .= ' nopeer';
2044
	}
2045
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
2046
		$ntpcfg .= ' notrap';
2047
	}
2048
	if (!empty($config['ntpd']['noserve'])) {
2049
		$ntpcfg .= ' noserve';
2050
	}
2051
	$ntpcfg .= "\nrestrict -6 default";
2052
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
2053
		$ntpcfg .= ' kod limited';
2054
	}
2055
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
2056
		$ntpcfg .= ' nomodify';
2057
	}
2058
	if (!empty($config['ntpd']['noquery'])) {
2059
		$ntpcfg .= ' noquery';
2060
	}
2061
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
2062
		$ntpcfg .= ' nopeer';
2063
	}
2064
	if (!empty($config['ntpd']['noserve'])) {
2065
		$ntpcfg .= ' noserve';
2066
	}
2067
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
2068
		$ntpcfg .= ' notrap';
2069
	}
2070

    
2071
	/* Pools require "restrict source" and cannot contain "nopeer" and "noserve". */
2072
	if ($have_pools) {
2073
		$ntpcfg .= "\nrestrict source";
2074
		if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
2075
			$ntpcfg .= ' kod limited';
2076
		}
2077
		if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
2078
			$ntpcfg .= ' nomodify';
2079
		}
2080
		if (!empty($config['ntpd']['noquery'])) {
2081
			$ntpcfg .= ' noquery';
2082
		}
2083
		if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
2084
			$ntpcfg .= ' notrap';
2085
		}
2086
	}
2087

    
2088
	/* Custom Access Restrictions */
2089
	if (is_array($config['ntpd']['restrictions']) && is_array($config['ntpd']['restrictions']['row'])) {
2090
		$networkacl = $config['ntpd']['restrictions']['row'];
2091
		foreach ($networkacl as $acl) {
2092
			$restrict = "";
2093
			if (is_ipaddrv6($acl['acl_network'])) {
2094
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask_v6($acl['mask']) . " ";
2095
			} elseif (is_ipaddrv4($acl['acl_network'])) {
2096
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask($acl['mask']) . " ";
2097
			} else {
2098
				continue;
2099
			}
2100
			if (!empty($acl['kod'])) {
2101
				$restrict .= ' kod limited';
2102
			}
2103
			if (!empty($acl['nomodify'])) {
2104
				$restrict .= ' nomodify';
2105
			}
2106
			if (!empty($acl['noquery'])) {
2107
				$restrict .= ' noquery';
2108
			}
2109
			if (!empty($acl['nopeer'])) {
2110
				$restrict .= ' nopeer';
2111
			}
2112
			if (!empty($acl['noserve'])) {
2113
				$restrict .= ' noserve';
2114
			}
2115
			if (!empty($acl['notrap'])) {
2116
				$restrict .= ' notrap';
2117
			}
2118
			if (!empty($restrict)) {
2119
				$ntpcfg .= "\nrestrict {$restrict} ";
2120
			}
2121
		}
2122
	}
2123
	/* End Custom Access Restrictions */
2124

    
2125
	/* A leapseconds file is really only useful if this clock is stratum 1 */
2126
	$ntpcfg .= "\n";
2127
	if (!empty($config['ntpd']['leapsec'])) {
2128
		$leapsec .= base64_decode($config['ntpd']['leapsec']);
2129
		file_put_contents('/var/db/leap-seconds', $leapsec);
2130
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
2131
	}
2132

    
2133

    
2134
	if (empty($config['ntpd']['interface'])) {
2135
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface'])) {
2136
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
2137
		} else {
2138
			$interfaces = array();
2139
		}
2140
	} else {
2141
		$interfaces = explode(",", $config['ntpd']['interface']);
2142
	}
2143

    
2144
	if (is_array($interfaces) && count($interfaces)) {
2145
		$finterfaces = array();
2146
		$ntpcfg .= "interface ignore all\n";
2147
		$ntpcfg .= "interface ignore wildcard\n";
2148
		foreach ($interfaces as $interface) {
2149
			$interface = get_real_interface($interface);
2150
			if (!empty($interface)) {
2151
				$finterfaces[] = $interface;
2152
			}
2153
		}
2154
		foreach ($finterfaces as $interface) {
2155
			$ntpcfg .= "interface listen {$interface}\n";
2156
		}
2157
	}
2158

    
2159
	/* open configuration for writing or bail */
2160
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
2161
		log_error(sprintf(gettext("Could not open %s/ntpd.conf for writing"), $g['varetc_path']));
2162
		return;
2163
	}
2164

    
2165
	/* if /var/empty does not exist, create it */
2166
	if (!is_dir("/var/empty")) {
2167
		mkdir("/var/empty", 0555, true);
2168
	}
2169

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

    
2173
	// Note that we are starting up
2174
	log_error("NTPD is starting up.");
2175

    
2176
	if (platform_booting()) {
2177
		echo gettext("done.") . "\n";
2178
	}
2179

    
2180
	return;
2181
}
2182

    
2183
function system_halt() {
2184
	global $g;
2185

    
2186
	system_reboot_cleanup();
2187

    
2188
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
2189
}
2190

    
2191
function system_reboot() {
2192
	global $g;
2193

    
2194
	system_reboot_cleanup();
2195

    
2196
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
2197
}
2198

    
2199
function system_reboot_sync($reroot=false) {
2200
	global $g;
2201

    
2202
	if ($reroot) {
2203
		$args = " -r ";
2204
	}
2205

    
2206
	system_reboot_cleanup();
2207

    
2208
	mwexec("/etc/rc.reboot {$args} > /dev/null 2>&1");
2209
}
2210

    
2211
function system_reboot_cleanup() {
2212
	global $config, $g, $cpzone;
2213

    
2214
	mwexec("/usr/local/bin/beep.sh stop");
2215
	require_once("captiveportal.inc");
2216
	if (is_array($config['captiveportal'])) {
2217
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
2218
			if (!isset($cp['preservedb'])) {
2219
				/* send Accounting-Stop packet for all clients, termination cause 'Admin-Reboot' */
2220
				captiveportal_radius_stop_all(7); // Admin-Reboot
2221
				unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
2222
				captiveportal_free_dnrules();
2223
			}
2224
			/* Send Accounting-Off packet to the RADIUS server */
2225
			captiveportal_send_server_accounting('off');
2226
		}
2227
		/* Remove the pipe database */
2228
		unlink_if_exists("{$g['vardb_path']}/captiveportaldn.rules");
2229
	}
2230
	require_once("voucher.inc");
2231
	voucher_save_db_to_config();
2232
	require_once("pkg-utils.inc");
2233
	stop_packages();
2234
}
2235

    
2236
function system_do_shell_commands($early = 0) {
2237
	global $config, $g;
2238
	if (isset($config['system']['developerspew'])) {
2239
		$mt = microtime();
2240
		echo "system_do_shell_commands() being called $mt\n";
2241
	}
2242

    
2243
	if ($early) {
2244
		$cmdn = "earlyshellcmd";
2245
	} else {
2246
		$cmdn = "shellcmd";
2247
	}
2248

    
2249
	if (is_array($config['system'][$cmdn])) {
2250

    
2251
		/* *cmd is an array, loop through */
2252
		foreach ($config['system'][$cmdn] as $cmd) {
2253
			exec($cmd);
2254
		}
2255

    
2256
	} elseif ($config['system'][$cmdn] <> "") {
2257

    
2258
		/* execute single item */
2259
		exec($config['system'][$cmdn]);
2260

    
2261
	}
2262
}
2263

    
2264
function system_dmesg_save() {
2265
	global $g;
2266
	if (isset($config['system']['developerspew'])) {
2267
		$mt = microtime();
2268
		echo "system_dmesg_save() being called $mt\n";
2269
	}
2270

    
2271
	$dmesg = "";
2272
	$_gb = exec("/sbin/dmesg", $dmesg);
2273

    
2274
	/* find last copyright line (output from previous boots may be present) */
2275
	$lastcpline = 0;
2276

    
2277
	for ($i = 0; $i < count($dmesg); $i++) {
2278
		if (strstr($dmesg[$i], "Copyright (c) 1992-")) {
2279
			$lastcpline = $i;
2280
		}
2281
	}
2282

    
2283
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
2284
	if (!$fd) {
2285
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
2286
		return 1;
2287
	}
2288

    
2289
	for ($i = $lastcpline; $i < count($dmesg); $i++) {
2290
		fwrite($fd, $dmesg[$i] . "\n");
2291
	}
2292

    
2293
	fclose($fd);
2294
	unset($dmesg);
2295

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

    
2299
	return 0;
2300
}
2301

    
2302
function system_set_harddisk_standby() {
2303
	global $g, $config;
2304

    
2305
	if (isset($config['system']['developerspew'])) {
2306
		$mt = microtime();
2307
		echo "system_set_harddisk_standby() being called $mt\n";
2308
	}
2309

    
2310
	if (isset($config['system']['harddiskstandby'])) {
2311
		if (platform_booting()) {
2312
			echo gettext('Setting hard disk standby... ');
2313
		}
2314

    
2315
		$standby = $config['system']['harddiskstandby'];
2316
		// Check for a numeric value
2317
		if (is_numeric($standby)) {
2318
			// Get only suitable candidates for standby; using get_smart_drive_list()
2319
			// from utils.inc to get the list of drives.
2320
			$harddisks = get_smart_drive_list();
2321

    
2322
			// Since get_smart_drive_list() only matches ad|da|ada; lets put the check below
2323
			// just in case of some weird pfSense platform installs.
2324
			if (count($harddisks) > 0) {
2325
				// Iterate disks and run the camcontrol command for each
2326
				foreach ($harddisks as $harddisk) {
2327
					mwexec("/sbin/camcontrol standby {$harddisk} -t {$standby}");
2328
				}
2329
				if (platform_booting()) {
2330
					echo gettext("done.") . "\n";
2331
				}
2332
			} else if (platform_booting()) {
2333
				echo gettext("failed!") . "\n";
2334
			}
2335
		} else if (platform_booting()) {
2336
			echo gettext("failed!") . "\n";
2337
		}
2338
	}
2339
}
2340

    
2341
function system_setup_sysctl() {
2342
	global $config;
2343
	if (isset($config['system']['developerspew'])) {
2344
		$mt = microtime();
2345
		echo "system_setup_sysctl() being called $mt\n";
2346
	}
2347

    
2348
	activate_sysctls();
2349

    
2350
	if (isset($config['system']['sharednet'])) {
2351
		system_disable_arp_wrong_if();
2352
	}
2353
}
2354

    
2355
function system_disable_arp_wrong_if() {
2356
	global $config;
2357
	if (isset($config['system']['developerspew'])) {
2358
		$mt = microtime();
2359
		echo "system_disable_arp_wrong_if() being called $mt\n";
2360
	}
2361
	set_sysctl(array(
2362
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
2363
		"net.link.ether.inet.log_arp_movements" => "0"
2364
	));
2365
}
2366

    
2367
function system_enable_arp_wrong_if() {
2368
	global $config;
2369
	if (isset($config['system']['developerspew'])) {
2370
		$mt = microtime();
2371
		echo "system_enable_arp_wrong_if() being called $mt\n";
2372
	}
2373
	set_sysctl(array(
2374
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
2375
		"net.link.ether.inet.log_arp_movements" => "1"
2376
	));
2377
}
2378

    
2379
function enable_watchdog() {
2380
	global $config;
2381
	return;
2382
	$install_watchdog = false;
2383
	$supported_watchdogs = array("Geode");
2384
	$file = file_get_contents("/var/log/dmesg.boot");
2385
	foreach ($supported_watchdogs as $sd) {
2386
		if (stristr($file, "Geode")) {
2387
			$install_watchdog = true;
2388
		}
2389
	}
2390
	if ($install_watchdog == true) {
2391
		if (is_process_running("watchdogd")) {
2392
			mwexec("/usr/bin/killall watchdogd", true);
2393
		}
2394
		exec("/usr/sbin/watchdogd");
2395
	}
2396
}
2397

    
2398
function system_check_reset_button() {
2399
	global $g;
2400

    
2401
	$specplatform = system_identify_specific_platform();
2402

    
2403
	switch ($specplatform['name']) {
2404
		case 'SG-2220':
2405
			$binprefix = "RCC-DFF";
2406
			break;
2407
		case 'alix':
2408
		case 'wrap':
2409
		case 'FW7541':
2410
		case 'APU':
2411
		case 'RCC-VE':
2412
		case 'RCC':
2413
			$binprefix = $specplatform['name'];
2414
			break;
2415
		default:
2416
			return 0;
2417
	}
2418

    
2419
	$retval = mwexec("/usr/local/sbin/" . $binprefix . "resetbtn");
2420

    
2421
	if ($retval == 99) {
2422
		/* user has pressed reset button for 2 seconds -
2423
		   reset to factory defaults */
2424
		echo <<<EOD
2425

    
2426
***********************************************************************
2427
* Reset button pressed - resetting configuration to factory defaults. *
2428
* All additional packages installed will be removed                   *
2429
* The system will reboot after this completes.                        *
2430
***********************************************************************
2431

    
2432

    
2433
EOD;
2434

    
2435
		reset_factory_defaults();
2436
		system_reboot_sync();
2437
		exit(0);
2438
	}
2439

    
2440
	return 0;
2441
}
2442

    
2443
function system_get_serial() {
2444
	$platform = system_identify_specific_platform();
2445

    
2446
	unset($output);
2447
	if ($platform['name'] == 'Turbot Dual-E') {
2448
		$if_info = pfSense_get_interface_addresses('igb0');
2449
		if (!empty($if_info['hwaddr'])) {
2450
			$serial = str_replace(":", "", $if_info['hwaddr']);
2451
		}
2452
	} else {
2453
		foreach (array('system', 'planar', 'chassis') as $key) {
2454
			unset($output);
2455
			$_gb = exec("/bin/kenv -q smbios.{$key}.serial",
2456
			    $output);
2457
			if (!empty($output[0]) && $output[0] != "0123456789" &&
2458
			    preg_match('/^[\w\d]{10,16}$/', $output[0]) === 1) {
2459
				$serial = $output[0];
2460
				break;
2461
			}
2462
		}
2463
	}
2464

    
2465
	$vm_guest = get_single_sysctl('kern.vm_guest');
2466

    
2467
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2468
	    $vm_guest == 'none') {
2469
		return $serial;
2470
	}
2471

    
2472
	return "";
2473
}
2474

    
2475
function system_get_uniqueid() {
2476
	global $g;
2477

    
2478
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2479

    
2480
	if (empty($g['uniqueid'])) {
2481
		if (!file_exists($uniqueid_file)) {
2482
			mwexec("/usr/sbin/gnid > {$g['vardb_path']}/uniqueid " .
2483
			    "2>/dev/null");
2484
		}
2485
		if (file_exists($uniqueid_file)) {
2486
			$g['uniqueid'] = @file_get_contents($uniqueid_file);
2487
		}
2488
	}
2489

    
2490
	return ($g['uniqueid'] ?: '');
2491
}
2492

    
2493
/*
2494
 * attempt to identify the specific platform (for embedded systems)
2495
 * Returns an array with two elements:
2496
 * name => platform string (e.g. 'wrap', 'alix' etc.)
2497
 * descr => human-readable description (e.g. "PC Engines WRAP")
2498
 */
2499
function system_identify_specific_platform() {
2500
	global $g;
2501

    
2502
	$hw_model = get_single_sysctl('hw.model');
2503
	$hw_ncpu = get_single_sysctl('hw.ncpu');
2504

    
2505
	/* Try to guess from smbios strings */
2506
	unset($product);
2507
	unset($maker);
2508
	unset($bios);
2509
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $product);
2510
	$_gb = exec('/bin/kenv -q smbios.system.maker 2>/dev/null', $maker);
2511
	$_gb = exec('/bin/kenv -q smbios.bios.version 2>/dev/null', $bios);
2512

    
2513
	$vm = get_single_sysctl('kern.vm_guest');
2514

    
2515
	// This switch needs to be expanded to include other virtualization systems
2516
	switch ($vm) {
2517
		case "none" :
2518
		break;
2519

    
2520
		case "kvm" :
2521
			return (array('name' => 'KVM', 'descr' => 'KVM Guest'));
2522
		break;
2523
	}
2524

    
2525
	if ($maker[0] == "QEMU") {
2526
		return (array('name' => 'QEMU', 'descr' => 'QEMU'));
2527
	}
2528

    
2529
	// AWS can only be identified via the bios version
2530
	if (stripos($bios[0], "amazon") !== false) {
2531
		return (array('name' => 'AWS', 'descr' => 'Amazon Web Services'));
2532
	} else  if (stripos($bios[0], "Google") !== false) {
2533
		return (array('name' => 'Google', 'descr' => 'Google Cloud Platform'));
2534
	}
2535

    
2536
	switch ($product[0]) {
2537
		case 'FW7541':
2538
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2539
			break;
2540
		case 'APU':
2541
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2542
			break;
2543
		case 'RCC-VE':
2544
			$result = array();
2545
			$result['name'] = 'RCC-VE';
2546

    
2547
			/* Detect specific models */
2548
			if (!function_exists('does_interface_exist')) {
2549
				require_once("interfaces.inc");
2550
			}
2551
			if (!does_interface_exist('igb4')) {
2552
				$result['model'] = 'SG-2440';
2553
			} elseif (strpos($hw_model, "C2558") !== false) {
2554
				$result['model'] = 'SG-4860';
2555
			} elseif (strpos($hw_model, "C2758") !== false) {
2556
				$result['model'] = 'SG-8860';
2557
			} else {
2558
				$result['model'] = 'RCC-VE';
2559
			}
2560
			$result['descr'] = 'Netgate ' . $result['model'];
2561
			return $result;
2562
			break;
2563
		case 'DFFv2':
2564
			return (array('name' => 'SG-2220', 'descr' => 'Netgate SG-2220'));
2565
			break;
2566
		case 'RCC':
2567
			return (array('name' => 'RCC', 'descr' => 'Netgate XG-2758'));
2568
			break;
2569
		case 'SG-5100':
2570
			return (array('name' => 'SG-5100', 'descr' => 'Netgate SG-5100'));
2571
			break;
2572
		case 'Minnowboard Turbot D0 PLATFORM':
2573
		case 'Minnowboard Turbot D0/D1 PLATFORM':
2574
			$result = array();
2575
			$result['name'] = 'Turbot Dual-E';
2576
			/* Detect specific model */
2577
			switch ($hw_ncpu) {
2578
			case '4':
2579
				$result['model'] = 'MBT-4220';
2580
				break;
2581
			case '2':
2582
				$result['model'] = 'MBT-2220';
2583
				break;
2584
			default:
2585
				$result['model'] = $result['name'];
2586
				break;
2587
			}
2588
			$result['descr'] = 'Netgate ' . $result['model'];
2589
			return $result;
2590
			break;
2591
		case 'SYS-5018A-FTN4':
2592
		case 'A1SAi':
2593
			if (strpos($hw_model, "C2558") !== false) {
2594
				return (array(
2595
				    'name' => 'C2558',
2596
				    'descr' => 'Super Micro C2558'));
2597
			} elseif (strpos($hw_model, "C2758") !== false) {
2598
				return (array(
2599
				    'name' => 'C2758',
2600
				    'descr' => 'Super Micro C2758'));
2601
			}
2602
			break;
2603
		case 'SYS-5018D-FN4T':
2604
			if (strpos($hw_model, "D-1541") !== false) {
2605
				return (array('name' => 'XG-1541', 'descr' => 'Super Micro XG-1541'));
2606
			} else {
2607
				return (array('name' => 'XG-1540', 'descr' => 'Super Micro XG-1540'));
2608
			}
2609
			break;
2610
		case 'apu2':
2611
		case 'APU2':
2612
			return (array('name' => 'apu2', 'descr' => 'PC Engines APU2'));
2613
			break;
2614
		case 'VirtualBox':
2615
			return (array('name' => 'VirtualBox', 'descr' => 'VirtualBox Virtual Machine'));
2616
			break;
2617
		case 'Virtual Machine':
2618
			if ($maker[0] == "Microsoft Corporation") {
2619
				if (stripos($bios[0], "Hyper") !== false) {
2620
					return (array('name' => 'Hyper-V', 'descr' => 'Hyper-V Virtual Machine'));
2621
				} else {
2622
					return (array('name' => 'Azure', 'descr' => 'Microsoft Azure'));
2623
				}
2624
			}
2625
			break;
2626
		case 'VMware Virtual Platform':
2627
			if ($maker[0] == "VMware, Inc.") {
2628
				return (array('name' => 'VMware', 'descr' => 'VMware Virtual Machine'));
2629
			}
2630
			break;
2631
	}
2632

    
2633
	$_gb = exec('/bin/kenv -q smbios.planar.product 2>/dev/null',
2634
	    $planar_product);
2635
	if (isset($planar_product[0]) &&
2636
	    $planar_product[0] == 'X10SDV-8C-TLN4F+') {
2637
		return array('name' => 'XG-1537', 'descr' => 'Super Micro XG-1537');
2638
	}
2639

    
2640
	if (strpos($hw_model, "PC Engines WRAP") !== false) {
2641
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
2642
	}
2643

    
2644
	if (strpos($hw_model, "PC Engines ALIX") !== false) {
2645
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2646
	}
2647

    
2648
	if (preg_match("/Soekris net45../", $hw_model, $matches)) {
2649
		return array('name' => 'net45xx', 'descr' => $matches[0]);
2650
	}
2651

    
2652
	if (preg_match("/Soekris net48../", $hw_model, $matches)) {
2653
		return array('name' => 'net48xx', 'descr' => $matches[0]);
2654
	}
2655

    
2656
	if (preg_match("/Soekris net55../", $hw_model, $matches)) {
2657
		return array('name' => 'net55xx', 'descr' => $matches[0]);
2658
	}
2659

    
2660
	unset($hw_model);
2661

    
2662
	$dmesg_boot = system_get_dmesg_boot();
2663
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
2664
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2665
	}
2666
	unset($dmesg_boot);
2667

    
2668
	return array('name' => $g['product_name'], 'descr' => $g['product_label']);
2669
}
2670

    
2671
function system_get_dmesg_boot() {
2672
	global $g;
2673

    
2674
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2675
}
2676

    
2677
function system_get_arp_table($resolve_hostnames = false) {
2678
	$params="-a";
2679
	if (!$resolve_hostnames) {
2680
		$params .= "n";
2681
	}
2682

    
2683
	$arp_table = array();
2684
	$_gb = exec("/usr/sbin/arp --libxo json {$params}", $rawdata, $rc);
2685
	if ($rc == 0) {
2686
		$arp_table = json_decode(implode(" ", $rawdata),
2687
		    JSON_OBJECT_AS_ARRAY);
2688
		if ($rc == 0) {
2689
			$arp_table = $arp_table['arp']['arp-cache'];
2690
		}
2691
	}
2692

    
2693
	return $arp_table;
2694
}
2695

    
2696
?>
(49-49/61)