Project

General

Profile

Download (70.4 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * system.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2004-2013 BSD Perimeter
7
 * Copyright (c) 2013-2016 Electric Sheep Fencing
8
 * Copyright (c) 2014-2020 Rubicon Communications, LLC (Netgate)
9
 * All rights reserved.
10
 *
11
 * originally part of m0n0wall (http://m0n0.ch/wall)
12
 * Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>.
13
 * All rights reserved.
14
 *
15
 * Licensed under the Apache License, Version 2.0 (the "License");
16
 * you may not use this file except in compliance with the License.
17
 * You may obtain a copy of the License at
18
 *
19
 * http://www.apache.org/licenses/LICENSE-2.0
20
 *
21
 * Unless required by applicable law or agreed to in writing, software
22
 * distributed under the License is distributed on an "AS IS" BASIS,
23
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24
 * See the License for the specific language governing permissions and
25
 * limitations under the License.
26
 */
27

    
28
require_once('syslog.inc');
29

    
30
function activate_powerd() {
31
	global $config, $g;
32

    
33
	if (is_process_running("powerd")) {
34
		exec("/usr/bin/killall powerd");
35
	}
36
	if (isset($config['system']['powerd_enable'])) {
37
		$ac_mode = "hadp";
38
		if (!empty($config['system']['powerd_ac_mode'])) {
39
			$ac_mode = $config['system']['powerd_ac_mode'];
40
		}
41

    
42
		$battery_mode = "hadp";
43
		if (!empty($config['system']['powerd_battery_mode'])) {
44
			$battery_mode = $config['system']['powerd_battery_mode'];
45
		}
46

    
47
		$normal_mode = "hadp";
48
		if (!empty($config['system']['powerd_normal_mode'])) {
49
			$normal_mode = $config['system']['powerd_normal_mode'];
50
		}
51

    
52
		mwexec("/usr/sbin/powerd" .
53
			" -b " . escapeshellarg($battery_mode) .
54
			" -a " . escapeshellarg($ac_mode) .
55
			" -n " . escapeshellarg($normal_mode));
56
	}
57
}
58

    
59
function get_default_sysctl_value($id) {
60
	global $sysctls;
61

    
62
	if (isset($sysctls[$id])) {
63
		return $sysctls[$id];
64
	}
65
}
66

    
67
function get_sysctl_descr($sysctl) {
68
	unset($output);
69
	$_gb = exec("/sbin/sysctl -qnd {$sysctl}", $output);
70

    
71
	return $output[0];
72
}
73

    
74
function system_get_sysctls() {
75
	global $config, $sysctls;
76

    
77
	$disp_sysctl = array();
78
	$disp_cache = array();
79
	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
80
		foreach ($config['sysctl']['item'] as $id => $tunable) {
81
			if ($tunable['value'] == "default") {
82
				$value = get_default_sysctl_value($tunable['tunable']);
83
			} else {
84
				$value = $tunable['value'];
85
			}
86

    
87
			$disp_sysctl[$id] = $tunable;
88
			$disp_sysctl[$id]['modified'] = true;
89
			$disp_cache[$tunable['tunable']] = 'set';
90
		}
91
	}
92

    
93
	foreach ($sysctls as $sysctl => $value) {
94
		if (isset($disp_cache[$sysctl])) {
95
			continue;
96
		}
97

    
98
		$disp_sysctl[$sysctl] = array('tunable' => $sysctl, 'value' => $value, 'descr' => get_sysctl_descr($sysctl));
99
	}
100
	unset($disp_cache);
101
	return $disp_sysctl;
102
}
103

    
104
function activate_sysctls() {
105
	global $config, $g, $sysctls;
106

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

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

    
119
	set_sysctl($sysctls);
120
}
121

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

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

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

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

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

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

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

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

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

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

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

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

    
217
	unlock($dnslock);
218

    
219
	return 0;
220
}
221

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

    
225
	$master_list = array();
226

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

    
243
	return $master_list;
244
}
245

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

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

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

    
278
	return $master_list;
