Project

General

Profile

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

    
26
function activate_powerd() {
27
	global $config, $g;
28

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

    
38
		$battery_mode = "hadp";
39
		if (!empty($config['system']['powerd_battery_mode'])) {
40
			$battery_mode = $config['system']['powerd_battery_mode'];
41
		}
42

    
43
		$normal_mode = "hadp";
44
		if (!empty($config['system']['powerd_normal_mode'])) {
45
			$normal_mode = $config['system']['powerd_normal_mode'];
46
		}
47

    
48
		mwexec("/usr/sbin/powerd -b $battery_mode -a $ac_mode -n $normal_mode");
49
	}
50
}
51

    
52
function get_default_sysctl_value($id) {
53
	global $sysctls;
54

    
55
	if (isset($sysctls[$id])) {
56
		return $sysctls[$id];
57
	}
58
}
59

    
60
function get_sysctl_descr($sysctl) {
61
	unset($output);
62
	$_gb = exec("/sbin/sysctl -qnd {$sysctl}", $output);
63

    
64
	return $output[0];
65
}
66

    
67
function system_get_sysctls() {
68
	global $config, $sysctls;
69

    
70
	$disp_sysctl = array();
71
	$disp_cache = array();
72
	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
73
		foreach ($config['sysctl']['item'] as $id => $tunable) {
74
			if ($tunable['value'] == "default") {
75
				$value = get_default_sysctl_value($tunable['tunable']);
76
			} else {
77
				$value = $tunable['value'];
78
			}
79

    
80
			$disp_sysctl[$id] = $tunable;
81
			$disp_sysctl[$id]['modified'] = true;
82
			$disp_cache[$tunable['tunable']] = 'set';
83
		}
84
	}
85

    
86
	foreach ($sysctls as $sysctl => $value) {
87
		if (isset($disp_cache[$sysctl])) {
88
			continue;
89
		}
90

    
91
		$disp_sysctl[$sysctl] = array('tunable' => $sysctl, 'value' => $value, 'descr' => get_sysctl_descr($sysctl));
92
	}
93
	unset($disp_cache);
94
	return $disp_sysctl;
