Project

General

Profile

Download (70.3 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * system.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2004-2013 BSD Perimeter
7
 * Copyright (c) 2013-2016 Electric Sheep Fencing
8
 * Copyright (c) 2014-2020 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;
106

    
107
	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
108
		foreach ($config['sysctl']['item'] as $tunable) {
109
			if ($tunable['value'] == "default") {
110
				$value = get_default_sysctl_value($tunable['tunable']);
111
			} else {
112
				$value = $tunable['value'];
113
			}
114

    
115
			$sysctls[$tunable['tunable']] = $value;
116
		}
117
	}
118

    
119
	set_sysctl($sysctls);
120
}
121

    
122
function system_resolvconf_generate($dynupdate = false) {
123
	global $config, $g;
124

    
125
	if (isset($config['system']['developerspew'])) {
126
		$mt = microtime();
127
		echo "system_resolvconf_generate() being called $mt\n";
128
	}
129

    
130
	$syscfg = $config['system'];
131

    
132
	foreach(get_dns_nameservers() as $dns_ns) {
133
		$resolvconf .= "nameserver $dns_ns\n";
134
	}
135

    
136
	$ns = array();
137
	if (isset($syscfg['dnsallowoverride'])) {
138
		/* get dynamically assigned DNS servers (if any) */
139
		$ns = array_unique(get_searchdomains());
140
		foreach ($ns as $searchserver) {
141
			if ($searchserver) {
142
				$resolvconf .= "search {$searchserver}\n";
143
			}
144
		}
145
	}
146
	if (empty($ns)) {
147
		// Do not create blank search/domain lines, it can break tools like dig.
148
		if ($syscfg['domain']) {
149
			$resolvconf .= "search {$syscfg['domain']}\n";
150
		}
151
	}
152

    
153
	// Add EDNS support
154
	if (isset($config['unbound']['enable']) && isset($config['unbound']['edns'])) {
155
		$resolvconf .= "options edns0\n";
156
	}
157

    
158
	$dnslock = lock('resolvconf', LOCK_EX);
159

    
160
	$fd = fopen("{$g['etc_path']}/resolv.conf", "w");
161
	if (!$fd) {
162
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
163
		unlock($dnslock);
164
		return 1;
165
	}
166

    
167
	fwrite($fd, $resolvconf);
168
	fclose($fd);
169

    
170
	// Prevent resolvconf(8) from rewriting our resolv.conf
171
	$fd = fopen("{$g['etc_path']}/resolvconf.conf", "w");
172
	if (!$fd) {
173
		printf("Error: cannot open resolvconf.conf in system_resolvconf_generate().\n");
174
		return 1;
175
	}
176
	fwrite($fd, "resolv_conf=\"/dev/null\"\n");
177
	fclose($fd);
178

    
179
	if (!platform_booting()) {
180
		/* restart dhcpd (nameservers may have changed) */
181
		if (!$dynupdate) {
182
			services_dhcpd_configure();
183
		}
184
	}
185

    
186
	// set up or tear down static routes for DNS servers
187
	$dnscounter = 1;
188
	$dnsgw = "dns{$dnscounter}gw";
189
	while (isset($config['system'][$dnsgw])) {
190
		/* setup static routes for dns servers */
191
		$gwname = $config['system'][$dnsgw];
192
		unset($gatewayip);
193
		unset($inet6);
194
		if ((!empty($gwname)) && ($gwname != "none")) {
195
			$gatewayip = lookup_gateway_ip_by_name($gwname);
196
			$inet6 = is_ipaddrv6($gatewayip) ? '-inet6 ' : '';
197
		}
198
		/* dns server array starts at 0 */
199
		$dnsserver = $syscfg['dnsserver'][$dnscounter - 1];
200
		if (!empty($dnsserver)) {
201
			if (is_ipaddr($gatewayip)) {
202
				route_add_or_change("-host {$inet6}{$dnsserver} {$gatewayip}");
203
			} else {
204
				/* Remove old route when disable gw */
205
				$gatewayip = exec("/sbin/route -n get {$dnsserver} | /usr/bin/awk '/gateway:/ {print $2;}'");
206
				mwexec("/sbin/route -q delete -host {$inet6}{$dnsserver} " . escapeshellarg($gatewayip));
207
				if (isset($config['system']['route-debug'])) {
208
					$mt = microtime();
209
					log_error("ROUTING debug: $mt - route delete -host {$inet6}{$dnsserver} {$gatewayip}");
210
				}
211
			}
212
		}
213
		$dnscounter++;
214
		$dnsgw = "dns{$dnscounter}gw";
215
	}
216

    
217
	unlock($dnslock);
218

    
219
	return 0;
220
}
221

    
222
function get_searchdomains() {
223
	global $config, $g;
224

    
225
	$master_list = array();
226

    
227
	// Read in dhclient nameservers
228
	$search_list = glob("/var/etc/searchdomain_*");
229
	if (is_array($search_list)) {
230
		foreach ($search_list as $fdns) {
231
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
232
			if (!is_array($contents)) {
233
				continue;
234
			}
235
			foreach ($contents as $dns) {
236
				if (is_hostname($dns)) {
237
					$master_list[] = $dns;
238
				}
239
			}
240
		}
241
	}
242

    
243
	return $master_list;
244
}
245

    
246
function get_nameservers() {
247
	global $config, $g;
248
	$master_list = array();
249

    
250
	// Read in dhclient nameservers
251
	$dns_lists = glob("/var/etc/nameserver_*");
252
	if (is_array($dns_lists)) {
253
		foreach ($dns_lists as $fdns) {
254
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
255
			if (!is_array($contents)) {
256
				continue;
257
			}
258
			foreach ($contents as $dns) {
259
				if (is_ipaddr($dns)) {
260
					$master_list[] = $dns;
261
				}
262
			}
263
		}
264
	}
265

    
266
	// Read in any extra nameservers
267
	if (file_exists("/var/etc/nameservers.conf")) {
268
		$dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
269
		if (is_array($dns_s)) {
270
			foreach ($dns_s as $dns) {
271
				if (is_ipaddr($dns)) {
272
					$master_list[] = $dns;
273
				}
274
			}
275
		}
276
	}
277

    
278
	return $master_list;
279
}
280

    
281
/* Create localhost + local interfaces entries for /etc/hosts */
282
function system_hosts_local_entries() {
283
	global $config;
284

    
285
	$syscfg = $config['system'];
286

    
287
	$hosts = array();
288
	$hosts[] = array(
289
	    'ipaddr' => '127.0.0.1',
290
	    'fqdn' => 'localhost.' . $syscfg['domain'],
291
	    'name' => 'localhost',
292
	    'domain' => $syscfg['domain']
293
	);
294
	$hosts[] = array(
295
	    'ipaddr' => '::1',
296
	    'fqdn' => 'localhost.' . $syscfg['domain'],
297
	    'name' => 'localhost',
298
	    'domain' => $syscfg['domain']
299
	);
300

    
301
	if ($config['interfaces']['lan']) {
302
		$sysiflist = array('lan' => "lan");
303
	} else {
304
		$sysiflist = get_configured_interface_list();
305
	}
306

    
307
	$hosts_if_found = false;
308
	$local_fqdn = "{$syscfg['hostname']}.{$syscfg['domain']}";
309
	foreach ($sysiflist as $sysif) {
310
		if ($sysif != 'lan' && interface_has_gateway($sysif)) {
311
			continue;
312
		}
313
		$cfgip = get_interface_ip($sysif);
314
		if (is_ipaddrv4($cfgip)) {
315
			$hosts[] = array(
316
			    'ipaddr' => $cfgip,
317
			    'fqdn' => $local_fqdn,
318
			    'name' => $syscfg['hostname'],
319
			    'domain' => $syscfg['domain']
320
			);
321
			$hosts_if_found = true;
322
		}
323
		if (!isset($syscfg['ipv6dontcreatelocaldns'])) {
324
			$cfgipv6 = get_interface_ipv6($sysif);
325
			if (is_ipaddrv6($cfgipv6)) {
326
				$hosts[] = array(
327
					'ipaddr' => $cfgipv6,
328
					'fqdn' => $local_fqdn,
329
					'name' => $syscfg['hostname'],
330
					'domain' => $syscfg['domain']
331
				);
332
				$hosts_if_found = true;
333
			}
334
		}
335
		if ($hosts_if_found == true) {
336
			break;
337
		}
338
	}
339

    
340
	return $hosts;
341
}
342

    
343
/* Read host override entries from dnsmasq or unbound */
344
function system_hosts_override_entries($dnscfg) {
345
	$hosts = array();
346

    
347
	if (!is_array($dnscfg) ||
348
	    !is_array($dnscfg['hosts']) ||
349
	    !isset($dnscfg['enable'])) {
350
		return $hosts;
351
	}
352

    
353
	foreach ($dnscfg['hosts'] as $host) {
354
		$fqdn = '';
355
		if ($host['host'] || $host['host'] == "0") {
356
			$fqdn .= "{$host['host']}.";
357
		}
358
		$fqdn .= $host['domain'];
359

    
360
		$hosts[] = array(
361
		    'ipaddr' => $host['ip'],
362
		    'fqdn' => $fqdn,
363
		    'name' => $host['host'],
364
		    'domain' => $host['domain']
365
		);
366

    
367
		if (!is_array($host['aliases']) ||
368
		    !is_array($host['aliases']['item'])) {
369
			continue;
370
		}
371

    
372
		foreach ($host['aliases']['item'] as $alias) {
373
			$fqdn = '';
374
			if ($alias['host'] || $alias['host'] == "0") {
375
				$fqdn .= "{$alias['host']}.";
376
			}
377
			$fqdn .= $alias['domain'];
378

    
379
			$hosts[] = array(
380
			    'ipaddr' => $host['ip'],
381
			    'fqdn' => $fqdn,
382
			    'name' => $alias['host'],
383
			    'domain' => $alias['domain']
384
			);
385
		}
386
	}
387

    
388
	return $hosts;
389
}
390

    
391
/* Read all dhcpd/dhcpdv6 staticmap entries */
392
function system_hosts_dhcpd_entries() {
393
	global $config;
394

    
395
	$hosts = array();
396
	$syscfg = $config['system'];
397

    
398
	if (is_array($config['dhcpd'])) {
399
		$conf_dhcpd = $config['dhcpd'];
400
	} else {
401
		$conf_dhcpd = array();
402
	}
403

    
404
	foreach ($conf_dhcpd as $dhcpif => $dhcpifconf) {
405
		if (!is_array($dhcpifconf['staticmap']) ||
406
		    !isset($dhcpifconf['enable'])) {
407
			continue;
408
		}
409
		foreach ($dhcpifconf['staticmap'] as $host) {
410
			if (!$host['ipaddr'] ||
411
			    !$host['hostname']) {
412
				continue;
413
			}
414

    
415
			$fqdn = $host['hostname'] . ".";
416
			$domain = "";
417
			if ($host['domain']) {
418
				$domain = $host['domain'];
419
			} elseif ($dhcpifconf['domain']) {
420
				$domain = $dhcpifconf['domain'];
421
			} else {
422
				$domain = $syscfg['domain'];
423
			}
424

    
425
			$hosts[] = array(
426
			    'ipaddr' => $host['ipaddr'],
427
			    'fqdn' => $fqdn . $domain,
428
			    'name' => $host['hostname'],
429
			    'domain' => $domain
430
			);
431
		}
432
	}
433
	unset($conf_dhcpd);
434

    
435
	if (is_array($config['dhcpdv6'])) {
436
		$conf_dhcpdv6 = $config['dhcpdv6'];
437
	} else {
438
		$conf_dhcpdv6 = array();
439
	}
440

    
441
	foreach ($conf_dhcpdv6 as $dhcpif => $dhcpifconf) {
442
		if (!is_array($dhcpifconf['staticmap']) ||
443
		    !isset($dhcpifconf['enable'])) {
444
			continue;
445
		}
446

    
447
		if (isset($config['interfaces'][$dhcpif]['ipaddrv6']) &&
448
		    $config['interfaces'][$dhcpif]['ipaddrv6'] ==
449
		    'track6') {
450
			$isdelegated = true;
451
		} else {
452
			$isdelegated = false;
453
		}
454

    
455
		foreach ($dhcpifconf['staticmap'] as $host) {
456
			$ipaddrv6 = $host['ipaddrv6'];
457

    
458
			if (!$ipaddrv6 || !$host['hostname']) {
459
				continue;
460
			}
461

    
462
			if ($isdelegated) {
463
				/*
464
				 * We are always in an "end-user" subnet
465
				 * here, which all are /64 for IPv6.
466
				 */
467
				$prefix6 = 64;
468
			} else {
469
				$prefix6 = get_interface_subnetv6($dhcpif);
470
			}
471
			$ipaddrv6 = merge_ipv6_delegated_prefix(get_interface_ipv6($dhcpif), $ipaddrv6, $prefix6);
472

    
473
			$fqdn = $host['hostname'] . ".";
474
			$domain = "";
475
			if ($host['domain']) {
476
				$domain = $host['domain'];
477
			} elseif ($dhcpifconf['domain']) {
478
				$domain = $dhcpifconf['domain'];
479
			} else {
480
				$domain = $syscfg['domain'];
481
			}
482

    
483
			$hosts[] = array(
484
			    'ipaddr' => $ipaddrv6,
485
			    'fqdn' => $fqdn . $domain,
486
			    'name' => $host['hostname'],
487
			    'domain' => $domain
488
			);
489
		}
490
	}
491
	unset($conf_dhcpdv6);
492

    
493
	return $hosts;
494
}
495

    
496
/* Concatenate local, dnsmasq/unbound and dhcpd/dhcpdv6 hosts entries */
497
function system_hosts_entries($dnscfg) {
498
	$local = array();
499
	if (!isset($dnscfg['disable_auto_added_host_entries'])) {
500
		$local = system_hosts_local_entries();
501
	}
502

    
503
	$dns = array();
504
	$dhcpd = array();
505
	if (isset($dnscfg['enable'])) {
506
		$dns = system_hosts_override_entries($dnscfg);
507
		if (isset($dnscfg['regdhcpstatic'])) {
508
			$dhcpd = system_hosts_dhcpd_entries();
509
		}
510
	}
511

    
512
	if (isset($dnscfg['dhcpfirst'])) {
513
		return array_merge($local, $dns, $dhcpd);
514
	} else {
515
		return array_merge($local, $dhcpd, $dns);
516
	}
517
}
518

    
519
function system_hosts_generate() {
520
	global $config, $g;
521
	if (isset($config['system']['developerspew'])) {
522
		$mt = microtime();
523
		echo "system_hosts_generate() being called $mt\n";
524
	}
525

    
526
	// prefer dnsmasq for hosts generation where it's enabled. It relies
527
	// on hosts for name resolution of its overrides, unbound does not.
528
	if (isset($config['dnsmasq']) && isset($config['dnsmasq']['enable'])) {
529
		$dnsmasqcfg = $config['dnsmasq'];
530
	} else {
531
		$dnsmasqcfg = $config['unbound'];
532
	}
533

    
534
	$syscfg = $config['system'];
535
	$hosts = "";
536
	$lhosts = "";
537
	$dhosts = "";
538

    
539
	$hosts_array = system_hosts_entries($dnsmasqcfg);
540
	foreach ($hosts_array as $host) {
541
		$hosts .= "{$host['ipaddr']}\t";
542
		if ($host['name'] == "localhost") {
543
			$hosts .= "{$host['name']} {$host['fqdn']}";
544
		} else {
545
			$hosts .= "{$host['fqdn']} {$host['name']}";
546
		}
547
		$hosts .= "\n";
548
	}
549
	unset($hosts_array);
550

    
551
	/*
552
	 * Do not remove this because dhcpleases monitors with kqueue it needs
553
	 * to be killed before writing to hosts files.
554
	 */
555
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
556
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
557
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
558
	}