279
}
280

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

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

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

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

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

    
340
	return $hosts;
341
}
342

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

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

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

    
360
		foreach (explode(',', $host['ip']) as $ip) {
361
			$hosts[] = array(
362
			    'ipaddr' => $ip,
363
			    'fqdn' => $fqdn,
364
			    'name' => $host['host'],
365
			    'domain' => $host['domain']
366
			);
367
		}
368

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

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

    
381
			foreach (explode(',', $host['ip']) as $ip) {
382
				$hosts[] = array(
383
				    'ipaddr' => $ip,
384
				    'fqdn' => $fqdn,
385
				    'name' => $alias['host'],
386
				    'domain' => $alias['domain']
387
				);
388
			}
389
		}
390
	}
391

    
392
	return $hosts;
393
}
394

    
395
/* Read all dhcpd/dhcpdv6 staticmap entries */
396
function system_hosts_dhcpd_entries() {
397
	global $config;
398

    
399
	$hosts = array();
400
	$syscfg = $config['system'];
401

    
402
	if (is_array($config['dhcpd'])) {
403
		$conf_dhcpd = $config['dhcpd'];
404
	} else {
405
		$conf_dhcpd = array();
406
	}
407

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

    
419
			$fqdn = $host['hostname'] . ".";
420
			$domain = "";
421
			if ($host['domain']) {
422
				$domain = $host['domain'];
423
			} elseif ($dhcpifconf['domain']) {
424
				$domain = $dhcpifconf['domain'];
425
			} else {
426
				$domain = $syscfg['domain'];
427
			}
428

    
429
			$hosts[] = array(
430
			    'ipaddr' => $host['ipaddr'],
431
			    'fqdn' => $fqdn . $domain,
432
			    'name' => $host['hostname'],
433
			    'domain' => $domain
434
			);
435
		}
436
	}
437
	unset($conf_dhcpd);
438

    
439
	if (is_array($config['dhcpdv6'])) {
440
		$conf_dhcpdv6 = $config['dhcpdv6'];
441
	} else {
442
		$conf_dhcpdv6 = array();
443
	}
444

    
445
	foreach ($conf_dhcpdv6 as $dhcpif => $dhcpifconf) {
446
		if (!is_array($dhcpifconf['staticmap']) ||
447
		    !isset($dhcpifconf['enable'])) {
448
			continue;
449
		}
450

    
451
		if (isset($config['interfaces'][$dhcpif]['ipaddrv6']) &&
452
		    $config['interfaces'][$dhcpif]['ipaddrv6'] ==
453
		    'track6') {
454
			$isdelegated = true;
455
		} else {
456
			$isdelegated = false;
457
		}
458

    
459
		foreach ($dhcpifconf['staticmap'] as $host) {
460
			$ipaddrv6 = $host['ipaddrv6'];
461

    
462
			if (!$ipaddrv6 || !$host['hostname']) {
463
				continue;
464
			}
465

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

    
477
			$fqdn = $host['hostname'] . ".";
478
			$domain = "";
479
			if ($host['domain']) {
480
				$domain = $host['domain'];
481
			} elseif ($dhcpifconf['domain']) {
482
				$domain = $dhcpifconf['domain'];
483
			} else {
484
				$domain = $syscfg['domain'];
485
			}
486

    
487
			$hosts[] = array(
488
			    'ipaddr' => $ipaddrv6,
489
			    'fqdn' => $fqdn . $domain,
490
			    'name' => $host['hostname'],
491
			    'domain' => $domain
492
			);
493
		}
494
	}
495
	unset($conf_dhcpdv6);
496

    
497
	return $hosts;
498
}
499

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

    
507
	$dns = array();
508
	$dhcpd = array();
509
	if (isset($dnscfg['enable'])) {
510
		$dns = system_hosts_override_entries($dnscfg);
511
		if (isset($dnscfg['regdhcpstatic'])) {
512
			$dhcpd = system_hosts_dhcpd_entries();
513
		}
514
	}
