Project

General

Profile

Download (72.5 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 <[email protected]>.
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
		if (!empty($dnsserver)) {
224
			if (is_ipaddr($gatewayip)) {
225
				route_add_or_change($dnsserver, $gatewayip);
226
			} else {
227
				/* Remove old route when disable gw */
228
				route_del($dnsserver);
229
			}
230
		}
231
		$dnscounter++;
232
		$dnsgw = "dns{$dnscounter}gw";
233
	}
234

    
235
	unlock($dnslock);
236

    
237
	return 0;
238
}
239

    
240
function get_searchdomains() {
241
	global $config, $g;
242

    
243
	$master_list = array();
244

    
245
	// Read in dhclient nameservers
246
	$search_list = glob("/var/etc/searchdomain_*");
247
	if (is_array($search_list)) {
248
		foreach ($search_list as $fdns) {
249
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
250
			if (!is_array($contents)) {
251
				continue;
252
			}
253
			foreach ($contents as $dns) {
254
				if (is_hostname($dns)) {
255
					$master_list[] = $dns;
256
				}
257
			}
258
		}
259
	}
260

    
261
	return $master_list;
262
}
263

    
264
/* Stub for deprecated function name
265
 * See https://redmine.pfsense.org/issues/10931 */
266
function get_nameservers() {
267
	return get_dynamic_nameservers();
268
}
269

    
270
/****f* system.inc/get_dynamic_nameservers
271
 * NAME
272
 *   get_dynamic_nameservers - Get DNS servers from dynamic sources (DHCP, PPP, etc)
273
 * INPUTS
274
 *   $iface: Interface name used to filter results.
275
 * RESULT
276
 *   $master_list - Array containing DNS servers
277
 ******/
278
function get_dynamic_nameservers($iface = '') {
279
	global $config, $g;
280
	$master_list = array();
281

    
282
	if (!empty($iface)) {
283
		$realif = get_real_interface($iface);
284
	}
285

    
286
	// Read in dynamic nameservers
287
	$dns_lists = array_merge(glob("/var/etc/nameserver_{$realif}*"), glob("/var/etc/nameserver_v6{$iface}*"));
288
	if (is_array($dns_lists)) {
289
		foreach ($dns_lists as $fdns) {
290
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
291
			if (!is_array($contents)) {
292
				continue;
293
			}
294
			foreach ($contents as $dns) {
295
				if (is_ipaddr($dns)) {
296
					$master_list[] = $dns;
297
				}
298
			}
299
		}
300
	}
301

    
302
	return $master_list;
303
}
304

    
305
/* Create localhost + local interfaces entries for /etc/hosts */
306
function system_hosts_local_entries() {
307
	global $config;
308

    
309
	$syscfg = $config['system'];
310

    
311
	$hosts = array();
312
	$hosts[] = array(
313
	    'ipaddr' => '127.0.0.1',
314
	    'fqdn' => 'localhost.' . $syscfg['domain'],
315
	    'name' => 'localhost',
316
	    'domain' => $syscfg['domain']
317
	);
318
	$hosts[] = array(
319
	    'ipaddr' => '::1',
320
	    'fqdn' => 'localhost.' . $syscfg['domain'],
321
	    'name' => 'localhost',
322
	    'domain' => $syscfg['domain']
323
	);
324

    
325
	if ($config['interfaces']['lan']) {
326
		$sysiflist = array('lan' => "lan");
327
	} else {
328
		$sysiflist = get_configured_interface_list();
329
	}
330

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

    
364
	return $hosts;
365
}
366

    
367
/* Read host override entries from dnsmasq or unbound */
368
function system_hosts_override_entries($dnscfg) {
369
	$hosts = array();
370

    
371
	if (!is_array($dnscfg) ||
372
	    !is_array($dnscfg['hosts']) ||
373
	    !isset($dnscfg['enable'])) {
374
		return $hosts;
375
	}
376

    
377
	foreach ($dnscfg['hosts'] as $host) {
378
		$fqdn = '';
379
		if ($host['host'] || $host['host'] == "0") {
380
			$fqdn .= "{$host['host']}.";
381
		}
382
		$fqdn .= $host['domain'];
383

    
384
		foreach (explode(',', $host['ip']) as $ip) {
385
			$hosts[] = array(
386
			    'ipaddr' => $ip,
387
			    'fqdn' => $fqdn,
388
			    'name' => $host['host'],
389
			    'domain' => $host['domain']
390
			);
391
		}
392

    
393
		if (!is_array($host['aliases']) ||
394
		    !is_array($host['aliases']['item'])) {
395
			continue;
396
		}
397

    
398
		foreach ($host['aliases']['item'] as $alias) {
399
			$fqdn = '';
400
			if ($alias['host'] || $alias['host'] == "0") {
401
				$fqdn .= "{$alias['host']}.";
402
			}
403
			$fqdn .= $alias['domain'];
404

    
405
			foreach (explode(',', $host['ip']) as $ip) {
406
				$hosts[] = array(
407
				    'ipaddr' => $ip,
408
				    'fqdn' => $fqdn,
409
				    'name' => $alias['host'],
410
				    'domain' => $alias['domain']
411
				);
412
			}
413
		}
414
	}
415

    
416
	return $hosts;
417
}
418

    
419
/* Read all dhcpd/dhcpdv6 staticmap entries */
420
function system_hosts_dhcpd_entries() {
421
	global $config;
422

    
423
	$hosts = array();
424
	$syscfg = $config['system'];
425

    
426
	if (is_array($config['dhcpd'])) {
427
		$conf_dhcpd = $config['dhcpd'];
428
	} else {
429
		$conf_dhcpd = array();
430
	}
431

    
432
	foreach ($conf_dhcpd as $dhcpif => $dhcpifconf) {
433
		if (!is_array($dhcpifconf['staticmap']) ||
434
		    !isset($dhcpifconf['enable'])) {
435
			continue;
436
		}
437
		foreach ($dhcpifconf['staticmap'] as $host) {
438
			if (!$host['ipaddr'] ||
439
			    !$host['hostname']) {
440
				continue;
441
			}
442

    
443
			$fqdn = $host['hostname'] . ".";
444
			$domain = "";
445
			if ($host['domain']) {
446
				$domain = $host['domain'];
447
			} elseif ($dhcpifconf['domain']) {
448
				$domain = $dhcpifconf['domain'];
449
			} else {
450
				$domain = $syscfg['domain'];
451
			}
452

    
453
			$hosts[] = array(
454
			    'ipaddr' => $host['ipaddr'],
455
			    'fqdn' => $fqdn . $domain,
456
			    'name' => $host['hostname'],
457
			    'domain' => $domain
458
			);
459
		}
460
	}
461
	unset($conf_dhcpd);
462

    
463
	if (is_array($config['dhcpdv6'])) {
464
		$conf_dhcpdv6 = $config['dhcpdv6'];
465
	} else {
466
		$conf_dhcpdv6 = array();
467
	}
468

    
469
	foreach ($conf_dhcpdv6 as $dhcpif => $dhcpifconf) {
470
		if (!is_array($dhcpifconf['staticmap']) ||
471
		    !isset($dhcpifconf['enable'])) {
472
			continue;
473
		}
474

    
475
		if (isset($config['interfaces'][$dhcpif]['ipaddrv6']) &&
476
		    $config['interfaces'][$dhcpif]['ipaddrv6'] ==
477
		    'track6') {
478
			$isdelegated = true;
479
		} else {
480
			$isdelegated = false;
481
		}
482

    
483
		foreach ($dhcpifconf['staticmap'] as $host) {
484
			$ipaddrv6 = $host['ipaddrv6'];
485

    
486
			if (!$ipaddrv6 || !$host['hostname']) {
487
				continue;
488
			}
489

    
490
			if ($isdelegated) {
491
				/*
492
				 * We are always in an "end-user" subnet
493
				 * here, which all are /64 for IPv6.
494
				 */
495
				$prefix6 = 64;
496
			} else {
497
				$prefix6 = get_interface_subnetv6($dhcpif);
498
			}
499
			$ipaddrv6 = merge_ipv6_delegated_prefix(get_interface_ipv6($dhcpif), $ipaddrv6, $prefix6);
500

    
501
			$fqdn = $host['hostname'] . ".";
502
			$domain = "";
503
			if ($host['domain']) {
504
				$domain = $host['domain'];
505
			} elseif ($dhcpifconf['domain']) {
506
				$domain = $dhcpifconf['domain'];
507
			} else {
508
				$domain = $syscfg['domain'];
509
			}
510

    
511
			$hosts[] = array(
512
			    'ipaddr' => $ipaddrv6,
513
			    'fqdn' => $fqdn . $domain,
514
			    'name' => $host['hostname'],
515
			    'domain' => $domain
516
			);
517
		}
518
	}
519
	unset($conf_dhcpdv6);
520

    
521
	return $hosts;
522
}
523

    
524
/* Concatenate local, dnsmasq/unbound and dhcpd/dhcpdv6 hosts entries */
525
function system_hosts_entries($dnscfg) {
526
	$local = array();
527
	if (!isset($dnscfg['disable_auto_added_host_entries'])) {
528
		$local = system_hosts_local_entries();
529
	}
530

    
531
	$dns = array();
532
	$dhcpd = array();
533
	if (isset($dnscfg['enable'])) {
534
		$dns = system_hosts_override_entries($dnscfg);
535
		if (isset($dnscfg['regdhcpstatic'])) {
536
			$dhcpd = system_hosts_dhcpd_entries();
537
		}
538
	}
539

    
540
	if (isset($dnscfg['dhcpfirst'])) {
541
		return array_merge($local, $dns, $dhcpd);
542
	} else {
543
		return array_merge($local, $dhcpd, $dns);
544
	}
545
}
546

    
547
function system_hosts_generate() {
548
	global $config, $g;
549
	if (isset($config['system']['developerspew'])) {
550
		$mt = microtime();
551
		echo "system_hosts_generate() being called $mt\n";
552
	}
553

    
554
	// prefer dnsmasq for hosts generation where it's enabled. It relies
555
	// on hosts for name resolution of its overrides, unbound does not.
556
	if (isset($config['dnsmasq']) && isset($config['dnsmasq']['enable'])) {
557
		$dnsmasqcfg = $config['dnsmasq'];
558
	} else {
559
		$dnsmasqcfg = $config['unbound'];
560
	}
561

    
562
	$syscfg = $config['system'];
563
	$hosts = "";
564
	$lhosts = "";
565
	$dhosts = "";
566

    
567
	$hosts_array = system_hosts_entries($dnsmasqcfg);
568
	foreach ($hosts_array as $host) {
569
		$hosts .= "{$host['ipaddr']}\t";
570
		if ($host['name'] == "localhost") {
571
			$hosts .= "{$host['name']} {$host['fqdn']}";
572
		} else {
573
			$hosts .= "{$host['fqdn']} {$host['name']}";
574
		}
575
		$hosts .= "\n";
576
	}
577
	unset($hosts_array);
578

    
579
	/*
580
	 * Do not remove this because dhcpleases monitors with kqueue it needs
581
	 * to be killed before writing to hosts files.
582
	 */
583
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
584
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
585
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
586
	}
