Project

General

Profile

Download (66.5 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * system.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2004-2013 BSD Perimeter
7
 * Copyright (c) 2013-2016 Electric Sheep Fencing
8
 * Copyright (c) 2014-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
	} elseif (isvalidpid($pidfile)) {
626
		sigkillbypid($pidfile, "TERM");
627
		@unlink($pidfile);
628
	}
629
}
630

    
631
function system_get_dhcpleases() {
632
	global $config, $g;
633

    
634
	$leases = array();
635
	$leases['lease'] = array();
636
	$leases['failover'] = array();
637

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

    
640
	if (!file_exists($leases_file)) {
641
		return $leases;
642
	}
643

    
644
	$leases_content = file($leases_file, FILE_IGNORE_NEW_LINES |
645
	    FILE_IGNORE_NEW_LINES);
646

    
647
	if ($leases_content === FALSE) {
648
		return $leases;
649
	}
650

    
651
	$arp_table = system_get_arp_table();
652

    
653
	$arpdata_ip = array();
654
	$arpdata_mac = array();
655
	foreach ($arp_table as $arp_entry) {
656
		if (isset($arpentry['incomplete'])) {
657
			continue;
658
		}
659
		$arpdata_ip[] = $arp_entry['ip-address'];
660
		$arpdata_mac[] = $arp_entry['mac-address'];
661
	}
662
	unset($arp_table);
663

    
664
	/*
665
	 * Translate these once so we don't do it over and over in the loops
666
	 * below.
667
	 */
668
	$online_string = gettext("online");
669
	$offline_string = gettext("offline");
670
	$active_string = gettext("active");
671
	$expired_string = gettext("expired");
672
	$reserved_string = gettext("reserved");
673
	$dynamic_string = gettext("dynamic");
674
	$static_string = gettext("static");
675

    
676
	$lease_regex = '/^lease\s+([^\s]+)\s+{$/';
677
	$starts_regex = '/^\s*(starts|ends)\s+\d+\s+([\d\/]+|never)\s*(|[\d:]*);$/';
678
	$binding_regex = '/^\s*binding\s+state\s+(.+);$/';
679
	$mac_regex = '/^\s*hardware\s+ethernet\s+(.+);$/';
680
	$hostname_regex = '/^\s*client-hostname\s+"(.+)";$/';
681

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

    
685
	$lease = false;
686
	$failover = false;
687
	$dedup_lease = false;
688
	$dedup_failover = false;
689
	foreach ($leases_content as $line) {
690
		/* Skip comments */
691
		if (preg_match('/^\s*(|#.*)$/', $line)) {
692
			continue;
693
		}
694

    
695
		if (preg_match('/}$/', $line)) {
696
			if ($lease) {
697
				if (empty($item['hostname'])) {
698
					$hostname = gethostbyaddr($item['ip']);
699
					if (!empty($hostname)) {
700
						$item['hostname'] = $hostname;
701
					}
702
				}
703
				$leases['lease'][] = $item;
704
				$lease = false;
705
				$dedup_lease = true;
706
			} else if ($failover) {
707
				$leases['failover'][] = $item;
708
				$failover = false;
709
				$dedup_failover = true;
710
			}
711
			continue;
712
		}
713

    
714
		if (preg_match($lease_regex, $line, $m)) {
715
			$lease = true;
716
			$item = array();
717
			$item['ip'] = $m[1];
718
			$item['type'] = $dynamic_string;
719
			continue;
720
		}
721

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

    
738
			if (preg_match($binding_regex, $line, $m)) {
739
				switch ($m[1]) {
740
					case "active":
741
						$item['act'] = $active_string;
742
						break;
743
					case "free":
744
						$item['act'] = $expired_string;
745
						$item['online'] =
746
						    $offline_string;
747
						break;
748
					case "backup":
749
						$item['act'] = $reserved_string;
750
						$item['online'] =
751
						    $offline_string;
752
						break;
753
				}
754
				continue;
755
			}
756

    
757
			if (preg_match($mac_regex, $line, $m) &&
758
			    is_macaddr($m[1])) {
759
				$item['mac'] = $m[1];
760

    
761
				if (in_array($item['ip'], $arpdata_ip)) {
762
					$item['online'] = $online_string;
763
				} else {
764
					$item['online'] = $offline_string;
765
				}
766
				continue;
767
			}
768

    
769
			if (preg_match($hostname_regex, $line, $m)) {
770
				$item['hostname'] = $m[1];
771
			}
772
		}
773

    
774
		if (preg_match($failover_regex, $line, $m)) {
775
			$failover = true;
776
			$item = array();
777
			$item['name'] = $m[1] . ' (' .
778
			    convert_friendly_interface_to_friendly_descr(
779
			    substr($m[1],5)) . ')';
780
			continue;
781
		}
782

    
783
		if ($failover && preg_match($state_regex, $line, $m)) {
784
			$item[$m[1] . 'state'] = $m[2];
785
			$item[$m[1] . 'date'] = dhcpd_date_adjust_gmt($m[3] .
786
			    ' ' . $m[4]);
787
			continue;
788
		}
789
	}
