Project

General

Profile

Download (70.7 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" .
49
			" -b " . escapeshellarg($battery_mode) .
50
			" -a " . escapeshellarg($ac_mode) .
51
			" -n " . escapeshellarg($normal_mode));
52
	}
53
}
54

    
55
function get_default_sysctl_value($id) {
56
	global $sysctls;
57

    
58
	if (isset($sysctls[$id])) {
59
		return $sysctls[$id];
60
	}
61
}
62

    
63
function get_sysctl_descr($sysctl) {
64
	unset($output);
65
	$_gb = exec("/sbin/sysctl -qnd {$sysctl}", $output);
66

    
67
	return $output[0];
68
}
69

    
70
function system_get_sysctls() {
71
	global $config, $sysctls;
72

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

    
83
			$disp_sysctl[$id] = $tunable;
84
			$disp_sysctl[$id]['modified'] = true;
85
			$disp_cache[$tunable['tunable']] = 'set';
86
		}
87
	}
88

    
89
	foreach ($sysctls as $sysctl => $value) {
90
		if (isset($disp_cache[$sysctl])) {
91
			continue;
92
		}
93

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

    
100
function activate_sysctls() {
101
	global $config, $g, $sysctls;
102

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

    
111
			$sysctls[$tunable['tunable']] = $value;
112
		}
113
	}
114

    
115
	set_sysctl($sysctls);
116
}
117

    
118
function system_resolvconf_generate($dynupdate = false) {
119
	global $config, $g;
120

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

    
126
	$syscfg = $config['system'];
127

    
128
	foreach(get_dns_nameservers() as $dns_ns) {
129
		$resolvconf .= "nameserver $dns_ns\n";
130
	}
131

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

    
149
	// Add EDNS support
150
	if (isset($config['unbound']['enable']) && isset($config['unbound']['edns'])) {
151
		$resolvconf .= "options edns0\n";
152
	}
153

    
154
	$dnslock = lock('resolvconf', LOCK_EX);
155

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

    
163
	fwrite($fd, $resolvconf);
164
	fclose($fd);
165

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

    
175
	if (!platform_booting()) {
176
		/* restart dhcpd (nameservers may have changed) */
177
		if (!$dynupdate) {
178
			services_dhcpd_configure();
179
		}
180
	}
181

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

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

    
210
	unlock($dnslock);
211

    
212
	return 0;
213
}
214

    
215
function get_searchdomains() {
216
	global $config, $g;
217

    
218
	$master_list = array();
219

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

    
236
	return $master_list;
237
}
238

    
239
function get_nameservers() {
240
	global $config, $g;
241
	$master_list = array();
242

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

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

    
271
	return $master_list;
272
}
273

    
274
/* Create localhost + local interfaces entries for /etc/hosts */
275
function system_hosts_local_entries() {
276
	global $config;
277

    
278
	$syscfg = $config['system'];
279

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

    
294
	if ($config['interfaces']['lan']) {
295
		$sysiflist = array('lan' => "lan");
296
	} else {
297
		$sysiflist = get_configured_interface_list();
298
	}
299

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

    
333
	return $hosts;
334
}
335

    
336
/* Read host override entries from dnsmasq or unbound */
337
function system_hosts_override_entries($dnscfg) {
338
	$hosts = array();
339

    
340
	if (!is_array($dnscfg) ||
341
	    !is_array($dnscfg['hosts']) ||
342
	    !isset($dnscfg['enable'])) {
343
		return $hosts;
344
	}
345

    
346
	foreach ($dnscfg['hosts'] as $host) {
347
		$fqdn = '';
348
		if ($host['host'] || $host['host'] == "0") {
349
			$fqdn .= "{$host['host']}.";
350
		}
351
		$fqdn .= $host['domain'];
352

    
353
		$hosts[] = array(
354
		    'ipaddr' => $host['ip'],
355
		    'fqdn' => $fqdn,
356
		    'name' => $host['host'],
357
		    'domain' => $host['domain']
358
		);
359

    
360
		if (!is_array($host['aliases']) ||
361
		    !is_array($host['aliases']['item'])) {
362
			continue;
363
		}
364

    
365
		foreach ($host['aliases']['item'] as $alias) {
366
			$fqdn = '';
367
			if ($alias['host'] || $alias['host'] == "0") {
368
				$fqdn .= "{$alias['host']}.";
369
			}
370
			$fqdn .= $alias['domain'];
371

    
372
			$hosts[] = array(
373
			    'ipaddr' => $host['ip'],
374
			    'fqdn' => $fqdn,
375
			    'name' => $alias['host'],
376
			    'domain' => $alias['domain']
377
			);
378
		}
379
	}
380

    
381
	return $hosts;
382
}
383

    
384
/* Read all dhcpd/dhcpdv6 staticmap entries */
385
function system_hosts_dhcpd_entries() {
386
	global $config;
387

    
388
	$hosts = array();
389
	$syscfg = $config['system'];
390

    
391
	if (is_array($config['dhcpd'])) {
392
		$conf_dhcpd = $config['dhcpd'];
393
	} else {
394
		$conf_dhcpd = array();
395
	}
396

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

    
408
			$fqdn = $host['hostname'] . ".";
409
			$domain = "";
410
			if ($host['domain']) {
411
				$domain = $host['domain'];
412
			} elseif ($dhcpifconf['domain']) {
413
				$domain = $dhcpifconf['domain'];
414
			} else {
415
				$domain = $syscfg['domain'];
416
			}
417

    
418
			$hosts[] = array(
419
			    'ipaddr' => $host['ipaddr'],
420
			    'fqdn' => $fqdn . $domain,
421
			    'name' => $host['hostname'],
422
			    'domain' => $domain
423
			);
424
		}