587

    
588
	$fd = fopen("{$g['etc_path']}/hosts", "w");
589
	if (!$fd) {
590
		log_error(gettext(
591
		    "Error: cannot open hosts file in system_hosts_generate()."
592
		    ));
593
		return 1;
594
	}
595

    
596
	fwrite($fd, $hosts);
597
	fclose($fd);
598

    
599
	if (isset($config['unbound']['enable'])) {
600
		require_once("unbound.inc");
601
		unbound_hosts_generate();
602
	}
603

    
604
	/* restart dhcpleases */
605
	if (!platform_booting()) {
606
		system_dhcpleases_configure();
607
	}
608

    
609
	return 0;
610
}
611

    
612
function system_dhcpleases_configure() {
613
	global $config, $g;
614
	if (!function_exists('is_dhcp_server_enabled')) {
615
		require_once('pfsense-utils.inc');
616
	}
617
	$pidfile = "{$g['varrun_path']}/dhcpleases.pid";
618

    
619
	/* Start the monitoring process for dynamic dhcpclients. */
620
	if (((isset($config['dnsmasq']['enable']) && isset($config['dnsmasq']['regdhcp'])) ||
621
	    (isset($config['unbound']['enable']) && isset($config['unbound']['regdhcp']))) &&
622
	    (is_dhcp_server_enabled())) {
623
		/* Make sure we do not error out */
624
		mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db");
625
		if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
626
			@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
627
		}
628

    
629
		if (isset($config['unbound']['enable'])) {
630
			$dns_pid = "unbound.pid";
631
			$unbound_conf = "-u {$g['unbound_chroot_path']}/dhcpleases_entries.conf";
632
		} else {
633
			$dns_pid = "dnsmasq.pid";
634
			$unbound_conf = "";
635
		}
636

    
637
		if (isvalidpid($pidfile)) {
638
			/* Make sure dhcpleases is using correct unbound or dnsmasq */
639
			$_gb = exec("/bin/pgrep -F {$pidfile} -f {$dns_pid}", $output, $retval);
640
			if (intval($retval) == 0) {
641
				sigkillbypid($pidfile, "HUP");
642
				return;
643
			} else {
644
				sigkillbypid($pidfile, "TERM");
645
			}
646
		}
647

    
648
		/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
649
		if (is_process_running("dhcpleases")) {
650
			sigkillbyname('dhcpleases', "TERM");
651
		}
652
		@unlink($pidfile);
653
		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");
654
	} else {
655
		if (isvalidpid($pidfile)) {
656
			sigkillbypid($pidfile, "TERM");
657
			@unlink($pidfile);
658
		}
659
		if (file_exists("{$g['unbound_chroot_path']}/dhcpleases_entries.conf")) {
660
			$dhcpleases = fopen("{$g['unbound_chroot_path']}/dhcpleases_entries.conf", "w");
661
			ftruncate($dhcpleases, 0);
662
			fclose($dhcpleases);
663
		}
664
	}
665
}
666

    
667
function system_get_dhcpleases() {
668
	global $config, $g;
669

    
670
	$leases = array();
671
	$leases['lease'] = array();
672
	$leases['failover'] = array();
673

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

    
676
	if (!file_exists($leases_file)) {
677
		return $leases;
678
	}
679

    
680
	$leases_content = file($leases_file, FILE_IGNORE_NEW_LINES |
681
	    FILE_IGNORE_NEW_LINES);
682

    
683
	if ($leases_content === FALSE) {
684
		return $leases;
685
	}
686

    
687
	$arp_table = system_get_arp_table();
688

    
689
	$arpdata_ip = array();
690
	$arpdata_mac = array();
691
	foreach ($arp_table as $arp_entry) {
692
		if (isset($arpentry['incomplete'])) {
693
			continue;
694
		}
695
		$arpdata_ip[] = $arp_entry['ip-address'];
696
		$arpdata_mac[] = $arp_entry['mac-address'];
697
	}
698
	unset($arp_table);
699

    
700
	/*
701
	 * Translate these once so we don't do it over and over in the loops
702
	 * below.
703
	 */
704
	$online_string = gettext("online");
705
	$offline_string = gettext("offline");
706
	$active_string = gettext("active");
707
	$expired_string = gettext("expired");
708
	$reserved_string = gettext("reserved");
709
	$dynamic_string = gettext("dynamic");
710
	$static_string = gettext("static");
711

    
712
	$lease_regex = '/^lease\s+([^\s]+)\s+{$/';
713
	$starts_regex = '/^\s*(starts|ends)\s+\d+\s+([\d\/]+|never)\s*(|[\d:]*);$/';
714
	$binding_regex = '/^\s*binding\s+state\s+(.+);$/';
715
	$mac_regex = '/^\s*hardware\s+ethernet\s+(.+);$/';
716
	$hostname_regex = '/^\s*client-hostname\s+"(.+)";$/';
717

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

    
721
	$lease = false;
722
	$failover = false;
723
	$dedup_lease = false;
724
	$dedup_failover = false;
725
	foreach ($leases_content as $line) {
726
		/* Skip comments */
727
		if (preg_match('/^\s*(|#.*)$/', $line)) {
728
			continue;
729
		}
730

    
731
		if (preg_match('/}$/', $line)) {
732
			if ($lease) {
733
				if (empty($item['hostname'])) {
734
					$hostname = gethostbyaddr($item['ip']);
735
					if (!empty($hostname)) {
736
						$item['hostname'] = $hostname;
737
					}
738
				}
739
				$leases['lease'][] = $item;
740
				$lease = false;
741
				$dedup_lease = true;
742
			} else if ($failover) {
743
				$leases['failover'][] = $item;
744
				$failover = false;
745
				$dedup_failover = true;
746
			}
747
			continue;
748
		}
749

    
750
		if (preg_match($lease_regex, $line, $m)) {
751
			$lease = true;
752
			$item = array();
753
			$item['ip'] = $m[1];
754
			$item['type'] = $dynamic_string;
755
			continue;
756
		}
757

    
758
		if ($lease) {
759
			if (preg_match($starts_regex, $line, $m)) {
760
				/*
761
				 * Quote from dhcpd.leases(5) man page:
762
				 * If a lease will never expire, date is never
763
				 * instead of an actual date
764
				 */
765
				if ($m[2] == "never") {
766
					$item[$m[1]] = gettext("Never");
767
				} else {
768
					$item[$m[1]] = dhcpd_date_adjust_gmt(
769
					    $m[2] . ' ' . $m[3]);
770
				}
771
				continue;
772
			}
773

    
774
			if (preg_match($binding_regex, $line, $m)) {
775
				switch ($m[1]) {
776
					case "active":
777
						$item['act'] = $active_string;
778
						break;
779
					case "free":
780
						$item['act'] = $expired_string;
781
						$item['online'] =
782
						    $offline_string;
783
						break;
784
					case "backup":
785
						$item['act'] = $reserved_string;
786
						$item['online'] =
787
						    $offline_string;
788
						break;
789
				}
790
				continue;
791
			}
792

    
793
			if (preg_match($mac_regex, $line, $m) &&
794
			    is_macaddr($m[1])) {
795
				$item['mac'] = $m[1];
796

    
797
				if (in_array($item['ip'], $arpdata_ip)) {
798
					$item['online'] = $online_string;
799
				} else {
800
					$item['online'] = $offline_string;
801
				}
802
				continue;
803
			}
804

    
805
			if (preg_match($hostname_regex, $line, $m)) {
806
				$item['hostname'] = $m[1];
807
			}
808
		}
809

    
810
		if (preg_match($failover_regex, $line, $m)) {
811
			$failover = true;
812
			$item = array();
813
			$item['name'] = $m[1] . ' (' .
814
			    convert_friendly_interface_to_friendly_descr(
815
			    substr($m[1],5)) . ')';
816
			continue;
817
		}
818

    
819
		if ($failover && preg_match($state_regex, $line, $m)) {
820
			$item[$m[1] . 'state'] = $m[2];
821
			$item[$m[1] . 'date'] = dhcpd_date_adjust_gmt($m[3] .
822
			    ' ' . $m[4]);
823
			continue;
824
		}
825
	}
826

    
827
	foreach ($config['interfaces'] as $ifname => $ifarr) {
828
		if (!is_array($config['dhcpd'][$ifname]) ||
829
		    !is_array($config['dhcpd'][$ifname]['staticmap'])) {
830
			continue;
831
		}
832

    
833
		foreach ($config['dhcpd'][$ifname]['staticmap'] as $idx =>
834
		    $static) {
835
			if (empty($static['mac']) && empty($static['cid'])) {
836
				continue;
837
			}
838

    
839
			$slease = array();
840
			$slease['ip'] = $static['ipaddr'];
841
			$slease['type'] = $static_string;
842
			if (!empty($static['cid'])) {
843
				$slease['cid'] = $static['cid'];
844
			}
845
			$slease['mac'] = $static['mac'];
846
			$slease['if'] = $ifname;
847
			$slease['starts'] = "";
848
			$slease['ends'] = "";
849
			$slease['hostname'] = $static['hostname'];
850
			$slease['descr'] = $static['descr'];
851
			$slease['act'] = $static_string;
852
			$slease['online'] = in_array(strtolower($slease['mac']),
853
			    $arpdata_mac) ? $online_string : $offline_string;
854
			$slease['staticmap_array_index'] = $idx;
855
			$leases['lease'][] = $slease;
856
			$dedup_lease = true;
857
		}
858
	}
859

    
860
	if ($dedup_lease) {
861
		$leases['lease'] = array_remove_duplicate($leases['lease'],
862
		    'ip');
863
	}
864
	if ($dedup_failover) {
865
		$leases['failover'] = array_remove_duplicate(
866
		    $leases['failover'], 'name');
867
		asort($leases['failover']);
868
	}
869

    
870
	return $leases;
871
}
872

    
873
function system_hostname_configure() {
874
	global $config, $g;
875
	if (isset($config['system']['developerspew'])) {
876
		$mt = microtime();
877
		echo "system_hostname_configure() being called $mt\n";
878
	}
879

    
880
	$syscfg = $config['system'];
881

    
882
	/* set hostname */
883
	$status = mwexec("/bin/hostname " .
884
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
885

    
886
	/* Setup host GUID ID.  This is used by ZFS. */
887
	mwexec("/etc/rc.d/hostid start");
888

    
889
	return $status;
890
}
891

    
892
function system_routing_configure($interface = "") {
893
	global $config, $g;
894

    
895
	if (isset($config['system']['developerspew'])) {
896
		$mt = microtime();
897
		echo "system_routing_configure() being called $mt\n";
898
	}
899

    
900
	$gateways_arr = return_gateways_array(false, true);
901
	foreach ($gateways_arr as $gateway) {
902
		// setup static interface routes for nonlocal gateways
903
		if (isset($gateway["nonlocalgateway"])) {
904
			$srgatewayip = $gateway['gateway'];
905
			$srinterfacegw = $gateway['interface'];
906
			if (is_ipaddr($srgatewayip) && !empty($srinterfacegw)) {
907
				route_add_or_change($srgatewayip, '',
908
				    $srinterfacegw);
909
			}
910
		}
911
	}
912

    
913
	$gateways_status = return_gateways_status(true);
914
	fixup_default_gateway("inet", $gateways_status, $gateways_arr);
915
	fixup_default_gateway("inet6", $gateways_status, $gateways_arr);
916

    
917
	system_staticroutes_configure($interface, false);
918

    
919
	return 0;
920
}
921

    
922
function system_staticroutes_configure($interface = "", $update_dns = false) {
923
	global $config, $g, $aliastable;
924

    
925
	$filterdns_list = array();
926

    
927
	$static_routes = get_staticroutes(false, true);
928
	if (count($static_routes)) {
929
		$gateways_arr = return_gateways_array(false, true);
930
		$gateways_status = return_gateways_status(true);
931

    
932
		foreach ($static_routes as $rtent) {
933
			if (empty($gateways_arr[$rtent['gateway']])) {
934
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
935
				continue;
936
			}
937
			$gateway = $gateways_arr[$rtent['gateway']];
938
			if (!empty($interface) && $interface != $gateway['friendlyiface']) {
939
				continue;
940
			}
941

    
942
			$gatewayip = $gateway['gateway'];
943
			$interfacegw = $gateway['interface'];
944

    
945
			$blackhole = "";
946
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 4))) {
947
				$blackhole = "-blackhole";
948
			}
949

    
950
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network'])) {
951
				continue;
952
			}