790

    
791
	foreach ($config['interfaces'] as $ifname => $ifarr) {
792
		if (!is_array($config['dhcpd'][$ifname]) ||
793
		    !is_array($config['dhcpd'][$ifname]['staticmap'])) {
794
			continue;
795
		}
796

    
797
		foreach ($config['dhcpd'][$ifname]['staticmap'] as $idx =>
798
		    $static) {
799
			if (empty($static['mac']) && empty($static['cid'])) {
800
				continue;
801
			}
802

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

    
824
	if ($dedup_lease) {
825
		$leases['lease'] = array_remove_duplicate($leases['lease'],
826
		    'ip');
827
	}
828
	if ($dedup_failover) {
829
		$leases['failover'] = array_remove_duplicate(
830
		    $leases['failover'], 'name');
831
		asort($leases['failover']);
832
	}
833

    
834
	return $leases;
835
}
836

    
837
function system_hostname_configure() {
838
	global $config, $g;
839
	if (isset($config['system']['developerspew'])) {
840
		$mt = microtime();
841
		echo "system_hostname_configure() being called $mt\n";
842
	}
843

    
844
	$syscfg = $config['system'];
845

    
846
	/* set hostname */
847
	$status = mwexec("/bin/hostname " .
848
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
849

    
850
	/* Setup host GUID ID.  This is used by ZFS. */
851
	mwexec("/etc/rc.d/hostid start");
852

    
853
	return $status;
854
}
855

    
856
function system_routing_configure($interface = "") {
857
	global $config, $g;
858

    
859
	if (isset($config['system']['developerspew'])) {
860
		$mt = microtime();
861
		echo "system_routing_configure() being called $mt\n";
862
	}
863

    
864
	$gateways_arr = return_gateways_array(false, true);
865
	foreach ($gateways_arr as $gateway) {
866
		// setup static interface routes for nonlocal gateways
867
		if (isset($gateway["nonlocalgateway"])) {
868
			$srgatewayip = $gateway['gateway'];
869
			$srinterfacegw = $gateway['interface'];
870
			if (is_ipaddr($srgatewayip) && !empty($srinterfacegw)) {
871
				$inet = (!is_ipaddrv4($srgatewayip) ? "-inet6" : "-inet");
872
				route_add_or_change("{$inet} {$srgatewayip} " .
873
				    "-iface {$srinterfacegw}");
874
			}
875
		}
876
	}
877

    
878
	$gateways_status = return_gateways_status(true);
879
	fixup_default_gateway("inet", $gateways_status, $gateways_arr);
880
	fixup_default_gateway("inet6", $gateways_status, $gateways_arr);
881

    
882
	system_staticroutes_configure($interface, false);
883

    
884
	return 0;
885
}
886

    
887
function system_staticroutes_configure($interface = "", $update_dns = false) {
888
	global $config, $g, $aliastable;
889

    
890
	$filterdns_list = array();
891

    
892
	$static_routes = get_staticroutes(false, true);
893
	if (count($static_routes)) {
894
		$gateways_arr = return_gateways_array(false, true);
895

    
896
		foreach ($static_routes as $rtent) {
897
			if (empty($gateways_arr[$rtent['gateway']])) {
898
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
899
				continue;
900
			}
901
			$gateway = $gateways_arr[$rtent['gateway']];
902
			if (!empty($interface) && $interface != $gateway['friendlyiface']) {
903
				continue;
904
			}
905

    
906
			$gatewayip = $gateway['gateway'];
907
			$interfacegw = $gateway['interface'];
908

    
909
			$blackhole = "";
910
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 4))) {
911
				$blackhole = "-blackhole";
912
			}
913

    
914
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network'])) {
915
				continue;
916
			}
917

    
918
			$dnscache = array();
919
			if ($update_dns === true) {
920
				if (is_subnet($rtent['network'])) {
921
					continue;
922
				}
923
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
924
				if (empty($dnscache)) {
925
					continue;
926
				}
927
			}
928

    
929
			if (is_subnet($rtent['network'])) {
930
				$ips = array($rtent['network']);
931
			} else {
932
				if (!isset($rtent['disabled'])) {
933
					$filterdns_list[] = $rtent['network'];
934
				}
935
				$ips = add_hostname_to_watch($rtent['network']);
936
			}
937

    
938
			foreach ($dnscache as $ip) {
939
				if (in_array($ip, $ips)) {
940
					continue;
941
				}
942
				mwexec("/sbin/route delete " . escapeshellarg($ip) . " " . escapeshellarg($gatewayip), true);
943
				if (isset($config['system']['route-debug'])) {
944
					$mt = microtime();
945
					log_error("ROUTING debug: $mt - route delete $ip $gatewayip ");
946
				}
947
			}
948

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

    
961
			foreach ($ips as $ip) {
962
				if (is_ipaddrv4($ip)) {
963
					$ip .= "/32";
964
				}
965
				// do NOT do the same check here on v6, is_ipaddrv6 returns true when including the CIDR mask. doing so breaks v6 routes
966

    
967
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
968

    
969
				$cmd = "{$inet} {$blackhole} {$ip} ";
970

    
971
				if (is_subnet($ip)) {
972
					if (is_ipaddr($gatewayip)) {
973
						if (is_linklocal($gatewayip) == "6" && !strpos($gatewayip, '%')) {
974
							// add interface scope for link local v6 routes
975
							$gatewayip .= "%$interfacegw";
976
						}
977
						route_add_or_change($cmd . $gatewayip);
978
					} else if (!empty($interfacegw)) {
979
						route_add_or_change($cmd . "-iface {$interfacegw}");
980
					}
981
				}
982
			}
983
		}
984
		unset($gateways_arr);
985
	}
986
	unset($static_routes);
987

    
988
	if ($update_dns === false) {
989
		if (count($filterdns_list)) {
990
			$interval = 60;
991
			$hostnames = "";
992
			array_unique($filterdns_list);
993
			foreach ($filterdns_list as $hostname) {
994
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
995
			}
996
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
997
			unset($hostnames);
998

    
999
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid")) {
1000
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
1001
			} else {
1002
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
1003
			}
1004
		} else {
1005
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
1006
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
1007
		}
1008
	}
1009
	unset($filterdns_list);
1010

    
1011
	return 0;
1012
}
1013

    
1014
function system_routing_enable() {
1015
	global $config, $g;
1016
	if (isset($config['system']['developerspew'])) {
1017
		$mt = microtime();
1018
		echo "system_routing_enable() being called $mt\n";
1019
	}
1020

    
1021
	set_sysctl(array(
1022
		"net.inet.ip.forwarding" => "1",
1023
		"net.inet6.ip6.forwarding" => "1"
1024
	));
1025

    
1026
	return;
1027
}
1028

    
1029
function system_webgui_create_certificate() {
1030
	global $config, $g, $cert_strict_values;
1031

    
1032
	init_config_arr(array('ca'));
1033
	$a_ca = &$config['ca'];
1034
	init_config_arr(array('cert'));
1035
	$a_cert = &$config['cert'];
1036
	log_error(gettext("Creating SSL/TLS Certificate for this host"));
1037

    
1038
	$cert = array();
1039
	$cert['refid'] = uniqid();
1040
	$cert['descr'] = sprintf(gettext("webConfigurator default (%s)"), $cert['refid']);
1041
	$cert_hostname = "{$config['system']['hostname']}-{$cert['refid']}";
1042

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

    
1057
	$a_cert[] = $cert;
1058
	$config['system']['webgui']['ssl-certref'] = $cert['refid'];
1059
	write_config(sprintf(gettext("Generated new self-signed SSL/TLS certificate for HTTPS (%s)"), $cert['refid']));
1060
	return $cert;
1061
}
1062

    
1063
function system_webgui_start() {
1064
	global $config, $g;
1065

    
1066
	if (platform_booting()) {
1067
		echo gettext("Starting webConfigurator...");
1068
	}
1069

    
1070
	chdir($g['www_path']);
1071

    
1072
	/* defaults */
1073
	$portarg = "80";
1074
	$crt = "";
1075
	$key = "";
1076
	$ca = "";
1077

    
1078
	/* non-standard port? */
1079
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "") {
1080
		$portarg = "{$config['system']['webgui']['port']}";
1081
	}
1082

    
1083
	if ($config['system']['webgui']['protocol'] == "https") {
1084
		// Ensure that we have a webConfigurator CERT
1085
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
1086
		if (!is_array($cert) || !$cert['crt'] || !$cert['prv']) {
1087
			$cert = system_webgui_create_certificate();
1088
		}
1089
		$crt = base64_decode($cert['crt']);
1090
		$key = base64_decode($cert['prv']);
1091

    
1092
		if (!$config['system']['webgui']['port']) {
1093
			$portarg = "443";
1094
		}
1095
		$ca = ca_chain($cert);
1096
		$hsts = isset($config['system']['webgui']['disablehsts']) ? false : true;
1097
	}
1098

    
1099
	/* generate nginx configuration */
1100
	system_generate_nginx_config("{$g['varetc_path']}/nginx-webConfigurator.conf",
1101
		$crt, $key, $ca, "nginx-webConfigurator.pid", $portarg, "/usr/local/www/",
1102
		"cert.crt", "cert.key", false, $hsts);
1103

    
1104
	/* kill any running nginx */
1105
	killbypid("{$g['varrun_path']}/nginx-webConfigurator.pid");
1106

    
1107
	sleep(1);