515

    
516
	if (isset($dnscfg['dhcpfirst'])) {
517
		return array_merge($local, $dns, $dhcpd);
518
	} else {
519
		return array_merge($local, $dhcpd, $dns);
520
	}
521
}
522

    
523
function system_hosts_generate() {
524
	global $config, $g;
525
	if (isset($config['system']['developerspew'])) {
526
		$mt = microtime();
527
		echo "system_hosts_generate() being called $mt\n";
528
	}
529

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

    
538
	$syscfg = $config['system'];
539
	$hosts = "";
540
	$lhosts = "";
541
	$dhosts = "";
542

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

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

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

    
572
	fwrite($fd, $hosts);
573
	fclose($fd);
574

    
575
	if (isset($config['unbound']['enable'])) {
576
		require_once("unbound.inc");
577
		unbound_hosts_generate();
578
	}
579

    
580
	/* restart dhcpleases */
581
	if (!platform_booting()) {
582
		system_dhcpleases_configure();
583
	}
584

    
585
	return 0;
586
}
587

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

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

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

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

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

    
643
function system_get_dhcpleases() {
644
	global $config, $g;
645

    
646
	$leases = array();
647
	$leases['lease'] = array();
648
	$leases['failover'] = array();
649

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

    
652
	if (!file_exists($leases_file)) {
653
		return $leases;
654
	}
655

    
656
	$leases_content = file($leases_file, FILE_IGNORE_NEW_LINES |
657
	    FILE_IGNORE_NEW_LINES);
658

    
659
	if ($leases_content === FALSE) {
660
		return $leases;
661
	}
662

    
663
	$arp_table = system_get_arp_table();
664

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

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

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

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

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

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

    
726
		if (preg_match($lease_regex, $line, $m)) {
727
			$lease = true;
728
			$item = array();
729
			$item['ip'] = $m[1];
730
			$item['type'] = $dynamic_string;
731
			continue;
732
		}
733

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

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

    
769
			if (preg_match($mac_regex, $line, $m) &&
770
			    is_macaddr($m[1])) {
771
				$item['mac'] = $m[1];
772

    
773
				if (in_array($item['ip'], $arpdata_ip)) {
774
					$item['online'] = $online_string;
775
				} else {
776
					$item['online'] = $offline_string;
777
				}
778
				continue;
779
			}
780

    
781
			if (preg_match($hostname_regex, $line, $m)) {
782
				$item['hostname'] = $m[1];
783
			}
784
		}
785

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

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

    
803
	foreach ($config['interfaces'] as $ifname => $ifarr) {
804
		if (!is_array($config['dhcpd'][$ifname]) ||
805
		    !is_array($config['dhcpd'][$ifname]['staticmap'])) {
806
			continue;
807
		}
808

    
809
		foreach ($config['dhcpd'][$ifname]['staticmap'] as $idx =>
810
		    $static) {
811
			if (empty($static['mac']) && empty($static['cid'])) {
812
				continue;
813
			}
814

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

    
836
	if ($dedup_lease) {
837
		$leases['lease'] = array_remove_duplicate($leases['lease'],
838
		    'ip');
839
	}
840
	if ($dedup_failover) {
841
		$leases['failover'] = array_remove_duplicate(
842
		    $leases['failover'], 'name');
843
		asort($leases['failover']);
844
	}
845

    
846
	return $leases;
847
}
848

    
849
function system_hostname_configure() {
850
	global $config, $g;
851
	if (isset($config['system']['developerspew'])) {
852
		$mt = microtime();
853
		echo "system_hostname_configure() being called $mt\n";
854
	}
855

    
856
	$syscfg = $config['system'];
857

    
858
	/* set hostname */
859
	$status = mwexec("/bin/hostname " .
860
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
861

    
862
	/* Setup host GUID ID.  This is used by ZFS. */
863
	mwexec("/etc/rc.d/hostid start");
864

    
865
	return $status;
866
}
867

    
868
function system_routing_configure($interface = "") {
869
	global $config, $g;
870

    
871
	if (isset($config['system']['developerspew'])) {
872
		$mt = microtime();
873
		echo "system_routing_configure() being called $mt\n";
874
	}
875

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

    
890
	$gateways_status = return_gateways_status(true);
891
	fixup_default_gateway("inet", $gateways_status, $gateways_arr);
892
	fixup_default_gateway("inet6", $gateways_status, $gateways_arr);
893

    
894
	system_staticroutes_configure($interface, false);
895

    
896
	return 0;
897
}
898

    
899
function system_staticroutes_configure($interface = "", $update_dns = false) {
900
	global $config, $g, $aliastable;
901

    
902
	$filterdns_list = array();
903

    
904
	$static_routes = get_staticroutes(false, true);
905
	if (count($static_routes)) {
906
		$gateways_arr = return_gateways_array(false, true);
907

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

    
918
			$gatewayip = $gateway['gateway'];
919
			$interfacegw = $gateway['interface'];
920

    
921
			$blackhole = "";
922
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 4))) {
923
				$blackhole = "-blackhole";
924
			}
925

    
926
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network'])) {
927
				continue;
928
			}