559

    
560
	$fd = fopen("{$g['etc_path']}/hosts", "w");
561
	if (!$fd) {
562
		log_error(gettext(
563
		    "Error: cannot open hosts file in system_hosts_generate()."
564
		    ));
565
		return 1;
566
	}
567

    
568
	fwrite($fd, $hosts);
569
	fclose($fd);
570

    
571
	if (isset($config['unbound']['enable'])) {
572
		require_once("unbound.inc");
573
		unbound_hosts_generate();
574
	}
575

    
576
	/* restart dhcpleases */
577
	if (!platform_booting()) {
578
		system_dhcpleases_configure();
579
	}
580

    
581
	return 0;
582
}
583

    
584
function system_dhcpleases_configure() {
585
	global $config, $g;
586
	if (!function_exists('is_dhcp_server_enabled')) {
587
		require_once('pfsense-utils.inc');
588
	}
589
	$pidfile = "{$g['varrun_path']}/dhcpleases.pid";
590

    
591
	/* Start the monitoring process for dynamic dhcpclients. */
592
	if (((isset($config['dnsmasq']['enable']) && isset($config['dnsmasq']['regdhcp'])) ||
593
	    (isset($config['unbound']['enable']) && isset($config['unbound']['regdhcp']))) &&
594
	    (is_dhcp_server_enabled())) {
595
		/* Make sure we do not error out */
596
		mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db");
597
		if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
598
			@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
599
		}
600

    
601
		if (isset($config['unbound']['enable'])) {
602
			$dns_pid = "unbound.pid";
603
			$unbound_conf = "-u {$g['unbound_chroot_path']}/dhcpleases_entries.conf";
604
		} else {
605
			$dns_pid = "dnsmasq.pid";
606
			$unbound_conf = "";
607
		}
608

    
609
		if (isvalidpid($pidfile)) {
610
			/* Make sure dhcpleases is using correct unbound or dnsmasq */
611
			$_gb = exec("/bin/pgrep -F {$pidfile} -f {$dns_pid}", $output, $retval);
612
			if (intval($retval) == 0) {
613
				sigkillbypid($pidfile, "HUP");
614
				return;
615
			} else {
616
				sigkillbypid($pidfile, "TERM");
617
			}
618
		}
619

    
620
		/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
621
		if (is_process_running("dhcpleases")) {
622
			sigkillbyname('dhcpleases', "TERM");
623
		}
624
		@unlink($pidfile);
625
		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");
626
	} else {
627
		if (isvalidpid($pidfile)) {
628
			sigkillbypid($pidfile, "TERM");
629
			@unlink($pidfile);
630
		}
631
		if (file_exists("{$g['unbound_chroot_path']}/dhcpleases_entries.conf")) {
632
			$dhcpleases = fopen("{$g['unbound_chroot_path']}/dhcpleases_entries.conf", "w");
633
			ftruncate($dhcpleases, 0);
634
			fclose($dhcpleases);
635
		}
636
	}
