Project

General

Profile

Download (72.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-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 net.pf.request_maxcount via sysctl since it is no longer a loader
120
	 *   tunable. See https://redmine.pfsense.org/issues/10861
121
	 *   Set the value dynamically since its default is not static, yet this
122
	 *   still could be overridden by a user tunable. */
123
	if (isset($config['system']['maximumtableentries'])) {
124
		$maximumtableentries = $config['system']['maximumtableentries'];
125
	} else {
126
		$maximumtableentries = pfsense_default_table_entries_size();
127
	}
128
	/* Set the default when there is no tunable or when the tunable is set
129
	 * too low. */
130
	if (empty($sysctls['net.pf.request_maxcount']) ||
131
	    ($sysctls['net.pf.request_maxcount'] < $maximumtableentries)) {
132
		$sysctls['net.pf.request_maxcount'] = $maximumtableentries;
133
	}
134

    
135
	set_sysctl($sysctls);
136
}
137

    
138
function system_resolvconf_generate($dynupdate = false) {
139
	global $config, $g;
140

    
141
	if (isset($config['system']['developerspew'])) {
142
		$mt = microtime();
143
		echo "system_resolvconf_generate() being called $mt\n";
144
	}
145

    
146
	$syscfg = $config['system'];
147

    
148
	foreach(get_dns_nameservers(false, false) as $dns_ns) {
149
		$resolvconf .= "nameserver $dns_ns\n";
150
	}
151

    
152
	$ns = array();
153
	if (isset($syscfg['dnsallowoverride'])) {
154
		/* get dynamically assigned DNS servers (if any) */
155
		$ns = array_unique(get_searchdomains());
156
		foreach ($ns as $searchserver) {
157
			if ($searchserver) {
158
				$resolvconf .= "search {$searchserver}\n";
159
			}
160
		}
161
	}
162
	if (empty($ns)) {
163
		// Do not create blank search/domain lines, it can break tools like dig.
164
		if ($syscfg['domain']) {
165
			$resolvconf .= "search {$syscfg['domain']}\n";
166
		}
167
	}
168

    
169
	// Add EDNS support
170
	if (isset($config['unbound']['enable']) && isset($config['unbound']['edns'])) {
171
		$resolvconf .= "options edns0\n";
172
	}
173

    
174
	$dnslock = lock('resolvconf', LOCK_EX);
175

    
176
	$fd = fopen("{$g['etc_path']}/resolv.conf", "w");
177
	if (!$fd) {
178
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
179
		unlock($dnslock);
180
		return 1;
181
	}
182

    
183
	fwrite($fd, $resolvconf);
184
	fclose($fd);
185

    
186
	// Prevent resolvconf(8) from rewriting our resolv.conf
187
	$fd = fopen("{$g['etc_path']}/resolvconf.conf", "w");
188
	if (!$fd) {
189
		printf("Error: cannot open resolvconf.conf in system_resolvconf_generate().\n");
190
		return 1;
191
	}
192
	fwrite($fd, "resolv_conf=\"/dev/null\"\n");
193
	fclose($fd);
194

    
195
	if (!platform_booting()) {
196
		/* restart dhcpd (nameservers may have changed) */
197
		if (!$dynupdate) {
198
			services_dhcpd_configure();
199
		}
200
	}
201

    
202
	// set up or tear down static routes for DNS servers
203
	$dnscounter = 1;
204
	$dnsgw = "dns{$dnscounter}gw";
205
	while (isset($config['system'][$dnsgw])) {
206
		/* setup static routes for dns servers */
207
		$gwname = $config['system'][$dnsgw];
208
		unset($gatewayip);
209
		unset($inet6);
210
		if ((!empty($gwname)) && ($gwname != "none")) {
211
			$gatewayip = lookup_gateway_ip_by_name($gwname);
212
			$inet6 = is_ipaddrv6($gatewayip) ? '-inet6 ' : '';
213
		}
214
		/* dns server array starts at 0 */
215
		$dnsserver = $syscfg['dnsserver'][$dnscounter - 1];
216
		if (!empty($dnsserver)) {
217
			if (is_ipaddr($gatewayip)) {
218
				route_add_or_change($dnsserver, $gatewayip);
219
			} else {
220
				/* Remove old route when disable gw */
221
				route_del($dnsserver);
222
			}
223
		}
224
		$dnscounter++;
225
		$dnsgw = "dns{$dnscounter}gw";
226
	}
227

    
228
	unlock($dnslock);
229

    
230
	return 0;
231
}
232

    
233
function get_searchdomains() {
234
	global $config, $g;
235

    
236
	$master_list = array();
237

    
238
	// Read in dhclient nameservers
239
	$search_list = glob("/var/etc/searchdomain_*");
240
	if (is_array($search_list)) {
241
		foreach ($search_list as $fdns) {
242
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
243
			if (!is_array($contents)) {
244
				continue;
245
			}
246
			foreach ($contents as $dns) {
247
				if (is_hostname($dns)) {
248
					$master_list[] = $dns;
249
				}
250
			}
251
		}
252
	}
253

    
254
	return $master_list;
255
}
256

    
257
/* Stub for deprecated function name
258
 * See https://redmine.pfsense.org/issues/10931 */
259
function get_nameservers() {
260
	return get_dynamic_nameservers();
261
}
262

    
263
/****f* system.inc/get_dynamic_nameservers
264
 * NAME
265
 *   get_dynamic_nameservers - Get DNS servers from dynamic sources (DHCP, PPP, etc)
266
 * INPUTS
267
 *   $iface: Interface name used to filter results.
268
 * RESULT
269
 *   $master_list - Array containing DNS servers
270
 ******/
