Project

General

Profile

Download (69 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
				$ipaddrv6 = merge_ipv6_delegated_prefix(
468
				    get_interface_ipv6($dhcpif),
469
				    $ipaddrv6, 64);
470
			}
471

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

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

    
492
	return $hosts;
493
}
494

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

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

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

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

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

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

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

    
550
	$fd = fopen("{$g['etc_path']}/hosts", "w");
551
	if (!$fd) {
552
		log_error(gettext(
553
		    "Error: cannot open hosts file in system_hosts_generate()."
554
		    ));
555
		return 1;
556
	}
557

    
558
	/*
559
	 * Do not remove this because dhcpleases monitors with kqueue it needs
560
	 * to be killed before writing to hosts files.
561
	 */
562
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
563
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
564
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
565
	}
566

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

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

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

    
580
	return 0;
581
}
582

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

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

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

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

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

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

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

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

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

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

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

    
658
	$arp_table = system_get_arp_table();
659

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
841
	return $leases;
842
}
843

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

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

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

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

    
860
	return $status;
861
}
862

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

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

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

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

    
889
	system_staticroutes_configure($interface, false);
890

    
891
	return 0;
892
}
893

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

    
897
	$filterdns_list = array();
898

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1018
	return 0;
1019
}
1020

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

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

    
1033
	return;
1034
}
1035

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1114
	sleep(1);
1115

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

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

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

    
1129
	return $res;
1130
}
1131

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

    
1135
	$dns_nameservers = array();
1136

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

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

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

    
1199
	global $config, $g;
1200

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

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

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

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

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

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

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

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

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

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

    
1270
EOD;
1271

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

    
1279
	$nginx_config .= <<<EOD
1280

    
1281
events {
1282
    worker_connections  1024;
1283
}
1284

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

    
1291
	sendfile        on;
1292

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

    
1295
EOD;
1296

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

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

    
1344
	$nginx_config .= <<<EOD
1345

    
1346
		client_max_body_size 200m;
1347

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

    
1351

    
1352
EOD;
1353

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

    
1361
EOD;
1362

    
1363
	}
1364

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

    
1399
EOD;
1400

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

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

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

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

    
1443
EOD;
1444
	}
1445

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

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

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

    
1459
	return 0;
1460

    
1461
}
1462

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

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

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

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

    
1484
	sort($file_list);
1485

    
1486
	return $file_list;
1487
}
1488

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1596
	return $pollstring;
1597
}
1598

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

    
1602
	init_config_arr(array('ntpd', 'gps', 'speed'));
1603
	$gps_device = '/dev/gps0';
1604
	$serialport = '/dev/'.$serialport;
1605

    
1606
	if (!file_exists($serialport)) {
1607
		return false;
1608
	}
1609

    
1610
	// Create symlink that ntpd requires
1611
	unlink_if_exists($gps_device);
1612
	@symlink($serialport, $gps_device);
1613

    
1614
	$gpsbaud = '4800';
1615
	$speeds = array(
1616
		0 => '4800', 
1617
		16 => '9600', 
1618
		32 => '19200', 
1619
		48 => '38400', 
1620
		64 => '57600', 
1621
		80 => '115200'
1622
	);
1623
	if (!empty($config['ntpd']['gps']['speed']) && array_key_exists($config['ntpd']['gps']['speed'], $speeds)) {
1624
		$gpsbaud = $speeds[$config['ntpd']['gps']['speed']];
1625
	}
1626

    
1627
	system_ntp_setup_rawspeed($serialport, $gpsbaud);
1628

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

    
1652
	/* Send the following to the GPS port to initialize the GPS */
1653
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
1654
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
1655
	} else {
1656
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1657
	}
1658

    
1659
	/* XXX: Why not file_put_contents to the device */
1660
	@file_put_contents('/tmp/gps.init', $gps_init);
1661
	mwexec("cat /tmp/gps.init > {$serialport}");
1662

    
1663
	if ($found && $config['ntpd']['gps']['autobaudinit']) {
1664
		system_ntp_setup_rawspeed($serialport, $gpsbaud);
1665
	}
1666

    
1667
	/* Remove old /etc/remote entry if it exists */
1668
	if (mwexec("/usr/bin/grep -c '^gps0' /etc/remote")) {
1669
		mwexec("/usr/bin/sed -i '' -n '/gps0/!p' /etc/remote");
1670
	}
1671

    
1672
	/* Add /etc/remote entry in case we need to read from the GPS with tip */
1673
	if (intval(`/usr/bin/grep -c '^gps0' /etc/remote`) == 0) {
1674
		@file_put_contents("/etc/remote", "gps0:dv={$serialport}:br#{$gpsbaud}:pa=none:\n", FILE_APPEND);
1675
	}
1676

    
1677
	return true;