929

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

    
941
			if (is_subnet($rtent['network'])) {
942
				$ips = array($rtent['network']);
943
			} else {
944
				if (!isset($rtent['disabled'])) {
945
					$filterdns_list[] = $rtent['network'];
946
				}
947
				$ips = add_hostname_to_watch($rtent['network']);
948
			}
949

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

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

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

    
979
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
980

    
981
				$cmd = "{$inet} {$blackhole} {$ip} ";
982

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

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

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

    
1023
	return 0;
1024
}
1025

    
1026
function system_routing_enable() {
1027
	global $config, $g;
1028
	if (isset($config['system']['developerspew'])) {
1029
		$mt = microtime();
1030
		echo "system_routing_enable() being called $mt\n";
1031
	}
1032

    
1033
	set_sysctl(array(
1034
		"net.inet.ip.forwarding" => "1",
1035
		"net.inet6.ip6.forwarding" => "1"
1036
	));
1037

    
1038
	return;
1039
}
1040

    
1041
function system_webgui_create_certificate() {
1042
	global $config, $g, $cert_strict_values;
1043

    
1044
	init_config_arr(array('ca'));
1045
	$a_ca = &$config['ca'];
1046
	init_config_arr(array('cert'));
1047
	$a_cert = &$config['cert'];
1048
	log_error(gettext("Creating SSL/TLS Certificate for this host"));
1049

    
1050
	$cert = array();
1051
	$cert['refid'] = uniqid();
1052
	$cert['descr'] = sprintf(gettext("webConfigurator default (%s)"), $cert['refid']);
1053
	$cert_hostname = "{$config['system']['hostname']}-{$cert['refid']}";
1054

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

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

    
1075
function system_webgui_start() {
1076
	global $config, $g;
1077

    
1078
	if (platform_booting()) {
1079
		echo gettext("Starting webConfigurator...");
1080
	}
1081

    
1082
	chdir($g['www_path']);
1083

    
1084
	/* defaults */
1085
	$portarg = "80";
1086
	$crt = "";
1087
	$key = "";
1088
	$ca = "";
1089

    
1090
	/* non-standard port? */
1091
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "") {
1092
		$portarg = "{$config['system']['webgui']['port']}";
1093
	}
1094

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

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

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

    
1116
	/* kill any running nginx */
1117
	killbypid("{$g['varrun_path']}/nginx-webConfigurator.pid");
1118

    
1119
	sleep(1);
1120

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

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

    
1126
	if (platform_booting()) {
1127
		if ($res == 0) {
1128
			echo gettext("done.") . "\n";
1129
		} else {
1130
			echo gettext("failed!") . "\n";
1131
		}
1132
	}
1133

    
1134
	return $res;
1135
}
1136

    
1137
function get_dns_nameservers($add_v6_brackets = false) {
1138
	global $config;
1139

    
1140
	$dns_nameservers = array();
1141

    
1142
	if (isset($config['system']['developerspew'])) {
1143
		$mt = microtime();
1144
		echo "get_dns_nameservers() being called $mt\n";
1145
	}
1146

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

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

    
1204
	global $config, $g;
1205

    
1206
	if (isset($config['system']['developerspew'])) {
1207
		$mt = microtime();
1208
		echo "system_generate_nginx_config() being called $mt\n";
1209
	}
1210

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

    
1232
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1233
		if (empty($maxprocperip)) {
1234
			$maxprocperip = 10;
1235
		}
1236
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1237
	}