1108

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

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

    
1114
	if (platform_booting()) {
1115
		if ($res == 0) {
1116
			echo gettext("done.") . "\n";
1117
		} else {
1118
			echo gettext("failed!") . "\n";
1119
		}
1120
	}
1121

    
1122
	return $res;
1123
}
1124

    
1125
function get_dns_nameservers($add_v6_brackets = false) {
1126
	global $config;
1127

    
1128
	$dns_nameservers = array();
1129

    
1130
	if (isset($config['system']['developerspew'])) {
1131
		$mt = microtime();
1132
		echo "get_dns_nameservers() being called $mt\n";
1133
	}
1134

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

    
1180
function system_generate_nginx_config($filename,
1181
	$cert,
1182
	$key,
1183
	$ca,
1184
	$pid_file,
1185
	$port = 80,
1186
	$document_root = "/usr/local/www/",
1187
	$cert_location = "cert.crt",
1188
	$key_location = "cert.key",
1189
	$captive_portal = false,
1190
	$hsts = true) {
1191

    
1192
	global $config, $g;
1193

    
1194
	if (isset($config['system']['developerspew'])) {
1195
		$mt = microtime();
1196
		echo "system_generate_nginx_config() being called $mt\n";
1197
	}
1198

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

    
1220
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1221
		if (empty($maxprocperip)) {
1222
			$maxprocperip = 10;
1223
		}
1224
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1225
	}
1226

    
1227
	if (empty($port)) {
1228
		$nginx_port = "80";
1229
	} else {
1230
		$nginx_port = $port;
1231
	}
1232

    
1233
	$memory = get_memory();
1234
	$realmem = $memory[1];
1235

    
1236
	// Determine web GUI process settings and take into account low memory systems
1237
	if ($realmem < 255) {
1238
		$max_procs = 1;
1239
	} else {
1240
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
1241
	}
1242

    
1243
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM
1244
	if ($captive_portal !== false) {
1245
		if ($realmem > 135 and $realmem < 256) {
1246
			$max_procs += 1; // 2 worker processes
1247
		} else if ($realmem > 255 and $realmem < 513) {
1248
			$max_procs += 2; // 3 worker processes
1249
		} else if ($realmem > 512) {
1250
			$max_procs += 4; // 6 worker processes
1251
		}
1252
	}
1253

    
1254
	$nginx_config = <<<EOD
1255
#
1256
# nginx configuration file
1257

    
1258
pid {$g['varrun_path']}/{$pid_file};
1259

    
1260
user  root wheel;
1261
worker_processes  {$max_procs};
1262

    
1263
EOD;
1264

    
1265
	/* Disable file logging */
1266
	$nginx_config .= "error_log /dev/null;\n";
1267
	if (!isset($config['syslog']['nolognginx'])) {
1268
		/* Send nginx error log to syslog */
1269
		$nginx_config .= "error_log  syslog:server=unix:/var/run/log,facility=local5;\n";
1270
	}
1271

    
1272
	$nginx_config .= <<<EOD
1273

    
1274
events {
1275
    worker_connections  1024;
1276
}
1277

    
1278
http {
1279
	include       /usr/local/etc/nginx/mime.types;
1280
	default_type  application/octet-stream;
1281
	add_header X-Frame-Options SAMEORIGIN;
1282
	server_tokens off;
1283

    
1284
	sendfile        on;
1285

    
1286
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1287

    
1288
EOD;
1289

    
1290
	if ($captive_portal !== false) {
1291
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1292
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1293
	} else {
1294
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1295
	}
1296

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

    
1337
	$nginx_config .= <<<EOD
1338

    
1339
		client_max_body_size 200m;
1340

    
1341
		gzip on;
1342
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
1343

    
1344

    
1345
EOD;
1346

    
1347
	if ($captive_portal !== false) {
1348
		$nginx_config .= <<<EOD
1349
$captive_portal_maxprocperip
1350
$cp_hostcheck
1351
$cp_rewrite
1352
		log_not_found off;
1353

    
1354
EOD;
1355

    
1356
	}
1357

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

    
1392
EOD;
1393

    
1394
	$cert = str_replace("\r", "", $cert);
1395
	$key = str_replace("\r", "", $key);
1396

    
1397
	$cert = str_replace("\n\n", "\n", $cert);
1398
	$key = str_replace("\n\n", "\n", $key);
1399

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

    
1424
	// Add HTTP to HTTPS redirect
1425
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1426
		if ($nginx_port != "443") {
1427
			$redirectport = ":{$nginx_port}";
1428
		}
1429
		$nginx_config .= <<<EOD
1430
	server {
1431
		listen 80;
1432
		listen [::]:80;
1433
		return 301 https://\$http_host$redirectport\$request_uri;
1434
	}
1435

    
1436
EOD;
1437
	}
1438

    
1439
	$nginx_config .= "}\n";
1440

    
1441
	$fd = fopen("{$filename}", "w");
1442
	if (!$fd) {
1443
		printf(gettext('Error: cannot open %1$s in system_generate_nginx_config().%2$s'), $filename, "\n");
1444
		return 1;
1445
	}
1446
	fwrite($fd, $nginx_config);
1447
	fclose($fd);
1448

    
1449
	/* nginx will fail to start if this directory does not exist. */
1450
	safe_mkdir("/var/tmp/nginx/");
1451

    
1452
	return 0;
1453

    
1454
}
1455

    
1456
function system_get_timezone_list() {
1457
	global $g;
1458

    
1459
	$file_list = array_merge(
1460
		glob("/usr/share/zoneinfo/[A-Z]*"),
1461
		glob("/usr/share/zoneinfo/*/*"),
1462
		glob("/usr/share/zoneinfo/*/*/*")
1463
	);
1464

    
1465
	if (empty($file_list)) {
1466
		$file_list[] = $g['default_timezone'];
1467
	} else {
1468
		/* Remove directories from list */
1469
		$file_list = array_filter($file_list, function($v) {
1470
			return !is_dir($v);
1471
		});
1472
	}
1473

    
1474
	/* Remove directory prefix */
1475
	$file_list = str_replace('/usr/share/zoneinfo/', '', $file_list);
1476

    
1477
	sort($file_list);
1478

    
1479
	return $file_list;
1480
}
1481

    
1482
function system_timezone_configure() {
1483
	global $config, $g;
1484
	if (isset($config['system']['developerspew'])) {
1485
		$mt = microtime();
1486
		echo "system_timezone_configure() being called $mt\n";
1487
	}
1488

    
1489
	$syscfg = $config['system'];
1490

    
1491
	if (platform_booting()) {
1492
		echo gettext("Setting timezone...");
1493
	}
1494

    
1495
	/* extract appropriate timezone file */
1496
	$timezone = (isset($syscfg['timezone']) ? $syscfg['timezone'] : $g['default_timezone']);
1497
	/* DO NOT remove \n otherwise tzsetup will fail */
1498
	@file_put_contents("/var/db/zoneinfo", $timezone . "\n");
1499
	mwexec("/usr/sbin/tzsetup -r");
1500

    
1501
	if (platform_booting()) {
1502
		echo gettext("done.") . "\n";
1503
	}
1504
}
1505

    
1506
/* Generate list of possible NTP poll values
1507
 * https://redmine.pfsense.org/issues/9439 */