95
}
96

    
97
function activate_sysctls() {
98
	global $config, $g, $sysctls;
99

    
100
	if (is_array($config['sysctl']) && is_array($config['sysctl']['item'])) {
101
		foreach ($config['sysctl']['item'] as $tunable) {
102
			if ($tunable['value'] == "default") {
103
				$value = get_default_sysctl_value($tunable['tunable']);
104
			} else {
105
				$value = $tunable['value'];
106
			}
107

    
108
			$sysctls[$tunable['tunable']] = $value;
109
		}
110
	}
111

    
112
	set_sysctl($sysctls);
113
}
114

    
115
function system_resolvconf_generate($dynupdate = false) {
116
	global $config, $g;
117

    
118
	if (isset($config['system']['developerspew'])) {
119
		$mt = microtime();
120
		echo "system_resolvconf_generate() being called $mt\n";
121
	}
122

    
123
	$syscfg = $config['system'];
124

    
125
	foreach(get_dns_nameservers() as $dns_ns) {
126
		$resolvconf .= "nameserver $dns_ns\n";
127
	}
128

    
129
	if (isset($syscfg['dnsallowoverride'])) {
130
		/* get dynamically assigned DNS servers (if any) */
131
		$ns = array_unique(get_searchdomains());
132
		foreach ($ns as $searchserver) {
133
			if ($searchserver) {
134
				$resolvconf .= "search {$searchserver}\n";
135
			}
136
		}
137
	} else {
138
		$ns = array();
139
		// Do not create blank search/domain lines, it can break tools like dig.
140
		if ($syscfg['domain']) {
141
			$resolvconf .= "search {$syscfg['domain']}\n";
142
		}
143
	}
144

    
145
	// Add EDNS support
146
	if (isset($config['unbound']['enable']) && isset($config['unbound']['edns'])) {
147
		$resolvconf .= "options edns0\n";
148
	}
149

    
150
	$dnslock = lock('resolvconf', LOCK_EX);
151

    
152
	$fd = fopen("{$g['etc_path']}/resolv.conf", "w");
153
	if (!$fd) {
154
		printf("Error: cannot open resolv.conf in system_resolvconf_generate().\n");
155
		unlock($dnslock);
156
		return 1;
157
	}
158

    
159
	fwrite($fd, $resolvconf);
160
	fclose($fd);
161

    
162
	// Prevent resolvconf(8) from rewriting our resolv.conf
163
	$fd = fopen("{$g['etc_path']}/resolvconf.conf", "w");
164
	if (!$fd) {
165
		printf("Error: cannot open resolvconf.conf in system_resolvconf_generate().\n");
166
		return 1;
167
	}
168
	fwrite($fd, "resolv_conf=\"/dev/null\"\n");
169
	fclose($fd);
170

    
171
	if (!platform_booting()) {
172
		/* restart dhcpd (nameservers may have changed) */
173
		if (!$dynupdate) {
174
			services_dhcpd_configure();
175
		}
176
	}
177

    
178
	/* setup static routes for DNS servers. */
179
	$dnscounter = 1;
180
	$dnsgw = "dns{$dnscounter}gw";
181
	while (isset($config['system'][$dnsgw])) {
182
		/* setup static routes for dns servers */
183
		if (!(empty($config['system'][$dnsgw]) ||
184
		    $config['system'][$dnsgw] == "none")) {
185
			$gwname = $config['system'][$dnsgw];
186
			$gatewayip = lookup_gateway_ip_by_name($gwname);
187
			$inet6 = is_ipaddrv6($gatewayip) ? '-inet6 ' : '';
188
			/* dns server array starts at 0 */
189
			$dnsserver = $syscfg['dnsserver'][$dnscounter - 1];
190

    
191
			if (is_ipaddr($gatewayip)) {
192
				route_add_or_change("-host {$inet6}{$dnsserver} {$gatewayip}");
193
			} else {
194
				/* Remove old route when disable gw */
195
				mwexec("/sbin/route delete -host {$inet6}{$dnsserver}");
196
				if (isset($config['system']['route-debug'])) {
197
					$mt = microtime();
198
					log_error("ROUTING debug: $mt - route delete -host {$inet6}{$dnsserver}");
199
				}
200
			}
201
		}
202
		$dnscounter++;
203
		$dnsgw = "dns{$dnscounter}gw";
204
	}
205

    
206
	unlock($dnslock);
207

    
208
	return 0;
209
}
210

    
211
function get_searchdomains() {
212
	global $config, $g;
213

    
214
	$master_list = array();
215

    
216
	// Read in dhclient nameservers
217
	$search_list = glob("/var/etc/searchdomain_*");
218
	if (is_array($search_list)) {
219
		foreach ($search_list as $fdns) {
220
			$contents = file($fdns, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
221
			if (!is_array($contents)) {
222
				continue;
223
			}
224
			foreach ($contents as $dns) {
225
				if (is_hostname($dns)) {
226
					$master_list[] = $dns;
227
				}
228
			}
229
		}
230
	}
231

    
232
	return $master_list;
233
}
234

    
235
function get_nameservers() {
236
	global $config, $g;
237
	$master_list = array();
238

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

    
255
	// Read in any extra nameservers
256
	if (file_exists("/var/etc/nameservers.conf")) {
257
		$dns_s = file("/var/etc/nameservers.conf", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
258
		if (is_array($dns_s)) {
259
			foreach ($dns_s as $dns) {
260
				if (is_ipaddr($dns)) {
261
					$master_list[] = $dns;
262
				}
263
			}
264
		}
265
	}
266

    
267
	return $master_list;
268
}
269

    
270
/* Create localhost + local interfaces entries for /etc/hosts */
271
function system_hosts_local_entries() {
272
	global $config;
273

    
274
	$syscfg = $config['system'];
275

    
276
	$hosts = array();
277
	$hosts[] = array(
278
	    'ipaddr' => '127.0.0.1',
279
	    'fqdn' => 'localhost.' . $syscfg['domain'],
280
	    'name' => 'localhost',
281
	    'domain' => $syscfg['domain']
282
	);
283
	$hosts[] = array(
284
	    'ipaddr' => '::1',
285
	    'fqdn' => 'localhost.' . $syscfg['domain'],
286
	    'name' => 'localhost',
287
	    'domain' => $syscfg['domain']
288
	);
289

    
290
	if ($config['interfaces']['lan']) {
291
		$sysiflist = array('lan' => "lan");
292
	} else {
293
		$sysiflist = get_configured_interface_list();
294
	}
295

    
296
	$hosts_if_found = false;
297
	$local_fqdn = "{$syscfg['hostname']}.{$syscfg['domain']}";
298
	foreach ($sysiflist as $sysif) {
299
		if ($sysif != 'lan' && interface_has_gateway($sysif)) {
300
			continue;
301
		}
302
		$cfgip = get_interface_ip($sysif);
303
		if (is_ipaddrv4($cfgip)) {
304
			$hosts[] = array(
305
			    'ipaddr' => $cfgip,
306
			    'fqdn' => $local_fqdn,
307
			    'name' => $syscfg['hostname'],
308
			    'domain' => $syscfg['domain']
309
			);
310
			$hosts_if_found = true;
311
		}
312
		if (!isset($syscfg['ipv6dontcreatelocaldns'])) {
313
			$cfgipv6 = get_interface_ipv6($sysif);
314
			if (is_ipaddrv6($cfgipv6)) {
315
				$hosts[] = array(
316
					'ipaddr' => $cfgipv6,
317
					'fqdn' => $local_fqdn,
318
					'name' => $syscfg['hostname'],
319
					'domain' => $syscfg['domain']
320
				);
321
				$hosts_if_found = true;
322
			}
323
		}
324
		if ($hosts_if_found == true) {
325
			break;
326
		}
327
	}
328

    
329
	return $hosts;
330
}
331

    
332
/* Read host override entries from dnsmasq or unbound */
333
function system_hosts_override_entries($dnscfg) {
334
	$hosts = array();
335

    
336
	if (!is_array($dnscfg) ||
337
	    !is_array($dnscfg['hosts']) ||
338
	    !isset($dnscfg['enable'])) {
339
		return $hosts;
340
	}
341

    
342
	foreach ($dnscfg['hosts'] as $host) {
343
		$fqdn = '';
344
		if ($host['host'] || $host['host'] == "0") {
345
			$fqdn .= "{$host['host']}.";
346
		}
347
		$fqdn .= $host['domain'];
348

    
349
		$hosts[] = array(
350
		    'ipaddr' => $host['ip'],
351
		    'fqdn' => $fqdn,
352
		    'name' => $host['host'],
353
		    'domain' => $host['domain']
354
		);
355

    
356
		if (!is_array($host['aliases']) ||
357
		    !is_array($host['aliases']['item'])) {
358
			continue;
359
		}
360

    
361
		foreach ($host['aliases']['item'] as $alias) {
362
			$fqdn = '';
363
			if ($alias['host'] || $alias['host'] == "0") {
364
				$fqdn .= "{$alias['host']}.";
365
			}
366
			$fqdn .= $alias['domain'];
367

    
368
			$hosts[] = array(
369
			    'ipaddr' => $host['ip'],
370
			    'fqdn' => $fqdn,
371
			    'name' => $alias['host'],
372
			    'domain' => $alias['domain']
373
			);
374
		}
375
	}
376

    
377
	return $hosts;
378
}
379

    
380
/* Read all dhcpd/dhcpdv6 staticmap entries */
381
function system_hosts_dhcpd_entries() {
382
	global $config;
383

    
384
	$hosts = array();
385
	$syscfg = $config['system'];
386

    
387
	if (is_array($config['dhcpd'])) {
388
		$conf_dhcpd = $config['dhcpd'];
389
	} else {
390
		$conf_dhcpd = array();
391
	}
392

    
393
	foreach ($conf_dhcpd as $dhcpif => $dhcpifconf) {
394
		if (!is_array($dhcpifconf['staticmap']) ||
395
		    !isset($dhcpifconf['enable'])) {
396
			continue;
397
		}
398
		foreach ($dhcpifconf['staticmap'] as $host) {
399
			if (!$host['ipaddr'] ||
400
			    !$host['hostname']) {
401
				continue;
402
			}
403

    
404
			$fqdn = $host['hostname'] . ".";
405
			$domain = "";
406
			if ($host['domain']) {
407
				$domain = $host['domain'];
408
			} elseif ($dhcpifconf['domain']) {
409
				$domain = $dhcpifconf['domain'];
410
			} else {
411
				$domain = $syscfg['domain'];
412
			}
413

    
414
			$hosts[] = array(
415
			    'ipaddr' => $host['ipaddr'],
416
			    'fqdn' => $fqdn . $domain,
417
			    'name' => $host['hostname'],
418
			    'domain' => $domain
419
			);
420
		}
421
	}
422
	unset($conf_dhcpd);
423

    
424
	if (is_array($config['dhcpdv6'])) {
425
		$conf_dhcpdv6 = $config['dhcpdv6'];
426
	} else {
427
		$conf_dhcpdv6 = array();
428
	}
429

    
430
	foreach ($conf_dhcpdv6 as $dhcpif => $dhcpifconf) {
431
		if (!is_array($dhcpifconf['staticmap']) ||
432
		    !isset($dhcpifconf['enable'])) {
433
			continue;
434
		}
435

    
436
		if (isset($config['interfaces'][$dhcpif]['ipaddrv6']) &&
437
		    $config['interfaces'][$dhcpif]['ipaddrv6'] ==
438
		    'track6') {
439
			$isdelegated = true;
440
		} else {
441
			$isdelegated = false;
442
		}
443

    
444
		foreach ($dhcpifconf['staticmap'] as $host) {
445
			$ipaddrv6 = $host['ipaddrv6'];
446

    
447
			if (!$ipaddrv6 || !$host['hostname']) {
448
				continue;
449
			}
450

    
451
			if ($isdelegated) {
452
				/*
453
				 * We are always in an "end-user" subnet
454
				 * here, which all are /64 for IPv6.
455
				 */
456
				$ipaddrv6 = merge_ipv6_delegated_prefix(
457
				    get_interface_ipv6($dhcpif),
458
				    $ipaddrv6, 64);
459
			}
460

    
461
			$fqdn = $host['hostname'] . ".";
462
			$domain = "";
463
			if ($host['domain']) {
464
				$domain = $host['domain'];
465
			} elseif ($dhcpifconf['domain']) {
466
				$domain = $dhcpifconf['domain'];
467
			} else {
468
				$domain = $syscfg['domain'];
469
			}
470

    
471
			$hosts[] = array(
472
			    'ipaddr' => $ipaddrv6,
473
			    'fqdn' => $fqdn . $domain,
474
			    'name' => $host['hostname'],
475
			    'domain' => $domain
476
			);
477
		}
478
	}
479
	unset($conf_dhcpdv6);
480

    
481
	return $hosts;
482
}
483

    
484
/* Concatenate local, dnsmasq/unbound and dhcpd/dhcpdv6 hosts entries */
485
function system_hosts_entries($dnscfg) {
486
	$local = array();
487
	if (!isset($dnscfg['disable_auto_added_host_entries'])) {
488
		$local = system_hosts_local_entries();
489
	}
490

    
491
	$dns = array();
492
	$dhcpd = array();
493
	if (isset($dnscfg['enable'])) {
494
		$dns = system_hosts_override_entries($dnscfg);
495
		if (isset($dnscfg['regdhcpstatic'])) {
496
			$dhcpd = system_hosts_dhcpd_entries();
497
		}
498
	}
499

    
500
	if (isset($dnscfg['dhcpfirst'])) {
501
		return array_merge($local, $dns, $dhcpd);
502
	} else {
503
		return array_merge($local, $dhcpd, $dns);
504
	}
505
}
506

    
507
function system_hosts_generate() {
508
	global $config, $g;
509
	if (isset($config['system']['developerspew'])) {
510
		$mt = microtime();
511
		echo "system_hosts_generate() being called $mt\n";
512
	}
513

    
514
	// prefer dnsmasq for hosts generation where it's enabled. It relies
515
	// on hosts for name resolution of its overrides, unbound does not.
516
	if (isset($config['dnsmasq']) && isset($config['dnsmasq']['enable'])) {
517
		$dnsmasqcfg = $config['dnsmasq'];
518
	} else {
519
		$dnsmasqcfg = $config['unbound'];
520
	}
521

    
522
	$syscfg = $config['system'];
523
	$hosts = "";
524
	$lhosts = "";
525
	$dhosts = "";
526

    
527
	$hosts_array = system_hosts_entries($dnsmasqcfg);
528
	foreach ($hosts_array as $host) {
529
		$hosts .= "{$host['ipaddr']}\t";
530
		if ($host['name'] == "localhost") {
531
			$hosts .= "{$host['name']} {$host['fqdn']}";
532
		} else {
533
			$hosts .= "{$host['fqdn']} {$host['name']}";
534
		}
535
		$hosts .= "\n";
536
	}
537
	unset($hosts_array);
538

    
539
	$fd = fopen("{$g['etc_path']}/hosts", "w");
540
	if (!$fd) {
541
		log_error(gettext(
542
		    "Error: cannot open hosts file in system_hosts_generate()."
543
		    ));
544
		return 1;
545
	}
546

    
547
	/*
548
	 * Do not remove this because dhcpleases monitors with kqueue it needs
549
	 * to be killed before writing to hosts files.
550
	 */
551
	if (file_exists("{$g['varrun_path']}/dhcpleases.pid")) {
552
		sigkillbypid("{$g['varrun_path']}/dhcpleases.pid", "TERM");
553
		@unlink("{$g['varrun_path']}/dhcpleases.pid");
554
	}
555

    
556
	fwrite($fd, $hosts);
557
	fclose($fd);
558

    
559
	if (isset($config['unbound']['enable'])) {
560
		require_once("unbound.inc");
561
		unbound_hosts_generate();
562
	}
563

    
564
	/* restart dhcpleases */
565
	if (!platform_booting()) {
566
		system_dhcpleases_configure();
567
	}
568

    
569
	return 0;
570
}
571

    
572
function system_dhcpleases_configure() {
573
	global $config, $g;
574
	if (!function_exists('is_dhcp_server_enabled')) {
575
		require_once('pfsense-utils.inc');
576
	}
577
	$pidfile = "{$g['varrun_path']}/dhcpleases.pid";
578

    
579
	/* Start the monitoring process for dynamic dhcpclients. */
580
	if (((isset($config['dnsmasq']['enable']) && isset($config['dnsmasq']['regdhcp'])) ||
581
	    (isset($config['unbound']['enable']) && isset($config['unbound']['regdhcp']))) &&
582
	    (is_dhcp_server_enabled())) {
583
		/* Make sure we do not error out */
584
		mwexec("/bin/mkdir -p {$g['dhcpd_chroot_path']}/var/db");
585
		if (!file_exists("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases")) {
586
			@touch("{$g['dhcpd_chroot_path']}/var/db/dhcpd.leases");
587
		}
588

    
589
		if (isset($config['unbound']['enable'])) {
590
			$dns_pid = "unbound.pid";
591
			$unbound_conf = "-u {$g['unbound_chroot_path']}/dhcpleases_entries.conf";
592
		} else {
593
			$dns_pid = "dnsmasq.pid";
594
			$unbound_conf = "";
595
		}
596

    
597
		if (isvalidpid($pidfile)) {
598
			/* Make sure dhcpleases is using correct unbound or dnsmasq */
599
			$_gb = exec("/bin/pgrep -F {$pidfile} -f {$dns_pid}", $output, $retval);
600
			if (intval($retval) == 0) {
601
				sigkillbypid($pidfile, "HUP");
602
				return;
603
			} else {
604
				sigkillbypid($pidfile, "TERM");
605
			}
606
		}
607

    
608
		/* To ensure we do not start multiple instances of dhcpleases, perform some clean-up first. */
609
		if (is_process_running("dhcpleases")) {
610
			sigkillbyname('dhcpleases', "TERM");
611
		}
612
		@unlink($pidfile);
613
		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");
614
	} elseif (isvalidpid($pidfile)) {
615
		sigkillbypid($pidfile, "TERM");
616
		@unlink($pidfile);
617
	}
618
}
619

    
620
function system_hostname_configure() {
621
	global $config, $g;
622
	if (isset($config['system']['developerspew'])) {
623
		$mt = microtime();
624
		echo "system_hostname_configure() being called $mt\n";
625
	}
626

    
627
	$syscfg = $config['system'];
628

    
629
	/* set hostname */
630
	$status = mwexec("/bin/hostname " .
631
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
632

    
633
	/* Setup host GUID ID.  This is used by ZFS. */
634
	mwexec("/etc/rc.d/hostid start");
635

    
636
	return $status;
637
}
638

    
639
function system_routing_configure($interface = "") {
640
	global $config, $g;
641

    
642
	if (isset($config['system']['developerspew'])) {
643
		$mt = microtime();
644
		echo "system_routing_configure() being called $mt\n";
645
	}
646

    
647
	$dont_add_route = false;
648
	/* if OLSRD is enabled, allow WAN to house DHCP. */
649
	if (is_array($config['installedpackages']['olsrd'])) {
650
		foreach ($config['installedpackages']['olsrd']['config'] as $olsrd) {
651
			if (($olsrd['enabledyngw'] == "on") && ($olsrd['enable'] == "on")) {
652
				$dont_add_route = true;
653
				log_error(gettext("Not adding default route because OLSR dynamic gateway is enabled."));
654
				break;
655
			}
656
		}
657
	}
658

    
659
	$gateways_arr = return_gateways_array(false, true);
660
	foreach ($gateways_arr as $gateway) {
661
		// setup static interface routes for nonlocal gateways
662
		if (isset($gateway["nonlocalgateway"])) {
663
			$srgatewayip = $gateway['gateway'];
664
			$srinterfacegw = $gateway['interface'];
665
			if (is_ipaddr($srgatewayip) && !empty($srinterfacegw)) {
666
				$inet = (!is_ipaddrv4($srgatewayip) ? "-inet6" : "-inet");
667
				route_add_or_change("{$inet} {$srgatewayip} " .
668
				    "-iface {$srinterfacegw}");
669
			}
670
		}
671
	}
672

    
673
	if ($dont_add_route == false) {
674
		$gateways_status = return_gateways_status(true);
675
		fixup_default_gateway("inet", $gateways_status, $gateways_arr);
676
		fixup_default_gateway("inet6", $gateways_status, $gateways_arr);
677
	}
678

    
679
	system_staticroutes_configure($interface, false);
680

    
681
	return 0;
682
}
683

    
684
function system_staticroutes_configure($interface = "", $update_dns = false) {
685
	global $config, $g, $aliastable;
686

    
687
	$filterdns_list = array();
688

    
689
	$static_routes = get_staticroutes(false, true);
690
	if (count($static_routes)) {
691
		$gateways_arr = return_gateways_array(false, true);
692

    
693
		foreach ($static_routes as $rtent) {
694
			if (empty($gateways_arr[$rtent['gateway']])) {
695
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
696
				continue;
697
			}
698
			$gateway = $gateways_arr[$rtent['gateway']];
699
			if (!empty($interface) && $interface != $gateway['friendlyiface']) {
700
				continue;
701
			}
702

    
703
			$gatewayip = $gateway['gateway'];
704
			$interfacegw = $gateway['interface'];
705

    
706
			$blackhole = "";
707
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 4))) {
708
				$blackhole = "-blackhole";
709
			}
710

    
711
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network'])) {
712
				continue;
713
			}
714

    
715
			$dnscache = array();
716
			if ($update_dns === true) {
717
				if (is_subnet($rtent['network'])) {
718
					continue;
719
				}
720
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
721
				if (empty($dnscache)) {
722
					continue;
723
				}
724
			}
725

    
726
			if (is_subnet($rtent['network'])) {
727
				$ips = array($rtent['network']);
728
			} else {
729
				if (!isset($rtent['disabled'])) {
730
					$filterdns_list[] = $rtent['network'];
731
				}
732
				$ips = add_hostname_to_watch($rtent['network']);
733
			}
734

    
735
			foreach ($dnscache as $ip) {
736
				if (in_array($ip, $ips)) {
737
					continue;
738
				}
739
				mwexec("/sbin/route delete " . escapeshellarg($ip), true);
740
				if (isset($config['system']['route-debug'])) {
741
					$mt = microtime();
742
					log_error("ROUTING debug: $mt - route delete $ip ");
743
				}
744
			}
745

    
746
			if (isset($rtent['disabled'])) {
747
				/* XXX: This can break things by deleting routes that shouldn't be deleted - OpenVPN, dynamic routing scenarios, etc. redmine #3709 */
748
				foreach ($ips as $ip) {
749
					mwexec("/sbin/route delete " . escapeshellarg($ip), true);
750
					if (isset($config['system']['route-debug'])) {
751
						$mt = microtime();
752
						log_error("ROUTING debug: $mt - route delete $ip ");
753
					}
754
				}
755
				continue;
756
			}
757

    
758
			foreach ($ips as $ip) {
759
				if (is_ipaddrv4($ip)) {
760
					$ip .= "/32";
761
				}
762
				// do NOT do the same check here on v6, is_ipaddrv6 returns true when including the CIDR mask. doing so breaks v6 routes
763

    
764
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
765

    
766
				$cmd = "{$inet} {$blackhole} {$ip} ";
767

    
768
				if (is_subnet($ip)) {
769
					if (is_ipaddr($gatewayip)) {
770
						if (is_linklocal($gatewayip) == "6" && !strpos($gatewayip, '%')) {
771
							// add interface scope for link local v6 routes
772
							$gatewayip .= "%$interfacegw";
773
						}
774
						route_add_or_change($cmd . $gatewayip);
775
					} else if (!empty($interfacegw)) {
776
						route_add_or_change($cmd . "-iface {$interfacegw}");
777
					}
778
				}
779
			}
780
		}
781
		unset($gateways_arr);
782
	}