953

    
954
			$dnscache = array();
955
			if ($update_dns === true) {
956
				if (is_subnet($rtent['network'])) {
957
					continue;
958
				}
959
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
960
				if (empty($dnscache)) {
961
					continue;
962
				}
963
			}
964

    
965
			if (is_subnet($rtent['network'])) {
966
				$ips = array($rtent['network']);
967
			} else {
968
				if (!isset($rtent['disabled'])) {
969
					$filterdns_list[] = $rtent['network'];
970
				}
971
				$ips = add_hostname_to_watch($rtent['network']);
972
			}
973

    
974
			foreach ($dnscache as $ip) {
975
				if (in_array($ip, $ips)) {
976
					continue;
977
				}
978
				route_del($ip);
979
			}
980

    
981
			if (isset($rtent['disabled']) || (!isset($gateway['action_disable']) &&
982
			    ($gateways_status[$gateway['name']]['status'] == 'down'))) {
983
				/*
984
				 * XXX: This can break things by deleting
985
				 * routes that shouldn't be deleted - OpenVPN,
986
				 * dynamic routing scenarios, etc.
987
				 * redmine #3709
988
				 */
989
				foreach ($ips as $ip) {
990
					route_del($ip);
991
				}
992
				continue;
993
			}
994

    
995
			foreach ($ips as $ip) {
996
				if (is_ipaddrv4($ip)) {
997
					$ip .= "/32";
998
				}
999
				/*
1000
				 * do NOT do the same check here on v6,
1001
				 * is_ipaddrv6 returns true when including
1002
				 * the CIDR mask. doing so breaks v6 routes
1003
				 */
1004
				if (is_subnet($ip)) {
1005
					if (is_ipaddr($gatewayip)) {
1006
						if (is_linklocal($gatewayip) == "6" &&
1007
						    !strpos($gatewayip, '%')) {
1008
							/*
1009
							 * add interface scope
1010
							 * for link local v6
1011
							 * routes
1012
							 */
1013
							$gatewayip .= "%$interfacegw";
1014
						}
1015
						route_add_or_change($ip,
1016
						    $gatewayip, '', $blackhole);
1017
					} else if (!empty($interfacegw)) {
1018
						route_add_or_change($ip,
1019
						    '', $interfacegw, $blackhole);
1020
					}
1021
				}
1022
			}
1023
		}
1024
		unset($gateways_arr);
1025
	}
1026
	unset($static_routes);
1027

    
1028
	if ($update_dns === false) {
1029
		if (count($filterdns_list)) {
1030
			$interval = 60;
1031
			$hostnames = "";
1032
			array_unique($filterdns_list);
1033
			foreach ($filterdns_list as $hostname) {
1034
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
1035
			}
1036
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
1037
			unset($hostnames);
1038

    
1039
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid")) {
1040
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
1041
			} else {
1042
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
1043
			}
1044
		} else {
1045
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
1046
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
1047
		}
1048
	}
1049
	unset($filterdns_list);
1050

    
1051
	return 0;
1052
}
1053

    
1054
function system_routing_enable() {
1055
	global $config, $g;
1056
	if (isset($config['system']['developerspew'])) {
1057
		$mt = microtime();
1058
		echo "system_routing_enable() being called $mt\n";
1059
	}
1060

    
1061
	set_sysctl(array(
1062
		"net.inet.ip.forwarding" => "1",
1063
		"net.inet6.ip6.forwarding" => "1"
1064
	));
1065

    
1066
	return;
1067
}
1068

    
1069
function system_webgui_create_certificate() {
1070
	global $config, $g, $cert_strict_values;
1071

    
1072
	init_config_arr(array('ca'));
1073
	$a_ca = &$config['ca'];
1074
	init_config_arr(array('cert'));
1075
	$a_cert = &$config['cert'];
1076
	log_error(gettext("Creating SSL/TLS Certificate for this host"));
1077

    
1078
	$cert = array();
1079
	$cert['refid'] = uniqid();
1080
	$cert['descr'] = sprintf(gettext("webConfigurator default (%s)"), $cert['refid']);
1081
	$cert_hostname = "{$config['system']['hostname']}-{$cert['refid']}";
1082

    
1083
	$dn = array(
1084
		'organizationName' => "{$g['product_label']} webConfigurator Self-Signed Certificate",
1085
		'commonName' => $cert_hostname,
1086
		'subjectAltName' => "DNS:{$cert_hostname}");
1087
	$old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warnings directly to a page screwing menu tab */
1088
	if (!cert_create($cert, null, 2048, $cert_strict_values['max_server_cert_lifetime'], $dn, "self-signed", "sha256")) {
1089
		while ($ssl_err = openssl_error_string()) {
1090
			log_error(sprintf(gettext("Error creating WebGUI Certificate: openssl library returns: %s"), $ssl_err));
1091
		}
1092
		error_reporting($old_err_level);
1093
		return null;
1094
	}
1095
	error_reporting($old_err_level);
1096

    
1097
	$a_cert[] = $cert;
1098
	$config['system']['webgui']['ssl-certref'] = $cert['refid'];
1099
	write_config(sprintf(gettext("Generated new self-signed SSL/TLS certificate for HTTPS (%s)"), $cert['refid']));
1100
	return $cert;
1101
}
1102

    
1103
function system_webgui_start() {
1104
	global $config, $g;
1105

    
1106
	if (platform_booting()) {
1107
		echo gettext("Starting webConfigurator...");
1108
	}
1109

    
1110
	chdir($g['www_path']);
1111

    
1112
	/* defaults */
1113
	$portarg = "80";
1114
	$crt = "";
1115
	$key = "";
1116
	$ca = "";
1117

    
1118
	/* non-standard port? */
1119
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "") {
1120
		$portarg = "{$config['system']['webgui']['port']}";
1121
	}
1122

    
1123
	if ($config['system']['webgui']['protocol'] == "https") {
1124
		// Ensure that we have a webConfigurator CERT
1125
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
1126
		if (!is_array($cert) || !$cert['crt'] || !$cert['prv']) {
1127
			$cert = system_webgui_create_certificate();
1128
		}
1129
		$crt = base64_decode($cert['crt']);
1130
		$key = base64_decode($cert['prv']);
1131

    
1132
		if (!$config['system']['webgui']['port']) {
1133
			$portarg = "443";
1134
		}
1135
		$ca = ca_chain($cert);
1136
		$hsts = isset($config['system']['webgui']['disablehsts']) ? false : true;
1137
	}
1138

    
1139
	/* generate nginx configuration */
1140
	system_generate_nginx_config("{$g['varetc_path']}/nginx-webConfigurator.conf",
1141
		$crt, $key, $ca, "nginx-webConfigurator.pid", $portarg, "/usr/local/www/",
1142
		"cert.crt", "cert.key", false, $hsts);
1143

    
1144
	/* kill any running nginx */
1145
	killbypid("{$g['varrun_path']}/nginx-webConfigurator.pid");
1146

    
1147
	sleep(1);
1148

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

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

    
1154
	if (platform_booting()) {
1155
		if ($res == 0) {
1156
			echo gettext("done.") . "\n";
1157
		} else {
1158
			echo gettext("failed!") . "\n";
1159
		}
1160
	}
1161

    
1162
	return $res;
