Project

General

Profile

Download (71.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-2019 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
	$gateways_arr = return_gateways_array(false, true);
652
	foreach ($gateways_arr as $gateway) {
653
		// setup static interface routes for nonlocal gateways
654
		if (isset($gateway["nonlocalgateway"])) {
655
			$srgatewayip = $gateway['gateway'];
656
			$srinterfacegw = $gateway['interface'];
657
			if (is_ipaddr($srgatewayip) && !empty($srinterfacegw)) {
658
				$inet = (!is_ipaddrv4($srgatewayip) ? "-inet6" : "-inet");
659
				route_add_or_change("{$inet} {$srgatewayip} " .
660
				    "-iface {$srinterfacegw}");
661
			}
662
		}
663
	}
664

    
665
	$gateways_status = return_gateways_status(true);
666
	fixup_default_gateway("inet", $gateways_status, $gateways_arr);
667
	fixup_default_gateway("inet6", $gateways_status, $gateways_arr);
668

    
669
	system_staticroutes_configure($interface, false);
670

    
671
	return 0;
672
}
673

    
674
function system_staticroutes_configure($interface = "", $update_dns = false) {
675
	global $config, $g, $aliastable;
676

    
677
	$filterdns_list = array();
678

    
679
	$static_routes = get_staticroutes(false, true);
680
	if (count($static_routes)) {
681
		$gateways_arr = return_gateways_array(false, true);
682

    
683
		foreach ($static_routes as $rtent) {
684
			if (empty($gateways_arr[$rtent['gateway']])) {
685
				log_error(sprintf(gettext("Static Routes: Gateway IP could not be found for %s"), $rtent['network']));
686
				continue;
687
			}
688
			$gateway = $gateways_arr[$rtent['gateway']];
689
			if (!empty($interface) && $interface != $gateway['friendlyiface']) {
690
				continue;
691
			}
692

    
693
			$gatewayip = $gateway['gateway'];
694
			$interfacegw = $gateway['interface'];
695

    
696
			$blackhole = "";
697
			if (!strcasecmp("Null", substr($rtent['gateway'], 0, 4))) {
698
				$blackhole = "-blackhole";
699
			}
700

    
701
			if (!is_fqdn($rtent['network']) && !is_subnet($rtent['network'])) {
702
				continue;
703
			}
704

    
705
			$dnscache = array();
706
			if ($update_dns === true) {
707
				if (is_subnet($rtent['network'])) {
708
					continue;
709
				}
710
				$dnscache = explode("\n", trim(compare_hostname_to_dnscache($rtent['network'])));
711
				if (empty($dnscache)) {
712
					continue;
713
				}
714
			}
715

    
716
			if (is_subnet($rtent['network'])) {
717
				$ips = array($rtent['network']);
718
			} else {
719
				if (!isset($rtent['disabled'])) {
720
					$filterdns_list[] = $rtent['network'];
721
				}
722
				$ips = add_hostname_to_watch($rtent['network']);
723
			}
724

    
725
			foreach ($dnscache as $ip) {
726
				if (in_array($ip, $ips)) {
727
					continue;
728
				}
729
				mwexec("/sbin/route delete " . escapeshellarg($ip), true);
730
				if (isset($config['system']['route-debug'])) {
731
					$mt = microtime();
732
					log_error("ROUTING debug: $mt - route delete $ip ");
733
				}
734
			}
735

    
736
			if (isset($rtent['disabled'])) {
737
				/* XXX: This can break things by deleting routes that shouldn't be deleted - OpenVPN, dynamic routing scenarios, etc. redmine #3709 */
738
				foreach ($ips as $ip) {
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
				continue;
746
			}
747

    
748
			foreach ($ips as $ip) {
749
				if (is_ipaddrv4($ip)) {
750
					$ip .= "/32";
751
				}
752
				// do NOT do the same check here on v6, is_ipaddrv6 returns true when including the CIDR mask. doing so breaks v6 routes
753

    
754
				$inet = (is_subnetv6($ip) ? "-inet6" : "-inet");
755

    
756
				$cmd = "{$inet} {$blackhole} {$ip} ";
757

    
758
				if (is_subnet($ip)) {
759
					if (is_ipaddr($gatewayip)) {
760
						if (is_linklocal($gatewayip) == "6" && !strpos($gatewayip, '%')) {
761
							// add interface scope for link local v6 routes
762
							$gatewayip .= "%$interfacegw";
763
						}
764
						route_add_or_change($cmd . $gatewayip);
765
					} else if (!empty($interfacegw)) {
766
						route_add_or_change($cmd . "-iface {$interfacegw}");
767
					}
768
				}
769
			}
770
		}
771
		unset($gateways_arr);
772
	}
773
	unset($static_routes);
774

    
775
	if ($update_dns === false) {
776
		if (count($filterdns_list)) {
777
			$interval = 60;
778
			$hostnames = "";
779
			array_unique($filterdns_list);
780
			foreach ($filterdns_list as $hostname) {
781
				$hostnames .= "cmd {$hostname} '/usr/local/sbin/pfSctl -c \"service reload routedns\"'\n";
782
			}
783
			file_put_contents("{$g['varetc_path']}/filterdns-route.hosts", $hostnames);
784
			unset($hostnames);
785

    
786
			if (isvalidpid("{$g['varrun_path']}/filterdns-route.pid")) {
787
				sigkillbypid("{$g['varrun_path']}/filterdns-route.pid", "HUP");
788
			} else {
789
				mwexec("/usr/local/sbin/filterdns -p {$g['varrun_path']}/filterdns-route.pid -i {$interval} -c {$g['varetc_path']}/filterdns-route.hosts -d 1");
790
			}
791
		} else {
792
			killbypid("{$g['varrun_path']}/filterdns-route.pid");
793
			@unlink("{$g['varrun_path']}/filterdns-route.pid");
794
		}
795
	}
796
	unset($filterdns_list);
797

    
798
	return 0;
799
}
800

    
801
function system_routing_enable() {
802
	global $config, $g;
803
	if (isset($config['system']['developerspew'])) {
804
		$mt = microtime();
805
		echo "system_routing_enable() being called $mt\n";
806
	}
807

    
808
	set_sysctl(array(
809
		"net.inet.ip.forwarding" => "1",
810
		"net.inet6.ip6.forwarding" => "1"
811
	));
812

    
813
	return;
814
}
815

    
816
function system_syslogd_fixup_server($server) {
817
	/* If it's an IPv6 IP alone, encase it in brackets */
818
	if (is_ipaddrv6($server)) {
819
		return "[$server]";
820
	} else {
821
		return $server;
822
	}
823
}
824

    
825
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
826
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
827
	$facility .= " ".
828
	$remote_servers = "";
829
	$pad_to  = max(strlen($facility), 56);
830
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
831
	if (isset($syslogcfg['enable'])) {
832
		if ($syslogcfg['remoteserver']) {
833
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
834
		}
835
		if ($syslogcfg['remoteserver2']) {
836
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
837
		}
838
		if ($syslogcfg['remoteserver3']) {
839
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
840
		}
841
	}
842
	return $remote_servers;
843
}
844

    
845
function clear_log_file($logfile = "/var/log/system.log", $restart_syslogd = true) {
846
	global $config, $g;
847

    
848
	if ($restart_syslogd) {
849
		/* syslogd does not react well to clog rewriting the file while it is running. */
850
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
851
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
852
		}
853
	}