271
function get_dynamic_nameservers($iface = '') {
272
	global $config, $g;
273
	$master_list = array();
274

    
275
	if (!empty($iface)) {
276
		$realif = get_real_interface($iface);
277
	}
278

    
279
	// Read in dynamic nameservers
280
	$dns_lists = array_merge(glob("/var/etc/nameserver_{$realif}*"), glob("/var/etc/nameserver_v6{$iface}*"));
281
	if (is_array($dns_lists)) {
282
		foreach ($dns_lists as $fdns) {
283
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
284
			if (!is_array($contents)) {
285
				continue;
286
			}
287
			foreach ($contents as $dns) {
288
				if (is_ipaddr($dns)) {
289
					$master_list[] = $dns;
290
				}
291
			}
292
		}
293
	}
294

    
295
	return $master_list;
296
}
297

    
298
/* Create localhost + local interfaces entries for /etc/hosts */
299
function system_hosts_local_entries() {
300
	global $config;
301

    
302
	$syscfg = $config['system'];
303

    
304
	$hosts = array();
305
	$hosts[] = array(
306
	    'ipaddr' => '127.0.0.1',
307
	    'fqdn' => 'localhost.' . $syscfg['domain'],
308
	    'name' => 'localhost',
309
	    'domain' => $syscfg['domain']
310
	);
311
	$hosts[] = array(
312
	    'ipaddr' => '::1',
313
	    'fqdn' => 'localhost.' . $syscfg['domain'],
314
	    'name' => 'localhost',
315
	    'domain' => $syscfg['domain']
316
	);
317

    
318
	if ($config['interfaces']['lan']) {
319
		$sysiflist = array('lan' => "lan");
320
	} else {
321
		$sysiflist = get_configured_interface_list();
322
	}
323

    
324
	$hosts_if_found = false;
325
	$local_fqdn = "{$syscfg['hostname']}.{$syscfg['domain']}";
326
	foreach ($sysiflist as $sysif) {
327
		if ($sysif != 'lan' && interface_has_gateway($sysif)) {
328
			continue;
329
		}
330
		$cfgip = get_interface_ip($sysif);
331
		if (is_ipaddrv4($cfgip)) {
332
			$hosts[] = array(
333
			    'ipaddr' => $cfgip,
334
			    'fqdn' => $local_fqdn,
335
			    'name' => $syscfg['hostname'],
336
			    'domain' => $syscfg['domain']
337
			);
338
			$hosts_if_found = true;
339
		}
340
		if (!isset($syscfg['ipv6dontcreatelocaldns'])) {
341
			$cfgipv6 = get_interface_ipv6($sysif);
342
			if (is_ipaddrv6($cfgipv6)) {
343
				$hosts[] = array(
344
					'ipaddr' => $cfgipv6,
345
					'fqdn' => $local_fqdn,
346
					'name' => $syscfg['hostname'],
347
					'domain' => $syscfg['domain']
348
				);
349
				$hosts_if_found = true;
350
			}
351
		}
352
		if ($hosts_if_found == true) {
353
			break;
354
		}
355
	}
356

    
357
	return $hosts;
358
}
359

    
360
/* Read host override entries from dnsmasq or unbound */
361
function system_hosts_override_entries($dnscfg) {
362
	$hosts = array();
363

    
364
	if (!is_array($dnscfg) ||
365
	    !is_array($dnscfg['hosts']) ||
366
	    !isset($dnscfg['enable'])) {
367
		return $hosts;
368
	}
369

    
370
	foreach ($dnscfg['hosts'] as $host) {
371
		$fqdn = '';
372
		if ($host['host'] || $host['host'] == "0") {
373
			$fqdn .= "{$host['host']}.";
374
		}
375
		$fqdn .= $host['domain'];
376

    
377
		foreach (explode(',', $host['ip']) as $ip) {
378
			$hosts[] = array(
379
			    'ipaddr' => $ip,
380
			    'fqdn' => $fqdn,
381
			    'name' => $host['host'],
382
			    'domain' => $host['domain']
383
			);
384
		}
385

    
386
		if (!is_array($host['aliases']) ||
387
		    !is_array($host['aliases']['item'])) {
388
			continue;
389
		}
390

    
391
		foreach ($host['aliases']['item'] as $alias) {
392
			$fqdn = '';
393
			if ($alias['host'] || $alias['host'] == "0") {
394
				$fqdn .= "{$alias['host']}.";
395
			}
396
			$fqdn .= $alias['domain'];
397

    
398
			foreach (explode(',', $host['ip']) as $ip) {
399
				$hosts[] = array(
400
				    'ipaddr' => $ip,
401
				    'fqdn' => $fqdn,
402
				    'name' => $alias['host'],
403
				    'domain' => $alias['domain']
404
				);
405
			}
406
		}
407
	}
408

    
409
	return $hosts;
410
}
411

    
412
/* Read all dhcpd/dhcpdv6 staticmap entries */
413
function system_hosts_dhcpd_entries() {
414
	global $config;
415

    
416
	$hosts = array();
417
	$syscfg = $config['system'];
418

    
419
	if (is_array($config['dhcpd'])) {
420
		$conf_dhcpd = $config['dhcpd'];
421
	} else {
422
		$conf_dhcpd = array();
423
	}
424

    
425
	foreach ($conf_dhcpd as $dhcpif => $dhcpifconf) {
426
		if (!is_array($dhcpifconf['staticmap']) ||
427
		    !isset($dhcpifconf['enable'])) {
428
			continue;
429
		}
430
		foreach ($dhcpifconf['staticmap'] as $host) {
431
			if (!$host['ipaddr'] ||
432
			    !$host['hostname']) {
433
				continue;
434
			}
435

    
436
			$fqdn = $host['hostname'] . ".";
437
			$domain = "";
438
			if ($host['domain']) {
439
				$domain = $host['domain'];
440
			} elseif ($dhcpifconf['domain']) {
441
				$domain = $dhcpifconf['domain'];
442
			} else {
443
				$domain = $syscfg['domain'];
444
			}
445

    
446
			$hosts[] = array(
447
			    'ipaddr' => $host['ipaddr'],
448
			    'fqdn' => $fqdn . $domain,
449
			    'name' => $host['hostname'],
450
			    'domain' => $domain
451
			);
452
		}
453
	}
454
	unset($conf_dhcpd);
455

    
456
	if (is_array($config['dhcpdv6'])) {
457
		$conf_dhcpdv6 = $config['dhcpdv6'];
458
	} else {
459
		$conf_dhcpdv6 = array();
460
	}
461

    
462
	foreach ($conf_dhcpdv6 as $dhcpif => $dhcpifconf) {
463
		if (!is_array($dhcpifconf['staticmap']) ||
464
		    !isset($dhcpifconf['enable'])) {
465
			continue;
466
		}
467

    
468
		if (isset($config['interfaces'][$dhcpif]['ipaddrv6']) &&
469
		    $config['interfaces'][$dhcpif]['ipaddrv6'] ==
470
		    'track6') {
471
			$isdelegated = true;
472
		} else {
473
			$isdelegated = false;
474
		}
475

    
476
		foreach ($dhcpifconf['staticmap'] as $host) {
477
			$ipaddrv6 = $host['ipaddrv6'];
478

    
479
			if (!$ipaddrv6 || !$host['hostname']) {
480
				continue;
481
			}
482

    
483
			if ($isdelegated) {
484
				/*
485
				 * We are always in an "end-user" subnet
486
				 * here, which all are /64 for IPv6.
487
				 */
488
				$prefix6 = 64;
489
			} else {
490
				$prefix6 = get_interface_subnetv6($dhcpif);
491
			}
492
			$ipaddrv6 = merge_ipv6_delegated_prefix(get_interface_ipv6($dhcpif), $ipaddrv6, $prefix6);
493

    
494
			$fqdn = $host['hostname'] . ".";
495
			$domain = "";
496
			if ($host['domain']) {
497
				$domain = $host['domain'];
498
			} elseif ($dhcpifconf['domain']) {
499
				$domain = $dhcpifconf['domain'];
500
			} else {
501
				$domain = $syscfg['domain'];
502
			}
503

    
504
			$hosts[] = array(
505
			    'ipaddr' => $ipaddrv6,
506
			    'fqdn' => $fqdn . $domain,
507
			    'name' => $host['hostname'],
508
			    'domain' => $domain
509
			);
510
		}
511
	}
512
	unset($conf_dhcpdv6);
513

    
514
	return $hosts;
515
}
516

    
517
/* Concatenate local, dnsmasq/unbound and dhcpd/dhcpdv6 hosts entries */
518
function system_hosts_entries($dnscfg) {
519
	$local = array();
520
	if (!isset($dnscfg['disable_auto_added_host_entries'])) {
521
		$local = system_hosts_local_entries();
522
	}
523

    
524
	$dns = array();
525
	$dhcpd = array();
526
	if (isset($dnscfg['enable'])) {
527
		$dns = system_hosts_override_entries($dnscfg);
528
		if (isset($dnscfg['regdhcpstatic'])) {
529
			$dhcpd = system_hosts_dhcpd_entries();
530
		}
531
	}
532

    
533
	if (isset($dnscfg['dhcpfirst'])) {
534
		return array_merge($local, $dns, $dhcpd);
535
	} else {
536
		return array_merge($local, $dhcpd, $dns);
537
	}
538
}
539

    
540
function system_hosts_generate() {
541
	global $config, $g;
542
	if (isset($config['system']['developerspew'])) {
543
		$mt = microtime();
544
		echo "system_hosts_generate() being called $mt\n";
545
	}
546

    
547
	// prefer dnsmasq for hosts generation where it's enabled. It relies
548
	// on hosts for name resolution of its overrides, unbound does not.
549
	if (isset($config['dnsmasq']) && isset($config['dnsmasq']['enable'])) {
550
		$dnsmasqcfg = $config['dnsmasq'];
551
	} else {
552
		$dnsmasqcfg = $config['unbound'];
553
	}
554

    
555
	$syscfg = $config['system'];
556
	$hosts = "";
557
	$lhosts = "";
558
	$dhosts = "";
559

    
560
	$hosts_array = system_hosts_entries($dnsmasqcfg);
561
	foreach ($hosts_array as $host) {
562
		$hosts .= "{$host['ipaddr']}\t";
563
		if ($host['name'] == "localhost") {
564
			$hosts .= "{$host['name']} {$host['fqdn']}";
565
		} else {
566
			$hosts .= "{$host['fqdn']} {$host['name']}";
567
		}
568
		$hosts .= "\n";
569
	}
570
	unset($hosts_array);
571

    
572
	/*
573
	 * Do not remove this because dhcpleases monitors with kqueue it needs
574
	 * to be killed before writing to hosts files.
575
	 */
576
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
577
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
578
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
579
	}
