Project

General

Profile

Download (66.1 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-2019 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
				mwexec("/sbin/route -q delete -host {$inet6}{$dnsserver}");
206
				if (isset($config['system']['route-debug'])) {
207
					$mt = microtime();
208
					log_error("ROUTING debug: $mt - route delete -host {$inet6}{$dnsserver}");
209
				}
210
			}
211
		}
212
		$dnscounter++;
213
		$dnsgw = "dns{$dnscounter}gw";
214
	}
215

    
216
	unlock($dnslock);
217

    
218
	return 0;
219
}
220

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

    
224
	$master_list = array();
225

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

    
242
	return $master_list;
243
}
244

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

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

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

    
277
	return $master_list;
278
}
279

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

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

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

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

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

    
339
	return $hosts;
340
}
341

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

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

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

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

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

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

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

    
387
	return $hosts;
388
}
389

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
491
	return $hosts;
492
}
493

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

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

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

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

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

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

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

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

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

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

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

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

    
579
	return 0;
580
}
581

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

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

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

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

    
618
		/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
619
		if (is_process_running("dhcpleases")) {
620
			sigkillbyname('dhcpleases', "TERM");
621
		}
622
		@unlink($pidfile);
623
		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");
624
	} elseif (isvalidpid($pidfile)) {
625
		sigkillbypid($pidfile, "TERM");
626
		@unlink($pidfile);
627
	}
628
}
629

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

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

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

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

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

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

    
650
	$arp_table = system_get_arp_table();
651

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
833
	return $leases;
834
}
835

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

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

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

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

    
852
	return $status;
853
}
854

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

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

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

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

    
881
	system_staticroutes_configure($interface, false);
882

    
883
	return 0;
884
}
885

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

    
889
	$filterdns_list = array();
890

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1010
	return 0;
1011
}
1012

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

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

    
1025
	return;
1026
}
1027

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1106
	sleep(1);
1107

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

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

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

    
1121
	return $res;
1122
}
1123

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

    
1127
	$dns_nameservers = array();
1128

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

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

    
1175
function system_generate_nginx_config($filename,
1176
	$cert,
1177
	$key,
1178
	$ca,
1179
	$pid_file,
1180
	$port = 80,
1181
	$document_root = "/usr/local/www/",
1182
	$cert_location = "cert.crt",
1183
	$key_location = "cert.key",
1184
	$captive_portal = false,
1185
	$hsts = true) {
1186

    
1187
	global $config, $g;
1188

    
1189
	if (isset($config['system']['developerspew'])) {
1190
		$mt = microtime();
1191
		echo "system_generate_nginx_config() being called $mt\n";
1192
	}
1193

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

    
1215
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1216
		if (empty($maxprocperip)) {
1217
			$maxprocperip = 10;
1218
		}
1219
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1220
	}
1221

    
1222
	if (empty($port)) {
1223
		$nginx_port = "80";
1224
	} else {
1225
		$nginx_port = $port;
1226
	}
1227

    
1228
	$memory = get_memory();
1229
	$realmem = $memory[1];
1230

    
1231
	// Determine web GUI process settings and take into account low memory systems
1232
	if ($realmem < 255) {
1233
		$max_procs = 1;
1234
	} else {
1235
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
1236
	}
1237

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

    
1249
	$nginx_config = <<<EOD
1250
#
1251
# nginx configuration file
1252

    
1253
pid {$g['varrun_path']}/{$pid_file};
1254

    
1255
user  root wheel;
1256
worker_processes  {$max_procs};
1257

    
1258
EOD;
1259

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

    
1267
	$nginx_config .= <<<EOD
1268

    
1269
events {
1270
    worker_connections  1024;
1271
}
1272

    
1273
http {
1274
	include       /usr/local/etc/nginx/mime.types;
1275
	default_type  application/octet-stream;
1276
	add_header X-Frame-Options SAMEORIGIN;
1277
	server_tokens off;
1278

    
1279
	sendfile        on;
1280

    
1281
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1282

    
1283
EOD;
1284

    
1285
	if ($captive_portal !== false) {
1286
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1287
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1288
	} else {
1289
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1290
	}
1291

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

    
1332
	$nginx_config .= <<<EOD
1333

    
1334
		client_max_body_size 200m;
1335

    
1336
		gzip on;
1337
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
1338

    
1339

    
1340
EOD;
1341

    
1342
	if ($captive_portal !== false) {
1343
		$nginx_config .= <<<EOD
1344
$captive_portal_maxprocperip
1345
$cp_hostcheck
1346
$cp_rewrite
1347
		log_not_found off;
1348

    
1349
EOD;
1350

    
1351
	}
1352

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

    
1387
EOD;
1388

    
1389
	$cert = str_replace("\r", "", $cert);
1390
	$key = str_replace("\r", "", $key);
1391

    
1392
	$cert = str_replace("\n\n", "\n", $cert);
1393
	$key = str_replace("\n\n", "\n", $key);
1394

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

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

    
1431
EOD;
1432
	}
