Project

General

Profile

Download (73.1 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

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

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

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

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

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

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

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

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

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

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

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

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

    
1063
	return 0;
1064
}
1065

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

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

    
1078
	return;
1079
}
1080

    
1081
function system_webgui_create_certificate() {
1082
	global $config, $g, $cert_strict_values;
1083

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

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

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

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

    
1115
function system_webgui_start() {
1116
	global $config, $g;
1117

    
1118
	if (platform_booting()) {
1119
		echo gettext("Starting webConfigurator...");
1120
	}
1121

    
1122
	chdir($g['www_path']);
1123

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

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

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

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

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

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

    
1159
	sleep(1);
1160

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

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

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

    
1174
	return $res;
1175
}
1176

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

    
1195
	$dns_nameservers = array();
1196

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

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

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

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

    
1254
	global $config, $g;
1255

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

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

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

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

    
1295
	$memory = get_memory();
1296
	$realmem = $memory[1];
1297

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

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

    
1316
	$nginx_config = <<<EOD
1317
#
1318
# nginx configuration file
1319

    
1320
pid {$g['varrun_path']}/{$pid_file};
1321

    
1322
user  root wheel;
1323
worker_processes  {$max_procs};
1324

    
1325
EOD;
1326

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

    
1334
	$nginx_config .= <<<EOD
1335

    
1336
events {
1337
    worker_connections  1024;
1338
}
1339

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

    
1346
	sendfile        on;
1347

    
1348
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1349

    
1350
EOD;
1351

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

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

    
1399
	$nginx_config .= <<<EOD
1400

    
1401
		client_max_body_size 200m;
1402

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

    
1406

    
1407
EOD;
1408

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

    
1416
EOD;
1417

    
1418
	}
1419

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

    
1454
EOD;
1455

    
1456
	$cert = str_replace("\r", "", $cert);
1457
	$key = str_replace("\r", "", $key);
1458

    
1459
	$cert = str_replace("\n\n", "\n", $cert);
1460
	$key = str_replace("\n\n", "\n", $key);
1461

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

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

    
1498
EOD;
1499
	}
1500

    
1501
	$nginx_config .= "}\n";
1502

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

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

    
1514
	return 0;
1515

    
1516
}
1517

    
1518
function system_get_timezone_list() {
1519
	global $g;
1520

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

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

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

    
1539
	sort($file_list);
1540

    
1541
	return $file_list;
1542
}
1543

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

    
1551
	$syscfg = $config['system'];
1552

    
1553
	if (platform_booting()) {
1554
		echo gettext("Setting timezone...");
1555
	}
1556

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

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

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

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

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

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

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

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

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

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

    
1645
function system_ntp_fixup_poll_value($type, $configvalue, $default) {
1646
	$pollstring = "";
1647

    
1648
	if (empty($configvalue)) {
1649
		$configvalue = $default;
1650
	}
1651

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

    
1656
	return $pollstring;
1657
}
1658

    
1659
function system_ntp_setup_gps($serialport) {
1660
	global $config, $g;
1661

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

    
1666
	init_config_arr(array('ntpd', 'gps'));
1667

    
1668
	$gps_device = '/dev/gps0';
1669
	$serialport = '/dev/'.$serialport;
1670

    
1671
	if (!file_exists($serialport)) {
1672
		return false;
1673
	}
1674

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

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

    
1692
	system_ntp_setup_rawspeed($serialport, $gpsbaud);
1693

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

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

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

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

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

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

    
1742
	return true;
1743
}
1744

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

    
1751
function system_ntp_setup_pps($serialport) {
1752
	global $config, $g;
1753

    
1754
	$pps_device = '/dev/pps0';
1755
	$serialport = '/dev/'.$serialport;
1756

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

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

    
1769

    
1770
	return true;
1771
}
1772

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

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

    
1783
	safe_mkdir($statsdir);
1784

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

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

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

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

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

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

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

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

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

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

    
1988
		$ntpcfg .= "{$ts} iburst";
1989

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

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

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

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

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

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

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

    
2131

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

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

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

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

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

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

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

    
2178
	return;
2179
}
2180

    
2181
function system_halt() {
2182
	global $g;
2183

    
2184
	system_reboot_cleanup();
2185

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

    
2189
function system_reboot() {
2190
	global $g;
2191

    
2192
	system_reboot_cleanup();
2193

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

    
2197
function system_reboot_sync($reroot=false) {
2198
	global $g;
2199

    
2200
	if ($reroot) {
2201
		$args = " -r ";
2202
	}
2203

    
2204
	system_reboot_cleanup();
2205

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

    
2209
function system_reboot_cleanup() {
2210
	global $config, $g, $cpzone;
2211

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

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

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

    
2247
	if (is_array($config['system'][$cmdn])) {
2248

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

    
2254
	} elseif ($config['system'][$cmdn] <> "") {
2255

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

    
2259
	}
2260
}
2261

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

    
2269
	$dmesg = "";
2270
	$_gb = exec("/sbin/dmesg", $dmesg);
2271

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

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

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

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

    
2291
	fclose($fd);
2292
	unset($dmesg);
2293

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

    
2297
	return 0;
2298
}
2299

    
2300
function system_set_harddisk_standby() {
2301
	global $g, $config;
2302

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

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

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

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

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

    
2346
	activate_sysctls();
2347

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

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

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

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

    
2396
function system_check_reset_button() {
2397
	global $g;
2398

    
2399
	$specplatform = system_identify_specific_platform();
2400

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

    
2417
	$retval = mwexec("/usr/local/sbin/" . $binprefix . "resetbtn");
2418

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

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

    
2430

    
2431
EOD;
2432

    
2433
		reset_factory_defaults();
2434
		system_reboot_sync();
2435
		exit(0);
2436
	}
2437

    
2438
	return 0;
2439
}
2440

    
2441
function system_get_serial() {
2442
	$platform = system_identify_specific_platform();
2443

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

    
2463
	$vm_guest = get_single_sysctl('kern.vm_guest');
2464

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

    
2470
	return "";
2471
}
2472

    
2473
function system_get_uniqueid() {
2474
	global $g;
2475

    
2476
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2477

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

    
2488
	return ($g['uniqueid'] ?: '');
2489
}
2490

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

    
2500
	$hw_model = get_single_sysctl('hw.model');
2501
	$hw_ncpu = get_single_sysctl('hw.ncpu');
2502

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

    
2511
	$vm = get_single_sysctl('kern.vm_guest');
2512

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

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

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

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

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

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

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

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

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

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

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

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

    
2658
	unset($hw_model);
2659

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

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

    
2669
function system_get_dmesg_boot() {
2670
	global $g;
2671

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

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

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

    
2691
	return $arp_table;
2692
}
2693

    
2694
?>
(49-49/61)