580

    
581
	$fd = fopen("{$g['etc_path']}/hosts", "w");
582
	if (!$fd) {
583
		log_error(gettext(
584
		    "Error: cannot open hosts file in system_hosts_generate()."
585
		    ));
586
		return 1;
587
	}
588

    
589
	fwrite($fd, $hosts);
590
	fclose($fd);
591

    
592
	if (isset($config['unbound']['enable'])) {
593
		require_once("unbound.inc");
594
		unbound_hosts_generate();
595
	}
596

    
597
	/* restart dhcpleases */
598
	if (!platform_booting()) {
599
		system_dhcpleases_configure();
600
	}
601

    
602
	return 0;
603
}
604

    
605
function system_dhcpleases_configure() {
606
	global $config, $g;
607
	if (!function_exists('is_dhcp_server_enabled')) {
608
		require_once('pfsense-utils.inc');
609
	}
610
	$pidfile = "{$g['varrun_path']}/dhcpleases.pid";
611

    
612
	/* Start the monitoring process for dynamic dhcpclients. */
613
	if (((isset($config['dnsmasq']['enable']) && isset($config['dnsmasq']['regdhcp'])) ||
614
	    (isset($config['unbound']['enable']) && isset($config['unbound']['regdhcp']))) &&
615
	    (is_dhcp_server_enabled())) {
616
		/* Make sure we do not error out */
617
		mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db");
618
		if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
619
			@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
620
		}
621

    
622
		if (isset($config['unbound']['enable'])) {
623
			$dns_pid = "unbound.pid";
624
			$unbound_conf = "-u {$g['unbound_chroot_path']}/dhcpleases_entries.conf";
625
		} else {
626
			$dns_pid = "dnsmasq.pid";
627
			$unbound_conf = "";
628
		}
629

    
630
		if (isvalidpid($pidfile)) {
631
			/* Make sure dhcpleases is using correct unbound or dnsmasq */
632
			$_gb = exec("/bin/pgrep -F {$pidfile} -f {$dns_pid}", $output, $retval);
633
			if (intval($retval) == 0) {
634
				sigkillbypid($pidfile, "HUP");
635
				return;
636
			} else {
637
				sigkillbypid($pidfile, "TERM");
638
			}
639
		}
640

    
641
		/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
642
		if (is_process_running("dhcpleases")) {
643
			sigkillbyname('dhcpleases', "TERM");
644
		}
645
		@unlink($pidfile);
646
		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");
647
	} else {
648
		if (isvalidpid($pidfile)) {
649
			sigkillbypid($pidfile, "TERM");
650
			@unlink($pidfile);
651
		}
652
		if (file_exists("{$g['unbound_chroot_path']}/dhcpleases_entries.conf")) {
653
			$dhcpleases = fopen("{$g['unbound_chroot_path']}/dhcpleases_entries.conf", "w");
654
			ftruncate($dhcpleases, 0);
655
			fclose($dhcpleases);
656
		}
657
	}
658
}
659

    
660
function system_get_dhcpleases() {
661
	global $config, $g;
662

    
663
	$leases = array();
664
	$leases['lease'] = array();
665
	$leases['failover'] = array();
666

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

    
669
	if (!file_exists($leases_file)) {
670
		return $leases;
671
	}
672

    
673
	$leases_content = file($leases_file, FILE_IGNORE_NEW_LINES |
674
	    FILE_IGNORE_NEW_LINES);
675

    
676
	if ($leases_content === FALSE) {
677
		return $leases;
678
	}
679

    
680
	$arp_table = system_get_arp_table();
681

    
682
	$arpdata_ip = array();
683
	$arpdata_mac = array();
684
	foreach ($arp_table as $arp_entry) {
685
		if (isset($arpentry['incomplete'])) {
686
			continue;
687
		}
688
		$arpdata_ip[] = $arp_entry['ip-address'];
689
		$arpdata_mac[] = $arp_entry['mac-address'];
690
	}
691
	unset($arp_table);
692

    
693
	/*
694
	 * Translate these once so we don't do it over and over in the loops
695
	 * below.
696
	 */
697
	$online_string = gettext("online");
698
	$offline_string = gettext("offline");
699
	$active_string = gettext("active");
700
	$expired_string = gettext("expired");
701
	$reserved_string = gettext("reserved");
702
	$dynamic_string = gettext("dynamic");
703
	$static_string = gettext("static");
704

    
705
	$lease_regex = '/^lease\s+([^\s]+)\s+{$/';
706
	$starts_regex = '/^\s*(starts|ends)\s+\d+\s+([\d\/]+|never)\s*(|[\d:]*);$/';
707
	$binding_regex = '/^\s*binding\s+state\s+(.+);$/';
708
	$mac_regex = '/^\s*hardware\s+ethernet\s+(.+);$/';
709
	$hostname_regex = '/^\s*client-hostname\s+"(.+)";$/';
710

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

    
714
	$lease = false;
715
	$failover = false;
716
	$dedup_lease = false;
717
	$dedup_failover = false;
718
	foreach ($leases_content as $line) {
719
		/* Skip comments */
720
		if (preg_match('/^\s*(|#.*)$/', $line)) {
721
			continue;
722
		}
723

    
724
		if (preg_match('/}$/', $line)) {
725
			if ($lease) {
726
				if (empty($item['hostname'])) {
727
					$hostname = gethostbyaddr($item['ip']);
728
					if (!empty($hostname)) {
729
						$item['hostname'] = $hostname;
730
					}
731
				}
732
				$leases['lease'][] = $item;
733
				$lease = false;
734
				$dedup_lease = true;
735
			} else if ($failover) {
736
				$leases['failover'][] = $item;
737
				$failover = false;
738
				$dedup_failover = true;
739
			}
740
			continue;
741
		}
742

    
743
		if (preg_match($lease_regex, $line, $m)) {
744
			$lease = true;
745
			$item = array();
746
			$item['ip'] = $m[1];
747
			$item['type'] = $dynamic_string;
748
			continue;
749
		}
750

    
751
		if ($lease) {
752
			if (preg_match($starts_regex, $line, $m)) {
753
				/*
754
				 * Quote from dhcpd.leases(5) man page:
755
				 * If a lease will never expire, date is never
756
				 * instead of an actual date
757
				 */
758
				if ($m[2] == "never") {
759
					$item[$m[1]] = gettext("Never");
760
				} else {
761
					$item[$m[1]] = dhcpd_date_adjust_gmt(
762
					    $m[2] . ' ' . $m[3]);
763
				}
764
				continue;
765
			}
766

    
767
			if (preg_match($binding_regex, $line, $m)) {
768
				switch ($m[1]) {
769
					case "active":
770
						$item['act'] = $active_string;
771
						break;
772
					case "free":
773
						$item['act'] = $expired_string;
774
						$item['online'] =
775
						    $offline_string;
776
						break;
777
					case "backup":
778
						$item['act'] = $reserved_string;
779
						$item['online'] =
780
						    $offline_string;
781
						break;
782
				}
783
				continue;
784
			}
785

    
786
			if (preg_match($mac_regex, $line, $m) &&
787
			    is_macaddr($m[1])) {
788
				$item['mac'] = $m[1];
789

    
790
				if (in_array($item['ip'], $arpdata_ip)) {
791
					$item['online'] = $online_string;
792
				} else {
793
					$item['online'] = $offline_string;
794
				}
795
				continue;
796
			}
797

    
798
			if (preg_match($hostname_regex, $line, $m)) {
799
				$item['hostname'] = $m[1];
800
			}
801
		}
802

    
803
		if (preg_match($failover_regex, $line, $m)) {
804
			$failover = true;
805
			$item = array();
806
			$item['name'] = $m[1] . ' (' .
807
			    convert_friendly_interface_to_friendly_descr(
808
			    substr($m[1],5)) . ')';
809
			continue;
810
		}
811

    
812
		if ($failover && preg_match($state_regex, $line, $m)) {
813
			$item[$m[1] . 'state'] = $m[2];
814
			$item[$m[1] . 'date'] = dhcpd_date_adjust_gmt($m[3] .
815
			    ' ' . $m[4]);
816
			continue;
817
		}
818
	}
819

    
820
	foreach ($config['interfaces'] as $ifname => $ifarr) {
821
		if (!is_array($config['dhcpd'][$ifname]) ||
822
		    !is_array($config['dhcpd'][$ifname]['staticmap'])) {
823
			continue;
824
		}
825

    
826
		foreach ($config['dhcpd'][$ifname]['staticmap'] as $idx =>
827
		    $static) {
828
			if (empty($static['mac']) && empty($static['cid'])) {
829
				continue;
830
			}
831

    
832
			$slease = array();
833
			$slease['ip'] = $static['ipaddr'];
834
			$slease['type'] = $static_string;
835
			if (!empty($static['cid'])) {
836
				$slease['cid'] = $static['cid'];
837
			}
838
			$slease['mac'] = $static['mac'];
839
			$slease['if'] = $ifname;
840
			$slease['starts'] = "";
841
			$slease['ends'] = "";
842
			$slease['hostname'] = $static['hostname'];
843
			$slease['descr'] = $static['descr'];
844
			$slease['act'] = $static_string;
845
			$slease['online'] = in_array(strtolower($slease['mac']),
846
			    $arpdata_mac) ? $online_string : $offline_string;
847
			$slease['staticmap_array_index'] = $idx;
848
			$leases['lease'][] = $slease;
849
			$dedup_lease = true;
850
		}
851
	}
852

    
853
	if ($dedup_lease) {
854
		$leases['lease'] = array_remove_duplicate($leases['lease'],
855
		    'ip');
856
	}
857
	if ($dedup_failover) {
858
		$leases['failover'] = array_remove_duplicate(
859
		    $leases['failover'], 'name');
860
		asort($leases['failover']);
861
	}
862

    
863
	return $leases;
864
}
865

    
866
function system_hostname_configure() {
867
	global $config, $g;
868
	if (isset($config['system']['developerspew'])) {
869
		$mt = microtime();
870
		echo "system_hostname_configure() being called $mt\n";
871
	}
872

    
873
	$syscfg = $config['system'];
874

    
875
	/* set hostname */
876
	$status = mwexec("/bin/hostname " .
877
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
878

    
879
	/* Setup host GUID ID.  This is used by ZFS. */
880
	mwexec("/etc/rc.d/hostid start");
881

    
882
	return $status;
883
}
884

    
885
function system_routing_configure($interface = "") {
886
	global $config, $g;
887

    
888
	if (isset($config['system']['developerspew'])) {
889
		$mt = microtime();
890
		echo "system_routing_configure() being called $mt\n";
891
	}
892

    
893
	$gateways_arr = return_gateways_array(false, true);
894
	foreach ($gateways_arr as $gateway) {
895
		// setup static interface routes for nonlocal gateways
896
		if (isset($gateway["nonlocalgateway"])) {
897
			$srgatewayip = $gateway['gateway'];
898
			$srinterfacegw = $gateway['interface'];
899
			if (is_ipaddr($srgatewayip) && !empty($srinterfacegw)) {
900
				route_add_or_change($srgatewayip, '',
901
				    $srinterfacegw);
902
			}
903
		}
904
	}
905

    
906
	$gateways_status = return_gateways_status(true);
907
	fixup_default_gateway("inet", $gateways_status, $gateways_arr);
908
	fixup_default_gateway("inet6", $gateways_status, $gateways_arr);
909

    
910
	system_staticroutes_configure($interface, false);
911

    
912
	return 0;
913
}
914

    
915
function system_staticroutes_configure($interface = "", $update_dns = false) {
916
	global $config, $g, $aliastable;
917

    
918
	$filterdns_list = array();
919

    
920
	$static_routes = get_staticroutes(false, true);
921
	if (count($static_routes)) {
922
		$gateways_arr = return_gateways_array(false, true);
923

    
924
		foreach ($static_routes as $rtent) {
925
			if (empty($gateways_arr[$rtent['gateway']])) {
926
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
927
				continue;
928
			}
929
			$gateway = $gateways_arr[$rtent['gateway']];
930
			if (!empty($interface) && $interface != $gateway['friendlyiface']) {
931
				continue;
932
			}
933

    
934
			$gatewayip = $gateway['gateway'];
935
			$interfacegw = $gateway['interface'];
936

    
937
			$blackhole = "";
938
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 4))) {
939
				$blackhole = "-blackhole";
940
			}
941

    
942
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network'])) {
943
				continue;
944
			}