637
}
638

    
639
function system_get_dhcpleases() {
640
	global $config, $g;
641

    
642
	$leases = array();
643
	$leases['lease'] = array();
644
	$leases['failover'] = array();
645

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

    
648
	if (!file_exists($leases_file)) {
649
		return $leases;
650
	}
651

    
652
	$leases_content = file($leases_file, FILE_IGNORE_NEW_LINES |
653
	    FILE_IGNORE_NEW_LINES);
654

    
655
	if ($leases_content === FALSE) {
656
		return $leases;
657
	}
658

    
659
	$arp_table = system_get_arp_table();
660

    
661
	$arpdata_ip = array();
662
	$arpdata_mac = array();
663
	foreach ($arp_table as $arp_entry) {
664
		if (isset($arpentry['incomplete'])) {
665
			continue;
666
		}
667
		$arpdata_ip[] = $arp_entry['ip-address'];
668
		$arpdata_mac[] = $arp_entry['mac-address'];
669
	}
670
	unset($arp_table);
671

    
672
	/*
673
	 * Translate these once so we don't do it over and over in the loops
674
	 * below.
675
	 */
676
	$online_string = gettext("online");
677
	$offline_string = gettext("offline");
678
	$active_string = gettext("active");
679
	$expired_string = gettext("expired");
680
	$reserved_string = gettext("reserved");
681
	$dynamic_string = gettext("dynamic");
682
	$static_string = gettext("static");
683

    
684
	$lease_regex = '/^lease\s+([^\s]+)\s+{$/';
685
	$starts_regex = '/^\s*(starts|ends)\s+\d+\s+([\d\/]+|never)\s*(|[\d:]*);$/';
686
	$binding_regex = '/^\s*binding\s+state\s+(.+);$/';
687
	$mac_regex = '/^\s*hardware\s+ethernet\s+(.+);$/';
688
	$hostname_regex = '/^\s*client-hostname\s+"(.+)";$/';
689

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

    
693
	$lease = false;
694
	$failover = false;
695
	$dedup_lease = false;
696
	$dedup_failover = false;
697
	foreach ($leases_content as $line) {
698
		/* Skip comments */
699
		if (preg_match('/^\s*(|#.*)$/', $line)) {
700
			continue;
701
		}
702

    
703
		if (preg_match('/}$/', $line)) {
704
			if ($lease) {
705
				if (empty($item['hostname'])) {
706
					$hostname = gethostbyaddr($item['ip']);
707
					if (!empty($hostname)) {
708
						$item['hostname'] = $hostname;
709
					}
710
				}
711
				$leases['lease'][] = $item;
712
				$lease = false;
713
				$dedup_lease = true;
714
			} else if ($failover) {
715
				$leases['failover'][] = $item;
716
				$failover = false;
717
				$dedup_failover = true;
718
			}
719
			continue;
720
		}
721

    
722
		if (preg_match($lease_regex, $line, $m)) {
723
			$lease = true;
724
			$item = array();
725
			$item['ip'] = $m[1];
726
			$item['type'] = $dynamic_string;
727
			continue;
728
		}
729

    
730
		if ($lease) {
731
			if (preg_match($starts_regex, $line, $m)) {
732
				/*
733
				 * Quote from dhcpd.leases(5) man page:
734
				 * If a lease will never expire, date is never
735
				 * instead of an actual date
736
				 */
737
				if ($m[2] == "never") {
738
					$item[$m[1]] = gettext("Never");
739
				} else {
740
					$item[$m[1]] = dhcpd_date_adjust_gmt(
741
					    $m[2] . ' ' . $m[3]);
742
				}
743
				continue;
744
			}
745

    
746
			if (preg_match($binding_regex, $line, $m)) {
747
				switch ($m[1]) {
748
					case "active":
749
						$item['act'] = $active_string;
750
						break;
751
					case "free":
752
						$item['act'] = $expired_string;
753
						$item['online'] =
754
						    $offline_string;
755
						break;
756
					case "backup":
757
						$item['act'] = $reserved_string;
758
						$item['online'] =
759
						    $offline_string;
760
						break;
761
				}
762
				continue;
763
			}
764

    
765
			if (preg_match($mac_regex, $line, $m) &&
766
			    is_macaddr($m[1])) {
767
				$item['mac'] = $m[1];
768

    
769
				if (in_array($item['ip'], $arpdata_ip)) {
770
					$item['online'] = $online_string;
771
				} else {
772
					$item['online'] = $offline_string;
773
				}
774
				continue;
775
			}
776

    
777
			if (preg_match($hostname_regex, $line, $m)) {
778
				$item['hostname'] = $m[1];
779
			}
780
		}
781

    
782
		if (preg_match($failover_regex, $line, $m)) {
783
			$failover = true;
784
			$item = array();
785
			$item['name'] = $m[1] . ' (' .
786
			    convert_friendly_interface_to_friendly_descr(
787
			    substr($m[1],5)) . ')';
788
			continue;
789
		}
790

    
791
		if ($failover && preg_match($state_regex, $line, $m)) {
792
			$item[$m[1] . 'state'] = $m[2];
793
			$item[$m[1] . 'date'] = dhcpd_date_adjust_gmt($m[3] .
794
			    ' ' . $m[4]);
795
			continue;
796
		}
797
	}
798

    
799
	foreach ($config['interfaces'] as $ifname => $ifarr) {
800
		if (!is_array($config['dhcpd'][$ifname]) ||
801
		    !is_array($config['dhcpd'][$ifname]['staticmap'])) {
802
			continue;
803
		}
804

    
805
		foreach ($config['dhcpd'][$ifname]['staticmap'] as $idx =>
806
		    $static) {
807
			if (empty($static['mac']) && empty($static['cid'])) {
808
				continue;
809
			}
810

    
811
			$slease = array();
812
			$slease['ip'] = $static['ipaddr'];
813
			$slease['type'] = $static_string;
814
			if (!empty($static['cid'])) {
815
				$slease['cid'] = $static['cid'];
816
			}
817
			$slease['mac'] = $static['mac'];
818
			$slease['if'] = $ifname;
819
			$slease['starts'] = "";
820
			$slease['ends'] = "";
821
			$slease['hostname'] = $static['hostname'];
822
			$slease['descr'] = $static['descr'];
823
			$slease['act'] = $static_string;
824
			$slease['online'] = in_array(strtolower($slease['mac']),
825
			    $arpdata_mac) ? $online_string : $offline_string;
826
			$slease['staticmap_array_index'] = $idx;
827
			$leases['lease'][] = $slease;
828
			$dedup_lease = true;
829
		}
830
	}
831

    
832
	if ($dedup_lease) {
833
		$leases['lease'] = array_remove_duplicate($leases['lease'],
834
		    'ip');
835
	}
836
	if ($dedup_failover) {
837
		$leases['failover'] = array_remove_duplicate(
838
		    $leases['failover'], 'name');
839
		asort($leases['failover']);
840
	}
841

    
842
	return $leases;
843
}
844

    
845
function system_hostname_configure() {
846
	global $config, $g;
847
	if (isset($config['system']['developerspew'])) {
848
		$mt = microtime();
849
		echo "system_hostname_configure() being called $mt\n";
850
	}
851

    
852
	$syscfg = $config['system'];
853

    
854
	/* set hostname */
855
	$status = mwexec("/bin/hostname " .
856
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
857

    
858
	/* Setup host GUID ID.  This is used by ZFS. */
859
	mwexec("/etc/rc.d/hostid start");
860

    
861
	return $status;
862
}
863

    
864
function system_routing_configure($interface = "") {
865
	global $config, $g;
866

    
867
	if (isset($config['system']['developerspew'])) {
868
		$mt = microtime();
869
		echo "system_routing_configure() being called $mt\n";
870
	}
871

    
872
	$gateways_arr = return_gateways_array(false, true);
873
	foreach ($gateways_arr as $gateway) {
874
		// setup static interface routes for nonlocal gateways
875
		if (isset($gateway["nonlocalgateway"])) {
876
			$srgatewayip = $gateway['gateway'];
877
			$srinterfacegw = $gateway['interface'];
878
			if (is_ipaddr($srgatewayip) && !empty($srinterfacegw)) {
879
				$inet = (!is_ipaddrv4($srgatewayip) ? "-inet6" : "-inet");
880
				route_add_or_change("{$inet} {$srgatewayip} " .
881
				    "-iface {$srinterfacegw}");
882
			}
883
		}
884
	}
885

    
886
	$gateways_status = return_gateways_status(true);
887
	fixup_default_gateway("inet", $gateways_status, $gateways_arr);
888
	fixup_default_gateway("inet6", $gateways_status, $gateways_arr);
889

    
890
	system_staticroutes_configure($interface, false);
891

    
892
	return 0;
893
}
894

    
895
function system_staticroutes_configure($interface = "", $update_dns = false) {
896
	global $config, $g, $aliastable;
897

    
898
	$filterdns_list = array();
899

    
900
	$static_routes = get_staticroutes(false, true);
901
	if (count($static_routes)) {
902
		$gateways_arr = return_gateways_array(false, true);
903

    
904
		foreach ($static_routes as $rtent) {
905
			if (empty($gateways_arr[$rtent['gateway']])) {
906
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
907
				continue;
908
			}
909
			$gateway = $gateways_arr[$rtent['gateway']];
910
			if (!empty($interface) && $interface != $gateway['friendlyiface']) {
911
				continue;
912
			}
913

    
914
			$gatewayip = $gateway['gateway'];
915
			$interfacegw = $gateway['interface'];
916

    
917
			$blackhole = "";
918
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 4))) {
919
				$blackhole = "-blackhole";
920
			}
921

    
922
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network'])) {
923
				continue;
924
			}
925

    
926
			$dnscache = array();
927
			if ($update_dns === true) {
928
				if (is_subnet($rtent['network'])) {
929
					continue;
930
				}
931
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
932
				if (empty($dnscache)) {
933
					continue;
934
				}
935
			}
936

    
937
			if (is_subnet($rtent['network'])) {
938
				$ips = array($rtent['network']);
939
			} else {
940
				if (!isset($rtent['disabled'])) {
941
					$filterdns_list[] = $rtent['network'];
942
				}
943
				$ips = add_hostname_to_watch($rtent['network']);
944
			}
945

    
946
			foreach ($dnscache as $ip) {
947
				if (in_array($ip, $ips)) {
948
					continue;
949
				}
950
				mwexec("/sbin/route delete " . escapeshellarg($ip) . " " . escapeshellarg($gatewayip), true);
951
				if (isset($config['system']['route-debug'])) {
952
					$mt = microtime();
953
					log_error("ROUTING debug: $mt - route delete $ip $gatewayip ");
954
				}
955
			}
956

    
957
			if (isset($rtent['disabled'])) {
958
				/* XXX: This can break things by deleting routes that shouldn't be deleted - OpenVPN, dynamic routing scenarios, etc. redmine #3709 */
959
				foreach ($ips as $ip) {
960
					mwexec("/sbin/route delete " . escapeshellarg($ip) . " " . escapeshellarg($gatewayip), true);
961
					if (isset($config['system']['route-debug'])) {
962
						$mt = microtime();
963
						log_error("ROUTING debug: $mt - route delete $ip $gatewayip ");
964
					}
965
				}
966
				continue;
967
			}
968

    
969
			foreach ($ips as $ip) {
970
				if (is_ipaddrv4($ip)) {
971
					$ip .= "/32";
972
				}
973
				// do NOT do the same check here on v6, is_ipaddrv6 returns true when including the CIDR mask. doing so breaks v6 routes
974

    
975
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
976

    
977
				$cmd = "{$inet} {$blackhole} {$ip} ";
978

    
979
				if (is_subnet($ip)) {
980
					if (is_ipaddr($gatewayip)) {
981
						if (is_linklocal($gatewayip) == "6" && !strpos($gatewayip, '%')) {
982
							// add interface scope for link local v6 routes
983
							$gatewayip .= "%$interfacegw";
984
						}
985
						route_add_or_change($cmd . $gatewayip);
986
					} else if (!empty($interfacegw)) {
987
						route_add_or_change($cmd . "-iface {$interfacegw}");
988
					}
989
				}
990
			}
991
		}
992
		unset($gateways_arr);
993
	}
994
	unset($static_routes);
995

    
996
	if ($update_dns === false) {
997
		if (count($filterdns_list)) {
998
			$interval = 60;
999
			$hostnames = "";
1000
			array_unique($filterdns_list);
1001
			foreach ($filterdns_list as $hostname) {
1002
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
1003
			}
1004
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
1005
			unset($hostnames);
1006

    
1007
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid")) {
1008
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
1009
			} else {
1010
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
1011
			}
1012
		} else {
1013
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
1014
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
1015
		}
1016
	}
1017
	unset($filterdns_list);
1018

    
1019
	return 0;
1020
}
1021

    
1022
function system_routing_enable() {
1023
	global $config, $g;
1024
	if (isset($config['system']['developerspew'])) {
1025
		$mt = microtime();
1026
		echo "system_routing_enable() being called $mt\n";
1027
	}
1028

    
1029
	set_sysctl(array(
1030
		"net.inet.ip.forwarding" => "1",
1031
		"net.inet6.ip6.forwarding" => "1"
1032
	));
1033

    
1034
	return;
1035
}
1036

    
1037
function system_webgui_create_certificate() {
1038
	global $config, $g, $cert_strict_values;
1039

    
1040
	init_config_arr(array('ca'));
1041
	$a_ca = &$config['ca'];
1042
	init_config_arr(array('cert'));
1043
	$a_cert = &$config['cert'];
1044
	log_error(gettext("Creating SSL/TLS Certificate for this host"));
1045

    
1046
	$cert = array();
1047
	$cert['refid'] = uniqid();
1048
	$cert['descr'] = sprintf(gettext("webConfigurator default (%s)"), $cert['refid']);
1049
	$cert_hostname = "{$config['system']['hostname']}-{$cert['refid']}";
1050

    
1051
	$dn = array(
1052
		'organizationName' => "{$g['product_name']} webConfigurator Self-Signed Certificate",
1053
		'commonName' => $cert_hostname,
1054
		'subjectAltName' => "DNS:{$cert_hostname}");
1055
	$old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warnings directly to a page screwing menu tab */
1056
	if (!cert_create($cert, null, 2048, $cert_strict_values['max_server_cert_lifetime'], $dn, "self-signed", "sha256")) {
1057
		while ($ssl_err = openssl_error_string()) {
1058
			log_error(sprintf(gettext("Error creating WebGUI Certificate: openssl library returns: %s"), $ssl_err));
1059
		}
1060
		error_reporting($old_err_level);
1061
		return null;
1062
	}
1063
	error_reporting($old_err_level);
1064

    
1065
	$a_cert[] = $cert;
1066
	$config['system']['webgui']['ssl-certref'] = $cert['refid'];
1067
	write_config(sprintf(gettext("Generated new self-signed SSL/TLS certificate for HTTPS (%s)"), $cert['refid']));
1068
	return $cert;
1069
}
1070

    
1071
function system_webgui_start() {
1072
	global $config, $g;
1073

    
1074
	if (platform_booting()) {
1075
		echo gettext("Starting webConfigurator...");
1076
	}
1077

    
1078
	chdir($g['www_path']);
1079

    
1080
	/* defaults */
1081
	$portarg = "80";
1082
	$crt = "";
1083
	$key = "";
1084
	$ca = "";
1085

    
1086
	/* non-standard port? */
1087
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "") {
1088
		$portarg = "{$config['system']['webgui']['port']}";
1089
	}
1090

    
1091
	if ($config['system']['webgui']['protocol'] == "https") {
1092
		// Ensure that we have a webConfigurator CERT
1093
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
1094
		if (!is_array($cert) || !$cert['crt'] || !$cert['prv']) {
1095
			$cert = system_webgui_create_certificate();
1096
		}
1097
		$crt = base64_decode($cert['crt']);
1098
		$key = base64_decode($cert['prv']);
1099

    
1100
		if (!$config['system']['webgui']['port']) {
1101
			$portarg = "443";
1102
		}
1103
		$ca = ca_chain($cert);
1104
		$hsts = isset($config['system']['webgui']['disablehsts']) ? false : true;
1105
	}