1238

    
1239
	if (empty($port)) {
1240
		$nginx_port = "80";
1241
	} else {
1242
		$nginx_port = $port;
1243
	}
1244

    
1245
	$memory = get_memory();
1246
	$realmem = $memory[1];
1247

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

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

    
1266
	$nginx_config = <<<EOD
1267
#
1268
# nginx configuration file
1269

    
1270
pid {$g['varrun_path']}/{$pid_file};
1271

    
1272
user  root wheel;
1273
worker_processes  {$max_procs};
1274

    
1275
EOD;
1276

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

    
1284
	$nginx_config .= <<<EOD
1285

    
1286
events {
1287
    worker_connections  1024;
1288
}
1289

    
1290
http {
1291
	include       /usr/local/etc/nginx/mime.types;
1292
	default_type  application/octet-stream;
1293
	add_header X-Frame-Options SAMEORIGIN;
1294
	server_tokens off;
1295

    
1296
	sendfile        on;
1297

    
1298
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1299

    
1300
EOD;
1301

    
1302
	if ($captive_portal !== false) {
1303
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1304
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1305
	} else {
1306
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1307
	}
1308

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

    
1349
	$nginx_config .= <<<EOD
1350

    
1351
		client_max_body_size 200m;
1352

    
1353
		gzip on;
1354
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
1355

    
1356

    
1357
EOD;
1358

    
1359
	if ($captive_portal !== false) {
1360
		$nginx_config .= <<<EOD
1361
$captive_portal_maxprocperip
1362
$cp_hostcheck
1363
$cp_rewrite
1364
		log_not_found off;
1365

    
1366
EOD;
1367

    
1368
	}
1369

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

    
1404
EOD;
1405

    
1406
	$cert = str_replace("\r", "", $cert);
1407
	$key = str_replace("\r", "", $key);
1408

    
1409
	$cert = str_replace("\n\n", "\n", $cert);
1410
	$key = str_replace("\n\n", "\n", $key);
1411

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

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

    
1448
EOD;
1449
	}
1450

    
1451
	$nginx_config .= "}\n";
1452

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

    
1461
	/* nginx will fail to start if this directory does not exist. */
1462
	safe_mkdir("/var/tmp/nginx/");
1463

    
1464
	return 0;
1465

    
1466
}
1467

    
1468
function system_get_timezone_list() {
1469
	global $g;
1470

    
1471
	$file_list = array_merge(
1472
		glob("/usr/share/zoneinfo/[A-Z]*"),
1473
		glob("/usr/share/zoneinfo/*/*"),
1474
		glob("/usr/share/zoneinfo/*/*/*")
1475
	);
1476

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

    
1486
	/* Remove directory prefix */
1487
	$file_list = str_replace('/usr/share/zoneinfo/', '', $file_list);
1488

    
1489
	sort($file_list);
1490

    
1491
	return $file_list;
1492
}
1493

    
1494
function system_timezone_configure() {
1495
	global $config, $g;
1496
	if (isset($config['system']['developerspew'])) {
1497
		$mt = microtime();
1498
		echo "system_timezone_configure() being called $mt\n";
1499
	}
1500

    
1501
	$syscfg = $config['system'];
1502

    
1503
	if (platform_booting()) {
1504
		echo gettext("Setting timezone...");
1505
	}
1506

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

    
1513
	if (platform_booting()) {
1514
		echo gettext("done.") . "\n";
1515
	}
1516
}
1517

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

    
1531
			// Wait for data to arive