945

    
946
			$dnscache = array();
947
			if ($update_dns === true) {
948
				if (is_subnet($rtent['network'])) {
949
					continue;
950
				}
951
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
952
				if (empty($dnscache)) {
953
					continue;
954
				}
955
			}
956

    
957
			if (is_subnet($rtent['network'])) {
958
				$ips = array($rtent['network']);
959
			} else {
960
				if (!isset($rtent['disabled'])) {
961
					$filterdns_list[] = $rtent['network'];
962
				}
963
				$ips = add_hostname_to_watch($rtent['network']);
964
			}
965

    
966
			foreach ($dnscache as $ip) {
967
				if (in_array($ip, $ips)) {
968
					continue;
969
				}
970
				route_del($ip);
971
			}
972

    
973
			if (isset($rtent['disabled'])) {
974
				/*
975
				 * XXX: This can break things by deleting
976
				 * routes that shouldn't be deleted - OpenVPN,
977
				 * dynamic routing scenarios, etc.
978
				 * redmine #3709
979
				 */
980
				foreach ($ips as $ip) {
981
					route_del($ip);
982
				}
983
				continue;
984
			}
985

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

    
1019
	if ($update_dns === false) {
1020
		if (count($filterdns_list)) {
1021
			$interval = 60;
1022
			$hostnames = "";
1023
			array_unique($filterdns_list);
1024
			foreach ($filterdns_list as $hostname) {
1025
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
1026
			}
1027
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
1028
			unset($hostnames);
1029

    
1030
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid")) {
1031
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
1032
			} else {
1033
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
1034
			}
1035
		} else {
1036
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
1037
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
1038
		}
1039
	}
1040
	unset($filterdns_list);
1041

    
1042
	return 0;
1043
}
1044

    
1045
function system_routing_enable() {
1046
	global $config, $g;
1047
	if (isset($config['system']['developerspew'])) {
1048
		$mt = microtime();
1049
		echo "system_routing_enable() being called $mt\n";
1050
	}
1051

    
1052
	set_sysctl(array(
1053
		"net.inet.ip.forwarding" => "1",
1054
		"net.inet6.ip6.forwarding" => "1"
1055
	));
1056

    
1057
	return;
1058
}
1059

    
1060
function system_webgui_create_certificate() {
1061
	global $config, $g, $cert_strict_values;
1062

    
1063
	init_config_arr(array('ca'));
1064
	$a_ca = &$config['ca'];
1065
	init_config_arr(array('cert'));
1066
	$a_cert = &$config['cert'];
1067
	log_error(gettext("Creating SSL/TLS Certificate for this host"));
1068

    
1069
	$cert = array();
1070
	$cert['refid'] = uniqid();
1071
	$cert['descr'] = sprintf(gettext("webConfigurator default (%s)"), $cert['refid']);
1072
	$cert_hostname = "{$config['system']['hostname']}-{$cert['refid']}";
1073

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

    
1088
	$a_cert[] = $cert;
1089
	$config['system']['webgui']['ssl-certref'] = $cert['refid'];
1090
	write_config(sprintf(gettext("Generated new self-signed SSL/TLS certificate for HTTPS (%s)"), $cert['refid']));
1091
	return $cert;
1092
}
1093

    
1094
function system_webgui_start() {
1095
	global $config, $g;
1096

    
1097
	if (platform_booting()) {
1098
		echo gettext("Starting webConfigurator...");
1099
	}
1100

    
1101
	chdir($g['www_path']);
1102

    
1103
	/* defaults */
1104
	$portarg = "80";
1105
	$crt = "";
1106
	$key = "";
1107
	$ca = "";
1108

    
1109
	/* non-standard port? */
1110
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "") {
1111
		$portarg = "{$config['system']['webgui']['port']}";
1112
	}