1508
global $ntp_poll_min_value, $ntp_poll_max_value;
1509
global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
1510
global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
1511
global $ntp_poll_min_default, $ntp_poll_max_default;
1512
$ntp_poll_min_value = 4;
1513
$ntp_poll_max_value = 17;
1514
$ntp_poll_min_default_gps = 4;
1515
$ntp_poll_max_default_gps = 4;
1516
$ntp_poll_min_default_pps = 4;
1517
$ntp_poll_max_default_pps = 4;
1518
$ntp_poll_min_default = 'omit';
1519
$ntp_poll_max_default = 9;
1520

    
1521
function system_ntp_poll_values() {
1522
	global $ntp_poll_min_value, $ntp_poll_max_value;
1523
	$poll_values = array("" => gettext('Default'));
1524

    
1525
	for ($i = $ntp_poll_min_value; $i <= $ntp_poll_max_value; $i++) {
1526
		$sec = 2 ** $i;
1527
		$poll_values[$i] = $i . ': ' . number_format($sec) . ' ' . gettext('seconds') .
1528
					' (' . convert_seconds_to_dhms($sec) . ')';
1529
	}
1530

    
1531
	$poll_values['omit'] = gettext('Omit (Do not set)');
1532
	return $poll_values;
1533
}
1534

    
1535
function system_ntp_fixup_poll_value($type, $configvalue, $default) {
1536
	$pollstring = "";
1537

    
1538
	if (empty($configvalue)) {
1539
		$configvalue = $default;
1540
	}
1541

    
1542
	if ($configvalue != 'omit') {
1543
		$pollstring = " {$type} {$configvalue}";
1544
	}
1545

    
1546
	return $pollstring;
1547
}
1548

    
1549
function system_ntp_setup_gps($serialport) {
1550
	global $config, $g;
1551
	$gps_device = '/dev/gps0';
1552
	$serialport = '/dev/'.$serialport;
1553

    
1554
	if (!file_exists($serialport)) {
1555
		return false;
1556
	}
1557

    
1558
	// Create symlink that ntpd requires
1559
	unlink_if_exists($gps_device);
1560
	@symlink($serialport, $gps_device);
1561

    
1562
	$gpsbaud = '4800';
1563
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['speed'])) {
1564
		switch ($config['ntpd']['gps']['speed']) {
1565
			case '16':
1566
				$gpsbaud = '9600';
1567
				break;
1568
			case '32':
1569
				$gpsbaud = '19200';
1570
				break;
1571
			case '48':
1572
				$gpsbaud = '38400';
1573
				break;
1574
			case '64':
1575
				$gpsbaud = '57600';
1576
				break;
1577
			case '80':
1578
				$gpsbaud = '115200';
1579
				break;
1580
		}
1581
	}
1582

    
1583
	/* Configure the serial port for raw IO and set the speed */
1584
	mwexec("stty -f {$serialport}.init raw speed {$gpsbaud}");
1585

    
1586
	/* Send the following to the GPS port to initialize the GPS */
1587
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
1588
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
1589
	} else {
1590
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1591
	}
1592

    
1593
	/* XXX: Why not file_put_contents to the device */
1594
	@file_put_contents('/tmp/gps.init', $gps_init);
1595
	mwexec("cat /tmp/gps.init > {$serialport}");
1596

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

    
1602

    
1603
	return true;
1604
}
1605

    
1606
function system_ntp_setup_pps($serialport) {
1607
	global $config, $g;
1608

    
1609
	$pps_device = '/dev/pps0';
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($pps_device);
1618
	@symlink($serialport, $pps_device);
1619

    
1620

    
1621
	return true;
1622
}
1623

    
1624

    
1625
function system_ntp_configure() {
1626
	global $config, $g;
1627
	global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
1628
	global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
1629
	global $ntp_poll_min_default, $ntp_poll_max_default;
1630

    
1631
	$driftfile = "/var/db/ntpd.drift";
1632
	$statsdir = "/var/log/ntp";
1633
	$gps_device = '/dev/gps0';
1634

    
1635
	safe_mkdir($statsdir);
1636

    
1637
	if (!is_array($config['ntpd'])) {
1638
		$config['ntpd'] = array();
1639
	}
1640

    
1641
	$ntpcfg = "# \n";
1642
	$ntpcfg .= "# pfSense ntp configuration file \n";
1643
	$ntpcfg .= "# \n\n";
1644
	$ntpcfg .= "tinker panic 0 \n";
1645

    
1646
	/* Add Orphan mode */
1647
	$ntpcfg .= "# Orphan mode stratum\n";
1648
	$ntpcfg .= 'tos orphan ';
1649
	if (!empty($config['ntpd']['orphan'])) {
1650
		$ntpcfg .= $config['ntpd']['orphan'];
1651
	} else {
1652
		$ntpcfg .= '12';
1653
	}
1654
	$ntpcfg .= "\n";
1655

    
1656
	/* Add PPS configuration */
1657
	if (is_array($config['ntpd']['pps']) && !empty($config['ntpd']['pps']['port']) &&
1658
	    file_exists('/dev/'.$config['ntpd']['pps']['port']) &&
1659
	    system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
1660
		$ntpcfg .= "\n";
1661
		$ntpcfg .= "# PPS Setup\n";
1662
		$ntpcfg .= 'server 127.127.22.0';
1663
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', $config['ntpd']['pps']['ppsminpoll'], $ntp_poll_min_default_pps);
1664
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', $config['ntpd']['pps']['ppsmaxpoll'], $ntp_poll_max_default_pps);
1665
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
1666
			$ntpcfg .= ' prefer';
1667
		}
1668
		if (!empty($config['ntpd']['pps']['noselect'])) {
1669
			$ntpcfg .= ' noselect ';
1670
		}
1671
		$ntpcfg .= "\n";
1672
		$ntpcfg .= 'fudge 127.127.22.0';
1673
		if (!empty($config['ntpd']['pps']['fudge1'])) {
1674
			$ntpcfg .= ' time1 ';
1675
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
1676
		}
1677
		if (!empty($config['ntpd']['pps']['flag2'])) {
1678
			$ntpcfg .= ' flag2 1';
1679
		}
1680
		if (!empty($config['ntpd']['pps']['flag3'])) {
1681
			$ntpcfg .= ' flag3 1';
1682
		} else {
1683
			$ntpcfg .= ' flag3 0';
1684
		}
1685
		if (!empty($config['ntpd']['pps']['flag4'])) {
1686
			$ntpcfg .= ' flag4 1';
1687
		}
1688
		if (!empty($config['ntpd']['pps']['refid'])) {
1689
			$ntpcfg .= ' refid ';
1690
			$ntpcfg .= $config['ntpd']['pps']['refid'];
1691
		}
1692
		$ntpcfg .= "\n";
1693
	}
1694
	/* End PPS configuration */
1695

    
1696
	/* Add GPS configuration */
1697
	if (is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['port']) &&
1698
	    file_exists('/dev/'.$config['ntpd']['gps']['port']) &&