1106

    
1107
	/* generate nginx configuration */
1108
	system_generate_nginx_config("{$g['varetc_path']}/nginx-webConfigurator.conf",
1109
		$crt, $key, $ca, "nginx-webConfigurator.pid", $portarg, "/usr/local/www/",
1110
		"cert.crt", "cert.key", false, $hsts);
1111

    
1112
	/* kill any running nginx */
1113
	killbypid("{$g['varrun_path']}/nginx-webConfigurator.pid");
1114

    
1115
	sleep(1);
1116

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

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

    
1122
	if (platform_booting()) {
1123
		if ($res == 0) {
1124
			echo gettext("done.") . "\n";
1125
		} else {
1126
			echo gettext("failed!") . "\n";
1127
		}
1128
	}
1129

    
1130
	return $res;
1131
}
1132

    
1133
function get_dns_nameservers($add_v6_brackets = false) {
1134
	global $config;
1135

    
1136
	$dns_nameservers = array();
1137

    
1138
	if (isset($config['system']['developerspew'])) {
1139
		$mt = microtime();
1140
		echo "get_dns_nameservers() being called $mt\n";
1141
	}
1142

    
1143
	$syscfg = $config['system'];
1144
	if ((((isset($config['dnsmasq']['enable'])) &&
1145
   		(empty($config['dnsmasq']['port']) || $config['dnsmasq']['port'] == "53") &&
1146
	      	(empty($config['dnsmasq']['interface']) ||
1147
	       	in_array("lo0", explode(",", $config['dnsmasq']['interface'])))) ||
1148
	     	((isset($config['unbound']['enable'])) &&
1149
	      	(empty($config['unbound']['port']) || $config['unbound']['port'] == "53") &&
1150
	      	(empty($config['unbound']['active_interface']) ||
1151
	       	in_array("lo0", explode(",", $config['unbound']['active_interface'])) ||
1152
	       	in_array("all", explode(",", $config['unbound']['active_interface']), true)))) &&
1153
	     	(!isset($config['system']['dnslocalhost']))) {
1154
			$dns_nameservers[] = "127.0.0.1";
1155
	}
1156
	/* get dynamically assigned DNS servers (if any) */
1157
	$ns = array_unique(get_nameservers());
1158
	if (isset($syscfg['dnsallowoverride'])) {
1159
		if(!is_array($ns)) {
1160
			$ns = array();
1161
		}
1162
		foreach ($ns as $nameserver) {
1163
			if ($nameserver) {
1164
				if ($add_v6_brackets && is_ipaddrv6($nameserver)) {
1165
					$nameserver = "[{$nameserver}]";
1166
				}
1167
				$dns_nameservers[] = $nameserver;
1168
			}
1169
		}
1170
	} else {
1171
		/* If override is disallowed, ignore the dynamic NS entries
1172
		 * https://redmine.pfsense.org/issues/9963 */
1173
		$ns = array();
1174
	}
1175
	if (is_array($syscfg['dnsserver'])) {
1176
		foreach ($syscfg['dnsserver'] as $sys_dnsserver) {
1177
			if ($sys_dnsserver && (!in_array($sys_dnsserver, $ns))) {
1178
				if ($add_v6_brackets && is_ipaddrv6($sys_dnsserver)) {
1179
					$sys_dnsserver = "[{$sys_dnsserver}]";
1180
				}
1181
				$dns_nameservers[] = $sys_dnsserver;
1182
			}
1183
		}
1184
	}
1185
	return array_unique($dns_nameservers);
1186
}
1187

    
1188
function system_generate_nginx_config($filename,
1189
	$cert,
1190
	$key,
1191
	$ca,
1192
	$pid_file,
1193
	$port = 80,
1194
	$document_root = "/usr/local/www/",
1195
	$cert_location = "cert.crt",
1196
	$key_location = "cert.key",
1197
	$captive_portal = false,
1198
	$hsts = true) {
1199

    
1200
	global $config, $g;
1201

    
1202
	if (isset($config['system']['developerspew'])) {
1203
		$mt = microtime();
1204
		echo "system_generate_nginx_config() being called $mt\n";
1205
	}
1206

    
1207
	if ($captive_portal !== false) {
1208
		$cp_interfaces = explode(",", $config['captiveportal'][$captive_portal]['interface']);
1209
		$cp_hostcheck = "";
1210
		foreach ($cp_interfaces as $cpint) {
1211
			$cpint_ip = get_interface_ip($cpint);
1212
			if (is_ipaddr($cpint_ip)) {
1213
				$cp_hostcheck .= "\t\tif (\$http_host ~* $cpint_ip) {\n";
1214
				$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1215
				$cp_hostcheck .= "\t\t}\n";
1216
			}
1217
		}
1218
		if (isset($config['captiveportal'][$captive_portal]['httpsname']) &&
1219
		    is_domain($config['captiveportal'][$captive_portal]['httpsname'])) {
1220
			$cp_hostcheck .= "\t\tif (\$http_host ~* {$config['captiveportal'][$captive_portal]['httpsname']}) {\n";
1221
			$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1222
			$cp_hostcheck .= "\t\t}\n";
1223
		}
1224
		$cp_rewrite = "\t\tif (\$cp_redirect = '') {\n";
1225
		$cp_rewrite .= "\t\t\trewrite	^ /index.php?zone=$captive_portal&redirurl=\$request_uri break;\n";
1226
		$cp_rewrite .= "\t\t}\n";
1227

    
1228
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1229
		if (empty($maxprocperip)) {
1230
			$maxprocperip = 10;
1231
		}
1232
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1233
	}
1234

    
1235
	if (empty($port)) {
1236
		$nginx_port = "80";
1237
	} else {
1238
		$nginx_port = $port;
1239
	}
1240

    
1241
	$memory = get_memory();
1242
	$realmem = $memory[1];
1243

    
1244
	// Determine web GUI process settings and take into account low memory systems
1245
	if ($realmem < 255) {
1246
		$max_procs = 1;
1247
	} else {
1248
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
1249
	}
1250

    
1251
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM
1252
	if ($captive_portal !== false) {
1253
		if ($realmem > 135 and $realmem < 256) {
1254
			$max_procs += 1; // 2 worker processes
1255
		} else if ($realmem > 255 and $realmem < 513) {
1256
			$max_procs += 2; // 3 worker processes
1257
		} else if ($realmem > 512) {
1258
			$max_procs += 4; // 6 worker processes
1259
		}
1260
	}
1261

    
1262
	$nginx_config = <<<EOD
1263
#
1264
# nginx configuration file
1265

    
1266
pid {$g['varrun_path']}/{$pid_file};
1267

    
1268
user  root wheel;
1269
worker_processes  {$max_procs};
1270

    
1271
EOD;
1272

    
1273
	/* Disable file logging */
1274
	$nginx_config .= "error_log /dev/null;\n";
1275
	if (!isset($config['syslog']['nolognginx'])) {
1276
		/* Send nginx error log to syslog */
1277
		$nginx_config .= "error_log  syslog:server=unix:/var/run/log,facility=local5;\n";
1278
	}
1279

    
1280
	$nginx_config .= <<<EOD
1281

    
1282
events {
1283
    worker_connections  1024;
1284
}
1285

    
1286
http {
1287
	include       /usr/local/etc/nginx/mime.types;
1288
	default_type  application/octet-stream;
1289
	add_header X-Frame-Options SAMEORIGIN;
1290
	server_tokens off;
1291

    
1292
	sendfile        on;
1293

    
1294
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1295

    
1296
EOD;
1297

    
1298
	if ($captive_portal !== false) {
1299
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1300
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1301
	} else {
1302
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1303
	}
1304

    
1305
	if ($cert <> "" and $key <> "") {
1306
		$nginx_config .= "\n";
1307
		$nginx_config .= "\tserver {\n";
1308
		$nginx_config .= "\t\tlisten {$nginx_port} ssl http2;\n";
1309
		$nginx_config .= "\t\tlisten [::]:{$nginx_port} ssl http2;\n";
1310
		$nginx_config .= "\n";
1311
		$nginx_config .= "\t\tssl_certificate         {$g['varetc_path']}/{$cert_location};\n";
1312
		$nginx_config .= "\t\tssl_certificate_key     {$g['varetc_path']}/{$key_location};\n";
1313
		$nginx_config .= "\t\tssl_session_timeout     10m;\n";
1314
		$nginx_config .= "\t\tkeepalive_timeout       70;\n";
1315
		$nginx_config .= "\t\tssl_session_cache       shared:SSL:10m;\n";
1316
		if ($captive_portal !== false) {
1317
			// leave TLSv1.1 for CP for now for compatibility
1318
			$nginx_config .= "\t\tssl_protocols   TLSv1.1 TLSv1.2 TLSv1.3;\n";
1319
		} else {
1320
			$nginx_config .= "\t\tssl_protocols   TLSv1.2 TLSv1.3;\n";
1321
		}
1322
		$nginx_config .= "\t\tssl_ciphers \"EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305\";\n";
1323
		$nginx_config .= "\t\tssl_prefer_server_ciphers       on;\n";
1324
		if ($captive_portal === false && $hsts !== false) {
1325
			$nginx_config .= "\t\tadd_header Strict-Transport-Security \"max-age=31536000\";\n";
1326
		}
1327
		$nginx_config .= "\t\tadd_header X-Content-Type-Options nosniff;\n";
1328
		$nginx_config .= "\t\tssl_session_tickets off;\n";
1329
		$nginx_config .= "\t\tssl_dhparam /etc/dh-parameters.4096;\n";
1330
		$cert_temp = lookup_cert($config['system']['webgui']['ssl-certref']);
1331
		if (($config['system']['webgui']['ocsp-staple'] == true) or
1332
		    (cert_get_ocspstaple($cert_temp['crt']) == true)) {
1333
			$nginx_config .= "\t\tssl_stapling on;\n";
1334
			$nginx_config .= "\t\tssl_stapling_verify on;\n";
1335
			$nginx_config .= "\t\tresolver " . implode(" ", get_dns_nameservers(true)) . " valid=300s;\n";
1336
			$nginx_config .= "\t\tresolver_timeout 5s;\n";
1337
		}
1338
	} else {
1339
		$nginx_config .= "\n";
1340
		$nginx_config .= "\tserver {\n";
1341
		$nginx_config .= "\t\tlisten {$nginx_port};\n";
1342
		$nginx_config .= "\t\tlisten [::]:{$nginx_port};\n";
1343
	}
1344

    
1345
	$nginx_config .= <<<EOD
1346

    
1347
		client_max_body_size 200m;
1348

    
1349
		gzip on;
1350
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
1351

    
1352

    
1353
EOD;
1354

    
1355
	if ($captive_portal !== false) {
1356
		$nginx_config .= <<<EOD
1357
$captive_portal_maxprocperip
1358
$cp_hostcheck
1359
$cp_rewrite
1360
		log_not_found off;
1361

    
1362
EOD;
1363

    
1364
	}
1365

    
1366
	$nginx_config .= <<<EOD
1367
		root "{$document_root}";
1368
		location / {
1369
			index  index.php index.html index.htm;
1370
		}
1371
		location ~ \.inc$ {
1372
			deny all;
1373
			return 403;
1374
		}
1375
		location ~ \.php$ {
1376
			try_files \$uri =404; #  This line closes a potential security hole
1377
			# ensuring users can't execute uploaded files
1378
			# see: http://forum.nginx.org/read.php?2,88845,page=3
1379
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1380
			fastcgi_index  index.php;
1381
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1382
			# Fix httpoxy - https://httpoxy.org/#fix-now
1383
			fastcgi_param  HTTP_PROXY  "";
1384
			fastcgi_read_timeout 180;
1385
			include        /usr/local/etc/nginx/fastcgi_params;
1386
		}
1387
		location ~ (^/status$) {
1388
			allow 127.0.0.1;
1389
			deny all;
1390
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1391
			fastcgi_index  index.php;
1392
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1393
			# Fix httpoxy - https://httpoxy.org/#fix-now
1394
			fastcgi_param  HTTP_PROXY  "";
1395
			fastcgi_read_timeout 360;
1396
			include        /usr/local/etc/nginx/fastcgi_params;
1397
		}
1398
	}
1399

    
1400
EOD;
1401

    
1402
	$cert = str_replace("\r", "", $cert);
1403
	$key = str_replace("\r", "", $key);
1404

    
1405
	$cert = str_replace("\n\n", "\n", $cert);
1406
	$key = str_replace("\n\n", "\n", $key);
1407

    
1408
	if ($cert <> "" and $key <> "") {
1409
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1410
		if (!$fd) {
1411
			printf(gettext("Error: cannot open certificate file in system_webgui_start().%s"), "\n");
1412
			return 1;
1413
		}
1414
		chmod("{$g['varetc_path']}/{$cert_location}", 0644);
1415
		if ($ca <> "") {
1416
			$cert_chain = $cert . "\n" . $ca;
1417
		} else {
1418
			$cert_chain = $cert;
1419
		}
1420
		fwrite($fd, $cert_chain);
1421
		fclose($fd);
1422
		$fd = fopen("{$g['varetc_path']}/{$key_location}", "w");
1423
		if (!$fd) {
1424
			printf(gettext("Error: cannot open certificate key file in system_webgui_start().%s"), "\n");
1425
			return 1;
1426
		}
1427
		chmod("{$g['varetc_path']}/{$key_location}", 0600);
1428
		fwrite($fd, $key);
1429
		fclose($fd);
1430
	}
1431

    
1432
	// Add HTTP to HTTPS redirect
1433
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1434
		if ($nginx_port != "443") {
1435
			$redirectport = ":{$nginx_port}";
1436
		}
1437
		$nginx_config .= <<<EOD
1438
	server {
1439
		listen 80;
1440
		listen [::]:80;
1441
		return 301 https://\$http_host$redirectport\$request_uri;
1442
	}
1443

    
1444
EOD;
1445
	}