1433

    
1434
	$nginx_config .= "}\n";
1435

    
1436
	$fd = fopen("{$filename}", "w");
1437
	if (!$fd) {
1438
		printf(gettext('Error: cannot open %1$s in system_generate_nginx_config().%2$s'), $filename, "\n");
1439
		return 1;
1440
	}
1441
	fwrite($fd, $nginx_config);
1442
	fclose($fd);
1443

    
1444
	/* nginx will fail to start if this directory does not exist. */
1445
	safe_mkdir("/var/tmp/nginx/");
1446

    
1447
	return 0;
1448

    
1449
}
1450

    
1451
function system_get_timezone_list() {
1452
	global $g;
1453

    
1454
	$file_list = array_merge(
1455
		glob("/usr/share/zoneinfo/[A-Z]*"),
1456
		glob("/usr/share/zoneinfo/*/*"),
1457
		glob("/usr/share/zoneinfo/*/*/*")
1458
	);
1459

    
1460
	if (empty($file_list)) {
1461
		$file_list[] = $g['default_timezone'];
1462
	} else {
1463
		/* Remove directories from list */
1464
		$file_list = array_filter($file_list, function($v) {
1465
			return !is_dir($v);
1466
		});
1467
	}
1468

    
1469
	/* Remove directory prefix */
1470
	$file_list = str_replace('/usr/share/zoneinfo/', '', $file_list);
1471

    
1472
	sort($file_list);
1473

    
1474
	return $file_list;
1475
}
1476

    
1477
function system_timezone_configure() {
1478
	global $config, $g;
1479
	if (isset($config['system']['developerspew'])) {
1480
		$mt = microtime();
1481
		echo "system_timezone_configure() being called $mt\n";
1482
	}
1483

    
1484
	$syscfg = $config['system'];
1485

    
1486
	if (platform_booting()) {
1487
		echo gettext("Setting timezone...");
1488
	}
1489

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

    
1496
	if (platform_booting()) {
1497
		echo gettext("done.") . "\n";
1498
	}
1499
}
1500

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

    
1516
function system_ntp_poll_values() {
1517
	global $ntp_poll_min_value, $ntp_poll_max_value;
1518
	$poll_values = array("" => gettext('Default'));
1519

    
1520
	for ($i = $ntp_poll_min_value; $i <= $ntp_poll_max_value; $i++) {
1521
		$sec = 2 ** $i;
1522
		$poll_values[$i] = $i . ': ' . number_format($sec) . ' ' . gettext('seconds') .
1523
					' (' . convert_seconds_to_dhms($sec) . ')';
1524
	}
1525

    
1526
	$poll_values['omit'] = gettext('Omit (Do not set)');
1527
	return $poll_values;
1528
}
1529

    
1530
function system_ntp_fixup_poll_value($type, $configvalue, $default) {
1531
	$pollstring = "";
1532

    
1533
	if (empty($configvalue)) {
1534
		$configvalue = $default;
1535
	}
1536

    
1537
	if ($configvalue != 'omit') {
1538
		$pollstring = " {$type} {$configvalue}";
1539
	}
1540

    
1541
	return $pollstring;
1542
}
1543

    
1544
function system_ntp_setup_gps($serialport) {
1545
	global $config, $g;
1546
	$gps_device = '/dev/gps0';
1547
	$serialport = '/dev/'.$serialport;
1548

    
1549
	if (!file_exists($serialport)) {
1550
		return false;
1551
	}
1552

    
1553
	// Create symlink that ntpd requires
1554
	unlink_if_exists($gps_device);
1555
	@symlink($serialport, $gps_device);
1556

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

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

    
1581
	/* Send the following to the GPS port to initialize the GPS */
1582
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
1583
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
1584
	} else {
1585
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1586
	}
1587

    
1588
	/* XXX: Why not file_put_contents to the device */
1589
	@file_put_contents('/tmp/gps.init', $gps_init);
1590
	mwexec("cat /tmp/gps.init > {$serialport}");
1591

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

    
1597

    
1598
	return true;
