Project

General

Profile

Download (70.3 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/sshlockout_pf 15
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
	if (!$sighup) {
1145
		sigkillbyname("sshlockout_pf", "TERM");
1146
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1147
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "TERM");
1148
			usleep(100000); // syslogd often doesn't respond to a TERM quickly enough for the starting of syslogd below to be successful
1149
		}
1150

    
1151
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1152
			// if it still hasn't responded to the TERM, KILL it.
1153
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
1154
			usleep(100000);
1155
		}
1156

    
1157
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c {$syslogd_sockets} -P {$g['varrun_path']}/syslog.pid {$syslogd_extra}");
1158
	} else {
1159
		$retval = sigkillbypid("{$g['varrun_path']}/syslog.pid", "HUP");
1160
	}
1161

    
1162
	if (platform_booting()) {
1163
		echo gettext("done.") . "\n";
1164
	}
1165

    
1166
	return $retval;
1167
}
1168

    
1169
function system_webgui_create_certificate() {
1170
	global $config, $g;
1171

    
1172
	if (!is_array($config['ca'])) {
1173
		$config['ca'] = array();
1174
	}
1175
	$a_ca =& $config['ca'];
1176
	if (!is_array($config['cert'])) {
1177
		$config['cert'] = array();
1178
	}
1179
	$a_cert =& $config['cert'];
1180
	log_error(gettext("Creating SSL Certificate for this host"));
1181

    
1182
	$cert = array();
1183
	$cert['refid'] = uniqid();
1184
	$cert['descr'] = sprintf(gettext("webConfigurator default (%s)"), $cert['refid']);
1185
	$cert_hostname = "{$config['system']['hostname']}-{$cert['refid']}";
1186

    
1187
	$dn = array(
1188
		'countryName' => "US",
1189
		'stateOrProvinceName' => "State",
1190
		'localityName' => "Locality",
1191
		'organizationName' => "{$g['product_name']} webConfigurator Self-Signed Certificate",
1192
		'emailAddress' => "admin@{$config['system']['hostname']}.{$config['system']['domain']}",
1193
		'commonName' => $cert_hostname,
1194
		'subjectAltName' => "DNS:{$cert_hostname}");
1195
	$old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warnings directly to a page screwing menu tab */
1196
	if (!cert_create($cert, null, 2048, 2000, $dn, "self-signed", "sha256")) {
1197
		while ($ssl_err = openssl_error_string()) {
1198
			log_error(sprintf(gettext("Error creating WebGUI Certificate: openssl library returns: %s"), $ssl_err));
1199
		}
1200
		error_reporting($old_err_level);
1201
		return null;
1202
	}
1203
	error_reporting($old_err_level);
1204

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

    
1211
function system_webgui_start() {
1212
	global $config, $g;
1213

    
1214
	if (platform_booting()) {
1215
		echo gettext("Starting webConfigurator...");
1216
	}
1217

    
1218
	chdir($g['www_path']);
1219

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

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

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

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

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

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

    
1255
	sleep(1);
1256

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

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

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

    
1270
	return $res;
1271
}
1272

    
1273
function get_dns_nameservers() {
1274
	global $config;
1275

    
1276
	$dns_nameservers = array();
1277

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

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

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

    
1330
	global $config, $g;
1331

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

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

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

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

    
1371
	$memory = get_memory();
1372
	$realmem = $memory[1];
1373

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

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

    
1392
	$nginx_config = <<<EOD
1393
#
1394
# nginx configuration file
1395

    
1396
pid {$g['varrun_path']}/{$pid_file};
1397

    
1398
user  root wheel;
1399
worker_processes  {$max_procs};
1400

    
1401
EOD;
1402

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

    
1407
	$nginx_config .= <<<EOD
1408

    
1409
events {
1410
    worker_connections  1024;
1411
}
1412

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

    
1419
	sendfile        on;
1420

    
1421
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1422

    
1423
EOD;
1424

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

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

    
1472
	$nginx_config .= <<<EOD
1473

    
1474
		client_max_body_size 200m;
1475

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

    
1479

    
1480
EOD;
1481

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

    
1489
EOD;
1490

    
1491
	}
1492

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

    
1527
EOD;
1528

    
1529
	$cert = str_replace("\r", "", $cert);
1530
	$key = str_replace("\r", "", $key);
1531

    
1532
	$cert = str_replace("\n\n", "\n", $cert);
1533
	$key = str_replace("\n\n", "\n", $key);
1534

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

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

    
1571
EOD;
1572
	}
1573

    
1574
	$nginx_config .= "}\n";
1575

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

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

    
1587
	return 0;
1588

    
1589
}
1590

    
1591
function system_get_timezone_list() {
1592
	global $g;
1593

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

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

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

    
1612
	sort($file_list);
1613

    
1614
	return $file_list;
1615
}
1616

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

    
1624
	$syscfg = $config['system'];
1625

    
1626
	if (platform_booting()) {
1627
		echo gettext("Setting timezone...");
1628
	}
1629

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

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

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

    
1646
	if (!file_exists($serialport)) {
1647
		return false;
1648
	}
1649

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

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

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

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

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

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

    
1694

    
1695
	return true;