854
	if (isset($config['system']['disablesyslogclog'])) {
855
		unlink($logfile);
856
		touch($logfile);
857
	} else {
858
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "511488";
859
		$log_size = ($log_size < (2**32)/2) ? $log_size : "511488";
860
		$log_size = isset($config['syslog'][basename($logfile, '.log') . '_settings']['logfilesize']) ? $config['syslog'][basename($logfile, '.log') . '_settings']['logfilesize'] : $log_size;
861
		exec("/usr/local/sbin/clog -i -s {$log_size} " . escapeshellarg($logfile));
862
	}
863
	if ($restart_syslogd) {
864
		system_syslogd_start();
865
	}
866
	// Bug #6915
867
	if ($logfile == "/var/log/resolver.log") {
868
		services_unbound_configure(true);
869
	}
870
}
871

    
872
function clear_all_log_files($restart = false) {
873
	global $g;
874
	if ($restart) {
875
		/* syslogd does not react well to clog rewriting the file while it is running. */
876
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
877
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
878
		}
879
	}
880

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

    
886
	if ($restart) {
887
		system_syslogd_start();
888
		killbyname("dhcpd");
889
		if (!function_exists('services_dhcpd_configure')) {
890
			require_once('services.inc');
891
		}
892
		services_dhcpd_configure();
893
		// Bug #6915
894
		services_unbound_configure(false);
895
	}
896
	return;
897
}
898

    
899
function system_syslogd_start($sighup = false) {
900
	global $config, $g;
901
	if (isset($config['system']['developerspew'])) {
902
		$mt = microtime();
903
		echo "system_syslogd_start() being called $mt\n";
904
	}
905

    
906
	mwexec("/etc/rc.d/hostid start");
907

    
908
	$syslogcfg = $config['syslog'];
909

    
910
	if (platform_booting()) {
911
		echo gettext("Starting syslog...");
912
	}
913

    
914
	// Which logging type are we using this week??
915
	if (isset($config['system']['disablesyslogclog'])) {
916
		$log_directive = "";
917
		$log_create_directive = "/usr/bin/touch ";
918
		$log_size = "";
919
	} else { // Defaults to CLOG
920
		$log_directive = "%";
921
		$log_size = isset($config['syslog']['logfilesize']) ? $config['syslog']['logfilesize'] : "10240";
922
		$log_create_directive = "/usr/local/sbin/clog -i -s ";
923
	}
924

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

    
949
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
950
		if (!isset($syslogcfg['disablelocallogging'])) {
951
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/ntpd.log\n";
952
		}
953
		if (isset($syslogcfg['ntpd'])) {
954
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
955
		}
956

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

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

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

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

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

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

    
1005
		$syslogconf .= "!dnsmasq,named,filterdns,unbound\n";
1006
		if (!isset($syslogcfg['disablelocallogging'])) {
1007
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/resolver.log\n";
1008
		}
1009
		if (isset($syslogcfg['resolver'])) {
1010
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1011
		}
1012

    
1013
		$syslogconf .= "!dhcpd,dhcrelay,dhclient,dhcp6c,dhcpleases,dhcpleases6\n";
1014
		if (!isset($syslogcfg['disablelocallogging'])) {
1015
			$syslogconf .= "*.*								{$log_directive}{$g['varlog_path']}/dhcpd.log\n";
1016
		}
1017
		if (isset($syslogcfg['dhcp'])) {
1018
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1019
		}
1020

    
1021
		$syslogconf .= "!relayd\n";
1022
		if (!isset($syslogcfg['disablelocallogging'])) {
1023
			$syslogconf .= "*.* 								{$log_directive}{$g['varlog_path']}/relayd.log\n";
1024
		}
1025
		if (isset($syslogcfg['relayd'])) {
1026
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1027
		}
1028

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

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

    
1045
		$syslogconf .= "!-{$facilitylist}\n";
1046
		if (!isset($syslogcfg['disablelocallogging'])) {
1047
			$syslogconf .= <<<EOD
1048
local3.*							{$log_directive}{$g['varlog_path']}/vpn.log
1049
local4.*							{$log_directive}{$g['varlog_path']}/portalauth.log
1050
local5.*							{$log_directive}{$g['varlog_path']}/nginx.log
1051
local7.*							{$log_directive}{$g['varlog_path']}/dhcpd.log
1052
*.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
1053
auth.info;authpriv.info 					|exec /usr/local/sbin/sshguard
1054
*.emerg								*
1055

    
1056
EOD;
1057
		}
1058
		if (isset($syslogcfg['vpn'])) {
1059
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
1060
		}
1061
		if (isset($syslogcfg['portalauth'])) {
1062
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local4.*");
1063
		}
1064
		if (isset($syslogcfg['dhcp'])) {
1065
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local7.*");
1066
		}
1067
		if (isset($syslogcfg['system'])) {
1068
			$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");
1069
		}
1070
		if (isset($syslogcfg['logall'])) {
1071
			// Make everything mean everything, including facilities excluded above.
1072
			$syslogconf .= "!*\n";
1073
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
1074
		}
1075

    
1076
		if (isset($syslogcfg['zmqserver'])) {
1077
				$syslogconf .= <<<EOD
1078
*.*								^{$syslogcfg['zmqserver']}
1079

    
1080
EOD;
1081
		}
1082
		/* write syslog.conf */
1083
		if (!@file_put_contents("{$g['etc_path']}/syslog.conf", $syslogconf)) {
1084
			printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
1085
			unset($syslogconf);
1086
			return 1;
1087
		}
1088
		unset($syslogconf);
1089

    
1090
		$sourceip = "";
1091
		if (!empty($syslogcfg['sourceip'])) {
1092
			if ($syslogcfg['ipproto'] == "ipv6") {
1093
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
1094
				if (!is_ipaddr($ifaddr)) {
1095
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
1096
				}
1097
			} else {
1098
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
1099
				if (!is_ipaddr($ifaddr)) {
1100
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
1101
				}
1102
			}
1103
			if (is_ipaddr($ifaddr)) {
1104
				$sourceip = "-b {$ifaddr}";
1105
			}
1106
		}
1107

    
1108
		$syslogd_extra = "-f {$g['etc_path']}/syslog.conf {$sourceip}";
1109
	}
1110

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

    
1113
	if (isset($config['installedpackages']['package'])) {
1114
		foreach ($config['installedpackages']['package'] as $package) {
1115
			if (isset($package['logging']['logsocket']) && $package['logging']['logsocket'] != '' &&
1116
			    !in_array($package['logging']['logsocket'], $log_sockets)) {
1117
				$log_sockets[] = $package['logging']['logsocket'];
1118
			}
1119
		}
1120
	}
1121

    
1122
	$syslogd_sockets = "";
1123
	foreach ($log_sockets as $log_socket) {
1124
		// Ensure that the log directory exists
1125
		$logpath = dirname($log_socket);
1126
		safe_mkdir($logpath);
1127
		$syslogd_sockets .= " -l {$log_socket}";
1128
	}
1129

    
1130
	/* If HUP was requested, but syslogd is not running, restart it instead. */