1163
}
1164

    
1165
/****f* system.inc/get_dns_nameservers
1166
 * NAME
1167
 *   get_dns_nameservers - Get system DNS servers
1168
 * INPUTS
1169
 *   $add_v6_brackets: (boolean, false)
1170
 *                     Add brackets around IPv6 DNS servers, as expected by some
1171
 *                     daemons such as nginx.
1172
 *   $hostns         : (boolean, true)
1173
 *                     true : Return only DNS servers used by the firewall
1174
 *                            itself as upstream forwarding servers
1175
 *                     false: Return all DNS servers from the configuration and
1176
 *                            overrides (if allowed).
1177
 * RESULT
1178
 *   $dns_nameservers - An array of the requested DNS servers
1179
 ******/
1180
function get_dns_nameservers($add_v6_brackets = false, $hostns=true) {
1181
	global $config;
1182

    
1183
	$dns_nameservers = array();
1184

    
1185
	if (isset($config['system']['developerspew'])) {
1186
		$mt = microtime();
1187
		echo "get_dns_nameservers() being called $mt\n";
1188
	}
1189

    
1190
	$syscfg = $config['system'];
1191
	if ((((isset($config['dnsmasq']['enable'])) &&
1192
	    (empty($config['dnsmasq']['port']) || $config['dnsmasq']['port'] == "53") &&
1193
	    (empty($config['dnsmasq']['interface']) ||
1194
	    in_array("lo0", explode(",", $config['dnsmasq']['interface'])))) ||
1195
	    ((isset($config['unbound']['enable'])) &&
1196
	    (empty($config['unbound']['port']) || $config['unbound']['port'] == "53") &&
1197
	    (empty($config['unbound']['active_interface']) ||
1198
	    in_array("lo0", explode(",", $config['unbound']['active_interface'])) ||
1199
	    in_array("all", explode(",", $config['unbound']['active_interface']), true)))) &&
1200
	    ($config['system']['dnslocalhost'] != 'remote')) {
1201
		$dns_nameservers[] = "127.0.0.1";
1202
	}
1203

    
1204
	if ($hostns || ($config['system']['dnslocalhost'] != 'local')) {
1205
		if (isset($syscfg['dnsallowoverride'])) {
1206
			/* get dynamically assigned DNS servers (if any) */
1207
			foreach (array_unique(get_dynamic_nameservers()) as $nameserver) {
1208
				if ($nameserver) {
1209
					if ($add_v6_brackets && is_ipaddrv6($nameserver)) {
1210
						$nameserver = "[{$nameserver}]";
1211
					}
1212
					$dns_nameservers[] = $nameserver;
1213
				}
1214
			}
1215
		}
1216
		if (is_array($syscfg['dnsserver'])) {
1217
			foreach ($syscfg['dnsserver'] as $sys_dnsserver) {
1218
				if ($sys_dnsserver && (!in_array($sys_dnsserver, $dns_nameservers))) {
1219
					if ($add_v6_brackets && is_ipaddrv6($sys_dnsserver)) {
1220
						$sys_dnsserver = "[{$sys_dnsserver}]";
1221
					}
1222
					$dns_nameservers[] = $sys_dnsserver;
1223
				}
1224
			}
1225
		}
1226
	}
1227
	return array_unique($dns_nameservers);
1228
}
1229

    
1230
function system_generate_nginx_config($filename,
1231
	$cert,
1232
	$key,
1233
	$ca,
1234
	$pid_file,
1235
	$port = 80,
1236
	$document_root = "/usr/local/www/",
1237
	$cert_location = "cert.crt",
1238
	$key_location = "cert.key",
1239
	$captive_portal = false,
1240
	$hsts = true) {
1241

    
1242
	global $config, $g;
1243

    
1244
	if (isset($config['system']['developerspew'])) {
1245
		$mt = microtime();
1246
		echo "system_generate_nginx_config() being called $mt\n";
1247
	}
1248

    
1249
	if ($captive_portal !== false) {
1250
		$cp_interfaces = explode(",", $config['captiveportal'][$captive_portal]['interface']);
1251
		$cp_hostcheck = "";
1252
		foreach ($cp_interfaces as $cpint) {
1253
			$cpint_ip = get_interface_ip($cpint);
1254
			if (is_ipaddr($cpint_ip)) {
1255
				$cp_hostcheck .= "\t\tif (\$http_host ~* $cpint_ip) {\n";
1256
				$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1257
				$cp_hostcheck .= "\t\t}\n";
1258
			}
1259
		}
1260
		if (isset($config['captiveportal'][$captive_portal]['httpsname']) &&
1261
		    is_domain($config['captiveportal'][$captive_portal]['httpsname'])) {
1262
			$cp_hostcheck .= "\t\tif (\$http_host ~* {$config['captiveportal'][$captive_portal]['httpsname']}) {\n";
1263
			$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1264
			$cp_hostcheck .= "\t\t}\n";
1265
		}
1266
		$cp_rewrite = "\t\tif (\$cp_redirect = '') {\n";
1267
		$cp_rewrite .= "\t\t\trewrite	^ /index.php?zone=$captive_portal&redirurl=\$request_uri break;\n";
1268
		$cp_rewrite .= "\t\t}\n";
1269

    
1270
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1271
		if (empty($maxprocperip)) {
1272
			$maxprocperip = 10;
1273
		}
1274
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1275
	}
1276

    
1277
	if (empty($port)) {
1278
		$nginx_port = "80";
1279
	} else {
1280
		$nginx_port = $port;
1281
	}
1282

    
1283
	$memory = get_memory();
1284
	$realmem = $memory[1];
1285

    
1286
	// Determine web GUI process settings and take into account low memory systems
1287
	if ($realmem < 255) {
1288
		$max_procs = 1;
1289
	} else {
1290
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
1291
	}
1292

    
1293
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM
1294
	if ($captive_portal !== false) {
1295
		if ($realmem > 135 and $realmem < 256) {
1296
			$max_procs += 1; // 2 worker processes
1297
		} else if ($realmem > 255 and $realmem < 513) {
1298
			$max_procs += 2; // 3 worker processes
1299
		} else if ($realmem > 512) {
1300
			$max_procs += 4; // 6 worker processes
1301
		}
1302
	}
1303

    
1304
	$nginx_config = <<<EOD
1305
#
1306
# nginx configuration file
1307

    
1308
pid {$g['varrun_path']}/{$pid_file};
1309

    
1310
user  root wheel;
1311
worker_processes  {$max_procs};
1312

    
1313
EOD;
1314

    
1315
	/* Disable file logging */
1316
	$nginx_config .= "error_log /dev/null;\n";
1317
	if (!isset($config['syslog']['nolognginx'])) {
1318
		/* Send nginx error log to syslog */
1319
		$nginx_config .= "error_log  syslog:server=unix:/var/run/log,facility=local5;\n";
1320
	}
1321

    
1322
	$nginx_config .= <<<EOD
1323

    
1324
events {
1325
    worker_connections  1024;
1326
}
1327

    
1328
http {
1329
	include       /usr/local/etc/nginx/mime.types;
1330
	default_type  application/octet-stream;
1331
	add_header X-Frame-Options SAMEORIGIN;
1332
	server_tokens off;
1333

    
1334
	sendfile        on;
1335

    
1336
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1337

    
1338
EOD;
1339

    
1340
	if ($captive_portal !== false) {
1341
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1342
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1343
	} else {
1344
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1345
	}
1346

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

    
1387
	$nginx_config .= <<<EOD
1388

    
1389
		client_max_body_size 200m;
1390

    
1391
		gzip on;
1392
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
1393

    
1394

    
1395
EOD;
1396

    
1397
	if ($captive_portal !== false) {
1398
		$nginx_config .= <<<EOD
1399
$captive_portal_maxprocperip
1400
$cp_hostcheck
1401
$cp_rewrite
1402
		log_not_found off;
1403

    
1404
EOD;
1405

    
1406
	}
1407

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

    
1442
EOD;
1443

    
1444
	$cert = str_replace("\r", "", $cert);
1445
	$key = str_replace("\r", "", $key);
1446

    
1447
	$cert = str_replace("\n\n", "\n", $cert);
1448
	$key = str_replace("\n\n", "\n", $key);
1449

    
1450
	if ($cert <> "" and $key <> "") {
1451
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1452
		if (!$fd) {
1453
			printf(gettext("Error: cannot open certificate file in system_webgui_start().%s"), "\n");
1454
			return 1;
1455
		}
1456
		chmod("{$g['varetc_path']}/{$cert_location}", 0644);
1457
		if ($ca <> "") {
1458
			$cert_chain = $cert . "\n" . $ca;
1459
		} else {
1460
			$cert_chain = $cert;
1461
		}
1462
		fwrite($fd, $cert_chain);
1463
		fclose($fd);
1464
		$fd = fopen("{$g['varetc_path']}/{$key_location}", "w");
1465
		if (!$fd) {
1466
			printf(gettext("Error: cannot open certificate key file in system_webgui_start().%s"), "\n");
1467
			return 1;
1468
		}
1469
		chmod("{$g['varetc_path']}/{$key_location}", 0600);
1470
		fwrite($fd, $key);
1471
		fclose($fd);
1472
	}
1473

    
1474
	// Add HTTP to HTTPS redirect
1475
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1476
		if ($nginx_port != "443") {
1477
			$redirectport = ":{$nginx_port}";
1478
		}
1479
		$nginx_config .= <<<EOD
1480
	server {
1481
		listen 80;
1482
		listen [::]:80;
1483
		return 301 https://\$http_host$redirectport\$request_uri;
1484
	}
1485

    
1486
EOD;
1487
	}
1488

    
1489
	$nginx_config .= "}\n";
1490

    
1491
	$fd = fopen("{$filename}", "w");
1492
	if (!$fd) {
1493
		printf(gettext('Error: cannot open %1$s in system_generate_nginx_config().%2$s'), $filename, "\n");
1494
		return 1;
1495
	}
1496
	fwrite($fd, $nginx_config);
1497
	fclose($fd);
1498

    
1499
	/* nginx will fail to start if this directory does not exist. */
1500
	safe_mkdir("/var/tmp/nginx/");
1501

    
1502
	return 0;
1503

    
1504
}
1505

    
1506
function system_get_timezone_list() {
1507
	global $g;
1508

    
1509
	$file_list = array_merge(
1510
		glob("/usr/share/zoneinfo/[A-Z]*"),
1511
		glob("/usr/share/zoneinfo/*/*"),
1512
		glob("/usr/share/zoneinfo/*/*/*")
1513
	);
1514

    
1515
	if (empty($file_list)) {
1516
		$file_list[] = $g['default_timezone'];
1517
	} else {
1518
		/* Remove directories from list */
1519
		$file_list = array_filter($file_list, function($v) {
1520
			return !is_dir($v);
1521
		});
1522
	}
1523

    
1524
	/* Remove directory prefix */
1525
	$file_list = str_replace('/usr/share/zoneinfo/', '', $file_list);
1526

    
1527
	sort($file_list);
1528

    
1529
	return $file_list;
1530
}
1531

    
1532
function system_timezone_configure() {
1533
	global $config, $g;
1534
	if (isset($config['system']['developerspew'])) {
1535
		$mt = microtime();
1536
		echo "system_timezone_configure() being called $mt\n";
1537
	}
1538

    
1539
	$syscfg = $config['system'];
1540

    
1541
	if (platform_booting()) {
1542
		echo gettext("Setting timezone...");
1543
	}
1544

    
1545
	/* extract appropriate timezone file */
1546
	$timezone = (isset($syscfg['timezone']) ? $syscfg['timezone'] : $g['default_timezone']);
1547
	/* DO NOT remove \n otherwise tzsetup will fail */
1548
	@file_put_contents("/var/db/zoneinfo", $timezone . "\n");
1549
	mwexec("/usr/sbin/tzsetup -r");
1550

    
1551
	if (platform_booting()) {
1552
		echo gettext("done.") . "\n";
1553
	}
1554
}
1555

    
1556
function check_gps_speed($device) {
1557
	usleep(1000);
1558
	// Set timeout to 5s
1559
	$timeout=microtime(true)+5;
1560
	if ($fp = fopen($device, 'r')) {
1561
		stream_set_blocking($fp, 0);
1562
		stream_set_timeout($fp, 5);
1563
		$contents = "";
1564
		$cnt = 0;
1565
		$buffersize = 256;
1566
		do {
1567
			$c = fread($fp, $buffersize - $cnt);
1568

    
1569
			// Wait for data to arive
1570
			if (($c === false) || (strlen($c) == 0)) {
1571
				usleep(500);
1572
				continue;
1573
			}
1574

    
1575
			$contents.=$c;
1576
			$cnt = $cnt + strlen($c);
1577
		} while (($cnt < $buffersize) && (microtime(true) < $timeout));
1578
		fclose($fp);
1579

    
1580
		$nmeasentences = ['RMC', 'GGA', 'GLL', 'ZDA', 'ZDG', 'PGRMF'];
1581
		foreach ($nmeasentences as $sentence) {
1582
			if (strpos($contents, $sentence) > 0) {
1583
				return true;
1584
			}
1585
		}
1586
		if (strpos($contents, '0') > 0) {
1587
			$filters = ['`', '?', '/', '~'];
1588
			foreach ($filters as $filter) {
1589
				if (strpos($contents, $filter) !== false) {
1590
					return false;
1591
				}
1592
			}
1593
			return true;
1594
		}
1595
	}
1596
	return false;
1597
}
1598

    
1599
/* Generate list of possible NTP poll values
1600
 * https://redmine.pfsense.org/issues/9439 */