1532
			if (($c === false) || (strlen($c) == 0)) {
1533
				usleep(500);
1534
				continue;
1535
			}
1536

    
1537
			$contents.=$c;
1538
			$cnt = $cnt + strlen($c);
1539
		} while (($cnt < $buffersize) && (microtime(true) < $timeout));
1540
		fclose($fp);
1541

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

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

    
1576
function system_ntp_poll_values() {
1577
	global $ntp_poll_min_value, $ntp_poll_max_value;
1578
	$poll_values = array("" => gettext('Default'));
1579

    
1580
	for ($i = $ntp_poll_min_value; $i <= $ntp_poll_max_value; $i++) {
1581
		$sec = 2 ** $i;
1582
		$poll_values[$i] = $i . ': ' . number_format($sec) . ' ' . gettext('seconds') .
1583
					' (' . convert_seconds_to_dhms($sec) . ')';
1584
	}
1585

    
1586
	$poll_values['omit'] = gettext('Omit (Do not set)');
1587
	return $poll_values;
1588
}
1589

    
1590
function system_ntp_fixup_poll_value($type, $configvalue, $default) {
1591
	$pollstring = "";
1592

    
1593
	if (empty($configvalue)) {
1594
		$configvalue = $default;
1595
	}
1596

    
1597
	if ($configvalue != 'omit') {
1598
		$pollstring = " {$type} {$configvalue}";
1599
	}
1600

    
1601
	return $pollstring;
1602
}
1603

    
1604
function system_ntp_setup_gps($serialport) {
1605
	global $config, $g;
1606

    
1607
	if (is_array($config['ntpd']) && ($config['ntpd']['enable'] == 'disabled')) {
1608
		return false;
1609
	}
1610

    
1611
	init_config_arr(array('ntpd', 'gps'));
1612

    
1613
	$gps_device = '/dev/gps0';
1614
	$serialport = '/dev/'.$serialport;
1615

    
1616
	if (!file_exists($serialport)) {
1617
		return false;
1618
	}
1619

    
1620
	// Create symlink that ntpd requires
1621
	unlink_if_exists($gps_device);
1622
	@symlink($serialport, $gps_device);
1623

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

    
1637
	system_ntp_setup_rawspeed($serialport, $gpsbaud);
1638

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

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

    
1669
	/* XXX: Why not file_put_contents to the device */
1670
	@file_put_contents('/tmp/gps.init', $gps_init);
1671
	mwexec("cat /tmp/gps.init > {$serialport}");
1672

    
1673
	if ($found && $config['ntpd']['gps']['autobaudinit']) {
1674
		system_ntp_setup_rawspeed($serialport, $gpsbaud);
1675
	}
1676

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

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

    
1687
	return true;
1688
}
1689

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

    
1696
function system_ntp_setup_pps($serialport) {
1697
	global $config, $g;
1698

    
1699
	$pps_device = '/dev/pps0';
1700
	$serialport = '/dev/'.$serialport;
1701

    
1702
	if (!file_exists($serialport)) {
1703
		return false;
1704
	}
1705
	// If ntpd is disabled, just return
1706
	if (is_array($config['ntpd']) && ($config['ntpd']['enable'] == 'disabled')) {
1707
		return false;
1708
	}
1709

    
1710
	// Create symlink that ntpd requires
1711
	unlink_if_exists($pps_device);
1712
	@symlink($serialport, $pps_device);
1713

    
1714

    
1715
	return true;
1716
}
1717

    
1718
function system_ntp_configure() {
1719
	global $config, $g;
1720
	global $ntp_poll_min_default_gps, $ntp_poll_max_default_gps;
1721
	global $ntp_poll_min_default_pps, $ntp_poll_max_default_pps;
1722
	global $ntp_poll_min_default, $ntp_poll_max_default;
1723

    
1724
	$driftfile = "/var/db/ntpd.drift";
1725
	$statsdir = "/var/log/ntp";
1726
	$gps_device = '/dev/gps0';
1727

    
1728
	safe_mkdir($statsdir);
1729

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

    
1744
	if (platform_booting()) {
1745
		echo gettext("Starting NTP Server...");
1746
	}
1747

    
1748
	/* if ntpd is running, kill it */
1749
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
1750
		killbypid("{$g['varrun_path']}/ntpd.pid");
1751
	}