425
	}
426
	unset($conf_dhcpd);
427

    
428
	if (is_array($config['dhcpdv6'])) {
429
		$conf_dhcpdv6 = $config['dhcpdv6'];
430
	} else {
431
		$conf_dhcpdv6 = array();
432
	}
433

    
434
	foreach ($conf_dhcpdv6 as $dhcpif => $dhcpifconf) {
435
		if (!is_array($dhcpifconf['staticmap']) ||
436
		    !isset($dhcpifconf['enable'])) {
437
			continue;
438
		}
439

    
440
		if (isset($config['interfaces'][$dhcpif]['ipaddrv6']) &&
441
		    $config['interfaces'][$dhcpif]['ipaddrv6'] ==
442
		    'track6') {
443
			$isdelegated = true;
444
		} else {
445
			$isdelegated = false;
446
		}
447

    
448
		foreach ($dhcpifconf['staticmap'] as $host) {
449
			$ipaddrv6 = $host['ipaddrv6'];
450

    
451
			if (!$ipaddrv6 || !$host['hostname']) {
452
				continue;
453
			}
454

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

    
465
			$fqdn = $host['hostname'] . ".";
466
			$domain = "";
467
			if ($host['domain']) {
468
				$domain = $host['domain'];
469
			} elseif ($dhcpifconf['domain']) {
470
				$domain = $dhcpifconf['domain'];
471
			} else {
472
				$domain = $syscfg['domain'];
473
			}
474

    
475
			$hosts[] = array(
476
			    'ipaddr' => $ipaddrv6,
477
			    'fqdn' => $fqdn . $domain,
478
			    'name' => $host['hostname'],
479
			    'domain' => $domain
480
			);
481
		}
482
	}
483
	unset($conf_dhcpdv6);
484

    
485
	return $hosts;
486
}
487

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

    
495
	$dns = array();
496
	$dhcpd = array();
497
	if (isset($dnscfg['enable'])) {
498
		$dns = system_hosts_override_entries($dnscfg);
499
		if (isset($dnscfg['regdhcpstatic'])) {
500
			$dhcpd = system_hosts_dhcpd_entries();
501
		}
502
	}
503

    
504
	if (isset($dnscfg['dhcpfirst'])) {
505
		return array_merge($local, $dns, $dhcpd);
506
	} else {
507
		return array_merge($local, $dhcpd, $dns);
508
	}