1678
}
1679

    
1680
// Configure the serial port for raw IO and set the speed
1681
function system_ntp_setup_rawspeed($serialport, $baud) {
1682
	mwexec("/bin/stty -f " .  escapeshellarg($serialport) . " raw speed " . escapeshellarg($baud));
1683
	mwexec("/bin/stty -f " .  escapeshellarg($serialport) . ".init raw speed " . escapeshellarg($baud));
1684
}
1685

    
1686
function system_ntp_setup_pps($serialport) {
1687
	global $config, $g;
1688

    
1689
	$pps_device = '/dev/pps0';
1690
	$serialport = '/dev/'.$serialport;
1691

    
1692
	if (!file_exists($serialport)) {
1693
		return false;
1694
	}
1695

    
1696
	// Create symlink that ntpd requires
1697
	unlink_if_exists($pps_device);
1698
	@symlink($serialport, $pps_device);
1699

    
1700

    
1701
	return true;
1702
}
1703

    
1704

    
1705
function system_ntp_configure() {
1706
	global $config, $g;
1707
	global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
1708
	global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
1709
	global $ntp_poll_min_default, $ntp_poll_max_default;
1710

    
1711
	$driftfile = "/var/db/ntpd.drift";
1712
	$statsdir = "/var/log/ntp";
1713
	$gps_device = '/dev/gps0';
1714

    
1715
	safe_mkdir($statsdir);
1716

    
1717
	if (!is_array($config['ntpd'])) {
1718
		$config['ntpd'] = array();
1719
	}
1720

    
1721
	/* if ntpd is running, kill it */
1722
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1723
		killbypid("{$g['varrun_path']}/ntpd.pid");
1724
	}
1725
	@unlink("{$g['varrun_path']}/ntpd.pid");
1726

    
1727
	$ntpcfg = "# \n";
1728
	$ntpcfg .= "# pfSense ntp configuration file \n";
1729
	$ntpcfg .= "# \n\n";
1730
	$ntpcfg .= "tinker panic 0 \n";
1731

    
1732
	/* Add Orphan mode */
1733
	$ntpcfg .= "# Orphan mode stratum and Maximum candidate NTP peers\n";
1734
	$ntpcfg .= 'tos orphan ';
1735
	if (!empty($config['ntpd']['orphan'])) {
1736
		$ntpcfg .= $config['ntpd']['orphan'];
1737
	} else {
1738
		$ntpcfg .= '12';
1739
	}
1740
	/* Add Maximum candidate NTP peers */
1741
	$ntpcfg .= ' maxclock ';
1742
	if (!empty($config['ntpd']['ntpmaxpeers'])) {
1743
		$ntpcfg .= $config['ntpd']['ntpmaxpeers'];
1744
	} else {
1745
		$ntpcfg .= '5';
1746
	}
1747
	$ntpcfg .= "\n";
1748

    
1749
	/* Add PPS configuration */
1750
	if (is_array($config['ntpd']['pps']) && !empty($config['ntpd']['pps']['port']) &&
1751
	    file_exists('/dev/'.$config['ntpd']['pps']['port']) &&
1752
	    system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
1753
		$ntpcfg .= "\n";
1754
		$ntpcfg .= "# PPS Setup\n";
1755
		$ntpcfg .= 'server 127.127.22.0';
1756
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', $config['ntpd']['pps']['ppsminpoll'], $ntp_poll_min_default_pps);
1757
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', $config['ntpd']['pps']['ppsmaxpoll'], $ntp_poll_max_default_pps);
1758
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
1759
			$ntpcfg .= ' prefer';
1760
		}
1761
		if (!empty($config['ntpd']['pps']['noselect'])) {
1762
			$ntpcfg .= ' noselect ';
1763
		}
1764
		$ntpcfg .= "\n";
1765
		$ntpcfg .= 'fudge 127.127.22.0';
1766
		if (!empty($config['ntpd']['pps']['fudge1'])) {
1767
			$ntpcfg .= ' time1 ';
1768
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
1769
		}
1770
		if (!empty($config['ntpd']['pps']['flag2'])) {
1771
			$ntpcfg .= ' flag2 1';
1772
		}
1773
		if (!empty($config['ntpd']['pps']['flag3'])) {
1774
			$ntpcfg .= ' flag3 1';
1775
		} else {
1776
			$ntpcfg .= ' flag3 0';
1777
		}
1778
		if (!empty($config['ntpd']['pps']['flag4'])) {
1779
			$ntpcfg .= ' flag4 1';
1780
		}
1781
		if (!empty($config['ntpd']['pps']['refid'])) {
1782
			$ntpcfg .= ' refid ';
1783
			$ntpcfg .= $config['ntpd']['pps']['refid'];
1784
		}
1785
		$ntpcfg .= "\n";
1786
	}
1787
	/* End PPS configuration */
1788

    
1789
	/* Add GPS configuration */