1446

    
1447
	$nginx_config .= "}\n";
1448

    
1449
	$fd = fopen("{$filename}", "w");
1450
	if (!$fd) {
1451
		printf(gettext('Error: cannot open %1$s in system_generate_nginx_config().%2$s'), $filename, "\n");
1452
		return 1;
1453
	}
1454
	fwrite($fd, $nginx_config);
1455
	fclose($fd);
1456

    
1457
	/* nginx will fail to start if this directory does not exist. */
1458
	safe_mkdir("/var/tmp/nginx/");
1459

    
1460
	return 0;
1461

    
1462
}
1463

    
1464
function system_get_timezone_list() {
1465
	global $g;
1466

    
1467
	$file_list = array_merge(
1468
		glob("/usr/share/zoneinfo/[A-Z]*"),
1469
		glob("/usr/share/zoneinfo/*/*"),
1470
		glob("/usr/share/zoneinfo/*/*/*")
1471
	);
1472

    
1473
	if (empty($file_list)) {
1474
		$file_list[] = $g['default_timezone'];
1475
	} else {
1476
		/* Remove directories from list */
1477
		$file_list = array_filter($file_list, function($v) {
1478
			return !is_dir($v);
1479
		});
1480
	}
1481

    
1482
	/* Remove directory prefix */
1483
	$file_list = str_replace('/usr/share/zoneinfo/', '', $file_list);
1484

    
1485
	sort($file_list);
1486

    
1487
	return $file_list;
1488
}
1489

    
1490
function system_timezone_configure() {
1491
	global $config, $g;
1492
	if (isset($config['system']['developerspew'])) {
1493
		$mt = microtime();
1494
		echo "system_timezone_configure() being called $mt\n";
1495
	}
1496

    
1497
	$syscfg = $config['system'];
1498

    
1499
	if (platform_booting()) {
1500
		echo gettext("Setting timezone...");
1501
	}
1502

    
1503
	/* extract appropriate timezone file */
1504
	$timezone = (isset($syscfg['timezone']) ? $syscfg['timezone'] : $g['default_timezone']);
1505
	/* DO NOT remove \n otherwise tzsetup will fail */
1506
	@file_put_contents("/var/db/zoneinfo", $timezone . "\n");
1507
	mwexec("/usr/sbin/tzsetup -r");
1508

    
1509
	if (platform_booting()) {
1510
		echo gettext("done.") . "\n";
1511
	}
1512
}
1513

    
1514
function check_gps_speed($device) {
1515
	usleep(1000);
1516
	// Set timeout to 5s
1517
	$timeout=microtime(true)+5;
1518
	if ($fp = fopen($device, 'r')) {
1519
		stream_set_blocking($fp, 0);
1520
		stream_set_timeout($fp, 5);
1521
		$contents = "";
1522
		$cnt = 0;
1523
		$buffersize = 256;
1524
		do {
1525
			$c = fread($fp, $buffersize - $cnt);
1526

    
1527
			// Wait for data to arive
1528
			if (($c === false) || (strlen($c) == 0)) {
1529
				usleep(500);
1530
				continue;
1531
			}
1532

    
1533
			$contents.=$c;
1534
			$cnt = $cnt + strlen($c);
1535
		} while (($cnt < $buffersize) && (microtime(true) < $timeout));
1536
		fclose($fp);
1537

    
1538
		$nmeasentences = ['RMC', 'GGA', 'GLL', 'ZDA', 'ZDG', 'PGRMF'];
1539
		foreach ($nmeasentences as $sentence) {
1540
			if (strpos($contents, $sentence) > 0) {
1541
				return true;
1542
			}
1543
		}
1544
		if (strpos($contents, '0') > 0) {
1545
			$filters = ['`', '?', '/', '~'];
1546
			foreach ($filters as $filter) {
1547
				if (strpos($contents, $filter) !== false) {
1548
					return false;
1549
				}
1550
			}
1551
			return true;
1552
		}
1553
	}
1554
	return false;
1555
}
1556

    
1557
/* Generate list of possible NTP poll values
1558
 * https://redmine.pfsense.org/issues/9439 */
1559
global $ntp_poll_min_value, $ntp_poll_max_value;
1560
global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
1561
global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
1562
global $ntp_poll_min_default, $ntp_poll_max_default;
1563
$ntp_poll_min_value = 4;
1564
$ntp_poll_max_value = 17;
1565
$ntp_poll_min_default_gps = 4;
1566
$ntp_poll_max_default_gps = 4;
1567
$ntp_poll_min_default_pps = 4;
1568
$ntp_poll_max_default_pps = 4;
1569
$ntp_poll_min_default = 'omit';
1570
$ntp_poll_max_default = 9;
1571

    
1572
function system_ntp_poll_values() {
1573
	global $ntp_poll_min_value, $ntp_poll_max_value;
1574
	$poll_values = array("" => gettext('Default'));
1575

    
1576
	for ($i = $ntp_poll_min_value; $i <= $ntp_poll_max_value; $i++) {
1577
		$sec = 2 ** $i;
1578
		$poll_values[$i] = $i . ': ' . number_format($sec) . ' ' . gettext('seconds') .
1579
					' (' . convert_seconds_to_dhms($sec) . ')';
1580
	}
1581

    
1582
	$poll_values['omit'] = gettext('Omit (Do not set)');
1583
	return $poll_values;
1584
}
1585

    
1586
function system_ntp_fixup_poll_value($type, $configvalue, $default) {
1587
	$pollstring = "";
1588

    
1589
	if (empty($configvalue)) {
1590
		$configvalue = $default;
1591
	}
1592

    
1593
	if ($configvalue != 'omit') {
1594
		$pollstring = " {$type} {$configvalue}";
1595
	}
1596

    
1597
	return $pollstring;
1598
}
1599

    
1600
function system_ntp_setup_gps($serialport) {
1601
	global $config, $g;
1602

    
1603
	if (is_array($config['ntpd']) && ($config['ntpd']['enable'] == 'disabled')) {
1604
		return false;
1605
	}
1606

    
1607
	init_config_arr(array('ntpd', 'gps'));
1608

    
1609
	$gps_device = '/dev/gps0';
1610
	$serialport = '/dev/'.$serialport;
1611

    
1612
	if (!file_exists($serialport)) {
1613
		return false;
1614
	}
1615

    
1616
	// Create symlink that ntpd requires
1617
	unlink_if_exists($gps_device);
1618
	@symlink($serialport, $gps_device);
1619

    
1620
	$gpsbaud = '4800';
1621
	$speeds = array(
1622
		0 => '4800', 
1623
		16 => '9600', 
1624
		32 => '19200', 
1625
		48 => '38400', 
1626
		64 => '57600', 
1627
		80 => '115200'
1628
	);
1629
	if (!empty($config['ntpd']['gps']['speed']) && array_key_exists($config['ntpd']['gps']['speed'], $speeds)) {
1630
		$gpsbaud = $speeds[$config['ntpd']['gps']['speed']];
1631
	}
1632

    
1633
	system_ntp_setup_rawspeed($serialport, $gpsbaud);
1634

    
1635
	$autospeed = ($config['ntpd']['gps']['speed'] == 'autoalways' || $config['ntpd']['gps']['speed'] == 'autoset');
1636
	if ($autospeed || ($config['ntpd']['gps']['autobaudinit'] && !check_gps_speed($gps_device))) {
1637
		$found = false;
1638
		foreach ($speeds as $baud) {
1639
			system_ntp_setup_rawspeed($serialport, $baud);
1640
			if ($found = check_gps_speed($gps_device)) {
1641
				if ($autospeed) {
1642
					$saveconfig = ($config['ntpd']['gps']['speed'] == 'autoset');
1643
					$config['ntpd']['gps']['speed'] = array_search($baud, $speeds);
1644
					$gpsbaud = $baud;
1645
					if ($saveconfig) {
1646
						write_config(sprintf(gettext('Autoset GPS baud rate to %s'), $baud));
1647
					}
1648
				}
1649
				break;
1650
			}
1651
		}
1652
		if ($found === false) {
1653
			log_error(gettext("Could not find correct GPS baud rate."));
1654
			return false;
1655
		}
1656
	}
1657

    
1658
	/* Send the following to the GPS port to initialize the GPS */
1659
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
1660
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
1661
	} else {
1662
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1663
	}
1664

    
1665
	/* XXX: Why not file_put_contents to the device */
1666
	@file_put_contents('/tmp/gps.init', $gps_init);
1667
	mwexec("cat /tmp/gps.init > {$serialport}");
1668

    
1669
	if ($found && $config['ntpd']['gps']['autobaudinit']) {
1670
		system_ntp_setup_rawspeed($serialport, $gpsbaud);
1671
	}
1672

    
1673
	/* Remove old /etc/remote entry if it exists */
1674
	if (mwexec("/usr/bin/grep -c '^gps0' /etc/remote") == 0) {
1675
		mwexec("/usr/bin/sed -i '' -n '/gps0/!p' /etc/remote");
1676
	}
1677

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

    
1683
	return true;