783
	unset($static_routes);
784

    
785
	if ($update_dns === false) {
786
		if (count($filterdns_list)) {
787
			$interval = 60;
788
			$hostnames = "";
789
			array_unique($filterdns_list);
790
			foreach ($filterdns_list as $hostname) {
791
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
792
			}
793
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
794
			unset($hostnames);
795

    
796
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid")) {
797
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
798
			} else {
799
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
800
			}
801
		} else {
802
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
803
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
804
		}
805
	}
806
	unset($filterdns_list);
807

    
808
	return 0;
809
}
810

    
811
function system_routing_enable() {
812
	global $config, $g;
813
	if (isset($config['system']['developerspew'])) {
814
		$mt = microtime();
815
		echo "system_routing_enable() being called $mt\n";
816
	}
817

    
818
	set_sysctl(array(
819
		"net.inet.ip.forwarding" => "1",
820
		"net.inet6.ip6.forwarding" => "1"
821
	));
822

    
823
	return;
824
}
825

    
826
function system_syslogd_fixup_server($server) {
827
	/* If it's an IPv6 IP alone, encase it in brackets */
828
	if (is_ipaddrv6($server)) {
829
		return "[$server]";
830
	} else {
831
		return $server;
832
	}
833
}
834

    
835
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
836
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
837
	$facility .= " ".
838
	$remote_servers = "";
839
	$pad_to  = max(strlen($facility), 56);