509
}
510

    
511
function system_hosts_generate() {
512
	global $config, $g;
513
	if (isset($config['system']['developerspew'])) {
514
		$mt = microtime();
515
		echo "system_hosts_generate() being called $mt\n";
516
	}
517

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

    
526
	$syscfg = $config['system'];
527
	$hosts = "";
528
	$lhosts = "";
529
	$dhosts = "";
530

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

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

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

    
560
	fwrite($fd, $hosts);
561
	fclose($fd);
562

    
563
	if (isset($config['unbound']['enable'])) {
564
		require_once("unbound.inc");
565
		unbound_hosts_generate();
566
	}
567

    
568
	/* restart dhcpleases */
569
	if (!platform_booting()) {
570
		system_dhcpleases_configure();
571
	}
572

    
573
	return 0;
574
}
575

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

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

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

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

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

    
624
function system_hostname_configure() {
625
	global $config, $g;
626
	if (isset($config['system']['developerspew'])) {
627
		$mt = microtime();
628
		echo "system_hostname_configure() being called $mt\n";
629
	}
630

    
631
	$syscfg = $config['system'];
632

    
633
	/* set hostname */
634
	$status = mwexec("/bin/hostname " .
635
		escapeshellarg("{$syscfg['hostname']}.{$syscfg['domain']}"));
636

    
637
	/* Setup host GUID ID.  This is used by ZFS. */
638
	mwexec("/etc/rc.d/hostid start");
639

    
640
	return $status;
641
}
642

    
643
function system_routing_configure($interface = "") {
644
	global $config, $g;
645

    
646
	if (isset($config['system']['developerspew'])) {
647
		$mt = microtime();
648
		echo "system_routing_configure() being called $mt\n";
649
	}
650

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

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

    
677
	if ($dont_add_route == false) {
678
		$gateways_status = return_gateways_status(true);
679
		fixup_default_gateway("inet", $gateways_status, $gateways_arr);
680
		fixup_default_gateway("inet6", $gateways_status, $gateways_arr);
681
	}
682

    
683
	system_staticroutes_configure($interface, false);
684

    
685
	return 0;
686
}
687

    
688
function system_staticroutes_configure($interface = "", $update_dns = false) {
689
	global $config, $g, $aliastable;
690

    
691
	$filterdns_list = array();
692

    
693
	$static_routes = get_staticroutes(false, true);
694
	if (count($static_routes)) {
695
		$gateways_arr = return_gateways_array(false, true);
696

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

    
707
			$gatewayip = $gateway['gateway'];
708
			$interfacegw = $gateway['interface'];
709

    
710
			$blackhole = "";
711
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 4))) {
712
				$blackhole = "-blackhole";
713
			}
714

    
715
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network'])) {
716
				continue;
717
			}
718

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

    
730
			if (is_subnet($rtent['network'])) {
731
				$ips = array($rtent['network']);
732
			} else {
733
				if (!isset($rtent['disabled'])) {
734
					$filterdns_list[] = $rtent['network'];
735
				}
736
				$ips = add_hostname_to_watch($rtent['network']);
737
			}
738

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

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

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

    
768
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
769

    
770
				$cmd = "{$inet} {$blackhole} {$ip} ";
771

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

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

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

    
812
	return 0;