1601
global $ntp_poll_min_value, $ntp_poll_max_value;
1602
global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
1603
global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
1604
global $ntp_poll_min_default, $ntp_poll_max_default;
1605
global $ntp_auth_halgos;
1606
$ntp_poll_min_value = 4;
1607
$ntp_poll_max_value = 17;
1608
$ntp_poll_min_default_gps = 4;
1609
$ntp_poll_max_default_gps = 4;
1610
$ntp_poll_min_default_pps = 4;
1611
$ntp_poll_max_default_pps = 4;
1612
$ntp_poll_min_default = 'omit';
1613
$ntp_poll_max_default = 9;
1614
$ntp_auth_halgos = array(
1615
	'md5' => 'MD5',
1616
	'sha1' => 'SHA1'
1617
);
1618

    
1619
function system_ntp_poll_values() {
1620
	global $ntp_poll_min_value, $ntp_poll_max_value;
1621
	$poll_values = array("" => gettext('Default'));
1622

    
1623
	for ($i = $ntp_poll_min_value; $i <= $ntp_poll_max_value; $i++) {
1624
		$sec = 2 ** $i;
1625
		$poll_values[$i] = $i . ': ' . number_format($sec) . ' ' . gettext('seconds') .
1626
					' (' . convert_seconds_to_dhms($sec) . ')';
1627
	}
1628

    
1629
	$poll_values['omit'] = gettext('Omit (Do not set)');
1630
	return $poll_values;
1631
}
1632

    
1633
function system_ntp_fixup_poll_value($type, $configvalue, $default) {
1634
	$pollstring = "";
1635

    
1636
	if (empty($configvalue)) {
1637
		$configvalue = $default;
1638
	}
1639

    
1640
	if ($configvalue != 'omit') {
1641
		$pollstring = " {$type} {$configvalue}";
1642
	}
1643

    
1644
	return $pollstring;
1645
}
1646

    
1647
function system_ntp_setup_gps($serialport) {
1648
	global $config, $g;
1649

    
1650
	if (is_array($config['ntpd']) && ($config['ntpd']['enable'] == 'disabled')) {
1651
		return false;
1652
	}
1653

    
1654
	init_config_arr(array('ntpd', 'gps'));
1655

    
1656
	$gps_device = '/dev/gps0';
1657
	$serialport = '/dev/'.$serialport;
1658

    
1659
	if (!file_exists($serialport)) {
1660
		return false;
1661
	}
1662

    
1663
	// Create symlink that ntpd requires
1664
	unlink_if_exists($gps_device);
1665
	@symlink($serialport, $gps_device);
1666

    
1667
	$gpsbaud = '4800';
1668
	$speeds = array(
1669
		0 => '4800', 
1670
		16 => '9600', 
1671
		32 => '19200', 
1672
		48 => '38400', 
1673
		64 => '57600', 
1674
		80 => '115200'
1675
	);
1676
	if (!empty($config['ntpd']['gps']['speed']) && array_key_exists($config['ntpd']['gps']['speed'], $speeds)) {
1677
		$gpsbaud = $speeds[$config['ntpd']['gps']['speed']];
1678
	}
1679

    
1680
	system_ntp_setup_rawspeed($serialport, $gpsbaud);
1681

    
1682
	$autospeed = ($config['ntpd']['gps']['speed'] == 'autoalways' || $config['ntpd']['gps']['speed'] == 'autoset');
1683
	if ($autospeed || ($config['ntpd']['gps']['autobaudinit'] && !check_gps_speed($gps_device))) {
1684
		$found = false;
1685
		foreach ($speeds as $baud) {
1686
			system_ntp_setup_rawspeed($serialport, $baud);
1687
			if ($found = check_gps_speed($gps_device)) {
1688
				if ($autospeed) {
1689
					$saveconfig = ($config['ntpd']['gps']['speed'] == 'autoset');
1690
					$config['ntpd']['gps']['speed'] = array_search($baud, $speeds);
1691
					$gpsbaud = $baud;
1692
					if ($saveconfig) {
1693
						write_config(sprintf(gettext('Autoset GPS baud rate to %s'), $baud));
1694
					}
1695
				}
1696
				break;
1697
			}
1698
		}
1699
		if ($found === false) {
1700
			log_error(gettext("Could not find correct GPS baud rate."));
1701
			return false;
1702
		}
1703
	}
1704

    
1705
	/* Send the following to the GPS port to initialize the GPS */
1706
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
1707
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
1708
	} else {
1709
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1710
	}
1711

    
1712
	/* XXX: Why not file_put_contents to the device */
1713
	@file_put_contents('/tmp/gps.init', $gps_init);
1714
	mwexec("cat /tmp/gps.init > {$serialport}");
1715

    
1716
	if ($found && $config['ntpd']['gps']['autobaudinit']) {
1717
		system_ntp_setup_rawspeed($serialport, $gpsbaud);
1718
	}
1719

    
1720
	/* Remove old /etc/remote entry if it exists */
1721
	if (mwexec("/usr/bin/grep -c '^gps0' /etc/remote") == 0) {
1722
		mwexec("/usr/bin/sed -i '' -n '/gps0/!p' /etc/remote");
1723
	}
1724

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

    
1730
	return true;
1731
}
1732

    
1733
// Configure the serial port for raw IO and set the speed
1734
function system_ntp_setup_rawspeed($serialport, $baud) {
1735
	mwexec("/bin/stty -f " .  escapeshellarg($serialport) . " raw speed " . escapeshellarg($baud));
1736
	mwexec("/bin/stty -f " .  escapeshellarg($serialport) . ".init raw speed " . escapeshellarg($baud));
1737
}
1738

    
1739
function system_ntp_setup_pps($serialport) {
1740
	global $config, $g;
1741

    
1742
	$pps_device = '/dev/pps0';
1743
	$serialport = '/dev/'.$serialport;
1744

    
1745
	if (!file_exists($serialport)) {
1746
		return false;
1747
	}
1748
	// If ntpd is disabled, just return
1749
	if (is_array($config['ntpd']) && ($config['ntpd']['enable'] == 'disabled')) {
1750
		return false;
1751
	}
1752

    
1753
	// Create symlink that ntpd requires
1754
	unlink_if_exists($pps_device);
1755
	@symlink($serialport, $pps_device);
1756

    
1757

    
1758
	return true;
1759
}
1760

    
1761
function system_ntp_configure() {
1762
	global $config, $g;
1763
	global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
1764
	global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
1765
	global $ntp_poll_min_default, $ntp_poll_max_default;
1766

    
1767
	$driftfile = "/var/db/ntpd.drift";
1768
	$statsdir = "/var/log/ntp";
1769
	$gps_device = '/dev/gps0';
1770

    
1771
	safe_mkdir($statsdir);
1772

    
1773
	if (!is_array($config['ntpd'])) {
1774
		$config['ntpd'] = array();
1775
	}
1776
	// ntpd is disabled, just stop it and return
1777
	if ($config['ntpd']['enable'] == 'disabled') {
1778
		while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1779
			killbypid("{$g['varrun_path']}/ntpd.pid");
1780
		}
1781
		@unlink("{$g['varrun_path']}/ntpd.pid");
1782
		@unlink("{$g['varetc_path']}/ntpd.conf");
1783
		@unlink("{$g['varetc_path']}/ntp.keys");
1784
		log_error("NTPD is disabled.");
1785
		return;
1786
	}