1131
	if ($sighup && !isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1132
		$sighup = false;
1133
	}
1134

    
1135
	$sshguard_whitelist = array();
1136
	if (!empty($config['system']['sshguard_whitelist'])) {
1137
		$sshguard_whitelist = explode(' ',
1138
		    $config['system']['sshguard_whitelist']);
1139
	}
1140

    
1141
	$sshguard_config = array();
1142
	$sshguard_config[] = 'BACKEND="/usr/local/libexec/sshg-fw-pf"' . "\n";
1143
	if (!empty($config['system']['sshguard_threshold'])) {
1144
		$sshguard_config[] = 'THRESHOLD=' .
1145
		    $config['system']['sshguard_threshold'] . "\n";
1146
	}
1147
	if (!empty($config['system']['sshguard_blocktime'])) {
1148
		$sshguard_config[] = 'BLOCK_TIME=' .
1149
		    $config['system']['sshguard_blocktime'] . "\n";
1150
	}
1151
	if (!empty($config['system']['sshguard_detection_time'])) {
1152
		$sshguard_config[] = 'DETECTION_TIME=' .
1153
		    $config['system']['sshguard_detection_time'] . "\n";
1154
	}
1155
	if (!empty($sshguard_whitelist)) {
1156
		@file_put_contents("/usr/local/etc/sshguard.whitelist",
1157
		    implode(PHP_EOL, $sshguard_whitelist));
1158
		$sshguard_config[] =
1159
		    'WHITELIST_FILE=/usr/local/etc/sshguard.whitelist' . "\n";
1160
	} else {
1161
		unlink_if_exists("/usr/local/etc/sshguard.whitelist");
1162
	}
1163
	file_put_contents("/usr/local/etc/sshguard.conf", $sshguard_config);
1164

    
1165
	if (!$sighup) {
1166
		sigkillbyname("sshguard", "TERM");
1167
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1168
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "TERM");
1169
			usleep(100000); // syslogd often doesn't respond to a TERM quickly enough for the starting of syslogd below to be successful
1170
		}
1171

    
1172
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
1173
			// if it still hasn't responded to the TERM, KILL it.
1174
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
1175
			usleep(100000);
1176
		}
1177

    
1178
		$retval = mwexec_bg("/usr/sbin/syslogd -s -c -c {$syslogd_sockets} -P {$g['varrun_path']}/syslog.pid {$syslogd_extra}");
1179
	} else {
1180
		$retval = sigkillbypid("{$g['varrun_path']}/syslog.pid", "HUP");
1181
	}
1182

    
1183
	if (platform_booting()) {
1184
		echo gettext("done.") . "\n";
1185
	}
1186

    
1187
	return $retval;