1699
	    system_ntp_setup_gps($config['ntpd']['gps']['port'])) {
1700
		$ntpcfg .= "\n";
1701
		$ntpcfg .= "# GPS Setup\n";
1702
		$ntpcfg .= 'server 127.127.20.0 mode ';
1703
		if (!empty($config['ntpd']['gps']['nmea']) || !empty($config['ntpd']['gps']['speed']) || !empty($config['ntpd']['gps']['subsec']) || !empty($config['ntpd']['gps']['processpgrmf'])) {
1704
			if (!empty($config['ntpd']['gps']['nmea'])) {
1705
				$ntpmode = (int) $config['ntpd']['gps']['nmea'];
1706
			}
1707
			if (!empty($config['ntpd']['gps']['speed'])) {
1708
				$ntpmode += (int) $config['ntpd']['gps']['speed'];
1709
			}
1710
			if (!empty($config['ntpd']['gps']['subsec'])) {
1711
				$ntpmode += 128;
1712
			}
1713
			if (!empty($config['ntpd']['gps']['processpgrmf'])) {
1714
				$ntpmode += 256;
1715
			}
1716
			$ntpcfg .= (string) $ntpmode;
1717
		} else {
1718
			$ntpcfg .= '0';
1719
		}
1720
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', $config['ntpd']['gps']['gpsminpoll'], $ntp_poll_min_default_gps);
1721
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', $config['ntpd']['gps']['gpsmaxpoll'], $ntp_poll_max_default_gps);
1722

    
1723
		if (empty($config['ntpd']['gps']['prefer'])) { /*note: this one works backwards */
1724
			$ntpcfg .= ' prefer';
1725
		}
1726
		if (!empty($config['ntpd']['gps']['noselect'])) {
1727
			$ntpcfg .= ' noselect ';
1728
		}
1729
		$ntpcfg .= "\n";
1730
		$ntpcfg .= 'fudge 127.127.20.0';
1731
		if (!empty($config['ntpd']['gps']['fudge1'])) {
1732
			$ntpcfg .= ' time1 ';
1733
			$ntpcfg .= $config['ntpd']['gps']['fudge1'];
1734
		}
1735
		if (!empty($config['ntpd']['gps']['fudge2'])) {
1736
			$ntpcfg .= ' time2 ';
1737
			$ntpcfg .= $config['ntpd']['gps']['fudge2'];
1738
		}
1739
		if (!empty($config['ntpd']['gps']['flag1'])) {
1740
			$ntpcfg .= ' flag1 1';
1741
		} else {
1742
			$ntpcfg .= ' flag1 0';
1743
		}
1744
		if (!empty($config['ntpd']['gps']['flag2'])) {
1745
			$ntpcfg .= ' flag2 1';
1746
		}
1747
		if (!empty($config['ntpd']['gps']['flag3'])) {
1748
			$ntpcfg .= ' flag3 1';
1749
		} else {
1750
			$ntpcfg .= ' flag3 0';
1751
		}
1752
		if (!empty($config['ntpd']['gps']['flag4'])) {
1753
			$ntpcfg .= ' flag4 1';
1754
		}
1755
		if (!empty($config['ntpd']['gps']['refid'])) {
1756
			$ntpcfg .= ' refid ';
1757
			$ntpcfg .= $config['ntpd']['gps']['refid'];
1758
		}
1759
		if (!empty($config['ntpd']['gps']['stratum'])) {
1760
			$ntpcfg .= ' stratum ';
1761
			$ntpcfg .= $config['ntpd']['gps']['stratum'];
1762
		}
1763
		$ntpcfg .= "\n";
1764
	} elseif (is_array($config['ntpd']) && !empty($config['ntpd']['gpsport']) &&
1765
	    file_exists('/dev/'.$config['ntpd']['gpsport']) &&
1766
	    system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1767
		/* This handles a 2.1 and earlier config */
1768
		$ntpcfg .= "# GPS Setup\n";
1769
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1770
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1771
		// Fall back to local clock if GPS is out of sync?
1772
		$ntpcfg .= "server 127.127.1.0\n";
1773
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1774
	}
1775
	/* End GPS configuration */
1776
	$auto_pool_suffix = "pool.ntp.org";
1777
	$have_pools = false;
1778
	$ntpcfg .= "\n\n# Upstream Servers\n";
1779
	/* foreach through ntp servers and write out to ntpd.conf */
1780
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1781
		if ((substr_compare($ts, $auto_pool_suffix, strlen($ts) - strlen($auto_pool_suffix), strlen($auto_pool_suffix)) === 0)
1782
		    || substr_count($config['ntpd']['ispool'], $ts)) {
1783
			$ntpcfg .= 'pool ';
1784
			$have_pools = true;
1785
		} else {
1786
			$ntpcfg .= 'server ';
1787
		}
1788

    
1789
		$ntpcfg .= "{$ts} iburst";
1790

    
1791
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', $config['ntpd']['ntpminpoll'], $ntp_poll_min_default);
1792
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', $config['ntpd']['ntpmaxpoll'], $ntp_poll_max_default);
1793

    
1794
		if (substr_count($config['ntpd']['prefer'], $ts)) {
1795
			$ntpcfg .= ' prefer';
1796
		}
1797
		if (substr_count($config['ntpd']['noselect'], $ts)) {
1798
			$ntpcfg .= ' noselect';
1799
		}
1800
		$ntpcfg .= "\n";
1801
	}
1802
	unset($ts);
1803

    
1804
	$ntpcfg .= "\n\n";
1805
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
1806
		$ntpcfg .= "enable stats\n";
1807
		$ntpcfg .= 'statistics';
1808
		if (!empty($config['ntpd']['clockstats'])) {
1809
			$ntpcfg .= ' clockstats';
1810
		}
1811
		if (!empty($config['ntpd']['loopstats'])) {
1812
			$ntpcfg .= ' loopstats';
1813
		}
1814
		if (!empty($config['ntpd']['peerstats'])) {
1815
			$ntpcfg .= ' peerstats';
1816
		}
1817
		$ntpcfg .= "\n";
1818
	}
1819
	$ntpcfg .= "statsdir {$statsdir}\n";
1820
	$ntpcfg .= 'logconfig =syncall +clockall';
1821
	if (!empty($config['ntpd']['logpeer'])) {
1822
		$ntpcfg .= ' +peerall';
1823
	}
1824
	if (!empty($config['ntpd']['logsys'])) {
1825
		$ntpcfg .= ' +sysall';
1826
	}
1827
	$ntpcfg .= "\n";
1828
	$ntpcfg .= "driftfile {$driftfile}\n";
1829

    
1830
	/* Default Access restrictions */
1831
	$ntpcfg .= 'restrict default';
1832
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1833
		$ntpcfg .= ' kod limited';
1834
	}
1835
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1836
		$ntpcfg .= ' nomodify';
1837
	}
1838
	if (!empty($config['ntpd']['noquery'])) {
1839
		$ntpcfg .= ' noquery';
1840
	}
1841
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1842
		$ntpcfg .= ' nopeer';
1843
	}
1844
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1845
		$ntpcfg .= ' notrap';
1846
	}
1847
	if (!empty($config['ntpd']['noserve'])) {
1848
		$ntpcfg .= ' noserve';
1849
	}
1850
	$ntpcfg .= "\nrestrict -6 default";
1851
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1852
		$ntpcfg .= ' kod limited';
1853
	}
1854
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1855
		$ntpcfg .= ' nomodify';
1856
	}
