Project

General

Profile

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

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

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

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

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

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

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

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

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

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

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

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

    
1049
	return 0;
1050
}
1051

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

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

    
1064
	return;
1065
}
1066

    
1067
function system_webgui_create_certificate() {
1068
	global $config, $g, $cert_strict_values;
1069

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

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

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

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

    
1101
function system_webgui_start() {
1102
	global $config, $g;
1103

    
1104
	if (platform_booting()) {
1105
		echo gettext("Starting webConfigurator...");
1106
	}
1107

    
1108
	chdir($g['www_path']);
1109

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

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

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

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

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

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

    
1145
	sleep(1);
1146

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

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

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

    
1160
	return $res;
1161
}
1162

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

    
1181
	$dns_nameservers = array();
1182

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

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

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

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

    
1240
	global $config, $g;
1241

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

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

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

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

    
1281
	$memory = get_memory();
1282
	$realmem = $memory[1];
1283

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

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

    
1302
	$nginx_config = <<<EOD
1303
#
1304
# nginx configuration file
1305

    
1306
pid {$g['varrun_path']}/{$pid_file};
1307

    
1308
user  root wheel;
1309
worker_processes  {$max_procs};
1310

    
1311
EOD;
1312

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

    
1320
	$nginx_config .= <<<EOD
1321

    
1322
events {
1323
    worker_connections  1024;
1324
}
1325

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

    
1332
	sendfile        on;
1333

    
1334
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1335

    
1336
EOD;
1337

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

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

    
1385
	$nginx_config .= <<<EOD
1386

    
1387
		client_max_body_size 200m;
1388

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

    
1392

    
1393
EOD;
1394

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

    
1402
EOD;
1403

    
1404
	}
1405

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

    
1440
EOD;
1441

    
1442
	$cert = str_replace("\r", "", $cert);
1443
	$key = str_replace("\r", "", $key);
1444

    
1445
	$cert = str_replace("\n\n", "\n", $cert);
1446
	$key = str_replace("\n\n", "\n", $key);
1447

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

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

    
1484
EOD;
1485
	}
1486

    
1487
	$nginx_config .= "}\n";
1488

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

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

    
1500
	return 0;
1501

    
1502
}
1503

    
1504
function system_get_timezone_list() {
1505
	global $g;
1506

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

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

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

    
1525
	sort($file_list);
1526

    
1527
	return $file_list;
1528
}
1529

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

    
1537
	$syscfg = $config['system'];
1538

    
1539
	if (platform_booting()) {
1540
		echo gettext("Setting timezone...");
1541
	}
1542

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

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

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

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

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

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

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

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

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

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

    
1631
function system_ntp_fixup_poll_value($type, $configvalue, $default) {
1632
	$pollstring = "";
1633

    
1634
	if (empty($configvalue)) {
1635
		$configvalue = $default;
1636
	}
1637

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

    
1642
	return $pollstring;
1643
}
1644

    
1645
function system_ntp_setup_gps($serialport) {
1646
	global $config, $g;
1647

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

    
1652
	init_config_arr(array('ntpd', 'gps'));
1653

    
1654
	$gps_device = '/dev/gps0';
1655
	$serialport = '/dev/'.$serialport;
1656

    
1657
	if (!file_exists($serialport)) {
1658
		return false;
1659
	}
1660

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

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

    
1678
	system_ntp_setup_rawspeed($serialport, $gpsbaud);
1679

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

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

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

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

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

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

    
1728
	return true;
1729
}
1730

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

    
1737
function system_ntp_setup_pps($serialport) {
1738
	global $config, $g;
1739

    
1740
	$pps_device = '/dev/pps0';
1741
	$serialport = '/dev/'.$serialport;
1742

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

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

    
1755

    
1756
	return true;
1757
}
1758

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

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

    
1769
	safe_mkdir($statsdir);
1770

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

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

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

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

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

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

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

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

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

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

    
1974
		$ntpcfg .= "{$ts} iburst";
1975

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

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

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

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

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

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

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

    
2117

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

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

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

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

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

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

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

    
2164
	return;
2165
}
2166

    
2167
function system_halt() {
2168
	global $g;
2169

    
2170
	system_reboot_cleanup();
2171

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

    
2175
function system_reboot() {
2176
	global $g;
2177

    
2178
	system_reboot_cleanup();
2179

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

    
2183
function system_reboot_sync($reroot=false) {
2184
	global $g;
2185

    
2186
	if ($reroot) {
2187
		$args = " -r ";
2188
	}
2189

    
2190
	system_reboot_cleanup();
2191

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

    
2195
function system_reboot_cleanup() {
2196
	global $config, $g, $cpzone;
2197

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

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

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

    
2233
	if (is_array($config['system'][$cmdn])) {
2234

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

    
2240
	} elseif ($config['system'][$cmdn] <> "") {
2241

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

    
2245
	}
2246
}
2247

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

    
2255
	$dmesg = "";
2256
	$_gb = exec("/sbin/dmesg", $dmesg);
2257

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

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

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

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

    
2277
	fclose($fd);
2278
	unset($dmesg);
2279

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

    
2283
	return 0;
2284
}
2285

    
2286
function system_set_harddisk_standby() {
2287
	global $g, $config;
2288

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

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

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

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

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

    
2332
	activate_sysctls();
2333

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

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

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

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

    
2382
function system_check_reset_button() {
2383
	global $g;
2384

    
2385
	$specplatform = system_identify_specific_platform();
2386

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

    
2403
	$retval = mwexec("/usr/local/sbin/" . $binprefix . "resetbtn");
2404

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

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

    
2416

    
2417
EOD;
2418

    
2419
		reset_factory_defaults();
2420
		system_reboot_sync();
2421
		exit(0);
2422
	}
2423

    
2424
	return 0;
2425
}
2426

    
2427
function system_get_serial() {
2428
	$platform = system_identify_specific_platform();
2429

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

    
2449
	$vm_guest = get_single_sysctl('kern.vm_guest');
2450

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

    
2456
	return "";
2457
}
2458

    
2459
function system_get_uniqueid() {
2460
	global $g;
2461

    
2462
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2463

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

    
2474
	return ($g['uniqueid'] ?: '');
2475
}
2476

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

    
2486
	$hw_model = get_single_sysctl('hw.model');
2487
	$hw_ncpu = get_single_sysctl('hw.ncpu');
2488

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

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

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

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

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

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

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

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

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

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

    
2628
	unset($hw_model);
2629

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

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

    
2639
function system_get_dmesg_boot() {
2640
	global $g;
2641

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

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

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

    
2661
	return $arp_table;
2662
}
2663

    
2664
?>
(49-49/61)