813
}
814

    
815
function system_routing_enable() {
816
	global $config, $g;
817
	if (isset($config['system']['developerspew'])) {
818
		$mt = microtime();
819
		echo "system_routing_enable() being called $mt\n";
820
	}
821

    
822
	set_sysctl(array(
823
		"net.inet.ip.forwarding" => "1",
824
		"net.inet6.ip6.forwarding" => "1"
825
	));
826

    
827
	return;
828
}
829

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

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

    
859
function clear_log_file($logfile = "/var/log/system.log", $restart_syslogd = true) {
860
	global $config, $g;
861

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

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

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

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

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

    
919
	mwexec("/etc/rc.d/hostid start");
920

    
921
	$syslogcfg = $config['syslog'];
922

    
923
	if (platform_booting()) {
924
		echo gettext("Starting syslog...");
925
	}
926

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

    
938
	$syslogd_extra = "";
939
	if (isset($syslogcfg)) {
940
		$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');
941
		$syslogconf = "";
942
		if ($config['installedpackages']['package']) {
943
			foreach ($config['installedpackages']['package'] as $package) {
944
				if (isset($package['logging']['facilityname']) && isset($package['logging']['logfilename'])) {
945
					array_push($separatelogfacilities, $package['logging']['facilityname']);
946
					if (!is_file($g['varlog_path'].'/'.$package['logging']['logfilename'])) {
947
						mwexec("{$log_create_directive} {$log_size} {$g['varlog_path']}/{$package['logging']['logfilename']}");
948
					}
949
					$syslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$log_directive}{$g['varlog_path']}/{$package['logging']['logfilename']}\n";
950
				}
951
			}
952
		}
953
		$facilitylist = implode(',', array_unique($separatelogfacilities));
954
		$syslogconf .= "!radvd,routed,olsrd,zebra,ospfd,ospf6d,bgpd,miniupnpd\n";
955
		if (!isset($syslogcfg['disablelocallogging'])) {
956
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/routing.log\n";
957
		}
958
		if (isset($syslogcfg['routing'])) {
959
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
960
		}
961

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

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

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

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

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

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

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

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

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

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

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

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

    
1058
		$syslogconf .= "!-{$facilitylist}\n";
1059
		if (!isset($syslogcfg['disablelocallogging'])) {
1060
			$syslogconf .= <<<EOD
1061
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
1062
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
1063
local5.*							{$log_directive}{$g['varlog_path']}/nginx.log
1064
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
1065
*.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
1066
auth.info;authpriv.info 					|exec /usr/local/sbin/sshguard
1067
*.emerg								*
1068

    
1069
EOD;
1070
		}
1071
		if (isset($syslogcfg['vpn'])) {
1072
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
1073
		}
1074
		if (isset($syslogcfg['portalauth'])) {
1075
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
1076
		}
1077
		if (isset($syslogcfg['dhcp'])) {
1078
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
1079
		}
1080
		if (isset($syslogcfg['system'])) {
1081
			$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");
1082
		}
1083
		if (isset($syslogcfg['logall'])) {
1084
			// Make everything mean everything, including facilities excluded above.
1085
			$syslogconf .= "!*\n";
1086
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1087
		}
1088

    
1089
		if (isset($syslogcfg['zmqserver'])) {
1090
				$syslogconf .= <<<EOD
1091
*.*								^{$syslogcfg['zmqserver']}
1092

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

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

    
1121
		$syslogd_extra = "-f {$g['etc_path']}/syslog.conf {$sourceip}";
1122
	}
1123

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

    
1126
	if (isset($config['installedpackages']['package'])) {
1127
		foreach ($config['installedpackages']['package'] as $package) {
1128
			if (isset($package['logging']['logsocket']) && $package['logging']['logsocket'] != '' &&
1129
			    !in_array($package['logging']['logsocket'], $log_sockets)) {
1130
				$log_sockets[] = $package['logging']['logsocket'];
1131
			}
1132
		}
1133
	}
1134

    
1135
	$syslogd_sockets = "";
1136
	foreach ($log_sockets as $log_socket) {
1137
		// Ensure that the log directory exists
1138
		$logpath = dirname($log_socket);
1139
		safe_mkdir($logpath);
1140
		$syslogd_sockets .= " -l {$log_socket}";
1141
	}
1142

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

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

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

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

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

    
1172
	if (platform_booting()) {
1173
		echo gettext("done.") . "\n";
1174
	}
1175

    
1176
	return $retval;
1177
}
1178

    
1179
function system_webgui_create_certificate() {
1180
	global $config, $g;
1181

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

    
1192
	$cert = array();
1193
	$cert['refid'] = uniqid();
1194
	$cert['descr'] = sprintf(gettext("webConfigurator default (%s)"), $cert['refid']);
1195
	$cert_hostname = "{$config['system']['hostname']}-{$cert['refid']}";
1196

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

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

    
1217
function system_webgui_start() {
1218
	global $config, $g;
1219

    
1220
	if (platform_booting()) {
1221
		echo gettext("Starting webConfigurator...");
1222
	}
1223

    
1224
	chdir($g['www_path']);
1225

    
1226
	/* defaults */
1227
	$portarg = "80";
1228
	$crt = "";
1229
	$key = "";
1230
	$ca = "";
1231

    
1232
	/* non-standard port? */
1233
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "") {
1234
		$portarg = "{$config['system']['webgui']['port']}";
1235
	}
1236

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

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

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

    
1258
	/* kill any running nginx */
1259
	killbypid("{$g['varrun_path']}/nginx-webConfigurator.pid");
1260

    
1261
	sleep(1);
1262

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

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

    
1268
	if (platform_booting()) {
1269
		if ($res == 0) {
1270
			echo gettext("done.") . "\n";
1271
		} else {
1272
			echo gettext("failed!") . "\n";
1273
		}
1274
	}
1275

    
1276
	return $res;
1277
}
1278

    
1279
function get_dns_nameservers() {
1280
	global $config;
1281

    
1282
	$dns_nameservers = array();
1283

    
1284
	if (isset($config['system']['developerspew'])) {
1285
		$mt = microtime();
1286
		echo "get_dns_nameservers() being called $mt\n";
1287
	}
1288

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

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

    
1336
	global $config, $g;
1337

    
1338
	if (isset($config['system']['developerspew'])) {
1339
		$mt = microtime();
1340
		echo "system_generate_nginx_config() being called $mt\n";
1341
	}
1342

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

    
1364
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1365
		if (empty($maxprocperip)) {
1366
			$maxprocperip = 10;
1367
		}
1368
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1369
	}