1684
}
1685

    
1686
// Configure the serial port for raw IO and set the speed
1687
function system_ntp_setup_rawspeed($serialport, $baud) {
1688
	mwexec("/bin/stty -f " .  escapeshellarg($serialport) . " raw speed " . escapeshellarg($baud));
1689
	mwexec("/bin/stty -f " .  escapeshellarg($serialport) . ".init raw speed " . escapeshellarg($baud));
1690
}
1691

    
1692
function system_ntp_setup_pps($serialport) {
1693
	global $config, $g;
1694

    
1695
	$pps_device = '/dev/pps0';
1696
	$serialport = '/dev/'.$serialport;
1697

    
1698
	if (!file_exists($serialport)) {
1699
		return false;
1700
	}
1701
	// If ntpd is disabled, just return
1702
	if (is_array($config['ntpd']) && ($config['ntpd']['enable'] == 'disabled')) {
1703
		return false;
1704
	}
1705

    
1706
	// Create symlink that ntpd requires
1707
	unlink_if_exists($pps_device);
1708
	@symlink($serialport, $pps_device);
1709

    
1710

    
1711
	return true;
1712
}
1713

    
1714
function system_ntp_configure() {
1715
	global $config, $g;
1716
	global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
1717
	global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
1718
	global $ntp_poll_min_default, $ntp_poll_max_default;
1719

    
1720
	$driftfile = "/var/db/ntpd.drift";
1721
	$statsdir = "/var/log/ntp";
1722
	$gps_device = '/dev/gps0';
1723

    
1724
	safe_mkdir($statsdir);
1725

    
1726
	if (!is_array($config['ntpd'])) {
1727
		$config['ntpd'] = array();
1728
	}
1729
	// ntpd is disabled, just stop it and return
1730
	if ($config['ntpd']['enable'] == 'disabled') {
1731
		while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1732
			killbypid("{$g['varrun_path']}/ntpd.pid");
1733
		}
1734
		@unlink("{$g['varrun_path']}/ntpd.pid");
1735
		@unlink("{$g['varetc_path']}/ntpd.conf");
1736
		log_error("NTPD is disabled.");
1737
		return;
1738
	}
1739

    
1740
	if (platform_booting()) {
1741
		echo gettext("Starting NTP Server...");
1742
	}
1743

    
1744
	/* if ntpd is running, kill it */
1745
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1746
		killbypid("{$g['varrun_path']}/ntpd.pid");
1747
	}
1748
	@unlink("{$g['varrun_path']}/ntpd.pid");
1749

    
1750
	$ntpcfg = "# \n";
1751
	$ntpcfg .= "# pfSense ntp configuration file \n";
1752
	$ntpcfg .= "# \n\n";
1753
	$ntpcfg .= "tinker panic 0 \n";
1754

    
1755
	/* Add Orphan mode */
1756
	$ntpcfg .= "# Orphan mode stratum and Maximum candidate NTP peers\n";
1757
	$ntpcfg .= 'tos orphan ';
1758
	if (!empty($config['ntpd']['orphan'])) {
1759
		$ntpcfg .= $config['ntpd']['orphan'];
1760
	} else {
1761
		$ntpcfg .= '12';
1762
	}
1763
	/* Add Maximum candidate NTP peers */
1764
	$ntpcfg .= ' maxclock ';
1765
	if (!empty($config['ntpd']['ntpmaxpeers'])) {
1766
		$ntpcfg .= $config['ntpd']['ntpmaxpeers'];
1767
	} else {
1768
		$ntpcfg .= '5';
1769
	}
1770
	$ntpcfg .= "\n";
1771

    
1772
	/* Add PPS configuration */
1773
	if (is_array($config['ntpd']['pps']) && !empty($config['ntpd']['pps']['port']) &&
1774
	    file_exists('/dev/'.$config['ntpd']['pps']['port']) &&
1775
	    system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
1776
		$ntpcfg .= "\n";
1777
		$ntpcfg .= "# PPS Setup\n";
1778
		$ntpcfg .= 'server 127.127.22.0';
1779
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', $config['ntpd']['pps']['ppsminpoll'], $ntp_poll_min_default_pps);
1780
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', $config['ntpd']['pps']['ppsmaxpoll'], $ntp_poll_max_default_pps);
1781
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
1782
			$ntpcfg .= ' prefer';
1783
		}
1784
		if (!empty($config['ntpd']['pps']['noselect'])) {
1785
			$ntpcfg .= ' noselect ';
1786
		}
1787
		$ntpcfg .= "\n";
1788
		$ntpcfg .= 'fudge 127.127.22.0';
1789
		if (!empty($config['ntpd']['pps']['fudge1'])) {
1790
			$ntpcfg .= ' time1 ';
1791
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
1792
		}
1793
		if (!empty($config['ntpd']['pps']['flag2'])) {
1794
			$ntpcfg .= ' flag2 1';
1795
		}
1796
		if (!empty($config['ntpd']['pps']['flag3'])) {
1797
			$ntpcfg .= ' flag3 1';
1798
		} else {
1799
			$ntpcfg .= ' flag3 0';
1800
		}
1801
		if (!empty($config['ntpd']['pps']['flag4'])) {
1802
			$ntpcfg .= ' flag4 1';
1803
		}
1804
		if (!empty($config['ntpd']['pps']['refid'])) {
1805
			$ntpcfg .= ' refid ';
1806
			$ntpcfg .= $config['ntpd']['pps']['refid'];
1807
		}
1808
		$ntpcfg .= "\n";
1809
	}
1810
	/* End PPS configuration */
1811

    
1812
	/* Add GPS configuration */
1813
	if (is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['port']) &&
1814
	    system_ntp_setup_gps($config['ntpd']['gps']['port'])) {
1815
		$ntpcfg .= "\n";
1816
		$ntpcfg .= "# GPS Setup\n";
1817
		$ntpcfg .= 'server 127.127.20.0 mode ';
1818
		if (!empty($config['ntpd']['gps']['nmea']) || !empty($config['ntpd']['gps']['speed']) || !empty($config['ntpd']['gps']['subsec']) || !empty($config['ntpd']['gps']['processpgrmf'])) {
1819
			if (!empty($config['ntpd']['gps']['nmea'])) {
1820
				$ntpmode = (int) $config['ntpd']['gps']['nmea'];
1821
			}
1822
			if (!empty($config['ntpd']['gps']['speed'])) {
1823
				$ntpmode += (int) $config['ntpd']['gps']['speed'];
1824
			}
1825
			if (!empty($config['ntpd']['gps']['subsec'])) {
1826
				$ntpmode += 128;
1827
			}
1828
			if (!empty($config['ntpd']['gps']['processpgrmf'])) {
1829
				$ntpmode += 256;
1830
			}
1831
			$ntpcfg .= (string) $ntpmode;
1832
		} else {
1833
			$ntpcfg .= '0';
1834
		}
1835
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', $config['ntpd']['gps']['gpsminpoll'], $ntp_poll_min_default_gps);
1836
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', $config['ntpd']['gps']['gpsmaxpoll'], $ntp_poll_max_default_gps);
1837

    
1838
		if (empty($config['ntpd']['gps']['prefer'])) { /*note: this one works backwards */
1839
			$ntpcfg .= ' prefer';
1840
		}
1841
		if (!empty($config['ntpd']['gps']['noselect'])) {
1842
			$ntpcfg .= ' noselect ';
1843
		}
1844
		$ntpcfg .= "\n";
1845
		$ntpcfg .= 'fudge 127.127.20.0';
1846
		if (!empty($config['ntpd']['gps']['fudge1'])) {
1847
			$ntpcfg .= ' time1 ';
1848
			$ntpcfg .= $config['ntpd']['gps']['fudge1'];
1849
		}
1850
		if (!empty($config['ntpd']['gps']['fudge2'])) {
1851
			$ntpcfg .= ' time2 ';
1852
			$ntpcfg .= $config['ntpd']['gps']['fudge2'];
1853
		}
1854
		if (!empty($config['ntpd']['gps']['flag1'])) {
1855
			$ntpcfg .= ' flag1 1';
1856
		} else {
1857
			$ntpcfg .= ' flag1 0';
1858
		}
1859
		if (!empty($config['ntpd']['gps']['flag2'])) {
1860
			$ntpcfg .= ' flag2 1';
1861
		}
1862
		if (!empty($config['ntpd']['gps']['flag3'])) {
1863
			$ntpcfg .= ' flag3 1';
1864
		} else {
1865
			$ntpcfg .= ' flag3 0';
1866
		}
1867
		if (!empty($config['ntpd']['gps']['flag4'])) {
1868
			$ntpcfg .= ' flag4 1';
1869
		}
1870
		if (!empty($config['ntpd']['gps']['refid'])) {
1871
			$ntpcfg .= ' refid ';
1872
			$ntpcfg .= $config['ntpd']['gps']['refid'];
1873
		}
1874
		if (!empty($config['ntpd']['gps']['stratum'])) {
1875
			$ntpcfg .= ' stratum ';
1876
			$ntpcfg .= $config['ntpd']['gps']['stratum'];
1877
		}
1878
		$ntpcfg .= "\n";
1879
	} elseif (is_array($config['ntpd']) && !empty($config['ntpd']['gpsport']) &&
1880
	    system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1881
		/* This handles a 2.1 and earlier config */
1882
		$ntpcfg .= "# GPS Setup\n";
1883
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1884
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1885
		// Fall back to local clock if GPS is out of sync?
1886
		$ntpcfg .= "server 127.127.1.0\n";
1887
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1888
	}
1889
	/* End GPS configuration */
1890
	$auto_pool_suffix = "pool.ntp.org";
1891
	$have_pools = false;
1892
	$ntpcfg .= "\n\n# Upstream Servers\n";
1893
	/* foreach through ntp servers and write out to ntpd.conf */
1894
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1895
		if ((substr_compare($ts, $auto_pool_suffix, strlen($ts) - strlen($auto_pool_suffix), strlen($auto_pool_suffix)) === 0)
1896
		    || substr_count($config['ntpd']['ispool'], $ts)) {
1897
			$ntpcfg .= 'pool ';
1898
			$have_pools = true;
1899
		} else {
1900
			$ntpcfg .= 'server ';
1901
		}
1902

    
1903
		$ntpcfg .= "{$ts} iburst";
1904

    
1905
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', $config['ntpd']['ntpminpoll'], $ntp_poll_min_default);
1906
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', $config['ntpd']['ntpmaxpoll'], $ntp_poll_max_default);
1907

    
1908
		if (substr_count($config['ntpd']['prefer'], $ts)) {
1909
			$ntpcfg .= ' prefer';
1910
		}
1911
		if (substr_count($config['ntpd']['noselect'], $ts)) {
1912
			$ntpcfg .= ' noselect';
1913
		}
1914
		$ntpcfg .= "\n";
1915
	}
1916
	unset($ts);
1917

    
1918
	$ntpcfg .= "\n\n";
1919
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
1920
		$ntpcfg .= "enable stats\n";
1921
		$ntpcfg .= 'statistics';
1922
		if (!empty($config['ntpd']['clockstats'])) {
1923
			$ntpcfg .= ' clockstats';
1924
		}
1925
		if (!empty($config['ntpd']['loopstats'])) {
1926
			$ntpcfg .= ' loopstats';
1927
		}
1928
		if (!empty($config['ntpd']['peerstats'])) {
1929
			$ntpcfg .= ' peerstats';
1930
		}
1931
		$ntpcfg .= "\n";
1932
	}
1933
	$ntpcfg .= "statsdir {$statsdir}\n";
1934
	$ntpcfg .= 'logconfig =syncall +clockall';
1935
	if (!empty($config['ntpd']['logpeer'])) {
1936
		$ntpcfg .= ' +peerall';
1937
	}