1113

    
1114
	if ($config['system']['webgui']['protocol'] == "https") {
1115
		// Ensure that we have a webConfigurator CERT
1116
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
1117
		if (!is_array($cert) || !$cert['crt'] || !$cert['prv']) {
1118
			$cert = system_webgui_create_certificate();
1119
		}
1120
		$crt = base64_decode($cert['crt']);
1121
		$key = base64_decode($cert['prv']);
1122

    
1123
		if (!$config['system']['webgui']['port']) {
1124
			$portarg = "443";
1125
		}
1126
		$ca = ca_chain($cert);
1127
		$hsts = isset($config['system']['webgui']['disablehsts']) ? false : true;
1128
	}
1129

    
1130
	/* generate nginx configuration */
1131
	system_generate_nginx_config("{$g['varetc_path']}/nginx-webConfigurator.conf",
1132
		$crt, $key, $ca, "nginx-webConfigurator.pid", $portarg, "/usr/local/www/",
1133
		"cert.crt", "cert.key", false, $hsts);
1134

    
1135
	/* kill any running nginx */
1136
	killbypid("{$g['varrun_path']}/nginx-webConfigurator.pid");
1137

    
1138
	sleep(1);
1139

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

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

    
1145
	if (platform_booting()) {
1146
		if ($res == 0) {
1147
			echo gettext("done.") . "\n";
1148
		} else {
1149
			echo gettext("failed!") . "\n";
1150
		}
1151
	}
1152

    
1153
	return $res;
1154
}
1155

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

    
1174
	$dns_nameservers = array();
1175

    
1176
	if (isset($config['system']['developerspew'])) {
1177
		$mt = microtime();
1178
		echo "get_dns_nameservers() being called $mt\n";
1179
	}
1180

    
1181
	$syscfg = $config['system'];
1182
	if ((((isset($config['dnsmasq']['enable'])) &&
1183
	    (empty($config['dnsmasq']['port']) || $config['dnsmasq']['port'] == "53") &&
1184
	    (empty($config['dnsmasq']['interface']) ||
1185
	    in_array("lo0", explode(",", $config['dnsmasq']['interface'])))) ||
1186
	    ((isset($config['unbound']['enable'])) &&
1187
	    (empty($config['unbound']['port']) || $config['unbound']['port'] == "53") &&
1188
	    (empty($config['unbound']['active_interface']) ||
1189
	    in_array("lo0", explode(",", $config['unbound']['active_interface'])) ||
1190
	    in_array("all", explode(",", $config['unbound']['active_interface']), true)))) &&
1191
	    ($config['system']['dnslocalhost'] != 'remote')) {
1192
		$dns_nameservers[] = "127.0.0.1";
1193
	}
1194

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

    
1221
function system_generate_nginx_config($filename,
1222
	$cert,
1223
	$key,
1224
	$ca,
1225
	$pid_file,
1226
	$port = 80,
1227
	$document_root = "/usr/local/www/",
1228
	$cert_location = "cert.crt",
1229
	$key_location = "cert.key",
1230
	$captive_portal = false,
1231
	$hsts = true) {
1232

    
1233
	global $config, $g;
1234

    
1235
	if (isset($config['system']['developerspew'])) {
1236
		$mt = microtime();
1237
		echo "system_generate_nginx_config() being called $mt\n";
1238
	}
1239

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

    
1261
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1262
		if (empty($maxprocperip)) {
1263
			$maxprocperip = 10;
1264
		}
1265
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1266
	}
1267

    
1268
	if (empty($port)) {
1269
		$nginx_port = "80";
1270
	} else {
1271
		$nginx_port = $port;
1272
	}
1273

    
1274
	$memory = get_memory();
1275
	$realmem = $memory[1];
1276

    
1277
	// Determine web GUI process settings and take into account low memory systems
1278
	if ($realmem < 255) {
1279
		$max_procs = 1;
1280
	} else {
1281
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
1282
	}
1283

    
1284
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM
1285
	if ($captive_portal !== false) {
1286
		if ($realmem > 135 and $realmem < 256) {
1287
			$max_procs += 1; // 2 worker processes
1288
		} else if ($realmem > 255 and $realmem < 513) {
1289
			$max_procs += 2; // 3 worker processes
1290
		} else if ($realmem > 512) {
1291
			$max_procs += 4; // 6 worker processes
1292
		}
1293
	}
1294

    
1295
	$nginx_config = <<<EOD
1296
#
1297
# nginx configuration file
1298

    
1299
pid {$g['varrun_path']}/{$pid_file};
1300

    
1301
user  root wheel;
1302
worker_processes  {$max_procs};
1303

    
1304
EOD;
1305

    
1306
	/* Disable file logging */
1307
	$nginx_config .= "error_log /dev/null;\n";
1308
	if (!isset($config['syslog']['nolognginx'])) {
1309
		/* Send nginx error log to syslog */
1310
		$nginx_config .= "error_log  syslog:server=unix:/var/run/log,facility=local5;\n";
1311
	}
1312

    
1313
	$nginx_config .= <<<EOD
1314

    
1315
events {
1316
    worker_connections  1024;
1317
}
1318

    
1319
http {
1320
	include       /usr/local/etc/nginx/mime.types;
1321
	default_type  application/octet-stream;
1322
	add_header X-Frame-Options SAMEORIGIN;
1323
	server_tokens off;
1324

    
1325
	sendfile        on;
1326

    
1327
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1328

    
1329
EOD;
1330

    
1331
	if ($captive_portal !== false) {
1332
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1333
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1334
	} else {
1335
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1336
	}
1337

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

    
1378
	$nginx_config .= <<<EOD
1379

    
1380
		client_max_body_size 200m;
1381

    
1382
		gzip on;
1383
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
1384

    
1385

    
1386
EOD;
1387

    
1388
	if ($captive_portal !== false) {
1389
		$nginx_config .= <<<EOD
1390
$captive_portal_maxprocperip
1391
$cp_hostcheck
1392
$cp_rewrite
1393
		log_not_found off;
1394

    
1395
EOD;
1396

    
1397
	}
1398

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

    
1433
EOD;
1434

    
1435
	$cert = str_replace("\r", "", $cert);
1436
	$key = str_replace("\r", "", $key);
1437

    
1438
	$cert = str_replace("\n\n", "\n", $cert);
1439
	$key = str_replace("\n\n", "\n", $key);
1440

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

    
1465
	// Add HTTP to HTTPS redirect
1466
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1467
		if ($nginx_port != "443") {
1468
			$redirectport = ":{$nginx_port}";
1469
		}
1470
		$nginx_config .= <<<EOD
1471
	server {
1472
		listen 80;
1473
		listen [::]:80;
1474
		return 301 https://\$http_host$redirectport\$request_uri;
1475
	}
1476

    
1477
EOD;
1478
	}
1479

    
1480
	$nginx_config .= "}\n";
1481

    
1482
	$fd = fopen("{$filename}", "w");
1483
	if (!$fd) {
1484
		printf(gettext('Error: cannot open %1$s in system_generate_nginx_config().%2$s'), $filename, "\n");
1485
		return 1;
1486
	}
1487
	fwrite($fd, $nginx_config);
1488
	fclose($fd);
1489

    
1490
	/* nginx will fail to start if this directory does not exist. */
1491
	safe_mkdir("/var/tmp/nginx/");
1492

    
1493
	return 0;