840
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
841
	if (isset($syslogcfg['enable'])) {
842
		if ($syslogcfg['remoteserver']) {
843
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
844
		}
845
		if ($syslogcfg['remoteserver2']) {
846
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
847
		}
848
		if ($syslogcfg['remoteserver3']) {
849
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
850
		}
851
	}
852
	return $remote_servers;
853
}
854

    
855
function clear_log_file($logfile = "/var/log/system.log", $restart_syslogd = true) {
856
	global $config, $g;
857

    
858
	if ($restart_syslogd) {
859
		/* syslogd does not react well to clog rewriting the file while it is running. */
860
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
861
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
862
		}
863
	}
864
	if (isset($config['system']['disablesyslogclog'])) {
865
		unlink($logfile);
866
		touch($logfile);
867
	} else {
868
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "511488";
869
		$log_size = isset($config['syslog'][basename($logfile, '.log') . '_settings']['logfilesize']) ? $config['syslog'][basename($logfile, '.log') . '_settings']['logfilesize'] : $log_size;
870
		exec("/usr/local/sbin/clog -i -s {$log_size} " . escapeshellarg($logfile));
871
	}
872
	if ($restart_syslogd) {
873
		system_syslogd_start();
874
	}
875
	// Bug #6915
876
	if ($logfile == "/var/log/resolver.log") {
877
		services_unbound_configure(true);
878
	}
879
}
880

    
881
function clear_all_log_files($restart = false) {
882
	global $g;
883
	if ($restart) {
884
		/* syslogd does not react well to clog rewriting the file while it is running. */
885
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
886
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
887
		}
888
	}
889

    
890
	$log_files = array("system", "filter", "dhcpd", "vpn", "poes", "l2tps", "openvpn", "portalauth", "ipsec", "ppp", "relayd", "wireless", "nginx", "ntpd", "gateways", "resolver", "routing");
891
	foreach ($log_files as $lfile) {
892
		clear_log_file("{$g['varlog_path']}/{$lfile}.log", false);
893
	}
894

    
895
	if ($restart) {
896
		system_syslogd_start();
897
		killbyname("dhcpd");
898
		if (!function_exists('services_dhcpd_configure')) {
899
			require_once('services.inc');
900
		}
901
		services_dhcpd_configure();
902
		// Bug #6915
903
		services_unbound_configure(false);
904
	}
905
	return;
906
}
907

    
908
function system_syslogd_start($sighup = false) {
909
	global $config, $g;
910
	if (isset($config['system']['developerspew'])) {
911
		$mt = microtime();
912
		echo "system_syslogd_start() being called $mt\n";
913
	}
914

    
915
	mwexec("/etc/rc.d/hostid start");
916

    
917
	$syslogcfg = $config['syslog'];
918

    
919
	if (platform_booting()) {
920
		echo gettext("Starting syslog...");
921
	}
922

    
923
	// Which logging type are we using this week??
924
	if (isset($config['system']['disablesyslogclog'])) {
925
		$log_directive = "";
926
		$log_create_directive = "/usr/bin/touch ";
927
		$log_size = "";
928
	} else { // Defaults to CLOG
929
		$log_directive = "%";
930
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
931
		$log_create_directive = "/usr/local/sbin/clog -i -s ";
932
	}
933

    
934
	$syslogd_extra = "";
935
	if (isset($syslogcfg)) {
936
		$separatelogfacilities = array('ntp', 'ntpd', 'ntpdate', 'charon', 'ipsec_starter', 'openvpn', 'poes', 'l2tps', 'relayd', 'hostapd', 'dnsmasq', 'named', 'filterdns', 'unbound', 'dhcpd', 'dhcrelay', 'dhclient', 'dhcp6c', 'dpinger', 'radvd', 'routed', 'olsrd', 'zebra', 'ospfd', 'ospf6d', 'bgpd', 'miniupnpd', 'filterlog');
937
		$syslogconf = "";
938
		if ($config['installedpackages']['package']) {
939
			foreach ($config['installedpackages']['package'] as $package) {
940
				if (isset($package['logging']['facilityname']) && isset($package['logging']['logfilename'])) {
941
					array_push($separatelogfacilities, $package['logging']['facilityname']);
942
					if (!is_file($g['varlog_path'].'/'.$package['logging']['logfilename'])) {
943
						mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
944
					}
945
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
946
				}
947
			}
948
		}
949
		$facilitylist = implode(',', array_unique($separatelogfacilities));
950
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,ospf6d,bgpd,miniupnpd\n";
951
		if (!isset($syslogcfg['disablelocallogging'])) {
952
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
953
		}
954
		if (isset($syslogcfg['routing'])) {
955
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
956
		}
957

    
958
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
959
		if (!isset($syslogcfg['disablelocallogging'])) {
960
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
961
		}
962
		if (isset($syslogcfg['ntpd'])) {
963
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
964
		}
965

    
966
		$syslogconf .= "!ppp\n";
967
		if (!isset($syslogcfg['disablelocallogging'])) {
968
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ppp.log\n";
969
		}
970
		if (isset($syslogcfg['ppp'])) {
971
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
972
		}
973

    
974
		$syslogconf .= "!poes\n";
975
		if (!isset($syslogcfg['disablelocallogging'])) {
976
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/poes.log\n";
977
		}
978
		if (isset($syslogcfg['vpn'])) {
979
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
980
		}
981

    
982
		$syslogconf .= "!l2tps\n";
983
		if (!isset($syslogcfg['disablelocallogging'])) {
984
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/l2tps.log\n";
985
		}
986
		if (isset($syslogcfg['vpn'])) {
987
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
988
		}
989

    
990
		$syslogconf .= "!charon,ipsec_starter\n";
991
		if (!isset($syslogcfg['disablelocallogging'])) {
992
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ipsec.log\n";
993
		}
994
		if (isset($syslogcfg['vpn'])) {
995
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
996
		}
997

    
998
		$syslogconf .= "!openvpn\n";
999
		if (!isset($syslogcfg['disablelocallogging'])) {
1000
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/openvpn.log\n";
1001
		}
1002
		if (isset($syslogcfg['vpn'])) {
1003
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1004
		}
1005

    
1006
		$syslogconf .= "!dpinger\n";
1007
		if (!isset($syslogcfg['disablelocallogging'])) {
1008
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/gateways.log\n";
1009
		}
1010
		if (isset($syslogcfg['dpinger'])) {
1011
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1012
		}
1013

    
1014
		$syslogconf .= "!dnsmasq,named,filterdns,unbound\n";
1015
		if (!isset($syslogcfg['disablelocallogging'])) {
1016
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
1017
		}
1018
		if (isset($syslogcfg['resolver'])) {
1019
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1020
		}
1021

    
1022
		$syslogconf .= "!dhcpd,dhcrelay,dhclient,dhcp6c,dhcpleases,dhcpleases6\n";
1023
		if (!isset($syslogcfg['disablelocallogging'])) {
1024
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/dhcpd.log\n";
1025
		}
1026
		if (isset($syslogcfg['dhcp'])) {
1027
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1028
		}
1029

    
1030
		$syslogconf .= "!relayd\n";
1031
		if (!isset($syslogcfg['disablelocallogging'])) {
1032
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/relayd.log\n";
1033
		}
1034
		if (isset($syslogcfg['relayd'])) {
1035
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1036
		}
1037

    
1038
		$syslogconf .= "!hostapd\n";
1039
		if (!isset($syslogcfg['disablelocallogging'])) {
1040
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/wireless.log\n";
1041
		}
1042
		if (isset($syslogcfg['hostapd'])) {
1043
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1044
		}
1045

    
1046
		$syslogconf .= "!filterlog\n";
1047
		if (!isset($syslogcfg['disablelocallogging'])) {
1048
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/filter.log\n";
1049
		}
1050
		if (isset($syslogcfg['filter'])) {
1051
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1052
		}
1053

    
1054
		$syslogconf .= "!-{$facilitylist}\n";
1055
		if (!isset($syslogcfg['disablelocallogging'])) {
1056
			$syslogconf .= <<<EOD
1057
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
1058
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
1059
local5.*							{$log_directive}{$g['varlog_path']}/nginx.log
1060
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
1061
*.notice;kern.debug;lpr.info;mail.crit;daemon.none;news.err;local0.none;local3.none;local4.none;local7.none;security.*;auth.info;authpriv.info;daemon.info	{$log_directive}{$g['varlog_path']}/system.log
1062
auth.info;authpriv.info 					|exec /usr/local/sbin/sshguard
1063
*.emerg								*
1064

    
1065
EOD;
1066
		}
1067
		if (isset($syslogcfg['vpn'])) {
1068
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
1069
		}
1070
		if (isset($syslogcfg['portalauth'])) {
1071
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
1072
		}
1073
		if (isset($syslogcfg['dhcp'])) {
1074
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
1075
		}
1076
		if (isset($syslogcfg['system'])) {
1077
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.emerg;*.notice;kern.debug;lpr.info;mail.crit;news.err;local0.none;local3.none;local7.none;security.*;auth.info;authpriv.info;daemon.info");
1078
		}
1079
		if (isset($syslogcfg['logall'])) {
1080
			// Make everything mean everything, including facilities excluded above.
1081
			$syslogconf .= "!*\n";
1082
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1083
		}
1084

    
1085
		if (isset($syslogcfg['zmqserver'])) {
1086
				$syslogconf .= <<<EOD
1087
*.*								^{$syslogcfg['zmqserver']}
1088

    
1089
EOD;
1090
		}
1091
		/* write syslog.conf */
1092
		if (!@file_put_contents("{$g['etc_path']}/syslog.conf", $syslogconf)) {
1093
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
1094
			unset($syslogconf);
1095
			return 1;
1096
		}
1097
		unset($syslogconf);
1098

    
1099
		$sourceip = "";
1100
		if (!empty($syslogcfg['sourceip'])) {
1101
			if ($syslogcfg['ipproto'] == "ipv6") {
1102
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
1103
				if (!is_ipaddr($ifaddr)) {
1104
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
1105
				}
1106
			} else {
1107
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
1108
				if (!is_ipaddr($ifaddr)) {
1109
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
1110
				}
1111
			}
1112
			if (is_ipaddr($ifaddr)) {
1113
				$sourceip = "-b {$ifaddr}";
1114
			}
1115
		}
1116

    
1117
		$syslogd_extra = "-f {$g['etc_path']}/syslog.conf {$sourceip}";
1118
	}
1119

    
1120
	$log_sockets = array("{$g['dhcpd_chroot_path']}/var/run/log");
1121

    
1122
	if (isset($config['installedpackages']['package'])) {
1123
		foreach ($config['installedpackages']['package'] as $package) {
1124
			if (isset($package['logging']['logsocket']) && $package['logging']['logsocket'] != '' &&
1125
			    !in_array($package['logging']['logsocket'], $log_sockets)) {
1126
				$log_sockets[] = $package['logging']['logsocket'];
1127
			}
1128
		}
1129
	}
1130

    
1131
	$syslogd_sockets = "";
1132
	foreach ($log_sockets as $log_socket) {
1133
		// Ensure that the log directory exists
1134
		$logpath = dirname($log_socket);
1135
		safe_mkdir($logpath);
1136
		$syslogd_sockets .= " -l {$log_socket}";
1137
	}
1138

    
1139
	/* If HUP was requested, but syslogd is not running, restart it instead. */
1140
	if ($sighup && !isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1141
		$sighup = false;
1142
	}
1143

    
1144
	$sshguard_config = array();
1145
	$sshguard_config[] = 'BACKEND="/usr/local/libexec/sshg-fw-pf"' . "\n";
1146
	/* XXX Add a GUI option to user to define it? */
1147
	$sshguard_config[] = 'DETECTION_TIME=3600' . "\n";
1148
	file_put_contents("/usr/local/etc/sshguard.conf", $sshguard_config);
1149

    
1150
	if (!$sighup) {
1151
		sigkillbyname("sshguard", "TERM");
1152
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1153
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "TERM");
1154
			usleep(100000); // syslogd often doesn't respond to a TERM quickly enough for the starting of syslogd below to be successful
1155
		}