1790
	if (is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['port']) &&
1791
	    system_ntp_setup_gps($config['ntpd']['gps']['port'])) {
1792
		$ntpcfg .= "\n";
1793
		$ntpcfg .= "# GPS Setup\n";
1794
		$ntpcfg .= 'server 127.127.20.0 mode ';
1795
		if (!empty($config['ntpd']['gps']['nmea']) || !empty($config['ntpd']['gps']['speed']) || !empty($config['ntpd']['gps']['subsec']) || !empty($config['ntpd']['gps']['processpgrmf'])) {
1796
			if (!empty($config['ntpd']['gps']['nmea'])) {
1797
				$ntpmode = (int) $config['ntpd']['gps']['nmea'];
1798
			}
1799
			if (!empty($config['ntpd']['gps']['speed'])) {
1800
				$ntpmode += (int) $config['ntpd']['gps']['speed'];
1801
			}
1802
			if (!empty($config['ntpd']['gps']['subsec'])) {
1803
				$ntpmode += 128;
1804
			}
1805
			if (!empty($config['ntpd']['gps']['processpgrmf'])) {
1806
				$ntpmode += 256;
1807
			}
1808
			$ntpcfg .= (string) $ntpmode;
1809
		} else {
1810
			$ntpcfg .= '0';
1811
		}
1812
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', $config['ntpd']['gps']['gpsminpoll'], $ntp_poll_min_default_gps);
1813
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', $config['ntpd']['gps']['gpsmaxpoll'], $ntp_poll_max_default_gps);
1814

    
1815
		if (empty($config['ntpd']['gps']['prefer'])) { /*note: this one works backwards */
1816
			$ntpcfg .= ' prefer';
1817
		}
1818
		if (!empty($config['ntpd']['gps']['noselect'])) {
1819
			$ntpcfg .= ' noselect ';
1820
		}
1821
		$ntpcfg .= "\n";
1822
		$ntpcfg .= 'fudge 127.127.20.0';
1823
		if (!empty($config['ntpd']['gps']['fudge1'])) {
1824
			$ntpcfg .= ' time1 ';
1825
			$ntpcfg .= $config['ntpd']['gps']['fudge1'];
1826
		}
1827
		if (!empty($config['ntpd']['gps']['fudge2'])) {
1828
			$ntpcfg .= ' time2 ';
1829
			$ntpcfg .= $config['ntpd']['gps']['fudge2'];
1830
		}
1831
		if (!empty($config['ntpd']['gps']['flag1'])) {
1832
			$ntpcfg .= ' flag1 1';
1833
		} else {
1834
			$ntpcfg .= ' flag1 0';
1835
		}
1836
		if (!empty($config['ntpd']['gps']['flag2'])) {
1837
			$ntpcfg .= ' flag2 1';
1838
		}
1839
		if (!empty($config['ntpd']['gps']['flag3'])) {
1840
			$ntpcfg .= ' flag3 1';
1841
		} else {
1842
			$ntpcfg .= ' flag3 0';
1843
		}
1844
		if (!empty($config['ntpd']['gps']['flag4'])) {
1845
			$ntpcfg .= ' flag4 1';
1846
		}
1847
		if (!empty($config['ntpd']['gps']['refid'])) {
1848
			$ntpcfg .= ' refid ';
1849
			$ntpcfg .= $config['ntpd']['gps']['refid'];
1850
		}
1851
		if (!empty($config['ntpd']['gps']['stratum'])) {
1852
			$ntpcfg .= ' stratum ';
1853
			$ntpcfg .= $config['ntpd']['gps']['stratum'];
1854
		}
1855
		$ntpcfg .= "\n";
1856
	} elseif (is_array($config['ntpd']) && !empty($config['ntpd']['gpsport']) &&
1857
	    system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1858
		/* This handles a 2.1 and earlier config */
1859
		$ntpcfg .= "# GPS Setup\n";
1860
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1861
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1862
		// Fall back to local clock if GPS is out of sync?
1863
		$ntpcfg .= "server 127.127.1.0\n";
1864
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1865
	}
1866
	/* End GPS configuration */
1867
	$auto_pool_suffix = "pool.ntp.org";
1868
	$have_pools = false;
1869
	$ntpcfg .= "\n\n# Upstream Servers\n";
1870
	/* foreach through ntp servers and write out to ntpd.conf */
1871
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1872
		if ((substr_compare($ts, $auto_pool_suffix, strlen($ts) - strlen($auto_pool_suffix), strlen($auto_pool_suffix)) === 0)
1873
		    || substr_count($config['ntpd']['ispool'], $ts)) {
1874
			$ntpcfg .= 'pool ';
1875
			$have_pools = true;
1876
		} else {
1877
			$ntpcfg .= 'server ';
1878
		}
1879

    
1880
		$ntpcfg .= "{$ts} iburst";