1188
}
1189

    
1190
function system_webgui_create_certificate() {
1191
	global $config, $g;
1192

    
1193
	init_config_arr(array('ca'));
1194
	$a_ca = &$config['ca'];
1195
	init_config_arr(array('cert'));
1196
	$a_cert = &$config['cert'];
1197
	log_error(gettext("Creating SSL Certificate for this host"));
1198

    
1199
	$cert = array();
1200
	$cert['refid'] = uniqid();
1201
	$cert['descr'] = sprintf(gettext("webConfigurator default (%s)"), $cert['refid']);
1202
	$cert_hostname = "{$config['system']['hostname']}-{$cert['refid']}";
1203

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

    
1218
	$a_cert[] = $cert;
1219
	$config['system']['webgui']['ssl-certref'] = $cert['refid'];
1220
	write_config(sprintf(gettext("Generated new self-signed HTTPS certificate (%s)"), $cert['refid']));
1221
	return $cert;
1222
}
1223

    
1224
function system_webgui_start() {
1225
	global $config, $g;
1226

    
1227
	if (platform_booting()) {
1228
		echo gettext("Starting webConfigurator...");
1229
	}
1230

    
1231
	chdir($g['www_path']);
1232

    
1233
	/* defaults */
1234
	$portarg = "80";
1235
	$crt = "";
1236
	$key = "";
1237
	$ca = "";
1238

    
1239
	/* non-standard port? */
1240
	if (isset($config['system']['webgui']['port']) && $config['system']['webgui']['port'] <> "") {
1241
		$portarg = "{$config['system']['webgui']['port']}";
1242
	}
1243

    
1244
	if ($config['system']['webgui']['protocol'] == "https") {
1245
		// Ensure that we have a webConfigurator CERT
1246
		$cert =& lookup_cert($config['system']['webgui']['ssl-certref']);
1247
		if (!is_array($cert) || !$cert['crt'] || !$cert['prv']) {
1248
			$cert = system_webgui_create_certificate();
1249
		}
1250
		$crt = base64_decode($cert['crt']);
1251
		$key = base64_decode($cert['prv']);
1252

    
1253
		if (!$config['system']['webgui']['port']) {
1254
			$portarg = "443";
1255
		}
1256
		$ca = ca_chain($cert);
1257
		$hsts = isset($config['system']['webgui']['disablehsts']) ? false : true;
1258
	}
1259

    
1260
	/* generate nginx configuration */
1261
	system_generate_nginx_config("{$g['varetc_path']}/nginx-webConfigurator.conf",
1262
		$crt, $key, $ca, "nginx-webConfigurator.pid", $portarg, "/usr/local/www/",
1263
		"cert.crt", "cert.key", false, $hsts);
1264

    
1265
	/* kill any running nginx */
1266
	killbypid("{$g['varrun_path']}/nginx-webConfigurator.pid");
1267

    
1268
	sleep(1);
1269

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

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

    
1275
	if (platform_booting()) {
1276
		if ($res == 0) {
1277
			echo gettext("done.") . "\n";
1278
		} else {
1279
			echo gettext("failed!") . "\n";
1280
		}
1281
	}
1282

    
1283
	return $res;
1284
}
1285

    
1286
function get_dns_nameservers($add_v6_brackets = false) {
1287
	global $config;
1288

    
1289
	$dns_nameservers = array();
1290

    
1291
	if (isset($config['system']['developerspew'])) {
1292
		$mt = microtime();
1293
		echo "get_dns_nameservers() being called $mt\n";
1294
	}
1295

    
1296
	$syscfg = $config['system'];
1297
	if ((((isset($config['dnsmasq']['enable'])) &&
1298
   		(empty($config['dnsmasq']['port']) || $config['dnsmasq']['port'] == "53") &&
1299
	      	(empty($config['dnsmasq']['interface']) ||
1300
	       	in_array("lo0", explode(",", $config['dnsmasq']['interface'])))) ||
1301
	     	((isset($config['unbound']['enable'])) &&
1302
	      	(empty($config['unbound']['port']) || $config['unbound']['port'] == "53") &&
1303
	      	(empty($config['unbound']['active_interface']) ||
1304
	       	in_array("lo0", explode(",", $config['unbound']['active_interface'])) ||
1305
	       	in_array("all", explode(",", $config['unbound']['active_interface']), true)))) &&
1306
	     	(!isset($config['system']['dnslocalhost']))) {
1307
			$dns_nameservers[] = "127.0.0.1";
1308
	}
1309
	/* get dynamically assigned DNS servers (if any) */
1310
	$ns = array_unique(get_nameservers());
1311
	if (isset($syscfg['dnsallowoverride'])) {
1312
		if(!is_array($ns)) {
1313
			$ns = array();
1314
		}
1315
		foreach ($ns as $nameserver) {
1316
			if ($nameserver) {
1317
				if ($add_v6_brackets && is_ipaddrv6($nameserver)) {
1318
					$nameserver = "[{$nameserver}]";
1319
				}
1320
				$dns_nameservers[] = $nameserver;
1321
			}
1322
		}
1323
	}
1324
	if (is_array($syscfg['dnsserver'])) {
1325
		foreach ($syscfg['dnsserver'] as $sys_dnsserver) {
1326
			if ($sys_dnsserver && (!in_array($sys_dnsserver, $ns))) {
1327
				if ($add_v6_brackets && is_ipaddrv6($sys_dnsserver)) {
1328
					$sys_dnsserver = "[{$sys_dnsserver}]";
1329
				}
1330
				$dns_nameservers[] = $sys_dnsserver;
1331
			}
1332
		}
1333
	}
1334
	return array_unique($dns_nameservers);
1335
}
1336

    
1337
function system_generate_nginx_config($filename,
1338
	$cert,
1339
	$key,
1340
	$ca,
1341
	$pid_file,
1342
	$port = 80,
1343
	$document_root = "/usr/local/www/",
1344
	$cert_location = "cert.crt",
1345
	$key_location = "cert.key",
1346
	$captive_portal = false,
1347
	$hsts = true) {
1348

    
1349
	global $config, $g;
1350

    
1351
	if (isset($config['system']['developerspew'])) {
1352
		$mt = microtime();
1353
		echo "system_generate_nginx_config() being called $mt\n";
1354
	}
1355

    
1356
	if ($captive_portal !== false) {
1357
		$cp_interfaces = explode(",", $config['captiveportal'][$captive_portal]['interface']);
1358
		$cp_hostcheck = "";
1359
		foreach ($cp_interfaces as $cpint) {
1360
			$cpint_ip = get_interface_ip($cpint);
1361
			if (is_ipaddr($cpint_ip)) {
1362
				$cp_hostcheck .= "\t\tif (\$http_host ~* $cpint_ip) {\n";
1363
				$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1364
				$cp_hostcheck .= "\t\t}\n";
1365
			}
1366
		}
1367
		if (isset($config['captiveportal'][$captive_portal]['httpsname']) &&
1368
		    is_domain($config['captiveportal'][$captive_portal]['httpsname'])) {
1369
			$cp_hostcheck .= "\t\tif (\$http_host ~* {$config['captiveportal'][$captive_portal]['httpsname']}) {\n";
1370
			$cp_hostcheck .= "\t\t\tset \$cp_redirect no;\n";
1371
			$cp_hostcheck .= "\t\t}\n";
1372
		}
1373
		$cp_rewrite = "\t\tif (\$cp_redirect = '') {\n";
1374
		$cp_rewrite .= "\t\t\trewrite	^ /index.php?zone=$captive_portal&redirurl=\$request_uri break;\n";
1375
		$cp_rewrite .= "\t\t}\n";
1376

    
1377
		$maxprocperip = $config['captiveportal'][$captive_portal]['maxprocperip'];
1378
		if (empty($maxprocperip)) {
1379
			$maxprocperip = 10;
1380
		}
1381
		$captive_portal_maxprocperip = "\t\tlimit_conn addr $maxprocperip;\n";
1382
	}
1383

    
1384
	if (empty($port)) {
1385
		$nginx_port = "80";
1386
	} else {
1387
		$nginx_port = $port;
1388
	}
1389

    
1390
	$memory = get_memory();
1391
	$realmem = $memory[1];
1392

    
1393
	// Determine web GUI process settings and take into account low memory systems
1394
	if ($realmem < 255) {
1395
		$max_procs = 1;
1396
	} else {
1397
		$max_procs = ($config['system']['webgui']['max_procs']) ? $config['system']['webgui']['max_procs'] : 2;
1398
	}
1399

    
1400
	// Ramp up captive portal max procs, assuming each PHP process can consume up to 64MB RAM
1401
	if ($captive_portal !== false) {
1402
		if ($realmem > 135 and $realmem < 256) {
1403
			$max_procs += 1; // 2 worker processes
1404
		} else if ($realmem > 255 and $realmem < 513) {
1405
			$max_procs += 2; // 3 worker processes
1406
		} else if ($realmem > 512) {
1407
			$max_procs += 4; // 6 worker processes
1408
		}
1409
	}
1410

    
1411
	$nginx_config = <<<EOD
1412
#
1413
# nginx configuration file
1414

    
1415
pid {$g['varrun_path']}/{$pid_file};
1416

    
1417
user  root wheel;
1418
worker_processes  {$max_procs};
1419

    
1420
EOD;
1421

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

    
1426
	$nginx_config .= <<<EOD
1427

    
1428
events {
1429
    worker_connections  1024;
1430
}
1431

    
1432
http {
1433
	include       /usr/local/etc/nginx/mime.types;
1434
	default_type  application/octet-stream;
1435
	add_header X-Frame-Options SAMEORIGIN;
1436
	server_tokens off;
1437

    
1438
	sendfile        on;
1439

    
1440
	access_log      syslog:server=unix:/var/run/log,facility=local5 combined;
1441

    
1442
EOD;
1443

    
1444
	if ($captive_portal !== false) {
1445
		$nginx_config .= "\tlimit_conn_zone \$binary_remote_addr zone=addr:10m;\n";
1446
		$nginx_config .= "\tkeepalive_timeout 0;\n";
1447
	} else {
1448
		$nginx_config .= "\tkeepalive_timeout 75;\n";
1449
	}
1450

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

    
1491
	$nginx_config .= <<<EOD
1492

    
1493
		client_max_body_size 200m;
1494

    
1495
		gzip on;
1496
		gzip_types text/plain text/css text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
1497

    
1498

    
1499
EOD;
1500

    
1501
	if ($captive_portal !== false) {
1502
		$nginx_config .= <<<EOD
1503
$captive_portal_maxprocperip
1504
$cp_hostcheck
1505
$cp_rewrite
1506
		log_not_found off;
1507

    
1508
EOD;
1509

    
1510
	}
1511

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

    
1546
EOD;
1547

    
1548
	$cert = str_replace("\r", "", $cert);
1549
	$key = str_replace("\r", "", $key);
1550

    
1551
	$cert = str_replace("\n\n", "\n", $cert);
1552
	$key = str_replace("\n\n", "\n", $key);
1553

    
1554
	if ($cert <> "" and $key <> "") {
1555
		$fd = fopen("{$g['varetc_path']}/{$cert_location}", "w");
1556
		if (!$fd) {
1557
			printf(gettext("Error: cannot open certificate file in system_webgui_start().%s"), "\n");
1558
			return 1;
1559
		}
1560
		chmod("{$g['varetc_path']}/{$cert_location}", 0644);
1561
		if ($ca <> "") {
1562
			$cert_chain = $cert . "\n" . $ca;
1563
		} else {
1564
			$cert_chain = $cert;
1565
		}
1566
		fwrite($fd, $cert_chain);
1567
		fclose($fd);
1568
		$fd = fopen("{$g['varetc_path']}/{$key_location}", "w");
1569
		if (!$fd) {
1570
			printf(gettext("Error: cannot open certificate key file in system_webgui_start().%s"), "\n");
1571
			return 1;
1572
		}
1573
		chmod("{$g['varetc_path']}/{$key_location}", 0600);
1574
		fwrite($fd, $key);
1575
		fclose($fd);
1576
	}
1577

    
1578
	// Add HTTP to HTTPS redirect
1579
	if ($captive_portal === false && $config['system']['webgui']['protocol'] == "https" && !isset($config['system']['webgui']['disablehttpredirect'])) {
1580
		if ($nginx_port != "443") {
1581
			$redirectport = ":{$nginx_port}";
1582
		}
1583
		$nginx_config .= <<<EOD
1584
	server {
1585
		listen 80;
1586
		listen [::]:80;
1587
		return 301 https://\$http_host$redirectport\$request_uri;
1588
	}
1589

    
1590
EOD;
1591
	}
1592

    
1593
	$nginx_config .= "}\n";
1594

    
1595
	$fd = fopen("{$filename}", "w");
1596
	if (!$fd) {
1597
		printf(gettext('Error: cannot open %1$s in system_generate_nginx_config().%2$s'), $filename, "\n");
1598
		return 1;
1599
	}
1600
	fwrite($fd, $nginx_config);
1601
	fclose($fd);
1602

    
1603
	/* nginx will fail to start if this directory does not exist. */
1604
	safe_mkdir("/var/tmp/nginx/");
1605

    
1606
	return 0;
1607

    
1608
}
1609

    
1610
function system_get_timezone_list() {
1611
	global $g;
1612

    
1613
	$file_list = array_merge(
1614
		glob("/usr/share/zoneinfo/[A-Z]*"),
1615
		glob("/usr/share/zoneinfo/*/*"),
1616
		glob("/usr/share/zoneinfo/*/*/*")
1617
	);
1618

    
1619
	if (empty($file_list)) {
1620
		$file_list[] = $g['default_timezone'];
1621
	} else {
1622
		/* Remove directories from list */
1623
		$file_list = array_filter($file_list, function($v) {
1624
			return !is_dir($v);
1625
		});
1626
	}
1627

    
1628
	/* Remove directory prefix */
1629
	$file_list = str_replace('/usr/share/zoneinfo/', '', $file_list);
1630

    
1631
	sort($file_list);
1632

    
1633
	return $file_list;
1634
}
1635

    
1636
function system_timezone_configure() {
1637
	global $config, $g;
1638
	if (isset($config['system']['developerspew'])) {
1639
		$mt = microtime();
1640
		echo "system_timezone_configure() being called $mt\n";
1641
	}
1642

    
1643
	$syscfg = $config['system'];
1644

    
1645
	if (platform_booting()) {
1646
		echo gettext("Setting timezone...");
1647
	}
1648

    
1649
	/* extract appropriate timezone file */
1650
	$timezone = (isset($syscfg['timezone']) ? $syscfg['timezone'] : $g['default_timezone']);
1651
	/* DO NOT remove \n otherwise tzsetup will fail */
1652
	@file_put_contents("/var/db/zoneinfo", $timezone . "\n");
1653
	mwexec("/usr/sbin/tzsetup -r");
1654

    
1655
	if (platform_booting()) {
1656
		echo gettext("done.") . "\n";
1657
	}
1658
}
1659

    
1660
function system_ntp_setup_gps($serialport) {
1661
	global $config, $g;
1662
	$gps_device = '/dev/gps0';
1663
	$serialport = '/dev/'.$serialport;
1664

    
1665
	if (!file_exists($serialport)) {
1666
		return false;
1667
	}
1668

    
1669
	// Create symlink that ntpd requires
1670
	unlink_if_exists($gps_device);
1671
	@symlink($serialport, $gps_device);
1672

    
1673
	$gpsbaud = '4800';
1674
	if (is_array($config['ntpd']) && is_array($config['ntpd']['gps']) && !empty($config['ntpd']['gps']['speed'])) {
1675
		switch ($config['ntpd']['gps']['speed']) {
1676
			case '16':
1677
				$gpsbaud = '9600';
1678
				break;
1679
			case '32':
1680
				$gpsbaud = '19200';
1681
				break;
1682
			case '48':
1683
				$gpsbaud = '38400';
1684
				break;
1685
			case '64':
1686
				$gpsbaud = '57600';
1687
				break;
1688
			case '80':
1689
				$gpsbaud = '115200';
1690
				break;
1691
		}
1692
	}
1693

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

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

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

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

    
1713

    
1714
	return true;
1715
}
1716

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

    
1720
	$pps_device = '/dev/pps0';
1721
	$serialport = '/dev/'.$serialport;
1722

    
1723
	if (!file_exists($serialport)) {
1724
		return false;
1725
	}
1726

    
1727
	// Create symlink that ntpd requires
1728
	unlink_if_exists($pps_device);
1729
	@symlink($serialport, $pps_device);
1730

    
1731

    
1732
	return true;
1733
}
1734

    
1735

    
1736
function system_ntp_configure() {
1737
	global $config, $g;
1738

    
1739
	$driftfile = "/var/db/ntpd.drift";
1740
	$statsdir = "/var/log/ntp";
1741
	$gps_device = '/dev/gps0';
1742

    
1743
	safe_mkdir($statsdir);
1744

    
1745
	if (!is_array($config['ntpd'])) {
1746
		$config['ntpd'] = array();
1747
	}
1748

    
1749
	$ntpcfg = "# \n";
1750
	$ntpcfg .= "# pfSense ntp configuration file \n";
1751
	$ntpcfg .= "# \n\n";
1752
	$ntpcfg .= "tinker panic 0 \n";
1753

    
1754
	/* Add Orphan mode */
1755
	$ntpcfg .= "# Orphan mode stratum\n";
1756
	$ntpcfg .= 'tos orphan ';
1757
	if (!empty($config['ntpd']['orphan'])) {
1758
		$ntpcfg .= $config['ntpd']['orphan'];
1759
	} else {
1760
		$ntpcfg .= '12';
1761
	}
1762
	$ntpcfg .= "\n";
1763

    
1764
	/* Add PPS configuration */
1765
	if (is_array($config['ntpd']['pps']) && !empty($config['ntpd']['pps']['port']) &&
1766
	    file_exists('/dev/'.$config['ntpd']['pps']['port']) &&
1767
	    system_ntp_setup_pps($config['ntpd']['pps']['port'])) {
1768
		$ntpcfg .= "\n";
1769
		$ntpcfg .= "# PPS Setup\n";
1770
		$ntpcfg .= 'server 127.127.22.0';
1771
		$ntpcfg .= ' minpoll 4 maxpoll 4';
1772
		if (empty($config['ntpd']['pps']['prefer'])) { /*note: this one works backwards */
1773
			$ntpcfg .= ' prefer';
1774
		}
1775
		if (!empty($config['ntpd']['pps']['noselect'])) {
1776
			$ntpcfg .= ' noselect ';
1777
		}
1778
		$ntpcfg .= "\n";
1779
		$ntpcfg .= 'fudge 127.127.22.0';
1780
		if (!empty($config['ntpd']['pps']['fudge1'])) {
1781
			$ntpcfg .= ' time1 ';
1782
			$ntpcfg .= $config['ntpd']['pps']['fudge1'];
1783
		}
1784
		if (!empty($config['ntpd']['pps']['flag2'])) {
1785
			$ntpcfg .= ' flag2 1';
1786
		}
1787
		if (!empty($config['ntpd']['pps']['flag3'])) {
1788
			$ntpcfg .= ' flag3 1';
1789
		} else {
1790
			$ntpcfg .= ' flag3 0';
1791
		}
1792
		if (!empty($config['ntpd']['pps']['flag4'])) {
1793
			$ntpcfg .= ' flag4 1';
1794
		}
1795
		if (!empty($config['ntpd']['pps']['refid'])) {
1796
			$ntpcfg .= ' refid ';
1797
			$ntpcfg .= $config['ntpd']['pps']['refid'];
1798
		}
1799
		$ntpcfg .= "\n";
1800
	}
1801
	/* End PPS configuration */
1802

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

    
1894
		$ntpcfg .= "{$ts} iburst maxpoll 9";
1895
		if (substr_count($config['ntpd']['prefer'], $ts)) {
1896
			$ntpcfg .= ' prefer';
1897
		}
1898
		if (substr_count($config['ntpd']['noselect'], $ts)) {
1899
			$ntpcfg .= ' noselect';
1900
		}
1901
		$ntpcfg .= "\n";
1902
	}