1938
	if (!empty($config['ntpd']['logsys'])) {
1939
		$ntpcfg .= ' +sysall';
1940
	}
1941
	$ntpcfg .= "\n";
1942
	$ntpcfg .= "driftfile {$driftfile}\n";
1943

    
1944
	/* Default Access restrictions */
1945
	$ntpcfg .= 'restrict default';
1946
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1947
		$ntpcfg .= ' kod limited';
1948
	}
1949
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1950
		$ntpcfg .= ' nomodify';
1951
	}
1952
	if (!empty($config['ntpd']['noquery'])) {
1953
		$ntpcfg .= ' noquery';
1954
	}
1955
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1956
		$ntpcfg .= ' nopeer';
1957
	}
1958
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1959
		$ntpcfg .= ' notrap';
1960
	}
1961
	if (!empty($config['ntpd']['noserve'])) {
1962
		$ntpcfg .= ' noserve';
1963
	}
1964
	$ntpcfg .= "\nrestrict -6 default";
1965
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1966
		$ntpcfg .= ' kod limited';
1967
	}
1968
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1969
		$ntpcfg .= ' nomodify';
1970
	}
1971
	if (!empty($config['ntpd']['noquery'])) {
1972
		$ntpcfg .= ' noquery';
1973
	}
1974
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1975
		$ntpcfg .= ' nopeer';
1976
	}
1977
	if (!empty($config['ntpd']['noserve'])) {
1978
		$ntpcfg .= ' noserve';
1979
	}
1980
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1981
		$ntpcfg .= ' notrap';
1982
	}
1983

    
1984
	/* Pools require "restrict source" and cannot contain "nopeer" and "noserve". */
1985
	if ($have_pools) {
1986
		$ntpcfg .= "\nrestrict source";
1987
		if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1988
			$ntpcfg .= ' kod limited';
1989
		}
1990
		if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1991
			$ntpcfg .= ' nomodify';
1992
		}
1993
		if (!empty($config['ntpd']['noquery'])) {
1994
			$ntpcfg .= ' noquery';
1995
		}
1996
		if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1997
			$ntpcfg .= ' notrap';
1998
		}
1999
	}
2000

    
2001
	/* Custom Access Restrictions */
2002
	if (is_array($config['ntpd']['restrictions']) && is_array($config['ntpd']['restrictions']['row'])) {
2003
		$networkacl = $config['ntpd']['restrictions']['row'];
2004
		foreach ($networkacl as $acl) {
2005
			$restrict = "";
2006
			if (is_ipaddrv6($acl['acl_network'])) {
2007
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask_v6($acl['mask']) . " ";
2008
			} elseif (is_ipaddrv4($acl['acl_network'])) {
2009
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask($acl['mask']) . " ";
2010
			} else {
2011
				continue;
2012
			}
2013
			if (!empty($acl['kod'])) {
2014
				$restrict .= ' kod limited';
2015
			}
2016
			if (!empty($acl['nomodify'])) {
2017
				$restrict .= ' nomodify';
2018
			}
2019
			if (!empty($acl['noquery'])) {
2020
				$restrict .= ' noquery';
2021
			}
2022
			if (!empty($acl['nopeer'])) {
2023
				$restrict .= ' nopeer';
2024
			}
2025
			if (!empty($acl['noserve'])) {
2026
				$restrict .= ' noserve';
2027
			}
2028
			if (!empty($acl['notrap'])) {
2029
				$restrict .= ' notrap';
2030
			}
2031
			if (!empty($restrict)) {
2032
				$ntpcfg .= "\nrestrict {$restrict} ";
2033
			}
2034
		}
2035
	}
2036
	/* End Custom Access Restrictions */
2037

    
2038
	/* A leapseconds file is really only useful if this clock is stratum 1 */
2039
	$ntpcfg .= "\n";
2040
	if (!empty($config['ntpd']['leapsec'])) {
2041
		$leapsec .= base64_decode($config['ntpd']['leapsec']);
2042
		file_put_contents('/var/db/leap-seconds', $leapsec);
2043
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
2044
	}
2045

    
2046

    
2047
	if (empty($config['ntpd']['interface'])) {
2048
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface'])) {
2049
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
2050
		} else {
2051
			$interfaces = array();
2052
		}
2053
	} else {
2054
		$interfaces = explode(",", $config['ntpd']['interface']);
2055
	}
2056

    
2057
	if (is_array($interfaces) && count($interfaces)) {
2058
		$finterfaces = array();
2059
		$ntpcfg .= "interface ignore all\n";
2060
		$ntpcfg .= "interface ignore wildcard\n";
2061
		foreach ($interfaces as $interface) {
2062
			$interface = get_real_interface($interface);
2063
			if (!empty($interface)) {
2064
				$finterfaces[] = $interface;
2065
			}
2066
		}
2067
		foreach ($finterfaces as $interface) {
2068
			$ntpcfg .= "interface listen {$interface}\n";
2069
		}
2070
	}
2071

    
2072
	/* open configuration for writing or bail */
2073
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
2074
		log_error(sprintf(gettext("Could not open %s/ntpd.conf for writing"), $g['varetc_path']));
2075
		return;
2076
	}
2077

    
2078
	/* if /var/empty does not exist, create it */
2079
	if (!is_dir("/var/empty")) {
2080
		mkdir("/var/empty", 0555, true);
2081
	}
2082

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

    
2086
	// Note that we are starting up
2087
	log_error("NTPD is starting up.");
2088

    
2089
	if (platform_booting()) {
2090
		echo gettext("done.") . "\n";
2091
	}
2092

    
2093
	return;
2094
}
2095

    
2096
function system_halt() {
2097
	global $g;
2098

    
2099
	system_reboot_cleanup();
2100

    
2101
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
2102
}
2103

    
2104
function system_reboot() {
2105
	global $g;
2106

    
2107
	system_reboot_cleanup();
2108

    
2109
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
2110
}
2111

    
2112
function system_reboot_sync($reroot=false) {
2113
	global $g;
2114

    
2115
	if ($reroot) {
2116
		$args = " -r ";
2117
	}
2118

    
2119
	system_reboot_cleanup();
2120

    
2121
	mwexec("/etc/rc.reboot {$args} > /dev/null 2>&1");
2122
}
2123

    
2124
function system_reboot_cleanup() {
2125
	global $config, $g, $cpzone;
2126

    
2127
	mwexec("/usr/local/bin/beep.sh stop");
2128
	require_once("captiveportal.inc");
2129
	if (is_array($config['captiveportal'])) {
2130
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
2131
			if (!isset($cp['preservedb'])) {
2132
				/* send Accounting-Stop packet for all clients, termination cause 'Admin-Reboot' */
2133
				captiveportal_radius_stop_all(7); // Admin-Reboot
2134
				unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
2135
				captiveportal_free_dnrules();
2136
			}
2137
			/* Send Accounting-Off packet to the RADIUS server */
2138
			captiveportal_send_server_accounting('off');
2139
		}
2140
		/* Remove the pipe database */
2141
		unlink_if_exists("{$g['vardb_path']}/captiveportaldn.rules");
2142
	}
2143
	require_once("voucher.inc");
2144
	voucher_save_db_to_config();
2145
	require_once("pkg-utils.inc");
2146
	stop_packages();
2147
}
2148

    
2149
function system_do_shell_commands($early = 0) {
2150
	global $config, $g;
2151
	if (isset($config['system']['developerspew'])) {
2152
		$mt = microtime();
2153
		echo "system_do_shell_commands() being called $mt\n";
2154
	}
2155

    
2156
	if ($early) {
2157
		$cmdn = "earlyshellcmd";
2158
	} else {
2159
		$cmdn = "shellcmd";
2160
	}
2161

    
2162
	if (is_array($config['system'][$cmdn])) {
2163

    
2164
		/* *cmd is an array, loop through */
2165
		foreach ($config['system'][$cmdn] as $cmd) {
2166
			exec($cmd);
2167
		}
2168

    
2169
	} elseif ($config['system'][$cmdn] <> "") {
2170

    
2171
		/* execute single item */
2172
		exec($config['system'][$cmdn]);
2173

    
2174
	}
2175
}
2176

    
2177
function system_dmesg_save() {
2178
	global $g;
2179
	if (isset($config['system']['developerspew'])) {
2180
		$mt = microtime();
2181
		echo "system_dmesg_save() being called $mt\n";
2182
	}
2183

    
2184
	$dmesg = "";
2185
	$_gb = exec("/sbin/dmesg", $dmesg);
2186

    
2187
	/* find last copyright line (output from previous boots may be present) */
2188
	$lastcpline = 0;
2189

    
2190
	for ($i = 0; $i < count($dmesg); $i++) {
2191
		if (strstr($dmesg[$i], "Copyright (c) 1992-")) {
2192
			$lastcpline = $i;
2193
		}
2194
	}
2195

    
2196
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
2197
	if (!$fd) {
2198
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
2199
		return 1;
2200
	}
2201

    
2202
	for ($i = $lastcpline; $i < count($dmesg); $i++) {
2203
		fwrite($fd, $dmesg[$i] . "\n");
2204
	}
2205

    
2206
	fclose($fd);
2207
	unset($dmesg);
2208

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

    
2212
	return 0;
2213
}
2214

    
2215
function system_set_harddisk_standby() {
2216
	global $g, $config;
2217

    
2218
	if (isset($config['system']['developerspew'])) {
2219
		$mt = microtime();
2220
		echo "system_set_harddisk_standby() being called $mt\n";
2221
	}
2222

    
2223
	if (isset($config['system']['harddiskstandby'])) {
2224
		if (platform_booting()) {
2225
			echo gettext('Setting hard disk standby... ');
2226
		}
2227

    
2228
		$standby = $config['system']['harddiskstandby'];
2229
		// Check for a numeric value
2230
		if (is_numeric($standby)) {
2231
			// Get only suitable candidates for standby; using get_smart_drive_list()
2232
			// from utils.inc to get the list of drives.
2233
			$harddisks = get_smart_drive_list();
2234

    
2235
			// Since get_smart_drive_list() only matches ad|da|ada; lets put the check below
2236
			// just in case of some weird pfSense platform installs.
2237
			if (count($harddisks) > 0) {
2238
				// Iterate disks and run the camcontrol command for each
2239
				foreach ($harddisks as $harddisk) {
2240
					mwexec("/sbin/camcontrol standby {$harddisk} -t {$standby}");
2241
				}
2242
				if (platform_booting()) {
2243
					echo gettext("done.") . "\n";
2244
				}
2245
			} else if (platform_booting()) {
2246
				echo gettext("failed!") . "\n";
2247
			}
2248
		} else if (platform_booting()) {
2249
			echo gettext("failed!") . "\n";
2250
		}
2251
	}
2252
}
2253

    
2254
function system_setup_sysctl() {
2255
	global $config;
2256
	if (isset($config['system']['developerspew'])) {
2257
		$mt = microtime();
2258
		echo "system_setup_sysctl() being called $mt\n";
2259
	}
2260

    
2261
	activate_sysctls();
2262

    
2263
	if (isset($config['system']['sharednet'])) {
2264
		system_disable_arp_wrong_if();
2265
	}
2266
}
2267

    
2268
function system_disable_arp_wrong_if() {
2269
	global $config;
2270
	if (isset($config['system']['developerspew'])) {
2271
		$mt = microtime();
2272
		echo "system_disable_arp_wrong_if() being called $mt\n";
2273
	}
2274
	set_sysctl(array(
2275
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
2276
		"net.link.ether.inet.log_arp_movements" => "0"
2277
	));
2278
}
2279

    
2280
function system_enable_arp_wrong_if() {
2281
	global $config;
2282
	if (isset($config['system']['developerspew'])) {
2283
		$mt = microtime();
2284
		echo "system_enable_arp_wrong_if() being called $mt\n";
2285
	}
2286
	set_sysctl(array(
2287
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
2288
		"net.link.ether.inet.log_arp_movements" => "1"
2289
	));
2290
}
2291

    
2292
function enable_watchdog() {
2293
	global $config;
2294
	return;
2295
	$install_watchdog = false;
2296
	$supported_watchdogs = array("Geode");
2297
	$file = file_get_contents("/var/log/dmesg.boot");
2298
	foreach ($supported_watchdogs as $sd) {
2299
		if (stristr($file, "Geode")) {
2300
			$install_watchdog = true;
2301
		}
2302
	}
2303
	if ($install_watchdog == true) {
2304
		if (is_process_running("watchdogd")) {
2305
			mwexec("/usr/bin/killall watchdogd", true);
2306
		}
2307
		exec("/usr/sbin/watchdogd");
2308
	}
2309
}
2310

    
2311
function system_check_reset_button() {
2312
	global $g;
2313

    
2314
	$specplatform = system_identify_specific_platform();
2315

    
2316
	switch ($specplatform['name']) {
2317
		case 'SG-2220':
2318
			$binprefix = "RCC-DFF";
2319
			break;
2320
		case 'alix':
2321
		case 'wrap':
2322
		case 'FW7541':
2323
		case 'APU':
2324
		case 'RCC-VE':
2325
		case 'RCC':
2326
			$binprefix = $specplatform['name'];
2327
			break;
2328
		default:
2329
			return 0;
2330
	}
2331

    
2332
	$retval = mwexec("/usr/local/sbin/" . $binprefix . "resetbtn");
2333

    
2334
	if ($retval == 99) {
2335
		/* user has pressed reset button for 2 seconds -
2336
		   reset to factory defaults */
2337
		echo <<<EOD
2338

    
2339
***********************************************************************
2340
* Reset button pressed - resetting configuration to factory defaults. *
2341
* All additional packages installed will be removed                   *
2342
* The system will reboot after this completes.                        *
2343
***********************************************************************
2344

    
2345

    
2346
EOD;
2347

    
2348
		reset_factory_defaults();
2349
		system_reboot_sync();
2350
		exit(0);
2351
	}
2352

    
2353
	return 0;
2354
}
2355

    
2356
function system_get_serial() {
2357
	$platform = system_identify_specific_platform();
2358

    
2359
	unset($output);
2360
	if ($platform['name'] == 'Turbot Dual-E') {
2361
		$if_info = pfSense_get_interface_addresses('igb0');
2362
		if (!empty($if_info['hwaddr'])) {
2363
			$serial = str_replace(":", "", $if_info['hwaddr']);
2364
		}
2365
	} else {
2366
		foreach (array('system', 'planar', 'chassis') as $key) {
2367
			unset($output);
2368
			$_gb = exec("/bin/kenv -q smbios.{$key}.serial",
2369
			    $output);
2370
			if (!empty($output[0]) && $output[0] != "0123456789" &&
2371
			    preg_match('/^[\w\d]{10,16}$/', $output[0]) === 1) {
2372
				$serial = $output[0];
2373
				break;
2374
			}
2375
		}
2376
	}
2377

    
2378
	$vm_guest = get_single_sysctl('kern.vm_guest');
2379

    
2380
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2381
	    $vm_guest == 'none') {
2382
		return $serial;
2383
	}