1857
	if (!empty($config['ntpd']['noquery'])) {
1858
		$ntpcfg .= ' noquery';
1859
	}
1860
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1861
		$ntpcfg .= ' nopeer';
1862
	}
1863
	if (!empty($config['ntpd']['noserve'])) {
1864
		$ntpcfg .= ' noserve';
1865
	}
1866
	if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1867
		$ntpcfg .= ' notrap';
1868
	}
1869

    
1870
	/* Pools require "restrict source" and cannot contain "nopeer" and "noserve". */
1871
	if ($have_pools) {
1872
		$ntpcfg .= "\nrestrict source";
1873
		if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1874
			$ntpcfg .= ' kod limited';
1875
		}
1876
		if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1877
			$ntpcfg .= ' nomodify';
1878
		}
1879
		if (!empty($config['ntpd']['noquery'])) {
1880
			$ntpcfg .= ' noquery';
1881
		}
1882
		if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1883
			$ntpcfg .= ' notrap';
1884
		}
1885
	}
1886

    
1887
	/* Custom Access Restrictions */
1888
	if (is_array($config['ntpd']['restrictions']) && is_array($config['ntpd']['restrictions']['row'])) {
1889
		$networkacl = $config['ntpd']['restrictions']['row'];
1890
		foreach ($networkacl as $acl) {
1891
			$restrict = "";
1892
			if (is_ipaddrv6($acl['acl_network'])) {
1893
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask_v6($acl['mask']) . " ";
1894
			} elseif (is_ipaddrv4($acl['acl_network'])) {
1895
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask($acl['mask']) . " ";
1896
			} else {
1897
				continue;
1898
			}
1899
			if (!empty($acl['kod'])) {
1900
				$restrict .= ' kod limited';
1901
			}
1902
			if (!empty($acl['nomodify'])) {
1903
				$restrict .= ' nomodify';
1904
			}
1905
			if (!empty($acl['noquery'])) {
1906
				$restrict .= ' noquery';
1907
			}
1908
			if (!empty($acl['nopeer'])) {
1909
				$restrict .= ' nopeer';
1910
			}
1911
			if (!empty($acl['noserve'])) {
1912
				$restrict .= ' noserve';
1913
			}
1914
			if (!empty($acl['notrap'])) {
1915
				$restrict .= ' notrap';
1916
			}
1917
			if (!empty($restrict)) {
1918
				$ntpcfg .= "\nrestrict {$restrict} ";
1919
			}
1920
		}
1921
	}
1922
	/* End Custom Access Restrictions */
1923

    
1924
	/* A leapseconds file is really only useful if this clock is stratum 1 */
1925
	$ntpcfg .= "\n";
1926
	if (!empty($config['ntpd']['leapsec'])) {
1927
		$leapsec .= base64_decode($config['ntpd']['leapsec']);
1928
		file_put_contents('/var/db/leap-seconds', $leapsec);
1929
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
1930
	}
1931

    
1932

    
1933
	if (empty($config['ntpd']['interface'])) {
1934
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface'])) {
1935
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
1936
		} else {
1937
			$interfaces = array();
1938
		}
1939
	} else {
1940
		$interfaces = explode(",", $config['ntpd']['interface']);
1941
	}
1942

    
1943
	if (is_array($interfaces) && count($interfaces)) {
1944
		$finterfaces = array();
1945
		$ntpcfg .= "interface ignore all\n";
1946
		$ntpcfg .= "interface ignore wildcard\n";
1947
		foreach ($interfaces as $interface) {
1948
			$interface = get_real_interface($interface);
1949
			if (!empty($interface)) {
1950
				$finterfaces[] = $interface;
1951
			}
1952
		}
1953
		foreach ($finterfaces as $interface) {
1954
			$ntpcfg .= "interface listen {$interface}\n";
1955
		}
1956
	}
1957

    
1958
	/* open configuration for writing or bail */
1959
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
1960
		log_error(sprintf(gettext("Could not open %s/ntpd.conf for writing"), $g['varetc_path']));
1961
		return;
1962
	}
1963

    
1964
	/* if ntpd is running, kill it */
1965
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1966
		killbypid("{$g['varrun_path']}/ntpd.pid");
1967
	}
1968
	@unlink("{$g['varrun_path']}/ntpd.pid");
1969

    
1970
	/* if /var/empty does not exist, create it */
1971
	if (!is_dir("/var/empty")) {
1972
		mkdir("/var/empty", 0555, true);
1973
	}
1974

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

    
1978
	// Note that we are starting up
1979
	log_error("NTPD is starting up.");
1980
	return;
1981
}
1982

    
1983
function system_halt() {
1984
	global $g;
1985

    
1986
	system_reboot_cleanup();
1987

    
1988
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
1989
}
1990

    
1991
function system_reboot() {
1992
	global $g;
1993

    
1994
	system_reboot_cleanup();
1995

    
1996
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
1997
}
1998

    
1999
function system_reboot_sync($reroot=false) {
2000
	global $g;
2001

    
2002
	if ($reroot) {
2003
		$args = " -r ";
2004
	}
2005

    
2006
	system_reboot_cleanup();
2007

    
2008
	mwexec("/etc/rc.reboot {$args} > /dev/null 2>&1");
2009
}
2010

    
2011
function system_reboot_cleanup() {
2012
	global $config, $g, $cpzone;
2013

    
2014
	mwexec("/usr/local/bin/beep.sh stop");
2015
	require_once("captiveportal.inc");
2016
	if (is_array($config['captiveportal'])) {
2017
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
2018
			if (!isset($cp['preservedb'])) {
2019
				/* send Accounting-Stop packet for all clients, termination cause 'Admin-Reboot' */
2020
				captiveportal_radius_stop_all(7); // Admin-Reboot
2021
				unlink_if_exists("{$g['vardb_path']}/captiveportal{$cpzone}.db");
2022
				captiveportal_free_dnrules();
2023
			}
2024
			/* Send Accounting-Off packet to the RADIUS server */
2025
			captiveportal_send_server_accounting('off');
2026
		}
2027
		/* Remove the pipe database */
2028
		unlink_if_exists("{$g['vardb_path']}/captiveportaldn.rules");
2029
	}
2030
	require_once("voucher.inc");
2031
	voucher_save_db_to_config();
2032
	require_once("pkg-utils.inc");
2033
	stop_packages();