1903
	unset($ts);
1904

    
1905
	$ntpcfg .= "\n\n";
1906
	if (!empty($config['ntpd']['clockstats']) || !empty($config['ntpd']['loopstats']) || !empty($config['ntpd']['peerstats'])) {
1907
		$ntpcfg .= "enable stats\n";
1908
		$ntpcfg .= 'statistics';
1909
		if (!empty($config['ntpd']['clockstats'])) {
1910
			$ntpcfg .= ' clockstats';
1911
		}
1912
		if (!empty($config['ntpd']['loopstats'])) {
1913
			$ntpcfg .= ' loopstats';
1914
		}
1915
		if (!empty($config['ntpd']['peerstats'])) {
1916
			$ntpcfg .= ' peerstats';
1917
		}
1918
		$ntpcfg .= "\n";
1919
	}
1920
	$ntpcfg .= "statsdir {$statsdir}\n";
1921
	$ntpcfg .= 'logconfig =syncall +clockall';
1922
	if (!empty($config['ntpd']['logpeer'])) {
1923
		$ntpcfg .= ' +peerall';
1924
	}
1925
	if (!empty($config['ntpd']['logsys'])) {
1926
		$ntpcfg .= ' +sysall';
1927
	}
1928
	$ntpcfg .= "\n";