1787

    
1788
	if (platform_booting()) {
1789
		echo gettext("Starting NTP Server...");
1790
	}
1791

    
1792
	/* if ntpd is running, kill it */
1793
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1794
		killbypid("{$g['varrun_path']}/ntpd.pid");
1795
	}
1796
	@unlink("{$g['varrun_path']}/ntpd.pid");
1797

    
1798
	/* set NTP server authentication key */
1799
	if ($config['ntpd']['serverauth'] == 'yes') {
1800
		$ntpkeyscfg = "1 " . strtoupper($config['ntpd']['serverauthalgo']) . " " . base64_decode($config['ntpd']['serverauthkey']) . "\n";
1801
		if (!@file_put_contents("{$g['varetc_path']}/ntp.keys", $ntpkeyscfg)) {
1802
			log_error(sprintf(gettext("Could not open %s/ntp.keys for writing"), $g['varetc_path']));
1803
			return;
1804
		}
1805
	} else {
1806
		unlink_if_exists("{$g['varetc_path']}/ntp.keys");
1807
	}
1808

    
1809
	$ntpcfg = "# \n";
1810
	$ntpcfg .= "# pfSense ntp configuration file \n";
1811
	$ntpcfg .= "# \n\n";
1812
	$ntpcfg .= "tinker panic 0 \n\n";
1813

    
1814
	if ($config['ntpd']['serverauth'] == 'yes') {
1815
		$ntpcfg .= "# Authentication settings \n";
1816
		$ntpcfg .= "keys /var/etc/ntp.keys \n";
1817
		$ntpcfg .= "trustedkey 1 \n";
1818
		$ntpcfg .= "requestkey 1 \n";
1819
		$ntpcfg .= "controlkey 1 \n";
1820
		$ntpcfg .= "\n";
1821
	}
1822

    
1823
	/* Add Orphan mode */
1824
	$ntpcfg .= "# Orphan mode stratum and Maximum candidate NTP peers\n";
1825
	$ntpcfg .= 'tos orphan ';
1826
	if (!empty($config['ntpd']['orphan'])) {
1827
		$ntpcfg .= $config['ntpd']['orphan'];
1828
	} else {
1829
		$ntpcfg .= '12';
1830
	}
1831
	/* Add Maximum candidate NTP peers */
1832
	$ntpcfg .= ' maxclock ';
1833
	if (!empty($config['ntpd']['ntpmaxpeers'])) {
1834
		$ntpcfg .= $config['ntpd']['ntpmaxpeers'];
1835
	} else {
1836
		$ntpcfg .= '5';
1837
	}
1838
	$ntpcfg .= "\n";
1839

    
1840
	/* Add PPS configuration */
1841
	if (is_array($config['ntpd']['pps']) && !empty($config['ntpd']['pps']['port']) &&
1842
	    file_exists('/dev/'.$config['ntpd']['pps']['port']) &&
1843
	    system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
1844
		$ntpcfg .= "\n";
1845
		$ntpcfg .= "# PPS Setup\n";
1846
		$ntpcfg .= 'server 127.127.22.0';
1847
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', $config['ntpd']['pps']['ppsminpoll'], $ntp_poll_min_default_pps);
1848
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', $config['ntpd']['pps']['ppsmaxpoll'], $ntp_poll_max_default_pps);
1849
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
1850
			$ntpcfg .= ' prefer';
1851
		}
1852
		if (!empty($config['ntpd']['pps']['noselect'])) {
1853
			$ntpcfg .= ' noselect ';
1854
		}
1855
		$ntpcfg .= "\n";
1856
		$ntpcfg .= 'fudge 127.127.22.0';
1857
		if (!empty($config['ntpd']['pps']['fudge1'])) {
1858
			$ntpcfg .= ' time1 ';
1859
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
1860
		}
1861
		if (!empty($config['ntpd']['pps']['flag2'])) {
1862
			$ntpcfg .= ' flag2 1';
1863
		}
1864
		if (!empty($config['ntpd']['pps']['flag3'])) {
1865
			$ntpcfg .= ' flag3 1';
1866
		} else {
1867
			$ntpcfg .= ' flag3 0';
1868
		}
1869
		if (!empty($config['ntpd']['pps']['flag4'])) {
1870
			$ntpcfg .= ' flag4 1';
1871
		}
1872
		if (!empty($config['ntpd']['pps']['refid'])) {
1873
			$ntpcfg .= ' refid ';
1874
			$ntpcfg .= $config['ntpd']['pps']['refid'];
1875
		}
1876
		$ntpcfg .= "\n";
1877
	}
1878
	/* End PPS configuration */
1879

    
1880
	/* Add GPS configuration */
1881
	if (is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['port']) &&
1882
	    system_ntp_setup_gps($config['ntpd']['gps']['port'])) {
1883
		$ntpcfg .= "\n";
1884
		$ntpcfg .= "# GPS Setup\n";
1885
		$ntpcfg .= 'server 127.127.20.0 mode ';
1886
		if (!empty($config['ntpd']['gps']['nmea']) || !empty($config['ntpd']['gps']['speed']) || !empty($config['ntpd']['gps']['subsec']) || !empty($config['ntpd']['gps']['processpgrmf'])) {
1887
			if (!empty($config['ntpd']['gps']['nmea'])) {
1888
				$ntpmode = (int) $config['ntpd']['gps']['nmea'];
1889
			}
1890
			if (!empty($config['ntpd']['gps']['speed'])) {
1891
				$ntpmode += (int) $config['ntpd']['gps']['speed'];
1892
			}
1893
			if (!empty($config['ntpd']['gps']['subsec'])) {
1894
				$ntpmode += 128;
1895
			}
1896
			if (!empty($config['ntpd']['gps']['processpgrmf'])) {
1897
				$ntpmode += 256;
1898
			}
1899
			$ntpcfg .= (string) $ntpmode;
1900
		} else {
1901
			$ntpcfg .= '0';
1902
		}
1903
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', $config['ntpd']['gps']['gpsminpoll'], $ntp_poll_min_default_gps);
1904
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', $config['ntpd']['gps']['gpsmaxpoll'], $ntp_poll_max_default_gps);
1905

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

    
1976
		$ntpcfg .= "{$ts} iburst";
1977

    
1978
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', $config['ntpd']['ntpminpoll'], $ntp_poll_min_default);
1979
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', $config['ntpd']['ntpmaxpoll'], $ntp_poll_max_default);
1980

    
1981
		if (substr_count($config['ntpd']['prefer'], $ts)) {
1982
			$ntpcfg .= ' prefer';
1983
		}
1984
		if (substr_count($config['ntpd']['noselect'], $ts)) {
1985
			$ntpcfg .= ' noselect';
1986
		}
1987
		$ntpcfg .= "\n";
1988
	}
1989
	unset($ts);
1990

    
1991
	$ntpcfg .= "\n\n";
1992
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
1993
		$ntpcfg .= "enable stats\n";
1994
		$ntpcfg .= 'statistics';
1995
		if (!empty($config['ntpd']['clockstats'])) {
1996
			$ntpcfg .= ' clockstats';
1997
		}
1998
		if (!empty($config['ntpd']['loopstats'])) {
1999
			$ntpcfg .= ' loopstats';
2000
		}
2001
		if (!empty($config['ntpd']['peerstats'])) {
2002
			$ntpcfg .= ' peerstats';
2003
		}
2004
		$ntpcfg .= "\n";
2005
	}
2006
	$ntpcfg .= "statsdir {$statsdir}\n";
2007
	$ntpcfg .= 'logconfig =syncall +clockall';
2008
	if (!empty($config['ntpd']['logpeer'])) {
2009
		$ntpcfg .= ' +peerall';
2010
	}
2011
	if (!empty($config['ntpd']['logsys'])) {
2012
		$ntpcfg .= ' +sysall';
2013
	}
2014
	$ntpcfg .= "\n";
2015
	$ntpcfg .= "driftfile {$driftfile}\n";
2016

    
2017
	/* Default Access restrictions */
2018
	$ntpcfg .= 'restrict default';
2019
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
2020
		$ntpcfg .= ' kod limited';
2021
	}
2022
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
2023
		$ntpcfg .= ' nomodify';
2024
	}
2025
	if (!empty($config['ntpd']['noquery'])) {
2026
		$ntpcfg .= ' noquery';
2027
	}
2028
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
2029
		$ntpcfg .= ' nopeer';
2030
	}
2031
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
2032
		$ntpcfg .= ' notrap';
2033
	}
2034
	if (!empty($config['ntpd']['noserve'])) {
2035
		$ntpcfg .= ' noserve';
2036
	}
2037
	$ntpcfg .= "\nrestrict -6 default";
2038
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
2039
		$ntpcfg .= ' kod limited';
2040
	}
2041
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
2042
		$ntpcfg .= ' nomodify';
2043
	}
2044
	if (!empty($config['ntpd']['noquery'])) {
2045
		$ntpcfg .= ' noquery';
2046
	}
2047
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
2048
		$ntpcfg .= ' nopeer';
2049
	}
2050
	if (!empty($config['ntpd']['noserve'])) {
2051
		$ntpcfg .= ' noserve';
2052
	}
2053
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
2054
		$ntpcfg .= ' notrap';
2055
	}
2056

    
2057
	/* Pools require "restrict source" and cannot contain "nopeer" and "noserve". */
2058
	if ($have_pools) {
2059
		$ntpcfg .= "\nrestrict source";
2060
		if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
2061
			$ntpcfg .= ' kod limited';
2062
		}
2063
		if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
2064
			$ntpcfg .= ' nomodify';
2065
		}
2066
		if (!empty($config['ntpd']['noquery'])) {
2067
			$ntpcfg .= ' noquery';
2068
		}
2069
		if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
2070
			$ntpcfg .= ' notrap';
2071
		}
2072
	}
2073

    
2074
	/* Custom Access Restrictions */