1752
	@unlink("{$g['varrun_path']}/ntpd.pid");
1753

    
1754
	$ntpcfg = "# \n";
1755
	$ntpcfg .= "# pfSense ntp configuration file \n";
1756
	$ntpcfg .= "# \n\n";
1757
	$ntpcfg .= "tinker panic 0 \n";
1758

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

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

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

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

    
1907
		$ntpcfg .= "{$ts} iburst";
1908

    
1909
		$ntpcfg .= system_ntp_fixup_poll_value('minpoll', $config['ntpd']['ntpminpoll'], $ntp_poll_min_default);
1910
		$ntpcfg .= system_ntp_fixup_poll_value('maxpoll', $config['ntpd']['ntpmaxpoll'], $ntp_poll_max_default);
1911

    
1912
		if (substr_count($config['ntpd']['prefer'], $ts)) {
1913
			$ntpcfg .= ' prefer';
1914
		}
1915
		if (substr_count($config['ntpd']['noselect'], $ts)) {
1916
			$ntpcfg .= ' noselect';
1917
		}
1918
		$ntpcfg .= "\n";
1919
	}
1920
	unset($ts);
1921

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

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

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

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

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

    
2050

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

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

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

    
2082
	/* if /var/empty does not exist, create it */
2083
	if (!is_dir("/var/empty")) {
2084
		mkdir("/var/empty", 0555, true);
2085
	}
2086

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

    
2090
	// Note that we are starting up
2091
	log_error("NTPD is starting up.");
2092

    
2093
	if (platform_booting()) {
2094
		echo gettext("done.") . "\n";
2095
	}
2096

    
2097
	return;