1156

    
1157
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1158
			// if it still hasn't responded to the TERM, KILL it.
1159
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
1160
			usleep(100000);
1161
		}
1162

    
1163
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c {$syslogd_sockets} -P {$g['varrun_path']}/syslog.pid {$syslogd_extra}");
1164
	} else {
1165
		$retval = sigkillbypid("{$g['varrun_path']}/syslog.pid", "HUP");
1166
	}
1167

    
1168
	if (platform_booting()) {
1169
		echo gettext("done.") . "\n";
1170
	}
1171

    
1172
	return $retval;
1173
}
1174

    
1175
function system_webgui_create_certificate() {
1176
	global $config, $g;
1177

    
1178
	if (!is_array($config['ca'])) {
1179
		$config['ca'] = array();
1180
	}
1181
	$a_ca =& $config['ca'];
1182
	if (!is_array($config['cert'])) {
1183
		$config['cert'] = array();
1184
	}
1185
	$a_cert =& $config['cert'];
1186
	log_error(gettext("Creating SSL Certificate for this host"));
1187

    
1188
	$cert = array();
1189
	$cert['refid'] = uniqid();
1190
	$cert['descr'] = sprintf(gettext("webConfigurator default (%s)"), $cert['refid']);
1191
	$cert_hostname = "{$config['system']['hostname']}-{$cert['refid']}";
1192

    
1193
	$dn = array(
1194
		'organizationName' => "{$g['product_name']} webConfigurator Self-Signed Certificate",
1195
		'commonName' => $cert_hostname,
1196
		'subjectAltName' => "DNS:{$cert_hostname}");
1197
	$old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warnings directly to a page screwing menu tab */
1198
	if (!cert_create($cert, null, 2048, 2000, $dn, "self-signed", "sha256")) {
1199
		while ($ssl_err = openssl_error_string()) {
1200
			log_error(sprintf(gettext("Error creating WebGUI Certificate: openssl library returns: %s"), $ssl_err));
1201
		}
1202
		error_reporting($old_err_level);
1203
		return null;
1204
	}
1205
	error_reporting($old_err_level);
1206

    
1207
	$a_cert[] = $cert;
1208
	$config['system']['webgui']['ssl-certref'] = $cert['refid'];
1209
	write_config(sprintf(gettext("Generated new self-signed HTTPS certificate (%s)"), $cert['refid']));
1210
	return $cert;
1211
}
1212

    
1213
function system_webgui_start() {
1214
	global $config, $g;
1215

    
1216
	if (platform_booting()) {
1217
		echo gettext("Starting webConfigurator...");
1218
	}
1219

    
1220
	chdir($g['www_path']);
1221

    
1222
	/* defaults */
1223
	$portarg = "80";
1224
	$crt = "";
1225
	$key = "";
1226
	$ca = "";
1227

    
1228
	/* non-standard port? */
1229
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "") {
1230
		$portarg = "{$config['system']['webgui']['port']}";
1231
	}
1232

    
1233
	if ($config['system']['webgui']['protocol'] == "https") {
1234
		// Ensure that we have a webConfigurator CERT
1235
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
1236
		if (!is_array($cert) || !$cert['crt'] || !$cert['prv']) {
1237
			$cert = system_webgui_create_certificate();
1238
		}
1239
		$crt = base64_decode($cert['crt']);
1240
		$key = base64_decode($cert['prv']);
1241

    
1242
		if (!$config['system']['webgui']['port']) {
1243
			$portarg = "443";
1244
		}
1245
		$ca = ca_chain($cert);
1246
		$hsts = isset($config['system']['webgui']['disablehsts']) ? false : true;
1247
	}
1248

    
1249
	/* generate nginx configuration */
1250
	system_generate_nginx_config("{$g['varetc_path']}/nginx-webConfigurator.conf",
1251
		$crt, $key, $ca, "nginx-webConfigurator.pid", $portarg, "/usr/local/www/",
1252
		"cert.crt", "cert.key", false, $hsts);
1253

    
1254
	/* kill any running nginx */
1255
	killbypid("{$g['varrun_path']}/nginx-webConfigurator.pid");
1256

    
1257
	sleep(1);
1258

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

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

    
1264
	if (platform_booting()) {
1265
		if ($res == 0) {
1266
			echo gettext("done.") . "\n";
1267
		} else {
1268
			echo gettext("failed!") . "\n";
1269
		}
1270
	}
1271

    
1272
	return $res;