2075
	if (is_array($config['ntpd']['restrictions']) && is_array($config['ntpd']['restrictions']['row'])) {
2076
		$networkacl = $config['ntpd']['restrictions']['row'];
2077
		foreach ($networkacl as $acl) {
2078
			$restrict = "";
2079
			if (is_ipaddrv6($acl['acl_network'])) {
2080
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask_v6($acl['mask']) . " ";
2081
			} elseif (is_ipaddrv4($acl['acl_network'])) {
2082
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask($acl['mask']) . " ";
2083
			} else {
2084
				continue;
2085
			}
2086
			if (!empty($acl['kod'])) {
2087
				$restrict .= ' kod limited';
2088
			}
2089
			if (!empty($acl['nomodify'])) {
2090
				$restrict .= ' nomodify';
2091
			}
2092
			if (!empty($acl['noquery'])) {
2093
				$restrict .= ' noquery';
2094
			}
2095
			if (!empty($acl['nopeer'])) {
2096
				$restrict .= ' nopeer';
2097
			}
2098
			if (!empty($acl['noserve'])) {
2099
				$restrict .= ' noserve';
2100
			}
2101
			if (!empty($acl['notrap'])) {
2102
				$restrict .= ' notrap';
2103
			}
2104
			if (!empty($restrict)) {
2105
				$ntpcfg .= "\nrestrict {$restrict} ";
2106
			}
2107
		}
2108
	}
2109
	/* End Custom Access Restrictions */
2110

    
2111
	/* A leapseconds file is really only useful if this clock is stratum 1 */
2112
	$ntpcfg .= "\n";
2113
	if (!empty($config['ntpd']['leapsec'])) {
2114
		$leapsec .= base64_decode($config['ntpd']['leapsec']);
2115
		file_put_contents('/var/db/leap-seconds', $leapsec);
2116
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
2117
	}
2118

    
2119

    
2120
	if (empty($config['ntpd']['interface'])) {
2121
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface'])) {
2122
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
2123
		} else {
2124
			$interfaces = array();
2125
		}
2126
	} else {
2127
		$interfaces = explode(",", $config['ntpd']['interface']);
2128
	}
2129

    
2130
	if (is_array($interfaces) && count($interfaces)) {
2131
		$finterfaces = array();
2132
		$ntpcfg .= "interface ignore all\n";
2133
		$ntpcfg .= "interface ignore wildcard\n";
2134
		foreach ($interfaces as $interface) {
2135
			$interface = get_real_interface($interface);
2136
			if (!empty($interface)) {
2137
				$finterfaces[] = $interface;
2138
			}
2139
		}
2140
		foreach ($finterfaces as $interface) {
2141
			$ntpcfg .= "interface listen {$interface}\n";
2142
		}
2143
	}
2144

    
2145
	/* open configuration for writing or bail */
2146
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
2147
		log_error(sprintf(gettext("Could not open %s/ntpd.conf for writing"), $g['varetc_path']));
2148
		return;
2149
	}
2150

    
2151
	/* if /var/empty does not exist, create it */
2152
	if (!is_dir("/var/empty")) {
2153
		mkdir("/var/empty", 0555, true);
2154
	}
2155

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

    
2159
	// Note that we are starting up
2160
	log_error("NTPD is starting up.");
2161

    
2162
	if (platform_booting()) {
2163
		echo gettext("done.") . "\n";
2164
	}
2165

    
2166
	return;
2167
}
2168

    
2169
function system_halt() {
2170
	global $g;
2171

    
2172
	system_reboot_cleanup();
2173

    
2174
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
2175
}
2176

    
2177
function system_reboot() {
2178
	global $g;
2179

    
2180
	system_reboot_cleanup();
2181

    
2182
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
2183
}
2184

    
2185
function system_reboot_sync($reroot=false) {
2186
	global $g;
2187

    
2188
	if ($reroot) {
2189
		$args = " -r ";
2190
	}
2191

    
2192
	system_reboot_cleanup();
2193

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

    
2197
function system_reboot_cleanup() {
2198
	global $config, $g, $cpzone;
2199

    
2200
	mwexec("/usr/local/bin/beep.sh stop");
2201
	require_once("captiveportal.inc");
2202
	if (is_array($config['captiveportal'])) {
2203
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
2204
			if (!isset($cp['preservedb'])) {
2205
				/* send Accounting-Stop packet for all clients, termination cause 'Admin-Reboot' */
2206
				captiveportal_radius_stop_all(7); // Admin-Reboot
2207
				unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
2208
				captiveportal_free_dnrules();
2209
			}
2210
			/* Send Accounting-Off packet to the RADIUS server */
2211
			captiveportal_send_server_accounting('off');
2212
		}
2213
		/* Remove the pipe database */
2214
		unlink_if_exists("{$g['vardb_path']}/captiveportaldn.rules");
2215
	}
2216
	require_once("voucher.inc");
2217
	voucher_save_db_to_config();
2218
	require_once("pkg-utils.inc");
2219
	stop_packages();
2220
}
2221

    
2222
function system_do_shell_commands($early = 0) {
2223
	global $config, $g;
2224
	if (isset($config['system']['developerspew'])) {
2225
		$mt = microtime();
2226
		echo "system_do_shell_commands() being called $mt\n";
2227
	}
2228

    
2229
	if ($early) {
2230
		$cmdn = "earlyshellcmd";
2231
	} else {
2232
		$cmdn = "shellcmd";
2233
	}
2234

    
2235
	if (is_array($config['system'][$cmdn])) {
2236

    
2237
		/* *cmd is an array, loop through */
2238
		foreach ($config['system'][$cmdn] as $cmd) {
2239
			exec($cmd);
2240
		}
2241

    
2242
	} elseif ($config['system'][$cmdn] <> "") {
2243

    
2244
		/* execute single item */
2245
		exec($config['system'][$cmdn]);
2246

    
2247
	}
2248
}
2249

    
2250
function system_dmesg_save() {
2251
	global $g;
2252
	if (isset($config['system']['developerspew'])) {
2253
		$mt = microtime();
2254
		echo "system_dmesg_save() being called $mt\n";
2255
	}
2256

    
2257
	$dmesg = "";
2258
	$_gb = exec("/sbin/dmesg", $dmesg);
2259

    
2260
	/* find last copyright line (output from previous boots may be present) */
2261
	$lastcpline = 0;
2262

    
2263
	for ($i = 0; $i < count($dmesg); $i++) {
2264
		if (strstr($dmesg[$i], "Copyright (c) 1992-")) {
2265
			$lastcpline = $i;
2266
		}
2267
	}
2268

    
2269
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
2270
	if (!$fd) {
2271
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
2272
		return 1;
2273
	}
2274

    
2275
	for ($i = $lastcpline; $i < count($dmesg); $i++) {
2276
		fwrite($fd, $dmesg[$i] . "\n");
2277
	}
2278

    
2279
	fclose($fd);
2280
	unset($dmesg);
2281

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

    
2285
	return 0;
2286
}
2287

    
2288
function system_set_harddisk_standby() {
2289
	global $g, $config;
2290

    
2291
	if (isset($config['system']['developerspew'])) {
2292
		$mt = microtime();
2293
		echo "system_set_harddisk_standby() being called $mt\n";
2294
	}
2295

    
2296
	if (isset($config['system']['harddiskstandby'])) {
2297
		if (platform_booting()) {
2298
			echo gettext('Setting hard disk standby... ');
2299
		}
2300

    
2301
		$standby = $config['system']['harddiskstandby'];
2302
		// Check for a numeric value
2303
		if (is_numeric($standby)) {
2304
			// Get only suitable candidates for standby; using get_smart_drive_list()
2305
			// from utils.inc to get the list of drives.
2306
			$harddisks = get_smart_drive_list();
2307

    
2308
			// Since get_smart_drive_list() only matches ad|da|ada; lets put the check below
2309
			// just in case of some weird pfSense platform installs.
2310
			if (count($harddisks) > 0) {
2311
				// Iterate disks and run the camcontrol command for each
2312
				foreach ($harddisks as $harddisk) {
2313
					mwexec("/sbin/camcontrol standby {$harddisk} -t {$standby}");
2314
				}
2315
				if (platform_booting()) {
2316
					echo gettext("done.") . "\n";
2317
				}
2318
			} else if (platform_booting()) {
2319
				echo gettext("failed!") . "\n";
2320
			}
2321
		} else if (platform_booting()) {
2322
			echo gettext("failed!") . "\n";
2323
		}
2324
	}
2325
}
2326

    
2327
function system_setup_sysctl() {
2328
	global $config;
2329
	if (isset($config['system']['developerspew'])) {
2330
		$mt = microtime();
2331
		echo "system_setup_sysctl() being called $mt\n";
2332
	}
2333

    
2334
	activate_sysctls();
2335

    
2336
	if (isset($config['system']['sharednet'])) {
2337
		system_disable_arp_wrong_if();
2338
	}
2339
}
2340

    
2341
function system_disable_arp_wrong_if() {
2342
	global $config;
2343
	if (isset($config['system']['developerspew'])) {
2344
		$mt = microtime();
2345
		echo "system_disable_arp_wrong_if() being called $mt\n";
2346
	}
2347
	set_sysctl(array(
2348
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
2349
		"net.link.ether.inet.log_arp_movements" => "0"
2350
	));
2351
}
2352

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

    
2365
function enable_watchdog() {
2366
	global $config;
2367
	return;
2368
	$install_watchdog = false;
2369
	$supported_watchdogs = array("Geode");
2370
	$file = file_get_contents("/var/log/dmesg.boot");
2371
	foreach ($supported_watchdogs as $sd) {
2372
		if (stristr($file, "Geode")) {
2373
			$install_watchdog = true;
2374
		}
2375
	}
2376
	if ($install_watchdog == true) {
2377
		if (is_process_running("watchdogd")) {
2378
			mwexec("/usr/bin/killall watchdogd", true);
2379
		}
2380
		exec("/usr/sbin/watchdogd");
2381
	}
2382
}
2383

    
2384
function system_check_reset_button() {
2385
	global $g;
2386

    
2387
	$specplatform = system_identify_specific_platform();
2388

    
2389
	switch ($specplatform['name']) {
2390
		case 'SG-2220':
2391
			$binprefix = "RCC-DFF";
2392
			break;
2393
		case 'alix':
2394
		case 'wrap':
2395
		case 'FW7541':
2396
		case 'APU':
2397
		case 'RCC-VE':
2398
		case 'RCC':
2399
			$binprefix = $specplatform['name'];
2400
			break;
2401
		default:
2402
			return 0;
2403
	}
2404

    
2405
	$retval = mwexec("/usr/local/sbin/" . $binprefix . "resetbtn");
2406

    
2407
	if ($retval == 99) {
2408
		/* user has pressed reset button for 2 seconds -
2409
		   reset to factory defaults */
2410
		echo <<<EOD
2411

    
2412
***********************************************************************
2413
* Reset button pressed - resetting configuration to factory defaults. *
2414
* All additional packages installed will be removed                   *
2415
* The system will reboot after this completes.                        *
2416
***********************************************************************
2417

    
2418

    
2419
EOD;
2420

    
2421
		reset_factory_defaults();
2422
		system_reboot_sync();
2423
		exit(0);
2424
	}
2425

    
2426
	return 0;
2427
}
2428

    
2429
function system_get_serial() {
2430
	$platform = system_identify_specific_platform();
2431

    
2432
	unset($output);
2433
	if ($platform['name'] == 'Turbot Dual-E') {
2434
		$if_info = pfSense_get_interface_addresses('igb0');
2435
		if (!empty($if_info['hwaddr'])) {
2436
			$serial = str_replace(":", "", $if_info['hwaddr']);
2437
		}
2438
	} else {
2439
		foreach (array('system', 'planar', 'chassis') as $key) {
2440
			unset($output);
2441
			$_gb = exec("/bin/kenv -q smbios.{$key}.serial",
2442
			    $output);
2443
			if (!empty($output[0]) && $output[0] != "0123456789" &&
2444
			    preg_match('/^[\w\d]{10,16}$/', $output[0]) === 1) {
2445
				$serial = $output[0];
2446
				break;
2447
			}
2448
		}
2449
	}
2450

    
2451
	$vm_guest = get_single_sysctl('kern.vm_guest');
2452

    
2453
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2454
	    $vm_guest == 'none') {
2455
		return $serial;
2456
	}