1881

    
1882
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', $config['ntpd']['ntpminpoll'], $ntp_poll_min_default);
1883
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', $config['ntpd']['ntpmaxpoll'], $ntp_poll_max_default);
1884

    
1885
		if (substr_count($config['ntpd']['prefer'], $ts)) {
1886
			$ntpcfg .= ' prefer';
1887
		}
1888
		if (substr_count($config['ntpd']['noselect'], $ts)) {
1889
			$ntpcfg .= ' noselect';
1890
		}
1891
		$ntpcfg .= "\n";
1892
	}
1893
	unset($ts);
1894

    
1895
	$ntpcfg .= "\n\n";
1896
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
1897
		$ntpcfg .= "enable stats\n";
1898
		$ntpcfg .= 'statistics';
1899
		if (!empty($config['ntpd']['clockstats'])) {
1900
			$ntpcfg .= ' clockstats';
1901
		}
1902
		if (!empty($config['ntpd']['loopstats'])) {
1903
			$ntpcfg .= ' loopstats';
1904
		}
1905
		if (!empty($config['ntpd']['peerstats'])) {
1906
			$ntpcfg .= ' peerstats';
1907
		}
1908
		$ntpcfg .= "\n";
1909
	}
1910
	$ntpcfg .= "statsdir {$statsdir}\n";
1911
	$ntpcfg .= 'logconfig =syncall +clockall';
1912
	if (!empty($config['ntpd']['logpeer'])) {
1913
		$ntpcfg .= ' +peerall';
1914
	}
1915
	if (!empty($config['ntpd']['logsys'])) {
1916
		$ntpcfg .= ' +sysall';
1917
	}
1918
	$ntpcfg .= "\n";
1919
	$ntpcfg .= "driftfile {$driftfile}\n";
1920

    
1921
	/* Default Access restrictions */
1922
	$ntpcfg .= 'restrict default';
1923
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1924
		$ntpcfg .= ' kod limited';
1925
	}
1926
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1927
		$ntpcfg .= ' nomodify';
1928
	}
1929
	if (!empty($config['ntpd']['noquery'])) {
1930
		$ntpcfg .= ' noquery';
1931
	}
1932
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1933
		$ntpcfg .= ' nopeer';
1934
	}
1935
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1936
		$ntpcfg .= ' notrap';
1937
	}
1938
	if (!empty($config['ntpd']['noserve'])) {
1939
		$ntpcfg .= ' noserve';
1940
	}
1941
	$ntpcfg .= "\nrestrict -6 default";
1942
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1943
		$ntpcfg .= ' kod limited';
1944
	}
1945
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1946
		$ntpcfg .= ' nomodify';
1947
	}
1948
	if (!empty($config['ntpd']['noquery'])) {
1949
		$ntpcfg .= ' noquery';
1950
	}
1951
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1952
		$ntpcfg .= ' nopeer';
1953
	}
1954
	if (!empty($config['ntpd']['noserve'])) {
1955
		$ntpcfg .= ' noserve';
1956
	}
1957
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1958
		$ntpcfg .= ' notrap';
1959
	}
1960

    
1961
	/* Pools require "restrict source" and cannot contain "nopeer" and "noserve". */
1962
	if ($have_pools) {
1963
		$ntpcfg .= "\nrestrict source";
1964
		if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1965
			$ntpcfg .= ' kod limited';
1966
		}
1967
		if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1968
			$ntpcfg .= ' nomodify';
1969
		}
1970
		if (!empty($config['ntpd']['noquery'])) {
1971
			$ntpcfg .= ' noquery';
1972
		}
1973
		if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1974
			$ntpcfg .= ' notrap';
1975
		}
1976
	}
1977

    
1978
	/* Custom Access Restrictions */
1979
	if (is_array($config['ntpd']['restrictions']) && is_array($config['ntpd']['restrictions']['row'])) {
1980
		$networkacl = $config['ntpd']['restrictions']['row'];
1981
		foreach ($networkacl as $acl) {
1982
			$restrict = "";
1983
			if (is_ipaddrv6($acl['acl_network'])) {
1984
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask_v6($acl['mask']) . " ";
1985
			} elseif (is_ipaddrv4($acl['acl_network'])) {
1986
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask($acl['mask']) . " ";
1987
			} else {
1988
				continue;
1989
			}
1990
			if (!empty($acl['kod'])) {
1991
				$restrict .= ' kod limited';
1992
			}
1993
			if (!empty($acl['nomodify'])) {
1994
				$restrict .= ' nomodify';
1995
			}
1996
			if (!empty($acl['noquery'])) {
1997
				$restrict .= ' noquery';
1998
			}
1999
			if (!empty($acl['nopeer'])) {
2000
				$restrict .= ' nopeer';
2001
			}
2002
			if (!empty($acl['noserve'])) {
2003
				$restrict .= ' noserve';
2004
			}
2005
			if (!empty($acl['notrap'])) {
2006
				$restrict .= ' notrap';
2007
			}
2008
			if (!empty($restrict)) {
2009
				$ntpcfg .= "\nrestrict {$restrict} ";
2010
			}
2011
		}
2012
	}