1494

    
1495
}
1496

    
1497
function system_get_timezone_list() {
1498
	global $g;
1499

    
1500
	$file_list = array_merge(
1501
		glob("/usr/share/zoneinfo/[A-Z]*"),
1502
		glob("/usr/share/zoneinfo/*/*"),
1503
		glob("/usr/share/zoneinfo/*/*/*")
1504
	);
1505

    
1506
	if (empty($file_list)) {
1507
		$file_list[] = $g['default_timezone'];
1508
	} else {
1509
		/* Remove directories from list */
1510
		$file_list = array_filter($file_list, function($v) {
1511
			return !is_dir($v);
1512
		});
1513
	}
1514

    
1515
	/* Remove directory prefix */
1516
	$file_list = str_replace('/usr/share/zoneinfo/', '', $file_list);
1517

    
1518
	sort($file_list);
1519

    
1520
	return $file_list;
1521
}
1522

    
1523
function system_timezone_configure() {
1524
	global $config, $g;
1525
	if (isset($config['system']['developerspew'])) {
1526
		$mt = microtime();
1527
		echo "system_timezone_configure() being called $mt\n";
1528
	}
1529

    
1530
	$syscfg = $config['system'];
1531

    
1532
	if (platform_booting()) {
1533
		echo gettext("Setting timezone...");
1534
	}
1535

    
1536
	/* extract appropriate timezone file */
1537
	$timezone = (isset($syscfg['timezone']) ? $syscfg['timezone'] : $g['default_timezone']);
1538
	/* DO NOT remove \n otherwise tzsetup will fail */
1539
	@file_put_contents("/var/db/zoneinfo", $timezone . "\n");
1540
	mwexec("/usr/sbin/tzsetup -r");
1541

    
1542
	if (platform_booting()) {
1543
		echo gettext("done.") . "\n";
1544
	}
1545
}
1546

    
1547
function check_gps_speed($device) {
1548
	usleep(1000);
1549
	// Set timeout to 5s
1550
	$timeout=microtime(true)+5;
1551
	if ($fp = fopen($device, 'r')) {
1552
		stream_set_blocking($fp, 0);
1553
		stream_set_timeout($fp, 5);
1554
		$contents = "";
1555
		$cnt = 0;
1556
		$buffersize = 256;
1557
		do {
1558
			$c = fread($fp, $buffersize - $cnt);
1559

    
1560
			// Wait for data to arive
1561
			if (($c === false) || (strlen($c) == 0)) {
1562
				usleep(500);
1563
				continue;
1564
			}
1565

    
1566
			$contents.=$c;
1567
			$cnt = $cnt + strlen($c);
1568
		} while (($cnt < $buffersize) && (microtime(true) < $timeout));
1569
		fclose($fp);
1570

    
1571
		$nmeasentences = ['RMC', 'GGA', 'GLL', 'ZDA', 'ZDG', 'PGRMF'];
1572
		foreach ($nmeasentences as $sentence) {
1573
			if (strpos($contents, $sentence) > 0) {
1574
				return true;
1575
			}
1576
		}
1577
		if (strpos($contents, '0') > 0) {
1578
			$filters = ['`', '?', '/', '~'];
1579
			foreach ($filters as $filter) {
1580
				if (strpos($contents, $filter) !== false) {
1581
					return false;
1582
				}
1583
			}
1584
			return true;
1585
		}
1586
	}
1587
	return false;
1588
}
1589

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

    
1610
function system_ntp_poll_values() {
1611
	global $ntp_poll_min_value, $ntp_poll_max_value;
1612
	$poll_values = array("" => gettext('Default'));
1613

    
1614
	for ($i = $ntp_poll_min_value; $i <= $ntp_poll_max_value; $i++) {
1615
		$sec = 2 ** $i;
1616
		$poll_values[$i] = $i . ': ' . number_format($sec) . ' ' . gettext('seconds') .
1617
					' (' . convert_seconds_to_dhms($sec) . ')';
1618
	}
1619

    
1620
	$poll_values['omit'] = gettext('Omit (Do not set)');
1621
	return $poll_values;
1622
}
1623

    
1624
function system_ntp_fixup_poll_value($type, $configvalue, $default) {
1625
	$pollstring = "";
1626

    
1627
	if (empty($configvalue)) {
1628
		$configvalue = $default;
1629
	}
1630

    
1631
	if ($configvalue != 'omit') {
1632
		$pollstring = " {$type} {$configvalue}";
1633
	}
1634

    
1635
	return $pollstring;
1636
}
1637

    
1638
function system_ntp_setup_gps($serialport) {
1639
	global $config, $g;
1640

    
1641
	if (is_array($config['ntpd']) && ($config['ntpd']['enable'] == 'disabled')) {
1642
		return false;
1643
	}
1644

    
1645
	init_config_arr(array('ntpd', 'gps'));
1646

    
1647
	$gps_device = '/dev/gps0';
1648
	$serialport = '/dev/'.$serialport;
1649

    
1650
	if (!file_exists($serialport)) {
1651
		return false;
1652
	}
1653

    
1654
	// Create symlink that ntpd requires
1655
	unlink_if_exists($gps_device);
1656
	@symlink($serialport, $gps_device);
1657

    
1658
	$gpsbaud = '4800';
1659
	$speeds = array(
1660
		0 => '4800', 
1661
		16 => '9600', 
1662
		32 => '19200', 
1663
		48 => '38400', 
1664
		64 => '57600', 
1665
		80 => '115200'
1666
	);
1667
	if (!empty($config['ntpd']['gps']['speed']) && array_key_exists($config['ntpd']['gps']['speed'], $speeds)) {
1668
		$gpsbaud = $speeds[$config['ntpd']['gps']['speed']];
1669
	}
1670

    
1671
	system_ntp_setup_rawspeed($serialport, $gpsbaud);
1672

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

    
1696
	/* Send the following to the GPS port to initialize the GPS */
1697
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
1698
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
1699
	} else {
1700
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1701
	}
1702

    
1703
	/* XXX: Why not file_put_contents to the device */
1704
	@file_put_contents('/tmp/gps.init', $gps_init);
1705
	mwexec("cat /tmp/gps.init > {$serialport}");
1706

    
1707
	if ($found && $config['ntpd']['gps']['autobaudinit']) {
1708
		system_ntp_setup_rawspeed($serialport, $gpsbaud);
1709
	}
1710

    
1711
	/* Remove old /etc/remote entry if it exists */
1712
	if (mwexec("/usr/bin/grep -c '^gps0' /etc/remote") == 0) {
1713
		mwexec("/usr/bin/sed -i '' -n '/gps0/!p' /etc/remote");
1714
	}
1715

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

    
1721
	return true;
1722
}
1723

    
1724
// Configure the serial port for raw IO and set the speed
1725
function system_ntp_setup_rawspeed($serialport, $baud) {
1726
	mwexec("/bin/stty -f " .  escapeshellarg($serialport) . " raw speed " . escapeshellarg($baud));
1727
	mwexec("/bin/stty -f " .  escapeshellarg($serialport) . ".init raw speed " . escapeshellarg($baud));
1728
}
1729

    
1730
function system_ntp_setup_pps($serialport) {
1731
	global $config, $g;
1732

    
1733
	$pps_device = '/dev/pps0';
1734
	$serialport = '/dev/'.$serialport;
1735

    
1736
	if (!file_exists($serialport)) {
1737
		return false;
1738
	}
1739
	// If ntpd is disabled, just return
1740
	if (is_array($config['ntpd']) && ($config['ntpd']['enable'] == 'disabled')) {
1741
		return false;
1742
	}
1743

    
1744
	// Create symlink that ntpd requires
1745
	unlink_if_exists($pps_device);
1746
	@symlink($serialport, $pps_device);
1747

    
1748

    
1749
	return true;
1750
}
1751

    
1752
function system_ntp_configure() {
1753
	global $config, $g;
1754
	global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
1755
	global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
1756
	global $ntp_poll_min_default, $ntp_poll_max_default;
1757

    
1758
	$driftfile = "/var/db/ntpd.drift";
1759
	$statsdir = "/var/log/ntp";
1760
	$gps_device = '/dev/gps0';
1761

    
1762
	safe_mkdir($statsdir);
1763

    
1764
	if (!is_array($config['ntpd'])) {
1765
		$config['ntpd'] = array();
1766
	}
1767
	// ntpd is disabled, just stop it and return
1768
	if ($config['ntpd']['enable'] == 'disabled') {
1769
		while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1770
			killbypid("{$g['varrun_path']}/ntpd.pid");
1771
		}
1772
		@unlink("{$g['varrun_path']}/ntpd.pid");
1773
		@unlink("{$g['varetc_path']}/ntpd.conf");
1774
		@unlink("{$g['varetc_path']}/ntp.keys");
1775
		log_error("NTPD is disabled.");
1776
		return;
1777
	}
1778

    
1779
	if (platform_booting()) {
1780
		echo gettext("Starting NTP Server...");
1781
	}
1782

    
1783
	/* if ntpd is running, kill it */
1784
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1785
		killbypid("{$g['varrun_path']}/ntpd.pid");
1786
	}