2457

    
2458
	return "";
2459
}
2460

    
2461
function system_get_uniqueid() {
2462
	global $g;
2463

    
2464
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2465

    
2466
	if (empty($g['uniqueid'])) {
2467
		if (!file_exists($uniqueid_file)) {
2468
			mwexec("/usr/sbin/gnid > {$g['vardb_path']}/uniqueid " .
2469
			    "2>/dev/null");
2470
		}
2471
		if (file_exists($uniqueid_file)) {
2472
			$g['uniqueid'] = @file_get_contents($uniqueid_file);
2473
		}
2474
	}
2475

    
2476
	return ($g['uniqueid'] ?: '');
2477
}
2478

    
2479
/*
2480
 * attempt to identify the specific platform (for embedded systems)
2481
 * Returns an array with two elements:
2482
 * name => platform string (e.g. 'wrap', 'alix' etc.)
2483
 * descr => human-readable description (e.g. "PC Engines WRAP")
2484
 */
2485
function system_identify_specific_platform() {
2486
	global $g;
2487

    
2488
	$hw_model = get_single_sysctl('hw.model');
2489
	$hw_ncpu = get_single_sysctl('hw.ncpu');
2490

    
2491
	/* Try to guess from smbios strings */
2492
	unset($product);
2493
	unset($maker);
2494
	unset($bios);
2495
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $product);
2496
	$_gb = exec('/bin/kenv -q smbios.system.maker 2>/dev/null', $maker);
2497
	$_gb = exec('/bin/kenv -q smbios.bios.version 2>/dev/null', $bios);
2498

    
2499
	// AWS can only be identified via the bios version
2500
	if (stripos($bios[0], "amazon") !== false) {
2501
		return (array('name' => 'AWS', 'descr' => 'Amazon Web Services'));
2502
	} else  if (stripos($bios[0], "Google") !== false) {
2503
		return (array('name' => 'Google', 'descr' => 'Google Cloud Platform'));
2504
	}
2505

    
2506
	switch ($product[0]) {
2507
		case 'FW7541':
2508
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2509
			break;
2510
		case 'APU':
2511
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2512
			break;
2513
		case 'RCC-VE':
2514
			$result = array();
2515
			$result['name'] = 'RCC-VE';
2516

    
2517
			/* Detect specific models */
2518
			if (!function_exists('does_interface_exist')) {
2519
				require_once("interfaces.inc");
2520
			}
2521
			if (!does_interface_exist('igb4')) {
2522
				$result['model'] = 'SG-2440';
2523
			} elseif (strpos($hw_model, "C2558") !== false) {
2524
				$result['model'] = 'SG-4860';
2525
			} elseif (strpos($hw_model, "C2758") !== false) {
2526
				$result['model'] = 'SG-8860';
2527
			} else {
2528
				$result['model'] = 'RCC-VE';
2529
			}
2530
			$result['descr'] = 'Netgate ' . $result['model'];
2531
			return $result;
2532
			break;
2533
		case 'DFFv2':
2534
			return (array('name' => 'SG-2220', 'descr' => 'Netgate SG-2220'));
2535
			break;
2536
		case 'RCC':
2537
			return (array('name' => 'RCC', 'descr' => 'Netgate XG-2758'));
2538
			break;
2539
		case 'SG-5100':
2540
			return (array('name' => 'SG-5100', 'descr' => 'Netgate SG-5100'));
2541
			break;
2542
		case 'Minnowboard Turbot D0 PLATFORM':
2543
		case 'Minnowboard Turbot D0/D1 PLATFORM':
2544
			$result = array();
2545
			$result['name'] = 'Turbot Dual-E';
2546
			/* Detect specific model */
2547
			switch ($hw_ncpu) {
2548
			case '4':
2549
				$result['model'] = 'MBT-4220';
2550
				break;
2551
			case '2':
2552
				$result['model'] = 'MBT-2220';
2553
				break;
2554
			default:
2555
				$result['model'] = $result['name'];
2556
				break;
2557
			}
2558
			$result['descr'] = 'Netgate ' . $result['model'];
2559
			return $result;
2560
			break;
2561
		case 'SYS-5018A-FTN4':
2562
		case 'A1SAi':
2563
			if (strpos($hw_model, "C2558") !== false) {
2564
				return (array(
2565
				    'name' => 'C2558',
2566
				    'descr' => 'Super Micro C2558'));
2567
			} elseif (strpos($hw_model, "C2758") !== false) {
2568
				return (array(
2569
				    'name' => 'C2758',
2570
				    'descr' => 'Super Micro C2758'));
2571
			}
2572
			break;
2573
		case 'SYS-5018D-FN4T':
2574
			if (strpos($hw_model, "D-1541") !== false) {
2575
				return (array('name' => 'XG-1541', 'descr' => 'Super Micro XG-1541'));
2576
			} else {
2577
				return (array('name' => 'XG-1540', 'descr' => 'Super Micro XG-1540'));
2578
			}
2579
			break;
2580
		case 'apu2':
2581
		case 'APU2':
2582
			return (array('name' => 'apu2', 'descr' => 'PC Engines APU2'));
2583
			break;
2584
		case 'VirtualBox':
2585
			return (array('name' => 'VirtualBox', 'descr' => 'VirtualBox Virtual Machine'));
2586
			break;
2587
		case 'Virtual Machine':
2588
			if ($maker[0] == "Microsoft Corporation") {
2589
				if (stripos($bios[0], "Hyper") !== false) {
2590
					return (array('name' => 'Hyper-V', 'descr' => 'Hyper-V Virtual Machine'));
2591
				} else {
2592
					return (array('name' => 'Azure', 'descr' => 'Microsoft Azure'));
2593
				}
2594
			}
2595
			break;
2596
		case 'VMware Virtual Platform':
2597
			if ($maker[0] == "VMware, Inc.") {
2598
				return (array('name' => 'VMware', 'descr' => 'VMware Virtual Machine'));
2599
			}
2600
			break;
2601
	}
2602

    
2603
	$_gb = exec('/bin/kenv -q smbios.planar.product 2>/dev/null',
2604
	    $planar_product);
2605
	if (isset($planar_product[0]) &&
2606
	    $planar_product[0] == 'X10SDV-8C-TLN4F+') {
2607
		return array('name' => 'XG-1537', 'descr' => 'Super Micro XG-1537');
2608
	}
2609

    
2610
	if (strpos($hw_model, "PC Engines WRAP") !== false) {
2611
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
2612
	}
2613

    
2614
	if (strpos($hw_model, "PC Engines ALIX") !== false) {
2615
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2616
	}
2617

    
2618
	if (preg_match("/Soekris net45../", $hw_model, $matches)) {
2619
		return array('name' => 'net45xx', 'descr' => $matches[0]);
2620
	}
2621

    
2622
	if (preg_match("/Soekris net48../", $hw_model, $matches)) {
2623
		return array('name' => 'net48xx', 'descr' => $matches[0]);
2624
	}
2625

    
2626
	if (preg_match("/Soekris net55../", $hw_model, $matches)) {
2627
		return array('name' => 'net55xx', 'descr' => $matches[0]);
2628
	}
2629

    
2630
	unset($hw_model);
2631

    
2632
	$dmesg_boot = system_get_dmesg_boot();
2633
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
2634
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2635
	}
2636
	unset($dmesg_boot);
2637

    
2638
	return array('name' => $g['product_name'], 'descr' => $g['product_label']);
2639
}
2640

    
2641
function system_get_dmesg_boot() {
2642
	global $g;
2643

    
2644
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2645
}
2646

    
2647
function system_get_arp_table($resolve_hostnames = false) {
2648
	$params="-a";
2649
	if (!$resolve_hostnames) {
2650
		$params .= "n";
2651
	}
2652

    
2653
	$arp_table = array();
2654
	$_gb = exec("/usr/sbin/arp --libxo json {$params}", $rawdata, $rc);
2655
	if ($rc == 0) {
2656
		$arp_table = json_decode(implode(" ", $rawdata),
2657
		    JSON_OBJECT_AS_ARRAY);
2658
		if ($rc == 0) {
2659
			$arp_table = $arp_table['arp']['arp-cache'];
2660
		}
2661
	}
2662

    
2663
	return $arp_table;
2664
}
2665

    
2666
?>
(49-49/61)
OSZAR »