2013
	/* End Custom Access Restrictions */
2014

    
2015
	/* A leapseconds file is really only useful if this clock is stratum 1 */
2016
	$ntpcfg .= "\n";
2017
	if (!empty($config['ntpd']['leapsec'])) {
2018
		$leapsec .= base64_decode($config['ntpd']['leapsec']);
2019
		file_put_contents('/var/db/leap-seconds', $leapsec);
2020
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
2021
	}
2022

    
2023

    
2024
	if (empty($config['ntpd']['interface'])) {
2025
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface'])) {
2026
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
2027
		} else {
2028
			$interfaces = array();
2029
		}
2030
	} else {
2031
		$interfaces = explode(",", $config['ntpd']['interface']);
2032
	}
2033

    
2034
	if (is_array($interfaces) && count($interfaces)) {
2035
		$finterfaces = array();
2036
		$ntpcfg .= "interface ignore all\n";
2037
		$ntpcfg .= "interface ignore wildcard\n";
2038
		foreach ($interfaces as $interface) {
2039
			$interface = get_real_interface($interface);
2040
			if (!empty($interface)) {
2041
				$finterfaces[] = $interface;
2042
			}
2043
		}
2044
		foreach ($finterfaces as $interface) {
2045
			$ntpcfg .= "interface listen {$interface}\n";
2046
		}
2047
	}
2048

    
2049
	/* open configuration for writing or bail */
2050
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
2051
		log_error(sprintf(gettext("Could not open %s/ntpd.conf for writing"), $g['varetc_path']));
2052
		return;
2053
	}
2054

    
2055
	/* if /var/empty does not exist, create it */
2056
	if (!is_dir("/var/empty")) {
2057
		mkdir("/var/empty", 0555, true);
2058
	}
2059

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

    
2063
	// Note that we are starting up
2064
	log_error("NTPD is starting up.");
2065
	return;
2066
}
2067

    
2068
function system_halt() {
2069
	global $g;
2070

    
2071
	system_reboot_cleanup();
2072

    
2073
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
2074
}
2075

    
2076
function system_reboot() {
2077
	global $g;
2078

    
2079
	system_reboot_cleanup();
2080

    
2081
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
2082
}
2083

    
2084
function system_reboot_sync($reroot=false) {
2085
	global $g;
2086

    
2087
	if ($reroot) {
2088
		$args = " -r ";
2089
	}
2090

    
2091
	system_reboot_cleanup();
2092

    
2093
	mwexec("/etc/rc.reboot {$args} > /dev/null 2>&1");
2094
}
2095

    
2096
function system_reboot_cleanup() {
2097
	global $config, $g, $cpzone;
2098

    
2099
	mwexec("/usr/local/bin/beep.sh stop");
2100
	require_once("captiveportal.inc");
2101
	if (is_array($config['captiveportal'])) {
2102
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
2103
			if (!isset($cp['preservedb'])) {
2104
				/* send Accounting-Stop packet for all clients, termination cause 'Admin-Reboot' */
2105
				captiveportal_radius_stop_all(7); // Admin-Reboot
2106
				unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
2107
				captiveportal_free_dnrules();
2108
			}
2109
			/* Send Accounting-Off packet to the RADIUS server */
2110
			captiveportal_send_server_accounting('off');
2111
		}
2112
		/* Remove the pipe database */
2113
		unlink_if_exists("{$g['vardb_path']}/captiveportaldn.rules");
2114
	}
2115
	require_once("voucher.inc");
2116
	voucher_save_db_to_config();
2117
	require_once("pkg-utils.inc");
2118
	stop_packages();
2119
}
2120

    
2121
function system_do_shell_commands($early = 0) {
2122
	global $config, $g;
2123
	if (isset($config['system']['developerspew'])) {
2124
		$mt = microtime();
2125
		echo "system_do_shell_commands() being called $mt\n";
2126
	}
2127

    
2128
	if ($early) {
2129
		$cmdn = "earlyshellcmd";
2130
	} else {
2131
		$cmdn = "shellcmd";
2132
	}
2133

    
2134
	if (is_array($config['system'][$cmdn])) {
2135

    
2136
		/* *cmd is an array, loop through */
2137
		foreach ($config['system'][$cmdn] as $cmd) {
2138
			exec($cmd);
2139
		}
2140

    
2141
	} elseif ($config['system'][$cmdn] <> "") {
2142

    
2143
		/* execute single item */
2144
		exec($config['system'][$cmdn]);
2145

    
2146
	}
2147
}
2148

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

    
2156
	$dmesg = "";