1273
}
1274

    
1275
function get_dns_nameservers() {
1276
	global $config;
1277

    
1278
	$dns_nameservers = array();
1279

    
1280
	if (isset($config['system']['developerspew'])) {
1281
		$mt = microtime();
1282
		echo "get_dns_nameservers() being called $mt\n";
1283
	}
1284

    
1285
	$syscfg = $config['system'];
1286
	if ((((isset($config['dnsmasq']['enable'])) &&
1287
   		(empty($config['dnsmasq']['port']) || $config['dnsmasq']['port'] == "53") &&
1288
	      	(empty($config['dnsmasq']['interface']) ||
1289
	       	in_array("lo0", explode(",", $config['dnsmasq']['interface'])))) ||
1290
	     	((isset($config['unbound']['enable'])) &&
1291
	      	(empty($config['unbound']['port']) || $config['unbound']['port'] == "53") &&
1292
	      	(empty($config['unbound']['active_interface']) ||
1293
	       	in_array("lo0", explode(",", $config['unbound']['active_interface'])) ||
1294
	       	in_array("all", explode(",", $config['unbound']['active_interface']), true)))) &&
1295
	     	(!isset($config['system']['dnslocalhost']))) {
1296
			$dns_nameservers[] = "127.0.0.1";
1297
	}
1298
	/* get dynamically assigned DNS servers (if any) */
1299
	$ns = array_unique(get_nameservers());
1300
	if (isset($syscfg['dnsallowoverride'])) {
1301
		if(!is_array($ns)) {
1302
			$ns = array();
1303
		}
1304
		foreach ($ns as $nameserver) {
1305
			if ($nameserver) {
1306
				$dns_nameservers[] = "$nameserver";
1307
			}
1308
		}
1309
	}
1310
	if (is_array($syscfg['dnsserver'])) {
1311
		foreach ($syscfg['dnsserver'] as $sys_dnsserver) {
1312
			if ($sys_dnsserver && (!in_array($sys_dnsserver, $ns))) {
1313
				$dns_nameservers[] = "$sys_dnsserver";
1314
			}
1315
		}
1316
	}
1317
	return array_unique($dns_nameservers);
1318
}
1319

    
1320
function system_generate_nginx_config($filename,
1321
	$cert,
1322
	$key,
1323
	$ca,
1324
	$pid_file,
1325
	$port = 80,
1326
	$document_root = "/usr/local/www/",
1327
	$cert_location = "cert.crt",
1328
	$key_location = "cert.key",
1329
	$captive_portal = false,
1330
	$hsts = true) {
1331

    
1332
	global $config, $g;
1333

    
1334
	if (isset($config['system']['developerspew'])) {
1335
		$mt = microtime();
1336
		echo "system_generate_nginx_config() being called $mt\n";
1337
	}
1338

    
1339
	if ($captive_portal !== false) {
1340
		$cp_interfaces = explode(",", $config['captiveportal'][$captive_portal]['interface']);
1341
		$cp_hostcheck = "";
1342
		foreach ($cp_interfaces as $cpint) {
1343
			$cpint_ip = get_interface_ip($cpint);
1344
			if (is_ipaddr($cpint_ip)) {
1345
				$cp_hostcheck .= "\t\tif (\$http_host ~* $cpint_ip) {\n";
1346
				$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1347
				$cp_hostcheck .= "\t\t}\n";
1348
			}
1349
		}
1350
		if (isset($config['captiveportal'][$captive_portal]['httpsname']) &&
1351
		    is_domain($config['captiveportal'][$captive_portal]['httpsname'])) {
1352
			$cp_hostcheck .= "\t\tif (\$http_host ~* {$config['captiveportal'][$captive_portal]['httpsname']}) {\n";
1353
			$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1354
			$cp_hostcheck .= "\t\t}\n";
1355
		}
1356
		$cp_rewrite = "\t\tif (\$cp_redirect = '') {\n";
1357
		$cp_rewrite .= "\t\t\trewrite	^ /index.php?zone=$captive_portal&redirurl=\$request_uri break;\n";
1358
		$cp_rewrite .= "\t\t}\n";
1359

    
1360
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1361
		if (empty($maxprocperip)) {
1362
			$maxprocperip = 10;
1363
		}
1364
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1365
	}
1366

    
1367
	if (empty($port)) {
1368
		$nginx_port = "80";
1369
	} else {
1370
		$nginx_port = $port;
1371
	}
1372

    
1373
	$memory = get_memory();
1374
	$realmem = $memory[1];
1375

    
1376
	// Determine web GUI process settings and take into account low memory systems
1377
	if ($realmem < 255) {
1378
		$max_procs = 1;
1379
	} else {
1380
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
1381
	}
1382

    
1383
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM
1384
	if ($captive_portal !== false) {
1385
		if ($realmem > 135 and $realmem < 256) {
1386
			$max_procs += 1; // 2 worker processes
1387
		} else if ($realmem > 255 and $realmem < 513) {
1388
			$max_procs += 2; // 3 worker processes
1389
		} else if ($realmem > 512) {
1390
			$max_procs += 4; // 6 worker processes
1391
		}
1392
	}
1393

    
1394
	$nginx_config = <<<EOD
1395
#
1396
# nginx configuration file
1397

    
1398
pid {$g['varrun_path']}/{$pid_file};
1399

    
1400
user  root wheel;
1401
worker_processes  {$max_procs};
1402

    
1403
EOD;
1404

    
1405
	if (!isset($config['syslog']['nolognginx'])) {
1406
		$nginx_config .= "error_log  syslog:server=unix:/var/run/log,facility=local5;\n";
1407
	}
1408

    
1409
	$nginx_config .= <<<EOD
1410

    
1411
events {
1412
    worker_connections  1024;
1413
}
1414

    
1415
http {
1416
	include       /usr/local/etc/nginx/mime.types;
1417
	default_type  application/octet-stream;
1418
	add_header X-Frame-Options SAMEORIGIN;
1419
	server_tokens off;
1420

    
1421
	sendfile        on;
1422

    
1423
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1424

    
1425
EOD;
1426

    
1427
	if ($captive_portal !== false) {
1428
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1429
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1430
	} else {
1431
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1432
	}
1433

    
1434
	if ($cert <> "" and $key <> "") {
1435
		$nginx_config .= "\n";
1436
		$nginx_config .= "\tserver {\n";
1437
		$nginx_config .= "\t\tlisten {$nginx_port} ssl http2;\n";
1438
		$nginx_config .= "\t\tlisten [::]:{$nginx_port} ssl http2;\n";
1439
		$nginx_config .= "\n";
1440
		$nginx_config .= "\t\tssl_certificate         {$g['varetc_path']}/{$cert_location};\n";
1441
		$nginx_config .= "\t\tssl_certificate_key     {$g['varetc_path']}/{$key_location};\n";
1442
		$nginx_config .= "\t\tssl_session_timeout     10m;\n";
1443
		$nginx_config .= "\t\tkeepalive_timeout       70;\n";
1444
		$nginx_config .= "\t\tssl_session_cache       shared:SSL:10m;\n";
1445
		if ($captive_portal !== false) {
1446
			// leave TLSv1.0 for CP for now for compatibility
1447
			$nginx_config .= "\t\tssl_protocols   TLSv1 TLSv1.1 TLSv1.2;\n";
1448
		} else {
1449
			$nginx_config .= "\t\tssl_protocols   TLSv1.1 TLSv1.2;\n";
1450
		}
1451
		$nginx_config .= "\t\tssl_ciphers \"EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH\";\n";
1452
		$nginx_config .= "\t\tssl_prefer_server_ciphers       on;\n";
1453
		if ($captive_portal === false && $hsts !== false) {
1454
			$nginx_config .= "\t\tadd_header Strict-Transport-Security \"max-age=31536000\";\n";
1455
		}
1456
		$nginx_config .= "\t\tadd_header X-Content-Type-Options nosniff;\n";
1457
		$nginx_config .= "\t\tssl_session_tickets off;\n";
1458
		$nginx_config .= "\t\tssl_dhparam /etc/dh-parameters.4096;\n";
1459
		$cert_temp = lookup_cert($config['system']['webgui']['ssl-certref']);
1460
		if (($config['system']['webgui']['ocsp-staple'] == true) or
1461
		    (cert_get_ocspstaple($cert_temp['crt']) == true)) {
1462
			$nginx_config .= "\t\tssl_stapling on;\n";
1463
			$nginx_config .= "\t\tssl_stapling_verify on;\n";
1464
			$nginx_config .= "\t\tresolver " . implode(" ", get_dns_nameservers()) . " valid=300s;\n";
1465
			$nginx_config .= "\t\tresolver_timeout 5s;\n";
1466
		}
1467
	} else {
1468
		$nginx_config .= "\n";
1469
		$nginx_config .= "\tserver {\n";
1470
		$nginx_config .= "\t\tlisten {$nginx_port};\n";
1471
		$nginx_config .= "\t\tlisten [::]:{$nginx_port};\n";
1472
	}
1473

    
1474
	$nginx_config .= <<<EOD
1475

    
1476
		client_max_body_size 200m;
1477

    
1478
		gzip on;
1479
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
1480

    
1481

    
1482
EOD;
1483

    
1484
	if ($captive_portal !== false) {
1485
		$nginx_config .= <<<EOD
1486
$captive_portal_maxprocperip
1487
$cp_hostcheck
1488
$cp_rewrite
1489
		log_not_found off;
1490

    
1491
EOD;
1492

    
1493
	}
1494

    
1495
	$nginx_config .= <<<EOD
1496
		root "{$document_root}";
1497
		location / {
1498
			index  index.php index.html index.htm;
1499
		}
1500
		location ~ \.inc$ {
1501
			deny all;
1502
			return 403;
1503
		}
1504
		location ~ \.php$ {
1505
			try_files \$uri =404; #  This line closes a potential security hole
1506
			# ensuring users can't execute uploaded files
1507
			# see: http://forum.nginx.org/read.php?2,88845,page=3
1508
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1509
			fastcgi_index  index.php;
1510
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1511
			# Fix httpoxy - https://httpoxy.org/#fix-now
1512
			fastcgi_param  HTTP_PROXY  "";
1513
			fastcgi_read_timeout 180;
1514
			include        /usr/local/etc/nginx/fastcgi_params;
1515
		}
1516
		location ~ (^/status$) {
1517
			allow 127.0.0.1;
1518
			deny all;
1519
			fastcgi_pass   unix:{$g['varrun_path']}/php-fpm.socket;
1520
			fastcgi_index  index.php;
1521
			fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
1522
			# Fix httpoxy - https://httpoxy.org/#fix-now
1523
			fastcgi_param  HTTP_PROXY  "";
1524
			fastcgi_read_timeout 360;
1525
			include        /usr/local/etc/nginx/fastcgi_params;
1526
		}
1527
	}
1528

    
1529
EOD;
1530

    
1531
	$cert = str_replace("\r", "", $cert);
1532
	$key = str_replace("\r", "", $key);
1533

    
1534
	$cert = str_replace("\n\n", "\n", $cert);
1535
	$key = str_replace("\n\n", "\n", $key);
1536

    
1537
	if ($cert <> "" and $key <> "") {
1538
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1539
		if (!$fd) {
1540
			printf(gettext("Error: cannot open certificate file in system_webgui_start().%s"), "\n");
1541
			return 1;
1542
		}
1543
		chmod("{$g['varetc_path']}/{$cert_location}", 0644);
1544
		if ($ca <> "") {
1545
			$cert_chain = $cert . "\n" . $ca;
1546
		} else {
1547
			$cert_chain = $cert;
1548
		}
1549
		fwrite($fd, $cert_chain);
1550
		fclose($fd);
1551
		$fd = fopen("{$g['varetc_path']}/{$key_location}", "w");
1552
		if (!$fd) {
1553
			printf(gettext("Error: cannot open certificate key file in system_webgui_start().%s"), "\n");
1554
			return 1;
1555
		}
1556
		chmod("{$g['varetc_path']}/{$key_location}", 0600);
1557
		fwrite($fd, $key);
1558
		fclose($fd);
1559
	}
1560

    
1561
	// Add HTTP to HTTPS redirect
1562
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1563
		if ($nginx_port != "443") {
1564
			$redirectport = ":{$nginx_port}";
1565
		}
1566
		$nginx_config .= <<<EOD
1567
	server {
1568
		listen 80;
1569
		listen [::]:80;
1570
		return 301 https://\$http_host$redirectport\$request_uri;
1571
	}
1572

    
1573
EOD;
1574
	}