2098
}
2099

    
2100
function system_halt() {
2101
	global $g;
2102

    
2103
	system_reboot_cleanup();
2104

    
2105
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
2106
}
2107

    
2108
function system_reboot() {
2109
	global $g;
2110

    
2111
	system_reboot_cleanup();
2112

    
2113
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
2114
}
2115

    
2116
function system_reboot_sync($reroot=false) {
2117
	global $g;
2118

    
2119
	if ($reroot) {
2120
		$args = " -r ";
2121
	}
2122

    
2123
	system_reboot_cleanup();
2124

    
2125
	mwexec("/etc/rc.reboot {$args} > /dev/null 2>&1");
2126
}
2127

    
2128
function system_reboot_cleanup() {
2129
	global $config, $g, $cpzone;
2130

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

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

    
2160
	if ($early) {
2161
		$cmdn = "earlyshellcmd";
2162
	} else {
2163
		$cmdn = "shellcmd";
2164
	}
2165

    
2166
	if (is_array($config['system'][$cmdn])) {
2167

    
2168
		/* *cmd is an array, loop through */
2169
		foreach ($config['system'][$cmdn] as $cmd) {
2170
			exec($cmd);
2171
		}
2172

    
2173
	} elseif ($config['system'][$cmdn] <> "") {
2174

    
2175
		/* execute single item */
2176
		exec($config['system'][$cmdn]);
2177

    
2178
	}
2179
}
2180

    
2181
function system_dmesg_save() {
2182
	global $g;
2183
	if (isset($config['system']['developerspew'])) {
2184
		$mt = microtime();
2185
		echo "system_dmesg_save() being called $mt\n";
2186
	}
2187

    
2188
	$dmesg = "";
2189
	$_gb = exec("/sbin/dmesg", $dmesg);
2190

    
2191
	/* find last copyright line (output from previous boots may be present) */
2192
	$lastcpline = 0;
2193

    
2194
	for ($i = 0; $i < count($dmesg); $i++) {
2195
		if (strstr($dmesg[$i], "Copyright (c) 1992-")) {
2196
			$lastcpline = $i;
2197
		}
2198
	}
2199

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

    
2206
	for ($i = $lastcpline; $i < count($dmesg); $i++) {
2207
		fwrite($fd, $dmesg[$i] . "\n");
2208
	}
2209

    
2210
	fclose($fd);
2211
	unset($dmesg);
2212

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

    
2216
	return 0;
2217
}
2218

    
2219
function system_set_harddisk_standby() {
2220
	global $g, $config;
2221

    
2222
	if (isset($config['system']['developerspew'])) {
2223
		$mt = microtime();
2224
		echo "system_set_harddisk_standby() being called $mt\n";
2225
	}
2226

    
2227
	if (isset($config['system']['harddiskstandby'])) {
2228
		if (platform_booting()) {
2229
			echo gettext('Setting hard disk standby... ');
2230
		}
2231

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

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

    
2258
function system_setup_sysctl() {
2259
	global $config;
2260
	if (isset($config['system']['developerspew'])) {
2261
		$mt = microtime();
2262
		echo "system_setup_sysctl() being called $mt\n";
2263
	}
2264

    
2265
	activate_sysctls();
2266

    
2267
	if (isset($config['system']['sharednet'])) {
2268
		system_disable_arp_wrong_if();
2269
	}
2270
}
2271

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

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

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

    
2315
function system_check_reset_button() {
2316
	global $g;
2317

    
2318
	$specplatform = system_identify_specific_platform();
2319

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

    
2336
	$retval = mwexec("/usr/local/sbin/" . $binprefix . "resetbtn");
2337

    
2338
	if ($retval == 99) {
2339
		/* user has pressed reset button for 2 seconds -
2340
		   reset to factory defaults */
2341
		echo <<<EOD
2342

    
2343
***********************************************************************
2344
* Reset button pressed - resetting configuration to factory defaults. *
2345
* All additional packages installed will be removed                   *
2346
* The system will reboot after this completes.                        *
2347
***********************************************************************
2348

    
2349

    
2350
EOD;
2351

    
2352
		reset_factory_defaults();
2353
		system_reboot_sync();
2354
		exit(0);
2355
	}
2356

    
2357
	return 0;
2358
}
2359

    
2360
function system_get_serial() {
2361
	$platform = system_identify_specific_platform();
2362

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

    
2382
	$vm_guest = get_single_sysctl('kern.vm_guest');
2383

    
2384
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2385
	    $vm_guest == 'none') {
2386
		return $serial;
2387
	}
2388

    
2389
	return "";
2390
}
2391

    
2392
function system_get_uniqueid() {
2393
	global $g;
2394

    
2395
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2396

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

    
2407
	return ($g['uniqueid'] ?: '');
2408
}
2409

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

    
2419
	$hw_model = get_single_sysctl('hw.model');
2420
	$hw_ncpu = get_single_sysctl('hw.ncpu');
2421

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

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

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

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

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

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

    
2544
	if (strpos($hw_model, "PC Engines ALIX") !== false) {
2545
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2546
	}
2547

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

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

    
2556
	if (preg_match("/Soekris net55../", $hw_model, $matches)) {
2557
		return array('name' => 'net55xx', 'descr' => $matches[0]);
2558
	}
2559

    
2560
	unset($hw_model);
2561

    
2562
	$dmesg_boot = system_get_dmesg_boot();
2563
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
2564
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2565
	}
2566
	unset($dmesg_boot);
2567

    
2568
	return array('name' => $g['platform'], 'descr' => $g['platform']);
2569
}
2570

    
2571
function system_get_dmesg_boot() {
2572
	global $g;
2573

    
2574
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2575
}
2576

    
2577
function system_get_arp_table($resolve_hostnames = false) {
2578
	$params="-a";
2579
	if (!$resolve_hostnames) {
2580
		$params .= "n";
2581
	}
2582

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

    
2593
	return $arp_table;
2594
}
2595

    
2596
?>
(50-50/62)