2157
	$_gb = exec("/sbin/dmesg", $dmesg);
2158

    
2159
	/* find last copyright line (output from previous boots may be present) */
2160
	$lastcpline = 0;
2161

    
2162
	for ($i = 0; $i < count($dmesg); $i++) {
2163
		if (strstr($dmesg[$i], "Copyright (c) 1992-")) {
2164
			$lastcpline = $i;
2165
		}
2166
	}
2167

    
2168
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
2169
	if (!$fd) {
2170
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
2171
		return 1;
2172
	}
2173

    
2174
	for ($i = $lastcpline; $i < count($dmesg); $i++) {
2175
		fwrite($fd, $dmesg[$i] . "\n");
2176
	}
2177

    
2178
	fclose($fd);
2179
	unset($dmesg);
2180

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

    
2184
	return 0;
2185
}
2186

    
2187
function system_set_harddisk_standby() {
2188
	global $g, $config;
2189

    
2190
	if (isset($config['system']['developerspew'])) {
2191
		$mt = microtime();
2192
		echo "system_set_harddisk_standby() being called $mt\n";
2193
	}
2194

    
2195
	if (isset($config['system']['harddiskstandby'])) {
2196
		if (platform_booting()) {
2197
			echo gettext('Setting hard disk standby... ');
2198
		}
2199

    
2200
		$standby = $config['system']['harddiskstandby'];
2201
		// Check for a numeric value
2202
		if (is_numeric($standby)) {
2203
			// Get only suitable candidates for standby; using get_smart_drive_list()
2204
			// from utils.inc to get the list of drives.
2205
			$harddisks = get_smart_drive_list();
2206

    
2207
			// Since get_smart_drive_list() only matches ad|da|ada; lets put the check below
2208
			// just in case of some weird pfSense platform installs.
2209
			if (count($harddisks) > 0) {
2210
				// Iterate disks and run the camcontrol command for each
2211
				foreach ($harddisks as $harddisk) {
2212
					mwexec("/sbin/camcontrol standby {$harddisk} -t {$standby}");
2213
				}
2214
				if (platform_booting()) {
2215
					echo gettext("done.") . "\n";
2216
				}
2217
			} else if (platform_booting()) {
2218
				echo gettext("failed!") . "\n";
2219
			}
2220
		} else if (platform_booting()) {
2221
			echo gettext("failed!") . "\n";
2222
		}
2223
	}
2224
}
2225

    
2226
function system_setup_sysctl() {
2227
	global $config;
2228
	if (isset($config['system']['developerspew'])) {
2229
		$mt = microtime();
2230
		echo "system_setup_sysctl() being called $mt\n";
2231
	}
2232

    
2233
	activate_sysctls();
2234

    
2235
	if (isset($config['system']['sharednet'])) {
2236
		system_disable_arp_wrong_if();
2237
	}
2238
}
2239

    
2240
function system_disable_arp_wrong_if() {
2241
	global $config;
2242
	if (isset($config['system']['developerspew'])) {
2243
		$mt = microtime();
2244
		echo "system_disable_arp_wrong_if() being called $mt\n";
2245
	}
2246
	set_sysctl(array(
2247
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
2248
		"net.link.ether.inet.log_arp_movements" => "0"
2249
	));
2250
}
2251

    
2252
function system_enable_arp_wrong_if() {
2253
	global $config;
2254
	if (isset($config['system']['developerspew'])) {
2255
		$mt = microtime();
2256
		echo "system_enable_arp_wrong_if() being called $mt\n";
2257
	}
2258
	set_sysctl(array(
2259
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
2260
		"net.link.ether.inet.log_arp_movements" => "1"
2261
	));
2262
}
2263

    
2264
function enable_watchdog() {
2265
	global $config;
2266
	return;
2267
	$install_watchdog = false;
2268
	$supported_watchdogs = array("Geode");
2269
	$file = file_get_contents("/var/log/dmesg.boot");
2270
	foreach ($supported_watchdogs as $sd) {
2271
		if (stristr($file, "Geode")) {
2272
			$install_watchdog = true;
2273
		}
2274
	}
2275
	if ($install_watchdog == true) {
2276
		if (is_process_running("watchdogd")) {
2277
			mwexec("/usr/bin/killall watchdogd", true);
2278
		}
2279
		exec("/usr/sbin/watchdogd");
2280
	}
2281
}
2282

    
2283
function system_check_reset_button() {
2284
	global $g;
2285

    
2286
	$specplatform = system_identify_specific_platform();
2287

    
2288
	switch ($specplatform['name']) {
2289
		case 'SG-2220':
2290
			$binprefix = "RCC-DFF";
2291
			break;
2292
		case 'alix':
2293
		case 'wrap':
2294
		case 'FW7541':
2295
		case 'APU':
2296
		case 'RCC-VE':
2297
		case 'RCC':
2298
			$binprefix = $specplatform['name'];
2299
			break;
2300
		default:
2301
			return 0;
2302
	}
2303

    
2304
	$retval = mwexec("/usr/local/sbin/" . $binprefix . "resetbtn");
2305

    
2306
	if ($retval == 99) {
2307
		/* user has pressed reset button for 2 seconds -
2308
		   reset to factory defaults */
2309
		echo <<<EOD
2310

    
2311
***********************************************************************
2312
* Reset button pressed - resetting configuration to factory defaults. *
2313
* All additional packages installed will be removed                   *
2314
* The system will reboot after this completes.                        *
2315
***********************************************************************
2316

    
2317

    
2318
EOD;
2319

    
2320
		reset_factory_defaults();
2321
		system_reboot_sync();
2322
		exit(0);
2323
	}
2324

    
2325
	return 0;
2326
}
2327

    
2328
function system_get_serial() {
2329
	$platform = system_identify_specific_platform();
2330

    
2331
	unset($output);
2332
	if ($platform['name'] == 'Turbot Dual-E') {
2333
		$if_info = pfSense_get_interface_addresses('igb0');
2334
		if (!empty($if_info['hwaddr'])) {
2335
			$serial = str_replace(":", "", $if_info['hwaddr']);
2336
		}
2337
	} else {
2338
		foreach (array('system', 'planar', 'chassis') as $key) {
2339
			unset($output);
2340
			$_gb = exec("/bin/kenv -q smbios.{$key}.serial",
2341
			    $output);
2342
			if (!empty($output[0]) && $output[0] != "0123456789" &&
2343
			    preg_match('/^[\w\d]{10,16}$/', $output[0]) === 1) {
2344
				$serial = $output[0];
2345
				break;
2346
			}
2347
		}
2348
	}
2349

    
2350
	$vm_guest = get_single_sysctl('kern.vm_guest');
2351

    
2352
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2353
	    $vm_guest == 'none') {
2354
		return $serial;
2355
	}