2384

    
2385
	return "";
2386
}
2387

    
2388
function system_get_uniqueid() {
2389
	global $g;
2390

    
2391
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2392

    
2393
	if (empty($g['uniqueid'])) {
2394
		if (!file_exists($uniqueid_file)) {
2395
			mwexec("/usr/sbin/gnid > {$g['vardb_path']}/uniqueid " .
2396
			    "2>/dev/null");
2397
		}
2398
		if (file_exists($uniqueid_file)) {
2399
			$g['uniqueid'] = @file_get_contents($uniqueid_file);
2400
		}
2401
	}
2402

    
2403
	return ($g['uniqueid'] ?: '');
2404
}
2405

    
2406
/*
2407
 * attempt to identify the specific platform (for embedded systems)
2408
 * Returns an array with two elements:
2409
 * name => platform string (e.g. 'wrap', 'alix' etc.)
2410
 * descr => human-readable description (e.g. "PC Engines WRAP")
2411
 */
2412
function system_identify_specific_platform() {
2413
	global $g;
2414

    
2415
	$hw_model = get_single_sysctl('hw.model');
2416
	$hw_ncpu = get_single_sysctl('hw.ncpu');
2417

    
2418
	/* Try to guess from smbios strings */
2419
	unset($product);
2420
	unset($maker);
2421
	unset($bios);
2422
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $product);
2423
	$_gb = exec('/bin/kenv -q smbios.system.maker 2>/dev/null', $maker);
2424
	$_gb = exec('/bin/kenv -q smbios.bios.version 2>/dev/null', $bios);
2425

    
2426
	// AWS can only be identified via the bios version
2427
	if (stripos($bios[0], "amazon") !== false) {
2428
		return (array('name' => 'AWS', 'descr' => 'Amazon Web Services'));
2429
	} else  if (stripos($bios[0], "Google") !== false) {
2430
		return (array('name' => 'Google', 'descr' => 'Google Cloud Platform'));
2431
	}
2432

    
2433
	switch ($product[0]) {
2434
		case 'FW7541':
2435
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2436
			break;
2437
		case 'APU':
2438
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2439
			break;
2440
		case 'RCC-VE':
2441
			$result = array();
2442
			$result['name'] = 'RCC-VE';
2443

    
2444
			/* Detect specific models */
2445
			if (!function_exists('does_interface_exist')) {
2446
				require_once("interfaces.inc");
2447
			}
2448
			if (!does_interface_exist('igb4')) {
2449
				$result['model'] = 'SG-2440';
2450
			} elseif (strpos($hw_model, "C2558") !== false) {
2451
				$result['model'] = 'SG-4860';
2452
			} elseif (strpos($hw_model, "C2758") !== false) {
2453
				$result['model'] = 'SG-8860';
2454
			} else {
2455
				$result['model'] = 'RCC-VE';
2456
			}
2457
			$result['descr'] = 'Netgate ' . $result['model'];
2458
			return $result;
2459
			break;
2460
		case 'DFFv2':
2461
			return (array('name' => 'SG-2220', 'descr' => 'Netgate SG-2220'));
2462
			break;
2463
		case 'RCC':
2464
			return (array('name' => 'RCC', 'descr' => 'Netgate XG-2758'));
2465
			break;
2466
		case 'SG-5100':
2467
			return (array('name' => 'SG-5100', 'descr' => 'Netgate SG-5100'));
2468
			break;
2469
		case 'Minnowboard Turbot D0 PLATFORM':
2470
			$result = array();
2471
			$result['name'] = 'Turbot Dual-E';
2472
			/* Detect specific model */
2473
			switch ($hw_ncpu) {
2474
			case '4':
2475
				$result['model'] = 'MBT-4220';
2476
				break;
2477
			case '2':
2478
				$result['model'] = 'MBT-2220';
2479
				break;
2480
			default:
2481
				$result['model'] = $result['name'];
2482
				break;
2483
			}
2484
			$result['descr'] = 'Netgate ' . $result['model'];
2485
			return $result;
2486
			break;
2487
		case 'SYS-5018A-FTN4':
2488
		case 'A1SAi':
2489
			if (strpos($hw_model, "C2558") !== false) {
2490
				return (array(
2491
				    'name' => 'C2558',
2492
				    'descr' => 'Super Micro C2558'));
2493
			} elseif (strpos($hw_model, "C2758") !== false) {
2494
				return (array(
2495
				    'name' => 'C2758',
2496
				    'descr' => 'Super Micro C2758'));
2497
			}
2498
			break;
2499
		case 'SYS-5018D-FN4T':
2500
			if (strpos($hw_model, "D-1541") !== false) {
2501
				return (array('name' => 'XG-1541', 'descr' => 'Super Micro XG-1541'));
2502
			} else {
2503
				return (array('name' => 'XG-1540', 'descr' => 'Super Micro XG-1540'));
2504
			}
2505
			break;
2506
		case 'apu2':
2507
		case 'APU2':
2508
			return (array('name' => 'apu2', 'descr' => 'PC Engines APU2'));
2509
			break;
2510
		case 'VirtualBox':
2511
			return (array('name' => 'VirtualBox', 'descr' => 'VirtualBox Virtual Machine'));
2512
			break;
2513
		case 'Virtual Machine':
2514
			if ($maker[0] == "Microsoft Corporation") {
2515
				if (stripos($bios[0], "Hyper") !== false) {
2516
					return (array('name' => 'Hyper-V', 'descr' => 'Hyper-V Virtual Machine'));
2517
				} else {
2518
					return (array('name' => 'Azure', 'descr' => 'Microsoft Azure'));
2519
				}
2520
			}
2521
			break;
2522
		case 'VMware Virtual Platform':
2523
			if ($maker[0] == "VMware, Inc.") {
2524
				return (array('name' => 'VMware', 'descr' => 'VMware Virtual Machine'));
2525
			}
2526
			break;
2527
	}
2528

    
2529
	$_gb = exec('/bin/kenv -q smbios.planar.product 2>/dev/null',
2530
	    $planar_product);
2531
	if (isset($planar_product[0]) &&
2532
	    $planar_product[0] == 'X10SDV-8C-TLN4F+') {
2533
		return array('name' => 'XG-1537', 'descr' => 'Super Micro XG-1537');
2534
	}
2535

    
2536
	if (strpos($hw_model, "PC Engines WRAP") !== false) {
2537
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
2538
	}
2539

    
2540
	if (strpos($hw_model, "PC Engines ALIX") !== false) {
2541
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2542
	}
2543

    
2544
	if (preg_match("/Soekris net45../", $hw_model, $matches)) {
2545
		return array('name' => 'net45xx', 'descr' => $matches[0]);
2546
	}
2547

    
2548
	if (preg_match("/Soekris net48../", $hw_model, $matches)) {
2549
		return array('name' => 'net48xx', 'descr' => $matches[0]);
2550
	}
2551

    
2552
	if (preg_match("/Soekris net55../", $hw_model, $matches)) {
2553
		return array('name' => 'net55xx', 'descr' => $matches[0]);
2554
	}
2555

    
2556
	unset($hw_model);
2557

    
2558
	$dmesg_boot = system_get_dmesg_boot();
2559
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
2560
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2561
	}
2562
	unset($dmesg_boot);
2563

    
2564
	return array('name' => $g['platform'], 'descr' => $g['platform']);
2565
}
2566

    
2567
function system_get_dmesg_boot() {
2568
	global $g;
2569

    
2570
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2571
}
2572

    
2573
function system_get_arp_table($resolve_hostnames = false) {
2574
	$params="-a";
2575
	if (!$resolve_hostnames) {
2576
		$params .= "n";
2577
	}
2578

    
2579
	$arp_table = array();
2580
	$_gb = exec("/usr/sbin/arp --libxo json {$params}", $rawdata, $rc);
2581
	if ($rc == 0) {
2582
		$arp_table = json_decode(implode(" ", $rawdata),
2583
		    JSON_OBJECT_AS_ARRAY);
2584
		if ($rc == 0) {
2585
			$arp_table = $arp_table['arp']['arp-cache'];
2586
		}
2587
	}
2588

    
2589
	return $arp_table;
2590
}
2591

    
2592
?>
(49-49/60)