1575

    
1576
	$nginx_config .= "}\n";
1577

    
1578
	$fd = fopen("{$filename}", "w");
1579
	if (!$fd) {
1580
		printf(gettext('Error: cannot open %1$s in system_generate_nginx_config().%2$s'), $filename, "\n");
1581
		return 1;
1582
	}
1583
	fwrite($fd, $nginx_config);
1584
	fclose($fd);
1585

    
1586
	/* nginx will fail to start if this directory does not exist. */
1587
	safe_mkdir("/var/tmp/nginx/");
1588

    
1589
	return 0;
1590

    
1591
}
1592

    
1593
function system_get_timezone_list() {
1594
	global $g;
1595

    
1596
	$file_list = array_merge(
1597
		glob("/usr/share/zoneinfo/[A-Z]*"),
1598
		glob("/usr/share/zoneinfo/*/*"),
1599
		glob("/usr/share/zoneinfo/*/*/*")
1600
	);
1601

    
1602
	if (empty($file_list)) {
1603
		$file_list[] = $g['default_timezone'];
1604
	} else {
1605
		/* Remove directories from list */
1606
		$file_list = array_filter($file_list, function($v) {
1607
			return !is_dir($v);
1608
		});
1609
	}
1610

    
1611
	/* Remove directory prefix */
1612
	$file_list = str_replace('/usr/share/zoneinfo/', '', $file_list);
1613

    
1614
	sort($file_list);
1615

    
1616
	return $file_list;
1617
}
1618

    
1619
function system_timezone_configure() {
1620
	global $config, $g;
1621
	if (isset($config['system']['developerspew'])) {
1622
		$mt = microtime();
1623
		echo "system_timezone_configure() being called $mt\n";
1624
	}
1625

    
1626
	$syscfg = $config['system'];
1627

    
1628
	if (platform_booting()) {
1629
		echo gettext("Setting timezone...");
1630
	}
1631

    
1632
	/* extract appropriate timezone file */
1633
	$timezone = (isset($syscfg['timezone']) ? $syscfg['timezone'] : $g['default_timezone']);
1634
	/* DO NOT remove \n otherwise tzsetup will fail */
1635
	@file_put_contents("/var/db/zoneinfo", $timezone . "\n");
1636
	mwexec("/usr/sbin/tzsetup -r");
1637

    
1638
	if (platform_booting()) {
1639
		echo gettext("done.") . "\n";
1640
	}
1641
}
1642

    
1643
function system_ntp_setup_gps($serialport) {
1644
	global $config, $g;
1645
	$gps_device = '/dev/gps0';
1646
	$serialport = '/dev/'.$serialport;
1647

    
1648
	if (!file_exists($serialport)) {
1649
		return false;
1650
	}
1651

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

    
1656
	$gpsbaud = '4800';
1657
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['speed'])) {
1658
		switch ($config['ntpd']['gps']['speed']) {
1659
			case '16':
1660
				$gpsbaud = '9600';
1661
				break;
1662
			case '32':
1663
				$gpsbaud = '19200';
1664
				break;
1665
			case '48':
1666
				$gpsbaud = '38400';
1667
				break;
1668
			case '64':
1669
				$gpsbaud = '57600';
1670
				break;
1671
			case '80':
1672
				$gpsbaud = '115200';
1673
				break;
1674
		}
1675
	}
1676

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

    
1680
	/* Send the following to the GPS port to initialize the GPS */
1681
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['type'])) {
1682
		$gps_init = base64_decode($config['ntpd']['gps']['initcmd']);
1683
	} else {
1684
		$gps_init = base64_decode('JFBVQlgsNDAsR1NWLDAsMCwwLDAqNTkNCiRQVUJYLDQwLEdMTCwwLDAsMCwwKjVDDQokUFVCWCw0MCxaREEsMCwwLDAsMCo0NA0KJFBVQlgsNDAsVlRHLDAsMCwwLDAqNUUNCiRQVUJYLDQwLEdTViwwLDAsMCwwKjU5DQokUFVCWCw0MCxHU0EsMCwwLDAsMCo0RQ0KJFBVQlgsNDAsR0dBLDAsMCwwLDANCiRQVUJYLDQwLFRYVCwwLDAsMCwwDQokUFVCWCw0MCxSTUMsMCwwLDAsMCo0Ng0KJFBVQlgsNDEsMSwwMDA3LDAwMDMsNDgwMCwwDQokUFVCWCw0MCxaREEsMSwxLDEsMQ==');
1685
	}
1686

    
1687
	/* XXX: Why not file_put_contents to the device */
1688
	@file_put_contents('/tmp/gps.init', $gps_init);
1689
	mwexec("cat /tmp/gps.init > {$serialport}");
1690

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

    
1696

    
1697
	return true;