1370

    
1371
	if (empty($port)) {
1372
		$nginx_port = "80";
1373
	} else {
1374
		$nginx_port = $port;
1375
	}
1376

    
1377
	$memory = get_memory();
1378
	$realmem = $memory[1];
1379

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

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

    
1398
	$nginx_config = <<<EOD
1399
#
1400
# nginx configuration file
1401

    
1402
pid {$g['varrun_path']}/{$pid_file};
1403

    
1404
user  root wheel;
1405
worker_processes  {$max_procs};
1406

    
1407
EOD;
1408

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

    
1413
	$nginx_config .= <<<EOD
1414

    
1415
events {
1416
    worker_connections  1024;
1417
}
1418

    
1419
http {
1420
	include       /usr/local/etc/nginx/mime.types;
1421
	default_type  application/octet-stream;
1422
	add_header X-Frame-Options SAMEORIGIN;
1423
	server_tokens off;
1424

    
1425
	sendfile        on;
1426

    
1427
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1428

    
1429
EOD;
1430

    
1431
	if ($captive_portal !== false) {
1432
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1433
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1434
	} else {
1435
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1436
	}
1437

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

    
1478
	$nginx_config .= <<<EOD
1479

    
1480
		client_max_body_size 200m;
1481

    
1482
		gzip on;
1483
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
1484

    
1485

    
1486
EOD;
1487

    
1488
	if ($captive_portal !== false) {
1489
		$nginx_config .= <<<EOD
1490
$captive_portal_maxprocperip
1491
$cp_hostcheck
1492
$cp_rewrite
1493
		log_not_found off;
1494

    
1495
EOD;
1496

    
1497
	}
1498

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

    
1533
EOD;
1534

    
1535
	$cert = str_replace("\r", "", $cert);
1536
	$key = str_replace("\r", "", $key);
1537

    
1538
	$cert = str_replace("\n\n", "\n", $cert);
1539
	$key = str_replace("\n\n", "\n", $key);
1540

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

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

    
1577
EOD;
1578
	}
1579

    
1580
	$nginx_config .= "}\n";
1581

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

    
1590
	/* nginx will fail to start if this directory does not exist. */
1591
	safe_mkdir("/var/tmp/nginx/");
1592

    
1593
	return 0;
1594

    
1595
}
1596

    
1597
function system_get_timezone_list() {
1598
	global $g;
1599

    
1600
	$file_list = array_merge(
1601
		glob("/usr/share/zoneinfo/[A-Z]*"),
1602
		glob("/usr/share/zoneinfo/*/*"),
1603
		glob("/usr/share/zoneinfo/*/*/*")
1604
	);
1605

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

    
1615
	/* Remove directory prefix */
1616
	$file_list = str_replace('/usr/share/zoneinfo/', '', $file_list);
1617

    
1618
	sort($file_list);
1619

    
1620
	return $file_list;
1621
}
1622

    
1623
function system_timezone_configure() {
1624
	global $config, $g;
1625
	if (isset($config['system']['developerspew'])) {
1626
		$mt = microtime();
1627
		echo "system_timezone_configure() being called $mt\n";
1628
	}
1629

    
1630
	$syscfg = $config['system'];
1631

    
1632
	if (platform_booting()) {
1633
		echo gettext("Setting timezone...");
1634
	}
1635

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

    
1642
	if (platform_booting()) {
1643
		echo gettext("done.") . "\n";
1644
	}
1645
}
1646

    
1647
function system_ntp_setup_gps($serialport) {
1648
	global $config, $g;
1649
	$gps_device = '/dev/gps0';
1650
	$serialport = '/dev/'.$serialport;
1651

    
1652
	if (!file_exists($serialport)) {
1653
		return false;
1654
	}
1655

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

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

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

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

    
1691
	/* XXX: Why not file_put_contents to the device */
1692
	@file_put_contents('/tmp/gps.init', $gps_init);
1693
	mwexec("cat /tmp/gps.init > {$serialport}");
1694

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

    
1700

    
1701
	return true;
1702
}
1703

    
1704
function system_ntp_setup_pps($serialport) {
1705
	global $config, $g;
1706

    
1707
	$pps_device = '/dev/pps0';
1708
	$serialport = '/dev/'.$serialport;
1709

    
1710
	if (!file_exists($serialport)) {
1711
		return false;
1712
	}
1713

    
1714
	// Create symlink that ntpd requires
1715
	unlink_if_exists($pps_device);
1716
	@symlink($serialport, $pps_device);
1717

    
1718

    
1719
	return true;
1720
}
1721

    
1722

    
1723
function system_ntp_configure() {
1724
	global $config, $g;
1725

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

    
1730
	safe_mkdir($statsdir);
1731

    
1732
	if (!is_array($config['ntpd'])) {
1733
		$config['ntpd'] = array();
1734
	}
1735

    
1736
	$ntpcfg = "# \n";
1737
	$ntpcfg .= "# pfSense ntp configuration file \n";
1738
	$ntpcfg .= "# \n\n";
1739
	$ntpcfg .= "tinker panic 0 \n";
1740

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

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

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

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

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

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

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

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

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

    
2023

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

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

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

    
2055
	/* if ntpd is running, kill it */
2056
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
2057
		killbypid("{$g['varrun_path']}/ntpd.pid");
2058
	}