2034
}
2035

    
2036
function system_do_shell_commands($early = 0) {
2037
	global $config, $g;
2038
	if (isset($config['system']['developerspew'])) {
2039
		$mt = microtime();
2040
		echo "system_do_shell_commands() being called $mt\n";
2041
	}
2042

    
2043
	if ($early) {
2044
		$cmdn = "earlyshellcmd";
2045
	} else {
2046
		$cmdn = "shellcmd";
2047
	}
2048

    
2049
	if (is_array($config['system'][$cmdn])) {
2050

    
2051
		/* *cmd is an array, loop through */
2052
		foreach ($config['system'][$cmdn] as $cmd) {
2053
			exec($cmd);
2054
		}
2055

    
2056
	} elseif ($config['system'][$cmdn] <> "") {
2057

    
2058
		/* execute single item */
2059
		exec($config['system'][$cmdn]);
2060

    
2061
	}
2062
}
2063

    
2064
function system_dmesg_save() {
2065
	global $g;
2066
	if (isset($config['system']['developerspew'])) {
2067
		$mt = microtime();
2068
		echo "system_dmesg_save() being called $mt\n";
2069
	}
2070

    
2071
	$dmesg = "";
2072
	$_gb = exec("/sbin/dmesg", $dmesg);
2073

    
2074
	/* find last copyright line (output from previous boots may be present) */
2075
	$lastcpline = 0;
2076

    
2077
	for ($i = 0; $i < count($dmesg); $i++) {
2078
		if (strstr($dmesg[$i], "Copyright (c) 1992-")) {
2079
			$lastcpline = $i;
2080
		}
2081
	}
2082

    
2083
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
2084
	if (!$fd) {
2085
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
2086
		return 1;
2087
	}
2088

    
2089
	for ($i = $lastcpline; $i < count($dmesg); $i++) {
2090
		fwrite($fd, $dmesg[$i] . "\n");
2091
	}
2092

    
2093
	fclose($fd);
2094
	unset($dmesg);
2095

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

    
2099
	return 0;
2100
}
2101

    
2102
function system_set_harddisk_standby() {
2103
	global $g, $config;
2104

    
2105
	if (isset($config['system']['developerspew'])) {
2106
		$mt = microtime();
2107
		echo "system_set_harddisk_standby() being called $mt\n";
2108
	}
2109

    
2110
	if (isset($config['system']['harddiskstandby'])) {
2111
		if (platform_booting()) {
2112
			echo gettext('Setting hard disk standby... ');
2113
		}
2114

    
2115
		$standby = $config['system']['harddiskstandby'];
2116
		// Check for a numeric value
2117
		if (is_numeric($standby)) {
2118
			// Get only suitable candidates for standby; using get_smart_drive_list()
2119
			// from utils.inc to get the list of drives.
2120
			$harddisks = get_smart_drive_list();
2121

    
2122
			// Since get_smart_drive_list() only matches ad|da|ada; lets put the check below
2123
			// just in case of some weird pfSense platform installs.
2124
			if (count($harddisks) > 0) {
2125
				// Iterate disks and run the camcontrol command for each
2126
				foreach ($harddisks as $harddisk) {
2127
					mwexec("/sbin/camcontrol standby {$harddisk} -t {$standby}");
2128
				}
2129
				if (platform_booting()) {
2130
					echo gettext("done.") . "\n";
2131
				}
2132
			} else if (platform_booting()) {
2133
				echo gettext("failed!") . "\n";
2134
			}
2135
		} else if (platform_booting()) {
2136
			echo gettext("failed!") . "\n";
2137
		}
2138
	}
2139
}
2140

    
2141
function system_setup_sysctl() {
2142
	global $config;
2143
	if (isset($config['system']['developerspew'])) {
2144
		$mt = microtime();
2145
		echo "system_setup_sysctl() being called $mt\n";
2146
	}
2147

    
2148
	activate_sysctls();
2149

    
2150
	if (isset($config['system']['sharednet'])) {
2151
		system_disable_arp_wrong_if();
2152
	}
2153
}
2154

    
2155
function system_disable_arp_wrong_if() {
2156
	global $config;
2157
	if (isset($config['system']['developerspew'])) {
2158
		$mt = microtime();
2159
		echo "system_disable_arp_wrong_if() being called $mt\n";
2160
	}
2161
	set_sysctl(array(
2162
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
2163
		"net.link.ether.inet.log_arp_movements" => "0"
2164
	));
2165
}
2166

    
2167
function system_enable_arp_wrong_if() {
2168
	global $config;
2169
	if (isset($config['system']['developerspew'])) {
2170
		$mt = microtime();
2171
		echo "system_enable_arp_wrong_if() being called $mt\n";
2172
	}
2173
	set_sysctl(array(
2174
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
2175
		"net.link.ether.inet.log_arp_movements" => "1"
2176
	));
2177
}
2178

    
2179
function enable_watchdog() {
2180
	global $config;
2181
	return;
2182
	$install_watchdog = false;
2183
	$supported_watchdogs = array("Geode");
2184
	$file = file_get_contents("/var/log/dmesg.boot");
2185
	foreach ($supported_watchdogs as $sd) {
2186
		if (stristr($file, "Geode")) {
2187
			$install_watchdog = true;
2188
		}
2189
	}
2190
	if ($install_watchdog == true) {
2191
		if (is_process_running("watchdogd")) {
2192
			mwexec("/usr/bin/killall watchdogd", true);
2193
		}
2194
		exec("/usr/sbin/watchdogd");
2195
	}
2196
}
2197

    
2198
function system_check_reset_button() {
2199
	global $g;
2200

    
2201
	$specplatform = system_identify_specific_platform();
2202

    
2203
	switch ($specplatform['name']) {
2204
		case 'SG-2220':
2205
			$binprefix = "RCC-DFF";
2206
			break;
2207
		case 'alix':
2208
		case 'wrap':
2209
		case 'FW7541':
2210
		case 'APU':
2211
		case 'RCC-VE':
2212
		case 'RCC':
2213
			$binprefix = $specplatform['name'];
2214
			break;
2215
		default:
2216
			return 0;
2217
	}
2218

    
2219
	$retval = mwexec("/usr/local/sbin/" . $binprefix . "resetbtn");
2220

    
2221
	if ($retval == 99) {
2222
		/* user has pressed reset button for 2 seconds -
2223
		   reset to factory defaults */
2224
		echo <<<EOD
2225

    
2226
***********************************************************************
2227
* Reset button pressed - resetting configuration to factory defaults. *
2228
* All additional packages installed will be removed                   *
2229
* The system will reboot after this completes.                        *
2230
***********************************************************************
2231

    
2232

    
2233
EOD;
2234

    
2235
		reset_factory_defaults();
2236
		system_reboot_sync();
2237
		exit(0);
2238
	}
2239

    
2240
	return 0;
2241
}
2242

    
2243
function system_get_serial() {
2244
	$platform = system_identify_specific_platform();
2245

    
2246
	unset($output);
2247
	if ($platform['name'] == 'Turbot Dual-E') {
2248
		$if_info = pfSense_get_interface_addresses('igb0');
2249
		if (!empty($if_info['hwaddr'])) {
2250
			$serial = str_replace(":", "", $if_info['hwaddr']);
2251
		}
2252
	} else {
2253
		foreach (array('system', 'planar', 'chassis') as $key) {
2254
			unset($output);
2255
			$_gb = exec("/bin/kenv -q smbios.{$key}.serial",
2256
			    $output);
2257
			if (!empty($output[0]) && $output[0] != "0123456789" &&
2258
			    preg_match('/^[\w\d]{10,16}$/', $output[0]) === 1) {
2259
				$serial = $output[0];
2260
				break;
2261
			}
2262
		}
2263
	}
2264

    
2265
	$vm_guest = get_single_sysctl('kern.vm_guest');
2266

    
2267
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2268
	    $vm_guest == 'none') {
2269
		return $serial;
2270
	}
2271

    
2272
	return "";