1599
}
1600

    
1601
function system_ntp_setup_pps($serialport) {
1602
	global $config, $g;
1603

    
1604
	$pps_device = '/dev/pps0';
1605
	$serialport = '/dev/'.$serialport;
1606

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

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

    
1615

    
1616
	return true;
1617
}
1618

    
1619

    
1620
function system_ntp_configure() {
1621
	global $config, $g;
1622
	global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
1623
	global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
1624
	global $ntp_poll_min_default, $ntp_poll_max_default;
1625

    
1626
	$driftfile = "/var/db/ntpd.drift";
1627
	$statsdir = "/var/log/ntp";
1628
	$gps_device = '/dev/gps0';
1629

    
1630
	safe_mkdir($statsdir);
1631

    
1632
	if (!is_array($config['ntpd'])) {
1633
		$config['ntpd'] = array();
1634
	}
1635

    
1636
	$ntpcfg = "# \n";
1637
	$ntpcfg .= "# pfSense ntp configuration file \n";
1638
	$ntpcfg .= "# \n\n";
1639
	$ntpcfg .= "tinker panic 0 \n";
1640

    
1641
	/* Add Orphan mode */
1642
	$ntpcfg .= "# Orphan mode stratum\n";
1643
	$ntpcfg .= 'tos orphan ';
1644
	if (!empty($config['ntpd']['orphan'])) {
1645
		$ntpcfg .= $config['ntpd']['orphan'];
1646
	} else {
1647
		$ntpcfg .= '12';
1648
	}
1649
	$ntpcfg .= "\n";
1650

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

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

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

    
1784
		$ntpcfg .= "{$ts} iburst";
1785

    
1786
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', $config['ntpd']['ntpminpoll'], $ntp_poll_min_default);
1787
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', $config['ntpd']['ntpmaxpoll'], $ntp_poll_max_default);
1788

    
1789
		if (substr_count($config['ntpd']['prefer'], $ts)) {
1790
			$ntpcfg .= ' prefer';
1791
		}
1792
		if (substr_count($config['ntpd']['noselect'], $ts)) {
1793
			$ntpcfg .= ' noselect';
1794
		}
1795
		$ntpcfg .= "\n";
1796
	}
1797
	unset($ts);
1798

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

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

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

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

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

    
1930

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

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

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

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

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

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

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

    
1981
function system_halt() {
1982
	global $g;
1983

    
1984
	system_reboot_cleanup();
1985

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

    
1989
function system_reboot() {
1990
	global $g;
1991

    
1992
	system_reboot_cleanup();
1993

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

    
1997
function system_reboot_sync($reroot=false) {
1998
	global $g;
1999

    
2000
	if ($reroot) {
2001
		$args = " -r ";
2002
	}
2003

    
2004
	system_reboot_cleanup();
2005

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

    
2009
function system_reboot_cleanup() {
2010
	global $config, $g, $cpzone;
2011

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

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

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

    
2047
	if (is_array($config['system'][$cmdn])) {
2048

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

    
2054
	} elseif ($config['system'][$cmdn] <> "") {
2055

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

    
2059
	}
2060
}
2061

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

    
2069
	$dmesg = "";
2070
	$_gb = exec("/sbin/dmesg", $dmesg);
2071

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

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

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

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

    
2091
	fclose($fd);
2092
	unset($dmesg);
2093

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

    
2097
	return 0;
2098
}
2099

    
2100
function system_set_harddisk_standby() {
2101
	global $g, $config;
2102

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

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

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

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

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

    
2146
	activate_sysctls();
2147

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

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

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

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

    
2196
function system_check_reset_button() {
2197
	global $g;
2198

    
2199
	$specplatform = system_identify_specific_platform();
2200

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

    
2217
	$retval = mwexec("/usr/local/sbin/" . $binprefix . "resetbtn");
2218

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

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

    
2230

    
2231
EOD;
2232

    
2233
		reset_factory_defaults();
2234
		system_reboot_sync();
2235
		exit(0);
2236
	}
2237

    
2238
	return 0;
2239
}
2240

    
2241
function system_get_serial() {
2242
	$platform = system_identify_specific_platform();
2243

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

    
2263
	$vm_guest = get_single_sysctl('kern.vm_guest');
2264

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

    
2270
	return "";
2271
}
2272

    
2273
function system_get_uniqueid() {
2274
	global $g;
2275

    
2276
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2277

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

    
2288
	return ($g['uniqueid'] ?: '');
2289
}
2290

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

    
2300
	$hw_model = get_single_sysctl('hw.model');
2301
	$hw_ncpu = get_single_sysctl('hw.ncpu');
2302

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

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

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

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

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

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

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

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

    
2427
	unset($hw_model);
2428

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

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

    
2438
function system_get_dmesg_boot() {
2439
	global $g;
2440

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

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

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

    
2460
	return $arp_table;
2461
}
2462

    
2463
?>
(49-49/60)