2059
	@unlink("{$g['varrun_path']}/ntpd.pid");
2060

    
2061
	/* if /var/empty does not exist, create it */
2062
	if (!is_dir("/var/empty")) {
2063
		mkdir("/var/empty", 0555, true);
2064
	}
2065

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

    
2069
	// Note that we are starting up
2070
	log_error("NTPD is starting up.");
2071
	return;
2072
}
2073

    
2074
function system_halt() {
2075
	global $g;
2076

    
2077
	system_reboot_cleanup();
2078

    
2079
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
2080
}
2081

    
2082
function system_reboot() {
2083
	global $g;
2084

    
2085
	system_reboot_cleanup();
2086

    
2087
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
2088
}
2089

    
2090
function system_reboot_sync($reroot=false) {
2091
	global $g;
2092

    
2093
	if ($reroot) {
2094
		$args = " -r ";
2095
	}
2096

    
2097
	system_reboot_cleanup();
2098

    
2099
	mwexec("/etc/rc.reboot {$args} > /dev/null 2>&1");
2100
}
2101

    
2102
function system_reboot_cleanup() {
2103
	global $config, $cpzone, $cpzoneid;
2104

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

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

    
2129
	if ($early) {
2130
		$cmdn = "earlyshellcmd";
2131
	} else {
2132
		$cmdn = "shellcmd";
2133
	}
2134

    
2135
	if (is_array($config['system'][$cmdn])) {
2136

    
2137
		/* *cmd is an array, loop through */
2138
		foreach ($config['system'][$cmdn] as $cmd) {
2139
			exec($cmd);
2140
		}
2141

    
2142
	} elseif ($config['system'][$cmdn] <> "") {
2143

    
2144
		/* execute single item */
2145
		exec($config['system'][$cmdn]);
2146

    
2147
	}
2148
}
2149

    
2150
function system_dmesg_save() {
2151
	global $g;
2152
	if (isset($config['system']['developerspew'])) {
2153
		$mt = microtime();
2154
		echo "system_dmesg_save() being called $mt\n";
2155
	}
2156

    
2157
	$dmesg = "";
2158
	$_gb = exec("/sbin/dmesg", $dmesg);
2159

    
2160
	/* find last copyright line (output from previous boots may be present) */
2161
	$lastcpline = 0;
2162

    
2163
	for ($i = 0; $i < count($dmesg); $i++) {
2164
		if (strstr($dmesg[$i], "Copyright (c) 1992-")) {
2165
			$lastcpline = $i;
2166
		}
2167
	}
2168

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

    
2175
	for ($i = $lastcpline; $i < count($dmesg); $i++) {
2176
		fwrite($fd, $dmesg[$i] . "\n");
2177
	}
2178

    
2179
	fclose($fd);
2180
	unset($dmesg);
2181

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

    
2185
	return 0;
2186
}
2187

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

    
2191
	if (isset($config['system']['developerspew'])) {
2192
		$mt = microtime();
2193
		echo "system_set_harddisk_standby() being called $mt\n";
2194
	}