1787
	@unlink("{$g['varrun_path']}/ntpd.pid");
1788

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

    
1800
	$ntpcfg = "# \n";
1801
	$ntpcfg .= "# pfSense ntp configuration file \n";
1802
	$ntpcfg .= "# \n\n";
1803
	$ntpcfg .= "tinker panic 0 \n\n";
1804

    
1805
	if ($config['ntpd']['serverauth'] == 'yes') {
1806
		$ntpcfg .= "# Authentication settings \n";
1807
		$ntpcfg .= "keys /var/etc/ntp.keys \n";
1808
		$ntpcfg .= "trustedkey 1 \n";
1809
		$ntpcfg .= "requestkey 1 \n";
1810
		$ntpcfg .= "controlkey 1 \n";
1811
		$ntpcfg .= "\n";
1812
	}
1813

    
1814
	/* Add Orphan mode */
1815
	$ntpcfg .= "# Orphan mode stratum and Maximum candidate NTP peers\n";
1816
	$ntpcfg .= 'tos orphan ';
1817
	if (!empty($config['ntpd']['orphan'])) {
1818
		$ntpcfg .= $config['ntpd']['orphan'];
1819
	} else {
1820
		$ntpcfg .= '12';
1821
	}
1822
	/* Add Maximum candidate NTP peers */
1823
	$ntpcfg .= ' maxclock ';
1824
	if (!empty($config['ntpd']['ntpmaxpeers'])) {
1825
		$ntpcfg .= $config['ntpd']['ntpmaxpeers'];
1826
	} else {
1827
		$ntpcfg .= '5';
1828
	}
1829
	$ntpcfg .= "\n";
1830

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

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

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

    
1967
		$ntpcfg .= "{$ts} iburst";
1968

    
1969
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', $config['ntpd']['ntpminpoll'], $ntp_poll_min_default);
1970
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', $config['ntpd']['ntpmaxpoll'], $ntp_poll_max_default);
1971

    
1972
		if (substr_count($config['ntpd']['prefer'], $ts)) {
1973
			$ntpcfg .= ' prefer';
1974
		}
1975
		if (substr_count($config['ntpd']['noselect'], $ts)) {
1976
			$ntpcfg .= ' noselect';
1977
		}
1978
		$ntpcfg .= "\n";
1979
	}
1980
	unset($ts);
1981

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

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

    
2048
	/* Pools require "restrict source" and cannot contain "nopeer" and "noserve". */
2049
	if ($have_pools) {
2050
		$ntpcfg .= "\nrestrict source";
2051
		if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
2052
			$ntpcfg .= ' kod limited';
2053
		}
2054
		if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
2055
			$ntpcfg .= ' nomodify';
2056
		}
2057
		if (!empty($config['ntpd']['noquery'])) {
2058
			$ntpcfg .= ' noquery';
2059
		}
2060
		if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
2061
			$ntpcfg .= ' notrap';
2062
		}
2063
	}
2064

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

    
2102
	/* A leapseconds file is really only useful if this clock is stratum 1 */
2103
	$ntpcfg .= "\n";
2104
	if (!empty($config['ntpd']['leapsec'])) {
2105
		$leapsec .= base64_decode($config['ntpd']['leapsec']);
2106
		file_put_contents('/var/db/leap-seconds', $leapsec);
2107
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
2108
	}
2109

    
2110

    
2111
	if (empty($config['ntpd']['interface'])) {
2112
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface'])) {
2113
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
2114
		} else {
2115
			$interfaces = array();
2116
		}
2117
	} else {
2118
		$interfaces = explode(",", $config['ntpd']['interface']);
2119
	}
2120

    
2121
	if (is_array($interfaces) && count($interfaces)) {
2122
		$finterfaces = array();
2123
		$ntpcfg .= "interface ignore all\n";
2124
		$ntpcfg .= "interface ignore wildcard\n";
2125
		foreach ($interfaces as $interface) {
2126
			$interface = get_real_interface($interface);
2127
			if (!empty($interface)) {
2128
				$finterfaces[] = $interface;
2129
			}
2130
		}
2131
		foreach ($finterfaces as $interface) {
2132
			$ntpcfg .= "interface listen {$interface}\n";
2133
		}
2134
	}
2135

    
2136
	/* open configuration for writing or bail */
2137
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
2138
		log_error(sprintf(gettext("Could not open %s/ntpd.conf for writing"), $g['varetc_path']));
2139
		return;
2140
	}
2141

    
2142
	/* if /var/empty does not exist, create it */
2143
	if (!is_dir("/var/empty")) {
2144
		mkdir("/var/empty", 0555, true);
2145
	}
2146

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

    
2150
	// Note that we are starting up
2151
	log_error("NTPD is starting up.");
2152

    
2153
	if (platform_booting()) {
2154
		echo gettext("done.") . "\n";
2155
	}
2156

    
2157
	return;