1929
	$ntpcfg .= "driftfile {$driftfile}\n";
1930

    
1931
	/* Default Access restrictions */
1932
	$ntpcfg .= 'restrict 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']['notrap'])) { /*note: this one works backwards */
1946
		$ntpcfg .= ' notrap';
1947
	}
1948
	if (!empty($config['ntpd']['noserve'])) {
1949
		$ntpcfg .= ' noserve';
1950
	}
1951
	$ntpcfg .= "\nrestrict -6 default";
1952
	if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1953
		$ntpcfg .= ' kod limited';
1954
	}
1955
	if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1956
		$ntpcfg .= ' nomodify';
1957
	}
1958
	if (!empty($config['ntpd']['noquery'])) {
1959
		$ntpcfg .= ' noquery';
1960
	}
1961
	if (empty($config['ntpd']['nopeer'])) { /*note: this one works backwards */
1962
		$ntpcfg .= ' nopeer';
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
	/* Pools require "restrict source" and cannot contain "nopeer". */
1972
	if ($have_pools) {
1973
		$ntpcfg .= "\nrestrict source";
1974
		if (empty($config['ntpd']['kod'])) { /*note: this one works backwards */
1975
			$ntpcfg .= ' kod limited';
1976
		}
1977
		if (empty($config['ntpd']['nomodify'])) { /*note: this one works backwards */
1978
			$ntpcfg .= ' nomodify';
1979
		}
1980
		if (!empty($config['ntpd']['noquery'])) {
1981
			$ntpcfg .= ' noquery';
1982
		}
1983
		if (!empty($config['ntpd']['noserve'])) {
1984
			$ntpcfg .= ' noserve';
1985
		}
1986
		if (empty($config['ntpd']['notrap'])) { /*note: this one works backwards */
1987
			$ntpcfg .= ' notrap';
1988
		}
1989
	}
1990

    
1991
	/* Custom Access Restrictions */
1992
	if (is_array($config['ntpd']['restrictions']) && is_array($config['ntpd']['restrictions']['row'])) {
1993
		$networkacl = $config['ntpd']['restrictions']['row'];
1994
		foreach ($networkacl as $acl) {
1995
			$restrict = "";
1996
			if (is_ipaddrv6($acl['acl_network'])) {
1997
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask_v6($acl['mask']) . " ";
1998
			} elseif (is_ipaddrv4($acl['acl_network'])) {
1999
				$restrict .= "{$acl['acl_network']} mask " . gen_subnet_mask($acl['mask']) . " ";
2000
			} else {
2001
				continue;
2002
			}
2003
			if (!empty($acl['kod'])) {
2004
				$restrict .= ' kod limited';
2005
			}
2006
			if (!empty($acl['nomodify'])) {
2007
				$restrict .= ' nomodify';
2008
			}
2009
			if (!empty($acl['noquery'])) {
2010
				$restrict .= ' noquery';
2011
			}
2012
			if (!empty($acl['nopeer'])) {
2013
				$restrict .= ' nopeer';
2014
			}
2015
			if (!empty($acl['noserve'])) {
2016
				$restrict .= ' noserve';
2017
			}
2018
			if (!empty($acl['notrap'])) {
2019
				$restrict .= ' notrap';
2020
			}
2021
			if (!empty($restrict)) {
2022
				$ntpcfg .= "\nrestrict {$restrict} ";
2023
			}
2024
		}
2025
	}
2026
	/* End Custom Access Restrictions */
2027

    
2028
	/* A leapseconds file is really only useful if this clock is stratum 1 */
2029
	$ntpcfg .= "\n";
2030
	if (!empty($config['ntpd']['leapsec'])) {
2031
		$leapsec .= base64_decode($config['ntpd']['leapsec']);
2032
		file_put_contents('/var/db/leap-seconds', $leapsec);
2033
		$ntpcfg .= "leapfile /var/db/leap-seconds\n";
2034
	}
2035

    
2036

    
2037
	if (empty($config['ntpd']['interface'])) {
2038
		if (is_array($config['installedpackages']['openntpd']) && !empty($config['installedpackages']['openntpd']['config'][0]['interface'])) {
2039
			$interfaces = explode(",", $config['installedpackages']['openntpd']['config'][0]['interface']);
2040
		} else {
2041
			$interfaces = array();
2042
		}
2043
	} else {
2044
		$interfaces = explode(",", $config['ntpd']['interface']);
2045
	}
2046

    
2047
	if (is_array($interfaces) && count($interfaces)) {
2048
		$finterfaces = array();
2049
		$ntpcfg .= "interface ignore all\n";
2050
		$ntpcfg .= "interface ignore wildcard\n";
2051
		foreach ($interfaces as $interface) {
2052
			$interface = get_real_interface($interface);
2053
			if (!empty($interface)) {
2054
				$finterfaces[] = $interface;
2055
			}
2056
		}
2057
		foreach ($finterfaces as $interface) {
2058
			$ntpcfg .= "interface listen {$interface}\n";
2059
		}
2060
	}
2061

    
2062
	/* open configuration for writing or bail */
2063
	if (!@file_put_contents("{$g['varetc_path']}/ntpd.conf", $ntpcfg)) {
2064
		log_error(sprintf(gettext("Could not open %s/ntpd.conf for writing"), $g['varetc_path']));
2065
		return;
2066
	}
2067

    
2068
	/* if ntpd is running, kill it */
2069
	while (isvalidpid("{$g['varrun_path']}/ntpd.pid")) {
2070
		killbypid("{$g['varrun_path']}/ntpd.pid");
2071
	}
2072
	@unlink("{$g['varrun_path']}/ntpd.pid");
2073

    
2074
	/* if /var/empty does not exist, create it */
2075
	if (!is_dir("/var/empty")) {
2076
		mkdir("/var/empty", 0555, true);
2077
	}
2078

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

    
2082
	// Note that we are starting up
2083
	log_error("NTPD is starting up.");
2084
	return;
2085
}
2086

    
2087
function system_halt() {
2088
	global $g;
2089

    
2090
	system_reboot_cleanup();
2091

    
2092
	mwexec("/usr/bin/nohup /etc/rc.halt > /dev/null 2>&1 &");
2093
}
2094

    
2095
function system_reboot() {
2096
	global $g;
2097

    
2098
	system_reboot_cleanup();
2099

    
2100
	mwexec("nohup /etc/rc.reboot > /dev/null 2>&1 &");
2101
}
2102

    
2103
function system_reboot_sync($reroot=false) {
2104
	global $g;
2105

    
2106
	if ($reroot) {
2107
		$args = " -r ";
2108
	}
2109

    
2110
	system_reboot_cleanup();
2111

    
2112
	mwexec("/etc/rc.reboot {$args} > /dev/null 2>&1");
2113
}
2114

    
2115
function system_reboot_cleanup() {
2116
	global $config, $cpzone, $cpzoneid;
2117

    
2118
	mwexec("/usr/local/bin/beep.sh stop");
2119
	require_once("captiveportal.inc");
2120
	if (is_array($config['captiveportal'])) {
2121
		foreach ($config['captiveportal'] as $cpzone=>$cp) {
2122
			/* send Accounting-Stop packet for all clients, termination cause 'Admin-Reboot' */
2123
			$cpzoneid = $cp['zoneid'];
2124
			captiveportal_radius_stop_all(7); // Admin-Reboot
2125
			/* Send Accounting-Off packet to the RADIUS server */
2126
			captiveportal_send_server_accounting('off');
2127
		}
2128
	}
2129
	require_once("voucher.inc");
2130
	voucher_save_db_to_config();
2131
	require_once("pkg-utils.inc");
2132
	stop_packages();
2133
}
2134

    
2135
function system_do_shell_commands($early = 0) {
2136
	global $config, $g;
2137
	if (isset($config['system']['developerspew'])) {
2138
		$mt = microtime();
2139
		echo "system_do_shell_commands() being called $mt\n";
2140
	}
2141

    
2142
	if ($early) {
2143
		$cmdn = "earlyshellcmd";
2144
	} else {
2145
		$cmdn = "shellcmd";
2146
	}
2147

    
2148
	if (is_array($config['system'][$cmdn])) {
2149

    
2150
		/* *cmd is an array, loop through */
2151
		foreach ($config['system'][$cmdn] as $cmd) {
2152
			exec($cmd);
2153
		}
2154

    
2155
	} elseif ($config['system'][$cmdn] <> "") {
2156

    
2157
		/* execute single item */
2158
		exec($config['system'][$cmdn]);
2159

    
2160
	}
2161
}
2162

    
2163
function system_dmesg_save() {
2164
	global $g;
2165
	if (isset($config['system']['developerspew'])) {
2166
		$mt = microtime();
2167
		echo "system_dmesg_save() being called $mt\n";
2168
	}
2169

    
2170
	$dmesg = "";
2171
	$_gb = exec("/sbin/dmesg", $dmesg);
2172

    
2173
	/* find last copyright line (output from previous boots may be present) */
2174
	$lastcpline = 0;
2175

    
2176
	for ($i = 0; $i < count($dmesg); $i++) {
2177
		if (strstr($dmesg[$i], "Copyright (c) 1992-")) {
2178
			$lastcpline = $i;
2179
		}
2180
	}
2181

    
2182
	$fd = fopen("{$g['varlog_path']}/dmesg.boot", "w");
2183
	if (!$fd) {
2184
		printf(gettext("Error: cannot open dmesg.boot in system_dmesg_save().%s"), "\n");
2185
		return 1;
2186
	}
2187

    
2188
	for ($i = $lastcpline; $i < count($dmesg); $i++) {
2189
		fwrite($fd, $dmesg[$i] . "\n");
2190
	}
2191

    
2192
	fclose($fd);
2193
	unset($dmesg);
2194

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

    
2198
	return 0;
2199
}
2200

    
2201
function system_set_harddisk_standby() {
2202
	global $g, $config;
2203

    
2204
	if (isset($config['system']['developerspew'])) {
2205
		$mt = microtime();
2206
		echo "system_set_harddisk_standby() being called $mt\n";
2207
	}
2208

    
2209
	if (isset($config['system']['harddiskstandby'])) {
2210
		if (platform_booting()) {
2211
			echo gettext('Setting hard disk standby... ');
2212
		}
2213

    
2214
		$standby = $config['system']['harddiskstandby'];
2215
		// Check for a numeric value
2216
		if (is_numeric($standby)) {
2217
			// Get only suitable candidates for standby; using get_smart_drive_list()
2218
			// from utils.inc to get the list of drives.
2219
			$harddisks = get_smart_drive_list();
2220

    
2221
			// Since get_smart_drive_list() only matches ad|da|ada; lets put the check below
2222
			// just in case of some weird pfSense platform installs.
2223
			if (count($harddisks) > 0) {
2224
				// Iterate disks and run the camcontrol command for each
2225
				foreach ($harddisks as $harddisk) {
2226
					mwexec("/sbin/camcontrol standby {$harddisk} -t {$standby}");
2227
				}
2228
				if (platform_booting()) {
2229
					echo gettext("done.") . "\n";
2230
				}
2231
			} else if (platform_booting()) {
2232
				echo gettext("failed!") . "\n";
2233
			}
2234
		} else if (platform_booting()) {
2235
			echo gettext("failed!") . "\n";
2236
		}
2237
	}
2238
}
2239

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

    
2247
	activate_sysctls();