2195

    
2196
	if (isset($config['system']['harddiskstandby'])) {
2197
		if (platform_booting()) {
2198
			echo gettext('Setting hard disk standby... ');
2199
		}
2200

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

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

    
2227
function system_setup_sysctl() {
2228
	global $config;
2229
	if (isset($config['system']['developerspew'])) {
2230
		$mt = microtime();
2231
		echo "system_setup_sysctl() being called $mt\n";
2232
	}
2233

    
2234
	activate_sysctls();
2235

    
2236
	if (isset($config['system']['sharednet'])) {
2237
		system_disable_arp_wrong_if();
2238
	}
2239
}
2240

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

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

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

    
2284
function system_check_reset_button() {
2285
	global $g;
2286

    
2287
	$specplatform = system_identify_specific_platform();
2288

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

    
2305
	$retval = mwexec("/usr/local/sbin/" . $binprefix . "resetbtn");
2306

    
2307
	if ($retval == 99) {
2308
		/* user has pressed reset button for 2 seconds -
2309
		   reset to factory defaults */
2310
		echo <<<EOD
2311

    
2312
***********************************************************************
2313
* Reset button pressed - resetting configuration to factory defaults. *
2314
* All additional packages installed will be removed                   *
2315
* The system will reboot after this completes.                        *
2316
***********************************************************************
2317

    
2318

    
2319
EOD;
2320

    
2321
		reset_factory_defaults();
2322
		system_reboot_sync();
2323
		exit(0);
2324
	}
2325

    
2326
	return 0;
2327
}
2328

    
2329
function system_get_serial() {
2330
	$platform = system_identify_specific_platform();
2331

    
2332
	unset($output);
2333
	if ($platform['name'] == 'Turbot Dual-E') {
2334
		$if_info = pfSense_get_interface_addresses('igb0');
2335
		if (!empty($if_info['hwaddr'])) {
2336
			$serial = str_replace(":", "", $if_info['hwaddr']);
2337
		}
2338
	} else {
2339
		foreach (array('system', 'planar', 'chassis') as $key) {
2340
			unset($output);
2341
			$_gb = exec("/bin/kenv -q smbios.{$key}.serial",
2342
			    $output);
2343
			if (!empty($output[0]) && $output[0] != "0123456789" &&
2344
			    preg_match('/^[\w\d]{10,16}$/', $output[0]) === 1) {
2345
				$serial = $output[0];
2346
				break;
2347
			}
2348
		}
2349
	}
2350

    
2351
	$vm_guest = get_single_sysctl('kern.vm_guest');
2352

    
2353
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2354
	    $vm_guest == 'none') {
2355
		return $serial;
2356
	}
2357

    
2358
	return "";
2359
}
2360

    
2361
function system_get_uniqueid() {
2362
	global $g;
2363

    
2364
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2365

    
2366
	if (empty($g['uniqueid'])) {
2367
		if (!file_exists($uniqueid_file)) {
2368
			mwexec("/usr/sbin/gnid > {$g['vardb_path']}/uniqueid " .
2369
			    "2>/dev/null");
2370
		}
2371
		if (file_exists($uniqueid_file)) {
2372
			$g['uniqueid'] = @file_get_contents($uniqueid_file);
2373
		}
2374
	}
2375

    
2376
	return ($g['uniqueid'] ?: '');
2377
}
2378

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

    
2388
	$hw_model = get_single_sysctl('hw.model');
2389
	$hw_ncpu = get_single_sysctl('hw.ncpu');
2390

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

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

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

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

    
2484
	if (strpos($hw_model, "PC Engines ALIX") !== false) {
2485
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2486
	}
2487

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

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

    
2496
	if (preg_match("/Soekris net55../", $hw_model, $matches)) {
2497
		return array('name' => 'net55xx', 'descr' => $matches[0]);
2498
	}
2499

    
2500
	unset($hw_model);
2501

    
2502
	$dmesg_boot = system_get_dmesg_boot();
2503
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
2504
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2505
	}
2506
	unset($dmesg_boot);
2507

    
2508
	return array('name' => $g['platform'], 'descr' => $g['platform']);
2509
}
2510

    
2511
function system_get_dmesg_boot() {
2512
	global $g;
2513

    
2514
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2515
}
2516

    
2517
?>
(48-48/60)