2273
}
2274

    
2275
function system_get_uniqueid() {
2276
	global $g;
2277

    
2278
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2279

    
2280
	if (empty($g['uniqueid'])) {
2281
		if (!file_exists($uniqueid_file)) {
2282
			mwexec("/usr/sbin/gnid > {$g['vardb_path']}/uniqueid " .
2283
			    "2>/dev/null");
2284
		}
2285
		if (file_exists($uniqueid_file)) {
2286
			$g['uniqueid'] = @file_get_contents($uniqueid_file);
2287
		}
2288
	}
2289

    
2290
	return ($g['uniqueid'] ?: '');
2291
}
2292

    
2293
/*
2294
 * attempt to identify the specific platform (for embedded systems)
2295
 * Returns an array with two elements:
2296
 * name => platform string (e.g. 'wrap', 'alix' etc.)
2297
 * descr => human-readable description (e.g. "PC Engines WRAP")
2298
 */
2299
function system_identify_specific_platform() {
2300
	global $g;
2301

    
2302
	$hw_model = get_single_sysctl('hw.model');
2303
	$hw_ncpu = get_single_sysctl('hw.ncpu');
2304

    
2305
	/* Try to guess from smbios strings */
2306
	unset($product);
2307
	unset($maker);
2308
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $product);
2309
	$_gb = exec('/bin/kenv -q smbios.system.maker 2>/dev/null', $maker);
2310
	switch ($product[0]) {
2311
		case 'FW7541':
2312
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2313
			break;
2314
		case 'APU':
2315
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2316
			break;
2317
		case 'RCC-VE':
2318
			$result = array();
2319
			$result['name'] = 'RCC-VE';
2320

    
2321
			/* Detect specific models */
2322
			if (!function_exists('does_interface_exist')) {
2323
				require_once("interfaces.inc");
2324
			}
2325
			if (!does_interface_exist('igb4')) {
2326
				$result['model'] = 'SG-2440';
2327
			} elseif (strpos($hw_model, "C2558") !== false) {
2328
				$result['model'] = 'SG-4860';
2329
			} elseif (strpos($hw_model, "C2758") !== false) {
2330
				$result['model'] = 'SG-8860';
2331
			} else {
2332
				$result['model'] = 'RCC-VE';
2333
			}
2334
			$result['descr'] = 'Netgate ' . $result['model'];
2335
			return $result;
2336
			break;
2337
		case 'DFFv2':
2338
			return (array('name' => 'SG-2220', 'descr' => 'Netgate SG-2220'));
2339
			break;
2340
		case 'RCC':
2341
			return (array('name' => 'RCC', 'descr' => 'Netgate XG-2758'));
2342
			break;
2343
		case 'SG-5100':
2344
			return (array('name' => 'SG-5100', 'descr' => 'Netgate SG-5100'));
2345
			break;
2346
		case 'Minnowboard Turbot D0 PLATFORM':
2347
			$result = array();
2348
			$result['name'] = 'Turbot Dual-E';
2349
			/* Detect specific model */
2350
			switch ($hw_ncpu) {
2351
			case '4':
2352
				$result['model'] = 'MBT-4220';
2353
				break;
2354
			case '2':
2355
				$result['model'] = 'MBT-2220';
2356
				break;
2357
			default:
2358
				$result['model'] = $result['name'];
2359
				break;
2360
			}
2361
			$result['descr'] = 'Netgate ' . $result['model'];
2362
			return $result;
2363
			break;
2364
		case 'SYS-5018A-FTN4':
2365
		case 'A1SAi':
2366
			if (strpos($hw_model, "C2558") !== false) {
2367
				return (array(
2368
				    'name' => 'C2558',
2369
				    'descr' => 'Super Micro C2558'));
2370
			} elseif (strpos($hw_model, "C2758") !== false) {
2371
				return (array(
2372
				    'name' => 'C2758',
2373
				    'descr' => 'Super Micro C2758'));
2374
			}
2375
			break;
2376
		case 'SYS-5018D-FN4T':
2377
			if (strpos($hw_model, "D-1541") !== false) {
2378
				return (array('name' => 'XG-1541', 'descr' => 'Super Micro XG-1541'));
2379
			} else {
2380
				return (array('name' => 'XG-1540', 'descr' => 'Super Micro XG-1540'));
2381
			}
2382
			break;
2383
		case 'apu2':
2384
		case 'APU2':
2385
			return (array('name' => 'apu2', 'descr' => 'PC Engines APU2'));
2386
			break;
2387
		case 'VirtualBox':
2388
			return (array('name' => 'VirtualBox', 'descr' => 'VirtualBox Virtual Machine'));
2389
			break;
2390
		case 'Virtual Machine':
2391
			if ($maker[0] == "Microsoft Corporation") {
2392
				return (array('name' => 'Hyper-V', 'descr' => 'Hyper-V Virtual Machine'));
2393
			}
2394
			break;
2395
		case 'VMware Virtual Platform':
2396
			if ($maker[0] == "VMware, Inc.") {
2397
				return (array('name' => 'VMware', 'descr' => 'VMware Virtual Machine'));
2398
			}
2399
			break;
2400
	}
2401

    
2402
	$_gb = exec('/bin/kenv -q smbios.planar.product 2>/dev/null',
2403
	    $planar_product);
2404
	if (isset($planar_product[0]) &&
2405
	    $planar_product[0] == 'X10SDV-8C-TLN4F+') {
2406
		return array('name' => 'XG-1537', 'descr' => 'Super Micro XG-1537');
2407
	}
2408

    
2409
	if (strpos($hw_model, "PC Engines WRAP") !== false) {
2410
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
2411
	}
2412

    
2413
	if (strpos($hw_model, "PC Engines ALIX") !== false) {
2414
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2415
	}
2416

    
2417
	if (preg_match("/Soekris net45../", $hw_model, $matches)) {
2418
		return array('name' => 'net45xx', 'descr' => $matches[0]);
2419
	}
2420

    
2421
	if (preg_match("/Soekris net48../", $hw_model, $matches)) {
2422
		return array('name' => 'net48xx', 'descr' => $matches[0]);
2423
	}
2424

    
2425
	if (preg_match("/Soekris net55../", $hw_model, $matches)) {
2426
		return array('name' => 'net55xx', 'descr' => $matches[0]);
2427
	}
2428

    
2429
	unset($hw_model);
2430

    
2431
	$dmesg_boot = system_get_dmesg_boot();
2432
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
2433
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2434
	}
2435
	unset($dmesg_boot);
2436

    
2437
	return array('name' => $g['platform'], 'descr' => $g['platform']);
2438
}
2439

    
2440
function system_get_dmesg_boot() {
2441
	global $g;
2442

    
2443
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2444
}
2445

    
2446
function system_get_arp_table($resolve_hostnames = false) {
2447
	$params="-a";
2448
	if (!$resolve_hostnames) {
2449
		$params .= "n";
2450
	}
2451

    
2452
	$arp_table = array();
2453
	$_gb = exec("/usr/sbin/arp --libxo json {$params}", $rawdata, $rc);
2454
	if ($rc == 0) {
2455
		$arp_table = json_decode(implode(" ", $rawdata),
2456
		    JSON_OBJECT_AS_ARRAY);
2457
		if ($rc == 0) {
2458
			$arp_table = $arp_table['arp']['arp-cache'];
2459
		}
2460
	}
2461

    
2462
	return $arp_table;
2463
}
2464

    
2465
?>
(49-49/60)