2248

    
2249
	if (isset($config['system']['sharednet'])) {
2250
		system_disable_arp_wrong_if();
2251
	}
2252
}
2253

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

    
2266
function system_enable_arp_wrong_if() {
2267
	global $config;
2268
	if (isset($config['system']['developerspew'])) {
2269
		$mt = microtime();
2270
		echo "system_enable_arp_wrong_if() being called $mt\n";
2271
	}
2272
	set_sysctl(array(
2273
		"net.link.ether.inet.log_arp_wrong_iface" => "1",
2274
		"net.link.ether.inet.log_arp_movements" => "1"
2275
	));
2276
}
2277

    
2278
function enable_watchdog() {
2279
	global $config;
2280
	return;
2281
	$install_watchdog = false;
2282
	$supported_watchdogs = array("Geode");
2283
	$file = file_get_contents("/var/log/dmesg.boot");
2284
	foreach ($supported_watchdogs as $sd) {
2285
		if (stristr($file, "Geode")) {
2286
			$install_watchdog = true;
2287
		}
2288
	}
2289
	if ($install_watchdog == true) {
2290
		if (is_process_running("watchdogd")) {
2291
			mwexec("/usr/bin/killall watchdogd", true);
2292
		}
2293
		exec("/usr/sbin/watchdogd");
2294
	}
2295
}
2296

    
2297
function system_check_reset_button() {
2298
	global $g;
2299

    
2300
	$specplatform = system_identify_specific_platform();
2301

    
2302
	switch ($specplatform['name']) {
2303
		case 'SG-2220':
2304
			$binprefix = "RCC-DFF";
2305
			break;
2306
		case 'alix':
2307
		case 'wrap':
2308
		case 'FW7541':
2309
		case 'APU':
2310
		case 'RCC-VE':
2311
		case 'RCC':
2312
			$binprefix = $specplatform['name'];
2313
			break;
2314
		default:
2315
			return 0;
2316
	}
2317

    
2318
	$retval = mwexec("/usr/local/sbin/" . $binprefix . "resetbtn");
2319

    
2320
	if ($retval == 99) {
2321
		/* user has pressed reset button for 2 seconds -
2322
		   reset to factory defaults */
2323
		echo <<<EOD
2324

    
2325
***********************************************************************
2326
* Reset button pressed - resetting configuration to factory defaults. *
2327
* All additional packages installed will be removed                   *
2328
* The system will reboot after this completes.                        *
2329
***********************************************************************
2330

    
2331

    
2332
EOD;
2333

    
2334
		reset_factory_defaults();
2335
		system_reboot_sync();
2336
		exit(0);
2337
	}
2338

    
2339
	return 0;
2340
}
2341

    
2342
function system_get_serial() {
2343
	$platform = system_identify_specific_platform();
2344

    
2345
	unset($output);
2346
	if ($platform['name'] == 'Turbot Dual-E') {
2347
		$if_info = pfSense_get_interface_addresses('igb0');
2348
		if (!empty($if_info['hwaddr'])) {
2349
			$serial = str_replace(":", "", $if_info['hwaddr']);
2350
		}
2351
	} else {
2352
		foreach (array('system', 'planar', 'chassis') as $key) {
2353
			unset($output);
2354
			$_gb = exec("/bin/kenv -q smbios.{$key}.serial",
2355
			    $output);
2356
			if (!empty($output[0]) && $output[0] != "0123456789" &&
2357
			    preg_match('/^[\w\d]{10,16}$/', $output[0]) === 1) {
2358
				$serial = $output[0];
2359
				break;
2360
			}
2361
		}
2362
	}
2363

    
2364
	$vm_guest = get_single_sysctl('kern.vm_guest');
2365

    
2366
	if (strlen($serial) >= 10 && strlen($serial) <= 16 &&
2367
	    $vm_guest == 'none') {
2368
		return $serial;
2369
	}
2370

    
2371
	return "";
2372
}
2373

    
2374
function system_get_uniqueid() {
2375
	global $g;
2376

    
2377
	$uniqueid_file="{$g['vardb_path']}/uniqueid";
2378

    
2379
	if (empty($g['uniqueid'])) {
2380
		if (!file_exists($uniqueid_file)) {
2381
			mwexec("/usr/sbin/gnid > {$g['vardb_path']}/uniqueid " .
2382
			    "2>/dev/null");
2383
		}
2384
		if (file_exists($uniqueid_file)) {
2385
			$g['uniqueid'] = @file_get_contents($uniqueid_file);
2386
		}
2387
	}
2388

    
2389
	return ($g['uniqueid'] ?: '');
2390
}
2391

    
2392
/*
2393
 * attempt to identify the specific platform (for embedded systems)
2394
 * Returns an array with two elements:
2395
 * name => platform string (e.g. 'wrap', 'alix' etc.)
2396
 * descr => human-readable description (e.g. "PC Engines WRAP")
2397
 */