2356

    
2357
	return "";
2358
}
2359

    
2360
function system_get_uniqueid() {
2361
	global $g;
2362

    
2363
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2364

    
2365
	if (empty($g['uniqueid'])) {
2366
		if (!file_exists($uniqueid_file)) {
2367
			mwexec("/usr/sbin/gnid > {$g['vardb_path']}/uniqueid " .
2368
			    "2>/dev/null");
2369
		}
2370
		if (file_exists($uniqueid_file)) {
2371
			$g['uniqueid'] = @file_get_contents($uniqueid_file);
2372
		}
2373
	}
2374

    
2375
	return ($g['uniqueid'] ?: '');
2376
}
2377

    
2378
/*
2379
 * attempt to identify the specific platform (for embedded systems)
2380
 * Returns an array with two elements:
2381
 * name => platform string (e.g. 'wrap', 'alix' etc.)
2382
 * descr => human-readable description (e.g. "PC Engines WRAP")
2383
 */
2384
function system_identify_specific_platform() {
2385
	global $g;
2386

    
2387
	$hw_model = get_single_sysctl('hw.model');
2388
	$hw_ncpu = get_single_sysctl('hw.ncpu');
2389

    
2390
	/* Try to guess from smbios strings */
2391
	unset($product);
2392
	unset($maker);
2393
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $product);
2394
	$_gb = exec('/bin/kenv -q smbios.system.maker 2>/dev/null', $maker);