2158
}
2159

    
2160
function system_halt() {
2161
	global $g;
2162

    
2163
	system_reboot_cleanup();
2164

    
2165
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
2166
}
2167

    
2168
function system_reboot() {
2169
	global $g;
2170

    
2171
	system_reboot_cleanup();
2172

    
2173
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
2174
}
2175

    
2176
function system_reboot_sync($reroot=false) {
2177
	global $g;
2178

    
2179
	if ($reroot) {
2180
		$args = " -r ";
2181
	}
2182

    
2183
	system_reboot_cleanup();
2184

    
2185
	mwexec("/etc/rc.reboot {$args} > /dev/null 2>&1");
2186
}
2187

    
2188
function system_reboot_cleanup() {
2189
	global $config, $g, $cpzone;
2190

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

    
2213
function system_do_shell_commands($early = 0) {
2214
	global $config, $g;
2215
	if (isset($config['system']['developerspew'])) {
2216
		$mt = microtime();
2217
		echo "system_do_shell_commands() being called $mt\n";
2218
	}
2219

    
2220
	if ($early) {
2221
		$cmdn = "earlyshellcmd";
2222
	} else {
2223
		$cmdn = "shellcmd";
2224
	}
2225

    
2226
	if (is_array($config['system'][$cmdn])) {
2227

    
2228
		/* *cmd is an array, loop through */
2229
		foreach ($config['system'][$cmdn] as $cmd) {
2230
			exec($cmd);
2231
		}
2232

    
2233
	} elseif ($config['system'][$cmdn] <> "") {
2234

    
2235
		/* execute single item */
2236
		exec($config['system'][$cmdn]);
2237

    
2238
	}
2239
}
2240

    
2241
function system_dmesg_save() {
2242
	global $g;
2243
	if (isset($config['system']['developerspew'])) {
2244
		$mt = microtime();
2245
		echo "system_dmesg_save() being called $mt\n";
2246
	}
2247

    
2248
	$dmesg = "";
2249
	$_gb = exec("/sbin/dmesg", $dmesg);
2250

    
2251
	/* find last copyright line (output from previous boots may be present) */
2252
	$lastcpline = 0;
2253

    
2254
	for ($i = 0; $i < count($dmesg); $i++) {
2255
		if (strstr($dmesg[$i], "Copyright (c) 1992-")) {
2256
			$lastcpline = $i;
2257
		}
2258
	}
2259

    
2260
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
2261
	if (!$fd) {
2262
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
2263
		return 1;
2264
	}
2265

    
2266
	for ($i = $lastcpline; $i < count($dmesg); $i++) {
2267
		fwrite($fd, $dmesg[$i] . "\n");
2268
	}
2269

    
2270
	fclose($fd);
2271
	unset($dmesg);
2272

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

    
2276
	return 0;
2277
}
2278

    
2279
function system_set_harddisk_standby() {
2280
	global $g, $config;
2281

    
2282
	if (isset($config['system']['developerspew'])) {
2283
		$mt = microtime();
2284
		echo "system_set_harddisk_standby() being called $mt\n";
2285
	}
2286

    
2287
	if (isset($config['system']['harddiskstandby'])) {
2288
		if (platform_booting()) {
2289
			echo gettext('Setting hard disk standby... ');
2290
		}
2291

    
2292
		$standby = $config['system']['harddiskstandby'];
2293
		// Check for a numeric value
2294
		if (is_numeric($standby)) {
2295
			// Get only suitable candidates for standby; using get_smart_drive_list()
2296
			// from utils.inc to get the list of drives.
2297
			$harddisks = get_smart_drive_list();
2298

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

    
2318
function system_setup_sysctl() {
2319
	global $config;
2320
	if (isset($config['system']['developerspew'])) {
2321
		$mt = microtime();
2322
		echo "system_setup_sysctl() being called $mt\n";
2323
	}
2324

    
2325
	activate_sysctls();
2326

    
2327
	if (isset($config['system']['sharednet'])) {
2328
		system_disable_arp_wrong_if();
2329
	}
2330
}
2331

    
2332
function system_disable_arp_wrong_if() {
2333
	global $config;
2334
	if (isset($config['system']['developerspew'])) {
2335
		$mt = microtime();
2336
		echo "system_disable_arp_wrong_if() being called $mt\n";
2337
	}
2338
	set_sysctl(array(
2339
		"net.link.ether.inet.log_arp_wrong_iface" => "0",
2340
		"net.link.ether.inet.log_arp_movements" => "0"
2341
	));
2342
}
2343

    
2344
function system_enable_arp_wrong_if() {
2345
	global $config;
2346
	if (isset($config['system']['developerspew'])) {
2347
		$mt = microtime();
2348
		echo "system_enable_arp_wrong_if() being called $mt\n";
2349
	}
2350
	set_sysctl(array(
2351
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
2352
		"net.link.ether.inet.log_arp_movements" => "1"
2353
	));
2354
}
2355

    
2356
function enable_watchdog() {
2357
	global $config;
2358
	return;
2359
	$install_watchdog = false;
2360
	$supported_watchdogs = array("Geode");
2361
	$file = file_get_contents("/var/log/dmesg.boot");
2362
	foreach ($supported_watchdogs as $sd) {
2363
		if (stristr($file, "Geode")) {
2364
			$install_watchdog = true;
2365
		}
2366
	}
2367
	if ($install_watchdog == true) {
2368
		if (is_process_running("watchdogd")) {
2369
			mwexec("/usr/bin/killall watchdogd", true);
2370
		}
2371
		exec("/usr/sbin/watchdogd");
2372
	}
2373
}
2374

    
2375
function system_check_reset_button() {
2376
	global $g;
2377

    
2378
	$specplatform = system_identify_specific_platform();
2379

    
2380
	switch ($specplatform['name']) {
2381
		case 'SG-2220':
2382
			$binprefix = "RCC-DFF";
2383
			break;
2384
		case 'alix':
2385
		case 'wrap':
2386
		case 'FW7541':
2387
		case 'APU':
2388
		case 'RCC-VE':
2389
		case 'RCC':
2390
			$binprefix = $specplatform['name'];
2391
			break;
2392
		default:
2393
			return 0;
2394
	}
2395

    
2396
	$retval = mwexec("/usr/local/sbin/" . $binprefix . "resetbtn");
2397

    
2398
	if ($retval == 99) {
2399
		/* user has pressed reset button for 2 seconds -
2400
		   reset to factory defaults */
2401
		echo <<<EOD
2402

    
2403
***********************************************************************
2404
* Reset button pressed - resetting configuration to factory defaults. *
2405
* All additional packages installed will be removed                   *
2406
* The system will reboot after this completes.                        *
2407
***********************************************************************
2408

    
2409

    
2410
EOD;
2411

    
2412
		reset_factory_defaults();
2413
		system_reboot_sync();
2414
		exit(0);
2415
	}
2416

    
2417
	return 0;
2418
}
2419

    
2420
function system_get_serial() {
2421
	$platform = system_identify_specific_platform();
2422

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

    
2442
	$vm_guest = get_single_sysctl('kern.vm_guest');
2443

    
2444
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2445
	    $vm_guest == 'none') {
2446
		return $serial;
2447
	}
2448

    
2449
	return "";
2450
}
2451

    
2452
function system_get_uniqueid() {
2453
	global $g;
2454

    
2455
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2456

    
2457
	if (empty($g['uniqueid'])) {
2458
		if (!file_exists($uniqueid_file)) {
2459
			mwexec("/usr/sbin/gnid > {$g['vardb_path']}/uniqueid " .
2460
			    "2>/dev/null");
2461
		}
2462
		if (file_exists($uniqueid_file)) {
2463
			$g['uniqueid'] = @file_get_contents($uniqueid_file);
2464
		}
2465
	}
2466

    
2467
	return ($g['uniqueid'] ?: '');
2468
}
2469

    
2470
/*
2471
 * attempt to identify the specific platform (for embedded systems)
2472
 * Returns an array with two elements:
2473
 * name => platform string (e.g. 'wrap', 'alix' etc.)
2474
 * descr => human-readable description (e.g. "PC Engines WRAP")
2475
 */
2476
function system_identify_specific_platform() {
2477
	global $g;
2478

    
2479
	$hw_model = get_single_sysctl('hw.model');
2480
	$hw_ncpu = get_single_sysctl('hw.ncpu');
2481

    
2482
	/* Try to guess from smbios strings */
2483
	unset($product);
2484
	unset($maker);
2485
	unset($bios);
2486
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $product);
2487
	$_gb = exec('/bin/kenv -q smbios.system.maker 2>/dev/null', $maker);
2488
	$_gb = exec('/bin/kenv -q smbios.bios.version 2>/dev/null', $bios);
2489

    
2490
	// AWS can only be identified via the bios version
2491
	if (stripos($bios[0], "amazon") !== false) {
2492
		return (array('name' => 'AWS', 'descr' => 'Amazon Web Services'));
2493
	} else  if (stripos($bios[0], "Google") !== false) {
2494
		return (array('name' => 'Google', 'descr' => 'Google Cloud Platform'));
2495
	}
2496

    
2497
	switch ($product[0]) {
2498
		case 'FW7541':
2499
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2500
			break;
2501
		case 'APU':
2502
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2503
			break;
2504
		case 'RCC-VE':
2505
			$result = array();
2506
			$result['name'] = 'RCC-VE';
2507

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

    
2593
	$_gb = exec('/bin/kenv -q smbios.planar.product 2>/dev/null',
2594
	    $planar_product);
2595
	if (isset($planar_product[0]) &&
2596
	    $planar_product[0] == 'X10SDV-8C-TLN4F+') {
2597
		return array('name' => 'XG-1537', 'descr' => 'Super Micro XG-1537');
2598
	}
2599

    
2600
	if (strpos($hw_model, "PC Engines WRAP") !== false) {
2601
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
2602
	}
2603

    
2604
	if (strpos($hw_model, "PC Engines ALIX") !== false) {
2605
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2606
	}
2607

    
2608
	if (preg_match("/Soekris net45../", $hw_model, $matches)) {
2609
		return array('name' => 'net45xx', 'descr' => $matches[0]);
2610
	}
2611

    
2612
	if (preg_match("/Soekris net48../", $hw_model, $matches)) {
2613
		return array('name' => 'net48xx', 'descr' => $matches[0]);
2614
	}
2615

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

    
2620
	unset($hw_model);
2621

    
2622
	$dmesg_boot = system_get_dmesg_boot();
2623
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
2624
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2625
	}
2626
	unset($dmesg_boot);
2627

    
2628
	return array('name' => $g['product_name'], 'descr' => $g['product_label']);
2629
}
2630

    
2631
function system_get_dmesg_boot() {
2632
	global $g;
2633

    
2634
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2635
}
2636

    
2637
function system_get_arp_table($resolve_hostnames = false) {
2638
	$params="-a";
2639
	if (!$resolve_hostnames) {
2640
		$params .= "n";
2641
	}
2642

    
2643
	$arp_table = array();
2644
	$_gb = exec("/usr/sbin/arp --libxo json {$params}", $rawdata, $rc);
2645
	if ($rc == 0) {
2646
		$arp_table = json_decode(implode(" ", $rawdata),
2647
		    JSON_OBJECT_AS_ARRAY);
2648
		if ($rc == 0) {
2649
			$arp_table = $arp_table['arp']['arp-cache'];
2650
		}
2651
	}
2652

    
2653
	return $arp_table;
2654
}
2655

    
2656
?>
(49-49/61)