2398
function system_identify_specific_platform() {
2399
	global $g;
2400

    
2401
	$hw_model = get_single_sysctl('hw.model');
2402
	$hw_ncpu = get_single_sysctl('hw.ncpu');
2403

    
2404
	/* Try to guess from smbios strings */
2405
	unset($product);
2406
	unset($maker);
2407
	$_gb = exec('/bin/kenv -q smbios.system.product 2>/dev/null', $product);
2408
	$_gb = exec('/bin/kenv -q smbios.system.maker 2>/dev/null', $maker);
2409
	switch ($product[0]) {
2410
		case 'FW7541':
2411
			return (array('name' => 'FW7541', 'descr' => 'Netgate FW7541'));
2412
			break;
2413
		case 'APU':
2414
			return (array('name' => 'APU', 'descr' => 'Netgate APU'));
2415
			break;
2416
		case 'RCC-VE':
2417
			$result = array();
2418
			$result['name'] = 'RCC-VE';
2419

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

    
2486
	$_gb = exec('/bin/kenv -q smbios.planar.product 2>/dev/null',
2487
	    $planar_product);
2488
	if (isset($planar_product[0]) &&
2489
	    $planar_product[0] == 'X10SDV-8C-TLN4F+') {
2490
		return array('name' => 'XG-1537', 'descr' => 'Super Micro XG-1537');
2491
	}
2492

    
2493
	if (strpos($hw_model, "PC Engines WRAP") !== false) {
2494
		return array('name' => 'wrap', 'descr' => gettext('PC Engines WRAP'));
2495
	}
2496

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

    
2501
	if (preg_match("/Soekris net45../", $hw_model, $matches)) {
2502
		return array('name' => 'net45xx', 'descr' => $matches[0]);
2503
	}
2504

    
2505
	if (preg_match("/Soekris net48../", $hw_model, $matches)) {
2506
		return array('name' => 'net48xx', 'descr' => $matches[0]);
2507
	}
2508

    
2509
	if (preg_match("/Soekris net55../", $hw_model, $matches)) {
2510
		return array('name' => 'net55xx', 'descr' => $matches[0]);
2511
	}
2512

    
2513
	unset($hw_model);
2514

    
2515
	$dmesg_boot = system_get_dmesg_boot();
2516
	if (strpos($dmesg_boot, "PC Engines ALIX") !== false) {
2517
		return array('name' => 'alix', 'descr' => gettext('PC Engines ALIX'));
2518
	}
2519
	unset($dmesg_boot);
2520

    
2521
	return array('name' => $g['platform'], 'descr' => $g['platform']);
2522
}
2523

    
2524
function system_get_dmesg_boot() {
2525
	global $g;
2526

    
2527
	return file_get_contents("{$g['varlog_path']}/dmesg.boot");
2528
}
2529

    
2530
?>
(48-48/60)