1698
}
1699

    
1700
function system_ntp_setup_pps($serialport) {
1701
	global $config, $g;
1702

    
1703
	$pps_device = '/dev/pps0';
1704
	$serialport = '/dev/'.$serialport;
1705

    
1706
	if (!file_exists($serialport)) {
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

    
1719
function system_ntp_configure() {
1720
	global $config, $g;
1721

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

    
1726
	safe_mkdir($statsdir);
1727

    
1728
	if (!is_array($config['ntpd'])) {
1729
		$config['ntpd'] = array();
1730
	}
1731

    
1732
	$ntpcfg = "# \n";
1733
	$ntpcfg .= "# pfSense ntp configuration file \n";
1734
	$ntpcfg .= "# \n\n";
1735
	$ntpcfg .= "tinker panic 0 \n";
1736

    
1737
	/* Add Orphan mode */
1738
	$ntpcfg .= "# Orphan mode stratum\n";
1739
	$ntpcfg .= 'tos orphan ';
1740
	if (!empty($config['ntpd']['orphan'])) {
1741
		$ntpcfg .= $config['ntpd']['orphan'];
1742
	} else {
1743
		$ntpcfg .= '12';
1744
	}
1745
	$ntpcfg .= "\n";
1746

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

    
1786
	/* Add GPS configuration */
1787
	if (is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['port']) &&
1788
	    file_exists('/dev/'.$config['ntpd']['gps']['port']) &&
1789
	    system_ntp_setup_gps($config['ntpd']['gps']['port'])) {
1790
		$ntpcfg .= "\n";
1791
		$ntpcfg .= "# GPS Setup\n";
1792
		$ntpcfg .= 'server 127.127.20.0 mode ';
1793
		if (!empty($config['ntpd']['gps']['nmea']) || !empty($config['ntpd']['gps']['speed']) || !empty($config['ntpd']['gps']['subsec']) || !empty($config['ntpd']['gps']['processpgrmf'])) {
1794
			if (!empty($config['ntpd']['gps']['nmea'])) {
1795
				$ntpmode = (int) $config['ntpd']['gps']['nmea'];
1796
			}
1797
			if (!empty($config['ntpd']['gps']['speed'])) {
1798
				$ntpmode += (int) $config['ntpd']['gps']['speed'];
1799
			}
1800
			if (!empty($config['ntpd']['gps']['subsec'])) {
1801
				$ntpmode += 128;
1802
			}
1803
			if (!empty($config['ntpd']['gps']['processpgrmf'])) {
1804
				$ntpmode += 256;
1805
			}
1806
			$ntpcfg .= (string) $ntpmode;
1807
		} else {
1808
			$ntpcfg .= '0';
1809
		}
1810
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1811
		if (empty($config['ntpd']['gps']['prefer'])) { /*note: this one works backwards */
1812
			$ntpcfg .= ' prefer';
1813
		}
1814
		if (!empty($config['ntpd']['gps']['noselect'])) {
1815
			$ntpcfg .= ' noselect ';
1816
		}
1817
		$ntpcfg .= "\n";
1818
		$ntpcfg .= 'fudge 127.127.20.0';
1819
		if (!empty($config['ntpd']['gps']['fudge1'])) {
1820
			$ntpcfg .= ' time1 ';
1821
			$ntpcfg .= $config['ntpd']['gps']['fudge1'];
1822
		}
1823
		if (!empty($config['ntpd']['gps']['fudge2'])) {
1824
			$ntpcfg .= ' time2 ';
1825
			$ntpcfg .= $config['ntpd']['gps']['fudge2'];
1826
		}
1827
		if (!empty($config['ntpd']['gps']['flag1'])) {
1828
			$ntpcfg .= ' flag1 1';
1829
		} else {
1830
			$ntpcfg .= ' flag1 0';
1831
		}
1832
		if (!empty($config['ntpd']['gps']['flag2'])) {
1833
			$ntpcfg .= ' flag2 1';
1834
		}
1835
		if (!empty($config['ntpd']['gps']['flag3'])) {
1836
			$ntpcfg .= ' flag3 1';
1837
		} else {
1838
			$ntpcfg .= ' flag3 0';
1839
		}
1840
		if (!empty($config['ntpd']['gps']['flag4'])) {
1841
			$ntpcfg .= ' flag4 1';
1842
		}
1843
		if (!empty($config['ntpd']['gps']['refid'])) {
1844
			$ntpcfg .= ' refid ';
1845
			$ntpcfg .= $config['ntpd']['gps']['refid'];
1846
		}
1847
		if (!empty($config['ntpd']['gps']['stratum'])) {
1848
			$ntpcfg .= ' stratum ';
1849
			$ntpcfg .= $config['ntpd']['gps']['stratum'];
1850
		}
1851
		$ntpcfg .= "\n";
1852
	} elseif (is_array($config['ntpd']) && !empty($config['ntpd']['gpsport']) &&
1853
	    file_exists('/dev/'.$config['ntpd']['gpsport']) &&
1854
	    system_ntp_setup_gps($config['ntpd']['gpsport'])) {
1855
		/* This handles a 2.1 and earlier config */
1856
		$ntpcfg .= "# GPS Setup\n";
1857
		$ntpcfg .= "server 127.127.20.0 mode 0 minpoll 4 maxpoll 4 prefer\n";
1858
		$ntpcfg .= "fudge 127.127.20.0 time1 0.155 time2 0.000 flag1 1 flag2 0 flag3 1\n";
1859
		// Fall back to local clock if GPS is out of sync?
1860
		$ntpcfg .= "server 127.127.1.0\n";
1861
		$ntpcfg .= "fudge 127.127.1.0 stratum 12\n";
1862
	}
1863
	/* End GPS configuration */
1864
	$auto_pool_suffix = "pool.ntp.org";
1865
	$have_pools = false;
1866
	$ntpcfg .= "\n\n# Upstream Servers\n";
1867
	/* foreach through ntp servers and write out to ntpd.conf */
1868
	foreach (explode(' ', $config['system']['timeservers']) as $ts) {
1869
		if ((substr_compare($ts, $auto_pool_suffix, strlen($ts) - strlen($auto_pool_suffix), strlen($auto_pool_suffix)) === 0)
1870
		    || substr_count($config['ntpd']['ispool'], $ts)) {
1871
			$ntpcfg .= 'pool ';
1872
			$have_pools = true;
1873
		} else {
1874
			$ntpcfg .= 'server ';
1875
		}
1876

    
1877
		$ntpcfg .= "{$ts} iburst maxpoll 9";
1878
		if (substr_count($config['ntpd']['prefer'], $ts)) {
1879
			$ntpcfg .= ' prefer';
1880
		}
1881
		if (substr_count($config['ntpd']['noselect'], $ts)) {
1882
			$ntpcfg .= ' noselect';
1883
		}
1884
		$ntpcfg .= "\n";
1885
	}
1886
	unset($ts);
1887

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

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

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

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

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

    
2019

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

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

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

    
2051
	/* if ntpd is running, kill it */
2052
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
2053
		killbypid("{$g['varrun_path']}/ntpd.pid");
2054
	}
2055
	@unlink("{$g['varrun_path']}/ntpd.pid");
2056

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

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

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

    
2070
function system_halt() {
2071
	global $g;
2072

    
2073
	system_reboot_cleanup();
2074

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

    
2078
function system_reboot() {
2079
	global $g;
2080

    
2081
	system_reboot_cleanup();
2082

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

    
2086
function system_reboot_sync($reroot=false) {
2087
	global $g;
2088

    
2089
	if ($reroot) {
2090
		$args = " -r ";
2091
	}
2092

    
2093
	system_reboot_cleanup();
2094

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

    
2098
function system_reboot_cleanup() {
2099
	global $config, $cpzone, $cpzoneid;
2100

    
2101
	mwexec("/usr/local/bin/beep.sh stop");
2102
	require_once("captiveportal.inc");
2103
	if (is_array($config['captiveportal'])) {
2104
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
2105
			/* send Accounting-Stop packet for all clients, termination cause 'Admin-Reboot' */
2106
			$cpzoneid = $cp['zoneid'];
2107
			captiveportal_radius_stop_all(7); // Admin-Reboot
2108
			/* Send Accounting-Off packet to the RADIUS server */
2109
			captiveportal_send_server_accounting('off');
2110
		}
2111
	}
2112
	require_once("voucher.inc");
2113
	voucher_save_db_to_config();
2114
	require_once("pkg-utils.inc");
2115
	stop_packages();
2116
}
2117

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

    
2125
	if ($early) {
2126
		$cmdn = "earlyshellcmd";
2127
	} else {
2128
		$cmdn = "shellcmd";
2129
	}
2130

    
2131
	if (is_array($config['system'][$cmdn])) {
2132

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

    
2138
	} elseif ($config['system'][$cmdn] <> "") {
2139

    
2140
		/* execute single item */
2141
		exec($config['system'][$cmdn]);
2142

    
2143
	}
2144
}
2145

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

    
2153
	$dmesg = "";
2154
	$_gb = exec("/sbin/dmesg", $dmesg);
2155

    
2156
	/* find last copyright line (output from previous boots may be present) */
2157
	$lastcpline = 0;
2158

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

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

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

    
2175
	fclose($fd);
2176
	unset($dmesg);
2177

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

    
2181
	return 0;
2182
}
2183

    
2184
function system_set_harddisk_standby() {
2185
	global $g, $config;
2186

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

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

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

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

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

    
2230
	activate_sysctls();
2231

    
2232
	if (isset($config['system']['sharednet'])) {
2233
		system_disable_arp_wrong_if();
2234
	}
2235
}
2236

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

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

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

    
2280
function system_check_reset_button() {
2281
	global $g;
2282

    
2283
	$specplatform = system_identify_specific_platform();
2284

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

    
2301
	$retval = mwexec("/usr/local/sbin/" . $binprefix . "resetbtn");
2302

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

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

    
2314

    
2315
EOD;
2316

    
2317
		reset_factory_defaults();
2318
		system_reboot_sync();
2319
		exit(0);
2320
	}
2321

    
2322
	return 0;
2323
}
2324

    
2325
function system_get_serial() {
2326
	$platform = system_identify_specific_platform();
2327

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

    
2346
	$vm_guest = get_single_sysctl('kern.vm_guest');
2347

    
2348
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2349
	    $vm_guest == 'none') {
2350
		return $serial;
2351
	}
2352

    
2353
	return "";
2354
}
2355

    
2356
function system_get_uniqueid() {
2357
	global $g;
2358

    
2359
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2360

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

    
2371
	return ($g['uniqueid'] ?: '');
2372
}
2373

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

    
2383
	$hw_model = get_single_sysctl('hw.model');
2384
	$hw_ncpu = get_single_sysctl('hw.ncpu');
2385

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

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

    
2468
	$_gb = exec('/bin/kenv -q smbios.planar.product 2>/dev/null',
2469
	    $planar_product);
2470
	if (isset($planar_product[0]) &&
2471
	    $planar_product[0] == 'X10SDV-8C-TLN4F+') {
2472
		return array('name' => 'XG-1537', 'descr' => 'Super Micro XG-1537');
2473
	}
2474

    
2475
	if (strpos($hw_model, "PC Engines WRAP") !== false) {
2476
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
2477
	}
2478

    
2479
	if (strpos($hw_model, "PC Engines ALIX") !== false) {
2480
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2481
	}
2482

    
2483
	if (preg_match("/Soekris net45../", $hw_model, $matches)) {
2484
		return array('name' => 'net45xx', 'descr' => $matches[0]);
2485
	}
2486

    
2487
	if (preg_match("/Soekris net48../", $hw_model, $matches)) {
2488
		return array('name' => 'net48xx', 'descr' => $matches[0]);
2489
	}
2490

    
2491
	if (preg_match("/Soekris net55../", $hw_model, $matches)) {
2492
		return array('name' => 'net55xx', 'descr' => $matches[0]);
2493
	}
2494

    
2495
	unset($hw_model);
2496

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

    
2503
	return array('name' => $g['platform'], 'descr' => $g['platform']);
2504
}
2505

    
2506
function system_get_dmesg_boot() {
2507
	global $g;
2508

    
2509
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2510
}
2511

    
2512
?>
(48-48/60)