2395
	switch ($product[0]) {
2396
		case 'FW7541':
2397
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2398
			break;
2399
		case 'APU':
2400
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2401
			break;
2402
		case 'RCC-VE':
2403
			$result = array();
2404
			$result['name'] = 'RCC-VE';
2405

    
2406
			/* Detect specific models */
2407
			if (!function_exists('does_interface_exist')) {
2408
				require_once("interfaces.inc");
2409
			}
2410
			if (!does_interface_exist('igb4')) {
2411
				$result['model'] = 'SG-2440';
2412
			} elseif (strpos($hw_model, "C2558") !== false) {
2413
				$result['model'] = 'SG-4860';
2414
			} elseif (strpos($hw_model, "C2758") !== false) {
2415
				$result['model'] = 'SG-8860';
2416
			} else {
2417
				$result['model'] = 'RCC-VE';
2418
			}
2419
			$result['descr'] = 'Netgate ' . $result['model'];
2420
			return $result;
2421
			break;
2422
		case 'DFFv2':
2423
			return (array('name' => 'SG-2220', 'descr' => 'Netgate SG-2220'));
2424
			break;
2425
		case 'RCC':
2426
			return (array('name' => 'RCC', 'descr' => 'Netgate XG-2758'));
2427
			break;
2428
		case 'SG-5100':
2429
			return (array('name' => 'SG-5100', 'descr' => 'Netgate SG-5100'));
2430
			break;
2431
		case 'Minnowboard Turbot D0 PLATFORM':
2432
			$result = array();
2433
			$result['name'] = 'Turbot Dual-E';
2434
			/* Detect specific model */
2435
			switch ($hw_ncpu) {
2436
			case '4':
2437
				$result['model'] = 'MBT-4220';
2438
				break;
2439
			case '2':
2440
				$result['model'] = 'MBT-2220';
2441
				break;
2442
			default:
2443
				$result['model'] = $result['name'];
2444
				break;
2445
			}
2446
			$result['descr'] = 'Netgate ' . $result['model'];
2447
			return $result;
2448
			break;
2449
		case 'SYS-5018A-FTN4':
2450
		case 'A1SAi':
2451
			if (strpos($hw_model, "C2558") !== false) {
2452
				return (array(
2453
				    'name' => 'C2558',
2454
				    'descr' => 'Super Micro C2558'));
2455
			} elseif (strpos($hw_model, "C2758") !== false) {
2456
				return (array(
2457
				    'name' => 'C2758',
2458
				    'descr' => 'Super Micro C2758'));
2459
			}
2460
			break;
2461
		case 'SYS-5018D-FN4T':
2462
			if (strpos($hw_model, "D-1541") !== false) {
2463
				return (array('name' => 'XG-1541', 'descr' => 'Super Micro XG-1541'));
2464
			} else {
2465
				return (array('name' => 'XG-1540', 'descr' => 'Super Micro XG-1540'));
2466
			}
2467
			break;
2468
		case 'apu2':
2469
		case 'APU2':
2470
			return (array('name' => 'apu2', 'descr' => 'PC Engines APU2'));
2471
			break;
2472
		case 'VirtualBox':
2473
			return (array('name' => 'VirtualBox', 'descr' => 'VirtualBox Virtual Machine'));
2474
			break;
2475
		case 'Virtual Machine':
2476
			if ($maker[0] == "Microsoft Corporation") {
2477
				return (array('name' => 'Hyper-V', 'descr' => 'Hyper-V Virtual Machine'));
2478
			}
2479
			break;
2480
		case 'VMware Virtual Platform':
2481
			if ($maker[0] == "VMware, Inc.") {
2482
				return (array('name' => 'VMware', 'descr' => 'VMware Virtual Machine'));
2483
			}
2484
			break;
2485
	}
2486

    
2487
	$_gb = exec('/bin/kenv -q smbios.planar.product 2>/dev/null',
2488
	    $planar_product);
2489
	if (isset($planar_product[0]) &&
2490
	    $planar_product[0] == 'X10SDV-8C-TLN4F+') {
2491
		return array('name' => 'XG-1537', 'descr' => 'Super Micro XG-1537');
2492
	}
2493

    
2494
	if (strpos($hw_model, "PC Engines WRAP") !== false) {
2495
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
2496
	}
2497

    
2498
	if (strpos($hw_model, "PC Engines ALIX") !== false) {
2499
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2500
	}
2501

    
2502
	if (preg_match("/Soekris net45../", $hw_model, $matches)) {
2503
		return array('name' => 'net45xx', 'descr' => $matches[0]);
2504
	}
2505

    
2506
	if (preg_match("/Soekris net48../", $hw_model, $matches)) {
2507
		return array('name' => 'net48xx', 'descr' => $matches[0]);
2508
	}
2509

    
2510
	if (preg_match("/Soekris net55../", $hw_model, $matches)) {
2511
		return array('name' => 'net55xx', 'descr' => $matches[0]);
2512
	}
2513

    
2514
	unset($hw_model);
2515

    
2516
	$dmesg_boot = system_get_dmesg_boot();
2517
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
2518
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2519
	}
2520
	unset($dmesg_boot);
2521

    
2522
	return array('name' => $g['platform'], 'descr' => $g['platform']);
2523
}
2524

    
2525
function system_get_dmesg_boot() {
2526
	global $g;
2527

    
2528
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2529
}
2530

    
2531
function system_get_arp_table($resolve_hostnames = false) {
2532
	$params="-a";
2533
	if (!$resolve_hostnames) {
2534
		$params .= "n";
2535
	}
2536

    
2537
	$arp_table = array();
2538
	$_gb = exec("/usr/sbin/arp --libxo json {$params}", $rawdata, $rc);
2539
	if ($rc == 0) {
2540
		$arp_table = json_decode(implode(" ", $rawdata),
2541
		    JSON_OBJECT_AS_ARRAY);
2542
		if ($rc == 0) {
2543
			$arp_table = $arp_table['arp']['arp-cache'];
2544
		}
2545
	}
2546

    
2547
	return $arp_table;
2548
}
2549

    
2550
?>
(49-49/60)