1696
}
1697

    
1698
function system_ntp_setup_pps($serialport) {
1699
	global $config, $g;
1700

    
1701
	$pps_device = '/dev/pps0';
1702
	$serialport = '/dev/'.$serialport;
1703

    
1704
	if (!file_exists($serialport)) {
1705
		return false;
1706
	}
1707

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

    
1712

    
1713
	return true;
1714
}
1715

    
1716

    
1717
function system_ntp_configure() {
1718
	global $config, $g;
1719

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

    
1724
	safe_mkdir($statsdir);
1725

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

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

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

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

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

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

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

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

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

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

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

    
2017

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

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

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

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

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

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

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

    
2068
function system_halt() {
2069
	global $g;
2070

    
2071
	system_reboot_cleanup();
2072

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

    
2076
function system_reboot() {
2077
	global $g;
2078

    
2079
	system_reboot_cleanup();
2080

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

    
2084
function system_reboot_sync($reroot=false) {
2085
	global $g;
2086

    
2087
	if ($reroot) {
2088
		$args = " -r ";
2089
	}
2090

    
2091
	system_reboot_cleanup();
2092

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

    
2096
function system_reboot_cleanup() {
2097
	global $config, $cpzone, $cpzoneid;
2098

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

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

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

    
2129
	if (is_array($config['system'][$cmdn])) {
2130

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

    
2136
	} elseif ($config['system'][$cmdn] <> "") {
2137

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

    
2141
	}
2142
}
2143

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

    
2151
	$dmesg = "";
2152
	$_gb = exec("/sbin/dmesg", $dmesg);
2153

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

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

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

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

    
2173
	fclose($fd);
2174
	unset($dmesg);
2175

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

    
2179
	return 0;
2180
}
2181

    
2182
function system_set_harddisk_standby() {
2183
	global $g, $config;
2184

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

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

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

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

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

    
2228
	activate_sysctls();
2229

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

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

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

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

    
2278
function system_check_reset_button() {
2279
	global $g;
2280

    
2281
	$specplatform = system_identify_specific_platform();
2282

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

    
2299
	$retval = mwexec("/usr/local/sbin/" . $binprefix . "resetbtn");
2300

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

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

    
2312

    
2313
EOD;
2314

    
2315
		reset_factory_defaults();
2316
		system_reboot_sync();
2317
		exit(0);
2318
	}
2319

    
2320
	return 0;
2321
}
2322

    
2323
function system_get_serial() {
2324
	$platform = system_identify_specific_platform();
2325

    
2326
	unset($output);
2327
	if ($platform['name'] == 'Turbot Dual-E') {
2328
		$if_info = pfSense_get_interface_addresses('igb0');
2329
		if (!empty($if_info['hwaddr'])) {
2330
			$serial = str_replace(":", "", $if_info['hwaddr']);
2331
		}
2332
	} else {
2333
		$_gb = exec('/bin/kenv smbios.system.serial 2>/dev/null', $output);
2334
		$serial = $output[0];
2335
	}
2336

    
2337
	$vm_guest = get_single_sysctl('kern.vm_guest');
2338

    
2339
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2340
	    $vm_guest == 'none') {
2341
		return $serial;
2342
	}
2343

    
2344
	return "";
2345
}
2346

    
2347
function system_get_uniqueid() {
2348
	global $g;
2349

    
2350
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2351

    
2352
	if (empty($g['uniqueid'])) {
2353
		if (!file_exists($uniqueid_file)) {
2354
			mwexec("/usr/sbin/gnid > {$g['vardb_path']}/uniqueid " .
2355
			    "2>/dev/null");
2356
		}
2357
		if (file_exists($uniqueid_file)) {
2358
			$g['uniqueid'] = @file_get_contents($uniqueid_file);
2359
		}
2360
	}
2361

    
2362
	return ($g['uniqueid'] ?: '');
2363
}
2364

    
2365
/*
2366
 * attempt to identify the specific platform (for embedded systems)
2367
 * Returns an array with two elements:
2368
 * name => platform string (e.g. 'wrap', 'alix' etc.)
2369
 * descr => human-readable description (e.g. "PC Engines WRAP")
2370
 */
2371
function system_identify_specific_platform() {
2372
	global $g;
2373

    
2374
	$hw_model = get_single_sysctl('hw.model');
2375
	$hw_ncpu = get_single_sysctl('hw.ncpu');
2376

    
2377
	/* Try to guess from smbios strings */
2378
	unset($product);
2379
	unset($maker);
2380
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $product);
2381
	$_gb = exec('/bin/kenv -q smbios.system.maker 2>/dev/null', $maker);
2382
	switch ($product[0]) {
2383
		case 'FW7541':
2384
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2385
			break;
2386
		case 'APU':
2387
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2388
			break;
2389
		case 'RCC-VE':
2390
			$result = array();
2391
			$result['name'] = 'RCC-VE';
2392

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

    
2459
	$_gb = exec('/bin/kenv -q smbios.planar.product 2>/dev/null',
2460
	    $planar_product);
2461
	if (isset($planar_product[0]) &&
2462
	    $planar_product[0] == 'X10SDV-8C-TLN4F+') {
2463
		return array('name' => 'XG-1537', 'descr' => 'Super Micro XG-1537');
2464
	}
2465

    
2466
	if (strpos($hw_model, "PC Engines WRAP") !== false) {
2467
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
2468
	}
2469

    
2470
	if (strpos($hw_model, "PC Engines ALIX") !== false) {
2471
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2472
	}
2473

    
2474
	if (preg_match("/Soekris net45../", $hw_model, $matches)) {
2475
		return array('name' => 'net45xx', 'descr' => $matches[0]);
2476
	}
2477

    
2478
	if (preg_match("/Soekris net48../", $hw_model, $matches)) {
2479
		return array('name' => 'net48xx', 'descr' => $matches[0]);
2480
	}
2481

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

    
2486
	unset($hw_model);
2487

    
2488
	$dmesg_boot = system_get_dmesg_boot();
2489
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
2490
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2491
	}
2492
	unset($dmesg_boot);
2493

    
2494
	return array('name' => $g['platform'], 'descr' => $g['platform']);
2495
}
2496

    
2497
function system_get_dmesg_boot() {
2498
	global $g;
2499

    
2500
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2501
}
2502

    
2503
?>
(48-48/60)